Challenge - 5 Problems
Merge Sort Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Merge Sort on a small list
What is the output of the following merge sort implementation when sorting the list [4, 1, 3, 2]?
DSA Python
def merge_sort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 left = merge_sort(arr[:mid]) right = merge_sort(arr[mid:]) return merge(left, right) def merge(left, right): result = [] i = j = 0 while i < len(left) and j < len(right): if left[i] < right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 result.extend(left[i:]) result.extend(right[j:]) return result print(merge_sort([4, 1, 3, 2]))
Attempts:
2 left
💡 Hint
Think about how merge sort splits the list and merges sorted halves.
✗ Incorrect
Merge sort splits the list into halves recursively until single elements remain, then merges them back in sorted order. The final output is the sorted list [1, 2, 3, 4].
🧠 Conceptual
intermediateUnderstanding the time complexity of merge sort
What is the time complexity of merge sort in the average and worst cases?
Attempts:
2 left
💡 Hint
Consider how many times the list is split and merged.
✗ Incorrect
Merge sort splits the list into halves (log n splits) and merges all elements (n) at each level, resulting in O(n log n) time complexity.
🔧 Debug
advancedIdentify the error in this merge function
What error will occur when running this merge function used in merge sort?
DSA Python
def merge(left, right): result = [] i = j = 0 while i < len(left) or j < len(right): if left[i] < right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 return result
Attempts:
2 left
💡 Hint
Check the loop condition and how indices i and j are used.
✗ Incorrect
The loop uses 'or' which allows i or j to go out of range. Accessing left[i] or right[j] when i or j is beyond list length causes IndexError.
🚀 Application
advancedUsing merge sort to count inversions
How can merge sort be modified to count the number of inversions (pairs where a larger number appears before a smaller one) in a list?
Attempts:
2 left
💡 Hint
Think about when elements from the right half are merged before left half elements.
✗ Incorrect
During merge, when an element from the right list is placed before one from the left, it indicates inversions equal to the remaining elements in left.
📝 Syntax
expertIdentify the syntax error in this merge sort code snippet
Which option correctly identifies the syntax error in this merge sort snippet?
DSA Python
def merge_sort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 left = merge_sort(arr[:mid]) right = merge_sort(arr[mid:]) return merge(left, right)
Attempts:
2 left
💡 Hint
Check the if statement syntax carefully.
✗ Incorrect
The if statement is missing a colon ':' at the end of the condition line, causing a syntax error.
