Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Floor in a Sorted Array

Easy Acceptance 33.75% Points 20.00

Given a sorted array arr[] containing unique elements and an integer k, your task is to find the index (0-based) of the largest element in the array that is less than or equal to k. This element is referred to as the "floor" of k. If no such element exists, return -1.

Examples
Example 1

Example 1

Input: arr[] = [3, 6, 8, 10, 15, 18], k = 7

Output: 1

Explanation: The largest number less than or equal to 7 is 6, and its index is 1.

Example 2

Example 2

Input: arr[] = [1, 2, 8, 10, 11, 12, 19], k = 20

Output: 6

Explanation: The largest number less than or equal to 20 is 19, and its index is 6.

Hints
Hint 1
Expected Time Complexity: O(log n)
Hint 2
Expected Auxiliary Space: O(1)
Constraints
  • 1 <= arr.size() <= 10^6
  • 1 <= arr[i] <= 10^6
  • 0 <= k <= arr[n-1]
Companies
Amazon Microsoft Walmart
Topics
Sorting Algorithms
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions