AlgoMaster Logo

Find First and Last Position of Element in Sorted Array

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Linear Scan

Intuition:

The simplest way to find the first and last positions of a target element in a sorted array is to perform a linear scan. We traverse the array from the beginning to end and record the positions when the target element matches.

Code:

2. Binary Search Twice

Intuition:

To improve efficiency, consider using binary search. By performing two separate binary searches, we can find the first occurrence and the last occurrence of the target element. The key is to tailor the binary search condition to continue searching for the first or last position once a target element is found.

Code:

Intuition:

We can further optimize by combining the searches for the first and last occurrence into a single binary search. We check for both conditions in a single run, further reducing complexity in terms of constant factors. This method uses binary search with a twist by utilizing stricter compared conditions.

Code: