Optimizing Two Sum Problem with HashMap in Java

Day 2/30 of #30DaysOfDSA 🔹 Problem: Two Sum 💡 Approach: I first thought of a brute-force approach. I checked all possible pairs using two loops and returned the indices where the sum equals the target. This works fine but takes O(n²) time. Then I optimized the solution using HashMap. Instead of checking every pair, I stored each element with its index in a HashMap. For every element, I calculated the complement (target - current value) and checked if it already exists in the map. This reduced the time complexity to O(n) and made the solution more efficient. ⚡ What I Learned: I learned how to optimize a problem by reducing unnecessary comparisons. Using HashMap helps achieve faster lookups and improves time complexity significantly. #DSA #Coding #Consistency #Java

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories