📖 Scenario: You have a sorted list of numbers representing daily temperatures recorded over a month. You want to find out how many times a specific temperature was recorded.
🎯 Goal: Build a Rust program that counts how many times a given number appears in a sorted array.
📋 What You'll Learn
Create a sorted array of integers called temperatures with exact values
Create a variable called target to hold the temperature to count
Write a function called count_occurrences that takes a slice of integers and the target integer, and returns the count of the target in the slice
Print the count of the target temperature using the function
💡 Why This Matters
🌍 Real World
Counting occurrences of values in sorted data is common in statistics, sensor data analysis, and searching logs.
💼 Career
This skill helps in data processing roles, software development, and any job involving efficient data querying.
Progress0 / 4 steps
1
Create the sorted array of temperatures
Create a sorted array called temperatures with these exact values: [15, 15, 16, 17, 17, 17, 18, 19, 20]
DSA Rust
Hint
Use let to create an array with the exact numbers in order.
2
Set the target temperature to count
Create a variable called target and set it to 17 to represent the temperature to count
DSA Rust
Hint
Use let to create a variable named target and assign it the value 17.
3
Write the function to count occurrences
Write a function called count_occurrences that takes a slice of integers called arr and an integer called target, and returns the number of times target appears in arr. Use a for loop with variable num to check each element.
DSA Rust
Hint
Use a mutable variable count starting at 0. Loop over arr with for num in arr. Increase count by 1 when *num == target. Return count.
4
Print the count of the target temperature
Print the result of calling count_occurrences with temperatures and target using println!.
DSA Rust
Hint
Use println!("{}", count_occurrences(&temperatures, target)); to print the count.
Practice
(1/5)
1. What is the main advantage of using binary search to count occurrences of an element in a sorted array?
easy
A. It counts elements without searching
B. It sorts the array automatically
C. It reduces the search time to logarithmic complexity
D. It works only on unsorted arrays
Solution
Step 1: Understand binary search efficiency
Binary search divides the search space in half each time, making it very fast on sorted arrays.
Step 2: Compare with linear search
Linear search checks each element, which is slower (linear time). Binary search is faster (logarithmic time).
Final Answer:
It reduces the search time to logarithmic complexity -> Option C
Quick Check:
Binary search = O(log n) time [OK]
Hint: Binary search halves search space each step [OK]
Common Mistakes:
Thinking binary search sorts the array
Assuming binary search works on unsorted arrays
Confusing counting with searching
2. Which Rust code snippet correctly declares a function to count occurrences of target in a sorted slice arr?
3. What is the output of this Rust code counting occurrences of 3 in the sorted array?
fn main() {
let arr = [1, 2, 3, 3, 3, 3, 5];
let count = count_occurrences(&arr, 3);
println!("{}", count);
}
fn count_occurrences(arr: &[i32], target: i32) -> usize {
let first = arr.binary_search(&target).unwrap_or_else(|x| x);
let mut count = 0;
for &num in &arr[first..] {
if num == target {
count += 1;
} else {
break;
}
}
count
}
medium
A. 4
B. 3
C. 1
D. 0
Solution
Step 1: Find occurrence index
binary_search returns Ok(index) for 3 at index 2.
Step 2: Count consecutive 3s from index 2
Elements at indices 2,3,4,5 are 3, so count = 4.
Final Answer:
4 -> Option A
Quick Check:
4 occurrences counted correctly [OK]
Hint: Start counting from binary_search index [OK]
Common Mistakes:
Using unwrap_or_else returns insertion point, not found index
Counting beyond target elements
Not breaking loop on different element
4. Identify the bug in this Rust function that counts occurrences of target in a sorted array arr:
fn count_occurrences(arr: &[i32], target: i32) -> usize {
let start = arr.binary_search(&target).unwrap_or_else(|_| 0);
let mut count = 0;
for &num in &arr[start..] {
if num == target {
count += 1;
} else {
break;
}
}
count
}
medium
A. Function returns i32 instead of usize
B. The loop does not break on different element
C. binary_search returns index of last occurrence, not first
D. unwrap_or_else(|_| 0) returns 0 even if target not found, causing wrong count
Solution
Step 1: Understand unwrap_or_else behavior
unwrap_or_else(|_| 0) returns 0 if target not found, which is incorrect start index.
Step 2: Consequence of wrong start index
Counting from 0 when target is absent counts wrong elements, giving wrong count.
Final Answer:
unwrap_or_else(|_| 0) returns 0 even if target not found, causing wrong count -> Option D
Quick Check:
unwrap_or_else should use insertion point or handle not found [OK]
Hint: Use unwrap_or_else with insertion point for not found [OK]
Common Mistakes:
Using unwrap_or_else(|| 0)
Not breaking loop on different element
Confusing first and last occurrence index
5. Given a sorted array arr with possible duplicates, which Rust approach best counts occurrences of target efficiently and correctly for all cases, including when target is absent?
Options:
A) Use binary_search to find insertion points of target and target+1, then subtract indices.
B) Use binary_search to find any occurrence, then count forward until different element.
C) Use linear scan from start to end counting matches.
D) Use binary_search to find last occurrence, then count backward until different element.
hard
A. Find one occurrence with binary_search, count forward until different element
B. Find insertion points for target and target+1, subtract to get count
C. Linear scan entire array counting matches
D. Find last occurrence with binary_search, count backward until different element
Solution
Step 1: Understand insertion points method
Finding insertion points for target and target+1 gives start and end indices of target range.
Step 2: Calculate count by subtraction
Subtracting these indices gives exact count, even if target is absent (count = 0).
Step 3: Compare with other methods
Counting forward or backward after binary_search can fail if target not found; linear scan is slow.
Final Answer:
Find insertion points for target and target+1, subtract to get count -> Option B
Quick Check:
Insertion points subtraction = accurate count [OK]
Hint: Use binary_search for insertion points, subtract indices [OK]
Common Mistakes:
Counting forward without checking if target found
Using linear scan on large arrays
Counting backward without binary_search for last occurrence
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.