LeetCode: Find First and Last Position of Element in Sorted Array

\(\)

Challenge Description

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm’s runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

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]

Naive Solution

Linear scan array from left to right or from right to left.

Find the first index with given value. A trivial optimization here is when we find current element is greater than target(search left to right), we won’t search the left elements.

Time complexity: \(O(N)\)

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> res;
        int le = -1, ri = -1;

        for(int i=0; i<nums.size(); i++) {
            if(nums[i] == target) {
                le = i;
                break;
            } else if(nums[i] > target) break;
        }

        for(int i=nums.size()-1; i>=0; i--) { 
            if(nums[i] == target) {
                ri = i;
                break;
            } else if(nums[i] < target) break;
        }

        res.push_back(le);
        res.push_back(ri);
        return res;
    }
};

Binary search

Naive approach will not meet the challenge requirement. We can use the approach of binary search, but it’s a variant of original binary-search.

Take search first left position for example, When we got an index(suppose idx) where value equal target, we store the current position and safely ignore the right part [idx ~ ..] of the array, so we update the hi pivot.

Search last right position is similar.

2020_02_03_leetcode-find-first-and-last-position-of-element-in-sorted-array.org_20200203_172745.png

Time complexity: \(O(logN)\).

#include <vector>
using namespace std;

class Solution {
public:
  int search(vector<int>& A, int target, bool search_left) {
    int lo = 0, hi = A.size()-1;
    int ans = -1;
    while(lo <= hi) {
      int mid = (lo + hi) / 2;
      if(A[mid] < target)
        lo = mid + 1;
      else if(A[mid] > target)
        hi = mid - 1;
      else {
        ans = mid;
        // find first left
        if(search_left)
          hi = mid - 1;
        else
          lo = mid + 1;
      }
    }
    return ans;
  }

  vector<int> searchRange(vector<int>& nums, int target) {
    vector<int> res;
    int left = search(nums, target, true);
    res.push_back(left);
    if(left == -1) {
      res.push_back(-1);
      return res;
    }
    int right = search(nums, target, false);
    res.push_back(right);
    return res;
  }

};

Preparing for an interview? Check out this!

Last Updated on

Leave a Reply

Your email address will not be published. Required fields are marked *