Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Binary Search for Target Index

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Binary Search for Target Index. Start with the requirements on the right.

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.

Problem

IDeaS G3 RMS can provide sorted forecast values for analysis. Given a sorted list of integers and a target integer, return the index of the target's first occurrence. Return -1 if the target is not present.

Your solution should use binary search rather than scanning every element.

Formal Specification

Implement search_first(nums, target).

  • Input: nums, a non-decreasing list of integers, and target, an integer.
  • Output: An integer containing the smallest index i such that nums[i] == target, or -1 when no such index exists.
  • Indices are zero-based.

Constraints

  • 0 <= nums.length <= 100,000
  • -10^9 <= nums[i], target <= 10^9
  • nums is sorted in non-decreasing order
  • The input list is not modified

Function Signature

def search_first(nums, target):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output