DATA STRUCTURES - rs-hash/GETTHATJOB GitHub Wiki

📚 1. Data Structures & Algorithms — Core Concepts & Fundamentals

A comprehensive quick-reference guide to understand the core idea, why it exists, and how it works — for every major Data Structure, Algorithm, and Pattern.


🧱 Core Data Structures
# Data Structure Core Concept Real-World Analogy Time Complexity (Avg) Key Notes
1 Stack (LIFO) Linear structure that supports push/pop from one end only. Stack of plates — last in, first out. Push/Pop: O(1) Used for recursion, parsing, backtracking, undo functionality.
2 Queue (FIFO) Elements inserted at one end, removed from the other. Waiting line — first come, first served. Enqueue/Dequeue: O(1) Used in BFS, scheduling, and streaming.
3 Deque (Double-Ended Queue) Queue that allows insertion/removal from both ends. Train with open cars at both ends. Insert/Delete: O(1) Used in sliding window and caching.
4 Linked List Sequence of nodes where each node points to the next. Chain of connected links. Insert/Delete: O(1) (given node) Used in queues, stacks, LRU cache.
5 Hash Map / Hash Set Stores key-value pairs for constant-time lookup. Dictionary — word to definition. Insert/Lookup/Delete: O(1) Used for counting, lookup tables, caching.
6 Heap / Priority Queue Complete binary tree maintaining order (min/max). Priority line — highest priority first. Insert/Delete: O(log n) Used for scheduling, top K problems, Dijkstra’s.
7 Tree Hierarchical data — nodes with children. Family tree. Search/Insert/Delete: O(log n) (BST) Used for hierarchy, recursion, and ordered data.
8 Graph Set of nodes and edges showing relationships. Road map — cities connected by roads. Depends on representation Used in networks, pathfinding, dependencies.
9 Trie (Prefix Tree) Tree for string prefixes. Contact list autocomplete. Insert/Search: O(L) (word length) Used for autocomplete, spell check, prefix search.
10 Union-Find (Disjoint Set) Tracks connectivity among elements. Grouping people by connection. Union/Find: O(α(n)) Used in Kruskal’s MST, connected components.
11 Array Fixed-size contiguous memory block. Row of boxes. Access: O(1) Great for indexing, static data.
12 Matrix / Grid 2D array — spatial structure. Chessboard. Access: O(1) Used in pathfinding, DP, image problems.
13 String Immutable sequence of characters. Word/sentence. Access: O(1) Used in pattern search, parsing, hashing.


⚙️ Core Algorithmic Techniques
# Algorithm / Concept Core Idea Use Case Typical Time Example
1 DFS (Depth First Search) Go deep recursively or with a stack. Explore all paths, trees, graphs. O(V+E) Graph traversal, island counting.
2 BFS (Breadth First Search) Visit nodes level by level with a queue. Shortest path, levels in tree. O(V+E) Shortest path in unweighted graph.
3 Binary Search Repeatedly divide sorted data in half. Search or optimize monotonic function. O(log n) Search in Rotated Array, Peak Element.
4 Two Pointers Two indices move to compare or find condition. Sorted arrays, subarray problems. O(n) Container with Most Water, Two Sum II.
5 Sliding Window Expand & shrink window dynamically. Substring/subarray optimization. O(n) Longest Substring Without Repeating.
6 Recursion Function calls itself to break problem down. Trees, divide-and-conquer, backtracking. Depends on recursion depth. Tree traversals, Fibonacci.
7 Dynamic Programming (DP) Break problem into overlapping subproblems. Optimal solutions, counting, sequences. O(n)–O(n²) Climbing Stairs, Longest Common Subsequence.
8 Greedy Always choose locally optimal step. Scheduling, interval, coin change. O(n log n) Activity Selection, Huffman Encoding.
9 Backtracking Try all paths, backtrack on failure. Permutations, subsets, N-Queens. Exponential Sudoku Solver, Word Search.
10 Divide & Conquer Split, solve independently, combine results. Sorting, searching. O(n log n) Merge Sort, Quick Sort.
11 Union-Find (DSU) Group elements by connectivity. Connected components, MST. Near O(1) Kruskal’s Algorithm, Islands.
12 Topological Sort Linear ordering of DAG vertices. Task scheduling, dependencies. O(V+E) Course Schedule, Build Order.


🧩 Pattern Concepts — How to Identify and Apply
Pattern Core Logic When to Use Typical Implementation Example Problem
Monotonic Stack Stack keeps elements in sorted order (increasing/decreasing). Find next/previous greater/smaller element. Compare while popping until order breaks. Next Greater Element, Trapping Rain Water
Sliding Window Move two pointers to form dynamic subarray/substring. Find longest/shortest subarray meeting condition. Expand → check → shrink. Longest Substring Without Repeating
Two Pointers Compare elements at different positions. Pair sums, palindrome checks. Move pointers inward/outward. 3Sum, Move Zeroes
Fast & Slow Pointers One pointer moves faster to detect cycles or midpoints. Linked lists, circular arrays. Move slow +1, fast +2. Detect Cycle, Find Middle of Linked List
Prefix Sum Precompute running totals for range queries. Range sum, subarray sums. Prefix[i] = Prefix[i-1] + A[i]. Subarray Sum Equals K
Binary Search on Answer Search in range of answers instead of array. Optimize a threshold or minimum limit. While (low < high) mid = (low + high)/2. Minimize Max Distance, Koko Eating Bananas
Backtracking Explore all possibilities recursively. Combinations, permutations, partitions. Add → recurse → remove (undo). Subsets, N-Queens
Dynamic Programming Store previous results to avoid recomputation. Count, maximize/minimize, sequence problems. Tabulation (bottom-up) or memoization (top-down). Coin Change, LCS
Greedy Make best local choice at each step. Interval scheduling, coin change, Huffman. Sort + iterate, pick locally best option. Jump Game, Activity Selection
Divide & Conquer Split into smaller independent parts. Sorting, searching, geometry. Recursively solve halves, combine. Merge Sort, Binary Search
Graph Traversal Explore connections systematically. Paths, networks, dependencies. DFS (stack/recursion) or BFS (queue). Shortest Path, Number of Islands
Topological Sort Order tasks with prerequisites. DAGs (directed acyclic graphs). BFS (Kahn’s) or DFS ordering. Course Schedule
Union-Find Pattern Detect connected groups. Connectivity, cycle detection. Union + Find with path compression. Redundant Connection, Kruskal MST


⚡ Time & Space Complexity Cheat Sheet
Data Structure / Algo Insert Delete Access / Search Space
Array O(n) O(n) O(1) / O(n) O(n)
Linked List O(1) O(1) O(n) O(n)
Stack / Queue O(1) O(1) O(n) O(n)
Hash Map / Set O(1) O(1) O(1) O(n)
Binary Search Tree O(log n) O(log n) O(log n) O(n)
Heap O(log n) O(log n) O(1) O(n)
Trie O(L) O(L) O(L) O(total chars)
Graph (Adj List) O(V+E) O(V+E)
Union-Find O(α(n)) O(α(n)) O(α(n)) O(n)
Binary Search O(log n) O(1)


🧭 Quick Identification Cheat Sheet
Clue Think Of Core Data Structure / Pattern
“Balanced”, “Valid”, “Matching” Stack Matching/Parsing Problems
“Shortest Path”, “Steps”, “Levels” BFS Queue
“Deep Explore”, “Traverse All” DFS Stack/Recursion
“All Combinations / Permutations” Backtracking Recursive Tree Search
“Optimal / Maximum / Minimum” Dynamic Programming / Greedy DP Table or Sorting
“Connected Components / Islands” DFS / Union-Find Graph Traversal
“Dependencies / Ordering” Topological Sort DAG
“Range Query” Prefix Sum / Segment Tree Precomputation
“Sorted / Threshold Condition” Binary Search Divide Range
“Kth Largest / Top K” Heap Priority Queue


✅ Tip

When solving a new problem:

  1. Rephrase it — “What is being asked? Counting, searching, optimizing, or ordering?”
  2. Spot the structure — “Sequence? Tree? Graph? String?”
  3. Match the pattern — choose from stack, queue, sliding window, DP, backtracking, etc.

With practice, pattern recognition becomes automatic 🔁


2. 🧠 Data Structures & Algorithms — Core Patterns & Identification Guide

A practical reference for engineers to quickly recognize which data structure or algorithmic pattern fits a problem.


🧱 Data Structure Patterns
# Data Structure When to Use / How to Identify Common Problems / Examples
1 Stack (LIFO) Problem involves reversing, nested structures, matching pairs, or undo/redo logic. Valid Parentheses, Min Stack, Decode String, Next Greater Element, Simplify Path
2 Queue (FIFO) Problem involves processing in order or first come, first served behavior. Implement Stack using Queues, Rotten Oranges, Sliding Window, BFS
3 Deque (Double-ended Queue) Need to add/remove from both ends efficiently (often in sliding window problems). Sliding Window Maximum, Moving Average
4 Linked List Dynamic data with frequent insertions/deletions, or when traversal/sequence manipulation is needed. Reverse Linked List, Detect Cycle, Merge Two Sorted Lists, Reorder List
5 Hash Map / Hash Set Fast lookup, counting, or duplicate detection. Two Sum, Group Anagrams, LRU Cache, Longest Substring Without Repeating Characters
6 Heap / Priority Queue Need to find min/max quickly or process by priority/order. Kth Largest Element, Merge K Sorted Lists, Top K Frequent Elements, Median Finder
7 Tree (Binary Tree, BST) Problems about hierarchy, recursion, or relationships (parent-child). Traversals (Inorder/Preorder/Postorder), Lowest Common Ancestor, Validate BST
8 Graph Problems involving connections, paths, or networks. DFS, BFS, Dijkstra’s Algorithm, Topological Sort, Detect Cycle
9 Trie (Prefix Tree) Word/prefix search, autocomplete, or dictionary-like problems. Implement Trie, Word Search II, Replace Words
10 Union-Find (Disjoint Set) Need to track connected components or merge sets efficiently. Number of Islands, Kruskal’s MST, Redundant Connection
11 Array / Two Pointers Linear data, often sorted or requiring in-place transformation. Two Sum II, Move Zeroes, Container With Most Water, Remove Duplicates
12 Matrix / Grid 2D traversal, spatial movement, or game board problems. Number of Islands, Game of Life, Spiral Matrix
13 String Pattern matching, substring search, or character frequency analysis. Longest Palindrome, Anagrams, KMP Algorithm, Sliding Window Substring
14 Dynamic Programming (DP Table / Memoization) Problem has overlapping subproblems and optimal substructure. Fibonacci, Climbing Stairs, Coin Change, Longest Common Subsequence
15 Greedy Algorithms Choose the best local option at each step — often optimization or scheduling problems. Interval Scheduling, Jump Game, Huffman Encoding
16 Backtracking / Recursion Problem requires exploring all possibilities or building combinations/permutations. Subsets, Permutations, N-Queens, Sudoku Solver
17 Divide and Conquer Problem can be split into independent subproblems, then combined. Merge Sort, Quick Sort, Binary Search
18 Binary Search (on array or answer) Input is sorted, or you can phrase question as “find smallest/largest X satisfying condition”. Search in Rotated Array, Find Peak Element, Minimum in Rotated Sorted Array
19 Sliding Window Find subarray/substring that satisfies a condition (sum, unique chars, etc.). Longest Substring Without Repeating, Minimum Window Substring
20 Topological Sort Ordering tasks with dependencies (DAGs). Course Schedule, Build Order, Dependency Resolution

⚙️ Algorithmic Pattern Quick Reference
# Algorithm Type When to Think of It Core Logic / Idea
1 DFS (Depth First Search) Explore all paths deeply (trees, graphs, recursion). Use stack or recursion; go deep before wide.
2 BFS (Breadth First Search) Shortest path or minimum steps. Use queue; level-by-level traversal.
3 Binary Search Sorted data or monotonic condition. Divide range in half each step.
4 Two Pointers Compare/move through sorted arrays or strings. One pointer moves ahead, one lags or scans.
5 Sliding Window Optimize contiguous subarray/substring problems. Expand & shrink window to meet condition.
6 Recursion Nested structure (tree, DFS). Base case + smaller subproblem call.
7 Dynamic Programming Optimal substructure + overlapping subproblems. Cache previous results to avoid recomputation.
8 Greedy Always pick best immediate option. Local choices lead to global optimum.
9 Backtracking Try all possible combinations with pruning. Recursive search + undo step (pop).
10 Union-Find / DSU Detect connectivity, grouping, or cycles. Union sets + find representative parent.


🧩 Problem Recognition by Keyword Clues
Keyword or Phrase Likely Pattern
“balanced”, “matching”, “valid” Stack
“undo”, “redo”, “back” Stack / History
“first come, first served” Queue
“shortest path”, “levels” BFS
“deep”, “recursive”, “traverse” DFS / Recursion
“next greater/smaller” Monotonic Stack
“subarray”, “substring”, “window” Sliding Window
“sorted”, “min/max”, “binary condition” Binary Search
“connected components”, “islands” DFS / Union-Find
“prefix”, “dictionary”, “autocomplete” Trie
“dependencies”, “order” Topological Sort
“maximize/minimize” Greedy / DP
“ways”, “count”, “longest/shortest” Dynamic Programming
“combinations”, “permutations”, “all possibilities” Backtracking
“merge”, “split”, “half” Divide and Conquer


🧩 Example Mapping: Common Problems → Core Pattern
Problem Pattern Key DS/Algo
Valid Parentheses Matching Stack
Two Sum Lookup Hash Map
Reverse Linked List Traversal Linked List
Level Order Traversal Layered BFS + Queue
Binary Tree Inorder Recursive / Iterative Stack or Recursion
Course Schedule Dependency Topological Sort
Longest Substring Without Repeating Window Sliding Window + Hash Map
Kth Largest Element Priority Heap
Merge Intervals Sorting + Merge Greedy
Coin Change Optimal Dynamic Programming
Subsets / Permutations Explore All Backtracking
Number of Islands Connected Components DFS / BFS
Trapping Rain Water Boundary Logic Monotonic Stack
Search in Rotated Array Divide Range Binary Search
Word Search II Prefix Search Trie + Backtracking


🧭 Quick Rule of Thumb
Problem Type Think Of
Nested / Balanced Stack
Sequential / Order-Based Queue
Relationships / Hierarchy Tree
Connections / Networks Graph
Optimal Choice / State Dynamic Programming
Exploring All Paths Backtracking
Finding Boundaries / Min/Max Binary Search or Greedy
Sorted + Fast Lookup Binary Search Tree / Heap
Prefix or Text Search Trie
Disjoint Groups Union-Find

✅ Tip:

When you read a new problem, ask yourself:

“What is the core relationship between elements — sequence, hierarchy, or connection?”

That answer almost always points to the right data structure and pattern.


🧠 Senior Front-End DSA & Patterns Cheat Sheet

Complete Front-End Interview Reference. Collapsible sections for readability.


Section 1: 🧱 Stack

Concept: Stack (LIFO)
  • Description: Last-In-First-Out structure.
  • Use cases: Undo/redo, nested parsing, recursion simulation, backtracking.
Problem 1: Valid Parentheses
  • Description: Check if a string of ()[]{} is valid (properly nested).
  • Why Stack: Tracks the last unclosed element.
function isValid(s) {
  const stack = [];
  const map = { ')':'(', ']':'[', '}':'{' };
  for (let ch of s) {
    if (map[ch]) {
      if (stack.pop() !== map[ch]) return false;
    } else stack.push(ch);
  }
  return stack.length === 0;
}
Problem 2: Min Stack
  • Description: Implement a stack that supports push, pop, top, and getMin in O(1).
  • Why Stack: Maintain history of minimums efficiently.
class MinStack {
  constructor() { this.stack = []; this.minStack = []; }
  push(val) {
    this.stack.push(val);
    this.minStack.push(Math.min(val, this.minStack[this.minStack.length-1] ?? val));
  }
  pop() { this.stack.pop(); this.minStack.pop(); }
  top() { return this.stack[this.stack.length-1]; }
  getMin() { return this.minStack[this.minStack.length-1]; }
}
Problem 3: Decode String (Nested)
  1. Description: Decode "3[a2[c]]" → "accaccacc".
  2. Why Stack: Tracks nested repeat counts and partial strings.
function decodeString(s) {
  const stackNum = [], stackStr = [];
  let curNum=0, curStr='';
  for (let ch of s) {
    if(!isNaN(ch)) curNum = curNum*10 + (+ch);
    else if(ch==='['){ stackNum.push(curNum); curNum=0; stackStr.push(curStr); curStr=''; }
    else if(ch===']'){ curStr = stackStr.pop() + curStr.repeat(stackNum.pop()); }
    else curStr += ch;
  }
  return curStr;
}
Problem 4: Simplify Path
  • Description: Simplify "/a/./b/../../c/" → "/c".
  • Why Stack: Track directories in LIFO order to handle ...
function simplifyPath(path) {
  const stack = [];
  const parts = path.split('/');
  for (let part of parts) {
    if(part===''||part=='.') continue;
    if(part==='..') stack.pop(); else stack.push(part);
  }
  return '/' + stack.join('/');
}

Section 2: 🧮 Queue & Priority Queue

Concept: Queue / Priority Queue
    • Queue (FIFO): First-In-First-Out, used in BFS, event scheduling, streaming.
    • Priority Queue / Heap: Efficiently retrieve min/max, used in Top-K, task scheduling.
Problem 1: Sliding Window Maximum
  • Description: Find max in every window of size k.
  • Why Queue/Deque: Keep candidate maximums efficiently.
function maxSlidingWindow(nums,k){
  const res=[], deque=[];
  for(let i=0;i<nums.length;i++){
    while(deque.length && deque[0]<=i-k) deque.shift();
    while(deque.length && nums[i]>=nums[deque[deque.length-1]]) deque.pop();
    deque.push(i);
    if(i>=k-1) res.push(nums[deque[0]]);
  }
  return res;
}
Problem 2: Rotten Oranges (BFS)
  • Description: Grid where rotten oranges infect neighbors per minute; find minimum time.
  • Why Queue: BFS ensures level-by-level traversal simulates time steps.
function orangesRotting(grid){
  const m=grid.length, n=grid[0].length;
  const queue=[];
  let fresh=0, minutes=0;
  
  for(let i=0;i<m;i++)
    for(let j=0;j<n;j++){
      if(grid[i][j]===2) queue.push([i,j]);
      else if(grid[i][j]===1) fresh++;
    }

  const dirs=[[0,1],[1,0],[0,-1],[-1,0]];
  while(queue.length && fresh>0){
    let sz=queue.length;
    for(let i=0;i<sz;i++){
      const [x,y]=queue.shift();
      for(let [dx,dy] of dirs){
        const nx=x+dx, ny=y+dy;
        if(nx<0||ny<0||nx>=m||ny>=n||grid[nx][ny]!==1) continue;
        grid[nx][ny]=2;
        queue.push([nx,ny]);
        fresh--;
      }
    }
    minutes++;
  }
  return fresh>0?-1:minutes;
}
Problem 3: Kth Largest Element (Min Heap)
  • Description: Find Kth largest element in array.
  • Why Heap: Maintains top K efficiently without sorting entire array.
class MinHeap {
  constructor(){ this.heap=[]; }
  insert(val){ 
    this.heap.push(val); 
    let i=this.heap.length-1; 
    while(i>0){ 
      const p=Math.floor((i-1)/2); 
      if(this.heap[p]<=this.heap[i]) break; 
      [this.heap[p],this.heap[i]]=[this.heap[i],this.heap[p]]; 
      i=p; 
    }
  }
  pop(){ 
    if(this.heap.length===1) return this.heap.pop();
    const top=this.heap[0]; this.heap[0]=this.heap.pop();
    let i=0;
    while(true){
      let left=2*i+1, right=2*i+2, smallest=i;
      if(left<this.heap.length && this.heap[left]<this.heap[smallest]) smallest=left;
      if(right<this.heap.length && this.heap[right]<this.heap[smallest]) smallest=right;
      if(smallest===i) break;
      [this.heap[i],this.heap[smallest]]=[this.heap[smallest],this.heap[i]];
      i=smallest;
    }
    return top;
  }
  peek(){ return this.heap[0]; }
}
function findKthLargest(nums,k){
  const heap=new MinHeap();
  for(let n of nums){
    heap.insert(n);
    if(heap.heap.length>k) heap.pop();
  }
  return heap.peek();
}

Section 3: 🔗 Set / Map / Hash Tables

Concept
    • Set: Stores unique values. Fast existence checks.
    • Map / Object / ES6 Map: Key-value store. Average O(1) lookup.
    • Hash Table: Underlying implementation for JS objects/sets.
Problem 1: Two Sum
  • Description: Find indices of two numbers that sum to target.
  • Why Map: Allows O(1) lookup for complement.
function twoSum(nums,target){
  const map=new Map();
  for(let i=0;i<nums.length;i++){
    if(map.has(target-nums[i])) return [map.get(target-nums[i]),i];
    map.set(nums[i],i);
  }
  return [];
}
Problem 2: Longest Substring Without Repeating Characters
  • Description: Find maximum length substring without repeating characters.
  • Why Set: Efficiently track unique characters in sliding window.
function lengthOfLongestSubstring(s){
  const set=new Set();
  let l=0,res=0;
  for(let r=0;r<s.length;r++){
    while(set.has(s[r])) set.delete(s[l++]);
    set.add(s[r]);
    res=Math.max(res,r-l+1);
  }
  return res;
}

Section 4: 🔗 Linked List

Concept
    • Linear structure of nodes pointing to next (and optionally prev).
    • Use cases: Dynamic sequences, history (undo/redo), carousel slides, LRU cache.
Problem 1: Reverse Linked List
function reverseList(head){
  let prev=null, cur=head;
  while(cur){
    let next=cur.next;
    cur.next=prev;
    prev=cur;
    cur=next;
  }
  return prev;
}

Why Linked List: Reversing a dynamic sequence efficiently in-place.

Problem 2: Detect Cycle
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;
}

Why Linked List: Floyd’s cycle detection leverages pointers for O(1) space.

Problem 3: Merge Two Sorted Lists
function mergeTwoLists(l1,l2){
  const dummy={next:null}; let cur=dummy;
  while(l1 && l2){
    if(l1.val<l2.val){ cur.next=l1; l1=l1.next; }
    else{ cur.next=l2; l2=l2.next; }
    cur=cur.next;
  }
  cur.next=l1||l2;
  return dummy.next;
}

Why Linked List: Efficiently merge two sorted sequences without extra space.

Section 5: 🌳 BST / Tree Traversals / Heights

Concept
  • BST: left < root < right.
  • Traversals: Preorder, Inorder, Postorder, BFS.
  • Height: Depth of tree, important for balancing, recursion, and depth-based algorithms.
Problem 1: Inorder Traversal
function inorder(root,res=[]){
  if(!root) return;
  inorder(root.left,res);
  res.push(root.val);
  inorder(root.right,res);
  return res;
}

Why BST: Retrieves elements in sorted order.

Problem 2: Lowest Common Ancestor
function lowestCommonAncestor(root,p,q){
  if(!root||root===p||root===q) return root;
  const left=lowestCommonAncestor(root.left,p,q);
  const right=lowestCommonAncestor(root.right,p,q);
  if(left && right) return root;
  return left || right;
}

Why BST: Finds intersection of two paths efficiently using recursion.

Problem 3: Height of Binary Tree
function height(root){
  if(!root) return 0;
  return 1 + Math.max(height(root.left), height(root.right));
}

Why Tree: Height is fundamental for balancing and performance in recursive algorithms.

Section 6: 🌲 Trie / Heap / Graph

Concept: Trie
  • Prefix tree for storing strings efficiently.
  • Use cases: Autocomplete, prefix search, dictionary, spell check.
class TrieNode{
  constructor(){ this.children={}; this.isWord=false; }
}

class Trie{
  constructor(){ this.root=new TrieNode(); }
  insert(word){
    let node=this.root;
    for(let c of word){
      if(!node.children[c]) node.children[c]=new TrieNode();
      node=node.children[c];
    }
    node.isWord=true;
  }
  search(word){
    let node=this.root;
    for(let c of word){
      if(!node.children[c]) return false;
      node=node.children[c];
    }
    return node.isWord;
  }
  startsWith(prefix){
    let node=this.root;
    for(let c of prefix){
      if(!node.children[c]) return false;
      node=node.children[c];
    }
    return true;
  }
}
Concept: Heap (Min/Max)
  • Complete binary tree; parent smaller/larger than children.
  • Efficient for priority operations, top-K, streaming data.
  • See MinHeap examples in Queue Section.
Concept: Graphs
  • Represent relationships; adjacency list for efficient storage.
  • BFS/DFS for traversal, shortest path, dependency resolution.
// BFS
function bfs(graph,start){
  const visited=new Set();
  const queue=[start];
  const result=[];
  visited.add(start);
  while(queue.length){
    const node=queue.shift();
    result.push(node);
    for(const nei of graph[node]){
      if(!visited.has(nei)){
        visited.add(nei);
        queue.push(nei);
      }
    }
  }
  return result;
}

// Example adjacency list
const graph={
  0:[1,2],
  1:[0,3],
  2:[0,3],
  3:[1,2]
};

Why Graph: BFS ensures level-by-level processing; adjacency list saves memory for sparse graphs.

Problem: Number of Islands (Grid BFS/DFS)
function numIslands(grid){
  const m=grid.length,n=grid[0].length;
  let res=0;
  function dfs(i,j){
    if(i<0||j<0||i>=m||j>=n||grid[i][j]==='0') return;
    grid[i][j]='0';
    dfs(i+1,j); dfs(i-1,j); dfs(i,j+1); dfs(i,j-1);
  }
  for(let i=0;i<m;i++)
    for(let j=0;j<n;j++)
      if(grid[i][j]==='1'){ dfs(i,j); res++; }
  return res;
}

Why Graph/Grid: Treat each land cell as a node; DFS/BFS finds connected components.

Section 7: 💡 Front-End Focused Patterns

Concept
  • Many front-end problems relate to:
    • Nested structures → Stack
    • Event loops / async streams → Queue
    • Sliding window → Live charts / scroll
    • Autocomplete → Trie
    • Dependency resolution → Graph / Topological Sort
  • Key idea: Identify the pattern first, then implement optimal solution.
Example 1: Next Greater Element (Stack)
function nextGreater(nums){
  const stack=[], res=Array(nums.length).fill(-1);
  for(let i=0;i<nums.length;i++){
    while(stack.length && nums[i]>nums[stack[stack.length-1]]){
      res[stack.pop()]=nums[i];
    }
    stack.push(i);
  }
  return res;
}

Use Case: Layout/render calculations, DOM animations.

Example 2: Daily Temperatures (Monotonic Stack)
function dailyTemperatures(T){
  const stack=[], res=Array(T.length).fill(0);
  for(let i=0;i<T.length;i++){
    while(stack.length && T[i]>T[stack[stack.length-1]]){
      let idx=stack.pop();
      res[idx]=i-idx;
    }
    stack.push(i);
  }
  return res;
}

Use Case: Scheduling, animation delays, next-event computation.

Example 3: Sliding Window Maximum (Queue)

Already covered in Queue Section, used in live UI streaming, charts, scroll windows.

Tip

Focus on patterns first, then implementation.

Identify Stack / Queue / Sliding Window / Trie / Graph / DP in UI scenarios.

Keep JS/ES6 idiomatic solutions.

Use

for wiki cheat sheet readability.
⚠️ **GitHub.com Fallback** ⚠️