Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 2

Two-Pointer Technique for Sorted Data Structures

This lesson is built with resources from youtube.com, itohi.com and 1 more site.

Introduction

Welcome to the second lesson in our "Advanced Algorithm Patterns" module. In our previous session, we explored the sliding window technique, which is a specific application of two pointers where both pointers typically move in the same direction to define a dynamic sub-array or sub-string.

Today, we will broaden our scope to cover other powerful variations of the two-pointer technique. Specifically, we will focus on:

  1. Opposite-End Pointers: Using two pointers that start at the opposite ends of a sorted array and move towards each other. This is highly effective for problems involving finding pairs or subsequences that satisfy certain criteria.
  2. Fast & Slow Pointers: Using two pointers that traverse a linked list at different speeds. This is the key to solving a class of list problems, including cycle detection and finding the middle element, with optimal time and space complexity.

Your goal for this lesson is to master these patterns so you can confidently apply them to reduce a problem's time complexity from a brute-force to a linear , often with the added benefit of space complexity—a critical skill to demonstrate in a Staff-level interview.

Let's begin by getting a high-level overview of the different scenarios where this pattern applies.

Coding Interview Patterns - Two Pointers

This video by Nikhil Lohia provides a great survey of the various problem types that can be solved using the two-pointer pattern. It will give you a mental map of the territory we're about to cover.

Watch the segment from 02:15 to 10:15. As you watch, notice the two main categories of pointer movement: (1) starting at opposite ends and converging, and (2) starting together but moving at different speeds. Also, pay attention to the "keywords" mentioned that hint at using this pattern.


1. Two Pointers on Sorted Arrays (Converging Pointers)

This is one of the most common and effective applications of the two-pointer technique. The core idea is simple but powerful: if an array is sorted, the relative positions of elements give us crucial information.

Two Pointer Technique Variations
This image shows the two main variations of the two-pointer technique. We covered the bottom variation (pointers moving in the same direction) in the sliding window lesson. Today, we focus on the top variation (opposite directions) and the fast/slow pointer pattern for linked lists.

The general algorithm for the converging pointer pattern is:

  1. Initialize a left pointer at the start of the array (index 0) and a right pointer at the end (index n-1).
  2. In a loop that continues as long as left < right, evaluate the elements at arr[left] and arr[right].
  3. Based on the problem's condition, move one of the pointers inward:
    • If you need a smaller value/sum, decrement right.
    • If you need a larger value/sum, increment left.
  4. This process systematically eliminates possibilities, allowing you to scan the entire set of potential pairs in a single pass.

Example 1: Two Sum on a Sorted Array

This is the canonical problem for this pattern. Given a sorted array of integers, find two numbers that add up to a specific target.

While you could use a hash map for an time and space solution, the two-pointer approach achieves an optimal time and space solution, a trade-off that is important to articulate in an interview.

The following resource explains this approach in detail, with a focus on a Go implementation.

Applying the Two-Pointer Technique for Pair Sums in Go - CodeSignal

This article from CodeSignal walks through the 'Pair Sums' problem, which is essentially 'Two Sum'. It clearly explains the logic of moving the pointers based on the sum.

Please read the entire article. Pay close attention to: The critical prerequisite of sorting the array. The logic for moving left vs. right pointers. The final time complexity analysis, which includes the cost of sorting, resulting in O(N log N). If the array is already sorted (as in LeetCode's 'Two Sum II'), the complexity is just O(N).

Here is a visual representation of the process described in the article:

Two-Pointer Technique for Target Sum in a Sorted Array
This diagram illustrates the converging pointers technique for finding a target sum of 8. The sum of the values at the pointers is compared to the target, and the right pointer is decremented if the sum is too high, while the left is incremented if it's too low, until the target is found.

Extending the Pattern: Three Sum and Beyond

A common follow-up is the Three Sum problem: find all unique triplets in an array that sum to zero. You can solve this by building on the Two Sum pattern:

  1. Sort the input array.
  2. Iterate through the array with a standard for loop, fixing one number, a.
  3. For each a, use the two-pointer technique on the remainder of the array to find two numbers, b and c, such that b + c = -a.
  4. Be mindful of skipping duplicate values to ensure the uniqueness of the resulting triplets.

This transforms a naive problem into an solution, which is generally the expected optimal result. The video from Nikhil Lohia you watched earlier briefly touched on this at 05:07.


2. Two Pointers on Linked Lists (Fast & Slow Pointers)

For linked lists, the "fast and slow pointer" approach (also known as Floyd's Tortoise and Hare algorithm) is fundamental. Here, two pointers start at the head but move at different speeds.

This simple mechanism is surprisingly effective for problems that are difficult to solve otherwise without using extra space.

The ITOHI resource below provides excellent, concise Go implementations for the patterns we're about to discuss. Keep it open as a reference.

Linked List Operations | ITOHI

This page from ITOHI is a fantastic cheat sheet of linked list operations in Go, with a focus on two-pointer techniques. We'll refer to its code examples.

Familiarize yourself with the structure of this page. We will specifically look at the 'Find Middle', 'Detect Cycle', and 'Find Cycle Start' sections and their Go implementations.

Example 1: Finding the Middle of a Linked List

Problem: Find the middle node of a linked list.

Algorithm:

  1. Initialize slow and fast pointers to head.
  2. In a loop, advance slow by one step (slow = slow.Next) and fast by two steps (fast = fast.Next.Next).
  3. When fast reaches the end of the list (i.e., fast == nil or fast.Next == nil), slow will be at the middle node.

This works because slow travels half the distance of fast. You can see the Go code for this in the "Find Middle of List" section of the ITOHI resource.

Example 2: Detecting a Cycle in a Linked List

Problem: Determine if a linked list has a cycle.

Algorithm:

  1. Use the same slow and fast pointer setup.
  2. If there is a cycle, the fast pointer will eventually lap the slow pointer, and they will collide (slow == fast).
  3. If fast reaches the end of the list, there is no cycle.

This is a classic application and a direct extension of the middle-finding logic. The Go code is in the "Detect Cycle" section of the ITOHI resource.

Example 3 (Deep Dive): Finding the Start of a Linked List Cycle

This is a more advanced problem that truly tests your understanding. It's not enough to know if a cycle exists; you must find the exact node where it begins. This is a great problem for a Staff-level interview because it requires a deeper insight than just applying the pattern.

The solution is a two-phase algorithm:

  1. Phase 1: Detect Collision. Use the fast and slow pointers to find a collision point anywhere within the cycle. If they don't collide, there is no cycle.
  2. Phase 2: Find Cycle Start. After collision, move one pointer (e.g., slow) back to the head of the list. Keep the other pointer (fast) at the collision point. Now, advance both pointers one step at a time. The node where they meet again is the start of the cycle.

The question is, why does this work? The following video provides one of the best mathematical proofs you'll find. Understanding this proof is the kind of depth that distinguishes a senior candidate.

L17. Find the starting point of the Loop/Cycle in LinkedList | Multiple Approaches

The 'take U forward' channel offers an exceptional deep dive into the algorithm and, more importantly, the mathematical intuition for finding the start of a cycle.

Please watch this segment carefully, from 07:04 to 21:46. The first part (up to 14:26) explains the algorithm and shows the pseudocode. The second part (from 14:26 onwards) provides the mathematical proof. Take your time with this section. It proves that the distance from the head to the cycle start is equal to the distance from the collision point to the cycle start. This is the key insight.

After watching the video, review the DetectCycle function in the "Find Cycle Start" section of the ITOHI resource. You'll see the two phases from the video implemented cleanly in Go.


Conclusion

In this lesson, we explored two fundamental variations of the two-pointer technique, moving beyond the sliding window pattern. You now have a framework for tackling a broad range of problems on sorted arrays and linked lists efficiently.

Key Takeaways:

  • Converging Pointers on a sorted array is the go-to pattern for finding pairs or triplets that meet a specific condition (e.g., summing to a target). It provides an time, space solution, which is often a significant optimization over hash map-based approaches.
  • Fast & Slow Pointers are indispensable for linked list problems. They allow for constant-space solutions to find the middle element, detect cycles, and pinpoint the start of a cycle.
  • For Staff-level interviews, knowing the why behind an algorithm is as important as knowing the how. Understanding the mathematical proof for finding a cycle's start is a perfect example of this deeper knowledge.

In our next lesson, we will cover another powerful optimization technique: Binary Search on the Answer Space. This pattern applies to a different class of problems where you're asked to find the minimum or maximum value that satisfies a certain condition.