D
DSA in DartHard40 XP5 min read

What are the two-pointer and sliding window techniques?

TL;DR: Two-pointer: use left/right pointers to solve pair/range problems in O(n) instead of O(n²). Sliding window: a variable-size two-pointer variant for substring/subarray problems. Both avoid nested loops for sorted or sequential data.

Full Answer

Two-pointer and sliding window are the most common algorithm patterns in coding interviews. They transform O(n²) nested loops into O(n) single passes.

Two-Pointer

Two pointers (left and right) move toward each other or in the same direction. Classic: find two numbers in a sorted array that sum to a target.

Sliding Window

A window of variable size slides across the array. Expand right when condition is met, shrink left when it's violated. Classic: longest substring without repeating characters.

Code Examples

dartTwo-pointer and sliding window
Output
true
9
3

Common Mistakes

  • Using two-pointer on unsorted arrays for pair-sum — only works on sorted data
  • Not handling the edge case when left pointer passes right pointer

Interview Tip

💡

These two patterns cover probably 30% of LeetCode medium problems. Practice identifying when a problem has a 'window' or 'pair' structure — that's the signal to apply these techniques.

#two-pointer#sliding-window#algorithms#optimization