InterviewLegend

Two Pointers & Intervals

Alex Chen35 min readGuide updated 387 real interview reports
In this lesson
  • Merge intervals and count meeting rooms with one sort and one sweep, handling touching endpoints the right way in each
  • Explain why Subarray Sum Equals K needs a prefix sum and a hashmap once negative numbers are allowed
  • Run Kadane's algorithm for Maximum Subarray, starting from the first element so an all-negative array returns its least-negative element
  • Solve 3Sum with two pointers over a sorted array, then Trapping Rain Water with two pointers and O(1) extra space

Two problems in this lesson come from 2026 Apple loops. Merge Intervals came up as the plain problem in a full-stack loop, and a coding round asked Subarray Sum Equals K, then asked what negative numbers do to the solution. Meeting Rooms II showed up in a 2025 loop with a twist on the hours. Intervals come first, then running sums.

The last three problems, Maximum Subarray, 3Sum and Trapping Rain Water, are older classics. They're here because they drill the running-sum and two-pointer moves cleanly, and in each one you walk the array carrying a few numbers. The hashmap, sliding-window and prefix-sweep templates are in Arrays & Strings.

Intervals and meeting rooms

When intervals come up, Merge Intervals has the newest Apple report. Meeting-room counting and practical schedule problems use the same idea: one sort, one sweep, and an endpoint comparison where most attempts go wrong.

How Apple frames it

Some teams ask familiar problems as written, and Merge Intervals came exactly that way in a 2026 loop. Many others wrap the pattern in a custom prompt, sometimes with a long problem statement, and add twists once the first version works. A schedule of store opening hours with a shift that runs past midnight is still intervals underneath. So practice spotting the pattern under the prompt. Meeting Rooms II asks "how many rooms does this schedule need," and it gets easier once you restate it. The fewest rooms equals the most meetings running at the same moment. Say that out loud and keep talking through your reasoning as you go, since some interviewers stop to ask why you wrote a line.

The Apple angle
Get the endpoint rule right before you code. A merge must join [1,2] and [2,3], so the test is start <= prev_end. The room count treats the same touch as free, since a meeting ending at 2 frees its room for one starting at 2. Say which rule applies before you write the comparison.

The interval pattern

Both problems start the same way. An interval is a pair, a start and an end, and the whole family gets easier once you sort by start time. In start order, anything that could overlap an interval sits right next to it. From there the two problems split: merging joins neighbors that touch, and the meeting-room count tracks how many ranges are open at once. Sort first, then sweep left to right.

Three ideas cover these problems. The first is the sort: in start order, a jumbled set becomes a single left-to-right pass. Next comes the overlap test. While you walk the sorted intervals, the current one overlaps the one you're tracking when its start is less than or equal to that interval's end. In code that's start <= prev_end. If it holds, the two ranges touch or cross and can be treated as one, and if it doesn't, there's a gap between them.

The third idea counts how many ranges are open at once, which is what the meeting-rooms question asks. A sweep line walks every start and end in time order with a running count, adding one when a meeting starts and subtracting one when it ends, and the highest count is the answer. A min-heap, a structure that always gives you its smallest element first, does the same count another way. It holds the end time of every meeting currently in a room, so its top is the room that frees up next. Both give the same number, and which one reads cleaner is mostly taste.

The wording of the question tells you which tool to use. Joining overlapping ranges into the fewest is a merge: sort by start, sweep, and extend the current range whenever the next one satisfies start <= prev_end. Counting how many ranges are open at the same moment is a concurrency count. Either sweep the starts and ends in time order and track the peak, or keep a min-heap of end times and read its size as the rooms in use. Work out which of the two you're being asked before you pick.

In code, the two rules come down to one comparison each. Merging tests start <= prev_end, which is true when start equals prev_end, so [1,2] and [2,3] become [1,3]. Meeting rooms frees a room when the earliest end is <= start, so a meeting that ends at 2 and one that starts at 2 share a room, because the first has left by the time the second begins.

Interval problems

Two problems, easier first. Merge Intervals (asked plainly in 2026) practices the sort-then-sweep step and the rule that touching counts as overlapping. Meeting Rooms II (asked in 2025) practices the concurrency count, with both the min-heap and the two-pointer sweep worked through. Code both before opening the solution, and say the endpoint rule out loud as you would for an interviewer.

1

Merge Intervals: Sort, Then Sweep

Medium
Problem
You're given a list intervals, where intervals[i] = [start, end] is one interval's start and end. Merge every set of overlapping intervals and return the fewest intervals that cover exactly the same span, in any order.

Two intervals overlap when they touch or cross, so [1,3] and [2,6] merge into [1,6], and [1,2] and [2,3] merge into [1,3] because they meet at the endpoint.
Inputintervals = [[1,3],[2,6],[8,10],[15,18]]Output[[1,6],[8,10],[15,18]]

[1,3] and [2,6] overlap and merge into [1,6]. The other two touch nothing, so they pass through unchanged.

How this uses the pattern

Sort by start time, then sweep left to right. Keep the last interval in your result open, and for each next interval test start <= prev_end. If it holds, extend the last interval's end to the max of the two; if not, the gap is real, so start a fresh interval.

Write it here, or go full screen with the problem, hints and solution beside the editor.

Merge Intervals: Sort, Then Sweep

Loading...
Click "Run" to execute your code
The Apple angle
Merge Intervals is the interval problem with the newest Apple report, from a 2026 full-stack loop that asked it plainly. Sort first, and treat touching endpoints as an overlap, so [1,4] and [4,5] merge. Watch the <= in start <= prev_end. Writing < leaves touching intervals unmerged without any error.
Take it further
Insert one new interval into a list that's already sorted and merged. Since the list is sorted and has no overlaps, you don't merge everything again. Copy the intervals that end before the new one starts, widen the new one to absorb every interval it overlaps, then copy the rest. That's Insert Interval, a natural follow-up, and it runs in one linear pass with no sort. Solved in the walkthrough below.
2

Meeting Rooms II: Counting Concurrency

MediumCommonly asked
Problem
You're given a list intervals where intervals[i] = [start, end] is a meeting's start and end time. Return the minimum number of rooms needed so that no two meetings sharing a room ever overlap in time.

A meeting that ends exactly when another begins, like [1,2] and [2,3], can share one room: the first has cleared by the instant the second starts.
Inputintervals = [[0,30],[5,10],[15,20]]Output2

[5,10] and [15,20] never overlap each other, but both overlap [0,30], so at the busiest moment two meetings are live and you need two rooms.

How this uses the pattern

The minimum rooms equals the most meetings live at any single moment. Sort by start. One option keeps a min-heap of the end times of meetings currently in rooms: pop any that have ended before the next meeting starts, then push the new end. The other sweeps the sorted starts and ends together and tracks the running peak.

Write it here, or go full screen with the problem, hints and solution beside the editor.

Meeting Rooms II: Counting Concurrency

Loading...
Click "Run" to execute your code
The Apple angle
In a 2025 Apple loop, a candidate solved Meeting Rooms II with a heap, then heard that hours were fixed from 1 to 24. With so few slots, a counting array over the hours beats the heap. Know both, and say which input sizes favor each.
Take it further
Return which meetings collide, or the time when the most rooms are in use. The sweep already has this: when the running count hits its peak, the meetings being counted are the ones colliding. Keep the set of live meetings next to the count instead of just a number, and save a copy whenever the count reaches a new high. Times might come from a small fixed range, like whole hours from 1 to 24. Then skip the sort: add one at each start hour, subtract one at each end hour, and take the peak of the running sum. An interviewer may also ask only whether one person can attend every meeting (Meeting Rooms I), which is the same sort plus a check of each adjacent pair. All three are worked through below.

Running sums and two pointers

Subarray Sum Equals K came up in a 2026 Apple coding round: count the contiguous subarrays whose sum is exactly k. The follow-up asked whether negative numbers or zeros change the solution, and they do. A sliding window only works when every value is positive, because then growing the window always raises the sum and shrinking it always lowers it. One negative number breaks that, so you can't tell which way to move. The fix is a running prefix sum plus a hashmap of how many times each prefix sum has appeared. At each index, any earlier prefix equal to running - k marks a subarray that ends here and sums to k, so add its count. Seed the map with {0: 1} so a subarray starting at index 0 counts. That's one pass in O(n) time and O(n) space, and it handles negatives and zeros with no change.

python
def subarray_sum(nums, k):
seen = {0: 1} # prefix sum -> how many times it has appeared
running = count = 0
for value in nums:
running += value
count += seen.get(running - k, 0) # earlier prefixes that leave exactly k
seen[running] = seen.get(running, 0) + 1
return count

Older classics, still good practice. The next three drill the running-sum and two-pointer moves. Trapping Rain Water was reported in Apple loops in 2024 and 2025. Maximum Subarray and 3Sum haven't shown up in recent Apple reports, but they drill the same moves well.

3

Maximum Subarray: Kadane in One Pass

Medium
Problem
Given an integer array nums, return the largest sum any contiguous subarray can reach.

A subarray is a non-empty run of adjacent elements, and the answer is the sum itself, a single number.
Inputnums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]Output6

The run [4, -1, 2, 1] sums to 6, the best any contiguous stretch reaches here.

How this uses the pattern

Kadane's algorithm, a running-sum sweep, fits here. Carry one number as you walk the array: the best sum of a subarray that ends at the current element. At each step, either extend the run you were building or start a fresh run from here, whichever gives the larger sum. Keep the best running value you ever saw.

Write it here, or go full screen with the problem, hints and solution beside the editor.

Maximum Subarray: Kadane in One Pass

Loading...
Click "Run" to execute your code
The Google angle
Apple interviewers often change a problem once your first version runs, so know why Kadane works, not only the code. Be ready to explain the reset rule: extend the current run, or start fresh here. And seed both totals from the first element, or [-3, -1, -2] reports 0 instead of -1.
Take it further
Report the start and end indices of the best run, then make it work on a stream. To recover the run, track where the current run started and save the start and end whenever the running sum sets a new high. The streaming version needs no rewrite. Kadane already reads each element once and holds two numbers, so it works on input you can't rewind. An interviewer may also move to the maximum product subarray, where you carry both the largest and the smallest running products, because one negative number swaps them. Worked through below.
4

3Sum: Sort then Converging Pointers

Medium
Problem
Given an integer array nums, return every unique triplet of values that sums to zero. Each triplet comes from three distinct positions, and no two triplets in the result may be the same set of values.

Order within a triplet and the order of the triplets do not matter for correctness, though the examples below show each triplet sorted ascending and listed in sorted order.
Inputnums = [-1, 0, 1, 2, -1, -4]Output[[-1, -1, 2], [-1, 0, 1]]

Two triplets sum to zero: (-1) + (-1) + 2 and (-1) + 0 + 1. The repeated -1 in the input still yields just one copy of each triplet.

How this uses the pattern

Sort the array, then fix the first value and walk a left pointer up from just after it and a right pointer down from the end. When the three values sum to zero, record them and step both pointers inward, sliding each past any equal neighbor so no triplet repeats. If the sum falls short of zero, raise the left pointer; if it overshoots, lower the right.

Write it here, or go full screen with the problem, hints and solution beside the editor.

3Sum: Sort then Converging Pointers

Loading...
Click "Run" to execute your code
The Google angle
The thing to get right is duplicates. Skip them inside the sweep, so [-2, 0, 0, 2, 2] gives [-2, 0, 2] once, and you never need a hash set. The pointers then run in place with O(1) extra space, which helps if the interviewer asks you to cut memory.
Take it further
Find the triplet whose sum is closest to a given target. The sweep barely changes. Track the best sum so far and replace it whenever the current three are nearer the target, moving the same two pointers by whether the sum is under or over. An interviewer may also ask for the general k-sum version, where you fix one more index and recurse down to this two-pointer case. The walkthrough below solves 3Sum Closest.
5

Trapping Rain Water: Two Pointers, No Extra Arrays

HardCommonly asked
Problem
Given an array height where each entry is the height of a vertical bar of width 1, return how much water the whole arrangement traps after rain.

Water rests above a bar up to the shorter of two walls: the tallest bar somewhere to its left and the tallest bar somewhere to its right. A bar at either end, or one with nothing taller on one side, holds none.
Inputheight = [0,1,0,2,1,0,1,3,2,1,2,1]Output6

Six units settle into the dips between the taller bars.

How this uses the pattern

Picture the water over any bar as capped by the taller wall to its left and the taller wall to its right, whichever is shorter. The clean version runs two pointers inward from both ends and advances the side whose running maximum is smaller, because that side alone fixes the water at the bar it lands on. No prefix or suffix arrays.

Write it here, or go full screen with the problem, hints and solution beside the editor.

Trapping Rain Water: Two Pointers, No Extra Arrays

Loading...
Click "Run" to execute your code
The Apple angle
Trapping Rain Water is a Hard problem that has come up at Apple, though not in the most recent reports. Build the prefix-max and suffix-max version first, then reduce it to two pointers with two running maxima. Interviewers sometimes ask you to bring extra space down to O(1), so know both versions.
Take it further
Return the water above each bar, one entry per bar. The same inward sweep settles one bar per step. Write each step's water into an array instead of a running total, and the two end bars stay at zero by themselves. A harder extension is the 2D version. There, water drains toward the lowest point anywhere on the outer edge instead of one left or right wall, and the edge becomes a min-heap you grow inward. Worked below.

Key Takeaways

  • ✓Sort intervals by start. [1,2] and [2,3] merge, but two meetings that touch share a room, so say which rule applies first.
  • ✓Subarray Sum Equals K needs a prefix sum and a hashmap, because negative numbers break a sliding window.
  • ✓Maximum Subarray is Kadane: extend the run or start fresh. Start from the first element, or [-3, -1, -2] reports 0 instead of -1.
  • ✓For Trapping Rain Water, build prefix and suffix max first, then reduce it to two pointers that move the side with the smaller max.
Apple interview guide

Know what Apple asks before you walk in.

22 coding · 6 system design · 34 behavioral questions

Get Premium$49 a year · Instant access
Or start freeNo card.

Get their questions first.

Arrays & StringsHad your Apple interview?How we research

InterviewLegend is independent and not affiliated with or endorsed by any company it covers.