Skip to main content

Command Palette

Search for a command to run...

LeetCode 1: Two Sum — Step-by-Step Visual Trace

Published
1 min read

Easy — Hash Table | Array | Two Pointers

The Problem

Given an array of integers and a target sum, find the indices of two numbers in the array that add up to the target value. Each input has exactly one solution, and the same element cannot be used twice.

Approach

Use a hash map to store previously seen numbers and their indices as we iterate through the array. For each number, calculate the complement needed to reach the target, and check if it exists in our hash map. If found, return the indices of both numbers.

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

Code

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        prevMap = {}  # val -> index

        for i, n in enumerate(nums):
            diff = target - n
            if diff in prevMap:
                return [prevMap[diff], i]
            prevMap[n] = i

Watch It Run

Open interactive visualization

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


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

More from this blog

T

Tracelit

131 posts