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

LeetCode 167: Two Sum II – Input Array Is Sorted is a Medium two pointers problem. This Python walkthrough develops an opposing two pointers solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

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

Recognizing the pattern

Two pointers are useful when one comparison lets you permanently discard one side of the remaining search range.

For this problem specifically, compare the endpoint sum with the target. A small sum requires a larger left value; a large sum requires a smaller right value. The invariant worth writing beside the code is: Every discarded endpoint is impossible to use in a solution with any remaining partner.

Step-by-step algorithm

  1. Identify the input state consumed by twoSum(numbers, target) and initialize the data required by the opposing two pointers pattern.
  2. Compare the endpoint sum with the target. A small sum requires a larger left value; a large sum requires a smaller right value.
  3. After each update, verify the page’s central invariant: Every discarded endpoint is impossible to use in a solution with any remaining partner.
  4. Finish only after the boundary behavior is covered: Return one-based indices and never reuse the same element.

Python solution

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

Reading the implementation

The main entry point is twoSum(numbers, target). The named working state includes left, total; those variables make the opposing two pointers state visible instead of hiding it in incidental control flow.

A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. In concrete terms, compare the endpoint sum with the target. A small sum requires a larger left value; a large sum requires a smaller right value.

Correctness argument

Initialization. Before the scan begins, the unresolved range contains every candidate and the processed range is empty, so no answer has been lost.

Preservation. Compare the endpoint sum with the target. A small sum requires a larger left value; a large sum requires a smaller right value. The chosen movement discards only candidates that cannot improve the answer; afterward, every discarded endpoint is impossible to use in a solution with any remaining partner.

Termination. A boundary advances on every iteration. Once the active range is exhausted, every viable candidate was either measured or safely eliminated, so the stored result is optimal.

Complexity and trade-offs

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

A quadratic pair scan is easier to invent but repeats comparisons that pointer movement can eliminate. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

assert Solution().twoSum([2,7,11,15],9) == [1,2]

Common mistakes and edge cases

  • Problem-specific boundary: Return one-based indices and never reuse the same element.
  • Pattern-level pitfall: Move the pointer justified by the comparison, and state whether the active interval includes or excludes each endpoint.
  • Invariant check: after every update, confirm that every discarded endpoint is impossible to use in a solution with any remaining partner.

Interview review checklist

  • Explain why opposing two pointers matches the structure of this input.
  • State the invariant in one sentence before tracing code: Every discarded endpoint is impossible to use in a solution with any remaining partner.
  • Derive O(n) time and O(1) extra space from how many times each element or state is visited.
  • Test the boundary explicitly: Return one-based indices and never reuse the same element.

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