4. Identify the bug in this merge function used in merge sort:
func merge(left, right []int) []int {
result := []int{}
i, j := 0, 0
for i < len(left) && j < len(right) {
if left[i] <= right[j] {
result = append(result, left[i])
i++
} else {
result = append(result, right[j])
j++
}
}
result = append(result, left[i:])
result = append(result, right[j:])
return result
}
medium
A. Incorrect slice append syntax for left and right remaining elements
B. Wrong comparison operator in if condition
C. Missing initialization of result slice
D. Loop condition should use || instead of &&
Solution
Step 1: Check how remaining elements are appended
The code uses append(result, left[i:]) which appends a slice as one element, not elements.
Step 2: Correct append syntax
It should use append(result, left[i:]...) to append all elements individually.
Final Answer:
Incorrect slice append syntax for left and right remaining elements -> Option A
Quick Check:
Use ... to append slice elements [OK]
Hint: Use ... to append slice elements, not slice itself [OK]
Common Mistakes:
Appending slice without ... causes nested slices
Changing comparison operator unnecessarily
Using || instead of && in loop condition
5. Given a large list of 1 million integers, which of these is the best reason to choose merge sort over bubble sort?
hard
A. Merge sort uses less memory than bubble sort because it sorts in place
B. Merge sort has better average and worst-case time complexity (O(n log n)) than bubble sort (O(n^2))
C. Bubble sort is faster for large lists because it swaps elements directly
D. Merge sort does not require recursion, so it uses less stack space
Solution
Step 1: Compare time complexities
Merge sort runs in O(n log n), which is much faster than bubble sort's O(n^2) for large n.
Step 2: Evaluate memory and recursion claims
Merge sort uses extra memory and recursion; bubble sort is in-place but slow.
Final Answer:
Merge sort has better average and worst-case time complexity (O(n log n)) than bubble sort (O(n^2)) -> Option B
Quick Check:
Time complexity matters most for large lists [OK]
Hint: Choose O(n log n) over O(n^2) for big data [OK]
Common Mistakes:
Assuming bubble sort is faster for large data
Thinking merge sort is in-place
Ignoring recursion stack usage
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.