Level:
No questions match — try other words or turn a level back on.
1
What does Big O notation measure, and why is it the first thing asked in an interview?
Big O shows how fast an algorithm's time or memory grows as the input size n grows. It gives you the shape of the growth, not exact milliseconds, which makes it the quickest way to compare solutions.
2
Give a Java example for each of O(1), O(log n), O(n) and O(n²).
O(1) is HashMap.get or reading an array by index; O(log n) is binary search; O(n) is one pass over a list; O(n²) is a nested loop that compares every element with every other.
3
What do index access and inserting in the middle cost in ArrayList and LinkedList?
ArrayList.get(i) is O(1), and inserting in the middle is O(n) because elements are shifted. LinkedList.get(i) is O(n); the insertion itself is O(1), but getting to that spot is O(n) anyway.
4
Reverse an array in place, without allocating another array.
Take two pointers, one at the start and one at the end. Swap them, move toward each other, and stop when they meet. Time is O(n), extra memory is O(1).
5
How do you check whether a string is a palindrome, ignoring spaces and letter case?
With two pointers: from the left and right I skip characters that aren't letters or digits, lowercase the rest and compare. No new string is built, time is O(n), memory is O(1).
6
How do you find the largest and second largest values in an array in a single pass?
I keep two variables, first and second. If a new number is greater than first, the old one drops into second; if it's greater only than second, second is updated. No sorting is needed, and time is O(n).
7
How do you check whether two words are anagrams of each other?
Count how many times each letter occurs, and if the two words give the same counts, they are anagrams. If it's only lowercase Latin letters, an int[] with 26 cells is enough, and time is O(n). Sorting and comparing works too, but it's O(n log n).
8
What is the difference between linear search and binary search, and what condition does binary search need?
Linear search checks the elements one by one: O(n), and it works on any array. Binary search halves the range at every step: O(log n), but the array must be sorted beforehand.
9
Write binary search iteratively and explain the trap in computing the midpoint.
I keep the lo and hi bounds, compare the middle element with the target and discard the half I don't need. I compute the midpoint as lo + (hi - lo) / 2, because (lo + hi) / 2 causes an int overflow on large indexes.
10
What is recursion, and what happens if there is no base case?
Recursion is a method calling itself with a smaller problem. The base case is the condition that stops the calls. If it's missing or never reached, the stack fills up and you get a StackOverflowError.
11
Why is computing a Fibonacci number with plain recursion so slow, and how do you fix it?
fib(n-1) + fib(n-2) computes the same values over and over, and the number of calls grows roughly as 2ⁿ. Remembering the results (memoization) or using a plain loop brings it down to O(n).
12
How do you quickly find out whether an array contains a duplicate element?
I add elements to a HashSet one by one: if add returns false, that element was seen before. Time is O(n) on average, memory is O(n). If memory is tight, you can sort and compare neighbors, which is O(n log n).
13
What is the difference between a Stack and a Queue, and which class is best to use for them in Java?
A stack is last in, first out (LIFO); a queue is first in, first out (FIFO). ArrayDeque is recommended for both; the old Stack class is synchronized and outdated.
14
Write a function that checks whether a sequence of brackets is correctly closed: "([]{})" is valid, "(]" is not.
I push opening brackets onto a stack, and when a closing bracket arrives I check that it matches the top of the stack. At the end the stack must be empty. Time is O(n), memory is O(n) in the worst case.
15
How does bubble sort work, and why wouldn't you use it in real code?
It compares neighboring elements and swaps the ones in the wrong order; on each pass the largest "floats up" to the end. Time is O(n²), so in real code you use Arrays.sort or List.sort instead.
16
Which algorithm runs inside Arrays.sort, and is there a difference between a primitive array and an object array?
Yes. For primitive arrays (int[], double[]) it uses a dual-pivot quicksort, which is fast but not stable. For object arrays and List.sort it uses TimSort, which is stable and guaranteed O(n log n).
17
Sort a list by last name, then by first name, with null last names at the end.
I build a chain with Comparator.comparing(User::lastName, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(User::firstName) and pass it to list.sort(...). Because the sort is stable, the order of equal elements is preserved.
18
How do you count how many times each word occurs in a text?
I split the text into words and write them to a HashMap<String, Integer> with merge(word, 1, Integer::sum). With streams, Collectors.groupingBy(w -> w, Collectors.counting()) works too. Time is O(n).
19
How do you merge two sorted arrays into one sorted array?
I put one pointer on each array, write the smaller element to the result and advance that pointer. When one array runs out, I copy the rest of the other. Time is O(n + m), and no re-sorting is needed.
20
What is the time complexity of the following method?
O(n log n). The outer loop runs n times, and the inner one runs about log₂n times, because it doubles j each time. They don't depend on each other, so you multiply.
21
Find the indexes of two elements in an array whose sum equals a given number, in O(n).
I walk the array once, and for each number I check in a HashMap whether target - number was seen earlier. If it was, we found the pair; if not, I put the current number into the map with its index.
22
When does the two pointers technique work? Show it with removing duplicates from a sorted array in place.
It works when the data is sorted, or when walking from both ends makes sense. For duplicates, the slow pointer marks where the next unique value gets written, and the fast pointer marks the element being read. O(n) time, O(1) memory.
23
How do you find the maximum sum of k consecutive elements in an array?
With a sliding window: I compute the sum of the first k elements, and as the window moves by one I add the new element and subtract the one that left. Each step is O(1), so the total is O(n); re-summing every window would be O(n·k).
24
Find the length of the longest substring without repeating characters.
With a variable window: I advance the right edge and keep each character's last seen index in a map. If a repeated character is inside the window, I jump the left edge to the position right after it. O(n).
25
Reverse a singly linked list.
With three references: prev, cur and next. At each step I point cur.next at prev and move all three one step forward. At the end prev becomes the new head. O(n) time, O(1) memory.
26
How do you detect a cycle in a linked list without extra memory?
Floyd's method: the slow pointer moves one step, the fast pointer moves two. If there is a cycle, they are guaranteed to meet; if the fast pointer reaches null, there is no cycle. O(n) time, O(1) memory.
27
ArrayList.add is called amortized O(1). What does amortized mean?
Some calls are expensive (when the internal array is full, copying to a bigger array is O(n)), but they are rare. Averaged over many calls, the cost per add comes out constant.
28
What is a stable sort, and when does it change the result?
A stable sort preserves the original relative order of elements with equal keys. The difference shows up when you sort by several fields in stages, or when the earlier order has meaning.
29
If an array gets many "sum from i to j" queries, how do you answer each in O(1)?
I build a prefix sum array once: pre[i] is the sum of the first i elements. Then the sum of the range [i, j] is pre[j + 1] - pre[i]. Building is O(n), each query is O(1).
30
Rotate an array to the right by k steps, without allocating another array.
With three reversals: the whole array, then the first k elements, then the rest. First I do k %= n, because k can be larger than the array length. O(n) time, O(1) memory.
31
How do BFS and DFS differ, and which do you choose depending on the problem?
BFS goes layer by layer with a queue and gives the shortest path in an unweighted graph. DFS goes as deep as it can in one direction with a stack or recursion, and suits connectivity, cycles, topological order and counting all paths. Both are O(V + E).
32
How do you traverse a binary tree in inorder without recursion?
With a stack: from the current node I go left, pushing every node on the way. When the left side runs out, I pop one from the stack, record its value and move to its right child. Each node goes in and out once, so it's O(n).
33
This code tries to check whether a binary tree is a BST. What is wrong?
The code compares a node only with its own children. But the BST rule requires the entire left subtree to be smaller than the node and the entire right subtree to be larger. The right way is to pass the allowed (min, max) range down to each node.
34
How do you output a binary tree level by level, with each level as a separate list?
With BFS, but at the start of each iteration I remember the queue size: that many nodes belong exactly to the current level. I take them, write them into one list and add their children to the queue. O(n).
35
You get a maze (0 is a path, 1 is a wall). Find the minimum number of steps from the top-left corner to the bottom-right corner.
I treat the grid as a graph and run BFS: each cell's four neighbors are the edges. I keep distances in a dist array. In an unweighted graph, BFS makes the first path to arrive the shortest. O(rows·cols).
36
How do you count the islands on a map made of 0s and 1s?
I walk through the grid. When I find a 1 I haven't seen yet, I increment the counter and "sink" the whole island with DFS or BFS, marking it as seen. Each cell is visited once, so it's O(rows·cols).
37
What is dynamic programming? Show the difference between memoization and tabulation on the staircase problem.
DP means splitting a problem into repeating subproblems and solving each one once, then storing the result. Memoization is top-down: recursion plus a cache. Tabulation is bottom-up: filling a table with a loop, starting from the smallest cases.
38
How do you find the k most frequent elements in an array?
First I count frequencies with a HashMap, then I keep the top ones in a min-heap (PriorityQueue) of size k. Time is O(n log k). It can also be done in O(n) with buckets by frequency.
39
How do you merge overlapping time intervals, for example [[1,3],[2,6],[8,10]] → [[1,6],[8,10]]?
I sort the intervals by start time and then walk through them: if the current interval overlaps the last one, I extend its end with max; otherwise I start a new interval. Because of the sorting, it's O(n log n).
40
How do you search for an element in O(log n) in a sorted array that has been rotated at an unknown point ([4,5,6,7,0,1,2])?
I modify binary search: at each step, one of the two halves around mid is always sorted. I work out which one is sorted, check whether the target falls into that range, and discard the appropriate half.
41
You're given courses and their prerequisites. How do you determine whether all the courses can be taken, and in what order?
This is a directed graph, and the answer is a topological sort. Kahn's algorithm: I put the nodes with in-degree 0 into a queue and remove them one by one. If not every node comes out, the graph has a cycle and there's no valid order. O(V + E).
42
Write an LRU cache where get and put are O(1).
A HashMap finds a node by key quickly, and a doubly linked list keeps the usage order: a used node moves to the front, and when space runs out the one at the end is evicted. The ready-made way in Java is LinkedHashMap with accessOrder=true and removeEldestEntry.
43
How do you compute the minimum number of edits (edit distance) to turn one word into another?
2D DP: dp[i][j] is the cost of making the first i letters of one word match the first j letters of the other. If the letters are equal, take the diagonal value; otherwise take the cheapest of insert, delete and replace, plus one. O(n·m) time.
44
Solve the 0/1 knapsack problem and explain why the loop has to run backwards when you shrink the DP table to one dimension.
dp[w] is the largest value achievable with capacity w. For each item, dp[w] = max(dp[w], dp[w - weight] + value). I go over the capacity from large w to small, otherwise one item may get taken several times. O(n·W).
45
What is Union-Find (Disjoint Set Union), and what do path compression and union by rank give you?
Union-Find merges elements into groups and answers "are these two in the same group?" in nearly O(1). Path compression flattens the tree, and union by rank keeps it from growing tall; together, the cost per operation is practically constant.
46
When you write Dijkstra's algorithm with a PriorityQueue, how do you deal with the lack of decrease-key?
Java's PriorityQueue has no way to decrease a key, so when I find a new, shorter distance I add the node to the queue again. When I pull one out and its distance is larger than the one in dist, it's a stale entry and I skip it.
47
For each day's temperature, how do you find in O(n) how many days later a warmer day comes?
With a monotonic stack: I keep on the stack the indexes of days whose answer hasn't been found yet, in decreasing temperature order. If a new day is warmer than the one at the top, that day's answer is found: I pop it and record the difference. Each index goes in once and comes out once.
48
How do you generate all subsets and all permutations of given numbers with backtracking, and how long does it take?
In the recursion I keep the current path in a list: I add an element, go deeper, and remove it on the way back. There are 2ⁿ subsets and n! permutations; the output itself is that large, so there is no faster way.
49
A search box needs autocomplete: finding words by prefix quickly. How does a Trie help, and when is it overkill?
A trie stores each letter as a tree node, so finding a prefix depends on the prefix length, not on the number of words: O(L). But it eats a lot of memory; in many cases a sorted list with binary search is enough.
50
In production, a recursive tree traversal started throwing StackOverflowError on large data. What do you do?
First I confirm the cause: I look in the stack trace for one method repeated thousands of times and check the depth of the data. Then I move the recursion onto an explicit stack with ArrayDeque. Raising -Xss is only a temporary patch.
51
How do you find the length of the longest substring that contains at most K distinct characters?
Sliding window: I advance the right edge, keep character counts in a Map, and shrink from the left whenever the number of distinct characters exceeds K. Each character enters the window once and leaves once, so it's O(n).
52
How do you find the maximum in every window of length k in O(n)? For example, [1,3,-1,-3,5,3,6,7] with k = 3.
A monotonic deque: I keep indexes in it with their values in decreasing order. When a new element arrives, I drop smaller ones from the back and drop an index that left the window from the front, so the maximum is always at the head of the deque. Each index goes in once and comes out once.
53
How do you count the contiguous subarrays whose sum is exactly K? The array also contains negative numbers.
A prefix sum and a HashMap<prefix, count>: at each step I add to the answer how many times sum - K has been seen before. A sliding window doesn't work because of the negative numbers, and this approach is O(n).
54
What is "binary search on the answer"? Explain it with the problem of the minimum ship capacity to deliver packages in D days.
We do binary search over the range of possible answers: the check "can we make it in D days with capacity C?" is monotonic, because increasing C never makes the answer worse. Each check is O(n), so the total is O(n log(sum)).
55
A graph has edges with negative weights. How do you find the shortest path, and how do you detect a negative cycle?
Dijkstra doesn't work here, because it treats a node pulled from the queue as final. Bellman-Ford relaxes all the edges V−1 times, O(V·E). If some distance still decreases on the V-th pass, there is a negative cycle reachable from the source.
56
You need to split a graph into two groups so that every edge connects different groups (bipartite). How do you check this?
I two-color it with BFS or DFS: the starting node gets 0, its neighbors get 1, their neighbors get 0 again. If a neighbor already has the same color, the graph isn't bipartite, meaning it has an odd-length cycle. O(V + E).
57
What is a minimum spanning tree? How do Kruskal's and Prim's algorithms differ, and when do you pick which?
An MST is the set of edges that connects all nodes without creating a cycle and has the smallest total weight. Kruskal sorts the edges by weight and checks for cycles with Union-Find: O(E log E). Prim grows from one node and takes the cheapest outgoing edge from a heap: O(E log V). Kruskal suits sparse graphs, Prim dense ones.
58
How do you write a set where insert, remove and getRandom are all O(1) on average?
An ArrayList stores the elements and gives a random index in O(1), while a HashMap takes you from a value to its index. On removal I put the last element of the list in the removed element's place and drop the last slot, so nothing gets shifted.
59
You need to find the K largest elements in an array. Do you choose a heap or quickselect?
If K is small or the data arrives as a stream, a min-heap of size K, O(n log K). If everything is in memory and it's a one-off query, quickselect is O(n) on average, but O(n²) in the worst case, and it modifies the array.
60
How do you find the median of two sorted arrays combined, without merging them, in O(log(min(n, m)))?
I binary-search for a cut point in the shorter array: the two left parts together must hold half of the elements, and the maximum of the left parts must not exceed the minimum of the right parts. Once that point is found, the median comes from the four numbers at the boundary.
61
What is pruning in backtracking? Show it with finding combinations that sum to a target.
Backtracking means making a choice, recursing, and undoing the choice on the way back. Pruning means cutting a branch early when it's clear it can't lead to an answer. For example, in a sorted array, if an element is larger than the remaining target, we don't bother trying the ones after it.
62
How do you find the longest common subsequence (LCS) of two strings with DP, and how do you reduce memory?
dp[i][j] is the LCS length for the first i characters of one string and the first j of the other. If the characters are equal, it's the diagonal plus 1; otherwise the larger of the top and left values. Time is O(n·m), and memory can be cut to two rows, which is O(min(n,m)).
63
When counting the ways to make a sum from coins, why does the order of the loops change the result?
If the outer loop is over coins, each combination is counted once (1+2 and 2+1 are the same). If the outer loop is over the sum, different orders are counted separately, which gives the number of sequences. The two pieces of code look almost identical, which makes this a classic trap.
64
You're given meeting time intervals. What is the minimum number of rooms needed to hold them all?
Sort the start and end times separately and walk with two pointers: a start means busy rooms +1, an end means −1, and I remember the maximum. Or I sort by start time and keep a min-heap of end times. Both are O(n log n).
65
How do you find the length of the longest strictly increasing subsequence (LIS) of an array in O(n log n)?
I keep a tails array: tails[k] is the smallest last element among increasing subsequences of length k + 1. For each new number I find its place with binary search and either replace an entry or append at the end. The answer is the filled length of tails.
66
How do you find the lowest common ancestor (LCA) of two nodes in a binary tree?
Postorder DFS: look at what comes back from the left and right subtrees. If a node comes back from both, the current node is the LCA. If it comes back from only one, we pass that up. O(n) time, O(h) stack.
67
What is wrong with this comparator, and when does it show up?
Subtracting a - b overflows the int range on large numbers and flips the sign. The order comes out wrong, and TimSort sometimes throws "Comparison method violates its general contract!". The right way is Integer.compare(a, b).
68
When does a greedy algorithm give the right answer, and how do you justify it in an interview? Show it with "jump game".
Greedy makes the locally best choice at each step and never goes back. It is correct only when the "greedy choice property" holds: an optimal solution that includes the local choice always exists. I justify it with an exchange argument, or I test it by looking for a small counterexample.
69
When several sources spread at the same time on a grid (for example rotting oranges), how do you compute the time to reach each cell?
Multi-source BFS: we put all the sources into the queue at the start with distance 0 and run an ordinary BFS. Each cell is marked in the first wave that arrives from its nearest source. O(R·C), whereas a separate BFS from each source would be O(k·R·C).
70
How does Kadane's algorithm work, and what happens if all the numbers in the array are negative?
At each position we keep "the best sum ending here": either we add to the previous one, or we start over from this element. The answer is the maximum of those. Written correctly, when everything is negative it returns the largest (smallest in absolute value) negative number.
71
You need to sort a 200 GB file on a server with 4 GB of memory. How do you do it?
External merge sort: I split the file into chunks that fit in memory, sort each one and write it to disk, then do a k-way merge of all the sorted chunks in a single pass using a min-heap. The main cost is disk I/O, so reducing the number of passes matters.
72
Numbers arrive as a stream. At any moment, how do you quickly return the median of everything received so far?
Two heaps: a max-heap for the smaller half and a min-heap for the larger half. I keep their sizes equal or differing by one. Adding is O(log n), and getting the median is O(1), from the tops of the heaps.
73
Compare the token bucket and sliding window log rate limiters as algorithms. Which do you choose when?
A token bucket works with two numbers per client, the token count and the last refill time, allows bursts and uses O(1) memory. A sliding window log stores every request time, is the most accurate, but its memory is proportional to the limit. In most cases a token bucket or a sliding window counter is enough.
74
How do you write consistent hashing in Java, and why are virtual nodes needed?
I place the nodes on a hash ring, a TreeMap<Long, Node>. For a key, ceilingEntry(hash) gives the first node clockwise. When a node is added or removed, only the keys in the neighboring range move. Virtual nodes spread the load evenly.
75
How does a Bloom filter work, and how do you compute the size you need?
An array of m bits and k hash functions. On insert we set k bits to 1; on lookup, if all are 1 the answer is "probably present", and if any is 0 it's "definitely absent". For n elements and false positive rate p, m ≈ −n·ln p / (ln 2)² and k ≈ (m/n)·ln 2.
76
Two pieces of code are both O(n), but one runs 10 times slower. What could the reasons be, and how do you measure?
Big-O hides constant factors: boxing and pointer chasing, memory access that doesn't fit the CPU cache, branch misprediction, unnecessary allocation and GC. To measure, use JMH and then a profiler (async-profiler), not System.currentTimeMillis().
77
You need to find the 100 most frequent IPs in a huge log stream, but you can't count everything in memory. What's your approach?
If an exact answer is required, I partition to disk by IP hash, count each chunk separately and merge the top-Ks. If an approximate answer is enough, Count-Min Sketch with a small heap, or the Space-Saving algorithm: fixed memory, a single pass.
78
If range-sum queries and element updates come mixed on an array, why isn't a prefix sum enough, and what do you use?
A prefix sum makes a query O(1), but a single update requires an O(n) recomputation. A Fenwick tree (BIT) or a segment tree makes both O(log n). A Fenwick tree is short and fast, while a segment tree is more flexible for min/max and range updates.
79
How do you pick K elements with equal probability from a stream of unknown length, in a single pass?
Reservoir sampling: I take the first K, then accept the i-th element (counting from 1) with probability K/i and put it in place of a random element in the reservoir. In the end each element remains with probability K/n, and memory is O(K).
80
When is the naive way of searching for a pattern in text slow? How do KMP and Rabin-Karp help?
Naive search is O(n·m) in the worst case, for example when you search for "aaaa…ab" inside "aaaa…a". KMP uses a prefix function to run in O(n+m) without moving backward. Rabin-Karp slides the window in O(1) with a rolling hash, which is handy for searching many patterns at once, but collisions must be verified.
81
If you were designing the coding interview process for your team, what problems would you pick and what would you assess a candidate on?
The problem should be close to our work, multi-stage, and have several correct solutions, so it doesn't test a memorized LeetCode answer. In the assessment, what counts is not the final code but the signals: clarifying requirements, stating trade-offs openly, tests and edge cases, and taking advice.
82
In production, code turned out to be O(n²) and the service slowed down as the data grew. How do you catch such "time bombs" at the organization level?
Code review alone is not enough. You need limits on input size, performance tests with real-sized data, request duration recorded in metrics together with input size, and, once a bug is found, an automatic check for that kind of pattern. The main thing is to make it clear who is responsible for which volume.
83
What is hash flooding (an algorithmic complexity attack)? How do you protect your Java services against such attacks?
An attacker deliberately sends keys that land on the same hash, turning an O(1) table into O(n) and an entire request into O(n²). Since Java 8, HashMap converts a colliding bucket into a tree, cutting the damage down to O(log n), but full protection means limits on input size, parser settings, and closing other explosive spots like regexes and recursion.
84
You need to join two large datasets (say 2 billion transactions and 50 million customers) by key. Which join algorithm do you choose, and what do you do about data skew?
If the small side fits in memory, a broadcast hash join. If both are large, shuffle by key and do a partitioned hash join or a sort-merge join. With skew (one customer has 100 million rows), you need to split the "hot" keys with a salt and spread them out, or broadcast them separately.
85
You're choosing a storage structure for data with a huge number of writes that is read by time. What is the algorithmic difference between a B-tree, an LSM-tree and a skip list, and how do you decide?
A B-tree updates in place: reads are fast and predictable, but random writes are expensive. An LSM collects writes in memory and flushes them to sequential files: writes are cheap, reads and compaction cost more. A skip list is an in-memory sorted structure, usually used as an LSM's memtable or as an in-memory index.
86
How do you run a query like "find the drivers within 5 km of me" quickly across millions of points? Which spatial index algorithm do you choose?
An ordinary B-tree index over two coordinates doesn't work well. Grid-based partitioning like Geohash or S2/H3 turns a point into a single key and suits fast-changing data. An R-tree or a quadtree is good for immutable or rarely changing objects and complex shapes. In every case you take candidates from the cells and check the real distance separately.
87
You have 300 microservices and their dependencies. How do you use graph algorithms to analyze deploy order, cycles, and "if one service goes down, who suffers"?
I model the dependencies as a directed graph. I find the strongly connected components with Tarjan or Kosaraju; those are the cycles. I collapse the cycles into single nodes to get a DAG and derive the deploy layers with a topological order. The blast radius is a BFS on the reversed graph.
88
How do you find the differences between replicas in two data centers without comparing every record? How does a Merkle tree help here?
Each replica splits its key range into pieces and builds a tree from the hash of each piece: a parent node is the hash of its children's hashes. If the roots are equal, the replicas are identical. If not, we descend only into the branches whose hashes differ. O(differences × log n) data crosses the network, not O(n).
89
You need to remove duplicates from events arriving in a stream, but you can't store all IDs forever. Which algorithm and guarantee do you choose?
First I agree on the guarantee with the business: "exact dedup within an N-hour window" or "approximate, with a small error". For exact, a key-value store with a TTL (Redis SET NX EX, RocksDB) and a time window. For approximate, Bloom filters rotated over time. The most reliable is to make the consumer idempotent, so that dedup becomes an optimization.
90
In a social network, how do you find the "shortest friendship chain between two users" on a graph with 500 million nodes?
A plain BFS multiplies the number of nodes at each layer by the average degree, so in 3-4 steps you have millions of nodes. Bidirectional BFS walks from both ends and meets in the middle, cutting the number of visited nodes to roughly the square root. On top of that you need a depth limit, bypassing hot nodes, and graph sharding.
91
In a multi-tenant job scheduler, what queueing algorithm do you choose so that one big customer doesn't block everyone else's queue?
A single shared FIFO or a priority-only queue is unfair: a big tenant takes everything. I use a separate queue per tenant and weighted fair queuing or deficit round robin between them, plus a parallel job limit per tenant. Priority stays inside the tenant.
92
For search in a product, do we write our own inverted index or bring in Elasticsearch/OpenSearch? How do you decide, algorithmically and organizationally?
An inverted index is algorithmically simple: word → list of documents, a query is an intersection of lists, and ranking is BM25. The hard parts are tokenization, morphology, updates, sharding and operations. If the data is small and queries are simple, PostgreSQL full-text search is enough; for complex search and large volume, a ready-made engine; writing our own, almost never.
93
How do you choose a cache eviction policy? What results do LRU, LFU and W-TinyLFU give, and when?
LRU keeps what was used recently: it's simple, but a one-off scan washes the cache out. LFU keeps what is used often, but doesn't forget stale popularity. W-TinyLFU (Caffeine) gets the strengths of both with a small LRU window and an admission filter that estimates frequency with an approximate sketch. I make the choice by simulating with a real trace.
94
You're writing a service that shows the difference between versions of a config or a document. Which diff algorithm do you choose, and what do you watch for on large files?
By lines, Myers' algorithm is the standard choice: it finds the minimal edit list in O((n+m)·D), where D is the size of the difference, so it's very fast on similar files. For structured data (JSON, YAML), a diff over the tree is more correct than over text. For large and very different files, you need a time limit and a heuristic.
95
When should you accept a probabilistic algorithm instead of an exact one? How do you agree on this decision with the business?
When the exact answer gets expensive (memory, latency, or the cost of merging across many nodes) and the error margin doesn't affect a business decision. I ask "who will make which decision based on this number?". Money, legal matters and user-visible promises must be exact; analytics, monitoring and recommendations are usually approximate.
96
When does parallelizing a divide and conquer algorithm with ForkJoinPool or a parallel stream give no benefit, or even do harm?
When the work is small, the cost of splitting and combining is larger than the gain. Parallelism is useless or dangerous when the data source splits poorly (LinkedList, Stream.iterate), when memory bandwidth is the limit, when there is blocking I/O inside, or when everything runs in the shared ForkJoinPool.commonPool(). In a service, request-level parallelism already exists.
97
How do you generate unique 64-bit IDs that sort by time across many services and many instances, without a central coordinator?
Snowflake style: a timestamp (ms), a worker ID and a per-millisecond sequence counter are packed into one long. There is no central point, and the order is roughly by time. The main risks are the clock going backward, duplicate worker IDs, and running out of bits in the layout.
98
In a logistics platform, a route must be returned within 50 ms on a graph with millions of road nodes. If Dijkstra isn't enough, which approaches do you consider?
On a city-scale graph, plain Dijkstra looks at hundreds of thousands of nodes and is slow. A* uses a heuristic to steer the search toward the goal. The real speedup comes from precomputation: Contraction Hierarchies or similar methods bring a query down to a millisecond, but they make fast-changing weights like traffic harder.
99
You need to count unique users in real time on a huge table. How does HyperLogLog work, and what are its limitations?
It tracks the number of leading zeros in each element's hash: a long run of zeros means many distinct elements were seen. It splits the hash across m registers and estimates with a harmonic mean. With ~12 KB of memory it gives ~0.8% error for billions of elements, and sketches can be merged. Subtraction, intersection and exact counts are its weak side.
100
How do you choose the algorithm for assigning couriers to orders on a delivery platform: greedy, optimal assignment, or batching?
Greedy (the nearest free courier for each order) is fast and simple, but leaves bad pairings in the overall result. Optimal assignment (Hungarian, min-cost flow) gives the global best for a batch collected in a short time window. In practice a 10-30 second batch with optimal or a good heuristic is the compromise between waiting and quality.
Sign up — studied questions get marked and your progress is saved.