HTHyperTransformer AI

Study cards › DSA

DSAInterview questions and answers

← Topics1 / 100
1 / 100 viewed
Question

What is Big-O notation?

Answer

Big-O describes the worst-case growth rate of an algorithm's time or space as input size n grows. It ignores constants and lower-order terms — O(2n) and O(n) are the same class. The point is comparing how algorithms scale, not exact runtimes.

Question

Common time complexities ordered?

Answer

O(1) constant < O(log n) logarithmic < O(n) linear < O(n log n) — typical good sorts < O(n²) — nested loops < O(2ⁿ) — naive recursion on subsets < O(n!) — permutations. Each step is a meaningful jump; n=1M is fine for O(n log n) but devastating for O(n²).

Question

Array vs Linked List?

Answer

Array: contiguous memory, O(1) random access by index, cache-friendly, but O(n) to insert in the middle (must shift). Linked list: scattered memory, O(n) random access, O(1) insert/remove if you already have the node, pointer overhead. For nearly all real workloads, arrays win.

Question

When should you choose a hash map?

Answer

When you need O(1) average lookup, insert, and delete by key, and you don't care about order. Hash maps are the workhorse of most algorithms — counting frequencies, deduplicating, mapping between values, caching. Worst-case is O(n) on bad collisions but rare in practice.

Question

What is a stack?

Answer

A LIFO (Last-In-First-Out) data structure. Operations: push (add to top), pop (remove from top), peek (look at top) — all O(1). Used for function call frames, undo/redo, balanced parentheses, expression evaluation, and DFS implementations.

Question

What is a queue?

Answer

A FIFO (First-In-First-Out) data structure. Operations: enqueue (add to back), dequeue (remove from front) — both O(1) with proper implementation. Used for BFS traversals, task queues, message buffers, and anything that needs orderly arrival-time processing.

Question

What is a deque?

Answer

A double-ended queue: O(1) push and pop on BOTH ends. More flexible than a regular queue or stack — used for sliding-window problems, monotonic queue algorithms, and palindrome checks. JS doesn't have a native deque but arrays handle it adequately for many problems.

Question

What is a heap?

Answer

A complete binary tree where each parent is greater (max-heap) or smaller (min-heap) than its children. Operations: insert in O(log n), peek-top in O(1), extract-top in O(log n). Stored as an array — index 0 is root, children of i are at 2i+1 and 2i+2.

Question

What is a priority queue?

Answer

An abstract data type that returns items in priority order rather than insertion order. Almost always implemented with a heap. Used in Dijkstra's algorithm, A*, task schedulers, K-largest problems, and event simulations.

Question

Binary tree traversal orders?

Answer

Pre-order: root, then left subtree, then right (used for cloning, prefix expressions). In-order: left, root, right (yields sorted order on a BST). Post-order: left, right, root (used for deletion, postfix expressions). Level-order: BFS by depth (used for level-based processing).

Question

When is in-order traversal useful?

Answer

On a Binary Search Tree, in-order yields nodes in sorted order. Used for printing BSTs sorted, finding the k-th smallest, validating BST property, and range queries. The connection 'BST + in-order = sorted' is one of the most useful identities in DSA.

Question

What is a BST?

Answer

Binary Search Tree — for every node, all left-subtree values are less and all right-subtree values are greater. Average O(log n) for search/insert/delete on balanced data; degenerates to O(n) if inserted in sorted order (becomes a linked list).

Question

How do you keep a BST balanced?

Answer

Use a self-balancing variant: AVL (strictly balanced, fast lookups), Red-Black (more relaxed balance, faster inserts — used in C++ map, Java TreeMap), or B-trees/B+-trees (multi-way, designed for disk and the basis of most database indexes).

Question

DFS vs BFS?

Answer

DFS goes deep first, using a stack (or recursion), O(V+E). BFS goes level by level, using a queue, O(V+E) — and finds the shortest path in unweighted graphs. Pick based on goal: shortest path → BFS; explore all paths or detect cycles → DFS.

Question

When should you use BFS?

Answer

Shortest path in unweighted graphs, level-order traversal of trees, minimum steps in a puzzle (sliding tiles, word ladder), connectivity in a grid, and 'find the nearest matching node' problems. The 'spread outward layer by layer' shape.

Question

When should you use DFS?

Answer

Enumerating all paths, detecting cycles, topological sort, finding connected components, backtracking problems (N-queens, sudoku), and tree-recursive algorithms. The 'go deep before going wide' shape.

Question

What is Dijkstra's algorithm?

Answer

Finds shortest paths from a source to all other nodes in a graph with non-negative weights. Uses a min-heap to always expand the closest unvisited node. Runs in O((V + E) log V) with a binary heap. Doesn't work with negative edges — use Bellman-Ford for those.

Question

What is the Bellman-Ford algorithm?

Answer

Single-source shortest paths that handles NEGATIVE edge weights and detects negative cycles. Slower than Dijkstra at O(V·E), but more general. Used when negative edges are possible — like routing problems where costs can decrease.

Question

What is Floyd-Warshall?

Answer

All-pairs shortest paths in O(V³) — finds shortest distance between every pair of vertices. Great for small, dense graphs and handles negative edges (no negative cycles). Simple to implement: three nested loops over the distance matrix.

Question

What is topological sort?

Answer

A linear ordering of a Directed Acyclic Graph (DAG) where every edge u → v has u before v. Two main approaches: DFS post-order (reverse the result) or Kahn's algorithm (BFS using in-degrees). Used for build orders, course prerequisites, and task scheduling.

Question

What are Union-Find use cases?

Answer

Tracking connectivity in a dynamic graph: detecting if two nodes are in the same group, merging groups, Kruskal's MST algorithm. With path compression and union-by-rank, operations are nearly O(1) amortized — one of the most surprisingly fast structures.

Question

What is recursion?

Answer

A function calling itself with a smaller version of the problem until it hits a base case. Powerful for problems with natural self-similarity (trees, divide-and-conquer). Watch for stack depth — JS doesn't reliably optimize tail calls, so very deep recursion can overflow.

Question

When does recursion overflow?

Answer

When call depth exceeds the call stack — typically thousands to tens of thousands of frames depending on the runtime. Fix by converting to iteration using an explicit stack/queue, or by using a language/runtime that does tail call optimization.

Question

What is memoization?

Answer

Caching the results of pure recursive calls keyed by their inputs. Converts exponential recursion (like naive Fibonacci) into polynomial time by avoiding redundant work. The top-down form of dynamic programming.

Question

What is dynamic programming?

Answer

Solving problems by combining solutions to overlapping subproblems with optimal substructure. Two styles: top-down (recursion + memoization) or bottom-up (build a table iteratively). DP turns 'try everything' into 'try each subproblem once'.

Question

Top-down vs bottom-up DP?

Answer

Top-down: recursive with memoization, easier to think through, only computes the subproblems you actually need. Bottom-up: iterative table-filling, avoids recursion overhead, often easier to optimize space. Same complexity in big-O — pick by readability and constants.

Question

Classic DP problems?

Answer

Fibonacci, climbing stairs, coin change, longest common subsequence (LCS), longest increasing subsequence (LIS), edit distance (Levenshtein), 0/1 knapsack, matrix chain multiplication, palindrome partitioning, subset sum. Master a handful and you'll see the patterns everywhere.

Question

0/1 knapsack problem?

Answer

Given items with weights and values and a capacity, maximize value picking each item at most once. Classic 2D DP: dp[i][w] = best value using the first i items with weight budget w. Can be optimized to 1D by iterating weight from high to low to avoid reusing items.

Question

What is the sliding window technique?

Answer

Maintain a window over an array/string, expanding from the right and shrinking from the left, to solve substring/subarray problems in O(n) instead of O(n²). Often replaces nested loops with a single pass keeping running state.

Question

Fixed vs variable sliding window?

Answer

Fixed: window size is constant — like sum of every k-length subarray. Variable: window grows or shrinks based on a condition — like 'longest substring without repeating characters' where you shrink whenever a duplicate enters.

Question

What is the two-pointer technique?

Answer

Use two indices moving over an array (toward each other, in the same direction, or at different speeds) to solve problems that look quadratic with one pointer. Classic uses: pair sums on sorted arrays, reverse, dedupe, palindrome checks, container-with-most-water.

Question

What is binary search?

Answer

Repeatedly halve the search range over a sorted (or monotonic-predicate) array to find a target in O(log n). Easy to write incorrectly — pay attention to inclusive vs exclusive bounds and the termination condition (low <= high vs low < high).

Question

What is 'binary search on the answer'?

Answer

When the answer space is sortable and you have a monotonic feasibility check (if X works, X+1 works), binary search the answer. Common in problems like 'min capacity', 'min days to ship', 'split array largest sum'. A powerful pattern beyond literal sorted arrays.

Question

What is QuickSort?

Answer

Divide and conquer: pick a pivot, partition the array so smaller items go left and larger go right, recurse on each side. Average O(n log n), worst-case O(n²) on bad pivot choices (median-of-three or random pivots help). In-place, but unstable.

Question

What is MergeSort?

Answer

Divide and conquer: split the array in half, sort each half recursively, merge the sorted halves. Always O(n log n), stable, but uses O(n) extra space. Preferred when stability matters or when sorting linked lists (merge needs only sequential access).

Question

Stable vs unstable sort?

Answer

A stable sort preserves the original relative order of elements with equal keys — MergeSort, TimSort, InsertionSort. Unstable sorts may reorder them — QuickSort, HeapSort. Matters when you sort by multiple keys in sequence (sort by name, then stable-sort by age).

Question

What is a Trie?

Answer

A tree where each path from root spells out a string and shared prefixes share nodes. Lookup and insert are O(L) where L is the key length. Used for autocomplete, dictionaries, IP routing, longest common prefix problems, and many text/spelling algorithms.

Question

What is a segment tree?

Answer

A tree for range queries (sum/min/max over [l,r]) and point or range updates in O(log n). More flexible than prefix sums because it supports updates. Heavier than Fenwick trees but more powerful. Used in competitive programming and certain DB index structures.

Question

What is a Fenwick tree (BIT)?

Answer

Binary Indexed Tree — a compact structure for prefix sums and point updates in O(log n). Simpler and lower-constant than a segment tree, but limited to cumulative operations. The 'low bit' trick (i & -i) is what makes it elegant.

Question

What is a hash collision?

Answer

Two different keys hashing to the same bucket. Resolved by chaining (each bucket holds a list) or open addressing (probe to the next slot — linear, quadratic, or double hashing). Good hash functions and load-factor management keep collisions rare.

Question

What is hash map load factor?

Answer

Ratio of stored entries to bucket slots. Above ~0.75, collisions become common and lookup degrades. Most implementations resize (double the buckets, rehash everything) when the load factor crosses a threshold, keeping average operations O(1) amortized.

Question

Adjacency list vs adjacency matrix?

Answer

Adjacency list: O(V + E) space, fast to iterate neighbors. Adjacency matrix: O(V²) space, O(1) edge existence checks. For sparse graphs (most real graphs), use lists. Matrices win only when graphs are dense or you need constant-time edge tests.

Question

Cycle detection in a directed graph?

Answer

DFS with three states (white = unvisited, gray = in current path, black = done). If you hit a gray node, you found a back edge — that's a cycle. Alternative: topological sort and check if it processed all nodes.

Question

Cycle detection in an undirected graph?

Answer

DFS tracking the parent — if you reach a visited node that isn't your parent, you've found a cycle. Alternative: Union-Find detects cycles as you process edges (if an edge connects two nodes already in the same set, it's a cycle).

Question

What is backtracking?

Answer

Depth-first exploration of choices with the ability to UNDO and try alternatives when a dead end is reached. Solves N-queens, permutations, subset sum, sudoku, word search, and combinatorial enumeration in general. Often combined with pruning (skip subtrees that can't work).

Question

What is a greedy algorithm?

Answer

Make locally optimal choices hoping they lead to a global optimum. Works only when the problem has the 'greedy choice property' and 'optimal substructure' — interval scheduling, Huffman coding, Kruskal's MST, fractional knapsack. Provably wrong on many other problems (like 0/1 knapsack).

Question

Greedy vs dynamic programming?

Answer

Greedy commits to a choice irrevocably; DP explores all combinations and keeps the best. Greedy is much faster when it works but only works on specific problem structures. DP is more general at the cost of speed and memory.

Question

What is divide and conquer?

Answer

Recursively split a problem into smaller subproblems, solve them independently, and combine the results. Examples: MergeSort, QuickSort, FFT, closest-pair-of-points, fast matrix multiplication. The Master theorem analyzes their runtime.

Question

Dynamic programming on grids?

Answer

dp[i][j] holds the best result reaching cell (i,j) from the start. Patterns: min path sum, unique paths, edit distance (string i, string j → grid), largest square of 1s. Move costs and constraints become transitions between cells.

Question

What is Kadane's algorithm?

Answer

Finds the maximum subarray sum in O(n). Track 'best ending here' = max(arr[i], best_ending_here + arr[i]) and update the global max as you go. Classic example of a 1D DP collapsed into two variables.

Question

What is the LIS problem?

Answer

Longest Increasing Subsequence — find the longest subsequence (not contiguous) that's strictly increasing. O(n²) DP (for each i, look back at all earlier j) or O(n log n) using patience-sorting / binary search into a tails array.

Question

What is LCS?

Answer

Longest Common Subsequence between two strings — DP table dp[i][j] in O(m·n). Underlies diff tools (git diff), file comparison, and bioinformatics (DNA alignment). The classic 2D string DP.

Question

What is edit distance (Levenshtein)?

Answer

Minimum number of insert, delete, or replace operations to convert string A to string B. Classic DP dp[i][j] = min cost to transform first i chars of A to first j chars of B in O(m·n). Used in spell check, fuzzy search, DNA comparison.

Question

What is fast/slow pointer?

Answer

A two-pointer technique on linked lists where one pointer advances faster than the other. Used to detect cycles (Floyd's), find the middle node, or find the Nth-from-end node — all in one pass and O(1) extra space.

Question

How do you detect a cycle in a linked list?

Answer

Floyd's tortoise-and-hare: slow pointer moves 1 step, fast pointer moves 2 steps. If a cycle exists, they will eventually meet inside it. If fast hits null, there's no cycle. O(n) time, O(1) space — much better than using a hash set.

Question

How do you reverse a linked list?

Answer

Iterate with three pointers — prev, curr, next. At each step: save next = curr.next, set curr.next = prev, advance prev = curr, curr = next. Return prev as the new head. O(n) time, O(1) space, classic warm-up problem.

Question

Find the K-th smallest in an array?

Answer

Three options: sort (O(n log n)), use a min-heap of size k (O(n log k)), or QuickSelect (average O(n), worst O(n²)). QuickSelect is the academically correct answer but tricky to implement; a heap is usually the practical choice.

Question

What is bit manipulation used for?

Answer

Compact sets (bitmask of which items chosen), parity tracking, fast equality testing (XOR), shifting/masking in protocols, and elegant solutions to specific puzzles. Constant-time operations on small fixed-size data when memory and speed both matter.

Question

XOR property for finding the unique number?

Answer

x XOR x = 0 and x XOR 0 = x. So XOR-ing every element of an array where one number appears once and the rest appear twice yields that unique number — duplicates cancel out, the singleton remains. O(n) time, O(1) space.

Question

What is a monotonic stack?

Answer

A stack maintained in strictly increasing or decreasing order — push pops elements that violate the order. Solves next-greater-element, daily-temperatures, largest-rectangle-in-histogram, and stock-span in O(n) total time despite looking nested.

Question

What is a monotonic deque?

Answer

A deque kept in monotonic order while supporting sliding-window operations. Solves sliding-window-maximum in O(n) by maintaining the deque so the front is always the window's max.

Question

What's the 'sort then scan' technique?

Answer

Many problems become O(n log n) easy after sorting: merging intervals, meeting rooms, two-sum on sorted (O(n) two-pointer), three-sum, scheduling. The first move on many array problems should be 'is this easier sorted?'

Question

What is the three-sum problem?

Answer

Find all triples that sum to zero. Sort the array, then for each i, use two pointers on the rest to find pairs that sum to -arr[i]. O(n²) total. Be careful to skip duplicates so you don't return the same triple twice.

Question

What is Manacher's algorithm?

Answer

Linear-time algorithm for finding the longest palindromic substring. Niche but elegant — uses symmetry to reuse work across positions. Most interview problems are happy with the simpler O(n²) expand-from-center approach.

Question

What is KMP?

Answer

Knuth-Morris-Pratt substring search in O(n + m). Builds a failure function from the pattern that says how far to skip on mismatches, so the algorithm never re-scans previously-matched characters. Used in text editors, log scanners, and any high-volume substring matching.

Question

What is Rabin-Karp?

Answer

String matching using a rolling hash — hash the pattern, then slide a window over the text computing hashes in O(1) per shift. Average O(n + m); particularly good for multi-pattern search (hash each pattern, check matches against the text's window hash).

Question

What is sliding window median?

Answer

Maintain two heaps — a max-heap of the lower half and a min-heap of the upper half — so the median is O(1) and updates are O(log n). Or use a balanced BST. Used in real-time streaming statistics.

Question

What is meet-in-the-middle?

Answer

Split the problem in half, solve each independently in O(2^(n/2)), then combine the results. Reduces brute-force 2ⁿ search to 2^(n/2). Classic in subset-sum problems with n around 40-50 where straight brute force is too slow.

Question

Find the duplicate in array [1..n]?

Answer

Treat values as 'next pointers' (since they're in range 1..n) and apply Floyd's cycle detection. The duplicate is the entrance to the cycle. O(n) time, O(1) space — beautiful application of the cycle-detection algorithm beyond linked lists.

Question

When is a sliding window 'invalid'?

Answer

When it violates the problem's constraint — e.g. sum > target, more than k distinct chars, a repeated character. The pattern: expand right, when invalid shrink from left until valid again, record the answer at each step.

Question

What is amortized complexity?

Answer

The average cost per operation over a worst-case sequence — not the worst case of a single operation. Dynamic array push is O(1) amortized despite the occasional O(n) resize, because resizes are rare and the cost is spread over many cheap pushes.

Question

What is an in-place algorithm?

Answer

Uses O(1) extra space beyond the input. Examples: reverse an array, heap sort, in-place QuickSort partition, Dutch flag partition. Often saves memory but makes the algorithm harder to read or test.

Question

How do you find a tree's diameter?

Answer

Two BFS/DFS passes: from any node, find the farthest (call it A). From A, find the farthest (call it B). Distance A↔B is the diameter. Alternative: one DFS that returns max-depth and updates a global max as it visits each node.

Question

What is the Lowest Common Ancestor (LCA)?

Answer

For two nodes in a tree, the deepest node that is an ancestor of both. Simple DFS: recurse into both children — if both return non-null, current node is the LCA. For repeated queries, use binary lifting for O(log n) per query.

Question

Shortest path in a weighted DAG?

Answer

Topologically sort the DAG, then relax edges in that order. O(V + E). Works even with negative weights (since there can't be negative cycles in a DAG). Much simpler than Dijkstra when the graph is acyclic.

Question

Minimum spanning tree algorithms?

Answer

Kruskal: sort edges by weight, add each if it doesn't form a cycle (Union-Find). Prim: grow a tree from a seed, always adding the cheapest edge to a new node (min-heap). Both are O(E log V). Use whichever feels more natural to code.

Question

When is Bellman-Ford the right choice?

Answer

When the graph has negative edge weights (Dijkstra fails) or you need to detect negative cycles. Runs in O(V·E) — slower than Dijkstra, but more general. Used in routing protocols (RIP) and arbitrage detection.

Question

What is a Strongly Connected Component (SCC)?

Answer

Maximal subgraph of a directed graph where every node can reach every other. Algorithms: Kosaraju (two DFS passes), Tarjan (one DFS with low-link values), both in O(V + E). Used in dependency analysis, social network clustering.

Question

What is counting sort?

Answer

Sort integers in a fixed range [0..k] in O(n + k). Build a count array, then output values in order. Stable, non-comparison-based. Great when k is small relative to n; bad when k is huge (uses k memory).

Question

What is radix sort?

Answer

Sort by digits using counting sort per digit position — O(d · (n + k)) where d is the number of digits. Linear time for fixed-width keys (32-bit ints, fixed-length strings). Used in database query engines and some specialized sort scenarios.

Question

What is heapify?

Answer

Convert an arbitrary array into a heap in O(n). Walk from the middle of the array to index 0, sift each element down. Counterintuitively faster than n inserts (which would be O(n log n)) because most subtrees being sifted are small.

Question

Find K-th largest using a heap?

Answer

Maintain a min-heap of size k. Push each new element; if size exceeds k, pop the smallest. After processing all elements, the heap's top is the k-th largest. O(n log k) time, O(k) space — better than full sort for streaming.

Question

Permutations vs combinations?

Answer

Permutations: order matters. P(n,k) = n! / (n-k)! ways to choose k from n with order. Combinations: order doesn't matter. C(n,k) = n! / (k!(n-k)!). Use combinations when subsets are equivalent regardless of arrangement, permutations when arrangement is meaningful.

Question

How do you generate all permutations?

Answer

Backtracking: at each position, try swapping each remaining element into that slot, recurse, then swap back. O(n!) outputs and time. Alternatives: lexicographic next-permutation algorithm (in-place) or iterative Heap's algorithm.

Question

How do you generate all subsets?

Answer

Either iterate from 0 to 2ⁿ-1 and use each bit i to decide whether to include element i (great for n up to ~20), or use DFS choosing include/exclude at each step. Both produce 2ⁿ subsets.

Question

What is an LRU cache?

Answer

A cache with a fixed size that evicts the Least Recently Used entry when full. Implemented with a hash map + doubly-linked list: hash gives O(1) lookup, the list tracks access order. Both operations O(1). Classic interview question.

Question

What is an LFU cache?

Answer

Evicts the Least Frequently Used entry. Implementation: a hash map keyed by frequency, each value a linked list of items with that frequency. More complex than LRU but still O(1) — clever bookkeeping required.

Question

What is graph coloring?

Answer

Assigning colors to nodes so no two adjacent nodes share a color, using as few colors as possible. NP-hard in general. Special case: bipartite graphs are 2-colorable — checkable in O(V+E) via BFS coloring.

Question

How do you check if a graph is bipartite?

Answer

BFS or DFS while assigning alternating colors. Start with any unvisited node, color it 0. Each neighbor gets the opposite color. If you ever try to give a node a color that contradicts an existing assignment, it's NOT bipartite. O(V + E).

Question

What is a rolling hash?

Answer

A hash function that can update in O(1) when the window slides by one character — remove the contribution of the outgoing char, add the incoming. Foundation of Rabin-Karp and similar substring-matching algorithms.

Question

Segment tree vs Fenwick tree?

Answer

Segment tree: supports many operations (sum, min, max, lazy propagation for range updates), but heavier code and constants. Fenwick tree: simpler, smaller, faster, but limited to prefix-sum-style queries. Use Fenwick for sums, segment trees when you need flexibility.

Question

Binary indexed tree update walk?

Answer

To update index i, walk parents with i += i & -i. To query prefix sum up to i, walk with i -= i & -i. The 'low bit' trick (i & -i isolates the lowest set bit) is what makes the data structure compact and fast.

Question

Max subarray with at most K distinct?

Answer

Sliding window over the array + a hash count of characters. Expand from the right; when distinct count > K, shrink from the left. Track the max window length. O(n) time, O(K) space.

Question

Boyer-Moore majority vote?

Answer

Find the element that appears more than n/2 times in O(n) time and O(1) space: keep a candidate and a counter. Increment if matching, decrement otherwise; reset candidate if counter hits 0. Verify the candidate with a second pass.

Question

What is reservoir sampling?

Answer

Sample k items uniformly at random from a stream of unknown length. Keep the first k, then for the i-th item (i > k), include it with probability k/i, replacing a random existing item. Used when you can't fit the whole stream in memory.

Question

When is recursion safe to use?

Answer

When the depth is bounded — typically when it's logarithmic in input (balanced trees, divide-and-conquer) or when the input itself is small. Deep linear recursion (n=10⁵) will overflow most stacks; convert to iteration in those cases.

Question

What is tail recursion?

Answer

A recursive call that's the last operation in the function — the caller has nothing to do after it returns. Some languages optimize tail calls into loops (no stack growth). JavaScript doesn't reliably; rewrite tail-recursive functions as iterative loops for safety.

Question

Recurrence T(n) = 2T(n/2) + O(n) — what is it?

Answer

O(n log n) by the Master theorem — same as MergeSort. The recursion tree has log n levels with O(n) work each, summing to O(n log n).

Question

Master theorem in one sentence?

Answer

For T(n) = aT(n/b) + f(n), compare f(n) to n^log_b(a) — whichever grows faster dominates, and if they grow at the same rate, multiply by a log factor. Determines whether the work is dominated by the recursion's branching or the per-call work.

Question

What is path compression in Union-Find?

Answer

During a Find operation, point every node on the path directly to the root. Future Finds on those nodes are then O(1). Combined with union-by-rank, makes Union-Find effectively O(1) amortized per operation — one of the fastest data structures around.

Practise DSA in the app
Track your progress, flag tricky cards and write your own answers.

Open in the app

More topics: React & Frontend JavaScript & TypeScript Backend Engineering Databases System Design AI & Agentic AI DevOps & Cloud Security Testing Coding Problems (Python)