Challenge - 5 Problems
Insertion Sort Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of Insertion Sort on a small array
What is the output of the following C++ code after performing insertion sort on the array?
DSA C++
int arr[] = {4, 3, 2, 1}; int n = 4; for (int i = 1; i < n; i++) { int key = arr[i]; int j = i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; } for (int i = 0; i < n; i++) { std::cout << arr[i] << " "; }
Attempts:
2 left
💡 Hint
Insertion sort places each element in its correct position by shifting larger elements to the right.
✗ Incorrect
Insertion sort iterates from the second element, shifting elements greater than the key to the right, then inserts the key. The final sorted array is 1 2 3 4.
🧠 Conceptual
intermediate1:30remaining
Number of comparisons in insertion sort best case
What is the number of comparisons insertion sort makes in the best case when the input array is already sorted?
Attempts:
2 left
💡 Hint
In the best case, the inner loop does not shift any elements.
✗ Incorrect
In the best case, insertion sort only compares each element once with the previous one, resulting in n - 1 comparisons.
🔧 Debug
advanced2:00remaining
Identify the bug in this insertion sort implementation
What error will this code produce when run?
DSA C++
int arr[] = {5, 2, 4, 6, 1, 3}; int n = 6; for (int i = 1; i < n; i++) { int key = arr[i]; int j = i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; }
Attempts:
2 left
💡 Hint
Check the loop boundary condition for i.
✗ Incorrect
The loop runs with i <= n, which accesses arr[n], out of bounds since valid indices are 0 to n-1.
🚀 Application
advanced2:00remaining
Insertion sort on a linked list
Which of the following statements about insertion sort on a singly linked list is true?
Attempts:
2 left
💡 Hint
Think about how nodes can be moved by changing pointers.
✗ Incorrect
Insertion sort on linked lists is efficient because nodes can be inserted by changing pointers without shifting data or extra space.
🧠 Conceptual
expert2:30remaining
Time complexity of insertion sort on nearly sorted data
If an array of size n is nearly sorted with only k elements out of place, what is the expected time complexity of insertion sort?
Attempts:
2 left
💡 Hint
Insertion sort shifts elements only when needed, so fewer misplaced elements reduce work.
✗ Incorrect
Insertion sort runs in O(n * k) time when only k elements are out of place, because each misplaced element may cause up to k shifts.