Two Sum Flashcards
(17 cards)
What is the classic problem discussed in the text?
Two Sum
List keywords that should stand out when recognizing the Two Sum problem.
- return indices
- two numbers
- add up to target
- exactly one solution
- don’t use the same element twice
What type of problem is the Two Sum problem categorized as?
Hashing problem
What are the constraints you can assume in the Two Sum problem?
- There is always exactly one solution
- You can return the indices in any order
- Don’t reuse the same index
What is the goal of the Two Sum problem?
Find two numbers in the array that sum to the target and return their indices.
Describe the brute force approach to solving the Two Sum problem.
For each element, check every other element to see if the sum equals the target.
What is the time complexity of the brute force approach?
O(n²)
What is the best approach to optimize the Two Sum problem?
Using a hash map
What is the core idea of the hash map approach?
Store each number in a hash map with its index and check if the complement exists.
What is the time complexity of the optimized hash map approach?
O(n)
What is the space complexity of the optimized hash map approach?
O(n)
What should you clarify in an interview when discussing the Two Sum problem?
- Can I assume there’s only one solution?
- Can the same number be used twice?
What should you do after quickly discussing the brute force method?
Propose the hash map approach.
In the hash map approach, when should you add the number to the hash map?
After checking the complement to avoid using the same element twice.
Provide an example of how the Two Sum algorithm works with nums = [2, 7, 11, 15] and target = 9.
- Iteration 0: num = 2, complement = 7 → not in seen, store 2:0
- Iteration 1: num = 7, complement = 2 → found! return [0, 1]
What is the summary of approaches for the Two Sum problem?
- Brute Force: O(n²), O(1)
- Hash Map: O(n), O(n)
What problem is this?
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Two Sum