LeetCode Find First and Last Position of Element in Sorted Array Solution Explained - Java

แชร์
ฝัง
  • เผยแพร่เมื่อ 24 ธ.ค. 2024

ความคิดเห็น • 106

  • @eshagupta9407
    @eshagupta9407 4 ปีที่แล้ว +92

    Got it in an interview today! Thanks a ton!

    • @abarag8
      @abarag8 3 ปีที่แล้ว +5

      Which company? What other questions were asked?

    • @KcClips
      @KcClips 2 ปีที่แล้ว +1

      @@abarag8 Are You doing Job ?

  • @Ola-xx4zh
    @Ola-xx4zh 4 ปีที่แล้ว +19

    Man, I was struggling with this for a long while and couldn't find a good explanation anywhere, until I found you and I think, I finally got it. You are doing a really good job, thanks!

  • @debasismandal1924
    @debasismandal1924 4 ปีที่แล้ว +25

    He made it seems so easy * meanwhile me stuck on this one since last hr * Thanks!

  • @tannerbarcelos6880
    @tannerbarcelos6880 4 ปีที่แล้ว +7

    I knew binary search was needed when hearing “sorted” then hearing “log N” supported that idea. However, the disconnect I was having was how to slightly tweak the search to accommodate for multiple targets in a row and get the left and right most. This video helped solve that disconnect. Thanks bro 🙏🏼

  • @kumarc4853
    @kumarc4853 3 ปีที่แล้ว

    Nick White for President of Programming.
    I got a variation of this in a interview recently, which is find the last index of an element in sorted array, whose index is equal to the value.
    The technique to find first or last was very helpful.

  • @akshaydwivedi935
    @akshaydwivedi935 5 ปีที่แล้ว +68

    All your videos are exceptionally good better then other fancy programmers.

    • @RaymondLo84
      @RaymondLo84 4 ปีที่แล้ว +8

      Not sure why but there are lots of Indian coding tutorials and always have a hard time understanding what they are trying to teach.

    • @andrewsavin9596
      @andrewsavin9596 ปีที่แล้ว

      @@RaymondLo84 🙂

  • @borishuang887
    @borishuang887 4 ปีที่แล้ว +2

    Simple and straightforward. No BS. Just hit it right on point. just a clean code and well-structural linear flow. thank you.

  • @davaa847
    @davaa847 4 ปีที่แล้ว +2

    Learned a lot from you, not only problem solution but also coding style.
    I watch your solution even I got my own solution to optimize my coding style and readability, This one was mindblowing my run time was also 0ms 100% BUT my code readability was not up to your standard. Keep doing the good work man.

  • @sarvottampriyadarshee5425
    @sarvottampriyadarshee5425 4 ปีที่แล้ว +17

    Thanks man! You saved me!
    and that Keyboard sound is so satisfying!

  • @satyamgupta6030
    @satyamgupta6030 ปีที่แล้ว +1

    thanks thanks alot nick brother.
    Please keep on making such videos.
    your leetcode solution videos help students all over the world.

  • @ZhouHaibo
    @ZhouHaibo 3 ปีที่แล้ว

    Pretty easy and clear, add 1 earlier break when first index is -1.
    ```
    result[0] = findStartIndex(nums, target);
    if (result[0] == -1) {
    result[1] = -1;
    return result;
    }
    ```

  • @alibaba998
    @alibaba998 4 ปีที่แล้ว +12

    Great video. One comment, If the firstIndex==-1 then we don't need to call the secondIndex binarySearch, right?

    • @miashani
      @miashani 4 ปีที่แล้ว +2

      correct, and also if it is NOT -1, I'd start findEndIndex with firstIndex+1 (add parameter to finction...)

    • @Abhishek_Poddar
      @Abhishek_Poddar 3 ปีที่แล้ว

      @@miashani but it won't create some significance change in time complexity of the problem or it will be ? ....cuz binary search will be like the way it is !!

  • @somyasinha6293
    @somyasinha6293 ปีที่แล้ว +1

    U did not check for the corner cases i.e when the mid = target so in that case we need to check that mid==0 || nums[mid-1]!=nums[mid] then return mid;

  • @nawaz_haider
    @nawaz_haider 3 ปีที่แล้ว

    I've watched 3 videos for this problem. But this one is the best. Thanks Nick.

  • @anmolverma075
    @anmolverma075 2 ปีที่แล้ว

    At 8:13 , what is the difference between the condition of this function and for the start index function?
    I don't understand because they are basically the same.
    Can anyone explain?

  • @wendywang8535
    @wendywang8535 4 ปีที่แล้ว +3

    Great Explanation!! Much better than those few lines code, and also I think this is really good for interview, you can explain your idea very clear. Thank you!

  • @rupaldesai7098
    @rupaldesai7098 5 ปีที่แล้ว +3

    If the target value occurs only once in the input array then the result[0] = indexvalue and result[1] = -1? Please correct if I am wrong..

    • @NickWhite
      @NickWhite  5 ปีที่แล้ว +6

      result[0] = indexvalue and result[1] = indexvalue. They would equal the same index value because there is only one occurrence of target in the array. That's why the conditions are = because they will find the target but then keep going to make sure it's not the only occurrence. At the end of each loop if they have seen the target we will set the index variable to the index we saw the target at

    • @rupaldesai7098
      @rupaldesai7098 5 ปีที่แล้ว +1

      @@NickWhite Got it! Thanks

  • @shivalikagupta3433
    @shivalikagupta3433 2 ปีที่แล้ว

    U had done same, just that i was writing the list.get(mid)==target condition first followed by other conditions(start = mid+1 or end = mid-1 as and when) Following this same as you did, I finally arrived at my answer. Thanks !!!:))

  • @prathamchitransh5338
    @prathamchitransh5338 2 ปีที่แล้ว

    Best Solution for this problem.

  • @ahmetozdemir2207
    @ahmetozdemir2207 4 ปีที่แล้ว +1

    If I remember this correctly, there was a better solution which does not solve this problem with 2 binary search. One is enough actually. While you are searching for a target value, you just have to remember last "smaller" and "bigger" number of target and maybe their indices. Then you simply add 1 to smaller value's index and subtract 1 to other index.

  • @saravanansarangan7035
    @saravanansarangan7035 5 ปีที่แล้ว +5

    Easily readable code Nick great work.. Thank you...

  • @kahizer
    @kahizer 4 ปีที่แล้ว +1

    very neat code, nice way of using methods rather than optimizing code lines and making it very hard to understand it. Very well explained

  • @akshaybhosale2724
    @akshaybhosale2724 3 ปีที่แล้ว

    Why did we not do linear search again? Did I miss something?
    start a loop with start and end as -1
    when you see the target first time set start = i and then till i is greater than target set end = i-1 and return.

  • @StayPuft787
    @StayPuft787 2 ปีที่แล้ว

    7:52 So ye, for the last index I just used the same code but removed the equals sign. if (nums[midpoint] > target) {
    end = midpoint - 1;} and it also worked

  • @bmy4415
    @bmy4415 4 ปีที่แล้ว +2

    What a nice explanation! This really helped me. Thanks

  • @fengxie4762
    @fengxie4762 4 ปีที่แล้ว

    The logic is so clear and the explanation is very easy to understand! Thx!

  • @akshatshah3013
    @akshatshah3013 4 ปีที่แล้ว +1

    Why cant we use the indexOf() and lastIndex() methods and store them in result?

    • @hritwiksom3032
      @hritwiksom3032 4 ปีที่แล้ว

      We can but in an interview, the interviewer won't be happy with it or ask for the logic anyway

  • @Leo-zh2or
    @Leo-zh2or 3 ปีที่แล้ว

    Nice solution. Easy to understand. Good job. Thanks.

  • @free-palestine000
    @free-palestine000 5 ปีที่แล้ว +1

    nick white >>>>

  • @ankurranjan3218
    @ankurranjan3218 3 ปีที่แล้ว

    This is really a good solution. Kudos @Nick

  • @tusharpadihar7030
    @tusharpadihar7030 4 ปีที่แล้ว +2

    You are a genius ❤️

  • @gourabbanerjee4152
    @gourabbanerjee4152 4 ปีที่แล้ว

    Excellent Description ! The best solution explanation I have found for this problem. Thank you!!

  • @yahwehagape
    @yahwehagape 4 ปีที่แล้ว

    Is it bad practice to rely on int casting to take the floor?

    • @hritwiksom3032
      @hritwiksom3032 4 ปีที่แล้ว

      This is implicit casting so I don't see why it would be.

  • @benjaminmalley5719
    @benjaminmalley5719 4 ปีที่แล้ว

    Did you consider binary search for this problem?

  • @rovingravi4603
    @rovingravi4603 4 ปีที่แล้ว

    Great explanation, very readable and clean coding... Thanks for sharing!!

  • @ManishKumar-xt6kf
    @ManishKumar-xt6kf 3 ปีที่แล้ว

    Thank u
    U explained it in simple way

  • @vaibhavjain4710
    @vaibhavjain4710 4 ปีที่แล้ว

    I have done using recrusive solution but got me error . Thanks for iterative version of the problem.

  • @Ramentop88
    @Ramentop88 5 ปีที่แล้ว

    Instead of combing through the discussion boards I check your channel first, leetcode solution , and discussion board last.

  • @chillu420
    @chillu420 3 ปีที่แล้ว +2

    the video is at 1.4K likes right now, Can we make it to be more liked than the actual leetcode question likes in this particular video i.e 1.9k

  • @044_karan9
    @044_karan9 4 ปีที่แล้ว

    outstanding explanation

  • @adjmonkey
    @adjmonkey 4 ปีที่แล้ว

    Why not just find any index of it with a normal binary search and then just move two pointers left and right until it changes? Then just an initialize an array with those pointers+-1? That would be faster unless the array has 10,000 of 1 value (or something obtuse like that) and a lot less code.

    • @RhymesWithCarbon
      @RhymesWithCarbon 4 ปีที่แล้ว

      adjmonkey this is along the same lines as what i was thinking, have two pointers, one far left and one far right, and start moving towards the middle. If one pointer finds a match, keep it moving until it finds another match. Then: if the unmatching Pointer and matching pointer overlap, stop, you know there’s only one match at all. Or if the unmatching pointer gets a hit, stop.

    • @bestsaurabh
      @bestsaurabh 4 ปีที่แล้ว +3

      That would be linear time complexity. Imagine having an array of same number repeating n times.

  • @surajpenugonda4756
    @surajpenugonda4756 5 ปีที่แล้ว +2

    Nice work bro

  • @nhht77
    @nhht77 4 ปีที่แล้ว +2

    Somehow, I tried the same method in Javascript but it didn't work. It works well on Java.

    • @aman4434
      @aman4434 4 ปีที่แล้ว

      Because mid in javascript will give decimal values on dividing by 2! Just tried myself and found out :)

  • @aravinds6406
    @aravinds6406 ปีที่แล้ว

    Well explained

  • @svalyavasvalyava9867
    @svalyavasvalyava9867 4 ปีที่แล้ว

    Can, please, someone explain why
    start + (end - start) / 2
    is preferrable to
    (start + end) / 2
    Thanks in advance.

    • @neloangelo172
      @neloangelo172 4 ปีที่แล้ว +1

      Use the first way to avoid integer overflow

    • @svalyavasvalyava9867
      @svalyavasvalyava9867 4 ปีที่แล้ว +1

      @@neloangelo172 thanks a lot, got it

  • @Taheershaik
    @Taheershaik 3 ปีที่แล้ว

    Clean... Great job, thanks mate.

  • @surajgrandhi6742
    @surajgrandhi6742 4 ปีที่แล้ว

    Amazing solution

  • @ethanhuang2127
    @ethanhuang2127 5 ปีที่แล้ว

    Since the time complexity only considers the worst case, if all integers in the list are the same, the time complexity would be O(n)...
    I have a not-so-smart proposal --"how about searching for targart-(smallest number) and target+(smallest number) and return the closest index?

    • @maddinmanek8679
      @maddinmanek8679 4 ปีที่แล้ว +1

      The time complexity would still be a fast binary search - and meet the log n. That only one of each occurs would make no difference in that.

    • @maddinmanek8679
      @maddinmanek8679 4 ปีที่แล้ว +1

      Of course you could check is first and last element are the same before running the algorithm.

  • @a4ankit27
    @a4ankit27 4 ปีที่แล้ว

    Why does this code return -1, -1 for me ? Any guesses , what i might me missing ?

    • @a4ankit27
      @a4ankit27 4 ปีที่แล้ว

      var searchRange = function(nums, target) {
      let array = [];
      array[0] = firstIndex(nums, target);
      array[1] = lastIndex(nums, target);
      return array;
      }
      var firstIndex = function(nums, target) {
      let index = -1;
      let start = 0;
      let end = nums.length -1;

      while (start = target) {
      end = middle -1
      } else {
      start = middle +1;
      }
      if(nums[middle] == target) {
      index = middle;
      }
      }
      return index;
      }
      var lastIndex = function(nums, target) {
      let index = -1

      let start = 0;
      let end = nums.length -1;

      while (start

    • @paveldubinin515
      @paveldubinin515 4 ปีที่แล้ว +1

      @@a4ankit27 your "middle" is float (use Math.floor() to convert to integer). He uses java and his variables are typed int so this happens automatically there.

  • @jashbhatia3948
    @jashbhatia3948 3 ปีที่แล้ว

    Question: Why not just find the left most index and then traverse through the array till we keep finding duplicates?

    • @fhantom784
      @fhantom784 3 ปีที่แล้ว +1

      That'd be O(n) in the worst case (e.g. an array of all 8s).
      What you could do though is use the left index as "start" when searching for the right index.

  • @amansayer4943
    @amansayer4943 ปีที่แล้ว

    class Solution {
    public int[] searchRange(int[] nums, int target) {
    int[] ans = {-1, -1};
    // First Occurrence
    int start = 0, end = nums.length - 1;
    int mid = (start + end) / 2;
    while (start nums[mid]) {
    start = mid + 1;
    }
    }
    // Last Occurrence
    start = 0;
    end = nums.length - 1;
    while (start nums[mid]) {
    start = mid + 1;
    }
    }
    return ans;
    }
    } clean code

  • @PramodRj
    @PramodRj 4 ปีที่แล้ว

    Great Video Nick!! Thanks

  • @rchukkapalli1
    @rchukkapalli1 4 ปีที่แล้ว

    Good explanation. Subscribed!

  • @dinamohamed13600
    @dinamohamed13600 ปีที่แล้ว

    very helpful thanks

  • @gaurbasu5274
    @gaurbasu5274 4 ปีที่แล้ว

    Great Explanation!

  • @NickKravitz
    @NickKravitz 4 ปีที่แล้ว

    Nice explanation, but you have broken the "don't repeat yourself" rule. Methods are similar enough to combine into a single method with a boolean startingOrEnding input variable.

  • @RawBert
    @RawBert 3 ปีที่แล้ว

    there’s a better way, get index of first, then with that index look at how long it goes

  • @huihuang2294
    @huihuang2294 5 ปีที่แล้ว +1

    Thank you for sharing

  • @existenence
    @existenence 5 ปีที่แล้ว

    Binary Search. Binary Search. Binary Search.

  • @yashwantkumar4998
    @yashwantkumar4998 4 ปีที่แล้ว

    you are superb bro !

  • @suprathikm3639
    @suprathikm3639 4 ปีที่แล้ว

    awesome Nick

  • @yashspr
    @yashspr 4 ปีที่แล้ว

    Simple and elegant explanation! Amazing man

  • @WLBx-x5c
    @WLBx-x5c 4 ปีที่แล้ว

    It's good!Thanks for sharing!

  • @RaymondLo84
    @RaymondLo84 4 ปีที่แล้ว

    I still really hate people writing code like those compressed javascripts with 1 line does all... I really don't think that's how the real world works...

  • @AshishKumar-dn6jc
    @AshishKumar-dn6jc 3 ปีที่แล้ว

    Thanks man!

  • @thesuburbanerrorist9727
    @thesuburbanerrorist9727 3 ปีที่แล้ว

    Dude you are like my hero and shit.

  • @lifeofme3172
    @lifeofme3172 4 ปีที่แล้ว

    Awesome video

  • @harikrishnak721
    @harikrishnak721 5 ปีที่แล้ว

    Thanks nick

  • @notgaurav
    @notgaurav 5 ปีที่แล้ว

    really good! keep it up

  • @visheshsahu-yn8wz
    @visheshsahu-yn8wz 2 ปีที่แล้ว

    big fan bro

  • @dushyantjakhar1716
    @dushyantjakhar1716 3 ปีที่แล้ว

    Everything is good but sound is not balance

  • @TheBestNameEverMade
    @TheBestNameEverMade 4 ปีที่แล้ว

    You don't need 2 binary searches.

    • @hritwiksom3032
      @hritwiksom3032 4 ปีที่แล้ว +1

      You mean you don't need 2 functions, two searches are obviously needed.

    • @TheBestNameEverMade
      @TheBestNameEverMade 4 ปีที่แล้ว +2

      @@hritwiksom3032 no he throws away information the way he does the search.
      You could split it into two and use the bounds found in the first as a starting point for the second. However you might as well just search for both at once and adjust both upper and lower ranges.
      At the very minimum he could have used the returned lower bound as the min range for the second algorithm, saving having to search the start of the array. Still that throws away information learned about the upper bound.

  • @tuannguyentranle7151
    @tuannguyentranle7151 5 ปีที่แล้ว +1

    So fancy ;))) thanks a lot

  • @farzanehahmadi9410
    @farzanehahmadi9410 4 ปีที่แล้ว

    you rock bro!

  • @somyasrivastava6315
    @somyasrivastava6315 3 ปีที่แล้ว

    you are Amazing

  • @abhishekkumarsinghA
    @abhishekkumarsinghA 2 ปีที่แล้ว

    awesome

  • @rubyjiang8836
    @rubyjiang8836 3 ปีที่แล้ว

    so smart

  • @shubhamuniyal2417
    @shubhamuniyal2417 4 ปีที่แล้ว

    Smooothhhh!!!!

  • @kingthunder9787
    @kingthunder9787 4 ปีที่แล้ว

    Hi

  • @sharuk3545
    @sharuk3545 3 ปีที่แล้ว

    Awesome solution