← Google Interview Insights

Google·Software Engineer·Onsite - Coding / Algorithms·Intermediate

IntermediatePrefer not to say
Jul 2026

Summary

Google SWE interview with a classic arrays problem that feels easy until you actually have to justify the time complexity out loud.

Questions Asked (1)

Q1

Given a binary array (containing only 0s and 1s), sort it in linear time.

Algorithms & Data Structures
Author's notes

My first instinct was to just count the zeros, then fill.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Clarify that the array contains only 0s and 1s, then propose a two-pointer or counting approach to achieve O(n) time and O(1) space. Walk through the algorithm step-by-step, analyze complexity, and discuss edge cases.

Pro tip: Mention that this is a special case of the Dutch National Flag problem (with only two values) and that the two-pointer approach is optimal for in-place sorting. Also, note that counting sort is simpler but requires two passes, while two-pointer does it in one pass.

1. Clarify constraints and assumptions

Confirm the array contains only 0s and 1s, and ask whether in-place sorting is required and if extra space is allowed. This shows attention to detail and avoids misinterpretation.

2. Choose an approach

Select either the two-pointer technique (one pass, in-place) or counting sort (two passes, O(1) space). Explain why the chosen method meets linear time and space constraints.

3. Walk through the algorithm

For two-pointer: initialize left at 0 and right at n-1; while left < right, move left until a 1 is found, move right until a 0 is found, then swap. For counting: count zeros, then overwrite the array with zeros followed by ones.

4. Analyze complexity and edge cases

State time complexity O(n) and space O(1). Discuss edge cases: empty array, all zeros, all ones, already sorted, and large input.

5. Test with examples

Run through a small example like [1,0,1,0,0] to demonstrate correctness, and optionally mention potential pitfalls like infinite loops if pointers are not updated correctly.

Key Points to Mention

  • Time complexity: O(n) with a single pass (two-pointer) or two passes (counting).
  • Space complexity: O(1) auxiliary space for both approaches.
  • Two-pointer technique: left pointer finds 1s, right pointer finds 0s, swap until pointers meet.
  • Counting approach: count zeros, then fill array with zeros and ones accordingly.
  • Edge cases: empty array, all 0s, all 1s, already sorted array.
  • Relation to Dutch National Flag problem (three-way partition) for generalization.

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.