Missing Number
LeetCode 268 · सोपा · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू
missing = n(n+1)/2 − sum(nums).
मी Missing Number (LeetCode 268) असा सोडवला — Hashing / Anagram पॅटर्नमधील एक सोपा प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.
खालील विवरण इंग्रजीत आहे.
Intuition
The numbers 0..n should all be present except one. You can mark which ones you see, or use arithmetic: the sum of 0..n is n(n+1)/2, and subtracting the actual sum leaves exactly the missing number.
Approach
- 1
Frequency version: mark each number, return the first unmarked index.
- 2
Math version: compute the expected total of 0..n.
- 3
Subtract the actual sum — the difference is the missing number.
मी कसा सोडवला · पहिल्या कल्पनेपासून अंतिम उपायापर्यंत
Mark what you see.
Expected sum minus actual.
Frequency tablePythonO(n) time · O(n) space
class Solution:
def missingNumber(self, nums: list[int]) -> int:
n = len(nums)
freq_table = [0]*(n+1)
for num in nums:
freq_table[num]+=1
for i in range(n+1):
if freq_table[i]==0:
return i
return -1
"""
[0,1,2,3] - 6
[3,0,1] - 4
"""Gauss sumPythonO(n) time · O(1) space
class Solution:
def missingNumber(self, nums: list[int]) -> int:
n = len(nums)
total_sum = n*(n+1)//2
cur_sum = sum(nums)
return total_sum-cur_sumMissing Number — वारंवार विचारले जाणारे प्रश्न
Missing Number मागील intuition काय आहे?
The numbers 0..n should all be present except one. You can mark which ones you see, or use arithmetic: the sum of 0..n is n(n+1)/2, and subtracting the actual sum leaves exactly the missing number.
Missing Number (LeetCode 268) कसा सोडवावा?
1. Frequency version: mark each number, return the first unmarked index. 2. Math version: compute the expected total of 0..n. 3. Subtract the actual sum — the difference is the missing number.
Missing Number ची time आणि space complexity किती आहे?
Time: O(n). Space: O(1). (Accepted approach: Gauss sum.)
Missing Number मध्ये सामान्य चुका कोणत्या?
The range is 0..n inclusive (n+1 values), not 1..n.
Missing Number सोडवण्याचे एकापेक्षा जास्त मार्ग आहेत का?
Frequency table (O(n) time · O(n) space): Mark what you see. Gauss sum (O(n) time · O(1) space): Expected sum minus actual.