DEV Community

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

Posted on

1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

If you found this post helpful, please consider leaving a ❤️ or a kind comment!

Sounds good!