Two Sum II - Input Array Is Sorted

Find two numbers in sorted array that add up to target. Return 1-indexed positions.

Medium

Examples

Example 1: [2,7,11,15], target=9 → [1,2]

Implementation

Ruby

  # 🔁 Two Pointers — Two Sum II
  #
  # Problem Statement:
  #   Given a 1-indexed, sorted array of integers numbers that is sorted in non-decreasing order, find two numbers such that they add up to a specific target number.
  #   Return the indices of the two numbers (as an array) such that they add up to the target.
  #
  # Input Examples:
  #   two_sum_sorted([2, 7, 11, 15], 9) => [1, 2]
  #   two_sum_sorted([1, 2, 3, 4, 4, 9, 56, 90], 8) => [4, 5]
  #
  # Time Complexity: O(n), where n is the length of the array
  def two_sum_sorted(numbers, target)
    left = 0
    right = numbers.length - 1

    while left < right
      sum = numbers[left] + numbers[right]
      puts "Checking: numbers[#{left}] + numbers[#{right}] = #{numbers[left]} + #{numbers[right]} = #{sum}"

      if sum == target
        puts "✅ Found it! Returning [#{left + 1}, #{right + 1}]"
        return [ left + 1, right + 1 ]  # 1-based index
      elsif sum < target
        puts "🔼 Sum too small, moving left pointer right"
        left += 1
      else
        puts "🔽 Sum too large, moving right pointer left"
        right -= 1
      end
    end
    puts "❌ No solution found"
    []

Complexity Analysis

Time Complexity: O(n)
Space Complexity: O(1)

Patterns & Techniques

Problem Details

Category: Pointer And Sliding Window
Difficulty: Medium
Module: PointerAndSlidingWindow
Method: two_sum_sorted
← Back to Pointer And Sliding Window