Smallest element present in every subarray of all possible lengths
Last Updated :
23 Jul, 2025
Given an array arr[] of length N, the task for every possible length of subarray is to find the smallest element present in every subarray of that length.
Examples:
Input: N = 10, arr[] = {2, 3, 5, 3, 2, 3, 1, 3, 2, 7}
Output: -1-1 3 2 2 2 1 1 1 1
Explanation:
For length = 1, no element is common in every subarray of length 1. Therefore, output is -1.
For length = 2, no element is common in every subarray of length 2. Therefore, output is -1.
For length = 3, the common element in every subarray is 3. Therefore, the output is 3.
For length = 4, both 2 and 3 are common in every subarray of length 4. 2 being the smaller, is the required output.
Similarly, for lengths 5 and 6, the smallest common element in every subarray of these lengths is 2.
For lengths 7, 8, 9 and 10, the smallest common element in every subarray of these lengths is 1.
Input: N = 3, arr[] = {2, 2, 2}
Output: 2 2 2
Naive Approach: The idea is to find the common elements in all the subarrays of size K for each possible value of K ( 1 ? K ? N) and print the smallest common element. Follow the steps below to solve the problem:
- Add the count of every unique number for every subarray of length K.
- Check if the count of numbers is equal to the number of subarrays i.e., N - K - 1.
- If found to be true, then that particular element has occurred in every subarray of size K.
- For multiple such elements, print the smallest amongst them.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to add count of numbers
// in the map for a subarray of length k
void uniqueElements(int arr[], int start, int K,
map<int, int>& mp)
{
// Set to store unique elements
set<int> st;
// Add elements to the set
for (int i = 0; i < K; i++)
st.insert(arr[start + i]);
// Iterator of the set
set<int>::iterator itr = st.begin();
// Adding count in map
for (; itr != st.end(); itr++)
mp[*itr]++;
}
// Function to check if there is any number
// which repeats itself in every subarray
// of length K
void checkAnswer(map<int, int>& mp, int N, int K)
{
// Check all number starting from 1
for (int i = 1; i <= N; i++) {
// Check if i occurred n-k+1 times
if (mp[i] == (N - K + 1)) {
// Print the smallest number
cout << i << " ";
return;
}
}
// Print -1, if no such number found
cout << -1 << " ";
}
// Function to count frequency of each
// number in each subarray of length K
void smallestPresentNumber(int arr[], int N, int K)
{
map<int, int> mp;
// Traverse all subarrays of length K
for (int i = 0; i <= N - K; i++) {
uniqueElements(arr, i, K, mp);
}
// Check and print the smallest number
// present in every subarray and print it
checkAnswer(mp, N, K);
}
// Function to generate the value of K
void generateK(int arr[], int N)
{
for (int k = 1; k <= N; k++)
// Function call
smallestPresentNumber(arr, N, k);
}
// Driver Code
int main()
{
// Given array
int arr[] = { 2, 3, 5, 3, 2, 3, 1, 3, 2, 7 };
// Size of array
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
generateK(arr, N);
return (0);
}
Java
// Java program for the above approach
import java.util.*;
import java.lang.*;
class GFG
{
// Function to add count of numbers
// in the map for a subarray of length k
static void uniqueElements(int arr[], int start, int K,
Map<Integer,Integer> mp)
{
// Set to store unique elements
Set<Integer> st=new HashSet<>();
// Add elements to the set
for (int i = 0; i < K; i++)
st.add(arr[start + i]);
// Iterator of the set
Iterator itr = st.iterator();
// Adding count in map
while(itr.hasNext())
{
Integer t = (Integer)itr.next();
mp.put(t,mp.getOrDefault(t, 0) + 1);
}
}
// Function to check if there is any number
// which repeats itself in every subarray
// of length K
static void checkAnswer(Map<Integer,Integer> mp, int N, int K)
{
// Check all number starting from 1
for (int i = 1; i <= N; i++)
{
// Check if i occurred n-k+1 times
if(mp.containsKey(i))
if (mp.get(i) == (N - K + 1))
{
// Print the smallest number
System.out.print(i + " ");
return;
}
}
// Print -1, if no such number found
System.out.print(-1 + " ");
}
// Function to count frequency of each
// number in each subarray of length K
static void smallestPresentNumber(int arr[], int N, int K)
{
Map<Integer, Integer> mp = new HashMap<>();
// Traverse all subarrays of length K
for (int i = 0; i <= N - K; i++)
{
uniqueElements(arr, i, K, mp);
}
// Check and print the smallest number
// present in every subarray and print it
checkAnswer(mp, N, K);
}
// Function to generate the value of K
static void generateK(int arr[], int N)
{
for (int k = 1; k <= N; k++)
// Function call
smallestPresentNumber(arr, N, k);
}
// Driver code
public static void main (String[] args)
{
// Given array
int arr[] = { 2, 3, 5, 3, 2, 3, 1, 3, 2, 7 };
// Size of array
int N = arr.length;
// Function call
generateK(arr, N);
}
}
// This code is contributed by offbeat.
Python3
# Python3 program for the above approach
# Function to add count of numbers
# in the map for a subarray of length k
def uniqueElements(arr, start, K, mp) :
# Set to store unique elements
st = set();
# Add elements to the set
for i in range(K) :
st.add(arr[start + i]);
# Adding count in map
for itr in st:
if itr in mp :
mp[itr] += 1;
else:
mp[itr] = 1;
# Function to check if there is any number
# which repeats itself in every subarray
# of length K
def checkAnswer(mp, N, K) :
# Check all number starting from 1
for i in range(1, N + 1) :
if i in mp :
# Check if i occurred n-k+1 times
if (mp[i] == (N - K + 1)) :
# Print the smallest number
print(i, end = " ");
return;
# Print -1, if no such number found
print(-1, end = " ");
# Function to count frequency of each
# number in each subarray of length K
def smallestPresentNumber(arr, N, K) :
mp = {};
# Traverse all subarrays of length K
for i in range(N - K + 1) :
uniqueElements(arr, i, K, mp);
# Check and print the smallest number
# present in every subarray and print it
checkAnswer(mp, N, K);
# Function to generate the value of K
def generateK(arr, N) :
for k in range(1, N + 1) :
# Function call
smallestPresentNumber(arr, N, k);
# Driver Code
if __name__ == "__main__" :
# Given array
arr = [ 2, 3, 5, 3, 2, 3, 1, 3, 2, 7 ];
# Size of array
N = len(arr);
# Function call
generateK(arr, N);
# This code is contributed by AnkThon
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to add count of numbers
// in the map for a subarray of length k
static void uniqueElements(int[] arr, int start,
int K, Dictionary<int, int> mp)
{
// Set to store unique elements
HashSet<int> st = new HashSet<int>();
// Add elements to the set
for (int i = 0; i < K; i++)
st.Add(arr[start + i]);
// Adding count in map
foreach(int itr in st)
{
if(mp.ContainsKey(itr))
{
mp[itr]++;
}
else{
mp[itr] = 1;
}
}
}
// Function to check if there is any number
// which repeats itself in every subarray
// of length K
static void checkAnswer(Dictionary<int, int> mp, int N, int K)
{
// Check all number starting from 1
for (int i = 1; i <= N; i++)
{
// Check if i occurred n-k+1 times
if(mp.ContainsKey(i))
if (mp[i] == (N - K + 1))
{
// Print the smallest number
Console.Write(i + " ");
return;
}
}
// Print -1, if no such number found
Console.Write(-1 + " ");
}
// Function to count frequency of each
// number in each subarray of length K
static void smallestPresentNumber(int[] arr, int N, int K)
{
Dictionary<int, int> mp = new Dictionary<int, int>();
// Traverse all subarrays of length K
for (int i = 0; i <= N - K; i++)
{
uniqueElements(arr, i, K, mp);
}
// Check and print the smallest number
// present in every subarray and print it
checkAnswer(mp, N, K);
}
// Function to generate the value of K
static void generateK(int[] arr, int N)
{
for (int k = 1; k <= N; k++)
// Function call
smallestPresentNumber(arr, N, k);
}
// Driver code
static void Main()
{
// Given array
int[] arr = { 2, 3, 5, 3, 2, 3, 1, 3, 2, 7 };
// Size of array
int N = arr.Length;
// Function call
generateK(arr, N);
}
}
// This code is contributed by divyesh072019.
JavaScript
<script>
// Javascript program for the above approach
// Function to add count of numbers
// in the map for a subarray of length k
function uniqueElements(arr, start, K, mp)
{
// Set to store unique elements
let st = new Set();
// add elements to the set
for (let i = 0; i < K; i++)
st.add(arr[start + i]);
// adding count in map
for(let itr of st)
{
if(mp.has(itr))
{
mp.set(itr, mp.get(itr) + 1);
}
else{
mp.set(itr, 1);
}
}
}
// Function to check if there is any number
// which repeats itself in every subarray
// of length K
function checkAnswer(mp, N, K)
{
// Check all number starting from 1
for (let i = 1; i <= N; i++)
{
// Check if i occurred n-k+1 times
if(mp.has(i))
if (mp.get(i) == (N - K + 1))
{
// Print the smallest number
document.write(i + " ");
return;
}
}
// Print -1, if no such number found
document.write(-1 + " ");
}
// Function to count frequency of each
// number in each subarray of length K
function smallestPresentNumber(arr, N, K)
{
let mp = new Map();
// Traverse all subarrays of length K
for (let i = 0; i <= N - K; i++)
{
uniqueElements(arr, i, K, mp);
}
// Check and print the smallest number
// present in every subarray and print it
checkAnswer(mp, N, K);
}
// Function to generate the value of K
function generateK(arr, N)
{
for (let k = 1; k <= N; k++)
// Function call
smallestPresentNumber(arr, N, k);
}
// Driver code
// Given array
let arr = [ 2, 3, 5, 3, 2, 3, 1, 3, 2, 7 ];
// Size of array
let N = arr.length;
// Function call
generateK(arr, N);
// This code is contributed by gfgking
</script>
Output: -1 -1 3 2 2 2 1 1 1 1
Time Complexity: O(N3)
Auxiliary Space: O(N)
Efficient Approach: The above approach can be optimized if all the indices where the particular number is present in the array are stored using an array and find the minimum length so that it is present in every subarray of length 1 ? K ? N.
Follow the steps below to solve the problem:
- Initialize an array, say indices[], to store the index where a particular number occurs corresponding to that index number.
- Now, for every number which is present in the given array, find the minimum length so that it is present in every subarray of that length.
- Minimum length can be found by finding the maximum interval at which that particular number repeats itself in the given array. Similarly, find the same for other numbers of the array.
- Initialize an answer[] array of size N+1 with -1 where answer[i] represents the answer for subarrays of length K.
- Now, the indices[] array gives the number which was present in every subarray of length, say K, then update answer[K] with the same number if answer[K] was -1.
- After traversing, update answer[] array such that if a number is present in all the subarrays of length K, then that particular number will also be present in all the subarrays of length greater than K.
- After updating answer[] array, print all the elements present in that array as the answer for every subarray of length K.
Below is the implementation of the above approach:
C++
// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to print the common
// elements for all subarray lengths
void printAnswer(int answer[], int N)
{
for (int i = 1; i <= N; i++) {
cout << answer[i] << " ";
}
}
// Function to find and store the
// minimum element present in all
// subarrays of all lengths from 1 to n
void updateAnswerArray(int answer[], int N)
{
int i = 0;
// Skip lengths for which
// answer[i] is -1
while (answer[i] == -1)
i++;
// Initialize minimum as the first
// element where answer[i] is not -1
int minimum = answer[i];
// Updating the answer array
while (i <= N) {
// If answer[i] is -1, then minimum
// can be substituted in that place
if (answer[i] == -1)
answer[i] = minimum;
// Find minimum answer
else
answer[i] = min(minimum, answer[i]);
minimum = min(minimum, answer[i]);
i++;
}
}
// Function to find the minimum number
// corresponding to every subarray of
// length K, for every K from 1 to N
void lengthOfSubarray(vector<int> indices[],
set<int> st, int N)
{
// Stores the minimum common
// elements for all subarray lengths
int answer[N + 1];
// Initialize with -1.
memset(answer, -1, sizeof(answer));
// Find for every element, the minimum length
// such that the number is present in every
// subsequence of that particular length or more
for (auto itr : st) {
// To store first occurrence and
// gaps between occurrences
int start = -1;
int gap = -1;
// To cover the distance between last
// occurrence and the end of the array
indices[itr].push_back(N);
// To find the distance
// between any two occurrences
for (int i = 0; i < indices[itr].size(); i++) {
gap = max(gap, indices[itr][i] - start);
start = indices[itr][i];
}
if (answer[gap] == -1)
answer[gap] = itr;
}
// Update and store the answer
updateAnswerArray(answer, N);
// Print the required answer
printAnswer(answer, N);
}
// Function to find the smallest
// element common in all subarrays for
// every possible subarray lengths
void smallestPresentNumber(int arr[], int N)
{
// Initializing indices array
vector<int> indices[N + 1];
// Store the numbers present
// in the array
set<int> elements;
// Push the index in the indices[A[i]] and
// also store the numbers in set to get
// the numbers present in input array
for (int i = 0; i < N; i++) {
indices[arr[i]].push_back(i);
elements.insert(arr[i]);
}
// Function call to calculate length of
// subarray for which a number is present
// in every subarray of that length
lengthOfSubarray(indices, elements, N);
}
// Driver Code
int main()
{
// Given array
int arr[] = { 2, 3, 5, 3, 2, 3, 1, 3, 2, 7 };
// Size of array
int N = sizeof(arr) / sizeof(arr[0]);
// Function Call
smallestPresentNumber(arr, N);
return (0);
}
Java
// Java program for above approach
import java.util.*;
import java.lang.*;
class GFG
{
// Function to print the common
// elements for all subarray lengths
static void printAnswer(int answer[], int N)
{
for (int i = 1; i <= N; i++)
{
System.out.print(answer[i]+" ");
}
}
// Function to find and store the
// minimum element present in all
// subarrays of all lengths from 1 to n
static void updateAnswerArray(int answer[], int N)
{
int i = 0;
// Skip lengths for which
// answer[i] is -1
while (answer[i] == -1)
i++;
// Initialize minimum as the first
// element where answer[i] is not -1
int minimum = answer[i];
// Updating the answer array
while (i <= N) {
// If answer[i] is -1, then minimum
// can be substituted in that place
if (answer[i] == -1)
answer[i] = minimum;
// Find minimum answer
else
answer[i] = Math.min(minimum, answer[i]);
minimum = Math.min(minimum, answer[i]);
i++;
}
}
// Function to find the minimum number
// corresponding to every subarray of
// length K, for every K from 1 to N
static void lengthOfSubarray(ArrayList<ArrayList<Integer>> indices,
Set<Integer> st, int N)
{
// Stores the minimum common
// elements for all subarray lengths
int[] answer = new int[N + 1];
// Initialize with -1.
Arrays.fill(answer, -1);
// Find for every element, the minimum length
// such that the number is present in every
// subsequence of that particular length or more
Iterator itr = st.iterator();
while (itr.hasNext())
{
// To store first occurrence and
// gaps between occurrences
int start = -1;
int gap = -1;
int t = (int)itr.next();
// To cover the distance between last
// occurrence and the end of the array
indices.get(t).add(N);
// To find the distance
// between any two occurrences
for (int i = 0; i < indices.get(t).size(); i++)
{
gap = Math.max(gap, indices.get(t).get(i) - start);
start = indices.get(t).get(i);
}
if (answer[gap] == -1)
answer[gap] = t;
}
// Update and store the answer
updateAnswerArray(answer, N);
// Print the required answer
printAnswer(answer, N);
}
// Function to find the smallest
// element common in all subarrays for
// every possible subarray lengths
static void smallestPresentNumber(int arr[], int N)
{
// Initializing indices array
ArrayList<ArrayList<Integer>> indices = new ArrayList<>();
for(int i = 0; i <= N; i++)
indices.add(new ArrayList<Integer>());
// Store the numbers present
// in the array
Set<Integer> elements = new HashSet<>();
// Push the index in the indices[A[i]] and
// also store the numbers in set to get
// the numbers present in input array
for (int i = 0; i < N; i++)
{
indices.get(arr[i]).add(i);
elements.add(arr[i]);
}
// Function call to calculate length of
// subarray for which a number is present
// in every subarray of that length
lengthOfSubarray(indices, elements, N);
}
// Driver function
public static void main (String[] args)
{
// Given array
int arr[] = { 2, 3, 5, 3, 2, 3, 1, 3, 2, 7 };
// Size of array
int N = arr.length;
// Function Call
smallestPresentNumber(arr, N);
}
}
// This code is contributed by offbeat
Python3
# Python program of the above approach
# Function to print the common
# elements for all subarray lengths
def printAnswer(answer, N):
for i in range(N + 1):
print(answer[i], end = " ")
# Function to find and store the
# minimum element present in all
# subarrays of all lengths from 1 to n
def updateAnswerArray(answer, N):
i = 0
# Skip lengths for which
# answer[i] is -1
while(answer[i] == -1):
i += 1
# Initialize minimum as the first
# element where answer[i] is not -1
minimum = answer[i]
# Updating the answer array
while(i <= N):
# If answer[i] is -1, then minimum
# can be substituted in that place
if(answer[i] == -1):
answer[i] = minimum
# Find minimum answer
else:
answer[i] = min(minimum, answer[i])
minimum = min(minimum, answer[i])
i += 1
# Function to find the minimum number
# corresponding to every subarray of
# length K, for every K from 1 to N
def lengthOfSubarray(indices, st, N):
# Stores the minimum common
# elements for all subarray lengths
#Initialize with -1.
answer = [-1 for i in range(N + 1)]
# Find for every element, the minimum length
# such that the number is present in every
# subsequence of that particular length or more
for itr in st:
# To store first occurrence and
# gaps between occurrences
start = -1
gap = -1
# To cover the distance between last
# occurrence and the end of the array
indices[itr].append(N)
# To find the distance
# between any two occurrences
for i in range(len(indices[itr])):
gap = max(gap, indices[itr][i] - start)
start = indices[itr][i]
if(answer[gap] == -1):
answer[gap] = itr
# Update and store the answer
updateAnswerArray(answer, N)
# Print the required answer
printAnswer(answer, N)
# Function to find the smallest
# element common in all subarrays for
# every possible subarray lengths
def smallestPresentNumber(arr, N):
# Initializing indices array
indices = [[] for i in range(N + 1)]
# Store the numbers present
# in the array
elements = []
# Push the index in the indices[A[i]] and
# also store the numbers in set to get
# the numbers present in input array
for i in range(N):
indices[arr[i]].append(i)
elements.append(arr[i])
elements = list(set(elements))
# Function call to calculate length of
# subarray for which a number is present
# in every subarray of that length
lengthOfSubarray(indices, elements, N)
# Driver Code
# Given array
arr = [2, 3, 5, 3, 2, 3, 1, 3, 2, 7]
# Size of array
N = len(arr)
# Function Call
smallestPresentNumber(arr, N)
# This code is contributed by avanitrachhadiya2155
C#
// C# program for above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to print the common
// elements for all subarray lengths
static void printAnswer(int[] answer, int N)
{
for(int i = 1; i <= N; i++)
{
Console.Write(answer[i] + " ");
}
}
// Function to find and store the
// minimum element present in all
// subarrays of all lengths from 1 to n
static void updateAnswerArray(int[] answer, int N)
{
int i = 0;
// Skip lengths for which
// answer[i] is -1
while (answer[i] == -1)
i++;
// Initialize minimum as the first
// element where answer[i] is not -1
int minimum = answer[i];
// Updating the answer array
while (i <= N)
{
// If answer[i] is -1, then minimum
// can be substituted in that place
if (answer[i] == -1)
answer[i] = minimum;
// Find minimum answer
else
answer[i] = Math.Min(minimum, answer[i]);
minimum = Math.Min(minimum, answer[i]);
i++;
}
}
// Function to find the minimum number
// corresponding to every subarray of
// length K, for every K from 1 to N
static void lengthOfSubarray(List<List<int>> indices,
HashSet<int> st, int N)
{
// Stores the minimum common
// elements for all subarray lengths
int[] answer = new int[N + 1];
// Initialize with -1.
Array.Fill(answer, -1);
// Find for every element, the minimum length
// such that the number is present in every
// subsequence of that particular length or more
foreach(int itr in st)
{
// To store first occurrence and
// gaps between occurrences
int start = -1;
int gap = -1;
int t = itr;
// To cover the distance between last
// occurrence and the end of the array
indices[t].Add(N);
// To find the distance
// between any two occurrences
for(int i = 0; i < indices[t].Count; i++)
{
gap = Math.Max(gap, indices[t][i] - start);
start = indices[t][i];
}
if (answer[gap] == -1)
answer[gap] = t;
}
// Update and store the answer
updateAnswerArray(answer, N);
// Print the required answer
printAnswer(answer, N);
}
// Function to find the smallest
// element common in all subarrays for
// every possible subarray lengths
static void smallestPresentNumber(int[] arr, int N)
{
// Initializing indices array
List<List<int>> indices = new List<List<int>>();
for(int i = 0; i <= N; i++)
indices.Add(new List<int>());
// Store the numbers present
// in the array
HashSet<int> elements = new HashSet<int>();
// Push the index in the indices[A[i]] and
// also store the numbers in set to get
// the numbers present in input array
for(int i = 0; i < N; i++)
{
indices[arr[i]].Add(i);
elements.Add(arr[i]);
}
// Function call to calculate length of
// subarray for which a number is present
// in every subarray of that length
lengthOfSubarray(indices, elements, N);
}
// Driver code
static void Main()
{
// Given array
int[] arr = { 2, 3, 5, 3, 2, 3, 1, 3, 2, 7 };
// Size of array
int N = arr.Length;
// Function Call
smallestPresentNumber(arr, N);
}
}
// This code is contributed by divyeshrabadiya07
JavaScript
<script>
// Javascript program of the above approach
// Function to print the common
// elements for all subarray lengths
function printAnswer(answer, N)
{
for(let i = 1; i <= N; i++)
{
document.write(answer[i] + " ");
}
}
// Function to find and store the
// minimum element present in all
// subarrays of all lengths from 1 to n
function updateAnswerArray(answer, N)
{
let i = 0;
// Skip lengths for which
// answer[i] is -1
while (answer[i] == -1)
i++;
// Initialize minimum as the first
// element where answer[i] is not -1
let minimum = answer[i];
// Updating the answer array
while (i <= N)
{
// If answer[i] is -1, then minimum
// can be substituted in that place
if (answer[i] == -1)
answer[i] = minimum;
// Find minimum answer
else
answer[i] = Math.min(minimum, answer[i]);
minimum = Math.min(minimum, answer[i]);
i++;
}
}
// Function to find the minimum number
// corresponding to every subarray of
// length K, for every K from 1 to N
function lengthOfSubarray(indices, st, N)
{
// Stores the minimum common
// elements for all subarray lengths
let answer = new Array(N + 1).fill(-1);
// Find for every element, the minimum length
// such that the number is present in every
// subsequence of that particular length or more
for(let itr of st)
{
// To store first occurrence and
// gaps between occurrences
let start = -1;
let gap = -1;
// To cover the distance between last
// occurrence and the end of the array
indices[itr].push(N);
// To find the distance
// between any two occurrences
for(let i = 0; i < indices[itr].length; i++)
{
gap = Math.max(
gap, indices[itr][i] - start);
start = indices[itr][i];
}
if (answer[gap] == -1)
answer[gap] = itr;
}
// Update and store the answer
updateAnswerArray(answer, N);
// Print the required answer
printAnswer(answer, N);
}
// Function to find the smallest
// element common in all subarrays for
// every possible subarray lengths
function smallestPresentNumber(arr, N)
{
// Initializing indices array
let indices = new Array(N + 1).fill(0).map(() => []);
// Store the numbers present
// in the array
let elements = new Set();
// Push the index in the indices[A[i]] and
// also store the numbers in set to get
// the numbers present in input array
for(let i = 0; i < N; i++)
{
indices[arr[i]].push(i);
elements.add(arr[i]);
}
// Function call to calculate length of
// subarray for which a number is present
// in every subarray of that length
lengthOfSubarray(indices, elements, N);
}
// Driver Code
// Given array
let arr = [ 2, 3, 5, 3, 2,
3, 1, 3, 2, 7 ];
// Size of array
let N = arr.length;
// Function Call
smallestPresentNumber(arr, N);
// This code is contributed by gfgking
</script>
Output: -1 -1 3 2 2 2 1 1 1 1
Time Complexity: O(NlogN)
Auxiliary Space: O(N)
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