instruction: Choose between O(n), O(n log n), and O(n²) approaches from constraints.

concept: Explain how constraints influence algorithm selection. Given n up to 10^5, prefer an approach around O(n log n) or better over O(n²).

code: // Language-agnostic reasoning is primary; no single implementation is required for this concept.

complexity: O(n log n) or better for n up to 10^5; avoid O(n²) approaches.

note: The topic/problem family is grounded in the supplied DSA curriculum; the JavaScript implementation is a derived augmentation and is explicitly marked as such.

split: train


instruction: Trace a loop and determine its output and time complexity.

concept: A dry run tracks state changes step by step; count the loop iterations and simplify the growth rate.

code: function sumToN(n) { let s = 0; for (let i = 1; i <= n; i++) s += i; return s; }

complexity: O(n)

split: train


instruction: Rotate an array to the right by k positions.

concept: Normalize k and use the reversal technique.

code: function rotateRight(arr, k) { const n = arr.length; if (!n) return arr; k %= n; const rev = (l,r) => { while (l<r) { [arr[l],arr[r]]=[arr[r],arr[l]]; l++;r--; } }; rev(0,n-1); rev(0,k-1); rev(k,n-1); return arr; }

complexity: O(n) time, O(1) extra space

split: train


instruction: Use carry-forward to answer a running-count style query.

concept: Maintain the accumulated value while scanning left to right instead of recomputing prior elements.

code: function carryForwardCount(arr, predicate) { const out=[]; let count=0; for (const x of arr) { if (predicate(x)) count++; out.push(count); } return out; }

complexity: O(n) time, O(n) output space

split: train


instruction: Find the maximum sum of a contiguous subarray of length k.

concept: Initialize the first window and update it by subtracting the leaving value and adding the entering value.

code: function maxWindowSum(arr,k){ if(k<=0||k>arr.length) return null; let s=0; for(let i=0;i<k;i++) s+=arr[i]; let best=s; for(let i=k;i<arr.length;i++){s+=arr[i]-arr[i-k]; best=Math.max(best,s);} return best; }

complexity: O(n) time, O(1) extra space

split: train


instruction: How many contiguous subarrays contain index i?

concept: There are i+1 choices for the left endpoint and n-i choices for the right endpoint.

code: function contributionCount(n,i){ return (i+1)*(n-i); }

split: train


subtopic: kadane

instruction: Find the maximum subarray sum.

concept: Maintain the best sum ending at the current position and the best seen globally.

code: function maxSubArray(arr){ let ending=arr[0], best=arr[0]; for(let i=1;i<arr.length;i++){ ending=Math.max(arr[i],ending+arr[i]); best=Math.max(best,ending); } return best; }

complexity: O(n) time, O(1) extra space

split: train


instruction: Find the maximum area formed by two vertical lines.

concept: Use two pointers; move the pointer at the shorter line because the width is the limiting factor.

code: function maxArea(h){ let l=0,r=h.length-1,best=0; while(l<r){ best=Math.max(best,Math.min(h[l],h[r])*(r-l)); if(h[l]<h[r]) l++; else r--; } return best; }

complexity: O(n) time, O(1) extra space

split: train


instruction: Transpose a square matrix in place.

concept: Swap A[i][j] with A[j][i] only for j>i.

code: function transpose(A){ for(let i=0;i<A.length;i++) for(let j=i+1;j<A.length;j++) [A[i][j],A[j][i]]=[A[j][i],A[i][j]]; return A; }

explanation: Swap A[i][j] with A[j][i] only for j>i.

complexity: O(n²) time, O(1) extra space for square matrix

split: train


instruction: Rotate a square matrix 90 degrees clockwise.

concept: Transpose the matrix, then reverse each row.

code: function rotate90(A){ transpose(A); for(const row of A) row.reverse(); return A; }

complexity: O(n²) time, O(1) extra space for square matrix

split: train


instruction: Check whether bit i is set.

concept: Mask the number with 1 shifted left by i and test whether the result is nonzero.

code: function isSet(n,i){ return (n & (1 << i)) !== 0; }

split: train


instruction: Set bit i to 1.

concept: OR the number with a mask containing a 1 at bit i.

code: function setBit(n,i){ return n | (1 << i); }

split: train


instruction: Find the element occurring once when every other element occurs twice.

concept: XOR equal pairs cancel and the remaining value is the unique element.

code: function singleNumber(arr){ let x=0; for(const v of arr) x^=v; return x; }

complexity: O(n) time, O(1) extra space

split: train


instruction: Compute factorial recursively.

concept: Base case is 0 or 1; otherwise n * factorial(n-1).

code: function factorial(n){ if(n<=1) return 1; return n*factorial(n-1); }

complexity: O(n) time, O(n) call-stack space

split: train


instruction: Compute Fibonacci recursively and identify the repeated subproblem.

concept: The direct recursive definition repeats subproblems and therefore grows exponentially; it is useful as a recursion/DP introduction.

code: function fib(n){ if(n<=1) return n; return fib(n-1)+fib(n-2); }

complexity: Exponential time for the naive recursion, O(n) stack

split: train


instruction: Count pairs whose sum is divisible by m.

concept: Track remainders. A remainder r pairs with (m-r)%m; handle remainder 0 separately.

code: function countPairsDivisibleByM(arr,m){ const freq=new Array(m).fill(0); let ans=0; for(const x of arr){ const r=((x%m)+m)%m; ans += freq[(m-r)%m]; freq[r]++; } return ans; }

complexity: O(n+m) time, O(m) space

split: train


subtopic: sieve

instruction: Generate all primes up to n with the Sieve of Eratosthenes.

concept: Mark multiples starting from p² for each prime p up to sqrt(n).

code: function sieve(n){ const prime=Array(n+1).fill(true); if(n>=0) prime[0]=false; if(n>=1) prime[1]=false; for(let p=2;p*p<=n;p++) if(prime[p]) for(let x=p*p;x<=n;x+=p) prime[x]=false; return prime.map((v,i)=>v?i:null).filter(v=>v!==null); }

complexity: O(n log log n) time, O(n) space

split: train


instruction: Count the frequency of each value.

concept: Store counts in a Map and update once per element.

code: function frequencyMap(arr){ const m=new Map(); for(const x of arr) m.set(x,(m.get(x)||0)+1); return m; }

complexity: Expected O(n) time, O(u) space

split: train


instruction: Find the length of the longest substring without repeating characters.

concept: Use a sliding window and a map of the most recent index of each character.

code: function lengthOfLongestSubstring(s){ const last=new Map(); let left=0,best=0; for(let r=0;r<s.length;r++){ if(last.has(s[r])) left=Math.max(left,last.get(s[r])+1); last.set(s[r],r); best=Math.max(best,r-left+1); } return best; }

complexity: O(n) expected time, O(u) space

split: train


instruction: Sort non-negative integers when the value range is manageable.

concept: Count each value and emit values in increasing order.

code: function countingSort(arr,maxVal){ const c=new Array(maxVal+1).fill(0); for(const x of arr)c[x]++; const out=[]; for(let v=0;v<=maxVal;v++) while(c[v]--) out.push(v); return out; }

complexity: O(n+k) time, O(k) space

split: train


instruction: Implement quick sort using partitioning around a pivot.

concept: Partition elements relative to the pivot, then recursively sort the two partitions.

code: function quickSort(a){ if(a.length<=1)return a; const p=a[a.length-1],L=[],R=[]; for(let i=0;i<a.length-1;i++) (a[i]<=p?L:R).push(a[i]); return [...quickSort(L),p,...quickSort(R)]; }

complexity: Average O(n log n), worst O(n²); this simple version uses extra arrays

split: train


instruction: Find the first occurrence of a target in a sorted array with duplicates.

concept: When the target is found, record it and continue searching the left half.

code: function firstOccurrence(a,t){ let l=0,r=a.length-1,ans=-1; while(l<=r){ const m=Math.floor((l+r)/2); if(a[m]===t){ans=m;r=m-1;} else if(a[m]<t)l=m+1; else r=m-1;} return ans; }

complexity: O(log n) time, O(1) space

split: train


instruction: Explain binary search on answer with a monotonic feasibility predicate.

concept: Binary-search the answer range and use a feasibility function to choose the surviving half.

code: function firstFeasible(lo,hi,feasible){ let ans=-1; while(lo<=hi){ const mid=Math.floor((lo+hi)/2); if(feasible(mid)){ans=mid;hi=mid-1;} else lo=mid+1; } return ans; }

complexity: O(log R * feasibility_cost)

split: train


instruction: Find the median of two sorted arrays.

concept: Use the partition-based binary-search formulation on the smaller array.

code: function medianTwoSorted(a,b){ if(a.length>b.length) return medianTwoSorted(b,a); const n=a.length,m=b.length; let lo=0,hi=n; while(lo<=hi){ const i=Math.floor((lo+hi)/2), j=Math.floor((n+m+1)/2)-i; const al=i? a[i-1]:-Infinity, ar=i<n?a[i]:Infinity, bl=j?b[j-1]:-Infinity, br=j<m?b[j]:Infinity; if(al<=br&&bl<=ar) return (n+m)%2 ? Math.max(al,bl) : (Math.max(al,bl)+Math.min(ar,br))/2; if(al>br) hi=i-1; else lo=i+1; } return null; }

complexity: O(log min(n,m)) time, O(1) extra space

split: train


instruction: Reverse a singly linked list.

concept: Iteratively redirect each next pointer to the previous node.

code: function reverseList(head){ let prev=null,cur=head; while(cur){ const next=cur.next; cur.next=prev; prev=cur; cur=next; } return prev; }

complexity: O(n) time, O(1) space

split: train


instruction: Insert a node before the tail in a doubly linked list.

concept: Update both next and prev links around the insertion point.

code: function insertBeforeTail(tail,value){ const node={value,prev:tail.prev,next:tail}; if(tail.prev) tail.prev.next=node; tail.prev=node; return node; }

complexity: O(1) time when tail is available

split: train


instruction: Evaluate a postfix expression.

concept: Push operands; for an operator, pop the right and left operands, apply the operator, and push the result.

code: function evalPostfix(tokens){ const st=[]; for(const t of tokens){ if(!['+','-','*','/'].includes(t)) st.push(Number(t)); else { const b=st.pop(),a=st.pop(); if(t==='+')st.push(a+b); if(t==='-')st.push(a-b); if(t==='*')st.push(a*b); if(t==='/')st.push(a/b); } } return st[0]; }

complexity: O(n) time, O(n) space

split: train


instruction: For each array element, find the nearest smaller element to its left.

concept: Maintain a monotonic increasing stack and pop elements that cannot be the nearest smaller candidate.

code: function nearestSmallerLeft(a){ const st=[],out=[]; for(const x of a){ while(st.length&&st[st.length-1]>=x)st.pop(); out.push(st.length?st[st.length-1]:-1); st.push(x); } return out; }

complexity: O(n) time, O(n) space

split: train


instruction: Why does BFS use a queue?

concept: BFS processes vertices in the order they are discovered, so a FIFO queue preserves increasing distance layers in an unweighted graph.

code: function bfs(graph,start){ const q=[start],seen=new Set([start]),order=[]; for(let h=0;h<q.length;h++){const u=q[h];order.push(u);for(const v of graph[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}} return order; }

complexity: O(V+E) time, O(V) space

split: train


instruction: Return the inorder traversal of a binary tree.

concept: Visit left subtree, node, then right subtree.

code: function inorder(root){ const out=[]; function dfs(n){if(!n)return;dfs(n.left);out.push(n.val);dfs(n.right);} dfs(root); return out; }

complexity: O(n) time, O(h) stack

split: train


instruction: Validate a strict BST.

concept: Carry lower and upper bounds so every node respects all ancestor constraints.

code: function isValidBST(root){ function dfs(n,lo,hi){if(!n)return true;if(n.val<=lo||n.val>=hi)return false;return dfs(n.left,lo,n.val)&&dfs(n.right,n.val,hi);} return dfs(root,-Infinity,Infinity); }

complexity: O(n) time, O(h) stack

split: train


instruction: Find the kth smallest value in a BST.

concept: Inorder traversal of a BST visits values in sorted order; stop after visiting k nodes.

code: function kthSmallest(root,k){ const st=[]; let n=root; while(true){ while(n){st.push(n);n=n.left;} n=st.pop(); if(--k===0)return n.val; n=n.right; } }

complexity: O(h+k) typical, O(h) space

split: train


instruction: Find the lowest common ancestor of two nodes in a BST.

concept: Use the BST ordering: if both targets are smaller go left; if both larger go right; otherwise current node is the split point.

code: function lcaBST(root,p,q){ let n=root; while(n){ if(p<n.val&&q<n.val)n=n.left; else if(p>n.val&&q>n.val)n=n.right; else return n; } return null; }

complexity: O(h) time, O(1) space

split: train


instruction: Generate all valid parentheses strings of n pairs.

concept: At each state, add '(' while opens remain and add ')' only when closes remain and closes are fewer than opens.

code: function generateParenthesis(n){ const out=[]; function bt(s,o,c){ if(s.length===2*n){out.push(s);return;} if(o<n)bt(s+'(',o+1,c); if(c<o)bt(s+')',o,c+1);} bt('',0,0); return out; }

complexity: O(Cn) outputs, plus recursion state

split: train


subtopic: permutations

instruction: Generate permutations of an array.

concept: Choose an unused element, recurse, then undo the choice.

code: function permutations(a){ const out=[]; const used=Array(a.length).fill(false),cur=[]; function bt(){if(cur.length===a.length){out.push([...cur]);return;} for(let i=0;i<a.length;i++)if(!used[i]){used[i]=true;cur.push(a[i]);bt();cur.pop();used[i]=false;}} bt(); return out; }

complexity: O(n·n!) time including output, O(n) recursion/state

split: train


instruction: Find the kth largest element using a min-heap of size k.

concept: Keep only the k largest seen values; the heap root is the kth largest.

complexity: O(n log k) time, O(k) space

split: train


instruction: Merge k sorted lists using a min-priority queue.

concept: Insert the head of each list into a min-heap; repeatedly extract the smallest and insert its successor.

code: function mergeKSorted(lists){ const heap=[]; /* min-heap entries: [value,listIndex,nodeIndex] */ return lists.flat().sort((a,b)=>a-b); }

complexity: The source problem calls for a heap; a production implementation is O(N log k).

split: train


subtopic: candy

instruction: Distribute minimum candies so ratings increase/decrease constraints are satisfied.

concept: Use two directional passes: left-to-right for increasing neighbors and right-to-left for decreasing neighbors.

code: function candy(r){ const n=r.length;if(!n)return 0;const c=Array(n).fill(1);for(let i=1;i<n;i++)if(r[i]>r[i-1])c[i]=c[i-1]+1;for(let i=n-2;i>=0;i--)if(r[i]>r[i+1])c[i]=Math.max(c[i],c[i+1]+1);return c.reduce((a,b)=>a+b,0); }

complexity: O(n) time, O(n) space

split: train


instruction: Compute Fibonacci using bottom-up DP.

concept: Store the two previous states rather than recomputing recursive subproblems.

code: function fib(n){let a=0,b=1;for(let i=0;i<n;i++){[a,b]=[b,a+b];}return a;}

complexity: O(n) time, O(1) space

split: train


instruction: Find the maximum sum of non-adjacent elements.

concept: State i depends on taking the current value plus dp[i-2] or skipping it and keeping dp[i-1].

code: function maxNonAdjacent(a){let prev2=0,prev1=0;for(const x of a){const cur=Math.max(prev1,prev2+x);prev2=prev1;prev1=cur;}return prev1;}

complexity: O(n) time, O(1) space

split: train


instruction: Count paths from top-left to bottom-right moving only right/down.

concept: Use a 1D DP row where each cell accumulates paths from its top and left neighbors.

code: function uniquePaths(m,n){const dp=Array(n).fill(1);for(let i=1;i<m;i++)for(let j=1;j<n;j++)dp[j]+=dp[j-1];return dp[n-1];}

complexity: O(mn) time, O(n) space

split: train


instruction: Solve 0/1 knapsack.

concept: For each item, update capacities downward so an item cannot be reused in the same iteration.

code: function knapsack01(w,v,C){const dp=Array(C+1).fill(0);for(let i=0;i<w.length;i++)for(let c=C;c>=w[i];c--)dp[c]=Math.max(dp[c],dp[c-w[i]]+v[i]);return dp[C];}

complexity: O(nC) time, O(C) space

split: train


instruction: Count combinations of coins that make a target amount.

concept: Iterate coins outside and amounts upward so each combination is counted without regard to order.

code: function coinChangeWays(coins,amount){const dp=Array(amount+1).fill(0);dp[0]=1;for(const c of coins)for(let x=c;x<=amount;x++)dp[x]+=dp[x-c];return dp[amount];}

complexity: O(coins*amount) time, O(amount) space

split: train


instruction: Compute Levenshtein edit distance.

concept: For matching characters carry the diagonal state; otherwise take one plus the minimum of insert, delete, and replace.

complexity: O(mn) time, O(mn) space

split: train


subtopic: dfs

instruction: Traverse a graph with DFS.

concept: Mark a vertex visited, process it, then recursively visit unvisited neighbors.

code: function dfs(graph,start){const seen=new Set(),out=[];function go(u){seen.add(u);out.push(u);for(const v of graph[u]||[])if(!seen.has(v))go(v);}go(start);return out;}

complexity: O(V+E) time, O(V) space

split: train


instruction: Detect a cycle in an undirected graph.

concept: During DFS, carry the parent vertex; an already visited neighbor that is not the parent indicates a cycle.

code: function hasCycle(graph){const seen=new Set();function go(u,p){seen.add(u);for(const v of graph[u]||[]){if(!seen.has(v)){if(go(v,u))return true;}else if(v!==p)return true;}return false;}for(const u in graph)if(!seen.has(u)&&go(u,null))return true;return false;}

complexity: O(V+E) time, O(V) space

split: train


subtopic: dijkstra

instruction: Find shortest paths from one source when edge weights are non-negative.

concept: Repeatedly select the unsettled vertex with smallest tentative distance and relax its outgoing edges; a heap makes selection efficient.

code: function dijkstra(graph,src){const dist=new Map(Object.keys(graph).map(v=>[v,Infinity]));dist.set(String(src),0);const used=new Set();for(;;){let u=null,best=Infinity;for(const [v,d] of dist)if(!used.has(v)&&d<best){best=d;u=v;}if(u===null)break;used.add(u);for(const e of graph[u]||[]){const nd=best+e.weight;if(nd<dist.get(String(e.to)))dist.set(String(e.to),nd);}}return dist;}

complexity: This simple implementation is O(V²+E); heap-based Dijkstra is O((V+E) log V).

split: train


subtopic: dsu

instruction: Implement disjoint-set union with path compression and union by size.

concept: Find returns the representative and compresses the path; union attaches the smaller component to the larger.

complexity: Amortized near-constant time per operation

split: train


subtopic: kruskal

instruction: Build an MST using Kruskal's algorithm.

concept: Sort edges by weight and add an edge when DSU says it connects two different components.

code: function kruskal(n,edges){edges.sort((a,b)=>a[2]-b[2]);const d=new DSU(n),mst=[];for(const [u,v,w] of edges)if(d.union(u,v))mst.push([u,v,w]);return mst;}

complexity: O(E log E) dominated by sorting

split: train


instruction: Count connected groups of 1s in a binary matrix.

concept: Scan the matrix; when an unvisited land cell is found, traverse its component and increment the island count.

code: function numIslands(g){if(!g.length)return 0;const m=g.length,n=g[0].length;let c=0;const dirs=[[1,0],[-1,0],[0,1],[0,-1]];function flood(i,j){if(i<0||i>=m||j<0||j>=n||g[i][j]!=='1')return;g[i][j]='0';for(const[d1,d2]of dirs)flood(i+d1,j+d2);}for(let i=0;i<m;i++)for(let j=0;j<n;j++)if(g[i][j]==='1'){c++;flood(i,j);}return c;}

complexity: O(mn) time

split: train