Coding Round 1
Mid
programming
LeetCode #75 - Sort Colors
Background: You are given an array consisting of red, white, and blue, represented by 0, 1, and 2 respectively. Your task is to sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
Problem Statement: Implement a function
Example 1:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Explanation: The numbers are sorted in order where 0 represents red, 1 represents white, and 2 represents blue.
Example 2:
Input: nums = [2,0,1]
Output: [0,1,2]
Constraints:
Problem Statement: Implement a function
void sortColors(int[] nums) that sorts the array in a single pass with O(n) time complexity and O(1) space complexity. Example 1:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Explanation: The numbers are sorted in order where 0 represents red, 1 represents white, and 2 represents blue.
Example 2:
Input: nums = [2,0,1]
Output: [0,1,2]
Constraints:
1 <= nums.length <= 300, nums[i] is either 0, 1, or 2.
Structured Response
Suggested Answer