BudiBadu Logo

Two Sum Indices

Hash Table Easy 5 views
Like0

Ever had a list of numbers and wanted to find two that add up to a specific target? That’s exactly what Two Sum Indices is about! You’re given an array of integers and a target value. Your mission is to find the indices of the two numbers that correctly add up to that total.

The "secret sauce" here is a Hash Table. While you could use nested loops to check every pair (which is slow), a hash table lets you ask: "Do I have the companion number that, when added to this one, equals our target?" as you walk through the array. This clever trick means you only scan the list once, giving you a lightning-fast O(n) linear complexity! This challenge is a classic because it perfectly demonstrates how to trade a tiny bit of memory for incredible speed. It’s the absolute best way to solve pairing problems with maximum elegance!

Keep the algorithm focused on one clear invariant and update path so correctness is easy to verify from left to right. This reduces accidental branching errors and helps ensure the final output stays consistent with the problem contract across random and adversarial test shapes.

Examples

Example 1
Input
nums = [2,7,11,15], target = 9
Output
[0,1]
Explanation

2 + 7 = 9.

Example 2
Input
nums = [3,2,4], target = 6
Output
[1,2]
Explanation

2 + 4 = 6.

Example 3
Input
nums = [3,3], target = 6
Output
[0,1]
Explanation

Both values 3 are used.

Algorithm Flow

Recommendation Algorithm Flow for Two Sum Indices - Budibadu
Recommendation Algorithm Flow for Two Sum Indices - Budibadu

Best Answers

java
import java.util.*;
class Solution {
    public int[] two_sum_indices(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[]{};
    }
}