Remove Duplicates from Sorted Array II - Leetcode 80 - Python

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

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

  • @factified9892
    @factified9892 ปีที่แล้ว +145

    To all those who are just starting their coding journey, you might not understand the code sometimes or even the question. But, that is completely fine. Just stick with it since you have chosen this journey with a purpose and have patience, which in my opinion, is the most important that a programmer must have. Be patient, give yourself time and practice whenever you can.

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

      Well said!

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

      Thank You very much

    • @studymotivation-c8t
      @studymotivation-c8t 9 หลายเดือนก่อน +1

      thank u, because of that exact same problem i quit leetcode twice before. This time im gonna stick to it no matter wat

    • @ayojohnson5933
      @ayojohnson5933 9 หลายเดือนก่อน

      Greatly said!

    • @AdityaRaut-l6p
      @AdityaRaut-l6p 7 หลายเดือนก่อน

      thank you

  • @jkk23-g7c
    @jkk23-g7c ปีที่แล้ว +60

    This solution is kind of a tricky one. I wouldn't be able to come up with this on my own, but yes once you explained it, it makes sense.

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

      couldn't agree more.

    • @leeroymlg4692
      @leeroymlg4692 ปีที่แล้ว +9

      that's becoming a pattern the more leetcode questions i come across lol

    • @nitiandiv
      @nitiandiv 11 หลายเดือนก่อน

      Same thing but in just slight more understanding way
      var removeDuplicates = function (A) {
      let pointer = 0;
      let i = 0;
      while (i < A.length) {
      let start = i;
      while (A[i] == A[i + 1]) {
      i++;
      }
      let end = i;
      const count = Math.min(2, end - start + 1);
      for (let x = 0; x < count; x++) {
      A[pointer] = A[end];
      pointer++;
      }
      i++;
      }
      return pointer;
      };

  • @crikxouba
    @crikxouba ปีที่แล้ว +29

    Even when explained to me as clearly as this, I always find these loops and pointers a complete mind f**k

  • @sergiofranklin8809
    @sergiofranklin8809 ปีที่แล้ว +11

    def removeDuplicates(self, nums):
    j, count = 1, 1
    for i in range(1, len(nums)):
    if nums[i] == nums[i - 1]:
    count += 1
    else:
    count = 1
    if count

  • @Dannyboyjr
    @Dannyboyjr ปีที่แล้ว +29

    I feel like ChatGPT's answer is easier to understand on this one.
    def removeDuplicates(self, nums: List[int]) -> int:
    left = 2
    if len(nums)

    • @hida-steak-donburi
      @hida-steak-donburi 8 หลายเดือนก่อน +4

      This solution is amazing... consider it a fixed-length sliding window

    • @sharaabsingh
      @sharaabsingh 7 หลายเดือนก่อน +5

      Yeah, ChatGPT's solution is much more intuitive and easy to understand. Still thanks for your efforts Neetcode!

    • @winniethepooh.
      @winniethepooh. 4 หลายเดือนก่อน +3

      I agree. It's pretty similar to his solution from his Remove Duplicates from Sorted Array video (th-cam.com/video/DEJAZBq0FDA/w-d-xo.html). It was my inital apporach when solving this problem!

    • @sidazhong2019
      @sidazhong2019 3 หลายเดือนก่อน +2

      well, in similar question #26, you just change every "left - 2" to "left - 1". that work too.

  • @RuslanZinovyev
    @RuslanZinovyev 4 หลายเดือนก่อน +1

    There is a way simpler solution and more intuitive from my perspective, I can't say that your explanation was really helpful this time, but I really appreciate what you are doing for us.
    def removeDuplicates(nums: List[int]) -> int:
    if len(nums)

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

    In the Constraints:
    1

  • @janki-bx1rn
    @janki-bx1rn 3 หลายเดือนก่อน +3

    Way easier solution from ChatGPT, easy to understand and much more intuitive
    class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
    if len(nums)

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

    An alternative solution building off of the Remove Duplicates from Sorted Array I solution:
    class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
    left = 1
    freq = 1

    for i in range(1, len(nums)):
    if nums[i] > nums[left - 1]:
    nums[left] = nums[i]
    left += 1
    freq = 1
    elif nums[i] == nums[left - 1] and freq < 2:
    nums[left] = nums[i]
    left += 1
    freq += 1
    return left
    Instead of nested loops I added a var that keeps track of how many times a value is added and an elif that adds up to two of a given value.

  • @EjazAhmed-pf5tz
    @EjazAhmed-pf5tz ปีที่แล้ว +7

    Thank you so much sir, but could you please combine videos in a playlist so that will be easy for us to follow

  • @vigneshs1852
    @vigneshs1852 8 หลายเดือนก่อน

    The fact i can write the solution with O(n^2) but still here to optimize the solution...Thank you bro

  • @AustinCS
    @AustinCS 17 ชั่วโมงที่ผ่านมา

    class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
    l = 1
    count = 1
    for r in range(1, len(nums)):
    if nums[r] != nums[r-1]:
    count = 0
    if count < 2:
    nums[l] = nums[r]
    l += 1
    count += 1
    return l
    Initialize count to 1 and both pointers to the first index. We may need to reset the count and write in the same iteration when we find a new element. First check if the current element is a duplicate. If it isn't reset the count to 0. Then if the count is < 2 write the current element to the left pointer and increment the left pointer. Let the for loop handle the right pointer increment. return the left pointer.

  • @dash2714
    @dash2714 11 หลายเดือนก่อน

    Love your videos, they are very insightful and helpful. I'm very greatful for you.
    I would like this time to share my solution to it, as for the first time ever it has a cleaner approach.
    Same idea with L and R pointers. with each iteration replace L with R, then check if L is valid, as follows:
    class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
    l = 2
    for r in range(2, len(nums)):
    nums[l] = nums[r]
    if nums[l] != nums[l - 2]:
    l += 1
    return l

  • @simsekcool9595
    @simsekcool9595 4 หลายเดือนก่อน

    I found it easier to use a set to solve this question and the first version of this question as well. I just check if the element we are currently at is already in both sets. If its in neither or in just one of the sets, then I added it to the other set and I swap the element at r and the element at i. But if the element is already in both sets, then I only increment r and don't do any swapping. Here is the code:
    sett1= set()
    sett2= set()
    i = 0
    for r in range(len(nums)):
    if nums[r] not in sett2:
    if nums[r] not in sett1:
    #case where its not in either set
    sett1.add(nums[r])
    nums[i], nums[r] = nums[r], nums[i]
    i+=1
    else:
    #case where its not in set 2 but its in set1
    sett2.add(nums[r])
    nums[i], nums[r] = nums[r], nums[i]
    i+=1
    #case where its in both sets
    return i

  • @p8ul
    @p8ul 6 หลายเดือนก่อน

    simpler version:
    function removeDuplicates(nums: number[]): number {
    // edge case to return early if 2 or fewer elements
    if (nums.length

  • @Jaeoh.woof765
    @Jaeoh.woof765 ปีที่แล้ว +1

    My solution is very similar to the 1st version of the problem but with a slight twist.
    Runtime beats 98%
    ======================
    def removeDuplicates(self, nums: List[int]) -> int:
    l = 2
    flag = 0
    for r in range(2, len(nums)):
    if nums[r] != nums[r-2-flag]:
    nums[l] = nums[r]
    l +=1
    else:
    flag +=1
    return l

  • @VikasReddyVenkannagari
    @VikasReddyVenkannagari 4 หลายเดือนก่อน

    For those, who want a more stricter solution.
    The relative order is not preserved in this solution, if there are 4 3's [2, 3,3,3,3], we should consider the relative ordering where the first two 3's are considered, but the your solution kinda considers the last occurence of 3.

  • @saksahmkumarsaksham
    @saksahmkumarsaksham 26 วันที่ผ่านมา

    def removeDuplicates(self, nums):
    if len(nums)

  • @arpitsharma7695
    @arpitsharma7695 8 หลายเดือนก่อน

    Thank You for all the videos but what are your thoughts on below solution? I avoid another for loop. I use your r+1 logic.
    class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
    r=1
    while r < len(nums)-1:
    while r+1

  • @CST1992
    @CST1992 6 หลายเดือนก่อน +1

    There's a bug in this problem(the problem itself, not the solution):
    It says it wants to remove duplicates in the title and it says in the description that each element will appear *at most* twice.
    It's quite normal to reason that this means that any element, even which originally has 2 copies of a given value in it, can be trimmed down to 1 copy. But that is forbidden: you have to leave *both* copies in the output for it to be what is expected.
    So, the description needs to be changed to "at least and at most" twice: If the original has only one of the given, fine; but if it contains two or more copies of the same value, you have to leave at least two in and remove the rest. Of course, the value of k needs to be set to factor this in.

  • @prashant.s.397
    @prashant.s.397 10 หลายเดือนก่อน

    Super fantastic explanation ,found best algorithm from u ,watched others tutorials but they are just making it complex,it is very easy to solve via your method and also quite easily understandable

  • @andrewcenteno3462
    @andrewcenteno3462 3 หลายเดือนก่อน

    simple solution, but the intutition behind it is tough

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

    class Solution {
    public:
    int removeDuplicates(vector& nums) {
    int len = nums.size();
    if (len

  • @PJ-nc4jh
    @PJ-nc4jh หลายเดือนก่อน

    My logic was to check
    if (nums[i] == nums[i-1]) and (nums[i] == nums[i+1])
    then i would push nums[i+1] to the back, but i got lost in the logic behind switching. Any comments/guidance regarding this would be appreciated

  • @cupidchakma6448
    @cupidchakma6448 2 หลายเดือนก่อน

    Is the time complexity O(n)^2 ? Since we are using 2 loops for the worst case?

  • @omar-eo8cq
    @omar-eo8cq ปีที่แล้ว

    you make this question hard, you can make it easier by starting left and right from index 2 and if(nums[right ]!==nums[left -2]){
    nums[left ]=nums[right ]; we increment left ++ otherwise right ++ , finally return left

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

    Thanks for the solution. Very easy to follow and reason.

  • @tirasjeffrey2002
    @tirasjeffrey2002 4 หลายเดือนก่อน

    i came up with an NlogN solution but broke my head trying to move the duplicate spots to the end,,,,,this one is very smart :0

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

    Thank you for your efforts for the fellow community !🤟

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

    # Another Soluion
    class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
    i = 0
    counter = 0
    l = len(nums)
    while i < (l-1):
    if nums[i] == nums[i+1] and counter == 1:
    nums.pop(i+1)
    l -= 1
    elif nums[i] == nums[i+1] and counter == 0:
    counter += 1
    i += 1
    else:
    i += 1
    counter = 0
    return len(nums)

  • @shyamsudheer8335
    @shyamsudheer8335 10 หลายเดือนก่อน

    at 0.55 why is it better to shift the value to the end instead of popping because both have time complexity of O(n)?

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

    This is my solution
    --------------------------------------
    class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
    if len(nums) < 2:
    return len(nums)
    pointer = 2
    for num in nums[2:]:
    if nums[pointer-2] != num:
    nums[pointer] = num
    pointer += 1
    return pointer
    --------------------------------------
    So basically, if the length of an array is less than 3, obviously everything is already sorted and correctly placed, therefore we just return it. The if condition in the beginning also allows us to start checking from the third element as well. After that we just start checking our current element and the one that is 2 steps behind. If there are equal, it means that the last two elements in the array are already equal to the current one and therefore we cannot place another one (it would be the third). In other cases, it is possible to add another element with the same value

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

    Here's the way i did it. maybe it's faster
    def removeDuplicates(self, nums) -> int:
    j = 1
    for i in range(2,len(nums)):
    x = nums[i]
    if x != nums[i-1] or x != nums[i-2]:
    j += 1
    nums[j] = x
    if i == j + 1 and i + 1 < len(nums) and x == nums[i+1]:
    j += 1
    return j+1

  • @asmamir7878
    @asmamir7878 2 วันที่ผ่านมา

    Beautiful 🙌

  • @ronnier320
    @ronnier320 11 หลายเดือนก่อน

    well explained helped a lot!

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

    My solution took 50 minutes and 38 lines of code.

  • @Dan-dg2pc
    @Dan-dg2pc 10 หลายเดือนก่อน

    There is an easier solution where R (right pointer) loops through the array and just checks whether nums[R] == nums[L] == nums[L-1].
    If not:
    L += 1
    nums[L] = nums[R]
    If yes: continue
    Return: L+1
    JS:
    var removeDuplicates = function(nums) {
    if (nums.length < 3) return nums.length // Handle edgecase
    let replaceIndex = 1
    for (let i = 2 ; i < nums.length ; i++) {
    if (nums[i] != nums[replaceIndex] || nums[replaceIndex] != nums[replaceIndex-1]) {
    replaceIndex++
    nums[replaceIndex] = nums[i]
    }
    }
    return replaceIndex+1
    };

  • @nirupomboseroy6067
    @nirupomboseroy6067 9 หลายเดือนก่อน

    An even more intuitive solution. O(n)
    class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
    if len(nums) == 1:
    return
    l = 0
    r = 0
    while r < len(nums):
    # edge case
    if l == 0 and nums[l+1] == nums[l]:
    # skip the first value to continue as usual
    r+=1
    l+=1
    if nums[r] != nums[l]:
    l+=1
    nums[l] = nums[r]
    # Greedily check for one more duplicate as it is two
    # if we get it we change else no problem.
    if r+1 < len(nums) and nums[r+1] == nums[r]:
    l+=1
    nums[l] = nums[r]
    r+=1
    r+=1
    return l+1

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

    Great work @NeetCodeIO
    Was thinking you actually stopped uploading daily leetcode video explanations when I didn't get any notification over the past few hours

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

    is there any reason for not uploading daily challenges ?

  • @mahmoudabdaltwab426
    @mahmoudabdaltwab426 8 หลายเดือนก่อน

    whoever strugle to understand this sol
    i think this easier to come up with
    int removeDuplicates(vector& nums) {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    if(nums.size()

  • @pranavmaniyar4592
    @pranavmaniyar4592 หลายเดือนก่อน

    Good question

  • @ratantejaswivadapalli1591
    @ratantejaswivadapalli1591 8 หลายเดือนก่อน

    l,c = 1,1
    for r in range(1,len(nums)):
    if(nums[r]!=nums[r-1]):
    c = 1
    nums[l]=nums[r]
    l += 1
    else:
    if c

  • @S5Dic09
    @S5Dic09 5 หลายเดือนก่อน

    geez before 5m you make this so redundant tbh that removes clarity

  • @FUNTasticFlutter
    @FUNTasticFlutter 7 หลายเดือนก่อน

    my solution : runtime 57 ms. mem 16.64 mb
    code
    for n in nums:
    if nums.count(n)>2:
    while nums.count(n)>2:
    nums.remove(n)
    return len(nums)

  • @gaganbhattacharya9890
    @gaganbhattacharya9890 11 หลายเดือนก่อน

    I would rather prefer to use a dictionary & if value for key > 2, pop the value & finally return the len(nums).

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

    are these questions prasent in NeetCodeAll ?

  • @JasonKAls
    @JasonKAls 7 หลายเดือนก่อน

    Doesn't this have a crazy time complexity like O(n^2) or even O(n^3) since he has a nested while loop and a for loop in within it?

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

    Please make a video on sliding window median

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

    You rock!

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

    Good Evening Sir.
    I'm an Indian and trying to buy Ur Yearly Plan. I'm getting Ur card is declined. Please help me Sir .. I'm interested to crack MAANG interviews

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

      Hi, please email me (neetcodebusiness@gmail.com)

  • @abdullahamin6138
    @abdullahamin6138 8 หลายเดือนก่อน

    Can be done in O(n)...

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

    Todays Daily Challenge?

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

    🙆‍♂️

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

    This is nice solution