Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • GfG 160: Daily DSA
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Sort a nearly sorted (or K sorted) array
Next article icon

Count of smaller elements on right side of each element in an Array using Merge sort

Last Updated : 06 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of N integers, the task is to count the number of smaller elements on the right side for each of the element in the array

Examples: 

Input: arr[] = {6, 3, 7, 2} 
Output: 2, 1, 1, 0 
Explanation: 
Smaller elements after 6 = 2 [3, 2] 
Smaller elements after 3 = 1 [2] 
Smaller elements after 7 = 1 [2] 
Smaller elements after 2 = 0 

Input: arr[] = {6, 19, 111, 13} 
Output: 0, 1, 1, 0 
Explanation: 
Smaller elements after 6 = 0 
Smaller elements after 19 = 1 [13] 
Smaller elements after 111 = 1 [13] 
Smaller elements after 13 = 0 

Approach: 
Use the idea of the merge sort at the time of merging two arrays. When higher index element is less than the lower index element, it represents that the higher index element is smaller than all the elements after that lower index because the left part is already sorted. Hence add up to all the elements after the lower index element for the required count. 

Below is the implementation of the above approach 

C++
// C++ program to find the count of
// smaller elements on right side of
// each element in an Array 
// using Merge sort
#include 
using namespace std;

const int N = 100001;
int ans[N];

// Utility function that merge the array 
// and count smaller element on right side 
void merge(pair<int, int> a[], int start,
                int mid, int end)
{
    pair<int, int> f[mid - start + 1],
                   s[end - mid];
                   
    int n = mid - start + 1;
    int m = end - mid;
    
    for(int i = start; i <= mid; i++)
        f[i - start] = a[i];
    for(int i = mid + 1; i <= end; i++)
        s[i - mid - 1] = a[i];
        
    int i = 0, j = 0, k = start;
    int cnt = 0;

    // Loop to store the count of smaller 
    // Elements on right side when both 
    // Array have some elements 
    while(i < n && j < m)
    {
        if (f[i].second <= s[j].second)
        {
            ans[f[i].first] += cnt;
            a[k++] = f[i++];
        }
        else
        {
            cnt++;
            a[k++] = s[j++];
        }
    }

    // Loop to store the count of smaller 
    // elements in right side when only 
    // left array have some element 
    while(i < n)
    {
        ans[f[i].first] += cnt;
        a[k++] = f[i++];
    }

    // Loop to store the count of smaller 
    // elements in right side when only 
    // right array have some element 
    while(j < m)
    {
        a[k++] = s[j++];
    }
}

// Function to invoke merge sort.
void mergesort(pair<int, int> item[],
                    int low, int high)
{
    if (low >= high)
        return;
        
    int mid = (low + high) / 2;
    mergesort(item, low, mid);
    mergesort(item, mid + 1, high);
    merge(item, low, mid, high);
}

// Utility function that prints 
// out an array on a line 
void print(int arr[], int n)
{
    for(int i = 0; i < n; i++)
        cout << arr[i] << " ";
}

// Driver code.
int main() 
{
    int arr[] = { 10, 9, 5, 2, 7,
                   6, 11, 0, 2 };
                   
    int n = sizeof(arr) / sizeof(int);
    pair<int, int> a[n];
    memset(ans, 0, sizeof(ans));
    
    for(int i = 0; i < n; i++)
    {
        a[i].second = arr[i];
        a[i].first = i;
    }
    
    mergesort(a, 0, n - 1);
    print(ans, n);
    
    return 0; 
}

// This code is contributed by rishabhtyagi2306
Java
// Java program to find the count of smaller elements
// on right side of each element in an Array
// using Merge sort

import java.util.*;

public class GFG {

    // Class for storing the index
    // and Value pairs
    class Item {

        int val;
        int index;

        public Item(int val, int index)
        {
            this.val = val;
            this.index = index;
        }
    }

    // Function to count the number of
    // smaller elements on right side
    public ArrayList<Integer> countSmall(int[] A)
    {

        int len = A.length;
        Item[] items = new Item[len];

        for (int i = 0; i < len; i++) {
            items[i] = new Item(A[i], i);
        }

        int[] count = new int[len];
        mergeSort(items, 0, len - 1, count);
        ArrayList<Integer> res = new ArrayList<>();

        for (int i : count) {
            res.add(i);
        }
        return res;
    }

    // Function for Merge Sort
    private void mergeSort(Item[] items,
                           int low, int high,
                           int[] count)
    {

        if (low >= high) {
            return;
        }

        int mid = low + (high - low) / 2;
        mergeSort(items, low, mid, count);
        mergeSort(items, mid + 1, high, count);
        merge(items, low, mid, mid + 1, high, count);
    }

    // Utility function that merge the array
    // and count smaller element on right side
    private void merge(Item[] items, int low,
                       int lowEnd, int high,
                       int highEnd, int[] count)
    {
        int m = highEnd - low + 1;
        Item[] sorted = new Item[m];
        int rightCounter = 0;
        int lowPtr = low, highPtr = high;
        int index = 0;

        // Loop to store the count of smaller
        // Elements on right side when both
        // Array have some elements
        while (lowPtr <= lowEnd && highPtr <= highEnd) {
            if (items[lowPtr].val > items[highPtr].val) {
                rightCounter++;
                sorted[index++] = items[highPtr++];
            }
            else {
                count[items[lowPtr].index] += rightCounter;
                sorted[index++] = items[lowPtr++];
            }
        }

        // Loop to store the count of smaller
        // elements in right side when only
        // left array have some element
        while (lowPtr <= lowEnd) {
            count[items[lowPtr].index] += rightCounter;
            sorted[index++] = items[lowPtr++];
        }

        // Loop to store the count of smaller
        // elements in right side when only
        // right array have some element
        while (highPtr <= highEnd) {
            sorted[index++] = items[highPtr++];
        }

        System.arraycopy(sorted, 0, items, low, m);
    }

    // Utility function that prints
    // out an array on a line
    void printArray(ArrayList<Integer> countList)
    {

        for (Integer i : countList)
            System.out.print(i + " ");

        System.out.println("");
    }

    // Driver Code
    public static void main(String[] args)
    {
        GFG cntSmall = new GFG();
        int arr[] = { 10, 9, 5, 2, 7, 6, 11, 0, 2 };
        int n = arr.length;
        ArrayList<Integer> countList
            = cntSmall.countSmall(arr);
        cntSmall.printArray(countList);
    }
}
Python3
# Python3 program to find the count of
# smaller elements on right side of
# each element in an Array 
# using Merge sort
N = 100001
ans = [0] * N

# Utility function that merge the array 
# and count smaller element on right side 
def merge(a, start, mid, end):

    f = [0] * (mid - start + 1)
    s = [0] * (end - mid)
                   
    n = mid - start + 1
    m = end - mid
    
    for i in range(start, mid + 1):
        f[i - start] = a[i]
    for i in range ( mid + 1, end + 1):
        s[i - mid - 1] = a[i]
        
    i = 0
    j = 0
    k = start
    cnt = 0

    # Loop to store the count of smaller 
    # Elements on right side when both 
    # Array have some elements 
    while (i < n and j < m):
        if (f[i][1] <= s[j][1]):
            ans[f[i][0]] += cnt
            a[k] = f[i]
            k += 1
            i += 1
            
        else:
            cnt += 1
            a[k] = s[j]
            k += 1
            j += 1
      
    # Loop to store the count of smaller 
    # elements in right side when only 
    # left array have some element 
    while (i < n):
        ans[f[i][0]] += cnt
        a[k] = f[i];
        k += 1
        i += 1
    
    # Loop to store the count of smaller 
    # elements in right side when only 
    # right array have some element 
    while (j < m):
        a[k] = s[j]
        k += 1
        j += 1
      
# Function to invoke merge sort.
def mergesort(item, low, high):

    if (low >= high):
        return
        
    mid = (low + high) // 2
    mergesort(item, low, mid)
    mergesort(item, mid + 1, high)
    merge(item, low, mid, high)

# Utility function that prints 
# out an array on a line 
def print_(arr, n):

    for i in range(n):
        print(arr[i], end = " ")

# Driver code.
if __name__ == "__main__":
  
    arr = [ 10, 9, 5, 2, 7,
            6, 11, 0, 2 ]
                   
    n = len(arr)
    a = [[0 for x in range(2)]
            for y in range(n)]
    
    for i in range(n):
        a[i][1] = arr[i]
        a[i][0] = i
   
    mergesort(a, 0, n - 1)
    print_(ans, n)
    
# This code is contributed by chitranayal
C#
// C# program to find the count of smaller elements
// on right side of each element in an Array
// using Merge sort
using System;
using System.Collections.Generic;

class GFG
{

    // Class for storing the index
    // and Value pairs
    public class Item 
    {

        public int val;
        public int index;

        public Item(int val, int index)
        {
            this.val = val;
            this.index = index;
        }
    }

    // Function to count the number of
    // smaller elements on right side
    public List<int> countSmall(int[] A)
    {

        int len = A.Length;
        Item[] items = new Item[len];

        for (int i = 0; i < len; i++) 
        {
            items[i] = new Item(A[i], i);
        }

        int[] count = new int[len];
        mergeSort(items, 0, len - 1, count);
        List<int> res = new List<int>();

        foreach (int i in count) 
        {
            res.Add(i);
        }
        return res;
    }

    // Function for Merge Sort
    private void mergeSort(Item[] items,
                        int low, int high,
                        int[] count)
    {

        if (low >= high) 
        {
            return;
        }

        int mid = low + (high - low) / 2;
        mergeSort(items, low, mid, count);
        mergeSort(items, mid + 1, high, count);
        merge(items, low, mid, mid + 1, high, count);
    }

    // Utility function that merge the array
    // and count smaller element on right side
    private void merge(Item[] items, int low,
                    int lowEnd, int high,
                    int highEnd, int[] count)
    {
        int m = highEnd - low + 1;
        Item[] sorted = new Item[m];
        int rightCounter = 0;
        int lowPtr = low, highPtr = high;
        int index = 0;

        // Loop to store the count of smaller
        // Elements on right side when both
        // Array have some elements
        while (lowPtr <= lowEnd && highPtr <= highEnd)
        {
            if (items[lowPtr].val > items[highPtr].val) 
            {
                rightCounter++;
                sorted[index++] = items[highPtr++];
            }
            else
            {
                count[items[lowPtr].index] += rightCounter;
                sorted[index++] = items[lowPtr++];
            }
        }

        // Loop to store the count of smaller
        // elements in right side when only
        // left array have some element
        while (lowPtr <= lowEnd) 
        {
            count[items[lowPtr].index] += rightCounter;
            sorted[index++] = items[lowPtr++];
        }

        // Loop to store the count of smaller
        // elements in right side when only
        // right array have some element
        while (highPtr <= highEnd)
        {
            sorted[index++] = items[highPtr++];
        }

        Array.Copy(sorted, 0, items, low, m);
    }

    // Utility function that prints
    // out an array on a line
    void printArray(List<int> countList)
    {

        foreach (int i in countList)
            Console.Write(i + " ");

        Console.WriteLine("");
    }

    // Driver Code
    public static void Main(String[] args)
    {
        GFG cntSmall = new GFG();
        int []arr = { 10, 9, 5, 2, 7, 6, 11, 0, 2 };
        int n = arr.Length;
        List<int> countList
            = cntSmall.countSmall(arr);
        cntSmall.printArray(countList);
    }
}

// This code is contributed by 29AjayKumar
JavaScript
<script>

// Javascript program to find the count of 
// smaller elements on right side of each
// element in an Array using Merge sort
let N = 100001;
let ans = new Array(N);

// Utility function that merge the array
// and count smaller element on right side
function merge(a, start, mid, end)
{
    let f = new Array((mid - start + 1));
    let s = new Array(end - mid);
    let n = mid - start + 1;
    let m = end - mid;
    
    for(let i = start; i <= mid; i++)
        f[i - start] = a[i];
    for(let i = mid + 1; i <= end; i++)
        s[i - mid - 1] = a[i];
    
    let i = 0, j = 0, k = start;
    let cnt = 0;
    
    // Loop to store the count of smaller
    // Elements on right side when both
    // Array have some elements
    while(i < n && j < m)
    {
        if (f[i][1] <= s[j][1])
        {
            ans[f[i][0]] += cnt;
            a[k++] = f[i++];
        }
        else
        {
            cnt++;
            a[k++] = s[j++];
        }
    }
    
    // Loop to store the count of smaller
    // elements in right side when only
    // left array have some element
    while(i < n)
    {
        ans[f[i][0]] += cnt;
        a[k++] = f[i++];
    }
    
    // Loop to store the count of smaller
    // elements in right side when only
    // right array have some element
    while(j < m)
    {
        a[k++] = s[j++];
    }       
}

// Function to invoke merge sort.
function mergesort(item, low, high)
{
    if (low >= high)
        return;
    
    let mid = Math.floor((low + high) / 2);
    mergesort(item, low, mid);
    mergesort(item, mid + 1, high);
    merge(item, low, mid, high);
}
    
// Utility function that prints
// out an array on a line
function print(arr, n)
{
    for(let i = 0; i < n; i++)
        document.write(arr[i] + " ");
}

// Driver Code
let arr = [ 10, 9, 5, 2, 7, 6, 11, 0, 2 ];
let n = arr.length;
let a = new Array(n);
for(let i = 0; i < a.length; i++)
{
    a[i] = new Array(2);
}
for(let i = 0; i < ans.length; i++)
{
    ans[i] = 0;
}

for(let i = 0; i < n; i++)
{
    a[i][1] = arr[i];
    a[i][0] = i;
}
mergesort(a, 0, n - 1);
print(ans, n);

// This code is contributed by rag2127

</script>

Output
7 6 3 1 3 2 2 0 0

Time Complexity: O(n log n)
The time complexity for the Merge Sort algorithm is O(nlog n). This is because the merge sort algorithm first divides the array in two halves and then recursively sorts each half. This process continues until the array is completely sorted.

Space Complexity: O(n)
The space complexity for the Merge Sort algorithm is O(n). This is because the Merge Sort algorithm uses an auxiliary array in which it stores the elements of the original array while the sorting process is taking place.
Related Article: Count smaller elements on right side
 


Next Article
Sort a nearly sorted (or K sorted) array

G

gs_2020
Improve
Article Tags :
  • Divide and Conquer
  • Sorting
  • DSA
  • Arrays
Practice Tags :
  • Arrays
  • Divide and Conquer
  • Sorting

Similar Reads

    Merge Sort - Data Structure and Algorithms Tutorials
    Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
    14 min read

    Merge sort in different languages

    C Program for Merge Sort
    Merge Sort is a comparison-based sorting algorithm that works by dividing the input array into two halves, then calling itself for these two halves, and finally it merges the two sorted halves. In this article, we will learn how to implement merge sort in C language.What is Merge Sort Algorithm?Merg
    3 min read
    C++ Program For Merge Sort
    Merge Sort is a comparison-based sorting algorithm that uses divide and conquer paradigm to sort the given dataset. It divides the dataset into two halves, calls itself for these two halves, and then it merges the two sorted halves.In this article, we will learn how to implement merge sort in a C++
    4 min read
    Java Program for Merge Sort
    Merge Sort is a divide-and-conquer algorithm. It divides the input array into two halves, calls itself the two halves, and then merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is a key process that assumes that arr[l..m] and arr[m+1..r] are
    3 min read
    Merge Sort in Python
    Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r] are sorte
    4 min read
    Merge Sort using Multi-threading
    Merge Sort is a popular sorting technique which divides an array or list into two halves and then start merging them when sufficient depth is reached. Time complexity of merge sort is O(nlogn).Threads are lightweight processes and threads shares with other threads their code section, data section an
    14 min read

    Variations of Merge Sort

    3-way Merge Sort
    Merge Sort is a divide-and-conquer algorithm that recursively splits an array into two halves, sorts each half, and then merges them. A variation of this is 3-way Merge Sort, where instead of splitting the array into two parts, we divide it into three equal parts. In traditional Merge Sort, the arra
    13 min read
    Iterative Merge Sort
    Given an array of size n, the task is to sort the given array using iterative merge sort.Examples:Input: arr[] = [4, 1, 3, 9, 7]Output: [1, 3, 4, 7, 9]Explanation: The output array is sorted.Input: arr[] = [1, 3 , 2]Output: [1, 2, 3]Explanation: The output array is sorted.You can refer to Merge Sort
    9 min read
    In-Place Merge Sort
    Implement Merge Sort i.e. standard implementation keeping the sorting algorithm as in-place. In-place means it does not occupy extra memory for merge operation as in the standard case. Examples: Input: arr[] = {2, 3, 4, 1} Output: 1 2 3 4 Input: arr[] = {56, 2, 45} Output: 2 45 56 Approach 1: Mainta
    15+ min read
    In-Place Merge Sort | Set 2
    Given an array A[] of size N, the task is to sort the array in increasing order using In-Place Merge Sort. Examples: Input: A = {5, 6, 3, 2, 1, 6, 7}Output: {1, 2, 3, 5, 6, 6, 7} Input: A = {2, 3, 4, 1}Output: {1, 2, 3, 4} Approach: The idea is to use the inplace_merge() function to merge the sorted
    7 min read
    Merge Sort with O(1) extra space merge and O(n log n) time [Unsigned Integers Only]
    We have discussed Merge sort. How to modify the algorithm so that merge works in O(1) extra space and algorithm still works in O(n Log n) time. We may assume that the input values are integers only. Examples: Input : 5 4 3 2 1 Output : 1 2 3 4 5 Input : 999 612 589 856 56 945 243 Output : 56 243 589
    10 min read

    Merge Sort in Linked List

    Merge Sort for Linked Lists
    Given a singly linked list, The task is to sort the linked list in non-decreasing order using merge sort.Examples: Input: 40 -> 20 -> 60 -> 10 -> 50 -> 30 -> NULLOutput: 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> NULLInput: 9 -> 5 -> 2 -> 8 -> NULLOutput: 2 -
    12 min read
    Merge Sort for Doubly Linked List
    Given a doubly linked list, The task is to sort the doubly linked list in non-decreasing order using merge sort.Examples:Input: 10 <-> 8 <-> 4 <-> 2Output: 2 <-> 4 <-> 8 <-> 10Input: 5 <-> 3 <-> 2Output: 2 <-> 3 <-> 5 Note: Merge sort for a
    13 min read
    Iterative Merge Sort for Linked List
    Given a singly linked list of integers, the task is to sort it using iterative merge sort.Examples:Input: 40 -> 20 -> 60 -> 10 -> 50 -> 30 -> NULLOutput: 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> NULLInput: 9 -> 5 -> 2 -> 8 -> NULLOutput: 2 -> 5 -> 8 -
    13 min read
    Merge two sorted lists (in-place)
    Given two sorted linked lists consisting of n and m nodes respectively. The task is to merge both of the lists and return the head of the merged list.Example:Input: Output: Input: Output: Approach:The idea is to iteratively merge two sorted linked lists using a dummy node to simplify the process. A
    9 min read
    Merge K sorted Doubly Linked List in Sorted Order
    Given K sorted doubly linked list. The task is to merge all sorted doubly linked list in single sorted doubly linked list means final list must be sorted.Examples: Input: List 1 : 2 <-> 7 <-> 8 <-> 12 <-> 15 <-> NULL List 2 : 4 <-> 9 <-> 10 <-> NULL Li
    15+ min read
    Merge a linked list into another linked list at alternate positions
    Given two singly linked lists, The task is to insert nodes of the second list into the first list at alternate positions of the first list and leave the remaining nodes of the second list if it is longer.Example:Input: head1: 1->2->3 , head2: 4->5->6->7->8Output: head1: 1->4-
    8 min read
    Find a permutation that causes worst case of Merge Sort
    Given a set of elements, find which permutation of these elements would result in worst case of Merge Sort.Asymptotically, merge sort always takes O(n Log n) time, but the cases that require more comparisons generally take more time in practice. We basically need to find a permutation of input eleme
    12 min read
    How to make Mergesort to perform O(n) comparisons in best case?
    As we know, Mergesort is a divide and conquer algorithm that splits the array to halves recursively until it reaches an array of the size of 1, and after that it merges sorted subarrays until the original array is fully sorted. Typical implementation of merge sort works in O(n Log n) time in all thr
    3 min read
    Concurrent Merge Sort in Shared Memory
    Given a number 'n' and a n numbers, sort the numbers using Concurrent Merge Sort. (Hint: Try to use shmget, shmat system calls).Part1: The algorithm (HOW?) Recursively make two child processes, one for the left half, one of the right half. If the number of elements in the array for a process is less
    10 min read

    Visualization of Merge Sort

    Sorting Algorithm Visualization : Merge Sort
    The human brain can easily process visuals instead of long codes to understand the algorithms. In this article, a program that program visualizes the Merge sort Algorithm has been implemented. The GUI(Graphical User Interface) is implemented using pygame package in python. Approach: An array of rand
    3 min read
    Merge Sort Visualization in JavaScript
    GUI(Graphical User Interface) helps users with better understanding programs. In this article, we will visualize Merge Sort using JavaScript. We will see how the arrays are divided and merged after sorting to get the final sorted array.  Refer: Merge SortCanvas in HTMLAsynchronous Function in JavaSc
    4 min read
    Visualize Merge sort Using Tkinter in Python
    Prerequisites: Python GUI – tkinter In this article, we will create a GUI application that will help us to visualize the algorithm of merge sort using Tkinter in Python. Merge Sort is a popular sorting algorithm. It has a time complexity of N(logN) which is faster than other sorting algorithms like
    5 min read
    Visualization of Merge sort using Matplotlib
    Prerequisites: Introduction to Matplotlib, Merge Sort Visualizing algorithms makes it easier to understand them by analyzing and comparing the number of operations that took place to compare and swap the elements. For this we will use matplotlib, to plot bar graphs to represent the elements of the a
    3 min read
    3D Visualisation of Merge Sort using Matplotlib
    Visualizing algorithms makes it easier to understand them by analyzing and comparing the number of operations that took place to compare and swap the elements. 3D visualization of algorithms is less common, for this we will use matplotlib to plot bar graphs and animate them to represent the elements
    3 min read

    Some problems on Merge Sort

    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
    Count of smaller elements on right side of each element in an Array using Merge sort
    Given an array arr[] of N integers, the task is to count the number of smaller elements on the right side for each of the element in the array Examples: Input: arr[] = {6, 3, 7, 2} Output: 2, 1, 1, 0 Explanation: Smaller elements after 6 = 2 [3, 2] Smaller elements after 3 = 1 [2] Smaller elements a
    12 min read
    Sort a nearly sorted (or K sorted) array
    Given an array arr[] and a number k . The array is sorted in a way that every element is at max k distance away from it sorted position. It means if we completely sort the array, then the index of the element can go from i - k to i + k where i is index in the given array. Our task is to completely s
    6 min read
    Median of two Sorted Arrays of Different Sizes
    Given two sorted arrays, a[] and b[], the task is to find the median of these sorted arrays. Assume that the two sorted arrays are merged and then median is selected from the combined array.This is an extension of Median of two sorted arrays of equal size problem. Here we handle arrays of unequal si
    15+ min read
    Merge k Sorted Arrays
    Given K sorted arrays, merge them and print the sorted output.Examples:Input: K = 3, arr = { {1, 3, 5, 7}, {2, 4, 6, 8}, {0, 9, 10, 11}}Output: 0 1 2 3 4 5 6 7 8 9 10 11 Input: k = 4, arr = { {1}, {2, 4}, {3, 7, 9, 11}, {13} }Output: 1 2 3 4 7 9 11 13Table of ContentNaive - Concatenate all and SortU
    15+ min read
    Merge K sorted arrays of different sizes | ( Divide and Conquer Approach )
    Given k sorted arrays of different length, merge them into a single array such that the merged array is also sorted.Examples: Input : {{3, 13}, {8, 10, 11} {9, 15}} Output : {3, 8, 9, 10, 11, 13, 15} Input : {{1, 5}, {2, 3, 4}} Output : {1, 2, 3, 4, 5} Let S be the total number of elements in all th
    8 min read
    Merge K sorted linked lists
    Given k sorted linked lists of different sizes, the task is to merge them all maintaining their sorted order.Examples: Input: Output: Merged lists in a sorted order where every element is greater than the previous element.Input: Output: Merged lists in a sorted order where every element is greater t
    15+ min read
    Union and Intersection of two Linked List using Merge Sort
    Given two singly Linked Lists, create union and intersection lists that contain the union and intersection of the elements present in the given lists. Each of the two lists contains distinct node values.Note: The order of elements in output lists doesn't matter.Examples:Input: head1: 10 -> 15 -
    15+ min read
    Sorting by combining Insertion Sort and Merge Sort algorithms
    Insertion sort: The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part.Advantages: Following are the advantages of insertion sort: If the size of the list to be sorted is small, insertion sort ru
    2 min read
    Find array with k number of merge sort calls
    Given two numbers n and k, find an array containing values in [1, n] and requires exactly k calls of recursive merge sort function. Examples: Input : n = 3 k = 3 Output : a[] = {2, 1, 3} Explanation: Here, a[] = {2, 1, 3} First of all, mergesort(0, 3) will be called, which then sets mid = 1 and call
    6 min read
    Difference of two Linked Lists using Merge sort
    Given two Linked List, the task is to create a Linked List to store the difference of Linked List 1 with Linked List 2, i.e. the elements present in List 1 but not in List 2.Examples: Input: List1: 10 -> 15 -> 4 ->20, List2: 8 -> 4 -> 2 -> 10 Output: 15 -> 20 Explanation: In the
    14 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

'); // $('.spinner-loading-overlay').show(); let script = document.createElement('script'); script.src = 'https://assets.geeksforgeeks.org/v2/editor-prod/static/js/bundle.min.js'; script.defer = true document.head.appendChild(script); script.onload = function() { suggestionModalEditor() //to add editor in suggestion modal if(loginData && loginData.premiumConsent){ personalNoteEditor() //to load editor in personal note } } script.onerror = function() { if($('.editorError').length){ $('.editorError').remove(); } var messageDiv = $('
').text('Editor not loaded due to some issues'); $('#suggestion-section-textarea').append(messageDiv); $('.suggest-bottom-btn').hide(); $('.suggestion-section').hide(); editorLoaded = false; } }); //suggestion modal editor function suggestionModalEditor(){ // editor params const params = { data: undefined, plugins: ["BOLD", "ITALIC", "UNDERLINE", "PREBLOCK"], } // loading editor try { suggestEditorInstance = new GFGEditorWrapper("suggestion-section-textarea", params, { appNode: true }) suggestEditorInstance._createEditor("") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } //personal note editor function personalNoteEditor(){ // editor params const params = { data: undefined, plugins: ["UNDO", "REDO", "BOLD", "ITALIC", "NUMBERED_LIST", "BULLET_LIST", "TEXTALIGNMENTDROPDOWN"], placeholderText: "Description to be......", } // loading editor try { let notesEditorInstance = new GFGEditorWrapper("pn-editor", params, { appNode: true }) notesEditorInstance._createEditor(loginData&&loginData.user_personal_note?loginData.user_personal_note:"") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } var lockedCasesHtml = `You can suggest the changes for now and it will be under 'My Suggestions' Tab on Write.

You will be notified via email once the article is available for improvement. Thank you for your valuable feedback!`; var badgesRequiredHtml = `It seems that you do not meet the eligibility criteria to create improvements for this article, as only users who have earned specific badges are permitted to do so.

However, you can still create improvements through the Pick for Improvement section.`; jQuery('.improve-header-sec-child').on('click', function(){ jQuery('.improve-modal--overlay').hide(); $('.improve-modal--suggestion').hide(); jQuery('#suggestion-modal-alert').hide(); }); $('.suggest-change_wrapper, .locked-status--impove-modal .improve-bottom-btn').on('click',function(){ // when suggest changes option is clicked $('.ContentEditable__root').text(""); $('.suggest-bottom-btn').html("Suggest changes"); $('.thank-you-message').css("display","none"); $('.improve-modal--improvement').hide(); $('.improve-modal--suggestion').show(); $('#suggestion-section-textarea').show(); jQuery('#suggestion-modal-alert').hide(); if(suggestEditorInstance !== null){ suggestEditorInstance.setEditorValue(""); } $('.suggestion-section').css('display', 'block'); jQuery('.suggest-bottom-btn').css("display","block"); }); $('.create-improvement_wrapper').on('click',function(){ // when create improvement option clicked then improvement reason will be shown if(loginData && loginData.isLoggedIn) { $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status) }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ } $('.improve-modal--improvement').show(); }); const showErrorMessage = (result,statusCode) => { if(!result) return; $('.spinner-loading-overlay:eq(0)').remove(); if(statusCode == 403) { $('.improve-modal--improve-content.error-message').html(result.message); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); return; } } function suggestionCall() { var editorValue = suggestEditorInstance.getValue(); var suggest_val = $(".ContentEditable__root").find("[data-lexical-text='true']").map(function() { return $(this).text().trim(); }).get().join(' '); suggest_val = suggest_val.replace(/\s+/g, ' ').trim(); var array_String= suggest_val.split(" ") //array of words var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(editorValue.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `${editorValue}`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { if(!loginData || !loginData.isLoggedIn) { grecaptcha.reset(); } jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('.suggest-bottom-btn').css("display","none"); $('#suggestion-section-textarea').hide() $('.thank-you-message').css('display', 'flex'); $('.suggestion-section').css('display', 'none'); jQuery('#suggestion-modal-alert').hide(); }, error:function(data) { if(!loginData || !loginData.isLoggedIn) { grecaptcha.reset(); } jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 4 Words and Maximum Words limit is 1000."); jQuery('#suggestion-modal-alert').show(); jQuery('.ContentEditable__root').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('.ContentEditable__root').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('.ContentEditable__root').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // script for grecaptcha loaded in loginmodal.html and call function to set the token setGoogleRecaptcha(); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status); }, }); });
"For an ad-free experience and exclusive features, subscribe to our Premium Plan!"
Continue without supporting
`; $('body').append(adBlockerModal); $('body').addClass('body-for-ad-blocker'); const modal = document.getElementById("adBlockerModal"); modal.style.display = "block"; } function handleAdBlockerClick(type){ if(type == 'disabled'){ window.location.reload(); } else if(type == 'info'){ document.getElementById("ad-blocker-div").style.display = "none"; document.getElementById("ad-blocker-info-div").style.display = "flex"; handleAdBlockerIconClick(0); } } var lastSelected= null; //Mapping of name and video URL with the index. const adBlockerVideoMap = [ ['Ad Block Plus','https://media.geeksforgeeks.org/auth-dashboard-uploads/abp-blocker-min.mp4'], ['Ad Block','https://media.geeksforgeeks.org/auth-dashboard-uploads/Ad-block-min.mp4'], ['uBlock Origin','https://media.geeksforgeeks.org/auth-dashboard-uploads/ub-blocke-min.mp4'], ['uBlock','https://media.geeksforgeeks.org/auth-dashboard-uploads/U-blocker-min.mp4'], ] function handleAdBlockerIconClick(currSelected){ const videocontainer = document.getElementById('ad-blocker-info-div-gif'); const videosource = document.getElementById('ad-blocker-info-div-gif-src'); if(lastSelected != null){ document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.backgroundColor = "white"; document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.borderColor = "#D6D6D6"; } document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.backgroundColor = "#D9D9D9"; document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.borderColor = "#848484"; document.getElementById('ad-blocker-info-div-name-span').innerHTML = adBlockerVideoMap[currSelected][0] videocontainer.pause(); videosource.setAttribute('src', adBlockerVideoMap[currSelected][1]); videocontainer.load(); videocontainer.play(); lastSelected = currSelected; }

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences