#34

Find First and Last Position of Element in Sorted Array

Medium
ArrayBinary SearchBinary SearchArrayTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution (Binary Search)
Time
O(n)
O(log n)
Space
O(1)
O(1)
💡

Intuition

Time O(log n)Space O(1)

Using binary search allows us to efficiently find the first and last positions of the target in O(log n) time. This is possible because the array is sorted, which allows us to eliminate half of the search space at each step.

⚙️

Algorithm

3 steps
  1. 1Step 1: Define a helper function to find the first position of the target using binary search.
  2. 2Step 2: Define another helper function to find the last position of the target using binary search.
  3. 3Step 3: Call both helper functions and return their results as an array.
solution.py31 lines
1# Full working Python code with comments
2
3def searchRange(nums, target):
4    def findFirst(nums, target):
5        left, right = 0, len(nums) - 1
6        while left <= right:
7            mid = left + (right - left) // 2
8            if nums[mid] < target:
9                left = mid + 1
10            else:
11                right = mid - 1
12        return left
13
14    def findLast(nums, target):
15        left, right = 0, len(nums) - 1
16        while left <= right:
17            mid = left + (right - left) // 2
18            if nums[mid] <= target:
19                left = mid + 1
20            else:
21                right = mid - 1
22        return right
23
24    first = findFirst(nums, target)
25    last = findLast(nums, target)
26    if first <= last:
27        return [first, last]
28    return [-1, -1]
29
30# Example usage
31print(searchRange([5,7,7,8,8,10], 8))  # Output: [3, 4]

Complexity note: This complexity is achieved by halving the search space with each iteration of binary search, making it much faster than the brute force approach.

  • 1The sorted nature of the array allows for the use of binary search, which is a powerful technique for problems involving sorted data.
  • 2Finding the first and last positions can be efficiently handled by slightly modifying the binary search algorithm.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.