FastPrepSort Ones, Twos, and Threes In Place

Sort Ones, Twos, and Threes In Place

Agoda logoAgoda● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

You are given an integer array nums containing only 1, 2, and 3. Rearrange it in place so all ones come first, followed by all twos and then all threes.

Use constant auxiliary space and return the same array after rearranging it so the result can be evaluated.

Function

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

Examples

Example 1

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

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

Example 2

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

Each permitted value occurs once.

Constraints

  • 1 <= nums.length <= 100000.
  • Every value is 1, 2, or 3.
  • The rearrangement must use constant auxiliary space.

More Agoda problems

See Agoda hiring insights
public int[] sortOneTwoThree(int[] nums) {
    // Write your code here.
}
nums[3,1,3,2,2,1]
expected[1,1,2,2,3,3]
Checking account…