Practice
def cyclic_sort_extra_space(arr):
n = len(arr)
result = [0] * n
for num in arr:
if 1 <= num <= n:
result[num - 1] = num
return result
print(cyclic_sort_extra_space([2, 3, 1]))
Solution
Step 1: Initialize result array
result = [0, 0, 0], n = 3Step 2: Place each number at index num-1
num=2 -> result[1]=2; num=3 -> result[2]=3; num=1 -> result[0]=1; final result = [1, 2, 3]Final Answer:
Option D -> Option DQuick Check:
All numbers placed at correct indices [OK]
- Off-by-one index errors
- Returning original array
- Not initializing result array correctly
Solution
Step 1: Analyze the while loop behavior
Without incrementing i in the else branch, the loop can get stuck when nums[i] == nums[correct_index], causing infinite loop.Step 2: Identify fix
Addingi += 1in the else branch ensures progress and termination.Final Answer:
Option A -> Option AQuick Check:
Infinite loop caused by missing index increment [OK]
- Forgetting to increment index after no swap
- Swapping incorrectly
- Misplaced return statements
Solution
Step 1: Analyze cyclic sort complexity
Cyclic sort runs in O(n) because each number is swapped at most once to its correct position.Step 2: Analyze missing number scanning
Scanning for missing numbers and filling missing list takes O(k) time, as it may extend beyond array length.Final Answer:
Option B -> Option BQuick Check:
Sum of O(n) + O(k) = O(n + k) [OK]
- Assuming sorting inside cyclic sort causes O(n log n)
- Confusing nested loops causing O(n*k)
- Ignoring that scanning missing numbers is linear in k
Solution
Step 1: Identify the loops and swaps
The while loop runs at most n times, each swap places an element correctly, so total swaps ≤ n.Step 2: Confirm no nested repeated work
Each element is swapped at most once, so total operations are linear in n.Final Answer:
Option D -> Option DQuick Check:
Linear time complexity confirmed by single pass swaps [OK]
- Assuming sorting cost O(n log n)
- Thinking swaps can be quadratic
- Confusing extra space usage
Solution
Step 1: Understand input constraints
Input may have invalid numbers (negatives, zeros, > n) and duplicates that break in-place cyclic sort.Step 2: Use extra array for placement
Creating a separate array of size n and placing valid numbers at index num-1 ensures correct placement ignoring invalids and duplicates.Step 3: Avoid in-place swaps that cause index errors or infinite loops
Extra space approach is safer and simpler for this variant.Final Answer:
Option B -> Option BQuick Check:
Extra array handles invalid and duplicate numbers cleanly [OK]
- Ignoring invalid range checks
- Trying to fix in-place swaps with invalid numbers
- Not handling duplicates properly
