JavaScript Algorithms Interview Cheatsheet

A quick reference guide covering useful language features and common algorithms used during JavaScript technical interviews.

JavaScript Algorithms Interview Cheatsheet
Photo by Jeroen den Otter / Unsplash

This quick reference guide serves as an overview of JavaScript language features and common algorithms. I wouldn't recommend referencing this during an interview, but it may be useful as a quick review or while working on leetcodes.

Core Data Structures & Methods

Arrays

// Creation & basic ops
const arr = [1, 2, 3];
arr.push(4);           // Add to end
arr.pop();             // Remove from end
arr.unshift(0);        // Add to start
arr.shift();           // Remove from start
arr.slice(1, 3);       // Copy subarray [start, end)
arr.splice(1, 2, 'x'); // Remove/replace elements

// Key methods
arr.indexOf(val);      // Find index (-1 if not found)
arr.includes(val);     // Boolean check
arr.join(',');         // Convert to string
arr.reverse();         // Reverse in-place
arr.sort((a,b) => a-b); // Sort (custom comparator)

// Functional methods
arr.map(x => x * 2);
arr.filter(x => x > 0);
arr.reduce((acc, x) => acc + x, 0);
arr.find(x => x > 5);
arr.every(x => x > 0);
arr.some(x => x > 0);

Strings

const str = "hello";
str.length;            // 5
str[0] or str.charAt(0); // 'h'
str.slice(1, 4);       // "ell"
str.substring(1, 4);   // "ell" 
str.split('');         // ['h','e','l','l','o']
str.toLowerCase();     // "hello"
str.toUpperCase();     // "HELLO"
str.trim();            // Remove whitespace
str.indexOf('l');      // 2
str.includes('ll');    // true

// Convert between string/array
str.split('') → Array
arr.join('') → String

Objects & Maps

// Object
const obj = { a: 1, b: 2 };
Object.keys(obj);      // ['a', 'b']
Object.values(obj);    // [1, 2]
Object.entries(obj);   // [['a',1], ['b',2]]

// Map (better for frequent additions/deletions)
const map = new Map();
map.set('key', 'value');
map.get('key');        // 'value'
map.has('key');        // true
map.delete('key');     // true/false
map.size;              // number of entries
map.clear();           // remove all

// Iterate
for (let [key, val] of map) { ... }

Sets

const set = new Set([1, 2, 2, 3]); // {1, 2, 3}
set.add(4);
set.has(2);            // true
set.delete(2);         // true/false
set.size;              // number of elements
set.clear();           // remove all

// Convert
Array.from(set);       // Set → Array
new Set(array);        // Array → Set

Essential Algorithms

Two Pointers

// Opposite direction
function twoSum(arr, target) {
    let left = 0, right = arr.length - 1;
    while (left < right) {
        const sum = arr[left] + arr[right];
        if (sum === target) return [left, right];
        else if (sum < target) left++;
        else right--;
    }
    return [-1, -1];
}

// Same direction (sliding window)
function maxSubarraySum(arr, k) {
    let sum = 0, maxSum = 0;
    // Initial window
    for (let i = 0; i < k; i++) sum += arr[i];
    maxSum = sum;
    
    // Slide window
    for (let i = k; i < arr.length; i++) {
        sum = sum - arr[i - k] + arr[i];
        maxSum = Math.max(maxSum, sum);
    }
    return maxSum;
}
function binarySearch(arr, target) {
    let left = 0, right = arr.length - 1;
    
    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        if (arr[mid] === target) return mid;
        else if (arr[mid] < target) left = mid + 1;
        else right = mid - 1;
    }
    return -1;
}

// Find insertion point
function searchInsert(arr, target) {
    let left = 0, right = arr.length - 1;
    
    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        if (arr[mid] < target) left = mid + 1;
        else right = mid - 1;
    }
    return left;
}

Sorting Algorithms

// Quick Sort
function quickSort(arr) {
    if (arr.length <= 1) return arr;
    
    const pivot = arr[Math.floor(arr.length / 2)];
    const left = arr.filter(x => x < pivot);
    const middle = arr.filter(x => x === pivot);
    const right = arr.filter(x => x > pivot);
    
    return [...quickSort(left), ...middle, ...quickSort(right)];
}

// Merge Sort
function mergeSort(arr) {
    if (arr.length <= 1) return arr;
    
    const mid = Math.floor(arr.length / 2);
    const left = mergeSort(arr.slice(0, mid));
    const right = mergeSort(arr.slice(mid));
    
    return merge(left, right);
}

function merge(left, right) {
    const result = [];
    let i = 0, j = 0;
    
    while (i < left.length && j < right.length) {
        if (left[i] <= right[j]) {
            result.push(left[i++]);
        } else {
            result.push(right[j++]);
        }
    }
    
    return result.concat(left.slice(i)).concat(right.slice(j));
}

Tree Algorithms

Binary Tree Structure

class TreeNode {
    constructor(val, left = null, right = null) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

Tree Traversals

// DFS - Recursive
function inorder(root) {
    const result = [];
    function dfs(node) {
        if (!node) return;
        dfs(node.left);
        result.push(node.val);
        dfs(node.right);
    }
    dfs(root);
    return result;
}

// DFS - Iterative
function inorderIterative(root) {
    const result = [], stack = [];
    let curr = root;
    
    while (curr || stack.length) {
        while (curr) {
            stack.push(curr);
            curr = curr.left;
        }
        curr = stack.pop();
        result.push(curr.val);
        curr = curr.right;
    }
    return result;
}

// BFS - Level Order
function levelOrder(root) {
    if (!root) return [];
    
    const result = [], queue = [root];
    
    while (queue.length) {
        const size = queue.length;
        const level = [];
        
        for (let i = 0; i < size; i++) {
            const node = queue.shift();
            level.push(node.val);
            
            if (node.left) queue.push(node.left);
            if (node.right) queue.push(node.right);
        }
        result.push(level);
    }
    return result;
}

Graph Algorithms

Graph Representations

// Adjacency List
const graph = {
    'A': ['B', 'C'],
    'B': ['A', 'D'],
    'C': ['A', 'D'],
    'D': ['B', 'C']
};

// Edge List
const edges = [['A', 'B'], ['B', 'C'], ['C', 'D']];

DFS & BFS

// DFS - Recursive
function dfs(graph, start, visited = new Set()) {
    visited.add(start);
    console.log(start);
    
    for (let neighbor of graph[start] || []) {
        if (!visited.has(neighbor)) {
            dfs(graph, neighbor, visited);
        }
    }
}

// BFS
function bfs(graph, start) {
    const visited = new Set();
    const queue = [start];
    visited.add(start);
    
    while (queue.length) {
        const node = queue.shift();
        console.log(node);
        
        for (let neighbor of graph[node] || []) {
            if (!visited.has(neighbor)) {
                visited.add(neighbor);
                queue.push(neighbor);
            }
        }
    }
}

Dynamic Programming Patterns

Basic Template

// Memoization (Top-down)
function fibonacci(n, memo = {}) {
    if (n in memo) return memo[n];
    if (n <= 1) return n;
    
    memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo);
    return memo[n];
}

// Tabulation (Bottom-up)
function fibonacciDP(n) {
    if (n <= 1) return n;
    
    const dp = [0, 1];
    for (let i = 2; i <= n; i++) {
        dp[i] = dp[i - 1] + dp[i - 2];
    }
    return dp[n];
}

Common DP Problems

// Coin Change
function coinChange(coins, amount) {
    const dp = Array(amount + 1).fill(Infinity);
    dp[0] = 0;
    
    for (let i = 1; i <= amount; i++) {
        for (let coin of coins) {
            if (i >= coin) {
                dp[i] = Math.min(dp[i], dp[i - coin] + 1);
            }
        }
    }
    return dp[amount] === Infinity ? -1 : dp[amount];
}

// Longest Increasing Subsequence
function lengthOfLIS(nums) {
    const dp = Array(nums.length).fill(1);
    
    for (let i = 1; i < nums.length; i++) {
        for (let j = 0; j < i; j++) {
            if (nums[j] < nums[i]) {
                dp[i] = Math.max(dp[i], dp[j] + 1);
            }
        }
    }
    return Math.max(...dp);
}

Useful Patterns & Tricks

Frequency Counter

function isAnagram(s, t) {
    if (s.length !== t.length) return false;
    
    const count = {};
    for (let char of s) count[char] = (count[char] || 0) + 1;
    for (let char of t) {
        if (!count[char]) return false;
        count[char]--;
    }
    return true;
}

Sliding Window Maximum

function maxSlidingWindow(nums, k) {
    const result = [];
    const deque = []; // Store indices
    
    for (let i = 0; i < nums.length; i++) {
        // Remove elements outside window
        while (deque.length && deque[0] < i - k + 1) {
            deque.shift();
        }
        
        // Remove smaller elements
        while (deque.length && nums[deque[deque.length - 1]] < nums[i]) {
            deque.pop();
        }
        
        deque.push(i);
        
        if (i >= k - 1) {
            result.push(nums[deque[0]]);
        }
    }
    return result;
}

Fast/Slow Pointers (Cycle Detection)

function hasCycle(head) {
    let slow = head, fast = head;
    
    while (fast && fast.next) {
        slow = slow.next;
        fast = fast.next.next;
        if (slow === fast) return true;
    }
    return false;
}

Common JavaScript Gotchas

Useful Built-ins

Math.max(...arr);           // Max value in array
Math.min(...arr);           // Min value in array
Math.floor(x);              // Round down
Math.ceil(x);               // Round up
Math.abs(x);                // Absolute value
Number.MAX_SAFE_INTEGER;    // 9007199254740991
Number.MIN_SAFE_INTEGER;    // -9007199254740991

// Create arrays
Array(n).fill(0);           // [0, 0, ..., 0]
Array.from({length: n}, (_, i) => i); // [0, 1, 2, ..., n-1]

// Infinity
Infinity > any_number;      // true
-Infinity < any_number;     // true

Common Patterns

// Swap variables
[a, b] = [b, a];

// Clone array/object
const arrCopy = [...arr];
const objCopy = {...obj};

// Check if number is integer
Number.isInteger(x);

// Convert string to number
parseInt(str);              // Parse integer
parseFloat(str);            // Parse float
+str;                       // Quick conversion

// Default values
const value = input || defaultValue;
const value = input ?? defaultValue; // Only null/undefined

Time Complexities to Remember

  • Array access/modify: O(1)
  • Array search: O(n)
  • Array sort: O(n log n)
  • Binary search: O(log n)
  • Hash map operations: O(1) average
  • BFS/DFS: O(V + E)
  • Dynamic Programming: Often O(n²) or O(n)

Interview Tips

  1. Always clarify the problem - Ask about edge cases, constraints
  2. Start with brute force - Get something working first
  3. Optimize step by step - Don't jump to the optimal solution
  4. Test with examples - Walk through your code with sample inputs
  5. Consider edge cases - Empty arrays, single elements, null values
  6. Communicate your thinking - Explain your approach out loud