📖 Scenario: You are working on a financial app that analyzes daily stock price changes. You want to find all unique sets of three days where the total change sums to zero, indicating a balanced period.
🎯 Goal: Build a Rust program that finds all unique triplets in a list of integers that sum to zero.
📋 What You'll Learn
Create a vector called nums with the exact values: -1, 0, 1, 2, -1, -4
Create a variable called result to store the unique triplets as vectors of integers
Implement the three sum logic using sorting and two pointers to find all unique triplets that sum to zero
Print the result vector showing all unique triplets
💡 Why This Matters
🌍 Real World
Finding balanced periods in financial data or sets of numbers that meet specific sum criteria is common in data analysis and algorithmic trading.
💼 Career
Understanding the three sum problem helps in mastering array manipulation, sorting, and two-pointer techniques, which are frequently asked in coding interviews.
Progress0 / 4 steps
1
Create the input vector
Create a vector called nums with the exact integers -1, 0, 1, 2, -1, -4.
DSA Rust
Hint
Use let mut nums = vec![...] to create the vector with the exact values.
2
Create the result vector
Create a mutable vector called result to store vectors of integers representing the unique triplets.
DSA Rust
Hint
Use let mut result: Vec> = Vec::new(); to create an empty vector of integer vectors.
3
Implement the three sum logic
Sort the nums vector. Use a for loop with index i to iterate over nums. Inside, use two pointers left and right to find all unique triplets that sum to zero and add them to result. Skip duplicates for i, left, and right to ensure uniqueness.
DSA Rust
Hint
Sort the vector first. Use a for loop with index i. Use two pointers left and right to find triplets. Skip duplicates by checking neighbors.
4
Print the result vector
Print the result vector using println! to display all unique triplets found.
DSA Rust
Hint
Use println!("{:?}", result); to print the vector of triplets.
Practice
(1/5)
1. What is the main goal of the Three Sum Problem All Unique Triplets in data structures and algorithms?
easy
A. Find the maximum element in the array
B. Find all unique triplets in an array that sum to zero
C. Sort the array in ascending order
D. Count the number of pairs that sum to zero
Solution
Step 1: Understand the problem statement
The problem asks to find all unique sets of three numbers in the array whose sum is zero.
Step 2: Clarify the output
The output should be a list of triplets with no duplicates, each summing to zero.
Final Answer:
Find all unique triplets in an array that sum to zero -> Option B
Quick Check:
Three Sum Problem = Find unique triplets summing to zero [OK]
Hint: Look for three numbers adding to zero without duplicates [OK]
Common Mistakes:
Confusing with pair sum problems
Ignoring uniqueness of triplets
Only finding one triplet instead of all
2. Which Rust code snippet correctly initializes a vector to solve the Three Sum problem?
easy
A. let nums = [1, -1, 0, 2, -2];
B. let nums = {1, -1, 0, 2, -2};
C. let nums = (1, -1, 0, 2, -2);
D. let nums = vec![1, -1, 0, 2, -2];
Solution
Step 1: Identify Rust vector syntax
In Rust, vectors are created using vec![elements] syntax.
Step 2: Check each option
let nums = vec![1, -1, 0, 2, -2]; uses vec![], which is correct. let nums = [1, -1, 0, 2, -2]; is an array, not a vector. let nums = (1, -1, 0, 2, -2); is a tuple. let nums = {1, -1, 0, 2, -2}; is invalid syntax.
Final Answer:
let nums = vec![1, -1, 0, 2, -2]; -> Option D
Quick Check:
Vector initialization uses vec! macro [OK]
Hint: Use vec![] to create vectors in Rust [OK]
Common Mistakes:
Using array syntax instead of vector
Using tuple instead of vector
Invalid braces for initialization
3. What is the output of the following Rust code snippet that finds unique triplets summing to zero?
fn main() {
let mut nums = vec![-1, 0, 1, 2, -1, -4];
nums.sort();
let mut result = Vec::new();
for i in 0..nums.len() - 2 {
if i > 0 && nums[i] == nums[i - 1] { continue; }
let (mut left, mut right) = (i + 1, nums.len() - 1);
while left < right {
let sum = nums[i] + nums[left] + nums[right];
if sum == 0 {
result.push(vec![nums[i], nums[left], nums[right]]);
while left < right && nums[left] == nums[left + 1] { left += 1; }
while left < right && nums[right] == nums[right - 1] { right -= 1; }
left += 1;
right -= 1;
} else if sum < 0 {
left += 1;
} else {
right -= 1;
}
}
}
println!("{:?}", result);
}
medium
A. [[-1, -1, 2], [-1, 0, 1]]
B. [[-4, 0, 4], [-1, -1, 2]]
C. [[0, 0, 0]]
D. []
Solution
Step 1: Sort the array
Sorted array is [-4, -1, -1, 0, 1, 2].
Step 2: Find triplets summing to zero
Triplets found are [-1, -1, 2] and [-1, 0, 1].
Final Answer:
[[-1, -1, 2], [-1, 0, 1]] -> Option A
Quick Check:
Unique triplets summing zero = [[-1,-1,2],[-1,0,1]] [OK]
Hint: Sort array, use two pointers to find triplets [OK]
Common Mistakes:
Not sorting before two-pointer approach
Including duplicate triplets
Incorrect pointer movement
4. Identify the bug in this Rust code snippet for the Three Sum problem:
fn three_sum(nums: &mut Vec<i32>) -> Vec {
nums.sort();
let mut res = Vec::new();
for i in 0..nums.len() {
if i > 0 && nums[i] == nums[i - 1] { continue; }
let (mut left, mut right) = (i + 1, nums.len() - 1);
while left < right {
let sum = nums[i] + nums[left] + nums[right];
if sum == 0 {
res.push(vec![nums[i], nums[left], nums[right]]);
left += 1;
right -= 1;
} else if sum < 0 {
left += 1;
} else {
right -= 1;
}
}
}
res
}
medium
A. Loop runs beyond valid range causing panic
B. Sorting is done after the loop
C. Missing duplicate skipping after finding a triplet
D. Using immutable vector instead of mutable
Solution
Step 1: Check duplicate handling after triplet found
The code does not skip duplicates for left and right pointers after pushing a triplet.
Step 2: Understand impact
Without skipping duplicates, duplicate triplets may be added to the result.
Final Answer:
Missing duplicate skipping after finding a triplet -> Option C
Quick Check:
Duplicate skipping after triplet push is required [OK]
Hint: Skip duplicates after adding triplet to avoid repeats [OK]
Common Mistakes:
Not skipping duplicates for left and right pointers
Incorrect loop range causing panic
Sorting after loop instead of before
5. Given the input vector vec![0, 0, 0, 0], what is the correct output of a properly implemented Three Sum solution that finds all unique triplets summing to zero?
hard
A. [[0, 0, 0]]
B. [[0, 0, 0], [0, 0, 0]]
C. []
D. [[0, 0]]
Solution
Step 1: Analyze input with duplicates
Input has four zeros, so multiple triplets of zeros exist but are duplicates.
Step 2: Unique triplets only
The solution must return only one unique triplet [0, 0, 0].
Final Answer:
[[0, 0, 0]] -> Option A
Quick Check:
Only one unique zero triplet exists [OK]
Hint: Return unique triplets only, even if duplicates exist [OK]
Common Mistakes:
Returning duplicate triplets multiple times
Returning empty list incorrectly
Returning pairs instead of triplets
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.