↓Skip to main content
  1. LeetCode/

LeetCode 34: Find First and Last Position of Element in Sorted Array

·2 mins· ·
LeetCode Medium 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: medium First Attempt: 2022-10-21

  • Submissions: Time Limit Exceeded ×5 → Runtime Error ×2 → Wrong Answer ×3 → Runtime Error → Wrong Answer ×2 → Accepted ×4 → Wrong Answer → Accepted ×2

Approach
#

Both ends come from one lower-bound function (Binary Search Template 1):

  • Start: the first position >= target.
  • End: the first position >= target + 1, minus one.

If the start is out of range or not target, it is absent.

My Attempts
#

This took 20 submissions in 2022:

  • The first versions used while l < r with l = mid / r = mid, so the interval stopped shrinking and looped forever (TLE).
  • After fixing the loops, the final check start < end treated a single occurrence (start equals end) as absent: [1], target = 1 should be [0, 0]; it returned [-1, -1], and one version used low instead of high for the end, returning [0, 1].

Solution
#

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

Complexity
#

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

Mistakes to Avoid
#

  • With a single match the start equals the end, so start < end cannot test existence.
  • Do not stop at a match; keep shrinking left (or right).

Interview Explanation
#

One lower-bound function gives the start (first position not less than the target) and the end (first position not less than target + 1, minus one); if the start is not the target I return [-1, -1]. Two searches, O(log n).

Related

LeetCode 33: Search in Rotated Sorted Array
·2 mins
LeetCode Medium Array Binary-Search
LeetCode 33 note: after rotation one side of mid is always sorted; check whether the target lies in it and search there, otherwise search the other side
LeetCode 31: Next Permutation
·2 mins
LeetCode Medium Array Two-Pointers
LeetCode 31 note: from the right find the first dip i, swap it with the smallest larger value to its right, then reverse everything after i, with comparisons that include equality
LeetCode 36: Valid Sudoku
·2 mins
LeetCode Medium Array Hash-Table Matrix
LeetCode 36 note: each digit may appear once per row, column and 3 × 3 box; put (digit, row), (digit, column) and (digit, box) keys into one set
LeetCode 39: Combination Sum
·2 mins
LeetCode Medium Array Backtracking
LeetCode 39 note: numbers may be reused, so the next level starts at i (not i + 1), which also avoids duplicates differing only in order
LeetCode 40: Combination Sum II
·2 mins
LeetCode Medium Array Backtracking
LeetCode 40 note: each number is used once and duplicates exist, so sort, start the next level at i + 1, and skip equal values within a level
LeetCode 46: Permutations
·2 mins
LeetCode Medium Array Backtracking
LeetCode 46 note: each level picks one unused number, marked in a used array, and records when the path is full