Intermediate Level

Implement the sortColorsThreeValues method that sorts an array containing only three possible values.

The input contains an integer array nums and its length size. The array contains only three possible values: 0, 1, and 2. Your task is to sort these values in ascending order.

For example, [2,0,2,1,1,0] should become [0,0,1,1,2,2].

Example 1

Input
nums (int[]) = [2,0,2,1,1,0]
size (int) = 6
Returns (int[]) [0,0,1,1,2,2]

Example 2

Input
nums (int[]) = [2,0,1]
size (int) = 3
Returns (int[]) [0,1,2]

Example 3

Input
nums (int[]) = [0]
size (int) = 1
Returns (int[]) [0]

Since there are only three possible values, count how many times each value appears.

After counting 0s, 1s, and 2s, overwrite the array by writing all 0s first, then all 1s, and finally all 2s.

Pseudocode:

function sortColorsThreeValues(nums, size):
    count0 = 0
    count1 = 0
    count2 = 0
    for each value in nums:
        if value == 0:
            count0++
        else if value == 1:
            count1++
        else:
            count2++
    index = 0
    repeat count0 times:
        nums[index] = 0
        index++
    repeat count1 times:
        nums[index] = 1
        index++
    repeat count2 times:
        nums[index] = 2
        index++
    return nums
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.