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.