Two Sum JavaScript Solution in O(n) Time

🚀 Day 4 of my JavaScript Coding Practice Today’s problem: Two Sum var twoSum = function(nums, target) { const map = new Map(); // Store: { value : index } for (let i = 0; i < nums.length; i++) { const complement = target - nums[i]; // If the needed number is already in our map, we found the pair! if (map.has(complement)) { return [map.get(complement), i]; } // Otherwise, save the current number and its index map.set(nums[i], i); } return []; // Return empty if no pair is found }; 💡 Instead of using brute force (O(n²)), I used a HashMap approach to solve it in O(n) time. Key takeaway: Understanding how to trade space for time can significantly optimize performance. Small steps every day → Big improvements over time 📈 #JavaScript #DSA #CodingPractice #100DaysOfCode #FrontendDevelopment

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories