Remove Duplicates from Sorted Array - Leetcode 26 - Python

Поділитися
Вставка
  • Опубліковано 19 гру 2024

КОМЕНТАРІ • 154

  • @NeetCode
    @NeetCode  2 роки тому +20

    🚀 neetcode.io/ - I created a FREE site to make interview prep a lot easier, hope it helps! ❤

  • @saisankalp5889
    @saisankalp5889 3 роки тому +227

    Generally we say "non-decreasing order" if the elements in the array are not strictly ascending like: [1,2,3,4,5], "non-decreasing order" means array can have elements like "[1,1,2,2,3]", not strictly ascending. Similar is the case for "non-increasing order".

  • @joshuaduffney
    @joshuaduffney 2 роки тому +24

    "Return the number of unique values in the array" is SO much better than saying "Return k", thank you!

  • @adilismail3593
    @adilismail3593 2 роки тому +96

    Been spending the last 3hours trying to solve this problem.
    Your explanations are very clear dude.
    Thanks

  • @ahyungrocks5509
    @ahyungrocks5509 8 місяців тому +3

    Was really confused about this problem until watching this video. The solution is so elegant.

  • @chrislee8319
    @chrislee8319 8 місяців тому +14

    For anyone who is seeing this comment, don't feel ashamed of watching the solution for an easy level leetcode, keep the grit and keep grinding. You'll eventually succeed!

    • @doc9448
      @doc9448 8 місяців тому +1

      At the end of the day, the task is to understand / be able to do what you previously did not understand / were not able to do. Whether you do it yourself or it's a learning experience for you, progress is nevertheless being made. For me, I'm trying to use my limited time efficiently so I'd rather look at the solution and internalize the logic and syntax then spend however much longer trying to solve it for myself (and possibly end up having to spend time learning the solution from scratch anyway).

  • @AbhishekDesai-lu6ih
    @AbhishekDesai-lu6ih 6 місяців тому +4

    Leetcode has the constraint : 1

  • @ramfattah211
    @ramfattah211 Рік тому +2

    0:28, because In mathematics, a sequence is said to be in non-decreasing order if each term is greater than or equal to the one before it. In other words, the sequence does not decrease at any point.

  • @КириллНиконов-ш2и
    @КириллНиконов-ш2и 2 роки тому +5

    2:40 That "say no more!" moment, where i literally stop watching and solve this problem. Understanding is king. Thanks a lot man!

    • @crimsonghoul8983
      @crimsonghoul8983 8 місяців тому

      To me, i was confused on how to prevent redundancy. I thought "ok. Let's use 2 pointers and have one start at 0 while the other starts at the next value. Keep the left pointer at one element while the right pointer increments upon every iteration. If both elements are same, then the loop keeps incrementing. If not, swap the values and then increment the left pointer.". I will leave it up to you to see the flaw in this logic.

  • @erikvandeven100
    @erikvandeven100 8 місяців тому +2

    Solved it first using a while loop, but using two pointers feels definitely much more easy to understand and explain.

  • @paganphoenixguitar
    @paganphoenixguitar 3 роки тому +22

    Awesome videos dude, these have been a super helpful resource as I study for interviews

  • @guptashashwat
    @guptashashwat 3 роки тому +11

    Non-decreasing means all numbers can be equal as well in the array.

  • @jst8922
    @jst8922 10 місяців тому +1

    I don't have lc account, but code from 10:15 doesn't replace duplicates with null/none/blank space/etc...
    this does:
    def removeDuplicates(nums):
    l = 1
    for r in range(1, len(nums)):
    if nums[r] != nums[r-1]:
    nums[l] = nums[r]
    l += 1
    for i in range(l, len(nums)):
    nums[i] = None
    return nums
    nums = [1, 2, 2, 3, 4, 4, 4, 5, 5]
    removeDuplicates(nums)
    print(nums)
    # output: [1, 2, 3, 4, 5, None, None, None, None]

  • @vasylynapavelko4036
    @vasylynapavelko4036 Рік тому +1

    Really like your explanations. I'm using JavaScript, but you make it so easy to undestand the problem and the solution for it.

  • @ericametta6964
    @ericametta6964 Рік тому +7

    The array cant be empty cuz the first constraint in the question is (1

  • @Elysium1711
    @Elysium1711 24 дні тому +1

    i am so appreciative for this video cause my mind is not developed enough to learn on my own and finally i understood it thank u brother

  • @Famelhaut
    @Famelhaut Рік тому +1

    This problem is written like shit. This comment helped solve it without watching the solution:
    "They don't really want you to remove the duplicates. They want you to sort the uniques at the front, then return the length of the sorted part. Then, behind the scenes, they slice the array at the length you give them and the result of that is what they check.
    Just FYI, this sh_t drove me crazy..."

    • @crypxtic
      @crypxtic Рік тому

      Yep this is the only thing that explains why we are not exactly "removing" duplicates from the array, a comment on LeetCode lol. We return the number they use to splice the array, it was excruciating trying to figure out what I was supposed to do with the rest of the freaking array!

  • @BurhanAijaz
    @BurhanAijaz 9 місяців тому

    10:04 u said what if we have an empty array , but according to the constraints , the minimum length of input will be 1 so that is why leetcode accepts it:
    constraint: 1

  • @elizabethr5161
    @elizabethr5161 2 роки тому +4

    Such a clean and brilliant solution.

  • @FaribaTasniaKhan
    @FaribaTasniaKhan 2 роки тому +3

    Oh my God... What an easy solution... And i was thinking all the complex way I can

    • @T_tintin
      @T_tintin Рік тому

      I really feel you..

  • @twezo
    @twezo 4 місяці тому

    Im ngl, this actually made sense. Was looking at the solution like why do all of this. I hate that none of this is visual on leetcode but this really helped

  • @symbol767
    @symbol767 2 роки тому +1

    Such a clear explanation and easy to understand solution, thank you man.
    This was way better explained and coded than the example on Grokking the Coding Interview

  • @butoyighyslain171
    @butoyighyslain171 Рік тому

    did this on my own after checking your other vids, thanks to you Neetcode!

  • @Insideoutcest
    @Insideoutcest 2 роки тому +2

    i used a map to track unique values and if i found the number before i spliced it out of the nums array and decremented the loop (to recheck for an indexOf from that position). i didnt use pointers but i had to use more memory.

  • @andreytamelo1183
    @andreytamelo1183 2 роки тому +1

    Thanks!

    • @NeetCode
      @NeetCode  2 роки тому

      Thank you so much Andrey!!!

  • @dennistsai5348
    @dennistsai5348 2 роки тому +3

    You just made it so easy!

  • @srikanthpoojary867
    @srikanthpoojary867 3 роки тому +2

    Thanks

    • @NeetCode
      @NeetCode  3 роки тому +1

      Hey Srikanth - thank you so much, I really appreciate it!! 😊

  • @soumyadas9939
    @soumyadas9939 2 роки тому +2

    Thank you, your approach was quite good enough. I just want to know how to think to come upon such a way to solve a problem?

  • @t-distributedkid3825
    @t-distributedkid3825 Рік тому

    Having a third pointer specifically for maintaing the unique value is much easier and more understandable thhan managing with two pointers

  • @pratik_chuckles
    @pratik_chuckles 3 місяці тому

    I struggled for hours!! Thanks

  • @WaldoTheWombat
    @WaldoTheWombat 6 місяців тому

    This is my solution, but yours is better:
    def removeDuplicates(self, nums: List[int]) -> int:
    l = 0
    r = 0 # or 1?
    while r < len(nums):
    while r+1 < len(nums) and nums[r] == nums[r+1]:
    r += 1
    nums[l] = nums[r]
    r += 1
    l += 1
    return l

  • @kevinliu9539
    @kevinliu9539 Рік тому

    Thank you! I was a bit confused because I thought you had to null all the other values in the updated array, because the question had _ representing those indices.

  • @NotNotNithin
    @NotNotNithin 2 роки тому +2

    Java solution:
    public static int removeDuplicates(int[] arr) {
    int left = 1;
    for (int right = 1; right < arr.length; right++) {
    if (arr[right] != arr[right - 1]) {
    arr[left] = arr[right];
    left++;
    }
    }
    return left;
    }

  • @yfjsdgzjdnfn
    @yfjsdgzjdnfn Рік тому +1

    10:00 1

  • @yanaphatpoonkrasee3409
    @yanaphatpoonkrasee3409 3 роки тому +1

    You are awesome. Thank you for all the videos you made. They're really helpful for beginners.

  • @palyanytsia
    @palyanytsia 10 місяців тому +1

    dislikes for this problem on the leetcode are from everyone who tried to create a new array from num. Not "in-place". It did that too, misread this part of requirements 😪

  • @sasidharnaidu4507
    @sasidharnaidu4507 10 місяців тому

    Well, I came up with similar approach, using count and last seen element. I actually forgot that this is a classic two pointer problem 😅 which I already had worked on before.

  • @КостяМос-я5о
    @КостяМос-я5о Рік тому

    This is genius! Best video on UA-cam, thanks bro!

  • @mh-sif
    @mh-sif 2 місяці тому

    Man, you're a gem!!

  • @pepelepew4400
    @pepelepew4400 3 роки тому +1

    I think a rules-lawyer used non-decreasing because an array 0,0,0,0,0 does not increase/ascend

  • @mushishows1120
    @mushishows1120 Місяць тому

    wow i just solved it and it felt so good

  • @ragerose13
    @ragerose13 2 роки тому +1

    Does anyone have problem running this code with zero or negative value's array on leet code simulation? Whenever i run array that has zero or negative value, the loop left out the very last value.

  • @MohamedSalah-xc9nm
    @MohamedSalah-xc9nm 9 місяців тому

    What is wrong when I store these values in a and then print the size of the set?

    • @deluksic
      @deluksic 8 місяців тому

      You're using O(k) extra space

  • @vinothiniseenivasan1502
    @vinothiniseenivasan1502 2 роки тому

    thanks for good work...crystal clear explanation..

  • @temuulentem1391
    @temuulentem1391 3 роки тому +1

    when i run this it says it works but when i submit it says wrong answer because the output isnt in ascending order.

  • @danteslog5887
    @danteslog5887 5 місяців тому

    More optimised approach -
    int removeDuplicates(std::vector& nums){
    int n=nums.size();
    int index = 2;
    if(n

  • @suraj-ej6oq
    @suraj-ej6oq 3 роки тому +2

    Great work 👍👍👍

  • @Richard-yz2gy
    @Richard-yz2gy 8 місяців тому

    so well explained thankyou

  • @joelrhine
    @joelrhine Рік тому

    My test cases were accepted but my final submission didn’t get accepted because it exceeded the time limit. That was just a clear reflection of how I code, inefficient but getting the job done. My house is burning but hey, at least we got heat.

  • @mio1201
    @mio1201 11 місяців тому

    LeetCode accepts this solution because there is a constraint for len(nums) to be => 1, so there always be at list 1 unique number in nums

  • @OmarMohammed44
    @OmarMohammed44 2 роки тому +1

    This is so well explained

  • @mmmk1414
    @mmmk1414 2 роки тому

    Thats beautiful and elegant
    Unlike mine 😂 but it works too

  • @deekshitht786
    @deekshitht786 Рік тому

    No one can replace you❤

  • @T_tintin
    @T_tintin Рік тому

    I actually spend so much time solving it.. that too by shifting the elements but it could have done a much simpler way. I really don't know if I will ever get good enough to reach the point where the best solution just clicks after some thinking .it's so frustrating

  • @nathan_milan_blacksmith3926
    @nathan_milan_blacksmith3926 2 роки тому

    hi, what drawing app are you using? thanks

  • @subhamthemusicalguy8851
    @subhamthemusicalguy8851 2 роки тому

    You are amazing. keep doing the good work

  • @rohitkumarjha3406
    @rohitkumarjha3406 Рік тому +1

    anyone could please send the program that i could execute on my ide with using the same logic

    • @rohitkumarjha3406
      @rohitkumarjha3406 Рік тому

      please sir help me out i need this logic only as a sokution in my ide

  • @muhammaddelen7769
    @muhammaddelen7769 2 роки тому

    this solution is uncharacteristically confusing for Neetcode. My recommended solution:
    prevNum = -101
    i = 0
    while i < len(nums):
    if nums[i] == prevNum: # repeat
    nums.pop(i)
    i -= 1 #keep the loop the same
    else: #not repeat
    prevNum = nums[i]
    i +=1
    return len(nums)

    • @prafulparashar9849
      @prafulparashar9849 2 роки тому +2

      So, I did the same thing first off when i read the question.
      But the problem with this is - popping an element from the index (i) takes O(n) complexity. so your solution is having the complexity of O(n^2).
      On the other hand, the solution in the video shows the approach of 2 pointers and achieves the answer in a single pass.
      You can try submitting your answer but will see a time inefficiency in the submission but your approach is absolutely correct.

  • @kancharajinikar585
    @kancharajinikar585 5 місяців тому

    great explanation

  • @sumyatnoe7128
    @sumyatnoe7128 Рік тому

    In my opinion, how about we used sort function? Answer : unique_arr = list(set(arr))

    • @8DMafia
      @8DMafia Рік тому

      you need to have 0(1) space answer.

  • @mohamedelhadi7088
    @mohamedelhadi7088 Рік тому

    I came up with a crafty solution xD, but it's in O(n^2) !

  • @nishantsharma7596
    @nishantsharma7596 2 роки тому

    def removeDuplicates(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    x = 0
    while x < len(nums):
    val = nums[x]
    if nums[x+1:].count(val) >= 1:
    # nums.remove(val)
    nums[x+1:] = list(filter(lambda a: a != val, nums[x+1:]))
    else:
    x += 1
    return len(nums)
    How is this approach?

  • @AbhishekYadav-vn2xj
    @AbhishekYadav-vn2xj Рік тому

    if array like [0 1 2 2 3] and we are starting from index 1 then r # r+1 so we lose the value 1 cuz 2#1, can someone explain me pls

  • @Sabre5106
    @Sabre5106 Рік тому

    Why is this code not working for the solution?
    class Solution:
    def removeDuplicates(self, nums):
    uniqueset = set()
    for n in nums:
    uniqueset.add(n)
    return len(uniqueset)
    I've tried this outside of LeetCode's checkers and it returns an integer of the expected length. Doing print(uniqueset) returns a set of the expected values, but Leetcode's checker says it returns a completely different list of values. I'm very confused as to what has gone wrong, but I am new to Python3.

    • @Sabre5106
      @Sabre5106 Рік тому

      Having watched the start of the video, you say that we can't initialise another array (and presumably a set as I've used) but this is not the state of the problem on the website today 1yr after this video was posted. It simply says to return k.
      Utterly stupid problem, just gonna skip this one.

    • @goldberg6330
      @goldberg6330 Рік тому

      @@Sabre5106 u should modify nums inplace according to the problem its more important than returning the length of unique elements. When u submit the code they check both nums and the value u r returning but u are not modifying the nums list

  • @williamtempleton7259
    @williamtempleton7259 3 роки тому +3

    Hey - love this content. Any ideas why this O(n) solution isn't just as fast as the other solutions, even though they are all pretty much O(n) time ?

    • @venkatasriharsha4227
      @venkatasriharsha4227 3 роки тому +2

      It's not about time in this question. It's about extra space.

  • @fahadahmedakash8045
    @fahadahmedakash8045 Рік тому

    why using set gives wrong answer?
    it prints the correct value in stdout but wrong in output

  • @midrees1286
    @midrees1286 2 роки тому

    def removeDuplicates(self, nums: List[int]) -> int:

    prev = None

    j=0
    for i in nums:
    if i != prev:
    nums[j] = i
    j+=1
    prev = i

    return j

  • @CEOofTheHood
    @CEOofTheHood 3 роки тому

    Hi Mr.Neet can you please cover the convex hull question erect the fence.

  • @AustinCS
    @AustinCS Місяць тому

    Wait until they learn about the word monotonic!
    Unfortunate as it is, non-decreasing, monotonic, whatever you want to use is actually the most mathematically precise way to express the problem constraints. Try and not resist these unfamiliar words but embrace the confusion as a learning opportunity!

  • @generalstep
    @generalstep 2 роки тому

    Great Explaination.

  • @fuchiahuang3822
    @fuchiahuang3822 3 роки тому +1

    Thanks for your clear explaination, but what if the size of nums is 0 or 1?

    • @yonahbyarugaba
      @yonahbyarugaba 2 роки тому

      We can't have duplicates if size is 0 or 1, so that wouldn't be a valid input I guess

  • @TutorialTechie
    @TutorialTechie Рік тому +1

    public int removeDuplicates(int[] nums) {
    int k = 1; // k is the left pointer
    for (int i = 1; i < nums.length; i++) { // ? i is the right pointer
    if (nums[i] != nums[i - 1])
    nums[k++] = nums[i];
    }
    return k;
    }

  • @binirxn
    @binirxn 6 місяців тому +1

    Isn't this too much for beginners, cuz they say it easy level

  • @igboman2860
    @igboman2860 3 роки тому +1

    def removeDuplicates(self, nums: List[int]) -> int:
    i=0
    for j in range(1,len(nums)):
    if nums[j] != nums[i]:
    nums[i+1],nums[j] = nums[j], nums[i+1]
    i += 1
    return i + 1

  • @asiftandel7757
    @asiftandel7757 3 роки тому

    Great explaination

  • @Lampalot
    @Lampalot 2 роки тому

    not sure why i get an index out of bound getting the same output using golang

  • @CameronSantiago-w6i
    @CameronSantiago-w6i 11 місяців тому

    Does this channel not have ads?

  • @WisdomShortvids
    @WisdomShortvids 2 роки тому

    easy with numbers what about strings ?

  • @KLuqman01
    @KLuqman01 2 роки тому

    How do you call this code within the IDE. I'm always getting the message ....NameError: name 'List' is not defined

  • @amalthiru206
    @amalthiru206 2 роки тому +1

    Why can't we just convert it to a set, and then convert it to a set and then return the length of the set?

    • @aman_axioms
      @aman_axioms 2 роки тому +3

      because we should not use extra space in this question. This means we cannot take any other data structure.

  • @atalaykarahan1066
    @atalaykarahan1066 Рік тому

    i did not understand when i try to use hash set and return the count of hash leetcode return me a error can we solve this problem with hash set? if its not why?

    • @SuubUWU
      @SuubUWU 9 місяців тому

      Sorry if it’s too late but it’s because the problem requires you to not allocate extra space.
      There’s probably an edge case where each element is unique, like all evens [2,4,6,8]
      Worst case scenario, your hash grew to the space time to O(n). Problem requires an O(1) space time solution.

  • @dipanjanjayswal554
    @dipanjanjayswal554 2 роки тому +1

    Hey NeetCode Can't we simply do like:
    k = set(nums)
    return list(k)
    The set function automatically removes duplicates. Still it's showing error. Can you please explain why set function isn't working

    • @lucifers6105
      @lucifers6105 2 роки тому

      I have the same exact problem, Like for real why doesn't it work with a set ??

    • @dipanjanjayswal554
      @dipanjanjayswal554 2 роки тому +1

      @@lucifers6105 actually I later realised that set function doesn't perform the operation inplace. Instead it creates an temporary array for the same. 😁

    • @morningstar3996
      @morningstar3996 2 роки тому +1

      @@dipanjanjayswal554 I think you are right but still, I managed to find a way to make work with a set implementation.
      new_nums = set(nums)
      new_nums = list(new_nums)
      new_nums.sort()
      for i in range(len(nums)):
      try:
      nums[i] = new_nums[i]
      except:
      nums.pop()
      return len(nums)

    • @dipanjanjayswal554
      @dipanjanjayswal554 2 роки тому +1

      @@morningstar3996 good approach dude.. out of the box thought 💭 👍🏻

  • @kanchidoshi6907
    @kanchidoshi6907 2 роки тому

    Sorry but this code doesn't return the output array with non duplicate values?

  • @saurabhkumarsrivastava6034
    @saurabhkumarsrivastava6034 Рік тому

    Great man salute 😄nicely explained

  • @aadityakiran_s
    @aadityakiran_s Рік тому

    About as efficient as it can get huh? But the LeetCode statistics aren't that reliable in terms of efficiency right?

  • @mhamxed
    @mhamxed 2 місяці тому

    I used a the len and a set but it would not accept the solution?

    • @scarytuber
      @scarytuber Місяць тому

      make sure your not creating a new instance of nums and your adding the sorted set to the original nums list
      ex:
      nums[:] = sorted(set(nums))

  • @riccimel
    @riccimel Рік тому

    Can we say that it is some way a sliding window?

  • @HSnake5
    @HSnake5 2 роки тому

    Problem seems to be very simple, but also seems to be written by an alien

  • @Dennis-Ong
    @Dennis-Ong 3 роки тому +2

    This question really confuse me lol..the wording itself is a quiz

    • @Lambyyy
      @Lambyyy 3 роки тому

      True! The solution is pretty simple, just the instructions are strange lol

  • @hasan_shans
    @hasan_shans 2 роки тому

    What if we have [1,2,3,4,4] ? Two values are different, but if we go with this solution, we will end up overriding the unique values.

    • @reisturm9296
      @reisturm9296 2 роки тому +1

      The algorithm still works for your case .
      [1,2,3,4,4] L=1, R=1
      First loop, if condition is true, so we place nums[R] at index L, so "replace" 2 with 2. Increment both pointers. Same thing happens for 3 and 4. We finally get to the duplicate 4, we'd leave the L pointer behind and only increment R pointer.

    • @prafulparashar9849
      @prafulparashar9849 2 роки тому

      @@reisturm9296 Very good catch 👍

    • @T_tintin
      @T_tintin Рік тому

      It will work

  • @JBEedits
    @JBEedits Рік тому

    If input is [1,1,2] it will do [1,2,2] and l=2
    So print [1,2]
    But expected output is [1,2,_]
    To do this you need to create new array

  • @adilsaju
    @adilsaju 5 місяців тому

    this is the best!

  • @fatimadarbandsari1870
    @fatimadarbandsari1870 2 роки тому

    Thank you

  • @abnerramirez6209
    @abnerramirez6209 Рік тому

    when i put the same code you did I still didn't get the write answer

  • @eli-eli1
    @eli-eli1 Рік тому

    The reason why the problem has so many dislikes is because the description for the task of this problem was horribly explained and seems to be intentionally unclear. It's verbose for literally no reason and the examples don't actually show what you're literally supposed to return. They show a number and a modified array, when you're just supposed to return the number, even though the expected result in the test cases show a modified array but don't show the number for k.
    You literally don't have to modify the array at all, even though the problem tells you to, and the solution would still get accepted as long as you return the right number.

  • @tsukuyomi1485
    @tsukuyomi1485 2 роки тому

    i put the same codes but its saying theres an error

  • @alanjerryson883
    @alanjerryson883 7 місяців тому

    What is the problem?
    Everything works fine in my paycharm, but not on the litcode
    class Solution:
    def removeDuplicates(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    tmp = []
    for i in nums:
    if i not in tmp:
    tmp.append(i)
    nums = tmp
    return len(tmp)
    ------------------------------------------------------------------
    Input
    nums = [0,0,1,1,1,2,2,3,3,4]
    Output
    [0,0,1,1,1]
    Expected
    [0,1,2,3,4]

  • @blackplaydoh3522
    @blackplaydoh3522 Рік тому +1

    I hated this problem

  • @ahmadab9666
    @ahmadab9666 2 роки тому

    thanks alot

  • @premraja55
    @premraja55 3 роки тому

    Awesome as always🙌🏻