Back to Arrays & Hashing
Easy
Two Sum
Given an array of integers `nums` and an integer `target`, return indices of the two numbers such that they add up to `target`. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Examples
Input:nums = [2,7,11,15], target = 9
Output:[0,1]
nums[0] + nums[1] == 9, so we return [0, 1].
Constraints
2 <= nums.length <= 10^4-10^9 <= nums[i] <= 10^9-10^9 <= target <= 10^9Only one valid answer exists.
Approach
Iterate through the array with two nested loops. For each element `nums[i]`, iterate through the rest of the array `nums[j]` where `j > i`. Check if `nums[i] + nums[j] == target`. If a match is found, return their indices.
Complexity Analysis
Time Complexity
O(n^2)
Space Complexity
O(1)
This approach checks all possible pairs and does not require any extra space.
Solution.java
class Solution { public int[] twoSum(int[] nums, int target) { // Nested loops to check every pair for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { return new int[] { i, j }; } } } return new int[0]; }}