Arrays · Coding problem
Two Sum
A free coding problem from the Array Hashing skill. Read it here, then solve it in the app in Java or Python.
- Easy
- Coding problem
- Free
- Java and Python
The problem
Given an unsorted list of integers nums and a number target, find the two positions whose values add up to target. Each test has exactly one such pair, and a position can't be paired with itself. Return the two 0-based positions, the smaller one first.
Example
Input: nums = [10, -4, 7, 3, 15], target = 11
Output: [1, 4]
-4 + 15 = 11.
Checking every pair with nested loops is O(n^2). Solve it in O(n) time.
Constraints
2 <= nums.length <= 2 * 10^5-10^9 <= nums[i] <= 10^9-10^9 <= target <= 10^9- Exactly one valid answer exists
How it's graded
- Run checks your code against the examples. Submit also runs a hidden suite in four groups - basic cases, edge cases, random inputs and performance tests at the size limit - and shows which groups pass, never the hidden inputs.
- Stuck? Hints come in four steps, from a nudge to a code skeleton, each costing part of the points.
- Once you pass, you see the approaches from brute force to optimal, and where your solution lands among them.
More problems in Array Hashing
Solve it Two Sum free
No card needed. Lessons, practice questions and easy problems are free forever.
Free plan, no card · 7-day Pro trial · Cancel anytime