Two pointers Flashcards

(5 cards)

1
Q

LeetCode 125 – Valid Palindrome
Check if string is a palindrome (ignore non-alnum, case).

A

Normalize comparison: two pointers l,r.

While l<r: skip non-alnum on both sides; compare lower(s[l]) == lower(s[r]); move inward.

If any mismatch → false; else true.

Time O(n), Space O(1).

Tags: Two pointers, Filtering.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

LeetCode 167 – Two Sum II
Sorted array; find 1-indexed pair with sum = target.

A

Two pointers l=0, r=n-1.

If nums[l] + nums[r] < target → l++; if > target → r–; else return.

Invariant: sorted lets us drop a side each step.

Time O(n), Space O(1).

Tags: Two pointers, Monotone shrink.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

LeetCode 15 – 3Sum
All unique triplets with sum 0.

A

Sort. For each i (skip duplicates & early break if nums[i]>0):

Two-sum on subarray [i+1..] with l/r.

Move l/r based on sum; after a hit, skip duplicates on both sides.

Time O(n²), Space O(1) extra.

Tags: Sorting + two pointers, Deduplication.

Pitfalls: duplicates, integer ranges.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

LeetCode 11 – Container With Most Water
Max area formed by two lines.

A

Two pointers at ends; area = min(h[l], h[r]) * (r-l).

Move the shorter side inward (only way to possibly increase min height).

Track best.

Time O(n), Space O(1).

Tags: Greedy two pointers, Invariant on min height.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

LeetCode 42 – Trapping Rain Water
Total trapped water between bars.

A

Two pointers with running maxima: leftMax, rightMax.

While l<r:

If leftMax ≤ rightMax: water += max(0, leftMax - height[l]); update leftMax; l++.

Else: water += max(0, rightMax - height[r]); update rightMax; r–.

Reason: lower side limits water level.

Time O(n), Space O(1).

Tags: Two pointers, Prefix/Suffix maxima (implicit).

Alt: monotonic stack (O(n), more memory).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly