LeetCode 167: Two Sum II – Input Array Is Sorted — Python Solution

Solve LeetCode 167: Two Sum II – Input Array Is Sorted in Python with a opposing two pointers approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

DifficultyMedium
TopicTwo Pointers
Reusable patternopposing two pointers
ComplexityO(n) time and O(1) extra space

What the problem is testing

Compare the endpoint sum with the target. A small sum requires a larger left value; a large sum requires a smaller right value.

Algorithm

  1. Compare the endpoint sum with the target. A small sum requires a larger left value; a large sum requires a smaller right value.
  2. Maintain this invariant: Every discarded endpoint is impossible to use in a solution with any remaining partner.
  3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

Python solution

from collections import Counter, defaultdict, deque, OrderedDict
import random

class Solution:
    def twoSum(self, numbers, target):
        left, right = 0, len(numbers) - 1
        while left < right:
            total = numbers[left] + numbers[right]
            if total == target: return [left + 1, right + 1]
            if total < target: left += 1
            else: right -= 1

Why this is correct

The proof follows the maintained state: Every discarded endpoint is impossible to use in a solution with any remaining partner. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

Complexity

O(n) time and O(1) extra space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

Edge cases

Return one-based indices and never reuse the same element.

Tested reference code

This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


Browse the searchable 100 LeetCode Python Solutions hub. Previous: 392. Is Subsequence · Next: 11. Container With Most Water