DEV Community

tracelit
tracelit

Posted on • Originally published at tracelit.dev

LeetCode 167: Two Sum Ii Input Array Is Sorted — Step-by-Step Visual Trace

Medium — Two Pointers | Array | Binary Search

The Problem

Find two numbers in a sorted array that add up to a specific target value, returning their 1-indexed positions.

Approach

Use two pointers starting from opposite ends of the sorted array. Move the left pointer right if the sum is too small, or move the right pointer left if the sum is too large, leveraging the sorted property to efficiently narrow down the search space.

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

Code

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        left, right = 0, len(numbers) - 1

        while left < right:
            current_sum = numbers[left] + numbers[right]

            if current_sum == target:
                return [left + 1, right + 1]
            elif current_sum < target:
                left += 1
            else:
                right -= 1

        # No solution found
        return [-1, -1]
Enter fullscreen mode Exit fullscreen mode

Watch It Run

Watch the algorithm run step by step

Watch the algorithm run step by step

Open interactive visualization

Try it yourself: Open TraceLit and step through every line.


Built with TraceLit — the visual algorithm tracer for LeetCode practice.

Top comments (0)