1. Two Sum - Brute Force to Optimal

1. Two Sum - Brute Force to Optimal

Table of Contents

๐Ÿง  Problem Statement

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

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

You can return the answer in any order.


๐Ÿงช Example

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


โŒ Brute Force Approach

๐Ÿ” Idea:

Try every possible pair and check if their sum is equal to the target.

๐Ÿงพ Steps:

  • Loop over each element i.
  • For every i, loop over the remaining elements j > i.
  • If nums[i] + nums[j] == target, return the indices.

๐Ÿงฎ Time Complexity:

  • O(nยฒ) โ€” because of the nested loops

โœ… Code (Java):

public int[] twoSum(int[] nums, int target) {
    for (int i = 0; i < nums.length; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            if (nums[i] + nums[j] == target) {
                return new int[]{i, j};
            }
        }
    }
    return new int[]{-1, -1}; // fallback
}

โšก Better Approach (Using HashMap)

๐Ÿ” Idea:

Instead of checking every pair, we use a HashMap to store visited elements and their indices.

While iterating, check if target - nums[i] exists in the map.

๐Ÿงพ Steps:

Create an empty HashMap<Integer, Integer> to store value โ†’ index.

For each element nums[i], calculate complement = target - nums[i].

If complement exists in map โ†’ we found the pair.

Otherwise, store nums[i] โ†’ i in the map.

โฑ Time Complexity:

O(n) โ€” Single pass through array

โœ… Code (Java):

public int[] twoSum(int[] nums, int target) {
    HashMap<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[]{-1, -1}; // fallback
}

๐Ÿš€ Optimal Solution: Explanation in Plain English

Letโ€™s say the array is [2, 7, 11, 15] and the target is 9.

Start at index 0 โ†’ value is 2 โ†’ we want 7 (because 9-2=7).

Is 7 in the map? No. So store 2:0 in the map.

Move to index 1 โ†’ value is 7 โ†’ 9-7 = 2.

Is 2 in the map? Yes! We found our answer โ†’ [0, 1].

โœ๏ธ Conclusion

Brute force is good to start understanding the problem.

HashMap-based approach is the go-to optimal solution in interviews.

Always look for ways to store useful info during iteration.

Share :
comments powered by Disqus