InterviewSam
Tech TracksStudySystem DesignAptitudeDaily Quiz
Log inStart free
Tech TracksStudySystem DesignAptitudeDaily Quiz
All topics

Two Pointers

Walk an array from two positions to turn O(n^2) scans into O(n).

5 pages, free to read

Start studying
  1. 1

    Pointers from both ends

    Beginner

    Start one pointer at each end of a sorted array or string and move them toward each other, discarding a whole set of candidates with every step, so one O(n) pass replaces checking all pairs.

    9 min read
  2. 2

    Fast & slow pointers

    Intermediate

    Move one pointer one step and another two steps at a time: if there is a cycle the fast one laps the slow one, and if there is none the slow one ends at the middle when the fast one hits the end.

    10 min read
  3. 3

    Read & write pointers (in-place)

    Beginner

    One pointer reads every element while a second marks where the next kept element goes, so you filter or compact an array in place in a single O(n) pass.

    8 min read
  4. 4

    Pair and triplet sums

    Intermediate

    Sort the array, fix one element, and find the rest with two pointers: two sum becomes O(n), three sum O(n^2), and duplicates are skipped by comparing neighbours.

    11 min read
  5. 5

    Merging sorted sequences

    Beginner

    Walk two sorted sequences with one pointer each, always taking the smaller front element, to produce one sorted result in O(n + m).

    9 min read