Find First And Last Position of Element in Sorted Array

LeetCode has a Medium coding Problem in Its’ Algorithm Section “Find First And Last Position of Element in Sorted Array”. Today We are going to solve this problem. LeetCode Link of the Problem is HERE

Find First And Last Position of Element in Sorted Array

Question

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.

Examples

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

Constraints to the problem:

  • 0 <= nums.length <= 105
  • -109 <= nums[i] <= 109
  • nums is a non-decreasing array.
  • -109 <= target <= 109

Solution to Find First And Last Position of Element in Sorted Array

Skeleton Code given by Leetcode on its site.

class Solution(object):
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        

To an ordered array of integers, find start and end positions of the same target, defines the time complexity is O (logn).

Solution: dichotomy, the complexity of the time typical binary search method, first using a binary search for the original array, find out the location of a target, and then find the start and end positions on both sides to search.

Complete Solution to the given problem

class Solution(object):
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        res = [-1, -1]
        if nums is None or len(nums) == 0:
            return res
        size = len(nums)
        l, r = 0, size - 1
        while l < r:
            m = (l + r)/2
            if nums[m] < target:
                l = m + 1
            else:
                r = m
        if nums[r] != target:
            return res
        res[0] = r
        l, r = 0, size
        while l < r:
            m = (l + r)/2
            if nums[m] <= target:
                l = m + 1
            else:
                r = m
        res[1] = l - 1
        return res

READ MORE

Python-related posts Visit HERE

C++ related posts Visit HERE

Databases related posts Visit HERE

Data Structures related posts visit HERE

Algorithms related posts visit HERE

Data Science related posts visit HERE

Share the Knowledge