5 First and Last occurrence of an Element

Sdílet
Vložit
  • čas přidán 10. 03. 2020
  • FIND FIRST AND LAST POSITIONS OF AN ELEMENT IN A SORTED ARRAY:
    Given a sorted array with possibly duplicate elements, the task is to find indexes of first and last occurrences of an element x in the given array.
    Example:
    Input : arr[] = {1, 3, 5, 5, 5, 5 ,67, 123, 125}
    x = 5
    Output : First Occurrence = 2
    Last Occurrence = 5
    PROBLEM STATEMENT LINK:www.geeksforgeeks.org/find-fi...
    PLAYLIST LINK: • Binary Search | Interv... .
    ------------------------------------------------------------------------------------------
    Here are some of the gears that I use almost everyday:
    🖊️ : My Pen (Used in videos too): amzn.to/38fKSM1
    👨🏻‍💻 : My Apple Macbook pro: amzn.to/3w8iZh6
    💻 : My gaming laptop: amzn.to/3yjcn23
    📱 : My Ipad: amzn.to/39yEMGS
    ✏️ : My Apple Pencil: amzn.to/3kMnKYf
    🎧 : My Headphones: amzn.to/3kMOzM7
    💺 : My Chair: amzn.to/385weqR
    🛋 : My Table: amzn.to/3kMohtd
    ⏰ : My Clock: amzn.to/3slFUV3
    🙋🏻‍♀️ : My girlfriend: amzn.to/3M6zLDK ¯\_(ツ)_/¯
    PS: While having good gears help you perform efficiently, don’t get under the impression that they will make you successful without any hard work.

Komentáře • 194

  • @anamaysrivastava1219
    @anamaysrivastava1219 Před 3 lety +58

    Sir, please bring in new lectures on the remaining topics . You have really been a boon to students who don't possess enough money to get paid courses. Thankyou .

  • @harshsahu7825
    @harshsahu7825 Před 4 lety +159

    Before this one, I was totally dependent on std::lower_bound and std::upper_bound. Thanks!

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

      i am aslo trying it with lower_bound and upper-bound , but it's not working . can you please tell me about this

    • @vatsalmehta7159
      @vatsalmehta7159 Před 2 lety +11

      @@saikatchattaraj7441 lowerbound and upperbound works only in sorted arrays and vectors.Try using it in set in c++.

    • @abhishek-singh31
      @abhishek-singh31 Před 2 lety +4

      @@saikatchattaraj7441 if you got arr[mid]= target ,then
      Find first occurence using lower_bound() and store it as index1, and then last occurrence using upper_bound() and store is at index2.
      Final ans will be an {index1,index2-1}

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

      @@vatsalmehta7159 Binary search also works on sorted arrays only .

  • @mental-block
    @mental-block Před 4 lety +22

    Clear explanation. Was confused with Leet code template 1, template 2, template 3 for binary search. But Your explanation made it easy for me. Thanks !

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

    love your short and crisp explanation. God bless you.

  • @MrChetan54
    @MrChetan54 Před 2 lety +8

    Awesome and most simplified. I was unable to think that we can save the mid and try to minimize. I was instead trying to go to a point where nums[mid] == target && (nums[mid - 1] < nums[mid]). All cases worked in my code except the one case. Hence, came here for solution and found easy logic to just save the mid and continue searching. Bhai tussi great ho!!

  • @ArpitChoudhary-bu6yt
    @ArpitChoudhary-bu6yt Před rokem +6

    After diving through so many videos on this question, Yours is the one that made most sense to me!
    Thanks Aditya!

  • @mohdaquib1638
    @mohdaquib1638 Před 4 lety +8

    Thanks bro..nice way of teaching. Please also add topics like Recursion, Greedy and Divide and conquer.

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

    just Amazing. This word even can't describe how good you are as a teacher.

  • @Sauravgpt34
    @Sauravgpt34 Před 4 lety +20

    Before watching I found this problem on leetcode and can't solve in O(log n) but now I can.

  • @surbhitamrakar1638
    @surbhitamrakar1638 Před 3 lety +5

    What a great explanation!

  • @kawaljeetsingh1657
    @kawaljeetsingh1657 Před 2 lety +13

    One of the most underrated channel for good resources and easy explanations and approaches to complex problems.
    Would be waiting for more topics coverage.
    Thanks for your precious time in putting up this content. 🤝

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

    Thanks! You explained very well.

  • @deepakraghav9849
    @deepakraghav9849 Před 3 lety +5

    Bro way of explanation is next level 🔥🔥

  • @kirtipalve1772
    @kirtipalve1772 Před 3 lety +4

    Really well explained! thanks

  • @abhinavmishra7617
    @abhinavmishra7617 Před 4 lety +1

    Bhai tum bahot achcha explain krte ho yaar.....thanks a lot...aise hi videos banate rahe

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

    Nice explanation, was confused why high-1 is done, thanks :)

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

    Bro nice explanation..Thank U ❤️❤️

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

    Excellent tutorial, need not to change pen, your session becomes so interesting that the color combinations doesn't matter

  • @philosphize
    @philosphize Před rokem +1

    Thanks Aditya, please come back ans teach us others topic. You are the best

  • @dhrumilvaghasiya1581
    @dhrumilvaghasiya1581 Před rokem +1

    Thank you brother a lot. It helped me a lot during my assignment.

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

    I was actually looking for a video explaining using pen paper, Thanks

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

    Did it by own, thanx for the concept

  • @piyushkumarrajput2779
    @piyushkumarrajput2779 Před 3 lety +20

    after getting the job I will definitely donate some amount to the growth of this channel.

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

      mili job ?

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

      @@MahimDashoraHackR Yup and thanks for asking.
      If you want to connect then send connection request on LinkedIn @iampkr

    • @bsaikumarreddy1413
      @bsaikumarreddy1413 Před 3 lety

      @@piyushkumarrajput2779 Bro , I have searched your username in Linked in didn't find it . Want to connect with you

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

      @@bsaikumarreddy1413 Connect with me using below link
      www.linkedin.com/in/iampkr/

    • @JohnWick-kh7ow
      @JohnWick-kh7ow Před 2 lety

      @@piyushkumarrajput2779 Kya salary h bhai

  • @vijaykumargodekereshivanna3626

    Crazy bro !! keep posting new solutions

  • @mdjameel5177
    @mdjameel5177 Před 4 lety

    Badiya bhai maaza agaya problem solve karke

  • @kartarsingh7791
    @kartarsingh7791 Před 3 lety

    Bhai boht shi video bnaya re jese apne dost smjhate hai vaise bdiya smjh aaya bidu 🔥🔥

  • @24_santanurath56
    @24_santanurath56 Před 2 lety

    Thank you vai what a explaination ❤️👍

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

    if we have to return both first and last occurrence in a single program what will be the changes

  • @vakhariyajay2224
    @vakhariyajay2224 Před rokem

    Thank you very much. You are a genius.

  • @FaizanKhan-gfaizank
    @FaizanKhan-gfaizank Před rokem

    The best explanation!!

  • @joshithmurthy6209
    @joshithmurthy6209 Před 2 lety

    I always learn something new in every video

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

    Bro big thanks..

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

    Better than most of the popular CZcams channels

  • @akhil-slfimp
    @akhil-slfimp Před 19 hodinami

    thanks man you helped me alot in revisions and how we can link concepts

  • @raj_kundalia
    @raj_kundalia Před 2 lety

    thanks for the video!

  • @PiyushKumar-ue9tz
    @PiyushKumar-ue9tz Před rokem +1

    explained in a very easy manner

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

    Thanks bhai, ek ghante se video dekh raha tha, sab chinese log samjha rahe the but ghanta kuch samjha nahi. Abhi apne bataya toh samjha.

  • @akashkarn8429
    @akashkarn8429 Před rokem

    Thank you Aditya !!!!!!!

  • @adil470
    @adil470 Před rokem +1

    Most underrated channel on CZcams

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

    Can't we apply exponential search for this problem?

  • @9a56mahabirjaiswal9
    @9a56mahabirjaiswal9 Před 3 lety +1

    Bhaiya from where to find more problems jisme aste aste krke problem ka level increase kiya ho aur almost problem/question cover kiya ho ??

  • @tnishachaudhary6231
    @tnishachaudhary6231 Před rokem

    Thank you 👍👍

  • @princekumar-wt7ne
    @princekumar-wt7ne Před 2 lety

    Thank you so much

  • @soniamalik4929
    @soniamalik4929 Před 2 lety

    Bhott acha pdhate ho ap bhaii!

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

    after solving around 50 questions, I was able to think this logic on my own. Phew... more to go.

  • @anjaligoswamii
    @anjaligoswamii Před rokem

    Thank you bhaiya

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

    understood each and everything.....
    thanks!!!

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

    can we find both first and last in only one traversal ?

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

    But how we can make the first and last occurrence in one program? PLease help

  • @Sing_56
    @Sing_56 Před rokem

    Nice.
    Can you plz make videos on graph and backtracking

  • @rkk1990
    @rkk1990 Před 2 lety +5

    One correction : For last occurrence there will be "ArrayIndexOutOfBoundsException" if while loop condition is "start

  • @gauravsharan4875
    @gauravsharan4875 Před 10 měsíci

    kya explnation tha man u nailed it

  • @rushiprajapati4597
    @rushiprajapati4597 Před rokem

    Sir In this binary search problem is already sorted and if the target is get so why need to do repeat process to find first occurrence,
    We can just apply while loop when arr[mid]=target than res=mid; mid=mid-1;while(arr[mid]==target){res=mid; mid--;}
    return res;
    This thing can we do ?

  • @dibyajitmazumdar3435
    @dibyajitmazumdar3435 Před rokem

    Great 👍

  • @learncode1846
    @learncode1846 Před rokem +1

    What if, if we use lower bound for found first occurencee,,,
    BTW,,Nice explanation ,bhaiaa,,,
    Love from Bangladesh..

  • @neerajmahapatra5239
    @neerajmahapatra5239 Před 2 lety

    Please bhaiya aur videos dalo ....It is very helpful.

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

    I saw many different videos but your way to explaining different to other .

  • @DeepakGupta-zz1vf
    @DeepakGupta-zz1vf Před 4 lety +9

    I was just wondering ki what if the mid element itself is the first occurence , here then we are unnecessarily running binary search on left side array of mid element . So is its time complexity so neglible that we can ignore???????

    • @DeepakGupta-zz1vf
      @DeepakGupta-zz1vf Před 4 lety +4

      I got one solution to it @Aditya Verma can you please check or even viewers can you u guys check this out
      int firstOccurrence(int arr[],int len, int x)
      {
      int start = 0;
      int end = len-1;
      int res;
      while(start

    • @sakshambali3040
      @sakshambali3040 Před 3 lety

      if l[mid] == x:
      while l[mid-1]==x:
      mid-=1
      return mid
      #you can have a look at it, it's in python though.

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

      @@DeepakGupta-zz1vf Even if the mid element is the first occurrence, binary search has log n complexity which you can say is negligible to consider different cases.

    • @harrypotter-el4lx
      @harrypotter-el4lx Před 3 lety +1

      Worst case complexity of binary search is logn

  • @firozkamdar6735
    @firozkamdar6735 Před 5 měsíci +1

    Shukriya Bhai, per ek aur help kar do isse recursion se karke bata do.

  • @kirtikhohal3313
    @kirtikhohal3313 Před 2 lety +4

    How can I write a more short code for this problem ??
    vector searchRange(vector& nums, int target) {
    int first=0,last=nums.size()-1,mid=ceil((first+last)/2);
    vector v(2,-1);
    if(nums.size()>0)
    {
    while(first

    • @divyanshverma495
      @divyanshverma495 Před rokem +4

      vector searchRange(vector& nums, int target) {
      return {search(nums, target, "FIRST"),search(nums, target, "LAST")};
      }
      int search(vector nums, int target, string find){
      int start = 0;
      int end = nums.size() - 1;
      int ans = -1;

      while(start nums[mid]){
      start = mid + 1;
      }
      else{
      ans = mid;
      if(find == "FIRST"){
      end = mid - 1;
      }
      else{
      start = mid + 1;
      }
      }
      }
      return ans;
      }

    • @Kirti-bi2yj
      @Kirti-bi2yj Před měsícem +1

      @@divyanshverma495 Thanks a lot! This solution is really nice I understood it and tried it, it's working perfectly.

  • @sachinshrestha2538
    @sachinshrestha2538 Před 4 lety

    wat is its space complexity

  • @pprathameshmore
    @pprathameshmore Před rokem +4

    JavaScript
    Leetcode: 34
    /**
    * @param {number[]} nums
    * @param {number} target
    * @return {number[]}
    */
    const binarySearch = (arr, target, last) => {
    let start = 0;
    let end = arr.length - 1;
    let res = -1;

    while (start target) {
    end = mid - 1;
    } else if (arr[mid] < target) {
    start = mid + 1;
    }
    }
    return res;
    }
    var searchRange = function(arr, target) {
    let res = [-1, -1]
    if (arr.length === 0) {
    return res;
    }
    const firstElement = binarySearch(arr, target, false);
    const lastElement = binarySearch(arr, target, true);
    res[0] = firstElement;
    res[1] = lastElement;
    return res;
    };

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

    Simple python code:
    #1st and last occurance of element
    class Solution:
    def bs(self,nums,target):
    l=0
    r=len(nums)-1
    res=-1
    while l

  • @rishabhjoshi3092
    @rishabhjoshi3092 Před 4 lety +4

    so they dont ask complete code in interviews? just u can explain with pseudo code and working ?

    • @vaibhavmalviya7290
      @vaibhavmalviya7290 Před 4 lety +1

      It may also chance they will agree with pseudo code and its working flow. But in worst case ready to write code. It is minor tweak in original binary search algo.

    • @TheAdityaVerma
      @TheAdityaVerma  Před 4 lety +11

      unless you got them convinced that writing code is no big deal for you, they will make you write code for sure after discussing the approach.

  • @binayakchoudhury4543
    @binayakchoudhury4543 Před 2 lety

    How can i impliment of them together

  • @techtalentblueprints
    @techtalentblueprints Před rokem +1

    can we use while loop here?
    this one is also working.....
    while (arr[mid] == target){
    mid = mid -1;
    }
    return mid+1;

    • @avadhoot05
      @avadhoot05 Před rokem

      it will work but the time complexity will be linear. it defeats the reason we are using BS in the first place

  • @srishtisharma7217
    @srishtisharma7217 Před 3 lety

    bhaiya agar dimaag mein ye approach na aaye aur hum first occurance ke liye start index 0 se ek for loop chala de aur last occurance ke liye last index se reverse loop chala de to kaam chal sakta hai kya?i mean tle aane ke kya chances hain?

    • @PabitraPadhy
      @PabitraPadhy Před 3 lety

      depend karta hai... aditya ka ek interview steps wala video hai... jisme woh TLE aur constraints ke barein mein bol raha hai.
      to us se pata lag jaega... ki kitna time mein nikalna hai.
      tumhara logic 2 loop wala.. O(n) mein execute hoga.
      agar test case aur constrants ko O (log n) hi chahiye hoga.. to TLE lag jaega.
      par itna buddhu to interview nain hota hai ki tumhe O(n) mein pooche... to identification kam aega us time pe
      agar sorted array hai.. to binary search lagane ki soch sakte ho.

  • @aarzoo_ahuja
    @aarzoo_ahuja Před 3 lety +7

    Sir if we need to do both then do we have to write 2 seperate programs?

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

      yes... write two seprate function 1. first and 2, last. call them separately to get the results....

    • @gyanabarik9389
      @gyanabarik9389 Před 2 lety

      @@PradeepKumarIIITD Thanks

  • @arindam1249
    @arindam1249 Před rokem

    great

  • @shrutianand719
    @shrutianand719 Před 6 měsíci

    if array is in sorted order , and we found the element at mid, y we need to go left and right to check for another occurrence, we also check if arr[mid-1] == element and arr[mid+1] == element as it's sorted .

    • @AbhishekAshish-sk4zh
      @AbhishekAshish-sk4zh Před 2 měsíci

      may be there will so many occurence which leads to time complexity problem as you are just checking linearily

  • @Rupeksha-we1jn
    @Rupeksha-we1jn Před 5 měsíci

    this may be the code according to sir's explaination: class Solution {
    public:
    int firstOccurance(vector &nums, int target){
    int start=0;
    int end=nums.size()-1;
    int result=-1;
    while(starttarget){
    end=mid-1;
    }
    else{
    start=mid+1;
    }
    }
    return result;
    }
    int lastOccurance(vector &nums, int target){
    int start=0;
    int end=nums.size()-1;
    int result=-1;
    while(starttarget){
    end=mid-1;
    }
    else{
    start=mid+1;
    }
    }
    return result;
    }
    vector searchRange(vector& nums, int target) {
    vector pair;
    pair.push_back(firstOccurance(nums,target));
    pair.push_back(lastOccurance(nums,target));
    return pair;
    }

    };

  • @srishtysinha6198
    @srishtysinha6198 Před 4 lety +1

    find function can also br used to find the first occurrence. Isn't it better?

    • @ayandas5438
      @ayandas5438 Před 4 lety

      that would take linear time as builtin functions take up internal time

    • @srishtysinha6198
      @srishtysinha6198 Před 4 lety

      Ayan Das okay. Thanks

  • @ajeetyadav1093
    @ajeetyadav1093 Před 4 lety +2

    Thanks!

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

      11 months phle hi padh liya BS :) your TA from iiitd :)

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

      @@PradeepKumarIIITD areee bhai bhai bhai bhai😃 You got really good memory 😂

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

      @@ajeetyadav1093 can't forget that DP....

    • @ajeetyadav1093
      @ajeetyadav1093 Před 3 lety

      @@PradeepKumarIIITD 😂

  • @pradeepmondal4943
    @pradeepmondal4943 Před 3 lety

    ❤️❤️❤️❤️❤️

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

    counting the no.of times you spoke "apan"...loll

  • @settyruthvik6236
    @settyruthvik6236 Před 2 lety +12

    #code using python
    class Solution:
    def Firstoccurence(self,A,B):
    l=0
    r=len(A)-1
    l_ele=-1
    while l

  • @abhishekmaurya1082
    @abhishekmaurya1082 Před 10 měsíci

  • @mona020391
    @mona020391 Před 4 lety +7

    when we find our mid == element, instead of doing BS again.. shouldn't we just check previous elements? As the array is sorted.

    • @TheAdityaVerma
      @TheAdityaVerma  Před 4 lety +37

      Okay, so lets just consider a case (worst case to be specific). let the array be
      arr[]: [2(0),2(1),2(2),2(3),2(4),2(5),2(6),2(7),2(8)]--> where the number in brackets()--are the indexes, just try to run your approach and my approach on this, I think you will get it. If not continue reading this-> so basically in yours after having our mid which 2(4)--> you will have to do a linear search till end ie., 2(0). While in mine it will be log of n. I hope that clears your doubt.

    • @mona020391
      @mona020391 Před 4 lety +8

      makes sense.. (one suggestion: in your videos can you also discuss time complexities at least in the base scenario cases you discuss like in subset prob in DP .. here in classic BS problem..)

    • @shailendrajain4231
      @shailendrajain4231 Před 4 lety +7

      @@TheAdityaVerma we dont have to do linear search for it.. if we found that another same element is present in left side then we will call binary search else current element will be first occurance....

    • @himanshujain5435
      @himanshujain5435 Před 3 lety

      @@shailendrajain4231 I tried using that approach its giving TLE on gfg

    • @shrujaigupta1803
      @shrujaigupta1803 Před 2 lety

      thats a very good question and explanation by aditya sir is op too!

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

    I have a doubt, i have used two pointers to get the starting and ending position, would the time complexity will be same as your approach?
    left = mid;
    right = mid;
    while (left - 1 >= 0 && arr[left - 1] == x)
    {
    left--;
    }
    while (right + 1 < n && arr[right + 1] == x)
    {
    right++;
    }

    • @saumitrapandey3070
      @saumitrapandey3070 Před 8 měsíci

      nahi bhai ye O(N) ho jaegi aur idhar tum galat assume kr rhe ho ki array me saare elements are target but array will have diff elements

  • @Anurag-fk3op
    @Anurag-fk3op Před 6 měsíci

    The idea is that if we found the element at any place then for first occurance go to left part again and for last occurance go to right part again simple

  • @bhavyaagrawal7098
    @bhavyaagrawal7098 Před měsícem

    don't forget to reinitializethe first and last i hope it helped someone
    pair indexes(vector v, long long x)
    {
    // code here
    int res=-1;
    int ser=-1;
    int first=0;
    int last=v.size()-1;
    while(first

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

    what if, we have asked both first and last occurrences together

  • @damandeepsingh6037
    @damandeepsingh6037 Před rokem

    we can do if(ele==arr[mid] && arr[mid-1]!=ele)

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

    What will be the complexity of this algorithm?
    got it
    Time Complexity : O(log n)
    Auxiliary Space : O(1)

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

      Yeah, I think yhi hona chahiye

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

      The time complexity of normal binary search is O(log n), and we've added just one extra line to it, so it will be same .
      We've Haven't used any auxiliary space, so yes constant space

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

    can you add english titles please

  • @rup6670
    @rup6670 Před rokem

    trying out something in api call

  • @Shubham-iy3ue
    @Shubham-iy3ue Před rokem +1

    I think the code is bit wrong ,here is my solution
    int firstOccurence(vector &v,int element){
    int hi = v.size()-1,lo = 0,mid;
    int res = -1;
    while (hi-lo>=0)
    {
    mid = lo + (hi-lo)/2;
    //2 4 10 10 10 18 20
    if (v[mid]==element)
    {
    res = mid;
    hi = mid-1;
    }
    else if(v[mid] < element)
    {
    lo = mid +1;
    }
    else //(element< v[mid])
    {
    hi = mid-1;
    }
    }
    return res;
    }
    int lastOccurence(vector &v, int element){
    int hi = v.size()-1,lo = 0,mid;
    int res = -1;
    while (hi-lo>=0)
    {
    mid = lo + (hi-lo)/2;
    if (v[mid]==element)
    {
    res = mid;
    lo = mid +1;
    }
    else if (v[mid]

  • @rup6670
    @rup6670 Před rokem

    trying out mantain

  • @devashish887
    @devashish887 Před 3 lety +3

    While searching first occurrence find mid then further one can just check mid-1 element if that is less then mid
    Then can directly return mid as answer
    And no need to continue further search. 😊
    Anyways thanks Aditya

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

      This will create a corner case if you have answer as first index Eg searching 10 in {10,10,10,10,10,13,15,79}

    • @notmewooshme9916
      @notmewooshme9916 Před 2 lety

      Also check if mid-1 is greater than -1.
      If mid-1=0 and arr[mid-1]==arr[mid] then end = mid-1
      If mid-1>=0 and arr[mid-1]!=arr[mid] thrn return mid

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

      lol what if there are >3 occurences ? then??
      Nothing is useless kimd , use your brain for learning new thing not finding god's errors coz there are none

  • @kushsrivastava9336
    @kushsrivastava9336 Před rokem

    For my recurrence:
    6:36

  • @rittik6023
    @rittik6023 Před 2 lety

    Kon se college se ho aap

    • @abhishek_singh512
      @abhishek_singh512 Před rokem

      College does not Matter a lot Bro if you have a Good Logic skill

  • @aviseklahiri3864
    @aviseklahiri3864 Před 4 lety +6

    Here is my solution: Leetcode: 34
    class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
    def getIndex(nums, left, right, target, search_for_first = True):
    location = -1
    while left target:
    right = mid - 1
    else:
    left = mid + 1
    return location

    if len(nums) == 0:
    return [-1,-1]

    start_index = getIndex(nums, 0, len(nums) - 1, target)
    if start_index != -1:
    end_index = getIndex(nums, 0, len(nums) - 1, target, search_for_first=False)
    if start_index != -1:
    return [start_index, end_index]
    else:
    return [-1, -1]

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

    I don't know why... but my last occurrence is not working

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

      send code

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

      You can check out my code:-
      class Solution {
      public:
      vector searchRange(vector& nums, int target) {
      int first=0,last=nums.size()-1,mid=ceil((first+last)/2);
      vector v;
      v.push_back(-1);
      v.push_back(-1);

      if(nums.size()>0)
      {
      while(first

  • @AmitSingh-cs2hb
    @AmitSingh-cs2hb Před 4 lety

    Yrr ye pen kaise ghumata ho aap fingers mein🤨🤨

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

    5:27 pe galti hai, high = mid hoga, NOT high=mid-1, humko mid ko include karna hai, kyuki wo ek possible answer ho sakta hai, mid-1 nahi le sakte
    Check kario bro ek baar

    • @anamika2866
      @anamika2866 Před 3 lety

      mid ko hum already res mein store karwa chuke hai then still we require to include mid as high=mid??

    • @yashverma4938
      @yashverma4938 Před 3 lety

      bhai us mid se phle hi toh check krenge ab kyuki usko toh vase bhi result mein store kr rkha h .isliye high=mid-1 shi h

  • @rup6670
    @rup6670 Před rokem

    trying out something

  • @rutvikshah4589
    @rutvikshah4589 Před 2 lety

    class Solution {
    public:
    vector searchRange(vector& nums, int target) {
    return {BinarySearch(nums, target, "FIRST"), BinarySearch(nums, target, "LAST")};
    }

    int BinarySearch(vector nums, int num, string find) {
    int left = 0, right = nums.size() - 1, mid;
    int result = -1;
    while (left num) {
    right = mid - 1;
    }
    else {
    left = mid + 1;
    }
    }
    return result;
    }
    };

  • @girdhar3224
    @girdhar3224 Před rokem

    class Solution {


    int f(long v[], long x){
    int first = -1;
    int s = 0;
    int e = v.length -1;
    while(sx)
    e = mid -1;
    else
    s = mid + 1;
    }
    return first;
    }



    int l(long v[], long x){
    int last = -1;
    int s = 0;
    int e = v.length -1;
    while(sx)
    e = mid -1;
    else
    s = mid + 1;
    }
    return last;
    }






    public pair indexes(long v[], long x)
    {
    // Your code goes here

    return new pair(f(v,x),l(v,x));

    }
    }

  • @aahanaganjewar9951
    @aahanaganjewar9951 Před rokem

    class Solution {
    public int[] searchRange(int[] nums, int target) {
    int[] res = new int[2];
    Arrays.fill(res, -1);

    //first occurrence
    int start = 0;
    int end = nums.length - 1;
    while (start

  • @akshaybhuradia9199
    @akshaybhuradia9199 Před 5 měsíci

    function binary_serach_f(arr, key){
    let start = 0;
    let end = arr.length -1;
    let res = -1;
    // let asc = (arr[start] > arr[end]) ? false : true;
    while(start