CodePark/ problems / Where Would It Go?
START PRACTICINGPRACTICE
Coding problem · Data structures and algorithms › Binary search

Where Would It Go?

easyabout 12 minutes in an interview

nums is sorted from smallest to largest, and target is a number. Return where target belongs in nums:

  • If target is in nums, return its index.
  • If not, return the index it would take if you slotted it in without breaking the sorted order.

Rules:

  • The values in nums are all different.
  • If nums is empty, return 0.
  • If target is bigger than everything in nums, return nums.length.
  • nums can hold up to 1,000,000 numbers and the function runs many times. So it must take O(log n) time.
Input: nums = [1, 4, 6, 9], target = 5 Output: 25 goes between 4 and 6, so it would take index 2.
Input: nums = [1, 4, 6, 9], target = 9 Output: 3
Input: nums = [1, 4, 6, 9], target = 12 Output: 4