BackmediumTwo Pointers Salesforce

Dutch National Flag Solution

Problem Statement

Rearrange the shipment list so all smalls come first, then mediums, then larges. Do this in a single pass.

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

Explanation: Step-by-step: with input [0, 1, 2, 0, 1, 2], we initialize pointers low = 0 and high = 5. We iterate through the array, swapping elements as necessary. After the first iteration, the array becomes [0, 0, 2, 1, 1, 2]. We continue iterating, swapping elements until the array becomes [0, 0, 0, 1, 1, 2, 2].

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

Explanation: Step-by-step: with input [2, 0, 1, 2, 0, 1], we initialize pointers low = 0 and high = 5. We iterate through the array, swapping elements as necessary. After the first iteration, the array becomes [0, 2, 1, 2, 0, 1]. We continue iterating, swapping elements until the array becomes [0, 0, 1, 1, 2, 2].

Constraints

  • 1 <= n <= 300
  • arr[i] is either 0, 1, or 2.
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free