diff --git a/Problems/Arrays/TwoSum.java b/Problems/Arrays/TwoSum.java new file mode 100644 index 0000000..dc63c80 --- /dev/null +++ b/Problems/Arrays/TwoSum.java @@ -0,0 +1,61 @@ +/** + * Problem: Two Sum (Issue #12) + * + * Given an array of integers nums and an integer target, return the 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. + * + * Approach: HashMap for O(n) lookup + * - Iterate through the array + * - For each element, check if (target - element) exists in the map + * - If yes, return the stored index and the current index + * - Otherwise, store the element and its index in the map + * + * Time Complexity: O(n) + * Space Complexity: O(n) + * + * Test Cases: + * nums = [2, 7, 11, 15], target = 9 -> [0, 1] + * nums = [3, 2, 4], target = 6 -> [1, 2] + * nums = [3, 3], target = 6 -> [0, 1] + */ + +import java.util.Arrays; +import java.util.HashMap; + +public class TwoSum { + + public int[] twoSum(int[] nums, int target) { + // Map stores: value -> index + HashMap map = new HashMap<>(); + + for (int i = 0; i < nums.length; i++) { + int complement = target - nums[i]; + + if (map.containsKey(complement)) { + // Found the pair + return new int[]{map.get(complement), i}; + } + + // Store current element with its index + map.put(nums[i], i); + } + + // Problem guarantees a solution exists, so this won't be reached + throw new IllegalArgumentException("No two sum solution found."); + } + + public static void main(String[] args) { + TwoSum solution = new TwoSum(); + + // Test case 1: Expected [0, 1] + System.out.println(Arrays.toString(solution.twoSum(new int[]{2, 7, 11, 15}, 9))); + + // Test case 2: Expected [1, 2] + System.out.println(Arrays.toString(solution.twoSum(new int[]{3, 2, 4}, 6))); + + // Test case 3: Expected [0, 1] + System.out.println(Arrays.toString(solution.twoSum(new int[]{3, 3}, 6))); + } +}