Each subpattern solves a specific type of problem. Click on a card to view its template.
Template for: Opposite Ends
Set L = 0 and R = n - 1 at opposite ends of the sorted array.
Check the condition on arr[L] and arr[R] (e.g. their sum vs target).
If the combined value is too large, move R left to decrease it.
If the combined value is too small, move L right to increase it.
Loop exits when L >= R — all pairs have been considered.
1// Opposite-ends two-pointer skeleton2void oppositeEnds(vector<int>& arr)3{4 int L = 0;5 int R = (int)arr.size() - 1;67 while (L < R)8 {9 int val = COMBINE(arr[L], arr[R]); // e.g. arr[L] + arr[R]1011 if (val == TARGET)12 {13 // ── found answer ─────────────────────────14 RECORD(L, R);15 L++;16 R--;17 }18 else if (val < TARGET)19 {20 L++; // need a larger value21 }22 else23 {24 R--; // need a smaller value25 }26 }27}
Sharpen your skills with hand-picked problems.
LeetCode #167
LeetCode #15
LeetCode #11
LeetCode #125
LeetCode #42
LeetCode #18
LeetCode #141
LeetCode #142
LeetCode #876
LeetCode #202
LeetCode #234
LeetCode #26
LeetCode #283
LeetCode #75
LeetCode #27
LeetCode #80
LeetCode #88
LeetCode #350
LeetCode #844
LeetCode #4