DEV Community

Cover image for Find First And Last Position of Element in Sorted Array
YTTMP3
YTTMP3

Posted on

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.

Image description
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
Visit https://hecodesit.com/find-first-and-last-position-of-element-in-sorted-array/ for solution

Top comments (0)