1️⃣ Core Idea

  • Use 2 pointers (indices) instead of 1
  • Move them in coordination
  • Goal β†’ reduce time, avoid extra space

3️⃣ When to Think Two Pointer πŸš€

βœ”οΈ Strong Signals

  • ONLY ON β†’ Array / Linked List
  • Sorted OR can be sorted
  • Find:
    • Pair / Triplet / Quadruple
  • Operations:
    • Merge
    • Remove duplicates
    • Rearrange elements
  • Constraint:
    • If No extra space allowed
  • Linked List:
    • Cycle detection
  • Time Complaxcity:
ApproachTimeSpaceNotes
Brute ForceO(nΒ²)O(1)Simple but slow
HashMapO(n)O(n)Fast but extra space
Two PointerO(n log n) - shortingO(1)Optimal space

4️⃣ Types of Two Pointer Problems (Important)

1. πŸ” Opposite Ends (Most Common)

One pointer at start s, one at end e Move towards center while (s < e)

πŸ“Œ Used in:

  • Pair sum
  • Palindrome
  • Sorting / rearranging

Example Problems

  • 1. Two Sum
  • 3Sum / 4Sum
  • Container with most water
  • Trapping rain water
  • Reverse string/Array

2. 🐒 Slow & Fast Pointer

Next type is using two pointers with different speed of movement. Typically they starts from the left end, then the fast pointer advances fast and give some feedback to the slow pointer and do some calculation.

πŸ“Œ Used in:

  • Linked list problems
  • Cycle detection

Example Problems

  • Find the middle of a linked list
  • Remove Dublicate from sorted LL - 3. Slow Fast ptr
  • Linked List Cycle
  • Find duplicate number
  • Remove nth node

3. πŸ”— Two Arrays / Merging

In this category, you will be given 2 arrays or lists, then have to process them with individual pointers.

πŸ“Œ Used in:

  • Merge sorted arrays
  • Intersection problems

Example Problems

  • Merge Sorted Array
  • Intersection of arrays
  • strstr()

4. βœ‚οΈ Split & Merge

The last one is similiar to previous category but there is one thing is added. First, you need to split the given list into 2 separate lists and then do two pointers approach to merge or unify them. There aren’t many tasks here.


3 items under this folder.