Partitioning Arrays

The Partitioning Arrays technique is useful in many problems. It is a basic building block. Later on, we also use it to implement Quick Sort.

First, we will illustrate this concept with an Easy problem - Moving all zeroes to the beginning of an array.

Question 1 (discussed in video): You are given an array of integers. Rearrange the array so that all zeroes are at the beginning of the array.
For example, [4,2,0,1,0,3,0] -> [0,0,0,4,1,2,3]

Note: Written Solutions are at the bottom.

Video 1: Intro to the problem and a sub-optimal solution:

Video 2: Solving the problem by Partitioning the Array.

Now, we will modify this problem. We will demonstrate how to partition the array from the back.

Question 2 (discussed in the video below): Now, given an array, move all zeroes to the end of the array.
For example, [4,2,0,1,0,3,0] -> [4,1,2,3,0,0,0]


Now, we will make it more complex. We will partition the array into 3 portions instead of 2.

Question 3 (discussed in video below): (Level: Medium) Dutch National Flag Problem: Given an array of integers A and a pivot, rearrange A in the following order:
[Elements less than pivot, elements equal to pivot, elements greater than pivot]

For example, if A = [5,2,4,4,6,4,4,3] and pivot = 4 -> result = [3,2,4,4,4,4,6,5]

Note: the order within each section doesn't matter.

Video 1: High level approach to the problem

Video 2: Detailed solution explanation

Solutions to Problems Discussed in videos:

PartitioningArrays.pdf

Homework Problem (Level: Medium)
Given an array with n marbles colored Red, White or Blue, sort them so that marbles of the same color are adjacent, with the colors in the order Red, White and Blue.
Assume the colors are given as numbers - 0 (Red), 1 (White) and 2 (Blue).
For example, if A = [1,0,1,2,1,0,1,2], Output = [0,0,1,1,1,1,2,2].

Homework Solution:

PartitioningArraysHomework.pdf
Complete and Continue  
Discussion

54 comments