Remove Element - Leetcode 27 - Python

Поделиться
HTML-код
  • Опубликовано: 12 дек 2024
  • НаукаНаука

Комментарии • 73

  • @servantofthelord8147
    @servantofthelord8147 3 месяца назад +12

    It's bizarre how many in-place problems you can solve using these exact lines of code (and some variant of the quicksort partition). Even more bizarre are the number of array problems that you can optimize for space complexity by turning them into in-place problems. Thank you so much!! I'm watching your videos concurrently with the Leetcode Arrays explore card, and everything is just starting to click and I can't believe I was just going into interviews this whole time without understanding how systematic your approach should be during interviews. I just practiced a ton and hoped I'd get lucky with stuff I remembered - but now I can reliably solve entire categories of problems with confidence every single time I see them in practice.

    • @eca8652
      @eca8652 2 месяца назад

      Hi. Can we link up. I am a freshman practicing leetcode also. I am grasping the concepts bit by bit, practicing towards a potential interview, and I would love the opportunity to chat with you and gain insights about your development.

  • @sekharsamanta6266
    @sekharsamanta6266 Год назад +29

    Thank God, finally found someone who explains the concept so clearly

    • @romeorivera9314
      @romeorivera9314 Год назад +5

      I didn't even knew what 'in-place' actually meant :/
      (At least I know now)

  • @veliea5160
    @veliea5160 3 года назад +52

    what is the time complexity of growth of this channel :)

  • @wonoh3427
    @wonoh3427 Год назад +5

    Thank you for the wonderful explanation. If you just use [for n in nums:] instead of [for i in range(len(nums):] it slightly improves the runtime as you avoid redundant array element access using indexes.

  • @austindavoren1339
    @austindavoren1339 6 месяцев назад +4

    This is really smart, I didn't think about this at all because I didn't understand the question, I thought it wanted us to SWAP the val with non val, but in truth, it doesn't really matter if val stays in the array or not, just that there is no val infront of non val, and we return the correct number of non vals.

    • @imrozkhan71
      @imrozkhan71 6 месяцев назад

      i solved the first test case but wasn't able to solve the second

  • @GaetanoBarreca
    @GaetanoBarreca Год назад +11

    Thanks!

  • @JEVSant
    @JEVSant Год назад +7

    The little disadvantage I see on this that is giving it such low score is exactly what was mentioned, that this is gonna perform the swap every time regardless of if its needed or not

    • @julian_handpan
      @julian_handpan 4 месяца назад +1

      not true!
      Assume:
      nums = [1,2,3]
      i = 0
      j = 0
      nums[i] = nums[j]
      The element of the array in this case "1" is the same(Same memory address), the thing that is changing is th index "i", "j".

  • @mwnkt
    @mwnkt 2 года назад +12

    The explanation was excellent and I understand everything, the code wondering why it worked 🥺

    • @YayaisHERE1
      @YayaisHERE1 4 месяца назад

      he is overwriting the whole array not a single element that is why I Was wondering too
      nums[k] = nums[i]

  • @bablikumari-gp4ce
    @bablikumari-gp4ce 3 года назад +9

    Seems similar to partition method of quick sort partition.

  • @haltersweb
    @haltersweb Месяц назад

    In this case I used replace() in my Python solution since replace() is an in-place method. Resulted in a 4-line solution. Memory complexity was O(1) and runtime was 0ms (100%)

  • @entrastic
    @entrastic 6 месяцев назад

    You can make it faster by swapping non-val numbers from the back of the array. Just use another pointer from the back of the array. Stop the swapping when your "front pointer" is greater than or equal to your "back pointer". Hope that helps

    • @LAFLAME1111
      @LAFLAME1111 4 месяца назад

      The array isn’t sorted so the right pointer isn’t finding non vals any faster

  • @idrisisah1
    @idrisisah1 Год назад +1

    NeetCode you are the best I so much trust and believe you
    Thanks for sharing all of this for free

  • @vishnupandey3390
    @vishnupandey3390 Месяц назад

    Pythonic Solution
    class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
    length=len(nums)
    if val not in nums: return length
    l,r=0,length-1
    while l=r: return l
    nums[l],nums[r]=nums[r],nums[l]
    l+=1
    return l

  • @shuddhendushekharmishra6958
    @shuddhendushekharmishra6958 Год назад

    # Take an easy solution for this problem
    class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
    i = 0
    l = len(nums)
    while i < l:
    if nums[i] == val:
    # Just pop the element if it's equal to val
    nums.pop(i)
    l -= 1
    else:
    i += 1
    return len(nums)

    • @fusehchan4775
      @fusehchan4775 11 месяцев назад

      im pretty sure .pop() updates the length of nums so doing "I -= 1" after "nums.pop(i)" isn't necessary right? I might be mistaken but I actually did the exact same thing you did without that

  •  3 года назад +11

    I think biggest reason that this question has so many down votes is mutability of arrays since they are "fixed sized" data structure.

    • @pinakadhara7650
      @pinakadhara7650 Год назад

      Can you please explain? I didn't understand

    •  Год назад +1

      @@pinakadhara7650 In general, arrays are fixed sized. That means, you can't (or at least too expensive) expand or shrink them. You can change their values but their size will be the same.
      en.wikipedia.org/wiki/Array_(data_structure)
      In past, the description was like: "Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory." which a lot of users were complained about this explanation.

    • @gradientO
      @gradientO Год назад

      ​@ description is quite clear. It doesn't expect us to change the length of array. After changing elements, we'd return the *size* of the array without the `val` elements , not a new array

    •  Год назад +2

      @@gradientO Old description was quite unclear, looks like it is updated.

  • @ItzMxsticTV
    @ItzMxsticTV Год назад +1

    //My solution going backwards through
    public int removeElement(int[] nums, int val) {
    int last = nums.length - 1;
    //go through and just swap the val we dont want to the end pointer
    for(int i = nums.length - 1; i >= 0; i--){
    if(nums[i] == val){
    nums[i] = nums[last];
    nums[last] = -1;
    last--;
    }
    }
    return last+1;
    }

  • @mmmk1414
    @mmmk1414 2 года назад +3

    i wrote it exactly like yours but my mistake was that i was returning ''nums'' and kept giving me errors

  • @usamahussain4461
    @usamahussain4461 4 месяца назад

    I solved it using a while loop which would simply remove the element from the list if the number is equal to val, otherwise it would increment the index. then we will finally return the index.

  • @swarnendudutta
    @swarnendudutta 10 месяцев назад

    I have learnt this from your other videos , Why didn't you use 2 pointers solution which is O( n - number_of_occurrence_of_val) instead of O(n) ? any thoughts ?

  • @iesmatty
    @iesmatty 6 месяцев назад +1

    thanks for the explanation

  • @arhum1224
    @arhum1224 Месяц назад +2

    This is NOT an Easy question lmao

  • @Luc1an_
    @Luc1an_ 3 года назад +4

    Similar to Move Zeroes to end.

    • @NeetCode
      @NeetCode  3 года назад +2

      Yeah, exactly!

  • @azikkii
    @azikkii Год назад +1

    Why can’t you just splice the element out since the other non-k elements will just fall in place when you splice the array? I don’t think that removes the O(n)

    • @nklido
      @nklido 11 месяцев назад

      Worst-case scenario of splice is O(n) because the remaining elements need to be shifted

  • @ashfanus5008
    @ashfanus5008 Месяц назад

    class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
    k = 0
    for i in range(len(nums)):
    if val in nums:
    nums.remove(val)
    k += 1
    return k
    How about this, it worked tho

  • @hoyinli7462
    @hoyinli7462 3 года назад +3

    hi
    your video of Leetcode 2002 is now a wrong answer. always getting TLE now

  • @meghanagowda9967
    @meghanagowda9967 3 месяца назад

    what is the time and space complexity. of this algorithm?

  • @mohammodroby8346
    @mohammodroby8346 5 месяцев назад

    Brother , I am here to learn. In my perception , I think there may a problem when we use [3,2,2,3] according your code.Waiting for your reply

    • @mohammodroby8346
      @mohammodroby8346 5 месяцев назад

      after simulate i found 2,2,2,3 . and the value of k is 2(This part is right)

  • @aceuu5759
    @aceuu5759 3 года назад +1

    nice explanation !!!

  • @samyisaac4244
    @samyisaac4244 Год назад

    you're a legend, man

  • @mibcw
    @mibcw 8 месяцев назад

    The example 2 output should be [0,1,3,0,4]

  • @servantofthelord8147
    @servantofthelord8147 3 месяца назад

    Read-Write pointer :)

  • @КостяМос-я5о
    @КостяМос-я5о Год назад

    This is genius!

  • @shuangsun6356
    @shuangsun6356 2 года назад +1

    thx!

  • @SnobbyLion
    @SnobbyLion Год назад

    Omg bro...I tried to do this, ended up having 24 lines of code and you do it in 8 lmao

    • @zfarahx
      @zfarahx 7 месяцев назад

      practice makes perfect, keep going 👍🏻

  • @SteveOh-j6f
    @SteveOh-j6f Год назад

    you can add another condition to make it even faster:
    if (nums[i] !== val) {
    if (k !== i) {
    nums[k] = nums[i];
    }
    k++;
    }

  • @WhiteBaller
    @WhiteBaller 4 месяца назад +2

    im an idiot

  • @notdumb3182
    @notdumb3182 2 года назад +2

    Hey bro i just started with leetcode and i can't solve any questions even the easy one. How do i approch a problem man. Can you please make a videos in it. I feel dumb.

    • @PAUL-ky4dq
      @PAUL-ky4dq 2 года назад +5

      Same haha. Ironically I already made many huge web applications

    • @JEVSant
      @JEVSant Год назад +5

      @@PAUL-ky4dq Funny enough, the skills you're gonna end up using during the job have little or nothing to do with what they ask in the interviews. Sometimes it feels like you're just memorizing the answers to standardized questions

    • @sancho608
      @sancho608 Год назад

      hey pal. I still feel that way too. I found a solution to this code that has 96% memory and 90% run time and it is very simple to understand. while a value is in the list, remove that value. then return the length of the list without the value. Makes sense?
      def removeElement(self, nums: List[int], val: int) -> int:

      while val in nums:
      nums.remove(val)

      return len(nums)

    • @azikkii
      @azikkii Год назад

      You shouldn’t look at it as “easy” even though it says easy. Easy means there is usually a super simple way to do it but if you do it in some elaborate way it’s not easy. Hope that makes sense. I actually do better with the medium problems bc I’m not great at noticing subtle patterns and mediums are more in line with my overthinking of every problem.

  • @jamescoughlin6357
    @jamescoughlin6357 10 месяцев назад

    I don't understand how you did this

  • @A7madYT
    @A7madYT Год назад

  • @roger8603
    @roger8603 2 года назад +3

    class Solution(object):
    def removeElement(self, nums, val):
    for v in nums[:]:
    if v==val:
    nums.remove(v)
    return len(nums)
    This is faster than 70% of answers

    • @EIpshitaRay
      @EIpshitaRay 2 года назад

      how do you give list as input though

    • @EIpshitaRay
      @EIpshitaRay 2 года назад

      class Solution(object):
      def removeElement(self, nums, val):
      for i in range(0,len(nums)):
      if val in nums:
      nums.remove(val)
      print(nums)
      c1 = Solution()
      nums = [3,2,2,3]
      val = 2
      c1.removeElement(nums,val)

    • @eugeneb9256
      @eugeneb9256 Год назад

      This modifies the array so it wont work in a real interview even if leetcode accepts it

    • @blank2588
      @blank2588 Год назад +1

      Bro forgot the point of doing leetcode 🗿🗿🗿🗿🗿

    • @ekcelhenrichekoumelong4457
      @ekcelhenrichekoumelong4457 8 месяцев назад

      "v in nums" is O(n), also "nums.remove()" is O(n) so in the worth case, let's say, nums is only composed of "val" (nums = [val, val, val...]), you solution's time complexity is O(n^2).

  • @shrishailkandi8944
    @shrishailkandi8944 3 года назад +1

    While (val in nums):
    nums.remove(val)
    len(nums)
    Is this wrong?

    • @zg5828
      @zg5828 3 года назад

      ..... you forgot k += 1. When I attempted the question, it told me to return k. :/

  • @funnymoment9164
    @funnymoment9164 Год назад

    Thanks!