DEV Community

Mohith
Mohith

Posted on

two sum- java

Optimizing the Two Sum Problem in Java Using Hashing

Introduction

The Two Sum problem is one of the most fundamental problems in data structures and algorithms. It is simple to understand, yet it provides a strong foundation for learning how to optimize solutions.

When I first approached this problem, I used a brute force method. While it worked, it was not efficient. This led me to rethink the problem and arrive at a better solution using hashing.


Problem Statement

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


Brute Force Approach

The most straightforward solution is to check every possible pair.

“Check each pair and verify if their sum equals the target.”

Although this works correctly, it requires nested loops, resulting in a time complexity of O(n²). This approach becomes inefficient as the input size increases.


Rethinking the Problem

Instead of checking all pairs, a better way is to reframe the question.

Rather than asking:

“Which two numbers add up to the target?”

We can ask:

“For each number, what value is required to reach the target?”

This shift in perspective allows us to reduce unnecessary computations.


Optimized Approach Using Hashing

To implement this idea efficiently, we use a HashMap.

Steps:

  1. Create a HashMap to store elements and their indices.
  2. Traverse the array once.
  3. For each element:
  • Compute the complement: complement = target - current element
  • Check if the complement exists in the HashMap.
  • If it exists, return the indices.
  • Otherwise, store the current element in the map.

Example Walkthrough

Input:

nums = [2, 7, 11, 15];
target = 9;
Enter fullscreen mode Exit fullscreen mode

Step 1:

  • Current = 2 → complement = 7 → not found
  • Store → {2:0}

Step 2:

  • Current = 7 → complement = 2 → found

Output:

[0, 1]
Enter fullscreen mode Exit fullscreen mode

Java Implementation

import java.util.HashMap;

class Solution {
    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[] {};
    }
}
Enter fullscreen mode Exit fullscreen mode

Line-by-Line Explanation

Import Statement

import java.util.HashMap;
Enter fullscreen mode Exit fullscreen mode

Imports the HashMap class used for storing key-value pairs.


Class Definition

class Solution {
Enter fullscreen mode Exit fullscreen mode

Defines the class containing the solution.


Method Declaration

public int[] twoSum(int[] nums, int target)
Enter fullscreen mode Exit fullscreen mode
  • Returns an array of indices
  • Accepts the input array and target value

Create HashMap

HashMap<Integer, Integer> map = new HashMap<>();
Enter fullscreen mode Exit fullscreen mode

Stores elements in the format:
number → index


Loop Through Array

for (int i = 0; i < nums.length; i++)
Enter fullscreen mode Exit fullscreen mode

Iterates through each element of the array.


Calculate Complement

int complement = target - nums[i];
Enter fullscreen mode Exit fullscreen mode

Determines the value needed to reach the target.


Check for Complement

if (map.containsKey(complement))
Enter fullscreen mode Exit fullscreen mode

Checks if the required value already exists in the map.


Return Result

return new int[] { map.get(complement), i };
Enter fullscreen mode Exit fullscreen mode

Returns the indices of the two numbers.


Store Current Element

map.put(nums[i], i);
Enter fullscreen mode Exit fullscreen mode

Stores the current element for future reference.


Default Return

return new int[] {};
Enter fullscreen mode Exit fullscreen mode

Returns an empty array if no solution is found.


Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

This is significantly more efficient than the brute force approach.


Key Insight

The main idea is to avoid repeated work. By storing previously seen elements, we can directly check whether the required complement exists instead of searching repeatedly.


Conclusion

The Two Sum problem highlights how a small change in perspective can lead to a more efficient solution. Using hashing reduces time complexity and simplifies the implementation.


Tags

java dsa algorithms hashmap problem-solving coding-interview beginners

Top comments (0)