
Problem
Solution
Submissions
Two Sum
Certification: Basic Level
Accuracy: 38.89%
Submissions: 234
Points: 5
Write a Java program to implement the twoSum(int[] nums, int target) function, which finds indices of two numbers in an array such that they add up to a specific 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:
- nums[0] = 2 → looking for 7
- nums[1] = 7 → found complement
- Return [0, 1] since 2 + 7 = 9
Example 2
- Input: nums = [3, 2, 4], target = 6
- Output: [1, 2]
- Explanation:
- nums[1] = 2 → looking for 4
- nums[2] = 4 → found complement
- Return [1, 2] since 2 + 4 = 6
Constraints
- 2 ≤ nums.length ≤ 10^4
- -10^9 ≤ nums[i] ≤ 10^9
- -10^9 ≤ target ≤ 10^9
- 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
- Use a HashMap to store values and their indices as you iterate through the array
- For each element, check if its complement (target - current element) exists in the HashMap
- If found, return the indices of the current element and its complement
- Otherwise, add the current element and its index to the HashMap