FIRST AND LAST OCCURRENCE

 

First and Last Occurrence of an Element in a Sorted Array

Introduction

In this problem, we are given a sorted array that may contain duplicate elements. The goal is to find the first and last occurrence of a given element.

Since the array is sorted, we can use Binary Search to solve this efficiently.

Problem Statement

Given a sorted array arr[] and a target x, return:

  • Index of the first occurrence of x

  • Index of the last occurrence of x

If x is not present, return [-1, -1].

Example

Input:

arr = [1, 3, 5, 5, 5, 5, 67, 123, 125]
x = 5

Output:

[2, 5]

Solution Code

class Solution:
    def find(self, arr, x):
        n = len(arr)

       
        low, high = 0, n - 1
        first = -1

        while low <= high:
            mid = (low + high) // 2

            if arr[mid] == x:
                first = mid
                high = mid - 1
            elif arr[mid] < x:
                low = mid + 1
            else:
                high = mid - 1

        low, high = 0, n - 1
        last = -1

        while low <= high:
            mid = (low + high) // 2

            if arr[mid] == x:
                last = mid
                low = mid + 1
            elif arr[mid] < x:
                low = mid + 1
            else:
                high = mid - 1

        return [first, last]

Approach Used: Modified Binary Search

Idea

We use Binary Search twice:

  • First to find the first occurrence

  • Second to find the last occurrence

How It Works

Finding First Occurrence

  • When arr[mid] == x:

    • Store index

    • Move left (high = mid - 1) to check for earlier occurrence

Finding Last Occurrence

  • When arr[mid] == x:

    • Store index

    • Move right (low = mid + 1) to check for later occurrence

Why This Approach Was Chosen

  • Efficient for sorted arrays

  • Avoids scanning entire array

  • Finds both positions in logarithmic time

Alternative Approach

  • Linear Search

    for i in range(n)
    

     Time Complexity: O(n)

Why not used?
Too slow for large arrays (up to 10⁶ elements)

Time and Space Complexity

  • Time Complexity: O(log n)

  • Space Complexity: O(1)

Important Observation

  • We don’t stop at first match

  • We continue searching to find boundary positions

  • That’s the key difference from normal binary search

Edge Cases

  • Element not present = return [-1, -1]

  • Only one occurrence = both indices same

  • All elements same

Conclusion

Using modified binary search allows us to efficiently find the first and last occurrences of an element in a sorted array. By slightly adjusting the search direction after finding the target, we can locate the exact boundaries in logarithmic time.

Comments

Popular posts from this blog

THE DELIVERY MAN

EC2 LAUNCHING

SORT A LINKED LIST USING MERGE SORT