Two Sum

LeetCode#1

Problem Statement

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to 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.

Golang code for Two sum

func twoSum(nums []int, target int) []int {
	seen := make(map[int]int)

	for i, x := range nums {
		if j, ok := seen[target - x]; ok {
			return []int{i, j}
		}
		seen[x] = i
	}

	return []int{}
}

JAVA CODE TWO SUM

Version-1

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int len = nums.length;
        HashMap<Integer, Integer> mem = new HashMap<Integer, Integer>();
        int[] result = new int[2];

        //First element handling: You are initializing the mem map with the
        // first element of the array before the loop starts. 
        //This can cause issues if the first element itself is 
        //part of the solution.
        mem.put(nums[0], 0);
        for(int i=0; i < nums.length; i++){
        // Index out of bounds exception: In the for loop, 
        // you access nums[j] where j = i + 1. 
        // When i is the last index (nums.length - 1), 
        // j will be nums.length, causing an IndexOutOfBoundsException.
    
    
            int j = i+1;
            if(mem.containsKey(target-nums[j])) {
                // Return order: The problem typically asks for 
                // indices in increasing order, 
                // but this solution may not guarantee this.
                result[0] = j;
                result[1] = mem.get(target-nums[j]);
                break;
            }else{
                mem.put(nums[j], j);
            }
        }
        
        return result;

    }
}

Version-2 Corrected and optimized

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> mem = new HashMap<>();

        for(int i = 0; i < nums.length; i++){
            int secondNumber = target - nums[i];
            if(mem.containsKey(secondNumber)){
                return new int[]{mem.get(secondNumber), i};
            }
            mem.put(nums[i], i);
        }
        return new int[]{-1,-1};
    }
}

Prev Problem : https://codeandalgo.com/water-bottles/

Visit https: https://codeandalgo.com for more such contents

Leave a Reply

Your email address will not be published. Required fields are marked *