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.