Posts

Showing posts with the label two pointer

Sort Colors

Sort Colors  Problem Statement You’re given: An array nums[] of integers, where each value is either: 0 = Red 🟥 1 = White ⚪ 2 = Blue 🔵 You need to sort the array in-place such that the final order is all 0 s, followed by 1 s, then 2 s. No using .sort()   Example Input: nums = [2, 0, 2, 1, 1, 0] Output: [0, 0, 1, 1, 2, 2] Best Data Structure for the Job Simple arrays do the trick! No need to pull out HashMaps or fancy data structures — all you need are: Some pointer magic A while loop A sprinkle of swaps  Different Approaches 1) Brute Force (Don't do this in interviews ) Just count how many 0s, 1s, and 2s exist, then rewrite the array. class Solution { public void sortColors ( int [] nums) { int count0 = 0 , count1 = 0 , count2 = 0 ; for ( int num : nums) { if (num == 0 ) count0++; else if (num == 1 ) count1++; else count2++; } for ( int i ...