Chapter 01 - Two Pointers
Two indexes walking through the same array instead of two nested loops. One of the simplest patterns, and one of the most rewarding.
This page is the entry point of chapter 1 of my Rust solutions to the book Coding Interview Patterns. It sums up the pattern in a few lines, then lists the problems of the chapter. As explained on the series page, the detailed explanations of the algorithms are in the book.
The idea
Testing every pair with two nested loops costs \(O(n^2)\). With two pointers, we keep two indexes and move one of them at each step, based on what we just saw. Most of the time they start at both ends of a sorted array and move inward. Sometimes they both go forward, one reading and one writing. Either way, every element is visited once: \(O(n)\) time and \(O(1)\) extra space.
When to reach for it
- The input is sorted, or sorting it first is acceptable, and we look for a pair or a triplet.
- We compare elements from both ends: palindromes, containers, mirrored structures.
- We must rearrange an array in place, like moving all the zeros to the end.
In Rust
- Indexes are
usize:right -= 1whenright == 0panics in debug builds. Check the loop condition (while left < right) before moving. nums.swap(i, j)swaps two elements of a slice without fighting the borrow checker.- For strings, work on
s.as_bytes(): indexing a&strby position is not allowed, bytes are.
Problems in this chapter
- p010 - Pair Sum - Sorted: Pair Sum - Sorted (Two Pointers) solved in Rust: in a sorted array, return the indexes of any pair of numbers that add up to a target sum.
- p014 - Triplet Sum: Triplet Sum (Two Pointers), solved in Rust. Given an array of int, return all triplets such that a+b+c =0. 1 2 3 and 2 3 1 are considered duplicates.
- p020 - Is Palindrome Valid: Is Palindrome Valid (Two Pointers), solved in Rust. Given a string determine if it’s a palindrome after removing all non-alphanumeric characters.
- p024 - Largest Container: Largest Container (Two Pointers) solved in Rust: given the heights of vertical lines, return the most water two of them can hold.
- bonus005 - Shift zeros to the end: Shift zeros to the end (Two Pointers), solved in Rust. Given an array of integers, modify the array in place to move all zeros to the end while maintaining…
- bonus010 - Next lexicographical sequence: Next lexicographical sequence (Two Pointers), solved in Rust. Given a string of lowercase English letters. Rearrange the characters to form a new string…
Other chapters
All the chapters, with every problem, are listed on the series page.