there's a small mistake in the dry run in moore's algo at last votes for majority 2 is 1,when majority reaches 3 the votes will be 0, so, majority will be updated in the next iteration so majority will be update as 1, please check, explanation is too good!!!
the dry-run is mainly to understand the simplicity of the code. The exact working code is available in the description too. Mostly you should understand the approach and how you are solving the problem :)
Great video man! Loved this explanation, you are highly underrated. If it's possible can you do python solutions as well for future leetcode videos? Thanks again!
i would advice you to focus on the problem solving method, rather than the language. Trust me...languages will come and go...get your basics right first :)
the voting method returns 1 for me for array {1, 2, 2, 2, 3, 3, 1 } so is that logic correct? I think after your logic, we need to check again in the array if the count of the majority element is greater than (n/2) to be considered as the majority. In my case, the majority is returned as 1 but 1 is repeated 2 times which is not greater than the expected majority which is (>3). here we can suspect 2 could be the majority but it's not because it is not repeated more than 3 times.
Majority element means the element which occurs more than n/2 times. Your test case is invalid, as it does not have a majority element. What you are talking about is the element occurring maximum number of times.
@@foodandjournieswithme8788 check your test case and code again. Here is the verified output: github.com/nikoo28/java-solutions/blob/master/src/test/java/leetcode/easy/MajorityElementTest.java
The mistake in the code is that the loop starts with i = 0, which causes the initial element to be counted twice. Specifically, when the loop starts, nums[0] is already assigned to the majority and the vote is set to 1. The loop then starts from i = 0, incrementing votes for the same element. The correct approach is to start the loop from i = 1. for (int i = 1; i < nums.length; i++)
@@abhiguptamusic That condition is absolutely correct, whenever votes become =0 you need to update your majority candidate, and then increase the vote count. What error do you see in the condition? Did you try running the code?