Floor and Ceil in Sorted Array in DSA Rust - Time & Space Complexity
We want to know how fast we can find the floor and ceil values in a sorted array.
How does the time to find these values grow as the array gets bigger?
Analyze the time complexity of the following code snippet.
fn floor_ceil(arr: &[i32], target: i32) -> (Option, Option) {
let mut left = 0;
let mut right = arr.len() as i32 - 1;
let mut floor = None;
let mut ceil = None;
while left <= right {
let mid = left + (right - left) / 2;
if arr[mid as usize] == target {
return (Some(arr[mid as usize]), Some(arr[mid as usize]));
} else if arr[mid as usize] < target {
floor = Some(arr[mid as usize]);
left = mid + 1;
} else {
ceil = Some(arr[mid as usize]);
right = mid - 1;
}
}
(floor, ceil)
}
This code finds the floor and ceil of a target number in a sorted array using binary search.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that halves the search space each time.
- How many times: The loop runs about log base 2 of n times, where n is the array size.
Each step cuts the array roughly in half, so the number of steps grows slowly as the array grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 4 steps |
| 100 | About 7 steps |
| 1000 | About 10 steps |
Pattern observation: Doubling the input size adds only one more step to the search.
Time Complexity: O(log n)
This means the time to find floor and ceil grows slowly, even if the array gets very large.
[X] Wrong: "Since we check elements one by one, the time is O(n)."
[OK] Correct: The code uses binary search, which skips many elements each step, so it does not check every element.
Knowing how to find floor and ceil efficiently shows you understand binary search and how to use sorted data well.
"What if the array was not sorted? How would the time complexity change?"
Practice
floor of a number in a sorted array?Solution
Step 1: Understand floor definition in sorted array
The floor of a number is the greatest element in the array that is less than or equal to the given number.Step 2: Compare options with definition
The greatest element less than or equal to the number matches the definition exactly, others describe ceil or incorrect concepts.Final Answer:
The greatest element less than or equal to the number -> Option CQuick Check:
Floor = greatest ≤ number [OK]
- Confusing floor with ceil
- Thinking floor is smallest element
- Ignoring equality in floor definition
Solution
Step 1: Recall Rust array syntax
Rust arrays use square brackets [] with comma-separated values.Step 2: Check each option
let arr = [1, 3, 5, 7, 9]; uses correct syntax. let arr = (1, 3, 5, 7, 9); uses tuple syntax with parentheses, let arr = {1, 3, 5, 7, 9}; uses braces resembling sets or blocks, let arr = <1, 3, 5, 7, 9>; uses angle brackets which are invalid.Final Answer:
let arr = [1, 3, 5, 7, 9]; -> Option AQuick Check:
Rust arrays use [] [OK]
- Using parentheses () for arrays
- Using braces {} which are for blocks
- Using angle brackets <> which are invalid here
arr = [2, 4, 6, 8, 10], what is the floor and ceil of 7?Solution
Step 1: Find floor of 7 in array
Floor is greatest element ≤ 7. Elements ≤ 7 are 2,4,6. Greatest is 6.Step 2: Find ceil of 7 in array
Ceil is smallest element ≥ 7. Elements ≥ 7 are 8,10. Smallest is 8.Final Answer:
Floor = 6, Ceil = 8 -> Option AQuick Check:
Floor ≤ 7 = 6, Ceil ≥ 7 = 8 [OK]
- Choosing floor or ceil outside array bounds
- Confusing floor and ceil values
- Assuming floor or ceil equals the target always
fn find_floor(arr: &[i32], target: i32) -> Option<i32> {
let mut low = 0;
let mut high = arr.len() - 1;
let mut floor = None;
while low <= high {
let mid = (low + high) / 2;
if arr[mid] == target {
return Some(arr[mid]);
} else if arr[mid] < target {
floor = Some(arr[mid]);
low = mid + 1;
} else {
high = mid - 1;
}
}
floor
}
What is the bug in this code?Solution
Step 1: Analyze initialization of high pointer
Usingarr.len() - 1causes panic if array is empty becauselen()is 0 and subtracting 1 underflows.Step 2: Check other parts of code
Other logic for binary search and floor update is correct. The main bug is unsafe initialization.Final Answer:
Using arr.len() - 1 without checking if array is empty -> Option BQuick Check:
Empty array causes panic at arr.len() - 1 [OK]
- Ignoring empty array edge case
- Assuming array always has elements
- Confusing return value with index
arr = [1, 3, 5, 7, 9]. You want to find the floor and ceil for multiple targets: [0, 4, 10]. Which Rust code snippet correctly returns a vector of tuples with floor and ceil for each target? Assume floor or ceil is None if not found.Solution
Step 1: Understand floor and ceil conditions
Floor is max element ≤ target, ceil is min element ≥ target.Step 2: Analyze each code snippet
```rust fn floor_ceil(arr: &[i32], targets: &[i32]) -> Vec<(Option<i32>, Option<i32>)> { targets.iter().map(|&t| { let floor = arr.iter().filter(|&&x| x <= t).max().copied(); let ceil = arr.iter().filter(|&&x| x >= t).min().copied(); (floor, ceil) }).collect() } ``` uses filter with ≤ and ≥, then max and min respectively, which matches floor and ceil definitions. ```rust fn floor_ceil(arr: &[i32], targets: &[i32]) -> Vec<(Option<i32>, Option<i32>)> { targets.iter().map(|&t| { let floor = arr.iter().filter(|&&x| x < t).max().copied(); let ceil = arr.iter().filter(|&&x| x > t).min().copied(); (floor, ceil) }).collect() } ``` uses < and > which exclude equality. ```rust fn floor_ceil(arr: &[i32], targets: &[i32]) -> Vec<(Option<i32>, Option<i32>)> { targets.iter().map(|&t| { let floor = arr.iter().find(|&&x| x <= t).copied(); let ceil = arr.iter().find(|&&x| x >= t).copied(); (floor, ceil) }).collect() } ``` uses find which returns first match, not max or min. ```rust fn floor_ceil(arr: &[i32], targets: &[i32]) -> Vec<(Option<i32>, Option<i32>)> { targets.iter().map(|&t| { let floor = arr.iter().filter(|&&x| x <= t).min().copied(); let ceil = arr.iter().filter(|&&x| x >= t).max().copied(); (floor, ceil) }).collect() } ``` reverses min and max causing wrong results.Final Answer:
filter(|&&x| x <= t).max() for floor, filter(|&&x| x >= t).min() for ceil -> Option DQuick Check:
Floor = max ≤ target, Ceil = min ≥ target [OK]
- Using strict < or > instead of ≤ or ≥
- Using find instead of max/min for floor/ceil
- Swapping min and max in floor/ceil logic
Ready to prove it?
Pass the test and this pattern moves unknown
