Pages

Sunday, November 30, 2025

Two Sum - optimized code (using HashMaps)

 public int[] twoSum(int[] nums, int target) {

    // Phase 2 Logic: HashMap

    HashMap<Integer, Integer> map = new HashMap<>();


    for (int i = 0; i < nums.length; i++) {

        int complement = target - nums[i];


        if (map.containsKey(complement)) {

            // Success: Return [Old Index, Current Index]

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

        }

        

        // Store: Key = Number, Value = Index

        map.put(nums[i], i);

    }

    return new int[] {}; // Fallback

}

No comments:

Post a Comment

3Sum - Leetcode solution - How i turned into two-pointer approach?

  class Solution {     public List < List < Integer >> threeSum ( int [] nums ) {         Arrays . sort (nums); // first sort...