
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Four Missing Numbers in an Array in Python
Suppose we have an array of distinct numbers where each number lies in the range [1, N], the array size is (N-4) and no single element is repeated. So, we can understand four numbers, from 1 to N, are missing in the array. We have to find these 4 missing numbers in sorted manner.
So, if the input is like A =[2, 8, 4, 13, 6, 11, 9, 5, 10], then the output will be [1, 3, 7, 12]
To solve this, we will follow these steps −
temp_arr := an array of size 4 with all 0s
-
for i in range 0 to size of A, do
temp := |A[i]|
-
if temp <= size of A , then
A[temp - 1] := A[temp - 1] *(-1)
-
otherwise when temp > size of A , then
-
if temp mod size of A is non-zero, then
temp_arr[temp mod size of A - 1] := -1
-
otherwise,
temp_arr[(temp mod size of A) +size of A - 1] := -1
-
-
for i in range 0 to size of A, do
-
if A[i] > 0, then
display i + 1
-
-
for i in range 0 to size of temp_arr, do
-
if temp_arr[i] >= 0, then
display size of A + i + 1
-
Example
Let us see the following implementation to get better understanding −
def find_missing_nums(A) : temp_arr = [0]*4 for i in range(0,len(A)) : temp = abs(A[i]) if (temp <= len(A)) : A[temp - 1] = A[temp - 1] * (-1) elif (temp > len(A)) : if (temp % len(A)) : temp_arr[temp % len(A) - 1] = -1 else : temp_arr[(temp % len(A)) +len(A) - 1] = -1 for i in range(0, len(A) ) : if (A[i] > 0) : print((i + 1) , end=" ") for i in range(0, len(temp_arr)) : if (temp_arr[i] >= 0) : print((len(A) + i + 1) , end=" ") A = [2, 8, 4, 13, 6, 11, 9, 5, 10] find_missing_nums(A)
Input
[2, 8, 4, 13, 6, 11, 9, 5, 10]
Output
1 3 7 12