BackendML

First and Last Occurrence of a Number

Easy2 min read
The Find First and Last Position of Element in Sorted Array problem requires finding the starting and ending positions of a target value in a sorted array.

Problem

Given a sorted array of integers nums and an integer target, return the starting and ending position of the target value.

If the target does not exist in the array, return [-1, -1]. The algorithm should run in O(log n) time.

Example(s)

Consider the following examples to understand the expected input and output.

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]

Solution

This solution uses Binary Search twice. The first search finds the first occurrence of the target, while the second search finds the last occurrence.

To find the first occurrence, when nums[mid] == target, we store the index and continue searching in the left half because another occurrence may exist earlier.

To find the last occurrence, when nums[mid] == target, we store the index and continue searching in the right half because another occurrence may exist later.
class Solution {
    public int[] searchRange(int[] nums, int target) {
        int first = findFirst(nums, target);
        int last = findLast(nums, target);

        return new int[]{first, last};
    }

    private int findFirst(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int result = -1;

        while (left <= right) {
            int mid = left + (right - left) / 2;

            if (nums[mid] == target) {
                result = mid;
                right = mid - 1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return result;
    }

    private int findLast(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int result = -1;

        while (left <= right) {
            int mid = left + (right - left) / 2;

            if (nums[mid] == target) {
                result = mid;
                left = mid + 1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return result;
    }
}

Complexity

Each Binary Search takes O(log n) time. Since we perform two binary searches, the overall time complexity is O(log n).

The algorithm uses only a few variables, so the extra space complexity is O(1).

Comments

No comments yet. Ask a question or share what helped.