Data Structures & AlgorithmsHardGATE CS · Product placement
Insertion sort is run on an array of n elements that has exactly k inversions. What is its running time?
- A. Θ(nk)
- B. Θ(n²) regardless of k
- C. Θ(n log n)
- D. Θ(n + k)
Correct answer: D. Θ(n + k)
Each shift removes exactly one inversion and each of the n − 1 insertions does at most one extra comparison, so the work is Θ(n + k) — linear for nearly sorted data.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- A queue is built from two stacks: enqueue pushes onto IN; dequeue pops from OUT, first moving every element of IN onto OUT only when OUT…
- Rearrange a linked list so that nodes at odd POSITIONS (1st, 3rd, …) come first, followed by the even-position nodes, keeping relative…
- Sort [−4, 3, −3, −5, −4, 5, 2] and, for each i, move two pointers to find the triplet sum closest to -2. What is that closest sum?
- Insertion sort (ascending; shift larger elements right, one key comparison per inner-loop test, the loop stops at the first element ≤ the…
- How many contiguous subarrays of [−2, 0, 5, −1, 4, 3, −1, −2, −3] have sum exactly 4? (Prefix sums with a hash map of prefix-sum…
- For s = "cdbccdddbaddca", what is the length of the longest substring with at most 2 distinct characters, and how many substrings (by…