First and Last Position of Element in Sorted Array - Binary Search - Leetcode 34

Sdílet
Vložit
  • čas přidán 27. 07. 2024
  • 🚀 neetcode.io/ - A better way to prepare for Coding Interviews
    🐦 Twitter: / neetcode1
    🥷 Discord: / discord
    🐮 Support the channel: / neetcode
    Coding Solutions: • Coding Interview Solut...
    Problem Link: leetcode.com/problems/find-fi...
    0:00 - Read the problem
    1:35 - Drawing Explanation
    5:15 - Coding Explanation
    leetcode 34
    This question was identified as a microsoft interview question from here: github.com/xizhengszhang/Leet...
    #binary #search #python
  • Věda a technologie

Komentáře • 82

  • @NeetCode
    @NeetCode  Před 3 lety +2

    💡 BINARY SEARCH PLAYLIST: czcams.com/video/U8XENwh8Oy8/video.html

  • @MP-ny3ep
    @MP-ny3ep Před 2 lety +33

    I watched some 4-5 videos for this problem , but this is hands down the most easiest and intuitive way of solving.
    Thanks a ton

  • @Chirayu19
    @Chirayu19 Před 11 měsíci +6

    Initially what I did is finding the element through binary search and then iterating left and right to find leftmost and rightmost. But now I realized in worst case that would be O(N).
    Thanks a ton for this video!

  • @nishanttanwar99
    @nishanttanwar99 Před 3 lety +2

    Great Explanation, I found the video using the link given in the leetcode post. This solution is so intuitive and is much better than the solution provided with the Leetcode problem. Keep up the good work.

  • @appcolab
    @appcolab Před 2 lety +6

    Wow!! Man, I love this. I was just coming across some complicated solutions but this 🔥, thank you so much!

  • @healing1000
    @healing1000 Před rokem

    Thank you. This is better than all leetcode discuss solutions. I don't even think I will forget this one

  • @MsSkip60
    @MsSkip60 Před 3 lety +1

    Great thanks! Tried tuning a little bit further and start searching after we found initial match but lots of edge cases in that case tbh

  • @aryanyadav3926
    @aryanyadav3926 Před 2 lety +9

    Using leftBias boolean variable was very clever.

  • @CasualyinAir
    @CasualyinAir Před 3 lety

    Thanks! Very clean approach. I like your explanation too, very concise.

  • @anshumansharma6758
    @anshumansharma6758 Před 3 lety

    You explain very well. Thanks for working hard on these explanations

  • @ShivangiSingh-wc3gk
    @ShivangiSingh-wc3gk Před 2 lety

    The binary search updates were very intutive thank you

  • @ChanChan-pg4wu
    @ChanChan-pg4wu Před 2 lety

    Great Explanation! Thanks for your smart and hard work.

  • @nataliagrigoryeva6615
    @nataliagrigoryeva6615 Před 3 měsíci

    As always, such a great explanation! I have a small suggestion for a slight efficiency boost: if the target is not in the array, we could run the binary search once and set right to -1 if left is -1, without running the binary search a second time.

  • @chenlee7934
    @chenlee7934 Před 2 lety

    This is the best explanation i watched, thank u.

  • @glen6638
    @glen6638 Před 2 lety

    Nice , it’s easy to understand.👍

  • @ltxlouis3918
    @ltxlouis3918 Před 2 lety

    Thank you! Great explanation

  • @yunaliu5946
    @yunaliu5946 Před 2 lety +1

    Best solution that I have ever seen

  • @arindammandal1513
    @arindammandal1513 Před 2 lety

    Always love ur explanation bro!!!

  • @sanjeeeeev
    @sanjeeeeev Před 3 lety

    Best Explaination EVER 🔥

  • @vaibhavdesai16
    @vaibhavdesai16 Před 2 lety

    I was used similar approach but I used binary search exit condition as (nums[mid] == target && nums[mid -1] != target) similarly for right bias it will nums[mid+1] != target. This one is much cleaner

  • @yalebass
    @yalebass Před rokem

    it makes total sense to use binary search to find the left and rightmost instances if the target, I don’t know why I suddenly let my code return to O(n). Thanks for the vid!

  • @vikassharma-ky1dv
    @vikassharma-ky1dv Před 4 měsíci +1

    We can optimise it further by finding first index , if not found we need not find second Index

  • @sivaganesh4489
    @sivaganesh4489 Před 2 lety

    awesome explanation

  • @anandhu5082
    @anandhu5082 Před 3 lety +2

    after r=m-1 and l=m+1, won't it be better if we return if the values in this new position != target? (To stop the search to left(or right) if we already reached left(or right) end)

  • @eshabaweja
    @eshabaweja Před rokem

    solved it myself; here to compare and improve :)

  • @atg878
    @atg878 Před měsícem +1

    great of the greatest 🙌🙌

  • @今天比昨天厲害
    @今天比昨天厲害 Před 3 lety

    You are amazing!

  • @yfh7024
    @yfh7024 Před 2 lety +1

    Hi, I have a question: my code looks almost the same to you expect my mid is m = l + (r - l) //2, when it executed test case: [2,2] 3, I got exceed time limit. but when I changed it to m = (l + r)//2, my code was accepted.

  • @AdityaBhongade
    @AdityaBhongade Před 4 měsíci

    Respect, sir!

  • @jnayehsirine6222
    @jnayehsirine6222 Před 2 měsíci

    ur channel is a safe place to me haha

  • @samCoder
    @samCoder Před 2 lety +2

    Had I watched your video before my interview, I would have cleared the interview :(

  • @edwardteach2
    @edwardteach2 Před 2 měsíci

    U a binary search God

  • @xinniu3145
    @xinniu3145 Před 2 lety

    Thanks this is so clear!

  • @jennielieu3312
    @jennielieu3312 Před rokem +1

    Do we need to define the leftBias function?

  • @HR-pz7ts
    @HR-pz7ts Před 11 měsíci

    My first approach was binary search and it unfortunately didn't worked and had to switch to linear search and it worked just fine after a few tries with using few conditions and Boolean. And for some reason it was better than 100% java submissions for time complexity.

  • @nagendrabommireddi8437

    thanks boss

  • @yuanfeng4843
    @yuanfeng4843 Před 9 měsíci

    class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
    def binSearch(leftBias):
    l, r, i = 0, len(nums)-1, -1
    while l nums[mid]: l = mid + 1
    elif target < nums[mid]: r = mid - 1
    else:
    i = mid
    if leftBias: r = mid - 1
    else: l = mid + 1
    return i
    return [binSearch(True), binSearch(False)]

  • @qazyip
    @qazyip Před 2 lety +1

    If I use a two pointer method, left at index 0 and right at end of length, traverse each until both meets the target and return left, right.
    Would this be o(n)?

  • @danishshaikh6151
    @danishshaikh6151 Před 2 měsíci

    If we just add This will reduce 1 extra logN is the target is not present
    if left == -1:
    return [-1, -1]

  • @satyakidas4835
    @satyakidas4835 Před rokem

    Hi I am getting an error SyntaxError: 'return' outside function can you please suggest what to do?

  • @SaulLee66
    @SaulLee66 Před 3 lety

    Could we do it in one while loop?

  • @LazyCoder20
    @LazyCoder20 Před 4 měsíci

    Its easy to do it using lower bound and upper bound - 1.

  • @eamonmahon6622
    @eamonmahon6622 Před rokem

    Why can't the helper function be nested and just have leftBias as the input argument?

  • @Vivekkumar-zc7mz
    @Vivekkumar-zc7mz Před 4 měsíci

    we use upper bound and lower bound for this

  • @yashsolanki3665
    @yashsolanki3665 Před rokem

    Nice

  • @sensei1781
    @sensei1781 Před 2 lety

    Since its sorted cant you just iterate once you find either the left or right target index?

    • @myroncarvalho4872
      @myroncarvalho4872 Před rokem +3

      time complexity would be O(n) in that case the moment you start iterating. coz in worst case you can have an array with all elements as target.

  • @BasicToAdvance_101
    @BasicToAdvance_101 Před 2 měsíci

    Bringing the Algorithms 101
    class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
    def binary_search_leftmost(A,T):
    L = 0
    R = len(A)
    while L < R:
    m = floor((L + R) / 2)
    if A[m] < T:
    L = m + 1
    else:
    R = m
    return L
    def binary_search_rightmost(A,T):
    L = 0
    R = len(A)
    while L < R:
    m = floor((L + R) / 2)
    if A[m] > T:
    R = m
    else:
    L = m + 1
    return R - 1
    l = binary_search_leftmost(nums,target)
    r = binary_search_rightmost(nums,target)
    return [l,r] if target in nums else [-1,-1]

  • @akshayskumar2427
    @akshayskumar2427 Před rokem

    what is the use of leftbias?

  • @krishgusain3959
    @krishgusain3959 Před 2 lety

    got it

  • @5_tejabvs818
    @5_tejabvs818 Před rokem

    isn't the time complexity O(log(n^2))

  • @henrydi800
    @henrydi800 Před 2 lety

    why need to update the left and right pointers when finding the target variable

    • @haruhipoulain8953
      @haruhipoulain8953 Před 11 měsíci

      Because we need to search most left and most right el

  • @ShashwataSaha-wb8qd
    @ShashwataSaha-wb8qd Před rokem

    How's it Log(N) everywhere it's showing as Log(N) TC. But no, it's O(Log(N)) before it enters in the last else block, as it enters the last else block it will iteratively reset the binary search for about log(N) times. So the time complexity should be O(log(N)*log(N)). Open to suggestions.

    • @haruhipoulain8953
      @haruhipoulain8953 Před 11 měsíci

      In the last loop we have some l and r index, so we have some range like r - l + 1 to check. And after that it not get bigger, after one operation we always get to check (r - l + 1) / 2 range. So it's log(n) because we always divide range by 2

  • @nodirbekhbudi1208
    @nodirbekhbudi1208 Před 2 lety

    How to run this in jupyter notebook

  • @jhonrobaon1669
    @jhonrobaon1669 Před 2 lety

    Code is good but for worst case, the complexity would be O(n) which is not acceptable

    • @denniskang6768
      @denniskang6768 Před 2 lety

      can you pls explain why it's O(n) in worst case?

  • @danielbzhang3280
    @danielbzhang3280 Před rokem

    Here's my solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
    leftpos, rightpos = -1, -1
    l, r = 0, len(nums)-1

    while l = 0 and nums[mid-1] == target:
    mid -= 1
    leftpos = mid
    while mid+1 target:
    r = mid - 1
    else:
    l = mid + 1
    return [leftpos, rightpos]

  • @igorf243
    @igorf243 Před 4 měsíci

    how is it medium?

  • @abhinav_mittal
    @abhinav_mittal Před 9 měsíci

    can some one tell me why can't i use this:-
    class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
    for i in nums:
    if target not in nums or len(nums)==0:
    return [-1, -1]

    elif target in nums:
    return [nums.index(target), len(nums) - 1 - nums[::-1].index(target)]
    And also this doesn't satisfy the Case 3:-
    Input: nums = [], target = 0
    Output: [-1,-1]
    Please tell me why .....

    • @RichItUp
      @RichItUp Před 2 měsíci

      Because the time complexity will be O(n) in the worst case. If all the elements are target.

  • @sniff4643
    @sniff4643 Před 3 lety

    video request!: leetcode.com/problems/jump-game/
    the DP solution is quadratic time. but the greedy one is linear?! could you help explain how the greedy works lol

    • @NeetCode
      @NeetCode  Před 3 lety

      Yeah, I like that problem, I'm gonna try to do it soon, thank you for the request!

  • @eugene6070
    @eugene6070 Před rokem

    hello my fellow sharpenarians

  • @__Y1a2s3h4__
    @__Y1a2s3h4__ Před 2 lety

    This code doesn't works for me

  • @nathamuni9435
    @nathamuni9435 Před 2 lety

    hay

  • @ARkhan-xw8ud
    @ARkhan-xw8ud Před měsícem

    why i = -1

  • @lostmeme9862
    @lostmeme9862 Před rokem

    I cheated and used floats.

  • @shubham2440
    @shubham2440 Před 2 lety

    93% Faster - 64 ms and 61% better memory usage
    class Solution(object):
    def searchRange(self, nums, target):
    l=0
    h=len(nums)-1

    loc = ['p']*2
    if len(nums)==0:
    return [-1,-1]
    if len(nums)==1 and target==nums[0]:
    return [0,0]


    if len(nums)==1 and target!=nums[0]:
    return [-1,-1]
    while l

  • @piyushbansal9716
    @piyushbansal9716 Před 3 lety +1

    lol i came for the edge cases and they are not there whats the point on teaching the simple binary search 😂😂

    • @arunr2265
      @arunr2265 Před 3 lety +8

      can you provide one edge case

  • @aleksproger_il
    @aleksproger_il Před rokem

    My solution:
    public class Solution {
    public int[] SearchRange(int[] nums, int target) {
    int[] res = {-1, -1};
    if(nums.Length == 0) return res;
    int l = 0;
    int r = nums.Length - 1;
    while(l