Find First and Last Position of Element in Sorted Array

by atalaykutlay

A not so great solution to "Find First and Last Position of Element in Sorted Array" question on Leetcode.

Find First and Last Position of Element in Sorted Array
1class Solution:
2    def searchRange(self, nums: List[int], target: int) -> List[int]:
3
4        def binarysearch(nums, target):
5            left = 0
6            right = len(nums)-1
7            while left <= right:
8                middle = left + (right-left)//2
9                if nums[middle] < target:
10                    left = middle + 1
11                elif nums[middle] > target:
12                    right = middle - 1
13                else:
14                    return middle
15            return -1
16        
17        found_index = binarysearch(nums, target)
18        if found_index == -1:
19            return [-1,-1]
20
21        left, right = found_index, found_index
22        while left > 0:
23            if nums[left-1] == target:
24                left -= 1
25            else:
26                break
27        
28        while right < len(nums)-1:
29            if nums[right+1] == target:
30                right += 1
31            else:
32                break
33
34        return [left, right]

Share

Share
Video
A cool 10 sec video.
Share
Detailed
Title, description, and syntax highlighted code.
Share
Simple
Syntax highlighted code with gradient background colored presentation.

Comments

It looks like there is no comment for this snippet. Leave the first one!
You need to login to send a comment.

Similar Snippets

Count Number of Texts
Count Number of Texts

Solution to "Count Number of Texts" question on Leetcode.

Language: python12 months ago
Quicksort in Python
Quicksort in Python

An easy quicksort implementation in Python.

Language: python13 months ago
Second Minimum Node In a Binary Tree
Second Minimum Node In a Binary Tree

Solution to "Second Minimum Node In a Binary Tree" on Leetcode.

Language: python11 months ago