Walk Two Indexes Toward an Answer

Some interview problems invite a nested loop: for every item, look at every other item. When the data has an order you can exploit, such as a sorted array or a string read from both ends, two indexes moving through it can replace the inner loop. Each step moves at least one index, and neither ever moves back, so the whole walk takes O(n) time and O(1) extra space.

Three Shapes of the Same Idea

Opposite ends, moving inward. Start one index at each end and move whichever one the comparison tells you to. Checking whether a text reads the same backward works this way, and so does finding two values in a sorted array that add up to a target:

Language: JavaScript
const prices = [150, 300, 450, 700, 900];
let left = 0;
let right = prices.length - 1;
while (prices[left] + prices[right] !== 1000) {
  if (prices[left] + prices[right] < 1000) left++;
  else right--;
}
console.log(left, right);

The loop stops at the pair that adds up to 1000:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.