Two Sum

Solve the famous Two Sum coding problem often asked in interviews.

Two Sum

🧩 Problem Statement

Given an array of integers, return the indices of the two numbers that add up to a specific target.

You may assume that each input has exactly one solution, and you may not use the same element twice.

✍️ Function Signature

public int[] twoSum(int[] nums, int target)

πŸš€ Approach

This solution uses a hash map to store the numbers we’ve seen so far and their indices. For each element, we check if the complement (target - current element) exists in the map. If it does, we return its index and the current index.

βœ… Time Complexity

  • O(n) β€” where n is the number of elements in the array.

πŸ’‘ Java Implementation

import java.util.*;

public class TwoSumSolver {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement)) {
                return new int[] { map.get(complement), i };
            }
            map.put(nums[i], i);
        }
        return new int[] {}; // Return empty array if no solution
    }
}

πŸ§ͺ Test Cases

public class TwoSumTest {
    public static void main(String[] args) {
        TwoSumSolver solver = new TwoSumSolver();

        // Test Case 1
        int[] result1 = solver.twoSum(new int[] {2, 7, 11, 15}, 9);
        System.out.println(Arrays.toString(result1)); // Output: [0, 1]

        // Test Case 2
        int[] result2 = solver.twoSum(new int[] {3, 2, 4}, 6);
        System.out.println(Arrays.toString(result2)); // Output: [1, 2]

        // Test Case 3
        int[] result3 = solver.twoSum(new int[] {1, 5, 3, 7}, 8);
        System.out.println(Arrays.toString(result3)); // Output: [0, 3]

        // Test Case 4
        int[] result4 = solver.twoSum(new int[] {0, -1, 2, -3, 1}, -2);
        System.out.println(Arrays.toString(result4)); // Output: [1, 3]

        // Test Case 5
        int[] result5 = solver.twoSum(new int[] {1, 2, 3, 4, 5}, 10);
        System.out.println(Arrays.toString(result5)); // Output: [] (No solution)
    }
}

πŸ“Œ Notes

  • Input constraints and assumptions should be clearly specified during interviews.
  • It’s a good idea to discuss edge cases, like arrays with duplicates or negative numbers.

Happy coding! 🎯

Related Posts