Two Sum Practice Problem
This data science coding problem helps you practice Data Structures, two sum, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Data Structures.
- Problem ID: 90
- Problem key: 90-two-sum
- URL: https://datacrack.app/solve/90-two-sum
- Difficulty: easy
- Topic: Data Structures
- Module: Python Fundamentals
Problem Statement
# š§© Two Sum
---
### šÆ Goal
Two Sum is the **most commonly asked coding interview problem** across data science, ML engineering, and software engineering roles. It teaches the single most important data structure pattern: using a **hash map (dictionary) to trade space for time**.
---
### š The Problem
Given a list of integers `nums` and a `target` sum, return the **indices** of the two numbers that add up to `target`. You may assume exactly one solution exists.
---
### š» Task
Implement `two_sum(nums, target)` in **O(n) time** using a dictionary.
> ā ļø **Do not** use a brute-force O(n²) nested loop. Use a hash map for O(n).
---
### š„ Input
- `nums`: list of integers
- `target`: int ā the target sum
### š¤ Output
- `list[int]` ā `[i, j]` where `nums[i] + nums[j] == target` and `i < j`
---
### š§© Starter Code
```python
def two_sum(nums, target):
"""
Find indices of two numbers that add up to target.
Args:
nums (list[int]): List of integers
target (int): Target sum
Returns:
list[int]: [i, j] where nums[i] + nums[j] == target
"""
seen = {} # maps value -> index
for i, num in enumerate(nums):
# š§ TODO: Compute the complement = target - num
# š§ TODO: If complement is already in seen, return [seen[complement], i]
# š§ TODO: Otherwise, store num in seen with its index
pass
```
---
### š” Example
```python
two_sum([2, 7, 11, 15], 9)
# Expected: [0, 1] (nums[0] + nums[1] = 2 + 7 = 9)
two_sum([3, 2, 4], 6)
# Expected: [1, 2] (nums[1] + nums[2] = 2 + 4 = 6)
```
---
### š Key Concepts
- `enumerate(nums)` gives `(index, value)` pairs
- `dict` lookup is O(1) ā this is why using a dict beats nested loops
- Complement: if `a + b = target`, then `b = target - a`Starter Code
def two_sum(nums, target):
"""
Find indices of two numbers that add up to target.
Args:
nums (list[int]): List of integers
target (int): Target sum
Returns:
list[int]: [i, j] where nums[i] + nums[j] == target
"""
seen = {} # maps value -> index
for i, num in enumerate(nums):
# š§ TODO: Compute the complement = target - num
# š§ TODO: If complement is already in seen, return [seen[complement], i]
# š§ TODO: Otherwise, store num in seen with its index
pass