EvalFrame Technical Mock Interviews & Coding Practice

Sort Colors

Medium · Array / Two Pointers · Algorithm problem · all problems

Given an array `nums` with `n` objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integers `0`, `1`, and `2` to represent red, white, and blue, respectively. You must solve this problem without using the library's sort function. **Examples:** ```typescript sortColors([2, 0, 2, 1, 1, 0]) // [0, 0, 1, 1, 2, 2] sortColors([2, 0, 1]) // [0, 1, 2] ```

Solve It in the BrowserPractice Explaining It Out Loud

Optimal Approach

  • Time complexity: O(n)
  • Space complexity: O(1)

Dutch National Flag algorithm partitions the 3 values in a single O(n) pass.

Follow-Up Questions Interviewers Ask About Sort Colors

  • Why does mid not increment when swapping nums[mid] with nums[high]?
    The element swapped from high into mid has not been inspected yet, so mid must re-examine it.

Practice the full problem with execution, tests, and AI code review in the interactive lab — then rehearse explaining your solution in a live voice mock interview.