Single Number
LeetCode 136 · आसान · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
2·sum(set(nums)) − sum(nums) = the single value (XOR also works).
मैंने Single Number (LeetCode 136) ऐसे हल किया — Hashing / Anagram पैटर्न का एक आसान प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Every value appears twice except one. Counting works with extra memory; a neat arithmetic trick uses the set of distinct values: doubling their sum counts every value twice, so subtracting the real sum cancels the pairs and leaves the single one.
Approach
- 1
Count occurrences and return the value seen once.
- 2
Or: 2 × sum of distinct values counts everything twice.
- 3
Subtract the actual sum — only the lonely value survives.
मैंने कैसे हल किया · पहले विचार से अंतिम हल तक
Count and pick the 1.
2·sum(set) − sum.
Frequency mapPythonO(n) time · O(n) space
class Solution:
def singleNumber(self, nums: list[int]) -> int:
freq_mpp = defaultdict(int)
for num in nums:
freq_mpp[num]+=1
for item in freq_mpp:
if freq_mpp[item]==1:
return item
return -1
"""
2 times sum/duplicate sum of unique nums
2*(a+b+c) - (a+a+b+b+c) => c
"""Set-sum trickPythonO(n) time · O(n) space
class Solution:
def singleNumber(self, nums: list[int]) -> int:
return 2*sum(set(nums))- sum(nums)Single Number — अक्सर पूछे जाने वाले प्रश्न
Single Number के पीछे intuition क्या है?
Every value appears twice except one. Counting works with extra memory; a neat arithmetic trick uses the set of distinct values: doubling their sum counts every value twice, so subtracting the real sum cancels the pairs and leaves the single one.
Single Number (LeetCode 136) कैसे हल करें?
1. Count occurrences and return the value seen once. 2. Or: 2 × sum of distinct values counts everything twice. 3. Subtract the actual sum — only the lonely value survives.
Single Number की time और space complexity क्या है?
Time: O(n)। Space: O(n) for the set। (Accepted approach: Set-sum trick।)
Single Number में आम गलतियाँ क्या हैं?
XOR of all values gives O(1) extra space: pairs cancel to 0.
क्या Single Number को हल करने के एक से ज़्यादा तरीके हैं?
Frequency map (O(n) time · O(n) space): Count and pick the 1. Set-sum trick (O(n) time · O(n) space): 2·sum(set) − sum.