Stack Bash - Master data structures and algorithms

Sort colors

Medium
Given an array of integers containing only 0, 1, and 2, sort the array in-place and return it.
For example, given the following input:
nums = [2, 0, 1, 2, 1, 0]
Your function should return [0, 0, 1, 1, 2, 2].
Array partitioning visualization with three regions for 0s, 1s, and 2s
This is known as the Dutch national flag problem, named after the three-color Dutch flag. The challenge is to sort the array in a single pass using constant extra space.

Try it first

Solution

7 Essential Arrays Coding Interview Problems

Master Arrays by trying the coding challenges below.
  1. 1.Trade stock onceEasy
  2. 2.AdditionEasy
  3. 3.Find the smallestEasy
  4. 4.Sort colorsMedium
  5. 5.Reorganize numbersHard
  6. 6.Maximum subarrayHard
  7. 7.Container of waterHard