Majority Element
LeetCode 169 · எளிது · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Vote: same → +1, different → −1, zero → new candidate.
நான் Majority Element (LeetCode 169) ஐ இப்படித் தீர்த்தேன் — Moore Voting பேட்டர்னின் ஒரு எளிது பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
Boyer–Moore voting: pair each occurrence of the candidate against a different value and cancel them. The majority element appears more than half the time, so it can't be fully cancelled and is left as the candidate.
Approach
- 1
count = 0, element = None.
- 2
When count is 0, adopt the current number.
- 3
Same number → count++; different → count−−.
- 4
The surviving element is the majority.
நான் எப்படித் தீர்த்தேன்
Boyer–Moore votingPythonO(n) time · O(1) space
class Solution:
def majorityElement(self, nums: List[int]) -> int:
count =0
element=None
for num in nums:
if count==0:
element=num
count=1
elif element==num:
count+=1
elif element!=num:
count-=1
return element
Majority Element — அடிக்கடி கேட்கப்படும் கேள்விகள்
Majority Element பின்னாலுள்ள intuition என்ன?
Boyer–Moore voting: pair each occurrence of the candidate against a different value and cancel them. The majority element appears more than half the time, so it can't be fully cancelled and is left as the candidate.
Majority Element (LeetCode 169) ஐ எப்படித் தீர்ப்பது?
1. count = 0, element = None. 2. When count is 0, adopt the current number. 3. Same number → count++; different → count−−. 4. The surviving element is the majority.
Majority Element இன் time மற்றும் space complexity என்ன?
Time: O(n). Space: O(1). (Accepted approach: Boyer–Moore voting.)
Majority Element இல் பொதுவான தவறுகள் என்ன?
This relies on a majority being guaranteed — otherwise verify with a second pass.