MEDIUM NC#11 Two Pointers

167. Two Sum II - Input Array Is Sorted

📖 Problem

Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length. Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2. The tests are generated such that there is exactly one solution. You may not use the same element twice. Your solution must use only constant extra space.

🧠 Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • Array methods (`push`, `pop`, `shift`, `slice`)
  • Object/Map/Set usage patterns
  • Function parameter and return typing
  • In-place array updates
  • Sorted array traversal
  • Boundary condition checks

Logical Thinking Concepts

  • Define invariants before coding
  • Check edge cases first (`[]`, single element, duplicates)
  • Estimate time/space before implementation
  • Apply Two Pointers reasoning pattern

💡 Approach

  • Array is sorted, use two pointers from ends
  • If sum < target, move left pointer to increase sum
  • If sum > target, move right pointer to decrease sum
  • Time: O(n), Space: O(1)

🛠️ Hints & Pitfalls

Hints

  • Array is sorted, use two pointers from ends
  • If sum < target, move left pointer to increase sum
  • If sum > target, move right pointer to decrease sum

Common Pitfalls

  • Time: O(n), Space: O(1)

🧪 Test Cases

Hidden tests on submit: 2

Test Case 1
Not run
Input:
twoSumII([2,7,11,15], 9);
Expected:
[1, 2]
Test Case 2
Not run
Input:
twoSumII([2,3,4], 6);
Expected:
[1, 3]
Test Case 3
Not run
Input:
twoSumII([-1,0], -1);
Expected:
[1, 2]

📝 Code Editor

📚 Reference Solution

⌘K Search ⌘↩ Run ⌘S Submit