i don't understand how we can come up with this in an interview or OA without already knowing it before
@shyam4034 Жыл бұрын
That will happen only when you practice and learn the patterns in the questions
@pacerq5337 Жыл бұрын
that's why you need to prepare and learn especially from neetcode.
@li-xuanhong3698 Жыл бұрын
@@sambro890 this will not satisfy the O(1) space complexity
@leeroymlg4692 Жыл бұрын
there are easier solutions to come up with instead, but not as efficient. I'm sure it's rare to come up with the perfect solution in an interview
@buttofthejoke10 ай бұрын
@@pacerq5337yeah but that only means you've mugged up the answers. that doesn't mean that you're a better developer than someone who just missed visiting this problem
@UpTwist Жыл бұрын
Thanks for the daily It's Boyer Moore's algorithm btw if anyone wants to read up on it.
@ngneerin Жыл бұрын
Boyer Moore. Thanks
@lenzvital2776 Жыл бұрын
def majorityElement(nums): if not nums: return [] # 1st pass count1, count2, candidate1, candidate2 = 0, 0, 0, 1 for n in nums: if n == candidate1: count1 += 1 elif n == candidate2: count2 += 1 elif count1 == 0: candidate1, count1 = n, 1 elif count2 == 0: candidate2, count2 = n, 1 else: count1, count2 = count1-1, count2-1 # 2nd pass return [n for n in (candidate1, candidate2) if nums.count(n) > len(nums) // 3] Space complexity = O(1), Time complexity = O(n)
@IntelliStar_28 күн бұрын
Such a beautiful implementation of Boyer Moore's algorithm!
@sambro890 Жыл бұрын
This is my solution using Hashmap and easier to understand class Solution: def majorityElement(self, nums: List[int]) -> List[int]: res = [] n = len(nums) hashmap = {} for ele in nums: if ele not in hashmap: hashmap[ele] = 1 else: hashmap[ele] += 1 k = n // 3 for key, val in hashmap.items(): if val > k: res.append(key) return res
@NeetCodeIO Жыл бұрын
Yeah it's definitely more intuitive, but I believe the memory usage is higher with this solution.
@sambro890 Жыл бұрын
@@NeetCodeIO yes. Your solution is better.
@Pegasus02Kr Жыл бұрын
great explanation. still think the additional condition makes it unnecessarily complicated though
@tanish5662 Жыл бұрын
I have a doubt, I am not sure if people will address but i think if we dont delete an element in hashmap, it will stay there with the content 0. I am not sure how the python backend complier works, but it kind of stricked me. So i used del Dict[key] in my code.
@dumbfailurekms Жыл бұрын
neetcode....is a legend
@ngneerin Жыл бұрын
Did not understand half of what you did in code. But I did the same as follows: def majorityElement(nums): m = {} for num in nums: if num in m: m[num] += 1 elif len(m) < 3: m[num] = 1 else: for k in list(m): if m[k] == 1: del m[k] else: m[k] -= 1 n = {} for num in nums: if num in n: n[num] += 1 elif num in m: n[num] = 1 ans = [] for k, v in n.items(): if v > len(nums) // 3: ans.append(k) return ans
@rebellious_703 Жыл бұрын
We say hashMap count > 2 because of n/3 or it is just a trick?
@chuckle_pugz96 Жыл бұрын
yeah because of n/3. if the question asked n/4 we would have used len(hashMap) >3
@plsgivemecat Жыл бұрын
@@chuckle_pugz96 So generalizing for n/k, would we use len(hashmap) > (k-1) ?
@chuckle_pugz96 Жыл бұрын
@@plsgivemecat yep correct
@infoknow3278 Жыл бұрын
hey neetcode solve potd 1420. Build Array Where You Can Find The Maximum Exactly K Comparisons
@ronbuchanan5432 Жыл бұрын
Thanks neety, but I'm lacking the intuition in your explanation which I think is very important
@adityaparab4314 Жыл бұрын
if we are using a map how is the space complexity still O(1)..?
@Kan-JenLiu Жыл бұрын
at most the size of the map is 3
@adityaparab4314 Жыл бұрын
@@Kan-JenLiu thanks!
@satwiktatikonda764 Жыл бұрын
My doubt is cant we do majority element 1 also in this approach If any one has any idea ,let me know
@ngneerin Жыл бұрын
He already showed it in some other video. Same way, little simpler though
@batman8377 Жыл бұрын
Hi guys! How can we replace "if nums.count(n) > len(nums) // 3" in Java without using another loop?
@sangeethajain744611 ай бұрын
u can traverse through the list again for counting the possible 2 most frequent elements. any inbuilt function too will run through the loop to give u counts the algorithm would still be O(n) asymptomatically and the total work leetcode will do while submitting will be in its constraints ,No TLE
@ignitedminds61648 ай бұрын
class Solution(object): def majorityElement(self, nums): n=len(nums) count={} result1=n/3 list1=[] for i in nums: if i in count: count[i]+=1 else: count[i]=1 for key,value in count.items(): if value>result1: list1.append(key) else: pass return list1
@littletiger12282 ай бұрын
extra space needed
@ttheguyy Жыл бұрын
How to solve this with O(1) space?
@DeathSugar Жыл бұрын
have two hashmaps of size 3 and return vector of size 2. and follow algo on the viideo.
@Akhillbj Жыл бұрын
HashMaps are N space
@NeetCodeIO Жыл бұрын
Hashmaps are not necessarily O(n) space. In this problem it's important to "remove" all elements with a count of 0, after the size of the map grows to 3.
@DeathSugar Жыл бұрын
@@Akhillbj if you wipe/pop elements from it at the certain size it's pretty much constant to the named size. Think of it as some cache not the regular hashmap
@reggie06 Жыл бұрын
@@NeetCodeIO hey neetcode, I have noticed not a lot of people have a great understanding of the concept of space and time complexities, with there being a lot of confusions such as seeing a double for loop and assuming thats o(n^2) in time, or a hashmap/stack/any other data structure and assuming that means we are using at least linear space. I think it would be very valuable discussing what complexities mean in algorithms, how to evaluate them, and how they can be useful. It would also be interesting in hearing what you think the importance of them in terms of tech interviews and how likely someone will have to explain the space complexity of their code for example
@pacerq5337 Жыл бұрын
Why don't we need a **deep copy** of the dictionary of new_count here?
@ihsannuruliman4005 Жыл бұрын
solve unique binary trees II
@sambro890 Жыл бұрын
class Solution: def generateTrees(self, n: int) -> List[Optional[TreeNode]]: dp = {} def memo(start, end): all_trees = [] if start > end: return [None,] elif (start, end) in dp: return dp[(start, end)] else: for i in range(start, end + 1): left = memo(start, i - 1) right = memo(i + 1, end) for r in right: for l in left: current = TreeNode(i) current.left = l current.right = r all_trees.append(current) dp[(start, end)] = all_trees return dp[(start, end)] return memo(1, n) unique binary trees II using memoization
@gabriel-accetta Жыл бұрын
Another way of doing it is checking if the count of the current number is equal to len(nums)//3 + 1, if it is you append the number to result actually i dont know if that solution is worse in some way, im accepting corrections
@satwiktatikonda764 Жыл бұрын
Tc is O(N) for iterrating over nums array and o(N) for count so final TC is o(n^2) wch is not desired
@shubhamraj25 Жыл бұрын
it's def unoptimized lol, the follow up asks for a O(1) SC solution and the one you are giving is O(n) space complexity
@reggie06 Жыл бұрын
@@shubhamraj25 How would his gabriel is sol be o(n) space?
@shivam-codes Жыл бұрын
what if test case is [2 , 1 , 1 , 3 , 1 , 4 , 5 , 6] , I dont understand how your logic is going to wok here ?? the answer is [1] , how is your logic going to get me answer to mentioned test case ? can anyone explain
@NeetCodeIO Жыл бұрын
it definitely works on this example, I would dry run it to prove it to yourself
@disenchanted_dove9 ай бұрын
[2 , 1 , 1 , 3 , 1 , 4 , 5 , 6] index 0 - map {2: 1} index 1 - map{2: 1, 1: 1} index 2 - map {2: 1, 1: 2} index 3 - map { 1: 1 } index 4 - map {1 : 2} index 5 - map { 1: 2, 4: 1} index 6 - map { 1: 1} index 7 - map {1: 1, 6: 1} see if you got these right. you are probably including the current iteration element in map after decrementing the counters which is not correct.
@melvinjijumathew3022Ай бұрын
@@disenchanted_dove in the end he is checking again to verify if the element frequency is greater than n/3 using count function
@Александр-ф9в3х Жыл бұрын
I'm tired of skipping videos with Indian accents. You saved me bro
@shubham_bit2 Жыл бұрын
The guy is still an indian though, there's no escape
@adityaparab4314 Жыл бұрын
I guess knowledge is more important than accent....sorry we are smarter than wherever you're from.😅
@illu1na Жыл бұрын
@@shubham_bit2lol there is no escape 😂😂😂
@reggie06 Жыл бұрын
@@adityaparab4314 To be fair, there is a ton of computer science youtubers with very thick indian accents where it seems like half of the time they aren't even speaking english. So I can definitely feel the main commenter on this one haha