Two Sum
Python data engineering interview problem. Difficulty: beginner. Pattern: Hashing. About 10 minutes. Free to practice.
Return indices of two numbers that add to target. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.
A classic question: given a list of numbers and a target, find two different numbers in the list that add up to the target, and return their positions. Write a function two_sum(nums, target) that returns a list [i, j] with i < j, so that nums[i] + nums[j] == target. Positions start at 0. You can assume there is exactly one valid pair, and you may not use the same position twice. For [2, 7, 11, 15] and a target of 9, the numbers 2 and 7 add up to 9. They sit at positions 0 and 1, so the answer is [0, 1]. Keep the print lines in the editor.
Requirements
- Return the 2 indexes, not the 2 values.
- The smaller index comes first, so i < j.
- The two numbers at those indexes must add up to target.
- Do not use the same index twice.
Constraints
- There is exactly one valid pair, so you do not need to handle 'no answer'.
- Indexes start at 0.
- A value may appear more than once in the list, such as [3, 3] with target 6.
Examples
Input: two_sum([2, 7, 11, 15], 9) Output: [0, 1] 2 + 7 = 9.
Topics: lakebench, python, indices, hash map.
More Python interview questions · All interview problems · Learn data engineering
Two Sum
Interview-style drill: Return indices of two numbers that add to target.
Implement `two_sum(nums: list, target: int) -> list` returning 0-based indices `[i, j]` with i < j and nums[i] + nums[j] == target. Assume exactly one solution. Example: `[2, 7, 11, 15], 9` → `[0, 1]`. Keep the harness.