Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
Binary Search with Insertion Index
00:00
5 left

Binary Search with Insertion Index

EasyPython

Problem

Clear maintains sorted integer identifiers for an onboarding workflow. Given a nondecreasing array of identifiers and a target value, return the target's 1-indexed position if it exists. If it does not exist, return the negative 1-indexed position where it should be inserted to preserve sorted order.

Use binary search and achieve O(log n) time. If the target appears multiple times, return the position of its first occurrence.

Formal Specification

Implement find_position(nums, target):

  • nums is a nondecreasing list of integers.
  • target is an integer.
  • Return an integer.
  • For a match at zero-based index i, return i + 1.
  • For an absent target that belongs at zero-based insertion index i, return -(i + 1).

Constraints

  • 0 <= nums.length <= 100000
  • -10^9 <= nums[i], target <= 10^9
  • nums is sorted in nondecreasing order
  • The input list must not be modified

Function Signature

def find_position(nums, target):
Interviewer

Your question is Binary Search with Insertion Index. Start with the requirements in the Question tab.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.
CodePython 3
You need to log in / sign up to run or submit.Ln 2
Run your code to see test output here.