Floor in a Sorted Array

easy

You are given an array arr of integers sorted in non-decreasing order, and an integer x.

Return the 0-based index of the largest element in arr that is less than or equal to x. This element is called the floor of x in arr. If no element of arr is less than or equal to x, return -1.

Note: if the floor value occurs multiple times in arr, return the index of its last occurrence.

Hints

The array is sorted. What does that tell you about where all the elements less than or equal to x must live?
Every element <= x sits in a prefix of the array — the answer is simply the index where that prefix ends.
Binary search for the boundary: when arr[mid] <= x, record mid as a candidate and move right; otherwise move left. The last recorded candidate is the answer.

Common doubts

That is the problem's tie rule — and the boundary search satisfies it for free: by moving right whenever arr[mid] <= x, the search keeps chasing later qualifying indices and settles on the last one.
Then no element is <= x, so there is no floor — return -1. This is why ans starts at -1 and is only overwritten when a qualifying element is found.
No. The floor is the largest element <= x — it equals x only when x itself appears in the array. For x = 5 in [1, 2, 8], the floor is 2.

Interview follow-ups

Mirror the search: find the first index with arr[i] >= x — on arr[mid] >= x record the candidate and move left, otherwise move right. Same skeleton, flipped comparison.
Run a second boundary binary search for the first index holding that value (record on equality, then move left) — still O(log n) overall.
Binary search shines: O(log n) per query versus O(n) for a scan. With 10^6 elements that is about 20 probes per query instead of up to a million.

Fun facts

  • The optimal solution is a disguised upper bound: the last index with arr[i] <= x is exactly one position before the first index with arr[i] > x — which is what C++'s upper_bound computes.
  • The record-and-move boundary pattern reappears in First and Last Occurrence, Search Insert Position, Ceiling in a Sorted Array, and Square Root of an Integer — one loop, five problems.
  • The name comes from the mathematical floor function: just as floor(2.7) = 2 is the greatest integer not exceeding 2.7, the array floor is the greatest element not exceeding x.

Asked at

AmazonMicrosoftOracleAdobe
Frequently Sometimes Occasionally
Example 1
Input: arr = [1, 2, 8, 10, 10, 12, 19], x = 5
Output: 1
The largest element <= 5 is 2, at index 1.
Example 2
Input: arr = [1, 2, 8, 10, 10, 12, 19], x = 11
Output: 4
The largest element <= 11 is 10, which appears at indices 3 and 4. The last occurrence is at index 4.
Example 3
Input: arr = [1, 2, 8, 10, 10, 12, 19], x = 0
Output: -1
No element is <= 0, so there is no floor.
Constraints

- 1 <= arr.size <= 10^6 - 1 <= arr[i] <= 10^6 - 0 <= x <= 10^6 - arr is sorted in non-decreasing order

Solve this problem →