You're given a sorted array 'a' of 'n' integers and an integer 'x'.
Find the floor and ceiling of 'x' in 'a[0..n-1]'.
Floor of 'x' is the largest element in the array which is smaller than or equal to 'x'.
Ceiling of 'x' is the smallest element in the array greater than or equal to 'x'.
Input:
n=6, x=5, a=[3, 4, 7, 8, 8, 10]
Output:
4
Explanation:
The floor and ceiling of 'x' = 5 are 4 and 7, respectively.
The first line contains two integers, ‘n’ and 'x', where n represents the size of the array.
The next line contains 'n' integers, denoting the elements of the given array.
Return two integers, the floor and ceiling of 'x'.
You are not required to print anything; it has already been handled. Just implement the function.
6 8
3 4 4 7 8 10
8 8
Since x = 8 is present in the array, it will be both floor and ceiling.
6 2
3 4 4 7 8 10
-1 3
Since no number is less than or equal to x = 2 in the array, its floor does not exist. The ceiling will be 3.
1 <= n <= 2 * 10^5
1 <= a[i] <= 10^9
Time limit: 1 sec
Try iterating each element of the array!
Simply iterate all the elements of the array. While iterating, check each number for floor and ceil.
The steps are as follows:
O(N), where ‘N’ is the length of the array given.
We are iterating the entire array. Hence time complexity linearly depends on the size of the input array.
O(1)
No auxiliary space used is dependent on the size of the input array.