Challenge - 5 Problems
Counting Sort Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Counting Sort on a small array
What is the output of the following Rust code that uses counting sort on the array [4, 2, 2, 8, 3, 3, 1]?
DSA Rust
fn counting_sort(arr: &mut [usize]) {
let max = *arr.iter().max().unwrap();
let mut count = vec![0; max + 1];
for &num in arr.iter() {
count[num] += 1;
}
let mut i = 0;
for num in 0..=max {
for _ in 0..count[num] {
arr[i] = num;
i += 1;
}
}
}
fn main() {
let mut data = vec![4, 2, 2, 8, 3, 3, 1];
counting_sort(&mut data);
println!("{:?}", data);
}Attempts:
2 left
💡 Hint
Think about how counting sort counts the frequency of each number and then reconstructs the sorted array.
✗ Incorrect
Counting sort counts how many times each number appears, then writes them back in order. The input has one 1, two 2s, two 3s, one 4, and one 8, so the sorted array is [1, 2, 2, 3, 3, 4, 8].
🧠 Conceptual
intermediateCounting Sort Stability Property
Which statement best describes the stability property of counting sort?
Attempts:
2 left
💡 Hint
Stability means equal elements keep their original order after sorting.
✗ Incorrect
Counting sort is stable because it processes elements in order and places them in the output array preserving their original relative order.
🔧 Debug
advancedIdentify the error in this counting sort implementation
What error will this Rust counting sort code produce when run on the array [3, 1, 2]?
DSA Rust
fn counting_sort(arr: &mut [usize]) {
let max = *arr.iter().max().unwrap();
let mut count = vec![0; max];
for &num in arr.iter() {
count[num] += 1;
}
let mut i = 0;
for num in 0..max {
for _ in 0..count[num] {
arr[i] = num;
i += 1;
}
}
}
fn main() {
let mut data = vec![3, 1, 2];
counting_sort(&mut data);
println!("{:?}", data);
}Attempts:
2 left
💡 Hint
Check the size of the count vector and the maximum value used as index.
✗ Incorrect
The count vector is created with size max, but max is the largest number in the array. Since indexing is zero-based, count[max] access is out of bounds causing a panic.
🚀 Application
advancedCounting Sort Usage Scenario
In which scenario is counting sort the best choice compared to other sorting algorithms?
Attempts:
2 left
💡 Hint
Counting sort works best when the range of input values is not much larger than the number of items.
✗ Incorrect
Counting sort is efficient when the range of input values is small compared to the number of elements, as it uses extra space proportional to the range.
📝 Syntax
expertCorrect the syntax to create a counting array in Rust
Which option correctly creates a counting vector for counting sort in Rust for an input array with maximum value max?
Attempts:
2 left
💡 Hint
Remember the syntax for creating a vector with repeated values in Rust.
✗ Incorrect
Option A uses the correct syntax vec![value; size] to create a vector filled with zeros of length max + 1.
