← Amazon Interview Insights

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

Intermediate
Jun 2026

Summary

Amazon SWE coding round with a classic array sorting problem. Nothing fancy, just you and the Dutch National Flag algorithm under pressure.

Questions Asked (1)

Q1

Given an array containing only 0s, 1s, and 2s, sort it in-place in O(n) time using O(1) extra space so all 0s come first, then 1s, then 2s.

Algorithms & Data Structures
Author's notes

I knew the three-pointer approach the second I read it, but explaining the invariants out loud while coding was trickier than expected.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Use the Dutch National Flag algorithm with three pointers (low, mid, high) to partition the array in a single pass. Iterate mid from start to high, swapping elements to place 0s before low, 2s after high, and leaving 1s in the middle. This achieves O(n) time and O(1) space.

Pro tip: Emphasize that this is a classic three-way partitioning problem and that the algorithm is optimal because it sorts in one pass without extra space. Mention that it's also known as the Dutch National Flag problem, which shows depth of knowledge.

1. Clarify the problem

Confirm that the array contains only 0s, 1s, and 2s, and that sorting must be in-place with O(n) time and O(1) extra space. Ask if stability matters (it usually doesn't for this problem).

2. Introduce the algorithm

Name the Dutch National Flag algorithm and explain the three-pointer approach: low, mid, and high. Describe the invariant: elements before low are 0s, between low and mid are 1s, after high are 2s, and the unknown region is between mid and high.

3. Walk through the logic

Explain the loop: while mid <= high, if arr[mid] == 0, swap arr[low] and arr[mid], increment low and mid; if arr[mid] == 1, increment mid; if arr[mid] == 2, swap arr[mid] and arr[high], decrement high. Show how this maintains the invariant.

4. Analyze complexity

State that each element is examined at most once, so time complexity is O(n). Space complexity is O(1) because only a constant number of pointers are used.

5. Test with examples

Walk through a small example like [2,0,1,2,0,1] to demonstrate correctness. Mention edge cases: all same elements, already sorted, reverse sorted, empty array.

Key Points to Mention

  • Dutch National Flag algorithm (three-way partitioning)
  • Three pointers: low, mid, high with clear invariants
  • Single-pass O(n) time and O(1) space
  • In-place sorting without extra data structures
  • Handling of edge cases (empty array, all 0s, all 2s, etc.)
  • Comparison to counting sort (which uses O(1) space but two passes)

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