34. Find First and Last Position of Element in Sorted Array

 


Finding the First and Last Position of an Element in a Sorted Array Using Binary Search

Introduction

Searching for an element in a sorted array is a common problem in computer science, and one of the most efficient ways to solve it is by using Binary Search. In this blog post, we'll discuss how to find the first and last positions of a target element in a sorted array using an optimized binary search approach. We'll also analyze its time complexity and why it outperforms brute-force methods.

Problem Statement

Given an array of integers nums sorted in non-decreasing order, we need to find the starting and ending position of a given target value. If target is not found, we return [-1, -1]. The solution must have a time complexity of O(log n).

Approach: Modified Binary Search

Since the array is sorted, binary search is an ideal approach. Instead of a single search, we perform two separate searches:

  1. Finding the Leftmost Index: We modify the binary search to continue searching on the left even after finding the target.
  2. Finding the Rightmost Index: Similarly, we modify the binary search to continue searching on the right.

Code Implementation

from typing import List

class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        def sidedBinarySearch(
            nums: List[int], target: int, is_right_search: bool
        ) -> int:
            start = 0
            end = len(nums) - 1
            index = -1

            while start <= end:
                mid = (start + end) // 2
                if nums[mid] < target:
                    start = mid + 1
                elif nums[mid] > target:
                    end = mid - 1
                else:
                    index = mid
                    if is_right_search:
                        start = mid + 1
                    else:
                        end = mid - 1
            return index

        start = sidedBinarySearch(nums, target, False)
        end = sidedBinarySearch(nums, target, True)

        return [start, end]

Complexity Analysis

  • Time Complexity: O(log n), since we perform two binary searches.
  • Space Complexity: O(1), as we use only a few integer variables.

Conclusion

By using binary search in a strategic way, we can efficiently determine the first and last occurrences of a target element in a sorted array. This method significantly outperforms brute-force approaches, making it ideal for large datasets.

For the full solution and explanation, check out my LeetCode post: Solving it using Binary Search by Bikash.

Comments

Popular posts from this blog

3Sum Closest: O(n²) Two-Pointer Magic šŸš€ leetcode: 16

Kadane's Algorithm: Maximum Subarray Problem - LeetCode(53) Solution

14. Longest Common Prefix