📘 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 🚀
JavaScript Single Number Problem Solution with Hash Map and XOR
More Relevant Posts
-
🤔 Ever wondered why some JavaScript functions can be called before they’re defined? JavaScript treats function declarations and function expressions differently. 🧠 JavaScript interview question What’s the difference between function declarations and function expressions? ✅ Short answer • Both define functions • Only declarations are fully hoisted • Expressions are evaluated at runtime • Timing of availability is the key difference 🔍 A bit more detail Function declarations are hoisted, meaning the entire function is available before the code runs. Function expressions create a function as part of an expression and are only usable after that expression executes. Function expressions can also be named, which helps with debugging and recursion without polluting the outer scope. 💻 Example // function declaration greet(); function greet() { console.log("Hi"); } // function expression const sayHi = function () { console.log("Hello"); }; sayHi(); // named function expression const factorial = function fact(n) { return n <= 1 ? 1 : n * fact(n - 1); }; console.log(factorial(5)); // 120 ⚠️ Small but important • Only function declarations are hoisted as callable functions • Function expressions are not available before assignment • Named function expressions keep their name scoped to the function body 👍 Follow for daily JavaScript interview questions #javascript #webdevelopment #frontend #frontenddeveloper #coding #programming #js #interviewprep #learnjavascript
To view or add a comment, sign in
-
🤔 Ever wondered why arrow functions behave differently from normal functions in JavaScript? They look shorter, but they change the rules. 🧠 JavaScript interview question What are arrow functions and how are they different from normal functions? ✅ Short answer • Arrow functions are a shorter ES6 syntax • They do not have their own this • They are not constructors • They don’t have arguments, prototype, or new.target 🔍 A bit more detail 👉 Lexical this (the big one) Arrow functions capture this from where they are defined, not how they’re called. const obj = { count: 0, inc() { setTimeout(() => { this.count++; }, 100); } }; No .bind(this) needed. The arrow keeps the outer this. 👉 No own arguments Use rest parameters instead: const sum = (...nums) => nums.reduce((a, b) => a + b, 0); 👉 Not constructible new (() => {}) // ❌ TypeError Arrow functions have no prototype and can’t be used with new. 👉 Implicit returns const double = x => x * 2; Block body? You must return. ⚠️ When to avoid arrow functions • Object or prototype methods that rely on dynamic this • Constructors or generator functions • Event handlers that expect this to be the DOM element const obj = { total: 0, add() { this.total++; // ✅ correct } }; 🚀 When arrow functions shine • Callbacks (setTimeout, promises) • Array methods (map, filter, reduce) • Short utility functions • Preserving outer this in classes 🧩 Mental checklist • Need your own this? → normal function • Need outer this? → arrow function • Need new, arguments, or prototype? → normal function 💡 Arrow functions aren’t just shorter syntax, they change semantics. #javascript #frontend #webdevelopment #react #interviewprep #programming
To view or add a comment, sign in
-
JavaScript Fundamentals – How Type Conversion Works Internally ⚙️ JavaScript often surprises people with results like: "5" + 1 → 51 "5" - 1 → 4 This happens because of Type Conversion (also called Type Coercion). JavaScript automatically converts values from one type to another when needed. There are two types of conversion: 1️⃣ Implicit Type Conversion (Automatic) JS converts types on its own. Examples: • + operator prefers strings → "5" + 1 becomes "51" • -, *, / prefer numbers → "5" - 1 becomes 4 2️⃣ Explicit Type Conversion (Manual) When we intentionally convert types. Examples: • Number("10") → 10 • String(10) → "10" • Boolean(0) → false Internally, JS follows rules like: • Strings dominate with + • Math operators convert values to numbers • Falsy values (0, "", null, undefined, NaN, false) convert to false Why does this matter? Understanding type conversion helps you: • Avoid unexpected bugs • Write predictable logic • Read other people’s JS code confidently • Perform better in interviews Learning JS fundamentals one concept at a time 🚀 #JavaScript #FrontendDevelopment #WebDevelopment #LearningInPublic
To view or add a comment, sign in
-
🤔 Ever confused by the three dots (...) in JavaScript? They look the same, but default parameters, rest, and spread solve very different problems. 🧠 JavaScript interview question What’s the difference between default parameters, rest parameters, and the spread operator? ✅ Short answer • Default parameters give fallback values • Rest collects multiple values into one • Spread expands one value into many Same syntax, different intent. 🔍 Default parameters — “Give me a fallback” Used when a function argument is missing or undefined. Instead of manual checks, JavaScript handles it for you. function greet(name = "there") { return "Hi " + name; } greet(); // "Hi there" greet("Sam"); // "Hi Sam" 🔍 Rest parameters — “Collect the leftovers” Used in function definitions to gather extra arguments into a real array. function sum(...nums) { return nums.reduce((a, b) => a + b, 0); } sum(1, 2, 3, 4); // 10 🔍 Spread operator — “Unpack things” Used in function calls, arrays, and objects to expand values. const a = [1, 2]; const b = [3, 4]; const combined = [...a, ...b]; // [1,2,3,4] With objects (shallow copy): const user = { name: "A", meta: { v: 1 } }; const copy = { ...user, role: "admin" }; ⚠️ Common misconceptions • Rest ≠ arguments (rest is a real array) • Spread does not deep clone objects • Default params apply only when value is undefined 🧩 Easy way to remember Rest gathers. Spread scatters. #javascript #frontend #webdevelopment #interviewprep #react #codingtips
To view or add a comment, sign in
-
𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗧𝗶𝗽: 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗗𝗲𝗰𝗹𝗮𝗿𝗮𝘁𝗶𝗼𝗻 𝘃𝘀 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻 Both are common ways to write functions in JavaScript, but they behave differently under the hood 👇 // 𝘍𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘋𝘦𝘤𝘭𝘢𝘳𝘢𝘵𝘪𝘰𝘯 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘨𝘳𝘦𝘦𝘵() { 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨("𝘏𝘦𝘭𝘭𝘰"); } // 𝘍𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘌𝘹𝘱𝘳𝘦𝘴𝘴𝘪𝘰𝘯 𝘤𝘰𝘯𝘴𝘵 𝘨𝘳𝘦𝘦𝘵 = 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 () { 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨("𝘏𝘦𝘭𝘭𝘰"); }; 𝗞𝗲𝘆 𝗗𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲𝘀 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 • Function declarations are available before they appear in the code • Function expressions are not 𝘨𝘳𝘦𝘦𝘵(); // 𝘸𝘰𝘳𝘬𝘴 𝘰𝘯𝘭𝘺 𝘸𝘪𝘵𝘩 𝘥𝘦𝘤𝘭𝘢𝘳𝘢𝘵𝘪𝘰𝘯 𝗦𝗰𝗼𝗽𝗲 & 𝗙𝗹𝗲𝘅𝗶𝗯𝗶𝗹𝗶𝘁𝘆 • Declarations are great for defining reusable, top-level logic • Expressions work well for callbacks, closures, and conditional behaviour 𝘤𝘰𝘯𝘴𝘵 𝘩𝘢𝘯𝘥𝘭𝘦𝘳 = 𝘪𝘴𝘔𝘰𝘣𝘪𝘭𝘦 ? 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘮𝘰𝘣𝘪𝘭𝘦𝘏𝘢𝘯𝘥𝘭𝘦𝘳() {} : 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘥𝘦𝘴𝘬𝘵𝘰𝘱𝘏𝘢𝘯𝘥𝘭𝘦𝘳() {}; 𝗡𝗮𝗺𝗲𝗱 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻𝘀 (𝗹𝗲𝘀𝘀 𝗸𝗻𝗼𝘄𝗻) 𝘤𝘰𝘯𝘴𝘵 𝘨𝘳𝘦𝘦𝘵 = 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘴𝘢𝘺𝘏𝘦𝘭𝘭𝘰() { 𝘴𝘢𝘺𝘏𝘦𝘭𝘭𝘰(); // 𝘢𝘤𝘤𝘦𝘴𝘴𝘪𝘣𝘭𝘦 𝘩𝘦𝘳𝘦 }; 𝘴𝘢𝘺𝘏𝘦𝘭𝘭𝘰(); // 𝘯𝘰𝘵 𝘢𝘤𝘤𝘦𝘴𝘴𝘪𝘣𝘭𝘦 𝘩𝘦𝘳𝘦 👉 In named function expressions, the function name exists 𝗼𝗻𝗹𝘆 𝗶𝗻𝘀𝗶𝗱𝗲 𝘁𝗵𝗲 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗶𝘁𝘀𝗲𝗹𝗳. This keeps the outer scope clean while still allowing recursion and better debugging. 𝗪𝗵𝗲𝗻 𝘁𝗼 𝘂𝘀𝗲 𝘄𝗵𝗮𝘁? Function Declarations → shared utilities, clearer structure Function Expressions → dynamic logic, event handlers Arrow Functions → concise syntax for simple callbacks 📌 Small details like these make your JavaScript more predictable and maintainable. If this helped, feel free to share or add your thoughts 👇 #JavaScript #WebDevelopment #Frontend #ProgrammingTips #Learning
To view or add a comment, sign in
-
-
🚀 JavaScript Module 1: Strong Foundations Matter. Every great developer starts with strong fundamentals. Before jumping into frameworks like #Angular, #React, or #Node.js, it’s critical to master #JavaScript basics the right way. In this carousel, I’ve covered Module 1: JavaScript Basics, focusing on: ✅ What #JavaScript really is ✅ #JS vs #HTML vs #CSS (interview favorite) ✅ How #JavaScript works in the browser ✅ var, let, const explained clearly ✅ Data Types & Operators ✅ Best practices used by professionals This module is designed for: 🎓 Students starting their coding journey 👨💻 Professionals revising fundamentals 🎯 Developers preparing for interviews 👉 Save this #post for revision 👉 Share with someone learning #JavaScript 👉 Comment “#JS” if you want full course details 👉 Follow me for complete JavaScript roadmap modules #JavaScript #LearnJavaScript #WebDevelopment #FrontendDeveloper #ProgrammingBasics #JavaScriptInterview #Coding #DeveloperRoadmap #CareerInTech #SoftwareDeveloper Satendra Rajput Aaqib Khan Akarsh Goel Ankit Kumar SahiL J. Rishi Singh Rishika Singhi Siddharth Gupta Gagan Jaiswal Vishal Garg Vishal Tiwari Vishal Chaudhary
To view or add a comment, sign in
-
One of the most common bugs in JavaScript and React comes from copying objects the wrong way 😅 Shallow Copy vs Deep Copy In JavaScript, when you copy an object using the spread operator (...), you are only creating a shallow copy. Example: ``` const user = { name: “Ali”, skills: [“JS”, “React”] }; const copy = { …user }; copy.skills.push(“Node”); console.log(user.skills); // [“JS”, “React”, “React”, “Node”] ``` Why did the original object change? Because: • name was copied • but skills is still pointing to the same array in memory Both user.skills and copy.skills reference the same place. To create a real independent copy, use: const deepCopy = structuredClone(user); Now changing deepCopy will not affect user. 📌 In React, this mistake can cause: • state bugs • missing re-renders • very confusing UI issues Understanding how memory and references work is a game changer. #JavaScript #React #Frontend #WebDevelopment #Programming
To view or add a comment, sign in
-
🚀 JavaScript Array Methods – slice vs splice (𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗙𝘂𝗻𝗱𝗮𝗺𝗲𝗻𝘁𝗮𝗹𝘀) Today I revised some core JavaScript array operations and clarified a concept that often confuses beginners (and sometimes even experienced devs). 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆𝘀 👇 ✅ 𝘀𝗹𝗶𝗰𝗲() • Returns a new array • Does NOT modify the original array • End index is excluded ✅ 𝘀𝗽𝗹𝗶𝗰𝗲() • Modifies the original array • Returns the deleted elements • Used for remove / insert operations 🧠 𝗘𝗮𝘀𝘆 𝘄𝗮𝘆 𝘁𝗼 𝗿𝗲𝗺𝗲𝗺𝗯𝗲𝗿 • slice → ✂️ copy • splice → 🔪 cut Strengthening these basics is super important for: • JavaScript interviews • DSA preparation • Writing bug-free code Learning step by step. Consistency over speed. 💪 #JavaScript #FrontendDevelopment #DSA #WebDevelopment #LearningInPublic #CodingInterview #ReactJS
To view or add a comment, sign in
-
-
🚀 5 Tricky JavaScript Output Questions (Closures & Scope) Let’s test your JS fundamentals 👇 Try to guess the output before checking answers. 1️⃣ for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } 2️⃣ let a = 10; (function () { console.log(a); let a = 20; })(); 3️⃣ function foo() { console.log(x); var x = 10; } foo(); 4️⃣ const obj = { a: 10, getA() { return this.a; } }; const fn = obj.getA; console.log(fn()); 5️⃣ console.log(typeof typeof 1); Answers below 👇 1️⃣ 3 3 3 (var is function-scoped, same reference) 2️⃣ ReferenceError (Temporal Dead Zone for `let`) 3️⃣ undefined (var hoisting without initialization) 4️⃣ undefined (`this` is lost when function is detached) 5️⃣ "string" (typeof 1 → "number", typeof "number" → "string") If you can explain *why*, you’re interview-ready 💯 #javascript #frontend #interviewprep #webdevelopment
To view or add a comment, sign in
-
⏱️ JavaScript Timers – Understanding setTimeout Like a Pro setTimeout is one of the most commonly used async features in JavaScript – but many developers misunderstand how it really works. It does NOT execute exactly after the given time. It executes after the minimum delay + when the call stack is free. 🧠 Important Facts About setTimeout It is handled by the browser / Node timer API Callback goes to the Macrotask Queue Execution depends on the Event Loop 0 ms delay does NOT mean instant execution 🚀 Key Takeaways setTimeout is asynchronous Delay is the minimum wait time, not guaranteed time Even setTimeout(fn, 0) waits for: current code to finish event loop to pick it up 💡 Interview Insight If someone asks: “Why doesn’t setTimeout 0 run immediately?” Answer: 👉 Because JavaScript must finish synchronous code first, and timers run later through the event loop. If this clarified your understanding of timers, drop a 👍 #JavaScript #setTimeout #WebDevelopment #Frontend #Coding #InterviewPrep
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development