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.