DevHireLab
TutorialsBootcamp
Problems
Code SimulatorAI InterviewSoonContact
DevHireLab
TutorialsBootcamp
Problems
Code SimulatorAI InterviewSoonContact
Back to Arena
easy
Array

Sort Colors (Dutch National Flag)

**Problem Statement:** 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 the color red, white, and blue, respectively. **Hint / Expected Approach:** Three-way partition with lo/mid/hi **Edge Cases to Consider:** - (1) All same color - (2) Already sorted - (3) Only two distinct colors

Examples

Example 1
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Example 2
Input: [2,0,1]
Output: [0,1,2]
Example 3
Input: [0]
Output: [0]

Constraints

  • ▪1 <= nums.length <= 10^4
  • ▪-10^9 <= nums[i] <= 10^9
  • ▪Time complexity should be O(n) or O(n log n)

Watch Out For Edge Cases

  • ▪All same color
  • ▪Already sorted
  • ▪Only two distinct colors
Frequently Asked At
MicrosoftAmazonGoogleAdobeZomato