Algorithmic Problem-Solving and Data Structure Selection Questions
The higher-order meta-skill of attacking an unfamiliar problem: recognizing problem archetypes and mapping them to known techniques, decomposing under constraints, and choosing, composing, or designing the right data structures to meet specified operation costs (LRU cache, min-stack, ordered maps, disjoint-set/union-find). Covers reasoning about trade-offs between competing structures and approaches, working through medium-to-hard problems methodically, handling problem variations, and communicating an approach before coding. The connective-tissue topic that ties the individual structure and algorithm topics together, rather than any single structure or algorithm.
Walk me through the standard time-complexity classes, from O(1) up through O(n log n) and O(n^2). For each one, give a concrete operation or algorithm that lands there, and explain why distinguishing best, average, and worst case matters when you are judging whether a piece of code is fast enough for its expected input size.
Sample Answer
Direct answer
The standard ladder, from fastest to slowest growth, is constant O(1), logarithmic O(logn), linear O(n), linearithmic O(nlogn), and quadratic O(n2), where n is the size of the input. Each class matches a signature access pattern: a direct lookup, halving a search space each step, one pass over the data, one pass paired with a logarithmic step (typical of good sorting), and comparing every pair of elements. Reporting only the worst-case bound without checking best- and average-case behavior can hide an algorithm that is usually fast but degrades badly on adversarial or already-sorted input, which is exactly the kind of surprise that shows up as a production incident rather than a benchmark number.
Structured elaboration
The five classes, with a concrete example each
| Class | Concrete example | Why it lands there |
|---|---|---|
| O(1) | Reading arr[i] by index, or a hash map get on a well-distributed key | The operation touches a fixed number of memory cells regardless of how much data exists |
| O(logn) | Binary search on a sorted array | Each comparison discards half of the remaining candidates |
| O(n) | A single linear scan (sum, max, membership check on an unsorted array) | Every element is touched once |
| O(nlogn) | Comparison-based sorting (merge sort, heap sort) | Each of logn merge/sift levels does O(n) work |
| O(n2) | Nested loops comparing every pair (naive duplicate-detection without a hash set, bubble sort) | Each of n elements is compared against each of the other n |
Why best, average, and worst case are separate questions
The same algorithm can sit in different classes depending on which case you're asking about:
- Linear search: best case O(1) (the target is first), worst case O(n) (the target is last or absent).
- Insertion sort: best case O(n) on already-sorted input, worst case O(n2) on reverse-sorted input.
- Quicksort: average case O(nlogn) with a reasonable pivot strategy, worst case O(n2) if the pivot choice is adversarial (e.g., always picking the first element on already-sorted input).
Judging whether code is "fast enough" means matching the case that actually describes your expected input, not defaulting to whichever case is easiest to state. A cache-friendly, average-case-only justification is fine for random production traffic; it is not fine if an attacker can choose the input (hash-flooding a hash table into its worst case is a real, exploitable pattern).
Ranking functions by growth
Given a set of functions, you rank them by how they behave as n→∞, not by their value at any one n. For example, rank {logn, n, n, nlogn, n2}: substituting n=16 gives log216=4, 16=4 (a tie at this specific n), n=16, nlogn=64, n2=256. The tie at n=16 is exactly why you don't rank by a single sample point: as n grows, n pulls permanently ahead of logn, so the correct asymptotic order is O(logn)<O(n)<O(n)<O(nlogn)<O(n2).
Big-O versus empirical profiling
Big-O describes an asymptotic trend as input size grows without bound; it deliberately ignores constant factors, lower-order terms, and hardware effects. Profiling measures what actually happens for the input sizes you really see, including those ignored factors (memory allocation, cache behavior, branch prediction, garbage collection). Neither replaces the other: Big-O tells you how a design will scale if the input grows 10x or 100x; profiling tells you where time is actually going today. A change that looks neutral or even negative in Big-O terms (e.g., adding a small constant-time cache) can be the dominant real-world win, and Big-O analysis alone would never surface that.
Why a smaller-Big-O algorithm can still be slower in practice
Big-O hides the constant multiplier in front of the growth term. An O(nlogn) algorithm with heavy per-element overhead (extra allocations, function-call indirection, poor cache locality) can lose to a simple O(n2) algorithm until n passes some crossover point, because the actual operation count is closer to c1⋅nlogn versus c2⋅n2, and if c1≫c2 the crossover point can be far larger than the n you ever encounter. This matters most on hardware with tight memory bandwidth and small caches (mobile devices, embedded targets): the "better" complexity class only pays off once you actually reach the sizes where the growth term dominates the constant.
Worked example
Comparing raw operation counts at n=1,000,000: log2n≈19.93, so nlog2n≈1,000,000×19.93≈19,931,569, while n2=1,000,000,000,000. The linearithmic count is about 20x the linear count, but the quadratic count is a million times the linear count, which is the concrete reason quadratic algorithms are the ones that visibly fall over first as data grows, while linearithmic ones stay usable much further out.
Trade-offs & pitfalls
- Quoting a single Big-O figure without naming which case (best, average, worst) it describes is the most common way this topic goes shallow in an interview; always attach the case.
- Big-O comparisons are only meaningful in the limit; for small, fixed input sizes, the algorithm with the better asymptotic class is not guaranteed to be faster once constants and hardware are accounted for.
- Average-case reasoning assumes something about the input distribution (often "roughly random"); that assumption breaks down for adversarial or attacker-controlled input, where the worst case is the one you actually need to defend against.
- Treating two algorithms in the same Big-O class as interchangeable ignores the constant factor, which is often the entire practical difference between them.
Implement a fixed-size circular (ring) buffer supporting enqueue, dequeue, peek, isEmpty, and isFull, all in O(1), backed by a single fixed-size array (no resizing, no shifting elements). Explain how you distinguish the full state from the empty state when the head and tail indices coincide.
Sample Answer
Direct answer
Back the buffer with a single fixed-size array plus a head index (next slot to read), a tail index (next slot to write), and an explicit count of stored elements; advance head and tail with modulo arithmetic so they wrap around the array instead of growing unbounded. The count is what distinguishes full from empty when head equals tail: head==tail with count==0 is empty, and head==tail with count==capacity is full, which is exactly the ambiguous case that arises because a fixed-size array wraps the same index for both states.
Structured elaboration
Why head==tail is ambiguous without extra state
After capacity-many enqueues with no dequeues, tail has wrapped all the way back around to equal head: the buffer is full. But before anything has ever been enqueued, head also equals tail: the buffer is empty. Comparing head and tail alone cannot tell these two states apart, since both produce head==tail. Two standard fixes exist:
- Keep an explicit count (as below): full is
count == capacity, empty iscount == 0, and head==tail is irrelevant to the check. - Reserve one slot: never let the buffer report full until only one slot remains empty, so full is
(tail + 1) % capacity == headand empty ishead == tail. This avoids a separate counter at the cost of one unusable slot.
Operations, all O(1)
enqueue(value): reject if full; otherwise write attail, advancetail = (tail + 1) % capacity, increment count.dequeue(): reject if empty; otherwise read athead, advancehead = (head + 1) % capacity, decrement count.peek(): reject if empty; otherwise read atheadwithout advancing anything.is_empty()/is_full(): direct comparisons against the count.
Worked example
class RingBufferFull(Exception):
pass
class RingBufferEmpty(Exception):
pass
class RingBuffer:
"""
Fixed-capacity circular buffer backed by a single preallocated list.
All operations O(1) time, O(capacity) space.
Distinguishes full from empty with an explicit count (no wasted slot).
"""
def __init__(self, capacity: int):
if capacity <= 0:
raise ValueError("capacity must be positive")
self._buf: list[object] = [None] * capacity
self._capacity = capacity
self._head = 0 # next slot to dequeue from
self._tail = 0 # next slot to enqueue into
self._count = 0
def is_empty(self) -> bool:
return self._count == 0
def is_full(self) -> bool:
return self._count == self._capacity
def enqueue(self, value: object) -> None:
if self.is_full():
raise RingBufferFull()
self._buf[self._tail] = value
self._tail = (self._tail + 1) % self._capacity
self._count += 1
def dequeue(self) -> object:
if self.is_empty():
raise RingBufferEmpty()
value = self._buf[self._head]
self._buf[self._head] = None
self._head = (self._head + 1) % self._capacity
self._count -= 1
return value
def peek(self) -> object:
if self.is_empty():
raise RingBufferEmpty()
return self._buf[self._head]
if __name__ == "__main__":
rb = RingBuffer(3)
rb.enqueue("a")
rb.enqueue("b")
rb.enqueue("c")
print("full:", rb.is_full())
print("peek:", rb.peek())
print("dequeue:", rb.dequeue())
rb.enqueue("d") # wraps into the slot freed by "a"
drained = [rb.dequeue() for _ in range(3)]
print("drained order:", drained)
print("empty:", rb.is_empty())
Running this prints:
full: True
peek: a
dequeue: a
drained order: ['b', 'c', 'd']
empty: True
After enqueueing "a", "b", "c" into a capacity-3 buffer, it reports full and peek/dequeue both correctly return "a" first (FIFO, first-in first-out order). Dequeuing "a" frees the slot at index 0; enqueueing "d" then wraps tail back to index 0, reusing that freed slot rather than growing the array. Draining the remaining three elements returns them in the order they were inserted: "b", "c", "d", confirming the wraparound did not disturb ordering.
Complexity
Time: O(1) for enqueue, dequeue, peek, is_empty, and is_full. Space: O(capacity), fixed at construction and never resized.
Edge cases
- Requesting a non-positive capacity is rejected at construction; a zero-capacity buffer can never hold anything meaningfully.
- Enqueue on a full buffer and dequeue or peek on an empty buffer both raise rather than silently corrupting state or returning a stale value.
- Wraparound at the exact array boundary (tail or head going from
capacity - 1back to0) is the core case the modulo arithmetic must get right; it is worth tracing by hand once, as in the worked example above. - A single-element capacity (capacity=1) still needs enqueue/dequeue/peek to behave correctly; it is a good minimal stress case for wraparound logic.
Trade-offs & pitfalls
The count-based design and the reserved-slot design are both correct and both O(1); the count-based version uses one extra integer but keeps the full array usable, while the reserved-slot version needs no extra counter but permanently wastes one slot of capacity. A common wrong turn is trying to distinguish full from empty using only head and tail without either fix, which silently produces a buffer that reports empty immediately after becoming full (or vice versa) the moment head and tail happen to coincide. Another common gap, in the producer/consumer framing this question absorbs, is forgetting that concurrent producers and consumers touching head, tail, and the array simultaneously need explicit synchronization (a lock, or lock-free atomic operations for the single-producer single-consumer case); the plain implementation above is correct only for a single thread, or for multiple threads coordinated externally. A related, absorbed framing: a deque that supports push and pop at both ends (not just enqueue at the tail and dequeue at the head) is the same fixed-capacity wraparound array, just allowing insertion and removal at either the head or the tail index; every operation is still O(1) against the fixed capacity. If that deque is also allowed to grow when full, by allocating a larger array and copying everything across (doubling being the usual choice), the cost analysis of those occasional resizes is the identical amortized argument used for a growable dynamic array: expensive individual resizes, but O(1) amortized per push or pop over the whole sequence.
Given the head of a singly linked list, determine whether it contains a cycle, and if so, return the node where the cycle begins, using O(1) extra space (no visited-set). Explain why moving one pointer twice as fast as the other guarantees they meet if and only if a cycle exists, and how that same meeting point lets you locate the cycle's start.
Sample Answer
Direct answer
Advance one pointer (slow) one step at a time and another (fast) two steps at a time. If the list has no cycle, fast reaches the end first and you can report there is none. If it does have a cycle, fast eventually laps slow and the two meet somewhere inside it. Once they meet, restarting one pointer at the head and advancing both pointers one step at a time makes them meet again exactly at the cycle's start. All of this uses O(1) extra space, no visited set required.
Structured elaboration
Why meeting implies a cycle, and why no meeting implies no cycle. With no cycle, fast strictly gains ground toward a null terminator every step and reaches it in at most n/2 steps; it can never occupy the same node as slow without a cycle to loop back through. Once both pointers are inside a cycle, fast closes the gap to slow by exactly one node per step, because fast gains two steps of distance while slow gains one, a net closing rate of one per step. Since the gap can never exceed the cycle's length, they are guaranteed to meet within one full lap of the cycle.
Why the meeting point locates the cycle's start. Let a be the distance from the head to the cycle's start, c be the cycle's length, and b be the distance from the cycle's start to the meeting point, with 0≤b<c. By the time they meet, slow has traveled a + b steps and fast has traveled exactly twice that, but fast has also gone around the cycle some whole number of extra laps n≥1:
So a and (c - b) differ by a whole number of cycle lengths, meaning a pointer walking one step at a time from the head, and a pointer walking one step at a time from the meeting point, land on the same node after exactly a steps: the cycle's start.
Related applications of the same fast/slow pattern. Removing the n-th node from the end of a list uses the same shape without any cycle involved: advance one pointer n steps first, then move both pointers together; when the front pointer reaches the end, the trailing pointer sits exactly at the node to remove. Finding a duplicate number hidden in an array reframes the array itself as an implicit linked list, where the value stored at each index tells you which index to visit next; a repeated value forces two different positions to point at the same next index, creating a cycle in that implicit list, which Floyd's tortoise-and-hare detects exactly the way it detects a cycle here.
Worked example
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
def detect_cycle_start(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
ptr = head
while ptr is not slow:
ptr = ptr.next
slow = slow.next
return ptr
return None
if __name__ == "__main__":
nodes = [Node(i) for i in range(5)] # values 0,1,2,3,4
for i in range(4):
nodes[i].next = nodes[i + 1]
nodes[4].next = nodes[2] # cycle back into node with value 2
start = detect_cycle_start(nodes[0])
print(start.val)
Running this prints 2. In the derivation's terms: a = 2 (two steps from the head, value 0, to the cycle's start, value 2), c = 3 (the cycle 2 to 3 to 4 back to 2 has three edges), and the two pointers first meet at the node with value 3, so b = 1 (one step from the cycle's start to that meeting point). Checking the identity: c - b = 3 - 1 = 2, which equals a, confirming the derivation against this concrete run.
Complexity
Time: O(n). The pointers meet within one full lap of the cycle once both are inside it, and finding the cycle's start afterward takes at most another full lap; both phases are bounded by a constant multiple of the list's length n.
Space: O(1), since only the slow and fast pointers (and later ptr) are held, with no visited set.
Edge cases
- Empty list (
headisNone):fastisNoneimmediately, so the loop never runs and the function correctly returns no cycle. - Single node with no self-link:
fast.nextisNoneon the first check, so the loop exits immediately with no cycle detected. - Single node that cycles to itself:
slowandfastboth land back on that same node on the first iteration, correctly reporting it as the cycle's start.
Trade-offs & pitfalls
A common bug is comparing pointer values instead of pointer identity; when list values can repeat, slow.val == fast.val can be true without slow and fast being the same node, so the check must be slow is fast.
Given a list of intervals, merge every pair that overlaps and return the resulting set of non-overlapping intervals. What is the key step that makes an O(n log n) solution possible, and what would you need to change if intervals could arrive one at a time instead of all at once?
Sample Answer
Direct answer
Sort the intervals by start time, then make a single linear pass, extending a running merged interval whenever the next interval's start is at or before its current end, and starting a new merged interval otherwise. The sort is what makes O(nlogn) possible: once intervals are ordered by start, every pair that can possibly overlap is adjacent in that order, so a single linear scan is enough to find every merge. If intervals arrive one at a time instead of all at once, you need a data structure that supports ordered insertion and neighbor lookup, such as a balanced binary search tree (BST, a tree that keeps keys ordered so lookup, insertion, and neighbor queries are all logarithmic) keyed by start time, rather than a one-shot sort.
Structured elaboration
Why sorting is the key step
Without an order, deciding whether interval A overlaps interval B requires comparing it against every other interval, an O(n2) scan overall. Sorting by start time establishes an invariant: once you have processed intervals in start order, the only interval that can still extend or overlap the one you are currently building is the very next one in the sorted order. That invariant is what collapses the overlap check from "compare against everything" to "compare against one neighbor," turning the merge itself into an O(n) linear pass after the O(nlogn) sort.
Batch algorithm (steps)
- Handle the empty-input case.
- Sort intervals by start time.
- Walk the sorted list, keeping a current interval: if the next interval's start is ≤ the current interval's end, extend the current end to the max of the two ends; otherwise, close out the current interval and start a new one from the next interval.
- Return the closed-out intervals.
Streaming variant
If intervals arrive one at a time and you must always be able to answer "what are the merged intervals so far," a one-shot sort no longer applies, since new intervals keep appearing. Two practical designs:
- Keep the current merged intervals in a balanced BST (or an ordered structure with the same guarantees) keyed by start time. On each new arrival, locate its insertion point in O(logn), check the neighbor(s) on both sides for overlap, and merge in place, splicing at most a bounded number of neighboring intervals per insertion.
- If you only need periodic snapshots rather than an always-current answer, buffer arrivals and re-run the batch algorithm on a schedule, trading immediacy for simplicity.
Worked example
def merge_intervals(intervals: list[list[int]]) -> list[list[int]]:
"""
Merge overlapping intervals. O(n log n) time (sort), O(n) space.
Assumes each interval is [start, end] with start <= end.
"""
if not intervals:
return []
ordered = sorted(intervals, key=lambda pair: pair[0])
merged = [ordered[0][:]]
for start, end in ordered[1:]:
last = merged[-1]
if start <= last[1]:
last[1] = max(last[1], end)
else:
merged.append([start, end])
return merged
if __name__ == "__main__":
sample = [[1, 3], [2, 6], [8, 10], [15, 18]]
print(merge_intervals(sample))
touching = [[1, 2], [2, 3]]
print(merge_intervals(touching))
Running this prints:
[[1, 6], [8, 10], [15, 18]]
[[1, 3]]
For [[1,3],[2,6],[8,10],[15,18]]: after sorting (already sorted here), [1,3] and [2,6] overlap since 2 <= 3, merging to [1,6]; [8,10] does not overlap [1,6] since 8 > 6, so it starts a new group; likewise [15,18]. For the touching pair [[1,2],[2,3]], 2 <= 2 counts as an overlap (touching intervals are treated as mergeable here), giving the single interval [1,3].
Complexity
Time: O(nlogn), dominated by the sort; the scan itself is O(n). Space: O(n) for the sorted copy and the output list (or O(1) extra if sorting and merging in place and the output does not count as extra space).
Edge cases
- Empty input returns an empty list.
- A single interval returns that interval unchanged.
- Touching intervals (end of one equals start of the next) are merged here; whether touching counts as overlapping is a modeling choice to state explicitly, since flipping the comparison from
<=to<changes the answer. - Intervals given with start greater than end (an inverted pair) should be rejected or normalized before sorting, since the algorithm assumes start <= end.
Trade-offs & pitfalls
The most common mistake is forgetting to sort at all, or sorting by end time instead of start time; the linear-scan step only works because sorting by start establishes the adjacency invariant above. A second common gap is not deciding, and stating, whether touching intervals count as overlapping: interviewers frequently probe exactly this boundary condition. For the streaming follow-up, the wrong turn is proposing to re-sort and re-scan the entire collection on every new arrival: that is correct but throws away the point of the question, which is to avoid O(n) work per insertion by using an ordered structure that supports local overlap checks near the insertion point.
Compare quicksort, merge sort, and heap sort on average-case and worst-case time, extra space, and stability. Given a dataset that is nearly sorted already, or one where worst-case guarantees matter more than average speed, which would you pick and why?
Sample Answer
Direct answer
Quicksort is in-place with average time O(nlogn) but a worst case of O(n2) on an unlucky pivot sequence; merge sort and heap sort both guarantee O(nlogn) in every case. Merge sort needs O(n) extra space and is stable; heap sort needs only O(1) extra space but is not stable; quicksort's extra space is O(logn) for the recursion stack on average, but can grow to O(n) in the worst case. For nearly-sorted data, pick an adaptive sort such as TimSort (the hybrid merge/insertion sort behind Python's and Java's built-in sort); when a guaranteed worst case matters more than average speed, pick heap sort or merge sort, never plain quicksort.
Structured elaboration
| Algorithm | Average time | Worst time | Extra space | Stable | Adaptive to existing order |
|---|---|---|---|---|---|
| Quicksort | O(nlogn) | O(n2) | O(logn) avg, O(n) worst (stack) | No (not without extra bookkeeping) | No |
| Merge sort | O(nlogn) | O(nlogn) | O(n) | Yes | Only the natural-merge variant |
| Heap sort | O(nlogn) | O(nlogn) | O(1) | No | No |
| TimSort (hybrid) | O(nlogn) | O(nlogn) | O(n) | Yes | Yes, detects existing runs |
Nearly-sorted input
Plain quicksort and plain top-down merge sort are not adaptive: both do the same O(nlogn) work regardless of how ordered the input already is. TimSort is: it scans for existing ascending or descending runs, extends and merges them, and degrades toward close to linear work as the input approaches already-sorted. For nearly-sorted data, reach for TimSort (or, if you must hand-roll something, a natural merge sort) rather than a textbook quicksort or merge sort.
Worst-case guarantees matter more than average speed
Both heap sort and merge sort guarantee O(nlogn) in every case; quicksort does not, no matter how the pivot is chosen, because an adversary (or, unintentionally, already-sorted or already-reverse-sorted input under a naive pivot rule) can always construct a sequence that degrades a fixed pivot strategy to O(n2). Choose heap sort when the extra O(n) memory merge sort needs is unavailable and stability is not required; choose merge sort when stability is required alongside the worst-case guarantee and the memory budget allows it.
Two side notes worth naming explicitly
- Parallelization on resource-constrained devices: merge sort's divide phase maps cleanly onto independent worker threads or cores (each half sorts independently before a merge step), which is attractive on a multi-core mobile device; the cost is the extra O(n) buffer merge sort needs, which is a real constraint on memory-limited hardware. Quicksort's partitions can also be sorted concurrently, but partition sizes are unpredictable (a skewed pivot gives one thread almost all the work), so load balancing is harder to reason about.
- Cross-language floating-point sort determinism: when the same data is sorted by comparator across different languages or platforms, an unstable sort's tie-breaking for equal keys is unspecified and can differ, and NaN comparisons under IEEE 754 floating point are neither less-than nor greater-than any value, which breaks the total-order assumption most sort implementations rely on. If reproducible ordering across systems matters (for example, deterministic test fixtures or replaying a pipeline), use a stable sort and either exclude or explicitly place NaNs, rather than relying on the default comparator.
Worked example
A concrete way to see the worst case: implement a plain quicksort that always pivots on the last element, and run it on an already-sorted array.
def quicksort_last_pivot_count(a: list[int]) -> int:
"""
Naive quicksort that always pivots on the last element.
Returns the number of comparisons performed (element-to-pivot checks).
"""
comparisons = 0
def sort(lo: int, hi: int) -> None:
nonlocal comparisons
if lo >= hi:
return
pivot = a[hi]
store = lo
for i in range(lo, hi):
comparisons += 1
if a[i] < pivot:
a[i], a[store] = a[store], a[i]
store += 1
a[store], a[hi] = a[hi], a[store]
sort(lo, store - 1)
sort(store + 1, hi)
sort(0, len(a) - 1)
return comparisons
if __name__ == "__main__":
for n in [6, 10, 20]:
already_sorted = list(range(n))
c = quicksort_last_pivot_count(already_sorted)
expected = n * (n - 1) // 2
print(f"n={n}: comparisons={c}, n(n-1)/2={expected}")
Running this prints:
n=6: comparisons=15, n(n-1)/2=15
n=10: comparisons=45, n(n-1)/2=45
n=20: comparisons=190, n(n-1)/2=190
Every partition step on already-sorted input with a last-element pivot puts everything on one side, so the recursion depth is n and the total comparisons are exactly n(n−1)/2=Θ(n2), confirmed by the counts matching the closed-form prediction at every size tested. A randomized or median-of-three pivot choice avoids this specific failure mode but does not eliminate the worst case in general, only make it exponentially unlikely to hit by chance.
Trade-offs & pitfalls
The most common wrong turn is treating quicksort as unconditionally the fastest choice: on already-sorted or reverse-sorted input under a naive pivot rule, it is the slowest of the three by an order of magnitude, as the worked example shows directly. A second common gap is forgetting that merge sort's memory cost is real: at large enough n, the O(n) auxiliary buffer competes with other memory pressure, which is exactly why external (disk-based) sorting is built on multi-way merge rather than quicksort, since merge sort's sequential access pattern suits disk or network I/O far better than quicksort's more random access pattern. A third trap is ignoring stability when it silently matters: if you sort by a secondary key after already sorting by a primary key, only a stable sort preserves the primary ordering among equal secondary keys; using an unstable sort there produces a result that looks correct on small examples but is wrong in general.
Unlock Full Question Bank
Get access to all 27 Algorithmic Problem-Solving and Data Structure Selection interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.