Skip to content
Hello Python

Checking your account…

Sign in to save your code and progress across devices. The lesson and problem statement remain public.

Loading the interactive Interview workspace.If it does not appear, the problem and learning material remain readable, but browser execution is unavailable.Reload Interview workspace

Problem

Implement Solution.twoSum(nums, target). Return the two distinct indices. Exactly one answer exists.

Starter code

class Solution:
    def twoSum(self, nums: list[int], target: int) -> list[int]:
        pass
Test cases

sample

{
  "args": [
    [
      2,
      7,
      11,
      15
    ],
    9
  ]
}

Expected: [0,1]

Wizard outline
  1. Step 1: Initialize Solution.twoSum

    Replace the empty starter with the first real state owned by Solution.twoSum. A small, named state is easier to verify than a complete algorithm. Establish it before adding the branch or loop that changes it.

  2. Step 2: Pass the Sample case

    Complete the readable core algorithm for one representative Interview case. Use a hash map to trade space for a linear scan.

  3. Step 3: Harden the Duplicates boundary

    Repair the reviewed boundary and pass the complete submission contract. When a complement is already stored, its index and the current index form the required distinct pair.

Footguns and prerequisites
  • Check the complement before storing the current value so the same index is not reused.
  • hashing and sets
Reviewed references
Practice prerequisites
  • Track Previously Seen Values(opens in a new tab)

    Track Previously Seen Values isolates before processing index i, seen contains exactly the distinct values from indices smaller than i. That focused state discipline is required when implementing two sum as a complete Interview Problem.

Recommended approach and implementation

Scan once and map each seen value to its index.

Why it works: When a complement is already stored, its index and the current index form the required distinct pair.

class Solution:
    def twoSum(self, nums, target):
        """
        Checkpoint 1: initialize the state owned by this Interview contract.
        Checkpoint 2: assemble the primary transition without hiding the boundary.
        """
        seen = {}
        for index, value in enumerate(nums):
            complement = target - value
            if complement in seen:
                return [seen[complement], index]
            seen[value] = index