Floor and Ceil in Sorted Array

Binary Search Logic Building Easy

Given a sorted array nums and an integer x. Find the floor and ceil of x in nums. The floor of x is the largest element in the array which is smaller than or equal to x. The ceiling of x is the smallest element in the array greater than or equal to x. If no floor or ceil exists, output -1.

Examples:

Input : nums =[3, 4, 4, 7, 8, 10], x= 5

Output: 4 7

Explanation: The floor of 5 in the array is 4, and the ceiling of 5 in the array is 7.

Input : nums =[3, 4, 4, 7, 8, 10], x= 8

Output: 8 8

Explanation: The floor of 8 in the array is 8, and the ceiling of 8 in the array is also 8.

Input : nums = [8, 4, 12, 2, 6, 10, 14], x= 1

Constraints

  •   1 <= nums.length <= 105 
  •   0 < nums[i], x < 10
  •   nums is sorted in ascending order.

Hints

  • "Perform a binary search for x in the sorted array. During the search: If nums[mid]≤x, update the floor to nums[mid] and move right. If nums[mid]≥x, update the ceiling to nums[mid] and move left."
  • If x is smaller than the smallest element, the floor is −1. If x is larger than the largest element, the ceiling is −1.

Company Tags

Etsy Lyft Red Hat GE Healthcare KPMG McKinsey & Company Twilio Chewy Mastercard American Express Cloudflare Nutanix Wayfair Ubisoft Johnson & Johnson PwC Uber Snowflake Target Ernst & Young PayPal Roblox Zomato Instacart HashiCorp TCS Cognizant Accenture Infosys Capgemini Wipro