HomeMedium Level QuestionTwo Sum Problem | HashMap | Two sum Interviewbit | leetcode two...

Two Sum Problem | HashMap | Two sum Interviewbit | leetcode two sum

Published on

spot_img

Introduction:
The “Two Sum” problem is a popular coding interview question where you are given an array of integers and a target sum. The task is to find two numbers in the array that add up to the target sum and return their indices. One efficient approach to solving this problem involves using a HashMap to store the elements of the array along with their indices. In this blog post, we will discuss how to solve the Two Sum problem using HashMap in the Java programming language.

Problem Statement:

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

Approach using HashMap:

  1. Create an empty HashMap to store the elements and their indices.
  2. Loop through each element num and index i in the array nums.
  3. Calculate the difference diff between the target and the current element num.
  4. Check if the diff is present in the HashMap. If yes, return the indices [hashMap.get(diff), i].
  5. Otherwise, put the current element num and its index i in the HashMap.

Java Code Implementation:

import java.util.*;

public class TwoSumHashMap {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> hashMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int diff = target - nums[i];
            if (hashMap.containsKey(diff)) {
                return new int[]{hashMap.get(diff), i};
            }
            hashMap.put(nums[i], i);
        }
        throw new IllegalArgumentException("No solution found.");
    }

    public static void main(String[] args) {
        TwoSumHashMap solution = new TwoSumHashMap();
        int[] nums = {2, 7, 11, 15};
        int target = 9;
        int[] result = solution.twoSum(nums, target);
        System.out.println("Indices: [" + result[0] + ", " + result[1] + "]");
    }
}

Explanation:

In this example, the array nums contains elements [2, 7, 11, 15] and the target sum is 9. The solution method twoSum uses a HashMap to store the elements encountered so far and their indices. During the loop, when i is 0, the current element is 2, and the difference diff is 7. Since 7 is not present in the HashMap, we add 2 to the HashMap with its index 0.

When i is 1, the current element is 7, and the difference diff is 2. Now, since 2 is present in the HashMap, we know that the pair [2, 7] adds up to the target 9, and we return the indices [0, 1].

Conclusion:

Using a HashMap to solve the Two Sum problem provides an efficient solution with a time complexity of O(n), where n is the number of elements in the input array. This approach showcases the power of data structures in solving common coding interview questions.

Latest articles

Social Proof Marketing: How to Build Trust and Boost Conversions Fast

Social Proof Marketing is a powerful strategy to build trust and influence customer decisions using reviews, testimonials, and real experiences. In this blog, learn how businesses and every digital marketer in 2026 use social proof to Boost Conversions Fast and grow using smart digital marketing services.

7 Proven Scarcity Marketing Strategies to Boost Sales Fast

Learn how Scarcity Marketing Strategies can help you create urgency, attract more customers, and boost conversions. This blog explains simple and proven techniques every digital marketer in 2026 can use to grow their digital marketing services and drive Sales Fast.

FOMO Marketing Strategy: How Brands Use Scarcity to Drive Instant Sales

Learn how the FOMO Marketing Strategy helps Brands create urgency and drive instant sales. This blog explains simple techniques used by every digital marketer in 2026 to boost conversions using smart digital marketing services. Discover how scarcity, social proof, and limited-time offers influence customer decisions and increase engagement.

The Psychology Behind Viral Content: Why Content Goes Viral

Discover the Psychology Behind Viral Content and learn why content goes viral. This guide helps every digital marketer in 2026 create engaging Content using smart digital marketing services.

More like this

Social Proof Marketing: How to Build Trust and Boost Conversions Fast

Social Proof Marketing is a powerful strategy to build trust and influence customer decisions using reviews, testimonials, and real experiences. In this blog, learn how businesses and every digital marketer in 2026 use social proof to Boost Conversions Fast and grow using smart digital marketing services.

7 Proven Scarcity Marketing Strategies to Boost Sales Fast

Learn how Scarcity Marketing Strategies can help you create urgency, attract more customers, and boost conversions. This blog explains simple and proven techniques every digital marketer in 2026 can use to grow their digital marketing services and drive Sales Fast.

FOMO Marketing Strategy: How Brands Use Scarcity to Drive Instant Sales

Learn how the FOMO Marketing Strategy helps Brands create urgency and drive instant sales. This blog explains simple techniques used by every digital marketer in 2026 to boost conversions using smart digital marketing services. Discover how scarcity, social proof, and limited-time offers influence customer decisions and increase engagement.