Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find all missing numbers from 1 to N in Python
Finding missing numbers from a range is a common programming problem. Given a list of numbers where each number should be in the range [1, N], we need to identify which numbers are missing. Some numbers may appear multiple times while others are missing entirely.
So, if the input is like [4, 4, 2, 2, 6, 6], then the output will be [1, 3, 5] since these numbers are missing from the range [1, 6].
Using Array Counting Method
This approach uses an auxiliary array to count occurrences of each number ?
def find_missing_numbers(nums):
# Create array of size n+1 to handle indices 1 to n
n = len(nums)
count = [0] * (n + 1)
# Count occurrences of each number
for num in nums:
count[num] += 1
# Find missing numbers (count = 0, excluding index 0)
missing = []
for i in range(1, len(count)):
if count[i] == 0:
missing.append(i)
return missing
# Test the function
numbers = [4, 4, 2, 2, 6, 6]
result = find_missing_numbers(numbers)
print("Input:", numbers)
print("Missing numbers:", result)
Input: [4, 4, 2, 2, 6, 6] Missing numbers: [1, 3, 5]
Using Set Difference Method
A more Pythonic approach using sets to find the difference ?
def find_missing_with_set(nums):
n = len(nums)
# Create set of all numbers from 1 to n
complete_set = set(range(1, n + 1))
# Create set from input numbers
nums_set = set(nums)
# Find missing numbers using set difference
missing = sorted(list(complete_set - nums_set))
return missing
# Test the function
numbers = [4, 4, 2, 2, 6, 6]
result = find_missing_with_set(numbers)
print("Input:", numbers)
print("Missing numbers:", result)
Input: [4, 4, 2, 2, 6, 6] Missing numbers: [1, 3, 5]
Using List Comprehension
A concise one-liner solution using list comprehension ?
def find_missing_comprehension(nums):
n = len(nums)
nums_set = set(nums)
return [i for i in range(1, n + 1) if i not in nums_set]
# Test the function
numbers = [4, 4, 2, 2, 6, 6]
result = find_missing_comprehension(numbers)
print("Input:", numbers)
print("Missing numbers:", result)
Input: [4, 4, 2, 2, 6, 6] Missing numbers: [1, 3, 5]
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Array Counting | O(n) | O(n) | Good |
| Set Difference | O(n) | O(n) | Excellent |
| List Comprehension | O(n) | O(n) | Very Good |
Conclusion
The set difference method is the most Pythonic and readable solution. All approaches have O(n) time complexity, but the set-based solutions are more intuitive and easier to understand.
