Two Sum Problem Solution in JavaScript

Today I didn’t just solve the Two Sum problem on LeetCode — I truly understood it. Instead of rushing to pass test cases, I slowed down and asked myself: What is the problem really asking? Why do we return indices and not values? How can I solve this efficiently instead of checking every possible pair? The key insight was thinking in terms of complements: “If I have this number, what number do I need to reach the target?” By storing previously seen numbers in a hash map, I was able to reduce the solution to a single pass through the array. Here’s the solution in JavaScript: function twoSum(nums, target) { const seen = {}; for (let i = 0; i < nums.length; i++) { const needed = target - nums[i]; if (seen[needed] !== undefined) { return [seen[needed], i]; } seen[nums[i]] = i; } } This small win reminded me that becoming a better software engineer isn’t about memorizing solutions — it’s about thinking clearly, writing intentional code, and understanding why it works. On to the next problem 🚀 #JavaScript #LeetCode #ProblemSolving #LearningInPublic #SoftwareEngineering #FrontendDeveloper #CareerGrowth

To view or add a comment, sign in

Explore content categories