Solving Two Pointers Coding Problems

Coding problems using two pointers technique

Larry | Peng Yang
Coding Interview Questions in C++
3 min readDec 21, 2019

--

Photo by Jefferson Santos on Unsplash

In this article, I am going to explain how we can utilize the two-pointer technique to solve coding problems

Two Pointers in Quick Sort

Every developer must have heard what Quick Sort is, here is the standard implementation using C++.

Explanation

The partition function does the following things:

  • Use the value of the first element of the specified range as the pivot.
  • Move the elements whose values are less than pivot to the left side of the pivot and those the values are greater than pivot to the right side of the pivot. The left part and the right part may not be sorted.
  • Return the index of the pivot after the movement

j is used to iterate through the array between [left + 1, right], The values whose indices are less than i are always less than the pivot. So, i — 1 is the last element whose value is less than the pivot. If we were to choose right as the pivot, we can initialize i = j = right — 1 , and swap the values with the following:

partition

Sort Colors

Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Example

Code

Explanation

  • blue always points to positions where 2 will be placed and red points to positions where 0 will be placed.
  • When 0 is found, we swap and increase red and i.
  • When 2 is found, swap and decrease blue and i, as the value of blue might be 0, and we have to check this position again (don't increase i ).
  • When 1 is found, just increase i.

--

--