FastPrepSort Colors

Sort Colors

Visa logoVisa● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

You are given an integer array nums containing only 0, 1, and 2. Rearrange the array in place so that equal values are adjacent and the values appear in the order 0, 1, then 2.

Do not call a library sorting routine. Return the same array after rearranging it so the result can be evaluated.

Function

sortColors(nums: int[]) → int[]

Examples

Example 1

nums = [2,0,2,1,1,0]return = [0,0,1,1,2,2]

The two zeros come first, followed by the two ones and the two twos.

Example 2

nums = [2,0,1]return = [0,1,2]

Each color occurs once.

Constraints

  • 1 <= nums.length <= 100000
  • nums[i] is 0, 1, or 2.
  • The rearrangement must use constant auxiliary space.

Source note: Author-written prompt excerpt retained for source fidelity.

More Visa problems

See Visa hiring insights
public int[] sortColors(int[] nums) {
  // write your code here
}
nums[2,0,2,1,1,0]
expected[0,0,1,1,2,2]
Checking account…