Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
3 Pointer solution I found on youtube

Nirbhay Lourembam

Jun 14, 2023

I found the below solution on youtube. In my opinion, this is the easiest one to understand and honestly much more elegant than what is given here.

public static void sortColors_3Pointers(int[] nums) { int start = 0; int mid = 0; int end = nums.length - 1; while (mid <= end) { switch (nums[mid]) { case 0: // Swap with start index swap(nums, start, mid); mid++; start++; break; case 1: mid++;// do nothing break; case 2: // Swap with end index swap(nums, mid, end); end--; break; } } }

2

1

Comments
Comments
N
Nirbhay Lourembam2 years ago
private static void swap(int[] arr, int pos1, int pos2) { int temp = arr[pos1]; arr[pos1] = arr[pos2]; arr[pos2] = temp; }

On this page

Problem Statement

Examples

Example 2

Try it yourself