Saturday, January 31, 2026

Two Sum

    Profile Pic of Akash AmanAkash Aman

    Updated: February 2026

    Two Sum
    easy

    💡 Intuition

    • As we scan the array, we trade extra memory for speed by remembering past numbers, allowing us to instantly check whether the current number completes a valid pair. Eg target − currentNumber should exist in past numbers.
    • We can maintain a hashmap to keep track of past number while iterating.

    111552711111552Iteration 1Iteration 2Iteration 3Iteration 4Iteration 5check presence of -2check presence of -6check presence of 4check presence of 7check presence of 2In every step after checking for key (difference) we add that to the set1115527111552711155271115527key = target - num[i] = 9 - 11 = -2 key = target - num[i] = 9 - 15 = -6 key = target - num[i] = 9 - 5 = 4 key = target - num[i] = 9 - 2 = 7 key = target - num[i] = 9 - 7 = 2 111551115

    🚀 Solution

    go
    func twoSum(nums []int, target int) []int {
        hashmap := map[int]int{};
    
        for index,val := range nums {
    		difference := target - val;
    
    		if  indx,ok := hashmap[val]; ok  {
    			return []int {
    				indx,
    				index,
    			};
    		}
    
    		hashmap[difference] = index;
        }
    
    	return []int {
    		0,
    		1,
    	}
    }

    ⏳ Time Complexity

    • Since we are taking single loop for the array of length n, the time complexity will be O(n)

    © 2026 Akash Aman | All rights reserved