Live Coding · 19 min · free lesson

Live Coding: Two Sum

Clarify duplicates, indices, and complexity first.

Core idea

State the contract before reaching for HashMap: may one index be reused, can values repeat, and what should happen when no pair exists? Then explain the O(n) time and O(n) space tradeoff.

Lesson map: the start of the two_sum HashMap scan with widened i64 arithmetic, above the rule to state the contract before reaching for HashMap.
Lookup before insertion enforces distinct indices; widening i32 arithmetic avoids complement overflow.

Understand it

State the contract before reaching for HashMap: may one index be reused, can values repeat, and what should happen when no pair exists? Then explain the O(n) time and O(n) space tradeoff.

Before coding, clarify whether the function returns values or indices, whether the same index may be used twice, whether duplicate values are allowed, and what 'no solution' means. A Rust signature such as fn two_sum(nums: &[i32], target: i32) -> Option<(usize, usize)> states that the input is borrowed and absence is normal. If arithmetic might overflow, decide whether the input range guarantees safety or whether checked subtraction is needed. This contract prevents an elegant implementation from solving the wrong problem.

For an O(n) expected-time approach, scan the slice once while storing previously seen values and their indices in a HashMap. For each current value, compute its complement and look it up before inserting the current value. That order prevents using the same index twice. Duplicates still work: when the second equal value appears, the first may be found. The map uses O(n) extra space. Hash lookup is expected constant time under normal assumptions, not an absolute worst-case guarantee.

Trace a small input by hand, including duplicates and a missing pair. State what happens when several pairs exist; the first found by this scan may depend on the chosen order. In an interview, test one element, two equal elements, negative numbers, and an overflow boundary if relevant. A nested-loop O(n²) version can be easier to verify and may be acceptable for tiny inputs. State the scale that justifies the map rather than treating O(n) as a ritual.

For deterministic results when multiple pairs exist, specify whether the earliest second index wins. The one-pass scan has a natural order, but changing the insertion or lookup order can change which valid pair is returned. A test should encode whichever rule the contract chooses.

Interview follow-up: Trace duplicates, no match and i32 extremes. What deterministic tie-breaking rule does this implementation actually provide?

Read the code

use std::collections::HashMap;
fn two_sum(values: &[i32], target: i32) -> Option<(usize, usize)> {
    let mut seen = HashMap::new();
    for (j, &value) in values.iter().enumerate() {
        let needed = i64::from(target) - i64::from(value);
        if let Some(&i) = seen.get(&needed) { return Some((i, j)); }
        seen.entry(i64::from(value)).or_insert(j);
    }
    None
}
fn main() {
    assert_eq!(two_sum(&[3, 3], 6), Some((0, 1)));
    assert_eq!(two_sum(&[3], 6), None);
}

Lookup before insertion enforces distinct indices; widening i32 arithmetic avoids complement overflow.

Practise this code in Playground ↗

Try it

Trace two_sum on [3, 3] with target 6, then state what it returns with no pair and with several pairs.

What success looks like: You explain why lookup comes before insertion and why the complement is computed in i64.

Check your understanding

Why must this scan look up the complement before inserting the current index?

Reveal the answer
  1. Only an earlier index can match, so one element is not reused as both operands.
  2. The lookup order guarantees all possible matching pairs are returned.
  3. Inserting first prevents all arithmetic overflow in the complement.

The example uses i64 arithmetic for i32 inputs. It returns the first matching second index, preserving the earliest stored first index; absence is None.

Go deeper

Common misconception: The lookup order guarantees all possible matching pairs are returned.

The function returns at its first match, so it reports one pair. Lookup before insertion only stops an element from pairing with itself.

  1. Identify the contract: Clarify duplicates, indices, and complexity first.
  2. Trace the concrete example: Lookup before insertion enforces distinct indices; widening i32 arithmetic avoids complement overflow.
  3. Test the changed constraint: Trace duplicates, no match and i32 extremes. What deterministic tie-breaking rule does this implementation actually provide?

Transfer challenge: Trace duplicates, no match and i32 extremes. What deterministic tie-breaking rule does this implementation actually provide?

Connections

  • FFI and ABI: Ownership across the C boundary
  • Design an LRU Cache: Combine lookup speed with recency updates
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Live Coding: Two Sum (courseId "interview", lessonId "q-two-sum-rust")
Link: https://crabrix.com/learn/interview/q-two-sum-rust/
Goal: State the contract before reaching for HashMap: may one index be reused, can values repeat, and what should happen when no pair exists? Then explain the O(n) time and O(n) space tradeoff.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=interview/q-two-sum-rust) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.