Find the smallest missing number
Last Updated :
03 Jul, 2023
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.
Similar Reads
Array Data Structure
Complete Guide to ArraysLearn more about Array in DSA Self Paced CoursePractice Problems on ArraysTop Quizzes on Arrays What is Array?An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calcul
3 min read
What is Array?
Array is a linear data structure where all elements are arranged sequentially. It is a collection of elements of same data type stored at contiguous memory locations. For simplicity, we can think of an array as a flight of stairs where on each step is placed a value (let's say one of your friends).
2 min read
Getting Started with Array Data Structure
Array is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
Applications, Advantages and Disadvantages of Array
Array is a linear data structure that is a collection of data elements of same types. Arrays are stored in contiguous memory locations. It is a static data structure with a fixed size.Table of ContentApplications of Array Data Structure:Advantages of Array Data Structure:Disadvantages of Array Data
2 min read
Subarrays, Subsequences, and Subsets in Array
What is a Subarray?A subarray is a contiguous part of array, i.e., Subarray is an array that is inside another array. In general, for an array of size n, there are n*(n+1)/2 non-empty subarrays. For example, Consider the array [1, 2, 3, 4], There are 10 non-empty sub-arrays. The subarrays are: (1),
10 min read
Basic operations in Array
Searching in Array
Searching is one of the most common operations performed in an array. Array searching can be defined as the operation of finding a particular element or a group of elements in the array. There are several searching algorithms. The most commonly used among them are: Linear Search Binary Search Ternar
4 min read
Array Reverse - Complete Tutorial
Given an array arr[], the task is to reverse the array. Reversing an array means rearranging the elements such that the first element becomes the last, the second element becomes second last and so on.Examples: Input: arr[] = {1, 4, 3, 2, 6, 5} Output: {5, 6, 2, 3, 4, 1}Explanation: The first elemen
15+ min read
Rotate an Array by d - Counterclockwise or Left
Given an array of integers arr[] of size n, the task is to rotate the array elements to the left by d positions.Examples:Input: arr[] = {1, 2, 3, 4, 5, 6}, d = 2Output: {3, 4, 5, 6, 1, 2}Explanation: After first left rotation, arr[] becomes {2, 3, 4, 5, 6, 1} and after the second rotation, arr[] bec
15+ min read
Print array after it is right rotated K times
Given an Array of size N and a value K, around which we need to right rotate the array. How do you quickly print the right rotated array?Examples : Input: Array[] = {1, 3, 5, 7, 9}, K = 2.Output: 7 9 1 3 5Explanation:After 1st rotation - {9, 1, 3, 5, 7}After 2nd rotation - {7, 9, 1, 3, 5} Input: Arr
15+ min read
Search, Insert, and Delete in an Unsorted Array | Array Operations
In this post, a program to search, insert, and delete operations in an unsorted array is discussed.Search Operation:In an unsorted array, the search operation can be performed by linear traversal from the first element to the last element. Coding implementation of the search operation:C++// C++ prog
15+ min read
Search, Insert, and Delete in an Sorted Array | Array Operations
How to Search in a Sorted Array?In a sorted array, the search operation can be performed by using binary search.Below is the implementation of the above approach:C++// C++ program to implement binary search in sorted array #include <bits/stdc++.h> using namespace std; int binarySearch(int arr[
15+ min read
Array Sorting - Practice Problems
Sorting an array means arranging the elements of the array in a certain order. Generally sorting in an array is done to arrange the elements in increasing or decreasing order. Problem statement: Given an array of integers arr, the task is to sort the array in ascending order and return it, without u
9 min read
Generating All Subarrays
Given an array arr[], the task is to generate all the possible subarrays of the given array.Examples: Input: arr[] = [1, 2, 3]Output: [ [1], [1, 2], [2], [1, 2, 3], [2, 3], [3] ]Input: arr[] = [1, 2]Output: [ [1], [1, 2], [2] ]Iterative ApproachTo generate a subarray, we need a starting index from t
8 min read
Easy problems on Array
Largest three distinct elements in an array
Given an array arr[], the task is to find the top three largest distinct integers present in the array.Note: If there are less than three distinct elements in the array, then return the available distinct numbers in descending order.Examples :Input: arr[] = [10, 4, 3, 50, 23, 90]Output: [90, 50, 23]
6 min read
Second Largest Element in an Array
Given an array of positive integers arr[] of size n, the task is to find second largest distinct element in the array.Note: If the second largest element does not exist, return -1. Examples:Input: arr[] = [12, 35, 1, 10, 34, 1]Output: 34Explanation: The largest element of the array is 35 and the sec
14 min read
Move all zeros to end of array
Given an array of integers arr[], the task is to move all the zeros to the end of the array while maintaining the relative order of all non-zero elements.Examples: Input: arr[] = [1, 2, 0, 4, 3, 0, 5, 0]Output: arr[] = [1, 2, 4, 3, 5, 0, 0, 0]Explanation: There are three 0s that are moved to the end
15 min read
Rearrange array such that even positioned are greater than odd
Given an array arr[], sort the array according to the following relations: arr[i] >= arr[i - 1], if i is even, â 1 <= i < narr[i] <= arr[i - 1], if i is odd, â 1 <= i < nFind the resultant array.[consider 1-based indexing]Examples: Input: arr[] = [1, 2, 2, 1]Output: [1 2 1 2] Expla
9 min read
Rearrange an array in maximum minimum form using Two Pointer Technique
Given a sorted array of positive integers, rearrange the array alternately i.e first element should be a maximum value, at second position minimum value, at third position second max, at fourth position second min, and so on. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: arr[] = {7, 1, 6, 2
6 min read
Segregate even and odd numbers using Lomutoâs Partition Scheme
Given an array arr[] of integers, segregate even and odd numbers in the array such that all the even numbers should be present first, and then the odd numbers.Examples: Input: arr[] = {7, 2, 9, 4, 6, 1, 3, 8, 5}Output: 2 4 6 8 7 9 1 3 5Input: arr[] = {1, 3, 2, 4, 7, 6, 9, 10}Output: 2 4 6 10 7 1 9 3
6 min read
Reversal algorithm for Array rotation
Given an array arr[] of size N, the task is to rotate the array by d position to the left. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7}, d = 2Output: 3, 4, 5, 6, 7, 1, 2Explanation: If the array is rotated by 1 position to the left, it becomes {2, 3, 4, 5, 6, 7, 1}.When it is rotated further by 1
15 min read
Print left rotation of array in O(n) time and O(1) space
Given an array of size n and multiple values around which we need to left rotate the array. How to quickly print multiple left rotations?Examples : Input : arr[] = {1, 3, 5, 7, 9}k1 = 1k2 = 3k3 = 4k4 = 6Output : 3 5 7 9 17 9 1 3 59 1 3 5 73 5 7 9 1Input : arr[] = {1, 3, 5, 7, 9}k1 = 14 Output : 9 1
15+ min read
Sort an array which contain 1 to n values
We are given an array that contains 1 to n elements, our task is to sort this array in an efficient way. We are not allowed to simply copy the numbers from 1 to n.Examples : Input : arr[] = {2, 1, 3};Output : {1, 2, 3}Input : arr[] = {2, 1, 4, 3};Output : {1, 2, 3, 4} Native approach - O(n Log n) Ti
7 min read
Count Possible Triangles
Given an unsorted array of positive integers, the task is to find the number of triangles that can be formed with three different array elements as three sides of triangles. For a triangle to be possible from 3 values as sides, the sum of the two values (or sides) must always be greater than the thi
15+ min read
Print all Distinct (Unique) Elements in given Array
Given an integer array arr[], print all distinct elements from this array. The given array may contain duplicates and the output should contain every element only once.Examples: Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45}Output: {12, 10, 9, 45, 2}Input: arr[] = {1, 2, 3, 4, 5}Output: {1, 2, 3, 4,
11 min read
Unique Number I
Given an array of integers, every element in the array appears twice except for one element which appears only once. The task is to identify and return the element that occurs only once.Examples: Input: arr[] = [2, 3, 5, 4, 5, 3, 4]Output: 2 Explanation: Since 2 occurs once, while other numbers occu
8 min read
Leaders in an array
Given an array arr[] of size n, the task is to find all the Leaders in the array. An element is a Leader if it is greater than or equal to all the elements to its right side. Note: The rightmost element is always a leader. Examples: Input: arr[] = [16, 17, 4, 3, 5, 2]Output: [17 5 2]Explanation: 17
10 min read
Subarray with Given Sum
Given a 1-based indexing array arr[] of non-negative integers and an integer sum. You mainly need to return the left and right indexes(1-based indexing) of that subarray. In case of multiple subarrays, return the subarray indexes which come first on moving from left to right. If no such subarray exi
10 min read
Intermediate problems on Array
Rearrange an array such that arr[i] = i
Given an array of elements of length n, ranging from 0 to n - 1. All elements may not be present in the array. If the element is not present then there will be -1 present in the array. Rearrange the array such that arr[i] = i and if i is not present, display -1 at that place.Examples: Input: arr[] =
13 min read
Alternate Rearrangement of Positives and Negatives
An array contains both positive and negative numbers in random order. Rearrange the array elements so that positive and negative numbers are placed alternatively. A number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If t
11 min read
Reorder an array according to given indexes
Given two integer arrays of the same length, arr[] and index[], the task is to reorder the elements in arr[] such that after reordering, each element from arr[i] moves to the position index[i]. The new arrangement reflects the values being placed at their target indices, as described by index[] arra
15+ min read
Find the smallest missing number
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 =
15 min read
Difference Array | Range update query in O(1)
You are given an integer array arr[] and a list of queries. Each query is represented as a list of integers where:[1, l, r, x]: Adds x to all elements from arr[l] to arr[r] (inclusive).[2]: Prints the current state of the array.You need to perform the queries in order.Examples : Input: arr[] = [10,
10 min read
Stock Buy and Sell â Max 2 Transactions Allowed
In the stock market, a person buys a stock and sells it on some future date. Given the stock prices of n days in an array prices[ ]. Find out the maximum profit a person can make in at most 2 transactions. A transaction is equivalent to (buying + selling) of a stock and a new transaction can start o
15+ min read
Smallest subarray with sum greater than a given value
Given an array arr[] of integers and a number x, the task is to find the smallest subarray with a sum strictly greater than x.Examples:Input: x = 51, arr[] = [1, 4, 45, 6, 0, 19]Output: 3Explanation: Minimum length subarray is [4, 45, 6]Input: x = 100, arr[] = [1, 10, 5, 2, 7]Output: 0Explanation: N
15+ min read
Count Inversions of an Array
Given an integer array arr[] of size n, find the inversion count in the array. Two array elements arr[i] and arr[j] form an inversion if arr[i] > arr[j] and i < j.Note: Inversion Count for an array indicates that how far (or close) the array is from being sorted. If the array is already sorted
15+ min read
Merge Two Sorted Arrays Without Extra Space
Given two sorted arrays a[] and b[] of size n and m respectively, the task is to merge both the arrays and rearrange the elements such that the smallest n elements are in a[] and the remaining m elements are in b[]. All elements in a[] and b[] should be in sorted order.Examples: Input: a[] = [2, 4,
15+ min read
Majority Element
You are given an array arr, and your task is to find the majority element an element that occurs more than half the length of the array (i.e., arr.size() / 2). If such an element exists return it, otherwise return -1, indicating that no majority element is present.Examples : Input : arr[] = [1, 1, 2
15+ min read
Two Pointers Technique
Two pointers is really an easy and effective technique that is typically used for Two Sum in Sorted Arrays, Closest Two Sum, Three Sum, Four Sum, Trapping Rain Water and many other popular interview questions. Given a sorted array arr (sorted in ascending order) and a target, find if there exists an
11 min read
3 Sum - Triplet Sum in Array
Given an array arr[] of size n and an integer sum, the task is to check if there is a triplet in the array which sums up to the given target sum.Examples: Input: arr[] = [1, 4, 45, 6, 10, 8], target = 13Output: true Explanation: The triplet [1, 4, 8] sums up to 13Input: arr[] = [1, 2, 4, 3, 6, 7], t
15 min read
Equilibrium Index
Given an array arr[] of size n, the task is to return an equilibrium index (if any) or -1 if no equilibrium index exists. The equilibrium index of an array is an index such that the sum of all elements at lower indexes equals the sum of all elements at higher indexes. Note: When the index is at the
15 min read
Hard problems on Array
MO's Algorithm (Query Square Root Decomposition) | Set 1 (Introduction)
Let us consider the following problem to understand MO's Algorithm. We are given an array and a set of query ranges, we are required to find the sum of every query range.Example: Input: arr[] = {1, 1, 2, 1, 3, 4, 5, 2, 8}; query[] = [0, 4], [1, 3] [2, 4]Output: Sum of arr[] elements in range [0, 4]
15+ min read
Square Root (Sqrt) Decomposition Algorithm
Square Root Decomposition Technique is one of the most common query optimization techniques used by competitive programmers. This technique helps us to reduce Time Complexity by a factor of sqrt(N) The key concept of this technique is to decompose a given array into small chunks specifically of size
15+ min read
Sparse Table
Sparse table concept is used for fast queries on a set of static data (elements do not change). It does preprocessing so that the queries can be answered efficiently.Range Minimum Query Using Sparse TableYou are given an integer array arr of length n and an integer q denoting the number of queries.
15+ min read
Range sum query using Sparse Table
We have an array arr[]. We need to find the sum of all the elements in the range L and R where 0 <= L <= R <= n-1. Consider a situation when there are many range queries. Examples: Input : 3 7 2 5 8 9 query(0, 5) query(3, 5) query(2, 4) Output : 34 22 15Note : array is 0 based indexed and q
8 min read
Range LCM Queries
Given an array arr[] of integers of size N and an array of Q queries, query[], where each query is of type [L, R] denoting the range from index L to index R, the task is to find the LCM of all the numbers of the range for all the queries.Examples: Input: arr[] = {5, 7, 5, 2, 10, 12 ,11, 17, 14, 1, 4
15+ min read
Jump Game - Minimum Jumps to Reach End
Given an array arr[] of non-negative numbers. Each number tells you the maximum number of steps you can jump forward from that position.For example:If arr[i] = 3, you can jump to index i + 1, i + 2, or i + 3 from position i.If arr[i] = 0, you cannot jump forward from that position.Your task is to fi
15+ min read
Space optimization using bit manipulations
There are many situations where we use integer values as index in array to see presence or absence, we can use bit manipulations to optimize space in such problems.Let us consider below problem as an example.Given two numbers say a and b, mark the multiples of 2 and 5 between a and b using less than
12 min read
Maximum value of Sum(i*arr[i]) with array rotations allowed
Given an array arr[], the task is to determine the maximum possible value of the expression i*arr[i] after rotating the array any number of times (including zero).Note: In each rotation, every element of the array shifts one position to the right, and the last element moves to the front.Examples : I
12 min read
Construct an array from its pair-sum array
Given a pair-sum array construct the original array. A pair-sum array for an array is the array that contains sum of all pairs in ordered form, i.e., pair[0] is sum of arr[0] and arr[1], pair[1] is sum of arr[0] and arr[2] and so on. Note that if the size of input array is n, then the size of pair a
5 min read
Maximum equilibrium sum in an array
Given an array arr[]. Find the maximum value of prefix sum which is also suffix sum for index i in arr[].Examples : Input : arr[] = {-1, 2, 3, 0, 3, 2, -1}Output : 4Explanation : Prefix sum of arr[0..3] = Suffix sum of arr[3..6]Input : arr[] = {-3, 5, 3, 1, 2, 6, -4, 2}Output : 7Explanation : Prefix
11 min read
Smallest Difference Triplet from Three arrays
Three arrays of same size are given. Find a triplet such that maximum - minimum in that triplet is minimum of all the triplets. A triplet should be selected in a way such that it should have one number from each of the three given arrays. If there are 2 or more smallest difference triplets, then the
9 min read
Top 50 Array Coding Problems for Interviews
Array is one of the most widely used data structure and is frequently asked in coding interviews to the problem solving skills. The following list of 50 array coding problems covers a range of difficulty levels, from easy to hard, to help candidates prepare for interviews.Easy ProblemsSecond Largest
2 min read