Bird
Raised Fist0
DSA Rustprogramming~20 mins

Two Sum Problem Classic Hash Solution in DSA Rust - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Two Sum Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Rust code for Two Sum?
Given the Rust function below that finds two indices of numbers adding up to the target, what will be printed when calling two_sum(vec![2, 7, 11, 15], 9)?
DSA Rust
use std::collections::HashMap;

fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
    let mut map = HashMap::new();
    for (i, &num) in nums.iter().enumerate() {
        let complement = target - num;
        if let Some(&index) = map.get(&complement) {
            return vec![index as i32, i as i32];
        }
        map.insert(num, i);
    }
    vec![]
}

fn main() {
    let result = two_sum(vec![2, 7, 11, 15], 9);
    println!("{:?}", result);
}
A[]
B[0, 1]
C[1, 2]
D[2, 3]
Attempts:
2 left
💡 Hint
Think about which two numbers add up to 9 and their indices in the vector.
❓ Predict Output
intermediate
2:00remaining
What does this Rust code print for no solution case?
What will be the output of the Rust program below when calling two_sum(vec![1, 2, 3], 7)?
DSA Rust
use std::collections::HashMap;

fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
    let mut map = HashMap::new();
    for (i, &num) in nums.iter().enumerate() {
        let complement = target - num;
        if let Some(&index) = map.get(&complement) {
            return vec![index as i32, i as i32];
        }
        map.insert(num, i);
    }
    vec![]
}

fn main() {
    let result = two_sum(vec![1, 2, 3], 7);
    println!("{:?}", result);
}
A[]
B[0, 2]
C[1, 2]
D[0, 1]
Attempts:
2 left
💡 Hint
Check if any two numbers add up to 7 in the list.
🔧 Debug
advanced
2:00remaining
What error does this Rust code cause?
Consider this Rust code snippet for Two Sum. What error will it produce when compiled?
DSA Rust
use std::collections::HashMap;

fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
    let mut map = HashMap::new();
    for (i, &num) in nums.iter().enumerate() {
        let complement = target - num;
        if let Some(&index) = map.get(&complement) {
            return vec![index as i32, i as i32];
        }
        map.insert(num, i);
    }
    vec![]
}
ASyntaxError: missing semicolon after HashMap::new()
BTypeError: cannot borrow immutable reference as mutable
CRuntimeError: index out of bounds
DNo error, compiles successfully
Attempts:
2 left
💡 Hint
Look carefully at the line where HashMap is created.
❓ Predict Output
advanced
2:00remaining
What is the output of this Rust code with duplicate numbers?
What will be printed when running this Rust program?
DSA Rust
use std::collections::HashMap;

fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
    let mut map = HashMap::new();
    for (i, &num) in nums.iter().enumerate() {
        let complement = target - num;
        if let Some(&index) = map.get(&complement) {
            return vec![index as i32, i as i32];
        }
        map.insert(num, i);
    }
    vec![]
}

fn main() {
    let result = two_sum(vec![3, 3, 4, 5], 6);
    println!("{:?}", result);
}
A[2, 3]
B[1, 2]
C[0, 1]
D[]
Attempts:
2 left
💡 Hint
Check which two numbers add up to 6 and their indices.
🧠 Conceptual
expert
2:00remaining
Why does the Two Sum hash solution run in O(n) time?
Which reason best explains why the classic Two Sum hash map solution runs in linear time?
ABecause it uses recursion to divide the problem
BBecause it sorts the array first and then uses two pointers
CBecause it uses nested loops to check all pairs
DBecause it uses a hash map to check complements in constant time for each element
Attempts:
2 left
💡 Hint
Think about how hash maps help with quick lookups.

Practice

(1/5)
1. What is the main purpose of using a hash map in the Two Sum problem classic hash solution?
easy
A. To reverse the array elements
B. To sort the array before searching
C. To store the sum of all pairs
D. To store numbers and their indices for quick lookup

Solution

  1. Step 1: Understand the role of hash map

    The hash map stores each number as a key and its index as the value for quick access.
  2. Step 2: Use hash map for complement lookup

    For each number, we check if the complement (target - number) exists in the hash map to find the pair.
  3. Final Answer:

    To store numbers and their indices for quick lookup -> Option D
  4. Quick Check:

    Hash map stores number:index pairs [OK]
Hint: Hash map helps find complements fast by storing indices [OK]
Common Mistakes:
  • Thinking hash map sorts the array
  • Trying to store sums instead of indices
  • Using hash map to reverse elements
2. Which of the following Rust code snippets correctly declares a mutable hash map to solve the Two Sum problem?
easy
A. let map = HashMap::new();
B. let mut map = std::collections::HashMap::new();
C. let mut map = HashMap::new();
D. let map = std::collections::HashMap::new();

Solution

  1. Step 1: Identify mutable hash map declaration

    To insert elements, the hash map must be mutable, so use 'let mut'.
  2. Step 2: Use full path or import HashMap

    Using 'std::collections::HashMap::new()' is correct if HashMap is not imported.
  3. Final Answer:

    let mut map = std::collections::HashMap::new(); -> Option B
  4. Quick Check:

    Mutable hash map declaration requires 'mut' [OK]
Hint: Use 'let mut' to allow inserting into hash map [OK]
Common Mistakes:
  • Forgetting 'mut' keyword for mutable map
  • Using HashMap without importing or full path
  • Declaring map immutable when insertions needed
3. What will be the output of the following Rust code snippet for the Two Sum problem?
fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
    let mut map = std::collections::HashMap::new();
    for (i, &num) in nums.iter().enumerate() {
        if let Some(&index) = map.get(&(target - num)) {
            return vec![index as i32, i as i32];
        }
        map.insert(num, i);
    }
    vec![]
}

fn main() {
    let result = two_sum(vec![2, 7, 11, 15], 9);
    println!("{:?}", result);
}
medium
A. [2, 3]
B. [1, 0]
C. [0, 1]
D. []

Solution

  1. Step 1: Iterate and check complements

    At i=0, num=2, map empty, insert (2,0). At i=1, num=7, complement=9-7=2 found at index 0.
  2. Step 2: Return indices of complement pair

    Return vector with indices [0,1] as the pair sums to target 9.
  3. Final Answer:

    [0, 1] -> Option C
  4. Quick Check:

    Indices of 2 and 7 are [0,1] [OK]
Hint: Check complement in map before inserting current number [OK]
Common Mistakes:
  • Returning indices in wrong order
  • Not casting usize to i32 for return
  • Returning empty vector when pair exists
4. Identify the bug in this Rust Two Sum solution and select the fix:
fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
    let mut map = std::collections::HashMap::new();
    for (i, num) in nums.iter().enumerate() {
        if let Some(&index) = map.get(&(target - num)) {
            return vec![index as i32, i as i32];
        }
        map.insert(num, i);
    }
    vec![]
}
medium
A. Change 'num' to '*num' in map.insert to match key type
B. Remove 'as i32' casts from return vector
C. Change 'map.get(&(target - num))' to 'map.get(&(target + num))'
D. Declare map as immutable instead of mutable

Solution

  1. Step 1: Check key types in hash map

    Keys are i32 values, but 'num' is a reference (&i32), so insert needs dereferenced value.
  2. Step 2: Fix insertion to use dereferenced num

    Change 'map.insert(num, i);' to 'map.insert(*num, i);' to insert i32 key, matching get() key type.
  3. Final Answer:

    Change 'num' to '*num' in map.insert to match key type -> Option A
  4. Quick Check:

    Dereference num when inserting key [OK]
Hint: Dereference iterator item before inserting into hash map [OK]
Common Mistakes:
  • Inserting reference instead of value as key
  • Changing target arithmetic incorrectly
  • Making map immutable causing insert error
5. Given the input array [3, 3, 4, 5] and target 6, what will the Two Sum classic hash solution return and why?
hard
A. [0, 1] because the first two 3's sum to 6
B. [1, 2] because 3 and 4 sum to 7, closest to 6
C. [2, 3] because 4 and 5 sum to 9, which is greater than 6
D. [] because no two numbers sum exactly to 6

Solution

  1. Step 1: Check pairs for target sum

    The first element 3 at index 0 is inserted. At index 1, num=3, complement=6-3=3 found at index 0.
  2. Step 2: Return indices of first matching pair

    Return [0,1] because these two 3's sum exactly to 6.
  3. Final Answer:

    [0, 1] because the first two 3's sum to 6 -> Option A
  4. Quick Check:

    First pair summing to target returned [OK]
Hint: Return first found pair that sums to target [OK]
Common Mistakes:
  • Choosing pairs that don't sum to target
  • Ignoring duplicate values as valid pairs
  • Returning empty vector incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard