LEETCODE SERIES || DAY 18 || (34) Find First and Last Position of Element in Sorted Array

1–2 minutes

read

Day 17 Leet code series, today we will be picking the problem Find First and Last Position of Element in Sorted Array (https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/).

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

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

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

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]

Example 3:

Input: nums = [], target = 0
Output: [-1,-1]
class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int start = -1;
        int end = -1;
        int count = 0;
        vector<int> res;
        for(int i=0;i<nums.size();i++){
            if(nums[i] == target){
                count++;
                end = i;
            }
        }
        if(count){
            start = end - count + 1;
        }
        res.push_back(start);
        res.push_back(end); 
        return res;
    }
};

Explaination:

  1. Just take start and end pointer.
  2. If the nums[i] matches the target keep the count and end will the the end pos of the occurance.
  3. Now to find start just subtract count from end and add 1 because indices are from 0.
  4. Return the resulted array.

Leave a comment