Upper Bound

Binary Search Fundamentals Easy

Given a sorted array of nums and an integer x, write a program to find the upper bound of x. The upper bound algorithm finds the first or the smallest index in a sorted array where the value at that index is greater than a given key i.e. x.

If no such index is found, return the size of the array.

Examples:

Input : n= 4, nums = [1,2,2,3], x = 2

Output:3

Explanation: Index 3 is the smallest index such that arr[3] > x.

Input : n = 5, nums = [3,5,8,15,19], x = 9

Output: 3

Explanation: Index 3 is the smallest index such that arr[3] > x.

Input : n = 5, nums = [3,5,8,15,19], x = 3

Constraints

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

Hints

  • "The upper bound doesn’t care about whether x exists in the array. It’s about finding the smallest index where nums[index]>x."
  • "Use the usual binary search setup, but adjust the condition: If nums[mid]>x, the result could be at mid, so move the high pointer to search the left half. Otherwise, move the low pointer to search the right half. Stop when the low pointer overtakes the high pointer."

Company Tags

American Express Shopify Stripe Micron Technology Intel Siemens Healthineers Square Bloomberg Western Digital Teladoc Health Docker Airbnb Red Hat Roblox Target Swiggy Deloitte Broadcom HashiCorp Pinterest Optum NVIDIA Zomato Splunk Activision Blizzard TCS Cognizant Accenture Infosys Capgemini Wipro