4. Identify the error in this Radix Sort counting step code snippet:
for (int i = 0; i < n; i++) {
count[(arr[i] / exp) % 10]++;
}
for (int i = 1; i < 10; i++) {
count[i] += count[i - 1];
}
for (int i = n - 1; i >= 0; i--) {
output[count[(arr[i] / exp) % 10]] = arr[i];
count[(arr[i] / exp) % 10]--;
}
medium
A. Counting array size should be 100, not 10
B. Indexing output array should be count[...] - 1
C. Loop for count prefix sum should start from 0
D. Division by exp should be replaced by modulo exp
Solution
Step 1: Analyze output array indexing
Indexing output array must use count[...] - 1 because count stores cumulative counts.
Step 2: Check other parts
Counting array size 10 is correct for digits 0-9; prefix sum loop starts at 1; division by exp is correct.
Final Answer:
Indexing output array should be count[...] - 1 -> Option B
Quick Check:
Output index = count - 1 [OK]
Hint: Subtract 1 from count for output indexing [OK]
Common Mistakes:
Using count directly as index without subtracting 1
Wrong counting array size
Incorrect loop start for prefix sums
Misusing division and modulo operators
5. Given an array of strings representing numbers with leading zeros, e.g., ["002", "010", "001", "100"], how can Radix Sort be adapted to sort them correctly as numbers?
hard
A. Pad all strings to equal length and sort digit by digit from right to left
B. Sort strings lexicographically without changes
C. Convert strings to integers first, then apply Radix Sort
D. Use Radix Sort only on the first character of each string
Solution
Step 1: Understand string number sorting
Strings with leading zeros must be equal length to compare digits correctly.
Step 2: Adapt Radix Sort
Pad strings to same length, then sort digit by digit from right to left to preserve numeric order.
Final Answer:
Pad all strings to equal length and sort digit by digit from right to left -> Option A