Majority Element II
LeetCode 229 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Count and keep values with count > n // 3.
मैंने Majority Element II (LeetCode 229) ऐसे हल किया — Moore Voting पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Any value appearing more than n/3 times qualifies; there can be at most two. Counting every value with a Counter and filtering by the threshold is straightforward.
Approach
- 1
Count frequencies.
- 2
Keep each value whose count exceeds n // 3.
मैंने कैसे हल किया
Counter filterPythonO(n) time · O(n) space
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
n = len(nums)
mpp = Counter(nums)
res = []
for key,val in mpp.items():
if val>(n//3):
res.append(key)
return resMajority Element II — अक्सर पूछे जाने वाले प्रश्न
Majority Element II के पीछे intuition क्या है?
Any value appearing more than n/3 times qualifies; there can be at most two. Counting every value with a Counter and filtering by the threshold is straightforward.
Majority Element II (LeetCode 229) कैसे हल करें?
1. Count frequencies. 2. Keep each value whose count exceeds n // 3.
Majority Element II की time और space complexity क्या है?
Time: O(n)। Space: O(n)। (Accepted approach: Counter filter।)
Majority Element II में आम गलतियाँ क्या हैं?
Extended Boyer–Moore (two candidates) does it in O(1) space.