Two Sum - LeetCode Solution in Java

1. Introduction

The "Two Sum" problem is a common coding challenge that involves finding two numbers in an array that add up to a specific target sum.

2. Problem

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

3. Solution Steps

1. Initialize a HashMap to store the elements and their indices.

2. Iterate through the array nums.

3. For each element, calculate the complement (i.e., target - nums[i]).

4. Check if the complement exists in the HashMap.

5. If it exists, return the current index and the index of the complement.

6. If not, put the element and its index into the HashMap.

7. Continue the process until a solution is found.

4. Solution in Java

import java.util.HashMap;
import java.util.Map;

public class TwoSum {
    public static int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> numMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (numMap.containsKey(complement)) {
                return new int[] { numMap.get(complement), i };
            }
            numMap.put(nums[i], i);
        }
        return new int[] {};
    }

    public static void main(String[] args) {
        int[] nums = {2, 7, 11, 15};
        int target = 9;
        int[] result = twoSum(nums, target);
        for (int index : result) {
            System.out.print(index + " ");
        }
    }
}

Output:

0 1

Explanation:

1. A hash map (HashMap) is used for storing the indices of the numbers.

2. Iterate through each element in the array.

3. Check if the complement (target - current element) exists in the map.

4. If it exists, return the pair of indices.

5. Store the current element and its index in the map if not already present.


Comments