Dataford
Interview QuestionsInterview GuidesExperiencesCoaching
New
Pricing
Get started
Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
Experiences
Practice
Mock InterviewsTimed interview simulations with feedbackCoaching1:1 coaching with people at your target companiesSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Build my plan
Complexity of Binary Search
00:00
5 left

Complexity of Binary Search

EasyPython

Problem

What is the complexity of binary search?

Implement binary search for a sorted list of integers. Return the index of target if it exists, or -1 otherwise. Use an iterative approach and explain why each iteration discards half of the remaining search range.

Function: def binary_search(nums, target):

Input: nums is sorted in ascending order; target is an integer. Output: an integer index or -1.

Examples:

  • nums = [1, 3, 5, 7, 9], target = 7 returns 3 because 7 is at index 3.
  • nums = [2, 4, 6, 8], target = 5 returns -1 because 5 is absent.

Constraints: The list may be empty, values are sorted in ascending order, and duplicate values are not included.

Constraints

  • 0 <= nums.length <= 10^5
  • nums is sorted in ascending order
  • nums contains no duplicate values
  • -10^9 <= nums[i], target <= 10^9

Function Signature

def binary_search(nums, target):
Interviewer

Your question is Complexity of Binary Search. 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
Sign up free to run your codeLog inLn 2
Run your code to see test output here.