First and last occurrence

Binary Search Logic Building Easy
  • Fun Fact: This problem is essentially about range queries which are a very common task in database management systems and search engines
  • For instance, if you use the filter function in an e-commerce website to specify a price range for a product, you're effectively asking the database to perform an operation much like this problem
  • The database will search through its sorted data to find the starting and ending positions of all products that fall within your specified price range
  • So the next time you're shopping online, remember you're indirectly solving this problem!

Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If the target is not found in the array, return [-1, -1].

Examples:

Input: nums = [5, 7, 7, 8, 8, 10], target = 8

Output: [3, 4]

Explanation:The target is 8, and it appears in the array at indices 3 and 4, so the output is [3,4]

Input: nums = [5, 7, 7, 8, 8, 10], target = 6

Output: [-1, -1]

Expalantion: The target is 6, which is not present in the array. Therefore, the output is [-1, -1].

Input: nums = [5, 7, 7, 8, 8, 10], target = 5

Constraints

  •   0 <= nums.length <= 105
  •   -109 <= nums[i] <= 109
  •   nums is a non-decreasing array.
  •   -109 <= target <= 109

Hints

  • "Perform two separate binary searches: One to find the first occurrence of the target. Another to find the last occurrence of the target."
  • "To find the first occurrence, move the search to the left half even after finding the target. To find the last occurrence, move the search to the right half after finding the target."

Company Tags

PayPal Qualcomm Zoho Western Digital Johnson & Johnson Ernst & Young Roblox eBay Walmart Shopify Deloitte NVIDIA Goldman Sachs MongoDB Etsy Dropbox Riot Games Flipkart Bain & Company Freshworks Boston Consulting Group Philips Healthcare IBM Roche Robinhood TCS Cognizant Accenture Infosys Capgemini Wipro