Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 268 · Hashing / Anagram

Missing Number

LeetCode 268 · ಸುಲಭ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

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

ಸುಲಭArrayHash TableMathBinary SearchBit Manipulation
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು 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.