
Problem
Solution
Submissions
Two Sum
Certification: Basic Level
Accuracy: 9.68%
Submissions: 31
Points: 5
Write a C program to find two numbers in an array that add up to a specific target. The function should return the indices of the two numbers such that they add up to the target. You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example 1
- Input: nums = [2, 7, 11, 15], target = 9
- Output: [0, 1]
- Explanation: The numbers at indices 0 and 1 are 2 and 7, and 2 + 7 = 9.
Example 2
- Input: nums = [3, 2, 4], target = 6
- Output: [1, 2]
- Explanation: The numbers at indices 1 and 2 are 2 and 4, and 2 + 4 = 6.
Constraints
- 2 ≤ nums.length ≤ 10^4
- -10^9 ≤ nums[i] ≤ 10^9
- -10^9 ≤ target ≤ 10^9
- Only one valid answer exists
- Time Complexity: O(n)
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- A brute force approach would be to check every possible pair, but this would be O(n²) time complexity
- Use a hash table (or a map) to store each element's value and its index
- For each element, check if the complement (target - current element) exists in the hash table
- If the complement exists, you've found your pair
- If not, add the current element to the hash table and continue