Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns

Topic · 5 patterns

Arrays & Two Pointers patterns

Most array questions are about not rescanning. Each of these five patterns turns an O(n²) scan into one or two passes: two pointers and sliding window move indices that never go back, prefix sums and difference arrays precompute running totals so any range costs O(1), and cyclic sort uses the values themselves as positions when they run from 1 to n.

The patterns

  1. Two Pointers

    O(n) / O(1)

    Walk two indices toward each other (or same-direction) so each step discards a whole branch of possibilities.

    Spot it: Sorted input (or sorting is free): find a pair/triplet with a target sum or best value, in-place dedupe/partition, or palindrome check.

    Learn Two PointersCheat sheet and practice
  2. Sliding Window

    O(n)

    Expand the right edge; shrink the left only while the window violates the rule. Track the best as you go.

    Spot it: Longest/shortest/count of a contiguous subarray or substring under a monotone rule (sum, ≤k distinct, no repeats), or a fixed size k.

    Learn first: Two Pointers

    Learn Sliding WindowCheat sheet and practice
  3. Prefix Sum

    O(n)

    Store cumulative sums; the sum of any range is a subtraction. Pair with a hashmap of seen prefixes to count subarrays.

    Spot it: Many range-sum queries on a static array, or count subarrays with sum/xor/mod = k (negatives OK), or balance problems (map 0 to -1).

    Learn Prefix SumCheat sheet and practice
  4. Cyclic Sort

    O(n) / O(1)

    Each value's correct index is the value itself — swap numbers home in one pass, then scan for the one out of place.

    Spot it: n numbers in range 1..n (or 0..n); find the missing, duplicate, or first missing positive in O(n) time and O(1) space.

    Learn Cyclic SortCheat sheet and practice
  5. Difference Array & Line Sweep

    O(n log n)

    Mark +1 at each start and −1 just past each end, then sweep a prefix sum to get the value at every position.

    Spot it: Many range-add updates with reads only at the end, or max overlap at a point: bookings, car pooling, calendars, flowers in bloom.

    Learn first: Prefix Sum

    Learn Difference Array & Line SweepCheat sheet and practice

Which one? Match the signal

If the problem saysReach for
Sorted array; find a pair / triplet hitting a target, or shrink from both endsTwo PointersO(n)
Contiguous subarray/substring asked to be longest/shortest/max/min under a constraintSliding WindowO(n)
"Subarray sum equals k" / "divisible by k", or many range-sum queriesPrefix Sum + HashMapO(n)
Array holds n numbers from a 1..n range; find missing / duplicate / first-missing-positiveCyclic SortO(n)
Many range increments, or count overlapping events at a point (bookings, car pool)Difference Array / SweepO(n log n)

Easy to confuse

  • Subarray Sum Equals K looks like Sliding Window, but it’s Prefix Sum

    Negative numbers make window validity non-monotone; count prefix pairs with a hash map.

  • Subarray Sums Divisible by K looks like Sliding Window, but it’s Prefix Sum

    Divisibility is not monotone in window size; key prefix sums by residue.

  • Shortest Subarray with Sum at Least K looks like Sliding Window, but it’s Monotonic Deque

    Negatives break shrinking; keep a monotone deque of prefix sums.

  • Find the Duplicate Number looks like Cyclic Sort, but it’s Fast & Slow Pointers

    Array must not be modified and O(1) space: values form a functional graph whose cycle entry is the duplicate.

  • Reverse Pairs looks like Two Pointers, but it’s Divide and Conquer (merge-sort counting)

    Pairs i < j with a[i] > 2a[j] are counted across merge-sort halves (or with a BIT).

  • Sum of Subarray Minimums looks like Sliding Window, but it’s Monotonic Stack

    No window condition; each element's contribution span comes from previous/next smaller.

Used together

  • Prefix Sum + Hash Map / Hash Set Lookup

    When: count/longest subarrays with sum (or mod, or balance) equal to a target, negatives allowed. With negative numbers no window is monotone; the pair view plus a lookup counts all subarrays in O(n).

  • Sliding Window + Hash Map / Hash Set Lookup

    When: longest/shortest substring with distinct/at-most-K/covers-all-chars condition. Validity depends on counts inside the window, which must update in O(1) per move.

  • Sliding Window + Monotonic Deque

    When: subarray where max - min <= limit, or window extreme queries. Validity depends on window max-min, which a counter cannot maintain under deletions.

  • Prefix Sum + Monotonic Deque

    When: shortest subarray with sum >= K when values can be negative; max subarray sum with length in [a, b]. Negative values break window monotonicity; on prefix sums, dominated left ends can be discarded.

Where to start

then the The 128 and The 365 sheets

Two Pointers

  • Valid PalindromeEasy
  • Two Sum II - Input Array Is SortedMedium

Sliding Window

  • Maximum Average Subarray IEasy
  • Longest Substring Without Repeating CharactersMedium

Prefix Sum

  • Running Sum of 1d ArrayEasy
  • Range Sum Query - ImmutableEasy

Cyclic Sort

  • Missing NumberEasy
  • Find All Numbers Disappeared in an ArrayEasy

Difference Array & Line Sweep

  • Corporate Flight BookingsMedium

Further reading

free, outside Lessgo
  • Two PointersUSACO Guide

    Clean explanation plus graded problems for two pointers and sliding window.

  • Prefix SumsUSACO Guide

    1D/2D prefix sums with problems; foundation for difference arrays.

  • More on Prefix Sums (difference arrays)USACO Guide

    Difference arrays, prefix minimum and range-update tricks.

  • Array cheatsheetTech Interview Handbook

    Interview corner cases, techniques and must-do problem list for arrays.

  • NeetCode RoadmapNeetCode

    Pattern-ordered problem tree with a short video per problem; best interview-first path.

  • Array and String explore cardLeetCode

    Guided basics with in-browser problems; good warmup before pattern drilling.

All 49 patternsLinked Lists →
TodayReviewPatternsProblems