Skip to main content

Must-know DSA interview questions

53 reported frequent at Meta, Microsoft, Amazon and 14 more. “Reported” because the company tags have no public source. Every quick answer is free.

Questions on this page
53
Must know
0
picked by the editor
Reported frequent
53
company tags, reported
Companies
17
with a frequent tag

Reported frequent· 53

Tagged as frequent at a company. Reported: the tags have no public source.

  1. Given a collection of intervals, merge all overlapping intervals.Sort by start, then merge into the last interval whenever the current start <= last end, taking max of ends. O(n log n). Watch the fully-contained case - always take max of the ends.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at Amazon+3
  2. Design and implement an LRU cache with O(1) get and put.HashMap for O(1) lookup plus a doubly linked list ordered by recency: move touched nodes to head, evict from tail on overflow, sentinels keep unlinking O(1). O(1) get/put. Follow-ups: thread-safety via locking and LFU vs LRU tradeoffs for a database's result cache.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at Apple+3
  3. Count the number of islands in a 2D grid of land and water. [BFS/DFS]Scan the grid, and each time you hit an unvisited land cell increment the island count and flood-fill all connected land (up/down/left/right) so it is not counted again. Marking visited cells in place (or in a separate set) prevents recounting. Every cell is visited once, giving O(rows × cols) time.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at Amazon+2
  4. Find the lowest common ancestor (LCA) of two given nodes in a binary tree.Recurse: return the node if it's null or a target; if both left and right recursions return non-null, this node is the LCA, else bubble up the non-null side. O(n). For a BST, walk down by value comparison in O(h); with parent pointers, intersect the two ancestor chains.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at Flipkart+2
  5. Given a board of characters and a list of words, return all words that can be formed by sequentially adjacent cells (Word Search II).Build a Trie of all words, then DFS the board once walking board and Trie in lockstep so shared prefixes are explored once and all words are searched together. Mark cells visited during a path and backtrack; prune Trie leaves after matches. The Trie prefix-sharing is the core optimization.Advanced₹499 (Pro plan required)Reported frequent at Databricks+2
  6. Given an array of integers and a target, return the indices of the two numbers that add up to the target (Two Sum). [Hash Map]Walk the array once, and for each number check whether its complement (target - num) has already been seen in a hash map that maps value to index. If it has, you have the answer; otherwise store the current number and index and continue. This gives an O(n) single-pass solution instead of the O(n^2) brute force.BeginnerFreeReported frequent at Amazon+1
  7. Merge k sorted lists into a single sorted list efficiently.Min-heap of the k list heads: pop the smallest, push the next from that list, with a list-index tiebreaker. O(N log k), O(k) space. Divide-and-conquer pairwise merge is an equivalent alternative. Relates directly to k-way merge of sorted runs in external sort / query engines.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at Netflix+1
  8. Find the k-th largest element in an unsorted array. [Heap]Maintain a min-heap of size k: push elements and pop the smallest whenever the heap exceeds k, so it always holds the k largest seen so far. After processing all elements, the heap's root is the k-th largest. This is O(n log k) time and O(k) space, better than a full O(n log n) sort when k is small.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at Apple+1
  9. Given n non-negative bar heights, compute how much rainwater can be trapped between them (Trapping Rain Water).Water over a bar = min(maxLeft, maxRight) - height. Two pointers move inward tracking leftMax/rightMax, always processing the shorter side (its wall is the binding constraint). O(n) time, O(1) space. Precomputed max arrays or a monotonic stack also work.Advanced₹499 (Pro plan required)Reported frequent at Flipkart+1
  10. Find the length of the longest substring without repeating characters. [Sliding Window]Slide a window over the string, tracking the last index at which each character was seen. When you hit a repeat that lies inside the current window, jump the window's left edge just past that previous occurrence. The answer is the maximum window size seen, computed in a single O(n) pass.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at Amazon+1
  11. Implement atoi: convert a string to a 32-bit signed integer, handling whitespace, sign, and overflow (String to Integer).Parse in strict order: skip spaces, read one optional sign, accumulate digits with num*10+d, stop at the first non-digit, and clamp to the 32-bit range on overflow. O(n). It's an edge-case exercise - enumerate spaces, sign, junk chars, and overflow aloud.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at Apple+1
  12. Given the root of a binary tree, return its vertical order traversal (LeetCode 987): group nodes by column from left to right, and within a column order nodes by row from top to bottom, breaking ties of the same row and column by smaller value first.Traverse with BFS or DFS carrying (row, col): root is (0,0), left child is (row+1, col-1), right child is (row+1, col+1). Bucket (row, value) pairs by column, then sort columns left to right and each column by (row, value). O(n log n) time because of sorting, O(n) space.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at Apple+1
  13. Given a reference to a node in a connected undirected graph, return a deep copy (clone) of the graph.BFS/DFS with a hash map from original node to its clone. Create a node's copy and record it in the map before recursing so cycles terminate, then clone and wire each neighbour. O(V+E). Same old->new map pattern clones any linked structure.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at Microsoft+1
  14. Design and implement an API rate limiter that allows at most N requests per client per time window. Compare fixed window, sliding window log and token bucket, and explain how to make it work across many servers.A rate limiter allowing N requests per window can use a sliding-window log: keep per-client timestamps, drop old ones, allow if fewer than N remain. Token bucket allows bursts at O(1) memory. Fixed windows can let 2N through at a boundary. Use Redis Lua for atomic distributed limits.Advanced₹499 (Pro plan required)Reported frequent at Apple+1
  15. Cheapest Flights Within K Stops: given n cities, a list of flights [from, to, price], a source, a destination and an integer K, return the cheapest price from source to destination with at most K stops, or -1 if it is not possible.Run Bellman-Ford for K+1 rounds, relaxing every flight against a copy of the previous round's distances so one round adds exactly one flight. dist[dst] is the answer, or -1 if infinite. Time O(K*E), space O(V). Dijkstra with (cost, node, flights used) state also works.Advanced₹499 (Pro plan required)Reported frequent at Airbnb+1
  16. Automata (complete the function): Complete the function to return the second largest element in an integer array of size n (assume distinct values, n >= 2).One pass tracking largest and second: if element > largest, demote largest to second and update largest; else if > second, update second. O(n) time, O(1) space. In Automata, fill only the function body - no main or extra prints.IntermediateFreeReported frequent at Cognizant
  17. Given a string of '(', ')' and letters, remove the minimum number of parentheses to make it valid (Minimum Remove to Make Valid Parentheses).Two passes with a stack of '(' indices: remove any ')' with no match immediately, then remove any '(' still unmatched at the end. Mark indices and rebuild the string. O(n). A ')' is invalid on sight; a '(' is invalid only if never closed.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at Meta
  18. Design a data structure that finds the median from a data stream, supporting addNum and findMedian.Two heaps: a max-heap for the lower half and a min-heap for the upper half, kept balanced. Median is the larger heap's top or the average of both tops. O(log n) insert, O(1) median. For unbounded streams mention t-digest; for rolling windows use an ordered multiset.Advanced₹499 (Pro plan required)Reported frequent at Netflix
  19. Determine whether a string is a valid palindrome, ignoring non-alphanumeric characters. [Two Pointers]Use two pointers starting at both ends, skipping any non-alphanumeric characters, and compare the lowercased characters as they move inward. If any pair mismatches it is not a palindrome; if the pointers cross, it is. This runs in O(n) time and O(1) space without building a cleaned copy of the string.BeginnerFreeReported frequent at Accenture
  20. Given a nested list of integers, return the sum of all integers weighted by their depth (an integer at depth d contributes value * d). Lists at the top level have depth 1. (LeetCode 339 - Nested List Weight Sum)DFS/BFS over the nested structure, adding value*depth for each integer and incrementing depth when you enter a sublist. O(N) time, O(D) space. Follow-up 364 inverts the weights - handle it with a running-sum BFS.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at LinkedIn
  21. Validate whether a binary tree is a valid binary search tree. [DFS]Recurse down the tree passing an allowed (low, high) range for each node's value, tightening the bound as you go left or right. A node is valid only if its value lies strictly inside its range and both subtrees are valid. Checking only a node against its immediate children is insufficient. Runs in O(n) time.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at Microsoft
  22. Design an algorithm to serialize a binary tree to a string and deserialize it back.Serialize via pre-order including explicit null markers so the shape is unambiguous; deserialize by consuming tokens in the same order, recursively building left then right. O(n) both ways. Null markers are what make reconstruction unique.Advanced₹499 (Pro plan required)Reported frequent at Microsoft
  23. Given an array of positive integers, determine whether it can be partitioned into two subsets with equal sum (Partition Equal Subset Sum).If total sum is odd, impossible. Else it reduces to subset-sum for S/2 via 1D boolean knapsack DP updated in reverse, giving O(n*sum/2) time and O(sum/2) space.Advanced₹99 (Interview Prep or Pro plan required)Reported frequent at Flipkart
  24. Return an array where each element is the product of all others without using division (Product of Array Except Self). [Prefix Sum]For each index, multiply everything to its left by everything to its right. Do it in two passes: fill the output array with prefix products, then sweep right to left with a running suffix product. This is O(n) time and O(1) extra space, and it avoids division, which would break on zeros.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at Google
  25. Automata (debug): The following function should return the factorial of n, but it returns wrong values. Find and fix the bug. int fact(int n){ int f = 0; for(int i=1;i<=n;i++) f = f * i; return f; }The accumulator f starts at 0, so every multiplication stays 0. Fix: initialize f = 1 (multiplicative identity). Then fact(5)=120. Bonus: use long long to avoid int overflow for larger n.BeginnerFreeReported frequent at Cognizant
  26. Determine whether a string of brackets ()[]{} is valid (properly balanced). [Stack]Push every opening bracket onto a stack; for every closing bracket, pop and check it matches the expected opener. The string is valid only if each closer matches the most recent unmatched opener and the stack is empty at the end. This is a single O(n) pass with O(n) space.BeginnerFreeReported frequent at Amazon
  27. Reverse a singly linked list, iteratively and recursively.Iteratively, walk the list and re-point each node's next to its predecessor, tracking previous and current nodes. Recursively, reverse the rest of the list, then make the next node point back to the current one. Both return the reversed head; iterative uses O(1) space, recursive O(n) call-stack space.BeginnerFreeReported frequent at Microsoft
  28. Coding: Given an integer array, print only the distinct elements in the order of their first appearance (remove duplicates).Use a HashSet to remember seen values; print each element the first time it appears. O(n) time, O(n) space, preserves order. A bounded boolean array works if the value range is small.BeginnerFreeReported frequent at Wipro
  29. Given course prerequisites, determine whether all courses can be finished. [Topological Sort]Model courses as nodes and prerequisites as directed edges; all courses are finishable if and only if the graph has no cycle. Use Kahn's algorithm: repeatedly remove nodes with no remaining prerequisites, and check that every node is processed. Leftover nodes mean a cycle. It runs in O(V + E).Advanced₹99 (Interview Prep or Pro plan required)Reported frequent at Swiggy
  30. Given an m x n integer matrix, return the length of the longest strictly increasing path (moves are 4-directional).Memoized DFS: dp[cell] = 1 + max over strictly-greater neighbours. The strict increase makes the grid a DAG, so each cell computes once - O(m*n). Without memo it's exponential.Advanced₹499 (Pro plan required)Reported frequent at Google
  31. Coding: Print the following numeric pattern for n rows (n=4 shown): 1 2 3 4 5 6 7 8 9 10Floyd's triangle: outer loop for rows 1..n, inner loop prints i numbers using a single running counter that never resets. O(n^2) time, O(1) space.Beginner₹99 (Interview Prep or Pro plan required)Reported frequent at Wipro
  32. Decode a string encoded as k[substring], where the substring is repeated k times, possibly nested (e.g. '3[a2[c]]' -> 'accaccacc').Use two stacks (previous string, previous count). On '[' push and reset; on ']' set cur = prevString + prevCount*cur; build multi-digit numbers with num*10+digit. O(output length). A recursive parser works too.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at Google
  33. Given a string, determine if it can be a palindrome after deleting at most one character (Valid Palindrome II).Two pointers inward until a mismatch; then check if skipping the left OR the right character yields a palindrome. O(n), O(1) space. You must test both sides at the mismatch - greedily picking one is the classic bug.IntermediateFreeReported frequent at Meta
  34. Given an array of integers and an integer k, return the total number of continuous subarrays whose sum equals k (Subarray Sum Equals K).Prefix sums + hash map of prefix-count; at each index add count[prefix - k] then record the prefix. Seed count[0]=1. O(n). Sliding window fails here because negatives break monotonicity - that's the key point to state.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at Meta
  35. Implement an iterator over an array of arrays (a nested list) that supports hasNext(), next(), and remove(). remove() deletes the last element returned by next() and may be called at most once per next() call, otherwise it throws.Track outer/inner cursors; hasNext() skips empty inner lists, next() records the position it returned, and remove() pops that position, adjusts the cursor, and nulls the record so a repeat remove() throws. Amortized O(1) traversal.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at Airbnb
  36. Given an integer array nums, find the contiguous subarray with the largest product and return that product. (LeetCode 152 - Maximum Product Subarray)Track both running max and running min product ending at each index because a negative flips them; swap on negatives and allow restarting at nums[i]. Answer is the best max seen. O(n) time, O(1) space.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at LinkedIn
  37. Design a data structure initialized with a list of words that efficiently answers repeated queries for the shortest distance between two given words. (LeetCode 244 - Shortest Word Distance II)Preprocess a map of word -> sorted index list, then answer each query with a two-pointer merge over the two lists, tracking the min gap. Constructor O(n), query O(a+b). The sorted lists make the merge correct.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at LinkedIn
  38. Implement an autocomplete / prefix-search feature using a Trie: insert words and, given a prefix, return all words with that prefix.Use a Trie: insert each word char by char (O(L)), walk to the prefix node, then DFS to gather all words below it. Insert and prefix lookup are O(word length), independent of dictionary size; add per-node frequencies for top-k suggestions.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at Swiggy
  39. Given the root of a binary tree, return the length of its diameter (the longest path between any two nodes, measured in edges).Post-order DFS returns each node's height while updating a global max with leftHeight + rightHeight (the path turning at that node). O(n). Return 1+max(L,R) as height but track L+R as the diameter - conflating them is the classic bug.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at Meta
  40. Given an undirected graph with n nodes and a list of edges, detect whether it contains a cycle using Union-Find (Disjoint Set Union).DSU with path compression and union by rank: for each edge, if both endpoints already share a root there is a cycle, else union them. O(E*alpha(V)). Works for undirected graphs; use DFS coloring for directed ones.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at LinkedIn
  41. Implement a Logger Rate Limiter: build a class with shouldPrintMessage(timestamp, message) that returns true only if the message has NOT been printed in the last 10 seconds; otherwise return false.Use a HashMap of message -> next-allowed timestamp (last + 10). Print and update only when timestamp >= the stored value; else reject. O(1) per call. Be ready to extend to sliding-window/token-bucket and to evict stale keys.IntermediateFreeReported frequent at Uber
  42. Given a binary tree, collect and return its nodes as if repeatedly removing all leaves until the tree is empty - each removal round is one list in the output. (LeetCode 366 - Find Leaves of Binary Tree)A node's removal round equals its height from the lowest leaf; compute heights bottom-up with post-order DFS and bucket node values by height in one pass. O(n) time, O(h) space - no repeated leaf stripping.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at LinkedIn
  43. What is the difference between an array and a linked list in data structures, and when would you use each?An array stores elements contiguously: O(1) index access and good cache locality, but O(n) insert or delete in the middle. A linked list links nodes by pointers: O(1) insert or delete at a known node, but O(n) to find it. In practice dynamic arrays win most of the time.BeginnerFreeReported frequent at Cognizant
  44. In a grid, cells are empty (0), fresh orange (1), or rotten (2). Each minute a rotten orange rots its 4-directional neighbours. Return the minimum minutes until no fresh orange remains, or -1 if impossible.Multi-source BFS: enqueue all rotten oranges at time 0, spread level by level, and count fresh oranges. Answer = levels elapsed, or -1 if any fresh remain. Seeding all sources at once models simultaneous spread.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at Amazon
  45. Given meeting time intervals, find the minimum number of conference rooms required (Meeting Rooms II).Answer = peak overlap. Sort by start and keep a min-heap of end times; reuse the earliest-ending room if it's free, else add a room. Heap size is the answer. O(n log n). Equivalent sweep-line: count starts before ends.Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at Google
  46. Given a list of listing records (host_id, listing_id, score, city) in a given order, split them into pages of a fixed size. On one page, two records should not share a host_id, unless there are not enough distinct-host records left to fill the page; then fill the page with the skipped records in their original order.For each page, scan the unused records in order, taking a record if its host is not yet on the page and skipping it otherwise. If the scan ends with a short page, fill the page from the skipped records in original order. Mark used records by index. Worst case O(N * pages) time, O(N) space.Intermediate₹499 (Pro plan required)Reported frequent at Airbnb
  47. Design and implement an LRU (Least Recently Used) cache in Python with O(1) get and put.An LRU cache uses a hash map from key to node plus a doubly linked list ordered by recency. get and put move the node to the head; when capacity is exceeded, remove the tail node and delete its key from the map. Sentinel head and tail nodes remove null checks. Every operation is O(1).Intermediate₹99 (Interview Prep or Pro plan required)Reported frequent at Amazon
  48. Given an input string, reverse the order of the words (Reverse Words in a String).Split on whitespace, reverse the word list, join with single spaces - O(n). The in-place char-array variant uses the double-reversal trick: reverse the whole string, then reverse each word, then trim spaces. Watch multiple/leading/trailing spaces.BeginnerFreeReported frequent at Microsoft
  49. Implement an in-memory file system in Python that supports the shell commands mkdir, cd, ls and pwd, with absolute and relative paths and clear errors.Model the file system as a tree of Dir nodes with a parent pointer and a children dict, plus a current-directory pointer. Write one path resolver that handles "/", ".", ".." and duplicate slashes; mkdir, cd, ls and pwd become thin wrappers. Each command is O(path length). Missing directories must raise a defined error.Advanced₹499 (Pro plan required)Reported frequent at Uber
  50. Count the number of distinct ways to travel N meters if in a single jump you can move 1, 2, 3, 4, or 5 meters. N can be very large.ways[i] = sum of ways[i-1..i-5] with ways[0]=1 — a linear DP in O(N)/O(1). For very large N, encode the recurrence as a 5x5 matrix and use matrix exponentiation for O(log N), usually under a modulus.Intermediate₹499 (Pro plan required)Reported frequent at Airbnb
  51. Given two strings word1 and word2, return the minimum number of insert, delete, or replace operations to convert word1 into word2 (Edit Distance).2D DP: dp[i][j] = dp[i-1][j-1] if chars match, else 1 + min(delete, insert, replace). Base rows/cols = string lengths. O(m*n) time, reducible to O(min(m,n)) space. Each term is one edit operation.Advanced₹99 (Interview Prep or Pro plan required)Reported frequent at Google
  52. Implement an LRU cache in Python and extend it to support a time-to-live (TTL) per entry, with lazy and active expiry.Build the LRU as a hash map plus doubly linked list and store an expiry time on each node. Lazy expiry checks the TTL on get and treats expired entries as misses. Active expiry uses a min-heap keyed by expiry (or a sweeper) to free dead entries early. Inject the clock for tests and add jitter to TTLs.Advanced₹499 (Pro plan required)Reported frequent at Netflix
  53. Design a Max Stack (LeetCode 716) that supports push, pop, top, peekMax and popMax, where popMax removes and returns the maximum element and, if there are several maximums, only the one closest to the top.Use a stack of (id, value) plus a max-heap keyed by (value, id), and track which ids are still alive. pop and popMax mark an id as deleted; top and peekMax first discard dead entries from their ends (lazy deletion). All operations are O(log n) amortised. A doubly linked list plus a sorted map gives true O(log n).Advanced₹499 (Pro plan required)Reported frequent at LinkedIn

Reported frequent at

Must-know questions for other tools