Eight patterns solve most array and string problems in coding interviews: two pointers, sliding window, binary search, merge intervals, monotonic stack, greedy and bit manipulation, plus the Big-O facts you need to state your solution's cost. For each you get the signal that points to it, a short template, the classic problems to practice and the mistakes that cost the round. The companion page covers tree, graph and recursion patterns.
How to use this page
Each pattern below has the signal that points to it, a short Python template, the classic problems to practice and the mistakes that cost candidates the round. Learn the signal first: in an interview, recognizing the pattern in the first two minutes is most of the battle. The tree, graph and recursion patterns are on the companion page, and our full list of LeetCode patterns covers the rest, including prefix sums.
Pointer and window patterns
Two pointers
Reach for it when the input is sorted or can be sorted, and you are looking for a pair, a triple or a partition, or you need to compare from both ends. Two indices moving toward each other, or a slow and a fast index moving the same way, turn an O(n²) scan into O(n).
def pair_with_sum(nums, target): # nums sorted
i, j = 0, len(nums) - 1
while i < j:
s = nums[i] + nums[j]
if s == target: return i, j
if s < target: i += 1
else: j -= 1
return NoneClassic problems: Two Sum II (sorted input), 3Sum, Container With Most Water, Valid Palindrome, Remove Duplicates from Sorted Array, Trapping Rain Water.
Mistakes that cost the round: forgetting to skip duplicates in 3Sum, moving the wrong pointer, and using two pointers on unsorted input without sorting first (and without saying the sort costs O(n log n)).
Sliding window
Reach for it when the problem asks for the longest, shortest or count of contiguous subarrays or substrings that satisfy a condition. Grow the window on the right, shrink it on the left while it is invalid, and record the answer.
def longest_without_repeat(s):
seen, left, best = {}, 0, 0
for right, ch in enumerate(s):
if ch in seen and seen[ch] >= left:
left = seen[ch] + 1
seen[ch] = right
best = max(best, right - left + 1)
return bestClassic problems: Longest Substring Without Repeating Characters, Minimum Window Substring, Longest Repeating Character Replacement, Permutation in String, Sliding Window Maximum (with a deque).
Mistakes that cost the round: shrinking with an if instead of a while, updating the answer before the window is valid again, and applying the pattern to arrays with negative numbers when the sum condition is not monotonic (use prefix sums instead).
For sums over ranges with negative numbers, prefix sums are the right tool.
Search and ordering
Binary search
Reach for it when the input is sorted, or the answer space is monotonic: if a value works, every larger value works too. Binary search on the answer covers problems that do not look like search at all, such as the minimum speed or capacity that meets a deadline.
def first_true(lo, hi, ok): # smallest x in [lo, hi] with ok(x) True
while lo < hi:
mid = (lo + hi) // 2
if ok(mid): hi = mid
else: lo = mid + 1
return loClassic problems: Binary Search, Search in Rotated Sorted Array, Find Minimum in Rotated Sorted Array, Koko Eating Bananas, Capacity To Ship Packages Within D Days, Median of Two Sorted Arrays.
Mistakes that cost the round: off-by-one loops that never end (pick one template and use it every time), computing mid in a way that overflows in fixed-width languages, and not checking that the condition really is monotonic.
Merge intervals
Reach for it when the input is a list of ranges, such as meetings, bookings or time spans, and you need to merge overlaps, insert a range, or count how many overlap at once. Sort by start time first; almost every interval problem begins there.
def merge(intervals):
intervals.sort(key=lambda x: x[0])
out = []
for s, e in intervals:
if out and s <= out[-1][1]:
out[-1][1] = max(out[-1][1], e)
else:
out.append([s, e])
return outClassic problems: Merge Intervals, Insert Interval, Non-overlapping Intervals, Meeting Rooms II (with a min-heap of end times), Interval List Intersections.
Mistakes that cost the round: sorting by end time when the problem needs start time, forgetting that touching intervals may or may not count as overlapping (ask), and mutating the input when the interviewer expects a new list.
Monotonic stack
Reach for it when the question is about the next or previous greater or smaller element, or about spans and areas bounded by the nearest taller or shorter bar. Keep a stack whose values only increase or only decrease; each element is pushed and popped at most once, so the whole pass is O(n).
def next_greater(nums):
ans, stack = [-1] * len(nums), [] # stack holds indices
for i, x in enumerate(nums):
while stack and nums[stack[-1]] < x:
ans[stack.pop()] = x
stack.append(i)
return ansClassic problems: Daily Temperatures, Next Greater Element I and II, Largest Rectangle in Histogram, Online Stock Span, Remove K Digits.
Mistakes that cost the round: storing values when you need indices to compute distances, choosing the wrong direction of monotonicity, and missing the circular case, handled by looping over the array twice.
Choices and bits
Greedy
Reach for it when making the locally best choice at each step can be shown to lead to the best overall answer, usually after sorting. Greedy is fast and short, but it is only correct if you can say why; interviewers often ask for that argument.
def can_jump(nums):
reach = 0
for i, step in enumerate(nums):
if i > reach: return False
reach = max(reach, i + step)
return TrueClassic problems: Jump Game, Jump Game II, Gas Station, Partition Labels, Task Scheduler, Non-overlapping Intervals (sort by end time).
Mistakes that cost the round: using greedy where it fails, as with coin change for arbitrary coin values (that one needs dynamic programming), and not giving the exchange argument: if an optimal answer differs from the greedy choice, swap it in and show the answer does not get worse.
Bit manipulation
Reach for it when the problem mentions pairs that cancel, powers of two, subsets of a small set, or asks for O(1) extra space where a hash set would be the obvious answer. XOR cancels equal values, x & (x - 1) clears the lowest set bit, and a bitmask of n bits enumerates all 2ⁿ subsets.
def single_number(nums): # every value appears twice except one
x = 0
for n in nums:
x ^= n
return xClassic problems: Single Number, Number of 1 Bits, Counting Bits, Reverse Bits, Missing Number, Sum of Two Integers, Subsets (bitmask version).
Mistakes that cost the round: forgetting that Python integers are unbounded, so masks are needed to mimic 32-bit behavior; mixing up arithmetic and logical shifts in Java and C++; and choosing a bit trick when a clear solution exists and readability is being scored.
Complexity
Big-O: the complexity facts you need to say out loud
Every coding round ends with "what is the time and space complexity?", and many candidates lose easy points here. State both, name the dominant term, and say which input size it refers to.
| Operation or algorithm | Time | Space |
|---|---|---|
| Array index, hash map get and put (average) | O(1) | O(1) |
| Binary search on a sorted array | O(log n) | O(1) |
| Single pass, two pointers, sliding window | O(n) | O(1) to O(n) |
| Sorting (comparison based) | O(n log n) | O(log n) to O(n) |
| Heap push and pop | O(log n) | O(n) for the heap |
| BFS or DFS on a graph | O(V + E) | O(V) |
| Nested loops over the input | O(n²) | O(1) |
| All subsets, or backtracking over choices | O(2ⁿ) or O(n!) | O(n) recursion depth |
What interviewers listen for: amortized costs (a dynamic array append is O(1) amortized), recursion depth counted as space, and the difference between average and worst case for hash maps. To build intuition for how these grow, try our Big-O complexity visualizer.
A two-week practice order
- Days 1 to 3: two pointers and sliding window, four problems each, timed at 25 minutes.
- Days 4 to 6: binary search, including two binary-search-on-the-answer problems.
- Days 7 and 8: merge intervals and monotonic stack.
- Days 9 and 10: greedy, and for each problem write one sentence on why greedy is correct.
- Day 11: bit manipulation, then mixed review.
- Days 12 to 14: mixed sets with no pattern label, explaining each solution aloud, then move on to trees, graphs and recursion or the NeetCode 150 roadmap.
Where CoPilot Interview fits
Knowing a pattern and explaining it under time pressure are different skills, and coding rounds score both. CoPilot Interview is an AI interview assistant; its free AI mock interview asks array and string problems against your résumé and the job description, reads them aloud and scores your spoken explanation out of ten, which is the part most people never practice. The free plan gives 15 minutes a day of live help in sessions of up to 15 minutes, with AI mock interviews included. In a real coding round, follow your employer's rules: many online assessments and live coding screens forbid outside help, and the invitation usually says so.
Disclosure: CoPilot Interview is our product, so weigh what we say about it accordingly.
Frequently asked questions
How many patterns do I need for coding interviews?
Around fifteen cover most problems asked at large tech companies: the eight on this page, plus tree traversal, graph search, heaps, tries, backtracking, dynamic programming and union-find. Depth on these beats a shallow pass over fifty.
How do I know which pattern a problem needs?
Read for the signal: sorted input or a monotonic answer suggests binary search; contiguous subarrays suggest a sliding window; pairs in sorted data suggest two pointers; next greater or smaller suggests a monotonic stack. Say the signal out loud, because interviewers score the reasoning as well as the code.
Should I memorize the templates?
Memorize the shape, not the code. Write each template from memory a few times, then solve problems without looking. The goal is to stop making off-by-one mistakes under pressure.
What language should I use?
Use the language you are fastest and most accurate in. Python is popular because it is short, but if you think in Java or C++, use it and know its standard library well.
Where are the old single-pattern pages?
Each of the eight patterns that used to be a separate page now lives in a section of this page, and the old addresses redirect to the matching section.
Practice this interview before the real one
The AI mock interview builds questions from your resume and the job description, reads them aloud and scores each spoken answer out of 10. Included on the free plan.
Start a mock interview