Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Algorithms
Algorithmseasy

What is the two pointers technique?

Tags
#two-pointers#array#technique
Back to categoryPractice quiz

Answer

You keep two indices (e.g., left/right) and move them based on a rule, often on a sorted array or a sliding window. It can reduce nested loops to O(n) in many problems.

function hasPairSum(arr: number[], target: number) {
  let l = 0;
  let r = arr.length - 1;

  while (l < r) {
    const sum = arr[l] + arr[r];
    if (sum === target) return true;
    if (sum < target) l++;
    else r--;
  }

  return false;
}

Advanced answer

Deep dive

Two pointers is a technique family: you maintain two positions and an invariant that lets you move one pointer safely.

Common variants:

  • Left/right on a sorted array (2-sum, pair constraints).
  • Sliding window (expand right, shrink left while condition fails).
  • Slow/fast pointer (cycle detection, middle of list).

How to use it well

  • Define the invariant (what the window/search space guarantees).
  • Ensure each step moves at least one pointer; total pointer moves stay O(n).

Common pitfalls

  • Sliding window breaks with negative numbers unless the invariant still holds.
  • Forgetting sorted preconditions for left/right patterns.
  • Off-by-one mistakes when updating boundaries.

Related questions

Algorithms
Boyer–Moore majority vote: what does it solve and what’s the core idea?
#majority-vote#array#linear-time
Algorithms
Floyd’s cycle detection (tortoise and hare): what does it detect and what are its time/space costs?
#cycle-detection#tortoise-hare#linked-list
Algorithms
Sliding window: what is it and when is it better than nested loops?
#sliding-window
#two-pointers
#complexity
Algorithms
What does Kadane’s algorithm solve?
#kadane#dynamic-programming#array