Two SumProblem StatementGiven an array of integers `nums` and an integer `target`, return indices of the two numbers such that they add up to `target`.Approach 1. Use a Map to store the difference between the target and the current number. 2. If the current number is in the map, you've found the pair! Solution`function twoSum(nums, target) { const map = new Map(); for (let i = 0; i < nums.length; i++) { const complement = target - nums[i]; if (map.has(complement)) { return [map.get(complement), i];
Valid AnagramProblem StatementGiven two strings `s` and `t`, return `true` if `t` is an anagram of `s`.Approach 1. If lengths differ, return false. 2. Sort both strings and compare. 3. Or use a frequency counter (object). Solution`function isAnagram(s, t) { if (s.length !== t.length) return false; const sSorted = s.split('').sort().join(''); const tSorted = t.split('').sort().join(''); return sSorted === tSorted;
FizzBuzz (Interview version)Problem StatementWrite a program that outputs the string representation of numbers from 1 to n.Approach 1. Use a loop from 1 to n. 2. Check for multiples of 3, 5, and 15. Solution`function fizzBuzz(n) { const res = []; for (let i = 1; i <= n; i++) { if (i % 15 === 0) res.push("FizzBuzz"); else if (i % 3 === 0) res.push("Fizz"); else if (i % 5 === 0) res.push("Buzz"); else res.push(i.toString());
Reverse IntegerProblem StatementGiven a signed 32-bit integer `x`, return `x` with its digits reversed.Approach 1. Convert to string, reverse, and convert back to number. 2. Handle the negative sign. 3. Check for 32nd bit overflow. Solution`function reverse(x) { const reversed = parseInt(Math.abs(x).toString().split('').reverse().join('')) * Math.sign(x); if (reversed < Math.pow(-2, 31) || reversed > Math.pow(2, 31) - 1) return 0; return reversed;
First Unique CharacterProblem StatementGiven a string `s`, find the first non-repeating character in it and return its index.Approach 1. Build a frequency map of characters. 2. Loop through the string again and find the first character with a count of 1. Solution`function firstUniqChar(s) { const count = {
Best Time to Buy/Sell StockProblem StatementGiven an array `prices`, find the maximum profit you can achieve by buying one day and selling another.Approach 1. Maintain a `minPrice` seen so far. 2. Calculate potential profit at each step and track the maximum. Solution`function maxProfit(prices) { let minPrice = Infinity; let maxProfit = 0; for (let price of prices) { if (price < minPrice) minPrice = price; else if (price - minPrice > maxProfit) maxProfit = price - minPrice;
Linked List CycleProblem StatementDetermine if a linked list has a cycle in it.Approach 1. Use Floyd's Cycle-Finding Algorithm (Fast and Slow Pointers). 2. If they meet, there is a cycle. Solution`function hasCycle(head) { let slow = head, fast = head; while (fast && fast.next) { slow = slow.next; fast = fast.next.next; if (slow === fast) return true;
Merge Sorted ListsProblem StatementMerge two sorted linked lists and return it as a new sorted list.Approach 1. Use a dummy node to simplify head handling. 2. Compare values of both lists and attach the smaller one. Solution`function mergeTwoLists(l1, l2) { const dummy = { val: 0, next: null
Climbing StairsProblem StatementYou are climbing a staircase. It takes `n` steps to reach the top. Each time you can either climb 1 or 2 steps. In how many ways?Approach 1. This is the Fibonacci sequence. 2. Ways(n) = Ways(n-1) + Ways(n-2). Solution`function climbStairs(n) { if (n <= 2) return n; let first = 1, second = 2; for (let i = 3; i <= n; i++) { let third = first + second; first = second; second = third;
Valid ParenthesesProblem Statement`Given a string containing characters '(', ')', '{', 'Approach 1. Use a stack. 2. Push opening brackets. 3. On closing bracket, pop and check if it matches. Solution`function isValid(s) { const stack = []; const map = { ')': '(', '
Maximum SubarrayProblem StatementFind the contiguous subarray with the largest sum and return its sum (Kadane's Algorithm).Approach 1. Max sum at current position is `max(num, currentSum + num)`. 2. Keep track of the global maximum. Solution`function maxSubArray(nums) { let maxSoFar = nums[0]; let maxEndingHere = nums[0]; for (let i = 1; i < nums.length; i++) { maxEndingHere = Math.max(nums[i], maxEndingHere + nums[i]); maxSoFar = Math.max(maxSoFar, maxEndingHere);
Single NumberProblem StatementEvery element appears twice except for one. Find that single one.Approach 1. Concept: XOR a number with itself is 0 (`a ^ a = 0`). 2. XOR all numbers; the result is the single one. Solution`function singleNumber(nums) { return nums.reduce((acc, curr) => acc ^ curr, 0);
Move ZeroesProblem StatementMove all 0's to the end of the array while maintaining the relative order of the non-zero elements.Approach 1. Use a pointer `lastNonZeroIndex`. 2. Iterate and move non-zero elements forward. 3. Fill the rest with zeroes. Solution`function moveZeroes(nums) { let pos = 0; for (let i = 0; i < nums.length; i++) { if (nums[i] !== 0) { nums[pos++] = nums[i];
Fibonacci NumberProblem StatementCalculate the n-th Fibonacci number.Approach 1. Recursion with memoization or iterative approach. Solution`function fib(n) { if (n <= 1) return n; let a = 0, b = 1; for (let i = 2; i <= n; i++) { [a, b] = [b, a + b];
Missing NumberProblem StatementGiven an array containing `n` distinct numbers in the range `[0, n]`, find the missing one.Approach 1. Calculate expected sum of 0 to n: `n * (n + 1) / 2`. 2. Subtract actual sum of array elements. Solution`function missingNumber(nums) { const n = nums.length; const expectedSum = (n * (n + 1)) / 2; const actualSum = nums.reduce((a, b) => a + b, 0); return expectedSum - actualSum;
Intersection of Two ArraysProblem StatementGiven two integer arrays, return an array of their intersection.Approach 1. Use a Set to store elements of the first array for O(1) lookup. 2. Filter the second array. Solution`function intersect(nums1, nums2) { const set1 = new Set(nums1); return [...new Set(nums2.filter(n => set1.has(n)))];
Throttle ImplementationProblem StatementWrite a basic throttle function that ensures `fn` is called at most once every `delay` ms.Approach 1. Use a `wait` flag in a closure. 2. If not waiting, call `fn` and set `wait = true`. 3. Reset `wait = false` after the delay. Solution`function throttle(fn, delay) { let waiting = false; return function(...args) { if (!waiting) { fn(...args); waiting = true; setTimeout(() => waiting = false, delay);
Debounce ImplementationProblem StatementWrite a basic debounce function that delays `fn` execution until `delay` ms has passed since the last call.Approach 1. Use `setTimeout` and `clearTimeout`. 2. Clear existing timer on every call. Solution`function debounce(fn, delay) { let timer; return function(...args) { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay);
Flatten Nested ArrayProblem StatementRecursively flatten a deeply nested array of unknown depth.Approach 1. Use `reduce` and recursion. 2. If item is array, call flatten recursively. Else concat it. Solution`function deepFlatten(arr) { return arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(deepFlatten(val)) : acc.concat(val), []);
Sieve of EratosthenesProblem StatementReturn all primes up to `n`.Approach 1. Create a boolean array initialized to true. 2. Mark multiples of each prime as false. Solution`function countPrimes(n) { const isPrime = new Array(n).fill(true); isPrime[0] = isPrime[1] = false; for (let i = 2; i * i < n; i++) { if (isPrime[i]) { for (let j = i * i; j < n; j += i) { isPrime[j] = false;