Skip to content
RED SAGSkills

Data Structures and Algorithms interview questions and answers

DSA questions are the core of most coding interviews and placement tests. They check whether you pick the right data structure and can reason about time and space complexity before you write code.

Below are 60 Data Structures and Algorithms questions with the correct answer and a short explanation, grouped from fresher to experienced level. Try each one before you open the answer.

What Data Structures and Algorithms interviews usually check

  • ✓Arrays, strings and two pointers
  • ✓Hash maps and sets
  • ✓Stacks, queues and heaps
  • ✓Trees and graphs: BFS and DFS
  • ✓Sorting, binary search and dynamic programming

Data Structures and Algorithms interview questions for freshers easy

1. Cost of reading arr[i]

An array of 10 lakh numbers is stored in memory. What is the time complexity of reading the element at index 7,50,000?

  1. A.O(n), because the array is scanned from the start
  2. B.O(log n), because the index is binary searched
  3. C.O(n log n), because the array is sorted first
  4. D.O(1), because the address is computed from the index
Show answer

Answer: D. O(1), because the address is computed from the index

Array elements sit in one contiguous block, so the address of element i is base + i × element size. That arithmetic takes the same time for any index, which is why random access in an array is O(1).

2. Best three-day sales window

Daily sales in thousands of ₹ are [2, 1, 5, 1, 3, 2]. What is the highest total for any 3 consecutive days?

  1. A.8
  2. B.10
  3. C.7
  4. D.9
Show answer

Answer: D. 9

The window sums are 2+1+5 = 8, 1+5+1 = 7, 5+1+3 = 9 and 1+3+2 = 6. The best is 9. A sliding window computes each next sum from the previous one in O(1).

3. Length of a window

A window covers indexes left to right inclusive. What is its length?

  1. A.right - left
  2. B.right - left + 1
  3. C.right + left
  4. D.right - left - 1
Show answer

Answer: B. right - left + 1

From index 2 to index 5 inclusive there are 4 elements: 5 - 2 + 1. Forgetting the + 1 is one of the most common off-by-one bugs in window problems.

4. Cost of prefix sum queries

You build a prefix sum array for n values and then answer q range-sum queries. What is the total cost?

  1. A.O(n × q)
  2. B.O(q log n)
  3. C.O(n + q)
  4. D.O(n²)
Show answer

Answer: C. O(n + q)

Building the prefix array is O(n), and each query is one subtraction, O(1). Without it, each query would cost up to O(n), giving O(n × q). This only works while the array does not change between queries.

5. Sliding window and negative numbers

The "shortest subarray with sum at least target" sliding window shrinks from the left once the sum reaches the target. When does this approach stop being correct?

  1. A.When the array can contain negative numbers
  2. B.When the target is larger than 100
  3. C.When the array has repeated values
  4. D.When the array length is odd
Show answer

Answer: A. When the array can contain negative numbers

The method relies on sums only growing as the window grows and only shrinking as it shrinks. Negative values break that, so removing an element can raise the sum. With negatives you need prefix sums with a monotonic deque instead.

6. Length of an emoji string

What does '😀'.length return in JavaScript?

  1. A.1
  2. B.4
  3. C.0
  4. D.2
Show answer

Answer: D. 2

JavaScript strings are sequences of UTF-16 code units, and characters outside the Basic Multilingual Plane, like most emoji, take two units (a surrogate pair). [...'😀'].length counts code points and gives 1.

7. What tabulation means

Which description matches tabulation in dynamic programming?

  1. A.Call the function recursively and cache the results
  2. B.Try every possible answer and keep the best one
  3. C.Fill a table from base cases up to the answer, in a fixed order
  4. D.Sort the input and scan it once from the left
Show answer

Answer: C. Fill a table from base cases up to the answer, in a fixed order

Tabulation computes small subproblems first and stores them in an array, so by the time you need a value it is ready. It avoids recursion and its stack limits. You must choose a fill order where each entry depends only on entries already filled.

8. When the greedy coin choice fails

Coins are 1, 3 and 4. Greedy always takes the largest coin that fits. For amount 6, how many coins does greedy use, and what is the true minimum?

  1. A.Greedy uses 2 coins; the minimum is 2
  2. B.Greedy uses 3 coins; the minimum is 3
  3. C.Greedy uses 4 coins; the minimum is 2
  4. D.Greedy uses 3 coins; the minimum is 2
Show answer

Answer: D. Greedy uses 3 coins; the minimum is 2

Greedy takes 4, then 1, then 1, which is 3 coins, but 3 + 3 uses only 2. For coin systems like this, the best first coin depends on what comes after, so you need DP over amounts. Greedy happens to work for standard currencies such as rupee and dirham notes.

9. Paths across a 3 × 7 grid

A robot starts at the top-left of a grid with 3 rows and 7 columns and can only move right or down. How many different paths reach the bottom-right cell?

  1. A.28
  2. B.21
  3. C.36
  4. D.10
Show answer

Answer: A. 28

Each path makes 2 down moves and 6 right moves, 8 moves in total, so the count is C(8, 2) = 28. The DP version sets paths[r][c] = paths[r - 1][c] + paths[r][c - 1], with 1 along the top row and left column. Both give the same answer.

10. Operations counted by edit distance

Levenshtein edit distance counts the fewest single-character operations to turn one string into another. Which operations are allowed?

  1. A.Insert and delete only
  2. B.Insert, delete and replace
  3. C.Swap adjacent characters only
  4. D.Replace only
Show answer

Answer: B. Insert, delete and replace

Levenshtein distance allows inserting, deleting or replacing one character, each with cost 1. Only insert and delete gives a different measure, tied to the LCS. Allowing swaps of neighbours gives the Damerau-Levenshtein distance.

11. Traversal for freeing a whole tree

In a language with manual memory management you must free every node of a binary tree. Which traversal makes sure no node is freed before its children?

  1. A.Preorder
  2. B.Inorder
  3. C.Postorder
  4. D.Level order
Show answer

Answer: C. Postorder

Postorder handles the left and right subtrees before the node itself. That means children are always freed before their parent, so you never lose the pointers you still need. The same order is used to evaluate expression trees and compute subtree sizes.

12. Edges in a complete graph

Ten branch offices are each connected to every other office by a direct link. How many links are there?

  1. A.45
  2. B.90
  3. C.100
  4. D.10
Show answer

Answer: A. 45

A complete undirected graph on n vertices has one edge per pair, which is n(n - 1) / 2. For 10 offices that is 10 × 9 / 2 = 45. Counting 90 would count each link twice, once from each end.

13. In-degree in a follower graph

In a directed graph, an edge A → B means "A follows B". What does the in-degree of a user tell you?

  1. A.How many accounts the user follows
  2. B.How many mutual friends the user has
  3. C.How many followers the user has
  4. D.How far the user is from the most popular user
Show answer

Answer: C. How many followers the user has

In-degree counts edges coming into a vertex, and every edge into B is someone following B. Out-degree counts edges going out, which is how many accounts the user follows. Getting the direction right matters when building feeds and recommendations.

14. Cost of Floyd-Warshall

What is the time complexity of the Floyd-Warshall all-pairs shortest path algorithm on V vertices?

  1. A.O(V^2)
  2. B.O(V × E)
  3. C.O(E log V)
  4. D.O(V^3)
Show answer

Answer: D. O(V^3)

Floyd-Warshall runs three nested loops over the vertices: for each middle vertex k, it tries to improve every pair (i, j). That is V × V × V steps, with O(V^2) memory for the distance table. It suits dense graphs with a few hundred vertices.

15. Two Sum with a hash map

For each number x you check whether target - x is already in a map of seen values, then add x. What is the time complexity for n numbers?

  1. A.O(n²)
  2. B.O(n log n)
  3. C.O(n)
  4. D.O(log n)
Show answer

Answer: C. O(n)

Each element costs one O(1) average lookup and one O(1) insert, so the whole pass is O(n). The brute force of checking every pair is O(n²).

16. Counting with getOrDefault in Java

Which Java line safely increments the count for word w in a HashMap<String, Integer> called counts?

  1. A.counts.get(w)++ after a containsKey check
  2. B.counts.put(w, counts.getOrDefault(w, 0) + 1)
  3. C.counts.put(w, counts.get(w) + 1)
  4. D.counts.add(w, counts.size() + 1)
Show answer

Answer: B. counts.put(w, counts.getOrDefault(w, 0) + 1)

For a new word, counts.get(w) returns null, and unboxing null throws NullPointerException. getOrDefault supplies 0. counts.merge(w, 1, Integer::sum) is an even shorter option.

17. What HashSet.add returns

In Java, what does set.add("INV-101") return if "INV-101" is already in the HashSet?

  1. A.true
  2. B.null
  3. C.false
  4. D.It throws an exception
Show answer

Answer: C. false

add returns true if the element was new and false if it was already present, leaving the set unchanged. That makes "if (!seen.add(x)) duplicate found" a neat one-step check.

18. Swaps made by selection sort

Selection sort is sometimes chosen when writes are expensive (for example, on flash memory). How many swaps does it make on an array of n items in the worst case?

  1. A.About n^2 / 2 swaps
  2. B.About n log n swaps
  3. C.At most n - 1 swaps
  4. D.Exactly n^2 swaps
Show answer

Answer: C. At most n - 1 swaps

Each pass finds the minimum of the unsorted part and does one swap to put it in place, so there are at most n - 1 swaps. Its comparisons are still O(n^2), but the low write count is its one real strength.

19. Extra memory used by merge sort

How much extra memory does a standard merge sort on an array need?

  1. A.O(1), it works fully in place
  2. B.O(n^2) for all the sub-arrays
  3. C.O(log n) and nothing more
  4. D.O(n) for the merge buffer
Show answer

Answer: D. O(n) for the merge buffer

Merging two sorted halves into one needs a temporary buffer as large as the data being merged, which is O(n). Linked-list merge sort avoids this because it can relink nodes instead of copying.

20. Java Arrays.binarySearch when not found

What does Java's Arrays.binarySearch(new int[]{10, 20, 30, 40}, 25) return?

  1. A.-3
  2. B.-1
  3. C.2
  4. D.-2
Show answer

Answer: A. -3

When the key is missing, Java returns -(insertion point) - 1. The insertion point for 25 is index 2, so the result is -2 - 1 = -3. The minus one makes sure "not found" is negative even when the insertion point is 0.

Data Structures and Algorithms intermediate interview questions medium

21. Remove duplicates from a sorted array

You remove duplicates in place from the sorted array below using a slow and fast pointer, returning the count k of unique values. What is k?

[0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
  1. A.4
  2. B.6
  3. C.5
  4. D.10
Show answer

Answer: C. 5

The unique values are 0, 1, 2, 3 and 4, so k = 5 and the first five slots become [0, 1, 2, 3, 4]. The slow pointer marks where the next unique value goes, and the fast pointer scans, copying only when it sees a new value.

22. Subarrays with product under k

How many contiguous subarrays of [10, 5, 2, 6] have a product strictly less than 100?

  1. A.8
  2. B.7
  3. C.10
  4. D.6
Show answer

Answer: A. 8

With a sliding window, each new right end adds (right - left + 1) subarrays ending there: 1 for [10], 2 for [5] and [10, 5], 2 for [2] and [5, 2] after [10, 5, 2] = 100 forces left forward, and 3 for [6], [2, 6], [5, 2, 6]. Total 1 + 2 + 2 + 3 = 8.

23. Intersect two schedules

Two sorted lists of free slots are A = [[0, 2], [5, 10]] and B = [[1, 5], [8, 12]]. What is their intersection?

  1. A.[[1, 2], [8, 10]]
  2. B.[[1, 2], [5, 5], [8, 10]]
  3. C.[[0, 12]]
  4. D.[[1, 5], [8, 10]]
Show answer

Answer: B. [[1, 2], [5, 5], [8, 10]]

Each overlap is [max(starts), min(ends)] when that is not empty. [0, 2] with [1, 5] gives [1, 2]; [5, 10] with [1, 5] gives [5, 5]; [5, 10] with [8, 12] gives [8, 10]. Advance whichever interval ends first.

24. Minimum of a rotated sorted array

To find the minimum of [4, 5, 6, 7, 0, 1, 2] in O(log n), which comparison decides the side?

  1. A.If a[mid] > a[lo], the minimum is left of mid
  2. B.If a[mid] is even, go left
  3. C.If a[mid] > a[hi], the minimum is right of mid
  4. D.If a[mid] < target, go right
Show answer

Answer: C. If a[mid] > a[hi], the minimum is right of mid

If a[mid] > a[hi], the drop from large to small happens after mid, so set lo = mid + 1. Otherwise the minimum is at mid or left of it, so set hi = mid. Here the search ends on 0.

25. Largest sum of a contiguous block

Daily profit changes are [-2, 1, -3, 4, -1, 2, 1, -5, 4]. What is the largest sum of any contiguous block of days?

  1. A.4
  2. B.5
  3. C.6
  4. D.7
Show answer

Answer: C. 6

Kadane’s algorithm keeps the best sum ending at each day: either extend the previous block or start fresh. The best block is [4, -1, 2, 1], which sums to 6. It runs in one O(n) pass with O(1) memory.

26. Stock trading with a cooldown day

You may trade many times, but after selling you must wait one day before buying. For prices [1, 2, 3, 0, 2], what is the largest profit?

  1. A.3
  2. B.2
  3. C.4
  4. D.5
Show answer

Answer: A. 3

Buy at 1, sell at 2, rest on the day priced 3, buy at 0, sell at 2: 1 + 2 = 3. The DP keeps three states per day: holding, just sold, and resting. Ignoring the cooldown would allow 2 + 2 = 4, which breaks the rule.

27. Direction of the capacity loop

In the 1D 0/1 knapsack, dp[w] = max(dp[w], dp[w - wt] + val). Why must w go from W down to wt?

  1. A.Going up would let an item be reused
  2. B.Going up gives an index out of range
  3. C.Going down is faster for the CPU cache
  4. D.Going up skips the base case
Show answer

Answer: A. Going up would let an item be reused

When w goes up, dp[w - wt] may already include the current item from earlier in the same loop, so the item gets reused. Going down means dp[w - wt] still holds the value from before this item. Looping up is exactly the unbounded knapsack.

28. Finding any key in a binary heap

A min-heap of 1 million delivery tasks is keyed by deadline. How long does it take to check whether a specific deadline exists in it?

  1. A.O(log n), by following the heap path
  2. B.O(1), because the heap is an array
  3. C.O(n), because a heap orders only parent and child
  4. D.O(log^2 n), using binary search on each level
Show answer

Answer: C. O(n), because a heap orders only parent and child

A heap only guarantees that each parent is not larger than its children; siblings and cousins are in no useful order. So finding an arbitrary key means scanning the array. Heaps are fast for the minimum (O(1)) and for push and pop (O(log n)), not for search.

29. When a graph cannot be two-coloured

You try to split players into two teams so that rivals are always on different teams, using BFS 2-colouring. When must it fail?

  1. A.When the graph has any cycle at all
  2. B.When some player has more than two rivals
  3. C.When the graph is disconnected
  4. D.When the rivalry graph has a cycle of odd length
Show answer

Answer: D. When the rivalry graph has a cycle of odd length

Colours must alternate along every edge, so walking around an odd cycle forces a node to have both colours. A graph is bipartite exactly when it has no odd cycles. Disconnected graphs are fine if you start a new BFS in each component.

30. A JavaScript BFS that gets slow

This BFS on a graph with 10^6 nodes is far slower than expected. What is the main cause?

const queue = [start]
while (queue.length) {
  const u = queue.shift()
  for (const v of adj[u]) if (!seen[v]) { seen[v] = true; queue.push(v) }
}
  1. A.push() is O(n) on large arrays
  2. B.The seen array should be a Set to be correct
  3. C.for...of cannot iterate arrays efficiently
  4. D.shift() can be O(n), so the loop can become O(V^2)
Show answer

Answer: D. shift() can be O(n), so the loop can become O(V^2)

Removing the first element of a JavaScript array can move every remaining element, so with a large queue each shift() is costly. Keep a head index and read queue[head++] instead, or use a ring-buffer queue. That keeps BFS at O(V + E).

31. Order of steps in Two Sum

In one-pass Two Sum, why do you look up target - x before adding x to the map?

  1. A.So x is never paired with itself
  2. B.Because lookups are faster than inserts
  3. C.So the map stays sorted
  4. D.To use less memory
Show answer

Answer: A. So x is never paired with itself

For target 6 and nums [3, 2, 4], inserting 3 first and then looking up 3 would wrongly pair index 0 with itself. Checking first means the map only holds earlier indexes, while [3, 3] still works because the first 3 is already there when the second arrives.

32. Longest subarray with equal 0s and 1s

Treating 0 as -1, you track the first index of each running sum. What is the longest subarray of [0, 1, 0] with equal 0s and 1s?

  1. A.3
  2. B.1
  3. C.0
  4. D.2
Show answer

Answer: D. 2

Running sums with 0 as -1 are -1, 0, -1. The sum -1 first appears at index 0 and again at index 2, giving length 2; the sum 0 is seeded at index -1 and appears at index 1, also length 2. Storing only the first index of each sum gives the longest span.

33. Bulls and Cows hint

The secret is "1807" and the guess is "7810". Bulls are right digit in the right place; cows are right digit in the wrong place. What is the hint?

  1. A.2A2B
  2. B.1A2B
  3. C.1A3B
  4. D.0A4B
Show answer

Answer: C. 1A3B

Only 8 is in the same position, so 1 bull. The remaining secret digits 1, 0, 7 and guess digits 7, 1, 0 match as a multiset, so 3 cows. Count unmatched digits from each side and add the minimum per digit.

34. Inverting a map with repeated values

You invert { Asha: 'Dubai', Ravi: 'Pune', Meena: 'Dubai' } into city → name with a simple loop. What is the result?

  1. A.{ Dubai: 'Asha', Pune: 'Ravi' }
  2. B.{ Dubai: ['Asha', 'Meena'], Pune: 'Ravi' }
  3. C.{ Dubai: 'Meena', Pune: 'Ravi' }
  4. D.It throws a duplicate key error
Show answer

Answer: C. { Dubai: 'Meena', Pune: 'Ravi' }

Both Asha and Meena map to Dubai, so the later write overwrites the earlier one and Asha is lost silently. When values can repeat, invert into city → list of names instead.

35. Finding the final city of a trip

Routes are [["London", "New York"], ["New York", "Lima"], ["Lima", "Sao Paulo"]]. Which city has no outgoing route?

  1. A.London
  2. B.Sao Paulo
  3. C.Lima
  4. D.New York
Show answer

Answer: B. Sao Paulo

Put every starting city in a Set, then return the destination not in that Set. London, New York and Lima all have an outgoing route, so the trip ends in Sao Paulo, in O(n).

36. Why quick sort uses a random pivot

An API sorts user lists with a quick sort that always picks the first element as the pivot. Requests with already sorted lists are very slow. What is the standard fix?

  1. A.Switch the pivot to always be the second element
  2. B.Sort the list twice to warm up the CPU cache
  3. C.Reverse the list before sorting it
  4. D.Choose the pivot at random or by median-of-three
Show answer

Answer: D. Choose the pivot at random or by median-of-three

A fixed first or last pivot gives the worst split on sorted or reverse-sorted input. A random pivot, or the median of first, middle and last, makes bad splits very unlikely, giving expected O(n log n). Reversing just moves the problem to another input pattern.

37. Solving T(n) = 4T(n/2) + n

Using the master theorem, what does T(n) = 4T(n/2) + O(n) solve to?

  1. A.O(n log n)
  2. B.O(n^2)
  3. C.O(n^2 log n)
  4. D.O(n)
Show answer

Answer: B. O(n^2)

Here a = 4 and b = 2, so n^(log2 4) = n^2. That grows faster than the O(n) combine work, so the leaves dominate and the result is O(n^2). Splitting into four half-size problems doubles the work at each level.

38. Running time of quickselect

Quickselect finds the k-th smallest value by partitioning and recursing into only one side. What are its average and worst-case times?

  1. A.O(n) average, O(n^2) worst
  2. B.O(n log n) average, O(n log n) worst
  3. C.O(log n) average, O(n) worst
  4. D.O(n) average, O(n) worst
Show answer

Answer: A. O(n) average, O(n^2) worst

With random pivots, the sizes shrink geometrically: n + n/2 + n/4 + ... is about 2n, so the average is O(n). Consistently bad pivots shrink the size by one each time, which gives O(n^2).

39. Stock span problem

The stock span on a day is the number of days in a row, ending today, with price at or below today's. For prices [100, 80, 60, 70, 60, 75, 85], what is the span on the day the price is 75?

  1. A.2
  2. B.5
  3. C.3
  4. D.4
Show answer

Answer: D. 4

Going back from 75: 60, 70 and 60 are all at or below 75, but 80 is higher, so the span covers 4 days including today. A stack holding (price, span) pairs merges spans as it pops, giving O(n) overall.

40. Merging two sorted linked lists

You merge two sorted linked lists of sizes m and n by relinking nodes. What are the time and extra space?

  1. A.O(m x n) time, O(1) extra space
  2. B.O(m + n) time, O(m + n) extra space
  3. C.O(m + n) time, O(1) extra space
  4. D.O((m + n) log(m + n)) time, O(1) space
Show answer

Answer: C. O(m + n) time, O(1) extra space

Each step compares the two current heads and links the smaller one onto the result, so each node is handled once. No new nodes are created, so the extra space is just a few pointers when done iteratively.

Data Structures and Algorithms interview questions for experienced candidates hard

41. Smallest missing positive integer

What is the smallest missing positive integer in [3, 4, -1, 1], and which O(n), O(1)-space idea finds it?

  1. A.2, by swapping each value v into index v - 1
  2. B.2, by sorting and scanning
  3. C.5, by taking the maximum plus one
  4. D.1, by checking for negatives
Show answer

Answer: A. 2, by swapping each value v into index v - 1

The answer must lie in 1 to n + 1, so you can use the array itself as a lookup table: keep swapping value v to index v - 1 when it is in range. Then the first index i where a[i] is not i + 1 gives the answer. After placement the array is [1, -1, 3, 4], so the answer is 2.

42. Quickselect for the k-th largest

You use quickselect to find the 10th largest order value in an array. What is its time complexity?

  1. A.O(n log n) in every case
  2. B.O(log n) on average, O(n) at worst
  3. C.O(n) on average, O(n²) in the worst case
  4. D.O(k log n) in every case
Show answer

Answer: C. O(n) on average, O(n²) in the worst case

Quickselect partitions like quicksort but recurses into only one side, so the expected work is n + n/2 + n/4 ... = O(n). Bad pivots, for example always the first element on sorted data, can make it O(n²); random pivots make that very unlikely. A size-k heap gives O(n log k) guaranteed.

43. Reversing a string that has emoji

What goes wrong with 'Hi 👋'.split('').reverse().join('')?

  1. A.It throws a RangeError for non-ASCII input
  2. B.The space is dropped from the output
  3. C.The emoji is split into two halves and becomes garbled
  4. D.Nothing, it prints the correct reverse string
Show answer

Answer: C. The emoji is split into two halves and becomes garbled

split('') splits by UTF-16 code units, and 👋 is a surrogate pair of two units. Reversing swaps the halves into an invalid sequence. [...s] or Array.from(s) splits by code point, and Intl.Segmenter is needed for multi-code-point emoji such as flags or family emoji.

44. Maximum sum of a circular subarray

For a circular array, the best sum is max(normal Kadane, total - minimum subarray). What edge case must you handle?

  1. A.An array of length 2 with one zero
  2. B.All negative: total - min is 0 for an empty subarray
  3. C.Arrays whose total sum is positive
  4. D.Arrays that are already sorted ascending
Show answer

Answer: B. All negative: total - min is 0 for an empty subarray

If every value is negative, the minimum subarray is the whole array and total - min = 0, which means taking nothing. In that case return the normal Kadane result, the largest element. For [5, -3, 5] the wrap-around answer is 7 - (-3) = 10.

45. The non-shrinking window trick

Some solutions for "longest valid window" use if instead of while when shrinking, so the window never gets smaller. Why does that still give the correct maximum length?

  1. A.The window only needs to grow when a longer valid one appears
  2. B.if and while behave the same in this loop
  3. C.The window is always valid at every step
  4. D.It finds the shortest window, which equals the longest
Show answer

Answer: A. The window only needs to grow when a longer valid one appears

Moving left by one each time right moves keeps the window at its best size so far. It may be temporarily invalid, but it only grows when a longer valid window exists. The final window size equals the answer, though its contents may not be a valid window.

46. Why the max deque stores indexes

In the sliding window maximum solution, why does the deque hold indexes instead of values?

  1. A.You need to know when the front has left the window
  2. B.Indexes use less memory than numbers
  3. C.Values cannot be compared inside a deque
  4. D.It makes the output sorted
Show answer

Answer: A. You need to know when the front has left the window

The front must be removed once it falls outside [i - k + 1, i], and only its index tells you that. With values alone you also cannot tell apart two equal values at different positions.

47. Common free time across many calendars

Each of k employees has a sorted list of busy intervals, N intervals in total. What is a good way to find the free time common to all?

  1. A.Intersect each pair of calendars separately
  2. B.Take the free time of the busiest employee
  3. C.Sort employees by number of meetings
  4. D.Merge all busy intervals, take the gaps
Show answer

Answer: D. Merge all busy intervals, take the gaps

Free time for everyone is time when nobody is busy, which is the gaps between merged busy intervals. Merge the k sorted lists with a min-heap in O(N log k), or sort all N in O(N log N), then read the gaps.

48. A memo cache in a long-running server

A Node.js API memoises a pricing function in a module-level Map keyed by request parameters. After a few days, memory keeps climbing. What is the right fix?

  1. A.Move the Map inside the function so it is local
  2. B.Add more RAM to the server
  3. C.Call the function twice per request
  4. D.Use a bounded cache, such as LRU with a size limit or TTL
Show answer

Answer: D. Use a bounded cache, such as LRU with a size limit or TTL

A DP memo is meant for one computation, but a global Map in a server keeps every key forever, so it leaks memory as new parameters arrive. An LRU or TTL cache keeps memory bounded while keeping the hot results. A cache inside the function would be rebuilt each call and stop helping across calls.

49. The "tight" flag in digit DP

You count numbers from 0 to N with some digit property using digit DP. What does the "tight" flag in the state track?

  1. A.Whether the number built so far is even
  2. B.Whether all the earlier digits are equal
  3. C.Whether the digits so far equal N’s prefix
  4. D.Whether the running count has overflowed
Show answer

Answer: C. Whether the digits so far equal N’s prefix

While the digits chosen so far match N exactly, the next digit cannot exceed N’s digit at that position. Once you choose a smaller digit, the rest is free to be 0 to 9. The state is usually (position, tight, plus whatever the property needs), giving a small table instead of looping to N.

50. Balanced strings of three bracket pairs

How many balanced strings can be made from 3 pairs of parentheses, such as "(())()"?

  1. A.6
  2. B.5
  3. C.3
  4. D.8
Show answer

Answer: B. 5

They are ((())), (()()), (())(), ()(()) and ()()(). Backtracking adds "(" while fewer than n are used and ")" only while it would not exceed the opens, so it never builds an invalid string. The count is the Catalan number C3 = 5.

51. CPU tasks with a cooldown

Tasks are A, A, A, B, B, B, and the same task needs at least 2 slots between runs. What is the fewest total slots, including idle ones?

  1. A.6
  2. B.7
  3. C.8
  4. D.9
Show answer

Answer: C. 8

One best schedule is A B idle A B idle A B. The formula is (maxCount - 1) × (n + 1) + tasksWithMaxCount = (3 - 1) × 3 + 2 = 8. If there are many different tasks, the answer is just the task count, since no idles are needed.

52. Fixing a BST with two swapped keys

Two keys in a BST were swapped by mistake. The inorder sequence is 1 2 4 3 5. Which keys must be swapped back?

  1. A.2 and 4
  2. B.4 and 3
  3. C.3 and 5
  4. D.1 and 5
Show answer

Answer: B. 4 and 3

An inorder traversal of a valid BST is strictly increasing, so any drop shows a swap. Here there is only one drop, 4 > 3, which means the swapped keys are next to each other, so you swap those two. When two drops appear, you swap the first element of the first drop with the second element of the second drop.

53. False cycle alarm in a dependency graph

A build tool reports a cycle whenever DFS meets an already visited node. For edges A → B, A → C, B → D, C → D, what goes wrong?

  1. A.It misses the cycle between B and C
  2. B.It is correct, since A → B → D and A → C → D form a cycle
  3. C.It never visits D
  4. D.It reports a cycle at D, though the graph is acyclic
Show answer

Answer: D. It reports a cycle at D, though the graph is acyclic

D is reached twice through two separate paths, which is a diamond, not a cycle. In directed graphs you must track nodes on the current recursion path (gray) separately from finished nodes (black). Only an edge back to a gray node is a cycle.

54. Checking 2-SAT with strongly connected components

In 2-SAT, each clause (a OR b) becomes edges ¬a → b and ¬b → a. When is the formula unsatisfiable?

  1. A.When the implication graph has any cycle
  2. B.When some x and ¬x are in the same SCC
  3. C.When some variable appears in more than two clauses
  4. D.When the graph has more edges than nodes
Show answer

Answer: B. When some x and ¬x are in the same SCC

If x and ¬x are in one SCC, then x forces ¬x and ¬x forces x, so no value works. Otherwise you can assign values using the topological order of the condensation. Cycles alone are fine, as long as they do not contain both a variable and its negation.

55. Two Java strings with the same hashCode

Java computes String.hashCode as s[0]×31^(n-1) + ... + s[n-1]. Which pair collides?

  1. A."ab" and "ba"
  2. B."AA" and "aa"
  3. C."Aa" and "BB"
  4. D."A" and "a"
Show answer

Answer: C. "Aa" and "BB"

"Aa" is 65 × 31 + 97 = 2112 and "BB" is 66 × 31 + 66 = 2112. Concatenating such blocks yields many strings with one hash, which was the basis of hash flooding attacks on Java web servers. Java 8 treeified buckets partly in response.

56. Distinct values in every window

What are the counts of distinct values in every window of size 4 in [1, 2, 1, 3, 4, 2, 3]?

  1. A.[3, 3, 4, 3]
  2. B.[4, 4, 4, 4]
  3. C.[3, 4, 4, 3]
  4. D.[3, 4, 3, 3]
Show answer

Answer: C. [3, 4, 4, 3]

Windows are [1, 2, 1, 3] → 3, [2, 1, 3, 4] → 4, [1, 3, 4, 2] → 4, [3, 4, 2, 3] → 3. Keep a count map: add the entering value, decrement the leaving one and delete it at zero, and read map.size, all O(1) per step.

57. C++ sort versus stable_sort

A C++ service sorts trades by price with std::sort, and equal-price trades lose their arrival order. What is the correct fix?

  1. A.Call std::sort twice in a row on the data
  2. B.Pass a comparator that uses <= instead of <
  3. C.Use std::stable_sort or add a tie-breaker
  4. D.Reserve more capacity in the vector first
Show answer

Answer: C. Use std::stable_sort or add a tie-breaker

std::sort is not stable. std::stable_sort is, usually through merge sort. A comparator with <= breaks the strict weak ordering rule and is undefined behaviour, which can even crash.

58. Duplicate number by counting values

An array of n + 1 integers holds values from 1 to n, so at least one repeats. You may not change the array or use extra memory. How does binary search help?

  1. A.Sort a copy, then search for equal neighbours
  2. B.Binary search the indices, as the array is sorted
  3. C.It does not help here; only hashing can work
  4. D.If over mid values are <= mid, the duplicate is <= mid
Show answer

Answer: D. If over mid values are <= mid, the duplicate is <= mid

By the pigeonhole principle, if more than mid values fall in [1, mid], a duplicate lies there. Each check is an O(n) count, so the total is O(n log n) with O(1) space. Floyd's cycle detection does it in O(n).

59. Place items to maximise the minimum gap

Stalls are at positions [1, 2, 4, 8, 9]. You must place 3 cows in stalls so that the smallest distance between any two cows is as large as possible. What is that distance?

  1. A.4
  2. B.2
  3. C.3
  4. D.5
Show answer

Answer: C. 3

Binary search the distance d, placing cows greedily from the left. For d = 3: cows at 1, 4 and 8 work. For d = 4: 1, then 8, and no stall is 4 or more past 8, so only 2 cows fit. The answer is 3.

60. Managing millions of timers

A server tracks idle timeouts for 2 million connections, and most timers are reset before they fire. Why might it use a hashed timing wheel instead of a binary heap?

  1. A.A heap cannot store more than 1 million timers
  2. B.Wheel insert and cancel are O(1), versus O(log n) in a heap
  3. C.Timing wheels fire timers with nanosecond accuracy
  4. D.A heap must be re-sorted every tick
Show answer

Answer: B. Wheel insert and cancel are O(1), versus O(log n) in a heap

A timing wheel is a circular array of buckets, one per tick, so adding or removing a timer is O(1). That suits huge numbers of timers that are mostly cancelled. The trade-off is coarser precision, set by the tick size. Netty and Kafka use timing wheels.

Ready to test yourself?

Take a 15-question Data Structures and Algorithms MCQ test with a score at the end, or practise the full Data Structures and Algorithms question bank and earn points on the leaderboard.