Back to articles
two sum- java

two sum- java

via Dev.to BeginnersMohith

🚀 Solving Two Sum Using Hashing (My Thought Process) When I first saw the Two Sum problem , my initial idea was simple: “Check every pair and see if their sum equals the target.” That works, but it’s slow (O(n²)). So I started thinking… My Thought Process Instead of checking all pairs, I asked myself: 👉 “For each number, what do I actually need to reach the target?” Let’s say: Target = 9 Current number = 2 Then I don’t need to search randomly. I just need 7 , because: 👉 2 + 7 = 9 So the problem becomes: 👉 “Have I already seen the number I need?” --- Key Idea (Breakthrough Moment) Instead of searching again and again… 👉 I can store the numbers I’ve already seen 👉 And quickly check if the required number exists This is where HashMap (Hashing) comes in. --- 🧠 How I Designed the Logic Create a HashMap → Store: number → index Loop through the array For each element: Calculate: complement = target - current number Check: 👉 “Does this complement already exist in my map?” If YES: I found the a

Continue reading on Dev.to Beginners

Opens in a new tab

Read Full Article
0 views

Related Articles