Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

The optimal solution uses a HashMap to store each number and its corresponding index while traversing the array. For every element, the required complement value is calculated as target - currentNumber.

If the complement already exists in the HashMap, the indices of the complement and the current element form the required answer. Otherwise, the current number and its index are added to the map for future lookups.

This approach avoids the nested loop solution and significantly improves performance for large input arrays.

Java Solution:

import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;

public class TwoSum {

    public static int[] findTwoSum(int[] nums, int target) {

        Map<Integer, Integer> numberIndexMap = new HashMap<>();

        for (int currentIndex = 0; currentIndex < nums.length; currentIndex++) {

            int complement = target - nums[currentIndex];

            if (numberIndexMap.containsKey(complement)) {
                return new int[]{
                        numberIndexMap.get(complement),
                        currentIndex
                };
            }

            numberIndexMap.put(nums[currentIndex], currentIndex);
        }

        return new int[]{-1, -1};
    }

    public static void main(String[] args) {

        int[] nums = {2, 7, 11, 15};
        int target = 9;

        int[] result = findTwoSum(nums, target);

        System.out.println(Arrays.toString(result));
    }
}

Output: [0, 1]

Time Complexity: O(n), where n is the number of elements in the array because each element is processed exactly once.

Space Complexity: O(n), as the HashMap may store all elements in the worst case.

Key Interview Points: • HashMap enables constant-time average lookup for complement values. • The brute-force approach uses nested loops and requires O(n²) time complexity. • This is one of the most frequently asked coding interview problems and is commonly used to evaluate understanding of HashMap usage. • A common follow-up question is to return the actual numbers instead of their indices or to solve the problem for a sorted array using the two-pointer technique.