🎯 Problem SolvedFind two elements in an ordered collection whose combined sum matches a target condition.
💡 When to UseWhen the input array is sorted or monotonic, and a pair condition can be evaluated from the extreme boundaries inward.
⚙️ Core MechanicsLeft starts at 0, Right starts at N-1. Advance left to increase sum; retract right to decrease sum.
Quick:
LEFT
1
[0]3
[1]4
[2]6
[3]8
[4]11
[5]RIGHT
15
[6]Step1 / 13
Speed:
⌨️ Shortcuts:Space Play/Pause•← → Step•R Reset
Algorithm Logic🐍 Python
⏱ TC: O(N)💾 SC: O(1)
1def two_sum_sorted(arr, target):2 left, right = 0, len(arr) - 1◀3 while left < right:4 curr_sum = arr[left] + arr[right]5 if curr_sum == target:6 return [left, right] # Pair found!7 elif curr_sum < target:8 left += 1 # Need larger sum9 else:10 right -= 1 # Need smaller sum11 return [-1, -1] # No pair found
💡Step Intuition
Initialize Pointersleft:0 (arr[0] = 1)right:6 (arr[6] = 15)target:14
Initialized left = 0 (val: 1) at the beginning, and right = 6 (val: 15) at the end of the sorted array.