Coding Pattern:

Two Pointers

This pattern has an earnable cheat sheet.

Pattern concept

Step 1 of 11
Two Pointers Slide
Two Pointers Slide
Two Pointers Slide
Two Pointers Slide
Two Pointers Slide
Two Pointers Slide
Two Pointers Slide
Two Pointers Slide
Two Pointers Slide
Two Pointers Slide
Two Pointers Slide

Use ← → arrow keys

Code snippets

How to identify

Does the problem involve any of these?

  • Searching for pairs or triplets of elements that satisfy certain conditions
  • Maintaining two pointers to scan a list simultaneously from both ends
  • Maintaining a sliding window or range within the array or list (covered later)
  • Manipulating pointers to nodes in a linked list or tree (covered later)
  • merging or comparing two sorted lists (covered later)

Note

Most two pointer problems can be solved in O(n) time and O(1) space complexity.