Tensorum
YouTubeसीखना शुरू करें
LeetCode 268 · Hashing / Anagram

Missing Number

LeetCode 268 · आसान · समाधान, intuition और कदम-दर-कदम वॉकथ्रू

missing = n(n+1)/2 − sum(nums).

आसानArrayHash TableMathBinary SearchBit Manipulation

मैंने 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. 1

    Frequency version: mark each number, return the first unmarked index.

  2. 2

    Math version: compute the expected total of 0..n.

  3. 3

    Subtract the actual sum — the difference is the missing number.

मैंने कैसे हल किया · पहले विचार से अंतिम हल तक

1
Frequency tableO(n) time · O(n) space

Mark what you see.

2
Gauss sumAcceptedO(n) time · O(1) space

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_sum
स्टेप-थ्रू लोड हो रहा है…

Missing 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.