Ceil in a Sorted Array – Binary Search Explained with Story & Visuals | GeeksforGeeks
Ceil in a Sorted Array – Binary Search Explained with Story & Visuals | GeeksforGeeks

Ceil in a Sorted Array – Binary Search Explained with Story & Visuals | GeeksforGeeks

GeeksforGeeks Problem – Find the smallest element ≥ x in a sorted array using multiple approaches, dry runs, and story-based visualization.

27 views
0
0

Try This Problem First

Platform: GeeksforGeeks

👉 Try this problem here: Ceil in a Sorted Array – GeeksforGeeks


Problem Statement

You are given a sorted array arr[] and an integer x. Your task is to find the index of the smallest element in the array that is greater than or equal to x.

  1. If no such element exists, return -1.
  2. If multiple elements equal the ceil, return the first occurrence.

Example:

Input: arr = [1, 2, 8, 10, 11, 12, 19], x = 5
Output: 2

Explanation: Smallest element ≥ 5 is 8 at index 2.


Intuition

Think of the problem as finding the first step you can reach without falling short:

  1. The ceil of x is the smallest number ≥ x.
  2. Since the array is sorted, we can use binary search to quickly locate the answer instead of checking each element.
Linear search is simple but slow for large arrays. Binary search gives an efficient O(log n) solution.


Multiple Approaches

1️⃣ Linear Search (Easy to Understand)

int ans = -1;
for(int i = 0; i < arr.length; i++){
if(arr[i] >= x){
ans = i; // first occurrence
break;
}
}
return ans;
  1. Time Complexity: O(n)
  2. Space Complexity: O(1)
  3. ✅ Works for small arrays
  4. ❌ Slow for large arrays

2️⃣ Binary Search (Optimized & Fast)

int ans = -1;
int low = 0, high = arr.length - 1;

while(low <= high){
int mid = low + (high - low)/2;

if(arr[mid] == x){
ans = mid;
high = mid - 1; // move left for first occurrence
} else if(arr[mid] > x){
ans = mid; // candidate ceil
high = mid - 1; // move left
} else {
low = mid + 1; // arr[mid] < x → move right
}
}

return ans;
  1. Time Complexity: O(log n)
  2. Space Complexity: O(1)
  3. ✅ Efficient for large arrays
  4. ✅ Automatically returns first occurrence


Dry Run

Input: arr = [1, 2, 8, 10, 11, 12, 19], x = 5


Steplowhighmidarr[mid]ansAction
1063103arr[mid] > x → move left
202123arr[mid] < x → move right
322282arr[mid] > x → move left
421--2low > high → stop, return 2


✅ Binary search finds ceil = 8 at index 2.

Why This Problem is Important

  1. Teaches binary search for first occurrence
  2. Strengthens understanding of ceil/floor concepts
  3. Visualization through story improves understanding and retention
  4. Prepares for coding interviews and competitive programming

Conclusion

  1. Linear search: simple but slow (O(n))
  2. Binary search: fast and efficient (O(log n))
  3. Story-based visualization helps learn, not just memorize
  4. Using numbers on books in images makes abstract concepts concrete

Ai Assistant Kas