Find the smallest missing number
Last Updated :
23 Jul, 2025
Given a sorted array of n distinct integers where each integer is in the range from 0 to m-1 and m > n. Find the smallest number that is missing from the array.
Examples:
Input: {0, 1, 2, 6, 9}, n = 5, m = 10
Output: 3
Input: {4, 5, 10, 11}, n = 4, m = 12
Output: 0
Input: {0, 1, 2, 3}, n = 4, m = 5
Output: 4
Input: {0, 1, 2, 3, 4, 5, 6, 7, 10}, n = 9, m = 11
Output: 8
Thanks to Ravichandra for suggesting following two methods.
Method 1 (Use Binary Search)
For i = 0 to m-1, do binary search for i in the array. If i is not present in the array then return i.
Time Complexity: O(m log n)
Method 2 (Linear Search)
If arr[0] is not 0, return 0. Otherwise traverse the input array starting from index 0, and for each pair of elements a[i] and a[i+1], find the difference between them. if the difference is greater than 1 then a[i]+1 is the missing number.
Time Complexity: O(n)
Another approach using linear search involves no need of finding the difference between the elements a[i] and a[i+1]. Starting from arr[0] to arr[n-1] check until arr[i] != i. If the condition (arr[i] != i) is satisfied then 'i' is the smallest missing number. If the condition is not satisfied, then it means there is no missing number in the given arr[], then return the element arr[n-1]+1 which is same as 'n'.
Time Complexity: O(n)
Method 3 (Use Modified Binary Search)
Thanks to yasein and Jams for suggesting this method.
In the standard Binary Search process, the element to be searched is compared with the middle element and on the basis of comparison result, we decide whether to search is over or to go to left half or right half.
In this method, we modify the standard Binary Search algorithm to compare the middle element with its index and make decision on the basis of this comparison.
- If the first element is not same as its index then return first index
- Else get the middle index say mid
- If arr[mid] greater than mid then the required element lies in left half.
- Else the required element lies in right half.
C++
// C++ program to find the smallest elements
// missing in a sorted array.
#include<bits/stdc++.h>
using namespace std;
int findFirstMissing(int array[],
int start, int end)
{
if (start > end)
return end + 1;
if (start != array[start])
return start;
int mid = (start + end) / 2;
// Left half has all elements
// from 0 to mid
if (array[mid] == mid)
return findFirstMissing(array,
mid+1, end);
return findFirstMissing(array, start, mid);
}
// Driver code
int main()
{
int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 10};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Smallest missing element is " <<
findFirstMissing(arr, 0, n-1) << endl;
}
// This code is contributed by
// Shivi_Aggarwal
C
// C program to find the smallest elements missing
// in a sorted array.
#include<stdio.h>
int findFirstMissing(int array[], int start, int end)
{
if (start > end)
return end + 1;
if (start != array[start])
return start;
int mid = (start + end) / 2;
// Left half has all elements from 0 to mid
if (array[mid] == mid)
return findFirstMissing(array, mid+1, end);
return findFirstMissing(array, start, mid);
}
// driver program to test above function
int main()
{
int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 10};
int n = sizeof(arr)/sizeof(arr[0]);
printf("Smallest missing element is %d",
findFirstMissing(arr, 0, n-1));
return 0;
}
Java
import java.io.*;
class SmallestMissing
{
int findFirstMissing(int array[], int start, int end)
{
if (start > end)
return end + 1;
if (start != array[start])
return start;
int mid = (start + end) / 2;
// Left half has all elements from 0 to mid
if (array[mid] == mid)
return findFirstMissing(array, mid+1, end);
return findFirstMissing(array, start, mid);
}
// Driver program to test the above function
public static void main(String[] args)
{
SmallestMissing small = new SmallestMissing();
int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 10};
int n = arr.length;
System.out.println("First Missing element is : "
+ small.findFirstMissing(arr, 0, n - 1));
}
}
Python3
# Python3 program to find the smallest
# elements missing in a sorted array.
def findFirstMissing(array, start, end):
if (start > end):
return end + 1
if (start != array[start]):
return start;
mid = int((start + end) / 2)
# Left half has all elements
# from 0 to mid
if (array[mid] == mid):
return findFirstMissing(array,
mid+1, end)
return findFirstMissing(array,
start, mid)
# driver program to test above function
arr = [0, 1, 2, 3, 4, 5, 6, 7, 10]
n = len(arr)
print("Smallest missing element is",
findFirstMissing(arr, 0, n-1))
# This code is contributed by Smitha Dinesh Semwal
C#
// C# program to find the smallest
// elements missing in a sorted array.
using System;
class GFG
{
static int findFirstMissing(int []array,
int start, int end)
{
if (start > end)
return end + 1;
if (start != array[start])
return start;
int mid = (start + end) / 2;
// Left half has all elements from 0 to mid
if (array[mid] == mid)
return findFirstMissing(array, mid+1, end);
return findFirstMissing(array, start, mid);
}
// Driver program to test the above function
public static void Main()
{
int []arr = {0, 1, 2, 3, 4, 5, 6, 7, 10};
int n = arr.Length;
Console.Write("smallest Missing element is : "
+ findFirstMissing(arr, 0, n - 1));
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP program to find the
// smallest elements missing
// in a sorted array.
// function that returns
// smallest elements missing
// in a sorted array.
function findFirstMissing($array, $start, $end)
{
if ($start > $end)
return $end + 1;
if ($start != $array[$start])
return $start;
$mid = ($start + $end) / 2;
// Left half has all
// elements from 0 to mid
if ($array[$mid] == $mid)
return findFirstMissing($array,
$mid + 1,
$end);
return findFirstMissing($array,
$start,
$mid);
}
// Driver Code
$arr = array (0, 1, 2, 3, 4, 5, 6, 7, 10);
$n = count($arr);
echo "Smallest missing element is " ,
findFirstMissing($arr, 2, $n - 1);
// This code Contributed by Ajit.
?>
JavaScript
<script>
// Javascript program to find the smallest
// elements missing in a sorted array.
function findFirstMissing(array, start, end)
{
if (start > end)
return end + 1;
if (start != array[start])
return start;
let mid = parseInt((start + end) / 2, 10);
// Left half has all elements from 0 to mid
if (array[mid] == mid)
return findFirstMissing(array, mid+1, end);
return findFirstMissing(array, start, mid);
}
let arr = [0, 1, 2, 3, 4, 5, 6, 7, 10];
let n = arr.length;
document.write("smallest Missing element is " +
findFirstMissing(arr, 0, n - 1));
</script>
OutputSmallest missing element is 8
Note: This method doesn't work if there are duplicate elements in the array.
Time Complexity: O(Log n)
Auxiliary Space : O(Log n)
Another Method: The idea is to use Recursive Binary Search to find the smallest missing number. Below is the illustration with the help of steps:
- If the first element of the array is not 0, then the smallest missing number is 0.
- If the last elements of the array is N-1, then the smallest missing number is N.
- Otherwise, find the middle element from the first and last index and check if the middle element is equal to the desired element. i.e. first + middle_index.
- If the middle element is the desired element, then the smallest missing element is in the right search space of the middle.
- Otherwise, the smallest missing number is in the left search space of the middle.
Below is the implementation of the above approach:
C++
//C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Program to find missing element
int findFirstMissing(vector<int> arr , int start ,
int end,int first)
{
if (start < end)
{
int mid = (start + end) / 2;
/** Index matches with value
at that index, means missing
element cannot be upto that po*/
if (arr[mid] != mid+first)
return findFirstMissing(arr, start,
mid , first);
else
return findFirstMissing(arr, mid + 1,
end , first);
}
return start + first;
}
// Program to find Smallest
// Missing in Sorted Array
int findSmallestMissinginSortedArray(vector<int> arr)
{
// Check if 0 is missing
// in the array
if(arr[0] != 0)
return 0;
// Check is all numbers 0 to n - 1
// are present in array
if(arr[arr.size() - 1] == arr.size() - 1)
return arr.size();
int first = arr[0];
return findFirstMissing(arr, 0, arr.size() - 1, first);
}
// Driver program to test the above function
int main()
{
vector<int> arr = {0, 1, 2, 3, 4, 5, 7};
int n = arr.size();
// Function Call
cout<<"First Missing element is : "<<findSmallestMissinginSortedArray(arr);
}
// This code is contributed by mohit kumar 29.
Java
// Java Program for above approach
import java.io.*;
class GFG
{
// Program to find Smallest
// Missing in Sorted Array
int findSmallestMissinginSortedArray(
int[] arr)
{
// Check if 0 is missing
// in the array
if(arr[0] != 0)
return 0;
// Check is all numbers 0 to n - 1
// are present in array
if(arr[arr.length-1] == arr.length - 1)
return arr.length;
int first = arr[0];
return findFirstMissing(arr,0,
arr.length-1,first);
}
// Program to find missing element
int findFirstMissing(int[] arr , int start ,
int end, int first)
{
if (start < end)
{
int mid = (start+end)/2;
/** Index matches with value
at that index, means missing
element cannot be upto that point */
if (arr[mid] != mid+first)
return findFirstMissing(arr, start,
mid , first);
else
return findFirstMissing(arr, mid+1,
end , first);
}
return start+first;
}
// Driver program to test the above function
public static void main(String[] args)
{
GFG small = new GFG();
int arr[] = {0, 1, 2, 3, 4, 5, 7};
int n = arr.length;
// Function Call
System.out.println("First Missing element is : "
+ small.findSmallestMissinginSortedArray(arr));
}
}
Python3
# Python3 program for above approach
# Function to find Smallest
# Missing in Sorted Array
def findSmallestMissinginSortedArray(arr):
# Check if 0 is missing
# in the array
if (arr[0] != 0):
return 0
# Check is all numbers 0 to n - 1
# are present in array
if (arr[-1] == len(arr) - 1):
return len(arr)
first = arr[0]
return findFirstMissing(arr, 0,
len(arr) - 1, first)
# Function to find missing element
def findFirstMissing(arr, start, end, first):
if (start < end):
mid = int((start + end) / 2)
# Index matches with value
# at that index, means missing
# element cannot be upto that point
if (arr[mid] != mid + first):
return findFirstMissing(arr, start,
mid, first)
else:
return findFirstMissing(arr, mid + 1,
end, first)
return start + first
# Driver code
arr = [ 0, 1, 2, 3, 4, 5, 7 ]
n = len(arr)
# Function Call
print("First Missing element is :",
findSmallestMissinginSortedArray(arr))
# This code is contributed by rag2127
C#
// C# program for above approach
using System;
class GFG{
// Program to find Smallest
// Missing in Sorted Array
int findSmallestMissinginSortedArray(int[] arr)
{
// Check if 0 is missing
// in the array
if (arr[0] != 0)
return 0;
// Check is all numbers 0 to n - 1
// are present in array
if (arr[arr.Length - 1] == arr.Length - 1)
return arr.Length;
int first = arr[0];
return findFirstMissing(arr, 0,
arr.Length - 1,first);
}
// Program to find missing element
int findFirstMissing(int[] arr , int start ,
int end, int first)
{
if (start < end)
{
int mid = (start + end) / 2;
/*Index matches with value
at that index, means missing
element cannot be upto that point */
if (arr[mid] != mid+first)
return findFirstMissing(arr, start,
mid, first);
else
return findFirstMissing(arr, mid + 1,
end, first);
}
return start + first;
}
// Driver code
static public void Main ()
{
GFG small = new GFG();
int[] arr = {0, 1, 2, 3, 4, 5, 7};
int n = arr.Length;
// Function Call
Console.WriteLine("First Missing element is : " +
small.findSmallestMissinginSortedArray(arr));
}
}
// This code is contributed by avanitrachhadiya2155
JavaScript
<script>
// Javascript program for the above approach
// Program to find missing element
function findFirstMissing(arr, start, end, first)
{
if (start < end)
{
let mid = (start + end) / 2;
/** Index matches with value
at that index, means missing
element cannot be upto that po*/
if (arr[mid] != mid + first)
return findFirstMissing(arr, start,
mid, first);
else
return findFirstMissing(arr, mid + 1,
end, first);
}
return start + first;
}
// Program to find Smallest
// Missing in Sorted Array
function findSmallestMissinginSortedArray(arr)
{
// Check if 0 is missing
// in the array
if (arr[0] != 0)
return 0;
// Check is all numbers 0 to n - 1
// are present in array
if (arr[arr.length - 1] == arr.length - 1)
return arr.length;
let first = arr[0];
return findFirstMissing(
arr, 0, arr.length - 1, first);
}
// Driver code
let arr = [ 0, 1, 2, 3, 4, 5, 7 ];
let n = arr.length;
// Function Call
document.write("First Missing element is : " +
findSmallestMissinginSortedArray(arr));
// This code is contributed by Mayank Tyagi
</script>
OutputFirst Missing element is : 6
Time Complexity: O(Log n)
Auxiliary Space : O(Log n)
Method-4(Using Hash Vector)
Make a vector of size m and initialize that with 0, so that every element of the array can be treated as an index of the vector.
Now traverse the array and mark the value as 1 in vector at a position equal to the element of the array. Now traverse the vector and find the first index where we get a value of 0, then that index is the smallest missing number.
Code-
C++
// C++ program to find the smallest element
// missing in a sorted array.
#include<bits/stdc++.h>
using namespace std;
int findFirstMissing(int arr[],int n ,int m)
{
vector<int> vec(m,0);
for(int i=0;i<n;i++){
vec[arr[i]]=1;
}
for(int i=0;i<m;i++){
if(vec[i]==0){return i;}
}
}
// Driver code
int main()
{
int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 10};
int n = sizeof(arr)/sizeof(arr[0]);
int m=11;
cout << "Smallest missing element is " <<findFirstMissing(arr, n, m) << endl;
}
Java
// Java program to find the smallest element
// missing in a sorted array.
import java.util.*;
class Main {
static int findFirstMissing(int arr[], int n, int m) {
int vec[] = new int[m];
for (int i = 0; i < n; i++) {
vec[arr[i]] = 1;
}
for (int i = 0; i < m; i++) {
if (vec[i] == 0) {
return i;
}
}
return m;
}
// Driver code
public static void main(String[] args) {
int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 10};
int n = arr.length;
int m = 11;
System.out.println("Smallest missing element is " + findFirstMissing(arr, n, m));
}
}
Python3
# Python program to find the smallest element missing in a sorted array.
def findFirstMissing(arr, n, m):
vec = [0] * m
for i in range(n):
vec[arr[i]] = 1
for i in range(m):
if vec[i] == 0:
return i
return m
# Driver code
arr = [0, 1, 2, 3, 4, 5, 6, 7, 10]
n = len(arr)
m = 11
print("Smallest missing element is", findFirstMissing(arr, n, m))
C#
using System;
public class Program
{
// function to find the smallest missing element in a sorted array
public static int FindFirstMissing(int[] arr, int n, int m)
{
// create an auxiliary array of size m with all elements set to 0
int[] vec = new int[m];
// iterate over the input array and set the corresponding element in vec to 1 if it is present in arr
for (int i = 0; i < n; i++)
{
vec[arr[i]] = 1;
}
// iterate over the range 0 to m and return the first index where the corresponding element in vec is 0
for (int i = 0; i < m; i++)
{
if (vec[i] == 0)
{
return i;
}
}
// if all elements in the range are present, return m (the upper bound of the range)
return m;
}
public static void Main()
{
// initialize an example array, compute its length, and set the upper bound of the range of elements
int[] arr = { 0, 1, 2, 3, 4, 5, 6, 7, 10 };
int n = arr.Length;
int m = 11;
// call the FindFirstMissing function and output the result to the console
Console.WriteLine("Smallest missing element is " + FindFirstMissing(arr, n, m));
}
}
JavaScript
// JS program to find the smallest element
// missing in a sorted array.
function findFirstMissing(arr, n, m) {
let vec = new Array(m).fill(0);
for (let i = 0; i < n; i++) {
vec[arr[i]] = 1;
}
for (let i = 0; i < m; i++) {
if (vec[i] === 0) {
return i;
}
}
}
let arr = [0, 1, 2, 3, 4, 5, 6, 7, 10];
let n = arr.length;
let m = 11;
console.log("Smallest missing element is " + findFirstMissing(arr, n, m));
Output-
Smallest missing element is 8
Time Complexity: O(m+n), where n is the size of the array and m is the range of elements in the array
Auxiliary Space : O(m), where n is the size of the array
Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem.
Find the smallest missing number
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem