Square Root (Sqrt) Decomposition Algorithm
Last Updated :
16 Aug, 2023
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 sqrt(N)
Follow the below steps to solve the problem:
- We have an array of n elements and we decompose this array into small chunks of size sqrt(N)
- We will be having exactly sqrt(N) such chunks provided that N is a perfect square
- Therefore, now our array of N elements is decomposed into sqrt(N) blocks, where each block contains sqrt(N) elements (assuming the size of the array is a perfect square)
- Let's consider these chunks or blocks as an individual array each of which contains sqrt(N) elements and you have computed your desired answer(according to your problem) individually for all the chunks
- Now, you need to answer certain queries asking you the answer for the elements in the range l to r(l and r are starting and ending indices of the array) in the original n-sized array
Naive Approach: To solve the problem follow the below idea:
Simply iterate over each element in the range l to r and calculate its corresponding answer. Therefore, the Time Complexity per query will be O(N)
Below is the code for above approach :
C++
// C++ program to demonstrate working of simple
// array query using iteration
#include <bits/stdc++.h>
using namespace std;
#define MAXN 10000
int arr[MAXN]; // original array
// Time Complexity: O(r-l+1)
int query(int l, int r)
{
int sum = 0;
for (int i = l; i <= r; i++) {
sum += arr[i];
}
return sum;
}
// Driver code
int main()
{
// We have used separate array for input because
// the purpose of this code is to explain simple
// array query using iteration in competitive
// programming where we have multiple inputs.
int input[] = { 1, 5, 2, 4, 6, 1, 3, 5, 7, 10 };
int n = sizeof(input) / sizeof(input[0]);
// copying input[] to arr[]
memcpy(arr, input, sizeof(input));
cout << "query(3,8) : " << query(3, 8) << endl;
cout << "query(1,6) : " << query(1, 6) << endl;
arr[8] = 0; // updating arr[8] to 0
cout << "query(8,8) : " << query(8, 8) << endl;
return 0;
}
Java
import java.util.Arrays;
public class GFG{
static int[] arr = new int[10000]; // original array
// Time Complexity: O(r-l+1)
static int query(int l, int r) {
int sum = 0;
for (int i = l; i <= r; i++) {
sum += arr[i];
}
return sum;
}
// Driver code
public static void main(String[] args) {
// We have used separate array for input because
// the purpose of this code is to explain simple
// array query using iteration in competitive
// programming where we have multiple inputs.
int[] input = {1, 5, 2, 4, 6, 1, 3, 5, 7, 10};
int n = input.length;
// copying input[] to arr[]
System.arraycopy(input, 0, arr, 0, n);
System.out.println("query(3,8) : " + query(3, 8));
System.out.println("query(1,6) : " + query(1, 6));
arr[8] = 0; // updating arr[8] to 0
System.out.println("query(8,8) : " + query(8, 8));
}
}
Python3
arr = [0] * 10000 # original array
# Time Complexity: O(r-l+1)
def query(l, r):
_sum = 0
for i in range(l, r + 1):
_sum += arr[i]
return _sum
# Driver code
if __name__ == '__main__':
# We have used separate list for input because
# the purpose of this code is to explain simple
# array query using iteration in competitive
# programming where we have multiple inputs.
input_arr = [1, 5, 2, 4, 6, 1, 3, 5, 7, 10]
# copying input_arr to arr
arr[:len(input_arr)] = input_arr
print("query(3,8) :", query(3, 8))
print("query(1,6) :", query(1, 6))
arr[8] = 0 # updating arr[8] to 0
print("query(8,8) :", query(8, 8))
C#
using System;
class Program
{
const int MAXN = 10000;
static int[] arr = new int[MAXN]; // original array
// Time Complexity: O(r-l+1)
static int Query(int l, int r)
{
int sum = 0;
for (int i = l; i <= r; i++)
{
sum += arr[i];
}
return sum;
}
static void Main()
{
// We have used separate array for input because
// the purpose of this code is to explain simple
// array query using iteration in competitive
// programming where we have multiple inputs.
int[] input = { 1, 5, 2, 4, 6, 1, 3, 5, 7, 10 };
int n = input.Length;
// copying input[] to arr[]
Array.Copy(input, arr, n);
Console.WriteLine("query(3,8) : " + Query(3, 8));
Console.WriteLine("query(1,6) : " + Query(1, 6));
arr[8] = 0; // updating arr[8] to 0
Console.WriteLine("query(8,8) : " + Query(8, 8));
}
}
// This code is contributed by uomkar369
JavaScript
// Function to calculate the sum of elements in the range [l, r] of the array arr
// Time Complexity: O(r - l + 1)
function query(l, r, arr) {
let sum = 0;
for (let i = l; i <= r; i++) {
sum += arr[i];
}
return sum;
}
// Driver code
// We have used a separate array for input because
// the purpose of this code is to explain a simple
// array query using iteration in competitive
// programming where we have multiple inputs.
const input = [1, 5, 2, 4, 6, 1, 3, 5, 7, 10];
const n = input.length;
// copying input[] to arr[]
const arr = [...input];
console.log("query(3,8) :", query(3, 8, arr));
console.log("query(1,6) :", query(1, 6, arr));
arr[8] = 0; // updating arr[8] to 0
console.log("query(8,8) :", query(8, 8, arr));
Outputquery(3,8) : 26
query(1,6) : 21
query(8,8) : 0
Efficient Approach(Sqrt Decomposition Trick): To solve the problem follow the below idea:
As we have already precomputed the answer for all individual chunks and now we need to answer the queries in range l to r. Now we can simply combine the answers of the chunks that lie in between the range l to r in the original array. So, if we see carefully here we are jumping sqrt(N) steps at a time instead of jumping 1 step at a time as done in the naive approach. Let's just analyze its Time Complexity and implementation considering the below problem:
Problem :
Given an array of n elements. We need to answer q
queries telling the sum of elements in range l to
r in the array. Also the array is not static i.e
the values are changed via some point update query.
Range Sum Queries are of form : Q l r ,
where l is the starting index r is the ending index
Point update Query is of form : U idx val,
where idx is the index to update val is the
updated value
Below is the illustration of the above approach:
Let us consider that we have an array of 9 elements: A[] = {1, 5, 2, 4, 6, 1, 3, 5, 7}
1. Let's decompose this array into sqrt(9) blocks, where each block will contain the sum of elements lying in it. Therefore now our decomposed array would look like this:

2. Till now we have constructed the decomposed array of sqrt(9) blocks and now we need to print the sum of elements in a given range.
So first let's see two basic types of overlap that a range query can have on our array:
Range Query of type 1 (Given Range is on Block Boundaries) :

In this type the query, the range may totally cover the continuous sqrt blocks. So we can easily answer the sum of values in this range as the sum of completely overlapped blocks.
So the answer for the above query in the described image will be: ans = 11 + 15 = 26
Time Complexity: O(sqrt(N)). In the worst case, our range can be 0 to N-1(where N is the size of the array and assuming N to be a perfect square). In this case, all the blocks are completely overlapped by our query range. Therefore, to answer this query we need to iterate over all the decomposed blocks for the array and we know that the number of blocks = sqrt(N). Hence, the complexity for this type of query will be O(sqrt(N)) in the worst case.
Range Query of type 2 (Given Range is NOT on boundaries):

We can deal with these types of queries by summing the data from the completely overlapped decomposed blocks lying in the query range and then summing elements one by one from the original array whose corresponding block is not completely overlapped by the query range.
So the answer for the above query in the described image will be: ans = 5 + 2 + 11 + 3 = 21
Time Complexity: O(sqrt(N)). Let's consider a query [l = 1 and r = n-2] (n is the size of the array and has 0-based indexing). Therefore, for this query exactly ( sqrt(n) - 2 ) blocks will be completely overlapped whereas the first and last blocks will be partially overlapped with just one element left outside the overlapping range. So, the completely overlapped blocks can be summed up in ( sqrt(n) - 2 ) ~ sqrt(n) iterations, whereas the first and last blocks are needed to be traversed one by one separately. But as we know that the number of elements in each block is at max sqrt(n), to sum up, the last block individually we need to make,
(sqrt(n)-1) ~ sqrt(n) iterations and same for the last block.
So, the overall Complexity = O(sqrt(n)) + O(sqrt(n)) + O(sqrt(n)) = O(3*sqrt(N)) = O(sqrt(N))
Update Queries(Point update):
In this query, we simply find the block in which the given index lies, then subtract its previous value and add the new updated value as per the point update query.
Time Complexity: O(1)
Below is the implementation of the above approach:
C++
// C++ program to demonstrate working of Square Root
// Decomposition.
#include <bits/stdc++.h>
using namespace std;
#define MAXN 10000
#define SQRSIZE 100
int arr[MAXN]; // original array
int block[SQRSIZE]; // decomposed array
int blk_sz; // block size
// Time Complexity : O(1)
void update(int idx, int val)
{
int blockNumber = idx / blk_sz;
block[blockNumber] += val - arr[idx];
arr[idx] = val;
}
// Time Complexity : O(sqrt(n))
int query(int l, int r)
{
int sum = 0;
while (l < r and l % blk_sz != 0 and l != 0) {
// traversing first block in range
sum += arr[l];
l++;
}
while (l + blk_sz - 1 <= r) {
// traversing completely overlapped blocks in range
sum += block[l / blk_sz];
l += blk_sz;
}
while (l <= r) {
// traversing last block in range
sum += arr[l];
l++;
}
return sum;
}
// Fills values in input[]
void preprocess(int input[], int n)
{
// initiating block pointer
int blk_idx = -1;
// calculating size of block
blk_sz = sqrt(n);
// building the decomposed array
for (int i = 0; i < n; i++) {
arr[i] = input[i];
if (i % blk_sz == 0) {
// entering next block
// incrementing block pointer
blk_idx++;
}
block[blk_idx] += arr[i];
}
}
// Driver code
int main()
{
// We have used separate array for input because
// the purpose of this code is to explain SQRT
// decomposition in competitive programming where
// we have multiple inputs.
int input[] = { 1, 5, 2, 4, 6, 1, 3, 5, 7, 10 };
int n = sizeof(input) / sizeof(input[0]);
preprocess(input, n);
cout << "query(3,8) : " << query(3, 8) << endl;
cout << "query(1,6) : " << query(1, 6) << endl;
update(8, 0);
cout << "query(8,8) : " << query(8, 8) << endl;
return 0;
}
Java
// Java program to demonstrate working of
// Square Root Decomposition.
import java.util.*;
class GFG {
static int MAXN = 10000;
static int SQRSIZE = 100;
static int[] arr = new int[MAXN]; // original array
static int[] block
= new int[SQRSIZE]; // decomposed array
static int blk_sz; // block size
// Time Complexity : O(1)
static void update(int idx, int val)
{
int blockNumber = idx / blk_sz;
block[blockNumber] += val - arr[idx];
arr[idx] = val;
}
// Time Complexity : O(sqrt(n))
static int query(int l, int r)
{
int sum = 0;
while (l < r && l % blk_sz != 0 && l != 0) {
// traversing first block in range
sum += arr[l];
l++;
}
while (l + blk_sz - 1 <= r) {
// traversing completely
// overlapped blocks in range
sum += block[l / blk_sz];
l += blk_sz;
}
while (l <= r) {
// traversing last block in range
sum += arr[l];
l++;
}
return sum;
}
// Fills values in input[]
static void preprocess(int input[], int n)
{
// initiating block pointer
int blk_idx = -1;
// calculating size of block
blk_sz = (int)Math.sqrt(n);
// building the decomposed array
for (int i = 0; i < n; i++) {
arr[i] = input[i];
if (i % blk_sz == 0) {
// entering next block
// incrementing block pointer
blk_idx++;
}
block[blk_idx] += arr[i];
}
}
// Driver code
public static void main(String[] args)
{
// We have used separate array for input because
// the purpose of this code is to explain SQRT
// decomposition in competitive programming where
// we have multiple inputs.
int input[] = { 1, 5, 2, 4, 6, 1, 3, 5, 7, 10 };
int n = input.length;
preprocess(input, n);
System.out.println("query(3, 8) : " + query(3, 8));
System.out.println("query(1, 6) : " + query(1, 6));
update(8, 0);
System.out.println("query(8, 8) : " + query(8, 8));
}
}
// This code is contributed by PrinciRaj1992
Python 3
# Python 3 program to demonstrate working of Square Root
# Decomposition.
from math import sqrt
MAXN = 10000
SQRSIZE = 100
arr = [0]*(MAXN) # original array
block = [0]*(SQRSIZE) # decomposed array
blk_sz = 0 # block size
# Time Complexity : O(1)
def update(idx, val):
blockNumber = idx // blk_sz
block[blockNumber] += val - arr[idx]
arr[idx] = val
# Time Complexity : O(sqrt(n))
def query(l, r):
sum = 0
while (l < r and l % blk_sz != 0 and l != 0):
# traversing first block in range
sum += arr[l]
l += 1
while (l + blk_sz - 1 <= r):
# traversing completely overlapped blocks in range
sum += block[l//blk_sz]
l += blk_sz
while (l <= r):
# traversing last block in range
sum += arr[l]
l += 1
return sum
# Fills values in input[]
def preprocess(input, n):
# initiating block pointer
blk_idx = -1
# calculating size of block
global blk_sz
blk_sz = int(sqrt(n))
# building the decomposed array
for i in range(n):
arr[i] = input[i]
if (i % blk_sz == 0):
# entering next block
# incrementing block pointer
blk_idx += 1
block[blk_idx] += arr[i]
# Driver code
# We have used separate array for input because
# the purpose of this code is to explain SQRT
# decomposition in competitive programming where
# we have multiple inputs.
input = [1, 5, 2, 4, 6, 1, 3, 5, 7, 10]
n = len(input)
preprocess(input, n)
print("query(3,8) : ", query(3, 8))
print("query(1,6) : ", query(1, 6))
update(8, 0)
print("query(8,8) : ", query(8, 8))
# This code is contributed by Sanjit_Prasad
C#
// C# program to demonstrate working of
// Square Root Decomposition.
using System;
class GFG {
static int MAXN = 10000;
static int SQRSIZE = 100;
static int[] arr = new int[MAXN]; // original array
static int[] block
= new int[SQRSIZE]; // decomposed array
static int blk_sz; // block size
// Time Complexity : O(1)
static void update(int idx, int val)
{
int blockNumber = idx / blk_sz;
block[blockNumber] += val - arr[idx];
arr[idx] = val;
}
// Time Complexity : O(sqrt(n))
static int query(int l, int r)
{
int sum = 0;
while (l < r && l % blk_sz != 0 && l != 0) {
// traversing first block in range
sum += arr[l];
l++;
}
while (l + blk_sz - 1 <= r) {
// traversing completely
// overlapped blocks in range
sum += block[l / blk_sz];
l += blk_sz;
}
while (l <= r) {
// traversing last block in range
sum += arr[l];
l++;
}
return sum;
}
// Fills values in input[]
static void preprocess(int[] input, int n)
{
// initiating block pointer
int blk_idx = -1;
// calculating size of block
blk_sz = (int)Math.Sqrt(n);
// building the decomposed array
for (int i = 0; i < n; i++) {
arr[i] = input[i];
if (i % blk_sz == 0) {
// entering next block
// incrementing block pointer
blk_idx++;
}
block[blk_idx] += arr[i];
}
}
// Driver code
public static void Main(String[] args)
{
// We have used separate array for input because
// the purpose of this code is to explain SQRT
// decomposition in competitive programming where
// we have multiple inputs.
int[] input = { 1, 5, 2, 4, 6, 1, 3, 5, 7, 10 };
int n = input.Length;
preprocess(input, n);
Console.WriteLine("query(3, 8) : " + query(3, 8));
Console.WriteLine("query(1, 6) : " + query(1, 6));
update(8, 0);
Console.WriteLine("query(8, 8) : " + query(8, 8));
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// Javascript program to demonstrate working of
// Square Root Decomposition.
let MAXN = 10000;
let SQRSIZE = 100;
let arr = new Array(MAXN);
for(let i = 0; i < MAXN; i++)
{
arr[i] = 0;
}
let block = new Array(SQRSIZE);
for(let i = 0; i < SQRSIZE; i++)
{
block[i] = 0;
}
let blk_sz;
// Time Complexity : O(1)
function update(idx,val)
{
let blockNumber = idx / blk_sz;
block[blockNumber] += val - arr[idx];
arr[idx] = val;
}
// Time Complexity : O(sqrt(n))
function query(l, r)
{
let sum = 0;
while (l < r && l % blk_sz != 0 && l != 0)
{
// traversing first block in range
sum += arr[l];
l++;
}
while (l+blk_sz-1 <= r)
{
// traversing completely
// overlapped blocks in range
sum += block[l / blk_sz];
l += blk_sz;
}
while (l <= r)
{
// traversing last block in range
sum += arr[l];
l++;
}
return sum;
}
// Fills values in input[]
function preprocess(input, n)
{
// initiating block pointer
let blk_idx = -1;
// calculating size of block
blk_sz = Math.floor( Math.sqrt(n));
// building the decomposed array
for (let i = 0; i < n; i++)
{
arr[i] = input[i];
if (i % blk_sz == 0)
{
// entering next block
// incrementing block pointer
blk_idx++;
}
block[blk_idx] += arr[i];
}
}
// Driver code
// We have used separate array for input because
// the purpose of this code is to explain SQRT
// decomposition in competitive programming where
// we have multiple inputs.
let input = [1, 5, 2, 4, 6, 1, 3, 5, 7, 10];
let n = input.length;
preprocess(input, n);
document.write("query(3, 8) : " +
query(3, 8)+"<br>");
document.write("query(1, 6) : " +
query(1, 6)+"<br>");
update(8, 0);
document.write("query(8, 8) : " +
query(8, 8)+"<br>");
// This code is contributed by rag2127
</script>
Outputquery(3,8) : 26
query(1,6) : 21
query(8,8) : 0
Time Complexity: O(N)
Auxiliary Space: O(MAXN), since MAXN extra space has been taken, where MAXN is the maximum value of N
Note: The above code works even if N is not a perfect square. In this case, the last block will contain even less number of elements than sqrt(N), thus reducing the number of iterations.
Let's say n = 10. In this case, we will have 4 blocks first three blocks of size 3, and the last block of size 1.
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