Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Find Floor and Ceiling in Sorted Array
Binary Search Approach



Problem Statement

Given a sorted array of integers and a target number x, your task is to find the floor and ceil of x in the array.

If the floor or ceil does not exist, return -1 for that value.

Examples

Input Array Key (x) Floor Ceil Description
[10, 20, 30, 40, 50] 35 30 40 35 lies between 30 and 40
[10, 20, 30, 40, 50] 10 10 10 Exact match, floor and ceil are the same
[10, 20, 30, 40, 50] 5 -1 10 No floor exists, ceil is the first element
[10, 20, 30, 40, 50] 55 50 -1 Floor exists, no ceil since key is greater than all
[10, 20, 30, 40, 50] 25 20 30 25 lies between 20 and 30
[15] 15 15 15 Single element match
[15] 10 -1 15 Single element greater than key
[15] 20 15 -1 Single element less than key

Solution

To find the floor and ceiling of a given number x in a sorted array, we use an efficient method called Binary Search. This method reduces the search space in half at each step, making it much faster than checking each element one by one.

Key Definitions

  • Floor: The largest number in the array that is less than or equal to x.
  • Ceiling: The smallest number in the array that is greater than or equal to x.

How the Binary Search Approach Works

We start by looking at the entire array and gradually narrow down the search range using two pointers: low (beginning of the array) and high (end of the array). At each step, we check the middle element:

Case 1: If the middle element exactly matches the number x we are looking for, then it is both the floor and the ceiling—so we can return it right away.

Case 2: If the middle element is smaller than x, it means this number could be the floor (since it's less than or equal to x). But maybe there's an even closer number to x further to the right, so we move our low pointer to the right and keep searching.

Case 3: On the other hand, if the middle element is greater than x, it could be the ceiling (the smallest number greater than or equal to x). We move the high pointer to the left and continue searching to find a smaller suitable value.

We keep repeating this process—checking the middle, updating floor or ceil candidates, and narrowing the search space—until the pointers cross each other. At that point, we’ve either found an exact match or the closest floor and ceiling values.

Why This Works

Since the input array is sorted, binary search helps us avoid scanning every element. Instead, we eliminate half of the remaining elements with every comparison.

Visualization

Algorithm Steps

  1. Given a sorted array arr and a target value x.
  2. Initialize floor = -1 and ceil = -1.
  3. Use binary search to find floor:
  4. → While low ≤ high, compute mid.
  5. → If arr[mid] == x, both floor and ceil are arr[mid]. Return.
  6. → If arr[mid] < x, update floor = arr[mid], search right.
  7. → If arr[mid] > x, update ceil = arr[mid], search left.
  8. Continue until low > high.
  9. Return the computed floor and ceil.

Code

Python
JavaScript
Java
C++
C
def find_floor_ceil(arr, x):
    low, high = 0, len(arr) - 1
    floor, ceil = -1, -1

    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == x:
            # Exact match is both floor and ceil
            return arr[mid], arr[mid]
        elif arr[mid] < x:
            # Current element could be a candidate for floor
            floor = arr[mid]
            low = mid + 1  # Search in the right half
        else:
            # Current element could be a candidate for ceil
            ceil = arr[mid]
            high = mid - 1  # Search in the left half

    return floor, ceil

# Sample Input
arr = [1, 2, 4, 6, 10, 12]
x = 5
print("Floor and Ceil:", find_floor_ceil(arr, x))

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(1)The target value is found at the mid index during the first iteration of binary search, requiring no further comparisons.
Average CaseO(log n)The binary search halves the search space in each step until the correct floor and ceiling values are found.
Average CaseO(log n)In the worst case, the search continues until only one element remains, after which the floor and ceiling values are determined.

Space Complexity

O(1)

Explanation: The algorithm operates using a constant number of variables (like low, high, mid, floor, ceil), without requiring additional memory.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M