Find First and Last Position in Sorted Array – From Brute Force to Binary Search (LeetCode 34)
Find First and Last Position in Sorted Array – From Brute Force to Binary Search (LeetCode 34)

Find First and Last Position in Sorted Array – From Brute Force to Binary Search (LeetCode 34)

Optimizing from O(n) Linear Scan to O(log n) Binary Search

18 views
0
0

Problem Link

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

👉 https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/

📌 Problem Overview

You are given a sorted array (non-decreasing order) and a target value.

Your task:

  1. Return the starting and ending index of the target.
  2. If target does not exist → return [-1, -1]
  3. Required Time Complexity: O(log n)

Example 1

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

🧠 My First Intuition – Brute Force (O(n))

When I first saw this problem, my thinking was simple:

"Since the array is sorted, I just need to find the first occurrence and the last occurrence."

So I used two loops:

  1. One loop from left → to find first occurrence
  2. One loop from right → to find last occurrence

Here is my submitted solution:

class Solution {
public int[] searchRange(int[] nums, int t) {
int arr[] = new int[2];
arr[0] = -1;
arr[1] = -1;

for(int i = nums.length-1;i >=0 ;i--){
if(nums[i] == t){
arr[1] = i;
break;
}
}

for(int i = 0;i <nums.length ;i++){
if(nums[i] == t){
arr[0] = i;
break;
}
}
return arr;
}
}

✅ Why This Works

  1. Since the array is sorted, occurrences of the same number are grouped together.
  2. First loop (reverse) finds last occurrence.
  3. Second loop (forward) finds first occurrence.

❌ Problem with This Approach

Time Complexity = O(n)

Worst case:

  1. Target is not present
  2. We scan entire array twice

But the problem clearly states:

You must write an algorithm with O(log n) runtime complexity.

That means: We must use Binary Search.

🚀 Optimized Approach – Binary Search (O(log n))

💡 Key Intuition

If the array is sorted:

  1. We can use Binary Search to find the first occurrence
  2. We can use Binary Search again to find the last occurrence

Instead of stopping when we find the target:

  1. For first occurrence → continue searching left
  2. For last occurrence → continue searching right

🧠 Idea Breakdown

1️⃣ Find First Occurrence

When we find target at mid:

  1. Store index
  2. Move left → high = mid - 1
  3. Because there might be another occurrence before it

2️⃣ Find Last Occurrence

When we find target at mid:

  1. Store index
  2. Move right → low = mid + 1
  3. Because there might be another occurrence after it

💻 Optimized Code (Binary Search Approach)

class Solution {
public int[] searchRange(int[] nums, int target) {
int[] result = new int[2];
result[0] = findFirst(nums, target);
result[1] = findLast(nums, target);
return result;
}

private int findFirst(int[] nums, int target) {
int low = 0, high = nums.length - 1;
int index = -1;

while (low <= high) {
int mid = low + (high - low) / 2;

if (nums[mid] == target) {
index = mid;
high = mid - 1; // move left
} else if (nums[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return index;
}

private int findLast(int[] nums, int target) {
int low = 0, high = nums.length - 1;
int index = -1;

while (low <= high) {
int mid = low + (high - low) / 2;

if (nums[mid] == target) {
index = mid;
low = mid + 1; // move right
} else if (nums[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return index;
}
}

🔍 Why This Works

Binary Search normally stops when target is found.

Here, we modify it slightly:

  1. Keep searching even after finding target.
  2. Narrow the search space toward the boundary we want.

This guarantees:

  1. First occurrence → leftmost index
  2. Last occurrence → rightmost index

⏱ Complexity Analysis

Brute Force Approach

  1. Time: O(n)
  2. Space: O(1)

Binary Search Approach

  1. Time: O(log n)
  2. Space: O(1)

This satisfies the problem constraint.

🎯 Key Learning from This Problem

This problem teaches an important pattern:

When array is sorted and you need boundaries → Think Binary Search.

It is not just about finding the element.

It is about finding:

  1. First occurrence (Lower Bound)
  2. Last occurrence (Upper Bound)

This pattern appears in many interview problems.

📚 Similar Problems to Practice

  1. https://leetcode.com/problems/binary-search/
  2. https://leetcode.com/problems/search-insert-position/
  3. https://leetcode.com/problems/search-in-rotated-sorted-array/
  4. https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
  5. https://leetcode.com/problems/sqrtx/

🏁 Final Thoughts

My journey solving this problem:

  1. First thought → Use two loops (works but O(n))
  2. Then realized constraint → Must be O(log n)
  3. Optimized using two Binary Searches

This is how problem solving improves:

  1. Start with correct solution.
  2. Then optimize.
  3. Then recognize patterns.

LeetCode 34 is one of the most important Binary Search boundary problems.

If you master this, you unlock an entire category of advanced Binary Search questions.

Ai Assistant Kas