Two Sum Problem Solved with HashMap and Complement Approach

Day 1 — 100 Days of Code | Solved Two Sum Problem (LeetCode) Today I solved the classic Two Sum problem, one of the most common problems asked in coding interviews. 🧩 Problem https://lnkd.in/g9KcCNRv Given an array of integers nums and an integer target, return the indices of two numbers such that their sum equals the target. Example: nums = [2,7,11,15] target = 9 Output → [0,1] Because: nums[0] + nums[1] = 2 + 7 = 9 💡 My Approach At first, the straightforward idea was: Brute Force Approach Check every pair using two loops Time Complexity → O(n²) But we can optimize it. Optimized Approach (HashMap) Idea: Iterate through the array once For each element calculate the complement complement = target - current number Check if complement already exists in HashMap If yes → solution found Otherwise store current number and index in map This reduces time complexity significantly. 🧠 Complexity Time Complexity → O(n) Space Complexity → O(n) 💻 Java Solution import java.util.HashMap; class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer,Integer> map = new HashMap<>(); for(int i = 0; i < nums.length; i++){ int complement = target - nums[i]; if(map.containsKey(complement)){ return new int[]{map.get(complement), i}; } map.put(nums[i], i); } return new int[]{-1,-1}; } } 📚 Key Learning This problem helped me understand the HashMap + Complement pattern, which is useful in many problems like: Pair Sum Subarray Sum Two Sum variants Excited to continue my #100DaysOfCode journey 🚀 Hashtags #100DaysOfCode #Java #DSA #LeetCode #ProblemSolving #CodingJourney #SoftwareEngineering #BackendDeveloper

  • graphical user interface, text, application, email

To view or add a comment, sign in

Explore content categories