Complexity Comparison Interview Questions
What is the time and space complexity of common sorting algorithms? — spoken sample answer for Indian interviews.
- 5Questions with answers
- 3Difficulty levels
Questions (5)
Browse beginner, intermediate, and advanced questions with answers — hide them when you want to self-test.
What is the time and space complexity of common sorting algorithms?
Compare sorting algorithms and justify which to use in an interview.
Merge sort: Always O(n log n) , O(n) extra space, stable — pick when worst case matters or sorting a linked list.
Quick sort: Average O(n log n) , in-place, not stable, worst case O(n²) with bad pivot.
Heap sort: O(n log n) , in-place, not stable.
Insertion sort: O(n²) but fast on nearly sorted data, O(1) extra space.
For integer keys in a small range, mention counting or radix sort O(n + k) . Default to language sort unless asked to implement.
When is quicksort worse than mergesort in an interview answer?
Quicksort average O(n log n) extra space O(log n) , but worst O(n squared) on already sorted data with a bad pivot. Mergesort is always O(n log n) and needs O(n) extra memory, and it is stable. I would use mergesort for linked lists and when I need a worst-case guarantee or stability. I would use well-pivoted quicksort for arrays in practice. I would not say 'quicksort is always faster'. I would say it depends on worst-case, stability, and memory.
Which sorts are stable, and when does stability matter?
Mergesort and insertion sort are stable. Heap sort and a naive quicksort are not. Stability matters when I sort by last name then want to keep the previous order by first name — two-key sorts. If I only have integers and no satellite data, stability may not matter. I mention that so I do not sound like I memorized a blog table.
When would you use heapsort?
Heapsort is O(n log n) worst case and O(1) extra array space, not stable. I would use it when I cannot afford mergesort's O(n) buffer and I cannot risk quicksort's worst case. In interviews it also explains why a heap exists. I would not pick heapsort for nearly sorted data — insertion sort is better then. I would not pick it when I need stable order.
Is O(n log n) the best comparison sort? What about counting sort?
Comparison sorts cannot beat O(n log n) in the worst case. Counting sort, radix sort, and bucket sort can be linear when the keys are integers in a small range. I would use counting sort for grades 0 to 100, not for arbitrary 64-bit ids. I would say the model matters: comparison versus integer keys. That sentence scores better than 'radix is O(n) so always use it'.
Practice with AI mock interviews
Run DSA mock interviews with AI follow-ups, instant feedback, and analytics on AiLx.
Free to start · No credit card required