↓Skip to main content
  1. LeetCode/

LeetCode 704: Binary Search

·2 mins· ·
LeetCode Easy Array Binary-Search
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-31

  • Submissions: Accepted → Runtime Error ×3 → Accepted ×2 → Runtime Error → Accepted ×3

Approach
#

Standard binary search (Binary Search Template 1). With a closed interval [l, r] and while l <= r: if nums[mid] is too small set l = mid + 1, if too large r = mid - 1.

My Attempts
#

The REs came from mid = (l + r) / 2 producing a float used as an index (TypeError), or bounds stepping out of range.

Solution
#

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        l, r = 0, len(nums) - 1
        while l <= r:
            mid = (l + r) // 2
            if nums[mid] == target:
                return mid
            if nums[mid] < target:
                l = mid + 1
            else:
                r = mid - 1
        return -1

Complexity
#

Time O(log n), space O(1).

Mistakes to Avoid
#

  • In Python 3 / gives a float; indices need //.
  • A closed interval goes with while l <= r and mid ± 1.

Interview Explanation
#

With a closed interval, I move the left bound to mid + 1 when mid is too small and the right bound to mid - 1 when too large, returning on a match. Time O(log n).

Related

LeetCode 268: Missing Number
·1 min
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 note: the sum of 0..n minus the array’s sum is the missing number, which may be 0
LeetCode 35: Search Insert Position
·2 mins
LeetCode Easy Array Binary-Search
LeetCode 35 note: find the first position >= target (lower bound); a half-open [l, r) needs r = mid, not r = mid - 1
LeetCode 349: Intersection of Two Arrays
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 note: convert both arrays to sets and intersect them
LeetCode 350: Intersection of Two Arrays II
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 350 note: an intersection keeping multiplicity, where Counter’s & takes the smaller count from each side
LeetCode 705: Design HashSet
·2 mins
LeetCode Easy Array Hash-Table Linked-List Design
LeetCode 705 note: a fixed number of buckets, with the key modulo the bucket count choosing the bucket and a list per bucket handling collisions
LeetCode 674: Longest Continuous Increasing Subsequence
·2 mins
LeetCode Easy Array
LeetCode 674 note: one pass that extends the run while strictly increasing and resets to 1 otherwise, updating the maximum after the loop too