Skip to main content
PreparationZone Logo
PreparationZone
Back to Fundamentals

Fundamentals · Easy · Free

Write and explain Two Sum — brute force vs hash map approach.

FresherFundamentalsData Structures & Algorithms
Model answer

Two Sum

Given array and target, return indices of two numbers that sum to target. Brute force checks all pairs O(n²); hash map stores value→index for O(n) one pass.

java
int[] twoSum(int[] nums, int target) {
  Map<Integer, Integer> seen = new HashMap<>();
  for (int i = 0; i < nums.length; i++) {
    int need = target - nums[i];
    if (seen.containsKey(need)) return new int[]{seen.get(need), i};
    seen.put(nums[i], i);
  }
  return new int[]{};
}
  • Edge: duplicate values, negative numbers
  • Space O(n) for map
Say brute force first, then optimize—interviewers track your process.