JavaScript Single Number Problem Solution with Hash Map and XOR

📘 DSA Practice | Single Number (JavaScript) Today I solved a classic DSA problem: Finding the Single Number in an array using JavaScript. 🔹 Problem Statement Given a non-empty array of integers, every element appears twice except for one. Find that single one. 📌 Example Input: [2, 2, 1] Output: 1 ✅ My Approach (Using Object / Hash Map) I used an object to count the frequency of each number. 💡 Idea Traverse the array and store counts in an object Loop through the object Return the number whose count is 1 🧠 Code var singleNumber = function(nums) { let obj = {} for (let i = 0; i < nums.length; i++) { let currentValue = nums[i] obj[currentValue] = obj[currentValue] ? obj[currentValue] + 1 : 1 } for (let item in obj) { if (obj[item] === 1) { return Number(item) } } }; console.log(singleNumber([2, 2, 1])); // 1 ⏱ Time & Space Complexity • Time: O(n) • Space: O(n) (extra object used) ✔ Easy to understand ✔ Beginner-friendly ✔ Works well for learning hash-based logic ⚡ Optimized Version (Using XOR – Interview Preferred) We can solve this problem without extra memory using the XOR operator. 💡 Why XOR? • a ^ a = 0 • a ^ 0 = a • Order doesn’t matter So all duplicate numbers cancel out, leaving the single number. 🚀 Optimized Code var singleNumber = function(nums) { let result = 0; for (let num of nums) { result ^= num; } return result; }; console.log(singleNumber([2, 2, 1])); // 1 ⏱ Time & Space Complexity • Time: O(n) • Space: O(1) ✅ 🔥 Best choice for interviews & production-level efficiency 🧠 Key Takeaways ✔ Hash maps are great for clarity ✔ XOR gives optimal performance ✔ Always think about space optimization ✔ Simple logic can beat complex code #JavaScript #DSA #ProblemSolving #BackendDeveloper #CodingInterview #LearningInPublic #100DaysOfCode 🚀

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories