Solving Two Sum Problem with Hashing in Java

🚀 Day 4 of 50 Days Coding Challenge Today I solved a problem on Hashing Pattern 🔹 Problem: Two Sum 🔹 Approach: First tried brute force using nested loops (checking all pairs) Then optimized using HashMap (Hashing concept) to reduce time complexity 🔹 Key Learning: Instead of checking every pair, we can store values and directly check if the required complement exists. This reduces time complexity from O(n²) → O(n) 🚀 Also learned an important concept: 👉 need = target - current element 🔹 Time Complexity: O(n) 🔹 Code (Java): import java.util.*; class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < nums.length; i++) { int need = target - nums[i]; if(map.containsKey(need)) { return new int[]{map.get(need), i}; } map.put(nums[i], i); } return new int[]{-1, -1}; } } 💡 Consistency > Motivation #coding #leetcode #100DaysOfCode #java #programming #dsa #learning #hashmap

To view or add a comment, sign in

Explore content categories