Missing Number - Complete Solution Guide
Missing Number is LeetCode problem 268, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
Given an array nums containing n distinct numbers in the range [0, n] , return the only number in the range that is missing from the array. Example 1: Input: nums = [3,0,1] Output: 2 Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3] . 2 is the missing number in the range since it does not appear in nums . Example 2: Input: nums = [0,1] Output: 2 Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2] . 2 is the missing number in the r
Detailed Explanation
The problem asks you to find the single missing number within a given array of numbers. The array contains 'n' distinct numbers, and these numbers are within the range [0, n]. This means the array should ideally contain all numbers from 0 to n, but exactly one number is missing. The task is to identify this missing number. For example, if the input is `[3, 0, 1]`, the missing number is 2 because the range is [0, 3] and 2 is absent.
Solution Approach
The solution uses a mathematical approach based on the sum of integers. It calculates the expected sum of numbers from 0 to n using the formula `n*(n+1)/2`, where n is the length of the input array. Then, it calculates the actual sum of the numbers present in the input array. The difference between the expected sum and the actual sum is the missing number. This works because the missing number is the only discrepancy between the expected and actual sum.
Step-by-Step Algorithm
- Step 1: Calculate the length of the input array and store it in variable 'n'.
- Step 2: Calculate the expected sum of numbers from 0 to n using the formula `n * (n + 1) / 2`.
- Step 3: Calculate the actual sum of the numbers in the input array by iterating through the array and summing up its elements.
- Step 4: Subtract the actual sum from the expected sum. The result is the missing number.
Key Insights
- Insight 1: The sum of numbers from 0 to n is easily calculated using the formula n*(n+1)/2.
- Insight 2: The difference between the expected sum (calculated using the formula) and the actual sum of the numbers in the array gives the missing number.
- Insight 3: This approach efficiently solves the problem using constant extra space (O(1)) because it only needs a few integer variables to store sums and the array length.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
Topics
This problem involves: Array, Hash Table, Math, Binary Search, Bit Manipulation, Sorting.
Companies
Asked at: AQR Capital Management, Arista Networks, Cisco, Genpact, Goldman Sachs, Google, Infosys, Nvidia, Revolut, Tesla, Warnermedia, tcs.