Тёмный

Remove Element - Leetcode 27 - Python 

NeetCode
Подписаться 841 тыс.
Просмотров 97 тыс.
50% 1

Опубликовано:

 

21 окт 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 85   
@servantofthelord8147
@servantofthelord8147 Месяц назад
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 8 дней назад
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 Год назад
Thank God, finally found someone who explains the concept so clearly
@romeorivera9314
@romeorivera9314 Год назад
I didn't even knew what 'in-place' actually meant :/ (At least I know now)
@veliea5160
@veliea5160 3 года назад
what is the time complexity of growth of this channel :)
@moulee007
@moulee007 2 года назад
exponential
@leeroymlg4692
@leeroymlg4692 Год назад
O(1)
@wonoh3427
@wonoh3427 10 месяцев назад
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 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 4 месяца назад
i solved the first test case but wasn't able to solve the second
@JEVSant
@JEVSant Год назад
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 2 месяца назад
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 года назад
The explanation was excellent and I understand everything, the code wondering why it worked 🥺
@YayaisHERE1
@YayaisHERE1 2 месяца назад
he is overwriting the whole array not a single element that is why I Was wondering too nums[k] = nums[i]
@idrisisah1
@idrisisah1 Год назад
NeetCode you are the best I so much trust and believe you Thanks for sharing all of this for free
@haltersweb
@haltersweb 2 дня назад
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%)
@bablikumari-gp4ce
@bablikumari-gp4ce 3 года назад
Seems similar to partition method of quick sort partition.
3 года назад
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
Год назад
@@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
Год назад
@@gradientO Old description was quite unclear, looks like it is updated.
@entrastic
@entrastic 4 месяца назад
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 2 месяца назад
The array isn’t sorted so the right pointer isn’t finding non vals any faster
@0yustas0
@0yustas0 2 года назад
2 pointers is much better Runtime: 28 ms, faster than 94.80% of Python3 online submissions for Remove Element. class Solution: def removeElement(self, nums: List[int], val: int) -> int: A = nums if len(A)
@vadimen181
@vadimen181 2 года назад
beautiful
@TheIaTaI
@TheIaTaI 2 года назад
Why is the above code much faster than the solution in the video?
@leeroymlg4692
@leeroymlg4692 Год назад
nums[:] = [x for x in nums if x != val] the best solution in terms of maintainability
@themidwife1624
@themidwife1624 Год назад
Can you not just forego defining c since L will always end up on the first target element, so it always equals the number of non targets. Also, the way L and R are defined takes care of the 'empty' edge case, so 'if len(A) < 1' is not needed.
@0yustas0
@0yustas0 Год назад
@@themidwife1624 just 3 lines inside loop: def removeElement(self, nums: List[int], val: int) -> int: A = nums L,R = 0,len(A)-1 while L
@mmmk1414
@mmmk1414 2 года назад
i wrote it exactly like yours but my mistake was that i was returning ''nums'' and kept giving me errors
@swarnendudutta
@swarnendudutta 9 месяцев назад
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 ?
@GaetanoBarreca
@GaetanoBarreca Год назад
Thanks!
@usamahussain4461
@usamahussain4461 2 месяца назад
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.
@iesmatty
@iesmatty 4 месяца назад
thanks for the explanation
@Luc1an_
@Luc1an_ 3 года назад
Similar to Move Zeroes to end.
@NeetCode
@NeetCode 3 года назад
Yeah, exactly!
@meghanagowda9967
@meghanagowda9967 Месяц назад
what is the time and space complexity. of this algorithm?
@azikkii
@azikkii 10 месяцев назад
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 9 месяцев назад
Worst-case scenario of splice is O(n) because the remaining elements need to be shifted
@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 9 месяцев назад
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
@mohammodroby8346
@mohammodroby8346 3 месяца назад
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 3 месяца назад
after simulate i found 2,2,2,3 . and the value of k is 2(This part is right)
@hoyinli7462
@hoyinli7462 3 года назад
hi your video of Leetcode 2002 is now a wrong answer. always getting TLE now
@ItzMxsticTV
@ItzMxsticTV 11 месяцев назад
//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; }
@mibcw
@mibcw 6 месяцев назад
The example 2 output should be [0,1,3,0,4]
@aceuu5759
@aceuu5759 3 года назад
nice explanation !!!
@samyisaac4244
@samyisaac4244 Год назад
you're a legend, man
@SnobbyLion
@SnobbyLion 10 месяцев назад
Omg bro...I tried to do this, ended up having 24 lines of code and you do it in 8 lmao
@zfarahx
@zfarahx 5 месяцев назад
practice makes perfect, keep going 👍🏻
@servantofthelord8147
@servantofthelord8147 Месяц назад
Read-Write pointer :)
@КостяМос-я5о
@КостяМос-я5о 11 месяцев назад
This is genius!
@shuangsun6356
@shuangsun6356 2 года назад
thx!
@SteveOh-j6f
@SteveOh-j6f 11 месяцев назад
you can add another condition to make it even faster: if (nums[i] !== val) { if (k !== i) { nums[k] = nums[i]; } k++; }
@jamescoughlin6357
@jamescoughlin6357 8 месяцев назад
I don't understand how you did this
@roger8603
@roger8603 2 года назад
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 11 месяцев назад
Bro forgot the point of doing leetcode 🗿🗿🗿🗿🗿
@ekcelhenrichekoumelong4457
@ekcelhenrichekoumelong4457 6 месяцев назад
"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).
@notdumb3182
@notdumb3182 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 года назад
Same haha. Ironically I already made many huge web applications
@JEVSant
@JEVSant Год назад
@@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 10 месяцев назад
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.
@shrishailkandi8944
@shrishailkandi8944 3 года назад
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. :/
@arhum1224
@arhum1224 3 дня назад
This is NOT an Easy question lmao
@WhiteBaller
@WhiteBaller 3 месяца назад
im an idiot
@arhum1224
@arhum1224 3 дня назад
same
@A7madYT
@A7madYT Год назад
@funnymoment9164
@funnymoment9164 Год назад
Thanks!
Далее
LeetCode was HARD until I Learned these 15 Patterns
13:00
Борщ в стиле высокой кухни!
00:57
I quit Amazon after two months
10:09
Просмотров 633 тыс.
5 Useful F-String Tricks In Python
10:02
Просмотров 318 тыс.
Yes, I was also Bad at LeetCode
3:20
Просмотров 128 тыс.
Majority Element - Leetcode 169 - Python
14:39
Просмотров 106 тыс.
How I would learn Leetcode if I could start over
18:03
Просмотров 618 тыс.
I gave 127 interviews. Top 5 Algorithms they asked me.
8:36
Борщ в стиле высокой кухни!
00:57