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.