Skip to content
Related Articles

Related Articles

Count of numbers in given Array greater than next K elements

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 11 May, 2022

Given an array arr[] of integers of size N, the task is to count the number of elements whose value is greater than all the K elements to its immediate right. If there are less than K numbers to the right of the ith element, then the value of all of them must be lesser than that of the ith person.

Examples:

Input: arr[] = {4, 3, 1, 2, 5}, N = 5, K = 1
Output: 3
Explanation: The 1st ,2nd and 5th are the elements whose values are greater than the element to its right(As k = 1 consider only the next). While the 3rd element can not be considered because of the 4th element whose value is greater than the 3rd element’s value. 

Input: arr[] = {9, 7, 7, 7, 4}, N = 5, K = 3
Output: 3
Explanation: The 1st ,4th and the 5th element will be the elements whose values are greater than all 3 elements after it.

 

Naive Approach: For each element check K elements to their immediate right and see if it is greater than all of those or not.

Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: This problem can be solved using the following steps:

  • Consider a queue for storing K elements.
  • Add K elements from the last to the queue and keep the max of the last K values in a variable (say, max_value).
  • Iterate over the remaining array in the backward direction from the position (N – K).
    • While iterating pop an element from the queue and push the current element in the queue.
    • If the current element has a value greater than max_value, then increment the count and update max_value to the current element.
    • Else If the popped value is the same as the max_value then find the new max from the queue.
  • Return the count value as the count of the element whose value is greater than all the k elements to its immediate right.

Below is the implementation of the above approach: 

C++




// C++ code to implement the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find
// maximum element in queue
int find_max(queue<int> q)
{
    int ans = INT_MIN;
 
    // Loop to find maximum from queue
    while (!q.empty()) {
        ans = max(ans, q.front());
        q.pop();
    }
    return ans;
}
 
// Function to count the elements
// whose values are greater than
// all the k elements to its immediate right
int solve(int n, int k, vector<int> arr)
{
    int max_value = INT_MIN;
    queue<int> q;
    int count = 0;
    int p = n - k;
 
    // Checking base cases
    if (n == 0)
        return 0;
    else if (k == 0)
        return n;
 
    // Traversing last k elements
    for (int i = n - 1; i >= p; i--) {
        q.push(arr[i]);
        if (arr[i] > max_value) {
            max_value = arr[i];
            count++;
        }
    }
 
    // Traversing rest of the elements
    for (int i = p - 1; i >= 0; i--) {
        int x = q.front();
        q.pop();
        q.push(arr[i]);
        if (arr[i] > max_value) {
            count++;
            max_value = arr[i];
        }
        else {
            if (x == max_value) {
                // If popped value
                // is same as max value
                // then update max value
                max_value = find_max(q);
            }
        }
    }
    return count;
}
 
// Driver Code Starts.
int main()
{
    int N, K;
    N = 5;
    K = 1;
    vector<int> arr = { 4, 3, 1, 2, 5};
 
    cout << solve(N, K, arr) << "\n";
    return 0;
}


Java




// Java code to implement the above approach
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
 
class GFG {
 
    // Function to find
    // maximum element in queue
    public static int find_max(Queue<Integer> q) {
        int ans = Integer.MIN_VALUE;
 
        // Loop to find maximum from queue
        while (!q.isEmpty()) {
            ans = Math.max(ans, q.peek());
            q.remove();
        }
        return ans;
    }
 
    // Function to count the elements
    // whose values are greater than
    // all the k elements to its immediate right
    public static int solve(int n, int k, ArrayList<Integer> arr) {
        int max_value = Integer.MIN_VALUE;
        Queue<Integer> q = new LinkedList<Integer>();
        int count = 0;
        int p = n - k;
 
        // Checking base cases
        if (n == 0)
            return 0;
        else if (k == 0)
            return n;
 
        // Traversing last k elements
        for (int i = n - 1; i >= p; i--) {
            q.add(arr.get(i));
            if (arr.get(i) > max_value) {
                max_value = arr.get(i);
                count++;
            }
        }
 
        // Traversing rest of the elements
        for (int i = p - 1; i >= 0; i--) {
            int x = 0;
            if (q.size() > 0) {
                x = q.peek();
                q.remove();
            }
            q.add(arr.get(i));
            if (arr.get(i) > max_value) {
                count++;
                max_value = arr.get(i);
            } else {
                if (x == max_value) {
                    // If popped value
                    // is same as max value
                    // then update max value
                    max_value = find_max(q);
                }
            }
        }
        return count;
    }
 
    // Driver Code Starts.
    public static void main(String args[]) {
        int N, K;
        N = 5;
        K = 1;
        ArrayList<Integer> arr = new ArrayList<>();
        arr.add(4);
        arr.add(3);
        arr.add(1);
        arr.add(2);
        arr.add(5);
 
        System.out.println(solve(N, K, arr));
    }
}
 
// This code is contributed by saurabh_jaiswal.


Python3




# Python3 code to implement the above approach
from queue import Queue
import copy
INT_MIN = -2147483648
 
# Function to find
# maximum element in queue
def find_max(q):
     
    ans = INT_MIN
     
    # Loop to find maximum from queue
    while (not q.empty()):
        ans = max(ans, q.get())
 
    return ans
     
# Function to count the elements
# whose values are greater than
# all the k elements to its immediate right
def solve(n, k, arr):
 
    max_value = INT_MIN
    q = Queue()
    count = 0
    p = n - k
 
    # Checking base cases
    if (n == 0):
        return 0
    elif (k == 0):
        return n
 
    # Traversing last k elements
    for i in range(n - 1, p - 1, -1):
        q.put(arr[i])
        if (arr[i] > max_value):
            max_value = arr[i]
            count += 1
 
    # Traversing rest of the elements
    for i in range(p - 1, -1, -1):
        x = q.get()
        q.put(arr[i])
         
        if (arr[i] > max_value):
            count += 1
            max_value = arr[i]
 
        else:
            if (x == max_value):
                 
                # If popped value is same
                # as max value then update
                # max value
                temp = Queue()
                for i in q.queue:
                    temp.put(i)
                     
                max_value = find_max(temp)
 
    return count
 
# Driver code
if __name__ == "__main__":
 
    N = 5
    K = 1
    arr = [ 4, 3, 1, 2, 5 ]
 
    print(solve(N, K, arr))
 
# This code is contributed by rakeshsahni


C#




// C# code to implement the above approach
using System;
using System.Collections.Generic;
 
public class GFG {
 
    // Function to find
    // maximum element in queue
    public static int find_max(Queue<int> q) {
        int ans = int.MinValue;
 
        // Loop to find maximum from queue
        while (q.Count != 0) {
            ans = Math.Max(ans, q.Peek());
            q.Dequeue();
        }
        return ans;
    }
 
    // Function to count the elements
    // whose values are greater than
    // all the k elements to its immediate right
    public static int solve(int n, int k, List<int> arr) {
        int max_value = int.MinValue;
        Queue<int> q = new Queue<int>();
        int count = 0;
        int p = n - k;
 
        // Checking base cases
        if (n == 0)
            return 0;
        else if (k == 0)
            return n;
 
        // Traversing last k elements
        for (int i = n - 1; i >= p; i--) {
            q.Enqueue(arr[i]);
            if (arr[i] > max_value) {
                max_value = arr[i];
                count++;
            }
        }
 
        // Traversing rest of the elements
        for (int i = p - 1; i >= 0; i--) {
            int x = 0;
            if (q.Count > 0) {
                x = q.Peek();
                q.Dequeue();
            }
            q.Enqueue(arr[i]);
            if (arr[i] > max_value) {
                count++;
                max_value = arr[i];
            } else {
                if (x == max_value) {
                    // If popped value
                    // is same as max value
                    // then update max value
                    max_value = find_max(q);
                }
            }
        }
        return count;
    }
 
    // Driver Code Starts.
    public static void Main(String []args) {
        int N, K;
        N = 5;
        K = 1;
        List<int> arr = new List<int>();
        arr.Add(4);
        arr.Add(3);
        arr.Add(1);
        arr.Add(2);
        arr.Add(5);
 
        Console.WriteLine(solve(N, K, arr));
    }
}
 
// This code is contributed by shikhasingrajput


Javascript




<script>
// Javascript code to implement the above approach
 
 
// Function to find
// maximum element in queue
function find_max(q) {
    let ans = Number.MIN_SAFE_INTEGER;
 
    // Loop to find maximum from queue
    while (q.length) {
        ans = Math.max(ans, q[0]);
        q.pop();
    }
    return ans;
}
 
// Function to count the elements
// whose values are greater than
// all the k elements to its immediate right
function solve(n, k, arr) {
    let max_value = Number.MIN_SAFE_INTEGER;
    let q = [];
    let count = 0;
    let p = n - k;
 
    // Checking base cases
    if (n == 0)
        return 0;
    else if (k == 0)
        return n;
 
    // Traversing last k elements
    for (let i = n - 1; i >= p; i--) {
        q.push(arr[i]);
        if (arr[i] > max_value) {
            max_value = arr[i];
            count++;
        }
    }
 
    // Traversing rest of the elements
    for (let i = p - 1; i >= 0; i--) {
        let x = q[0];
        q.pop();
        q.push(arr[i]);
        if (arr[i] > max_value) {
            count++;
            max_value = arr[i];
        }
        else {
            if (x == max_value) {
                // If popped value
                // is same as max value
                // then update max value
                max_value = find_max(q);
            }
        }
    }
    return count;
}
 
// Driver Code Starts.
 
let N, K;
N = 5;
K = 1;
let arr = [4, 3, 1, 2, 5];
 
document.write(solve(N, K, arr))
 
// This code is contributed by gfgking.
</script>


Output

3

Time Complexity: O(N)
Auxiliary Space: O(K)

Space Optimized Approach: The problem can be solved with lesser space using two pointer approach. Follow the steps mentioned below. 

  • Initialize two-pointer (say “left” and “right”) pointing to the end of the array.
  • The left pointer points to the starting index of the K-sized window and the right pointer points to the maximum value in that window.
  • If the value at the left pointer is greater than the value at the right pointer, increase answer count by 1. (Because it means it is greater than all the K elements to its immediate right)
  • If at any point the window size exceeds K, decrement the right pointer by one and adjust it to point to the maximum value of the current window.

Below is the implementation of the above approach: 

C++




// C++ code to implement the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to count the elements
// whose values are greater than
// all k elements to its immediate right
int solve(int n, int k, vector<int> arr)
{
    int count = 1;
    int left = n - 2, right = n - 1;
 
    // Checking base cases
    if (n == 0)
        return 0;
    else if (k == 0)
        return n;
     
    // Loop to implement two-pointer approach
    for (; left >= 0; left--) {
        if (right - left > k) {
            right--;
            while (arr[left] > arr[right])
                right--;
            if (right == left)
                count++;
        }
        else if (arr[left] > arr[right]) {
            count++;
            right = left;
        }
    }
 
    return count;
}
 
// Driver Code Starts.
int main()
{
    int N, K;
    N = 5;
    K = 1;
    vector<int> arr = { 4, 3, 1, 2, 5};
    cout << solve(N, K, arr);
    return 0;
}


Java




// Java code to implement the above approach
import java.io.*;
 
class GFG{
 
// Function to count the elements
// whose values are greater than
// all k elements to its immediate right
static int solve(int n, int k, int[] arr)
{
    int count = 1;
    int left = n - 2, right = n - 1;
 
    // Checking base cases
    if (n == 0)
        return 0;
    else if (k == 0)
        return n;
 
    // Loop to implement two-pointer approach
    for(; left >= 0; left--)
    {
        if (right - left > k)
        {
            right--;
             
            while (arr[left] > arr[right])
                right--;
            if (right == left)
                count++;
        }
        else if (arr[left] > arr[right])
        {
            count++;
            right = left;
        }
    }
    return count;
}
 
// Driver Code
public static void main(String[] args)
{
    int N, K;
    N = 5;
    K = 1;
    int[] arr = { 4, 3, 1, 2, 5 };
 
    System.out.println(solve(N, K, arr));
}
}
 
// This code is contributed by Potta Lokesh


Python3




# Python 3 code to implement the above approach
 
# Function to count the elements
# whose values are greater than
# all k elements to its immediate right
def solve(n,  k, arr):
 
    count = 1
    left = n - 2
    right = n - 1
 
    # Checking base cases
    if (n == 0):
        return 0
    elif (k == 0):
        return n
 
    # Loop to implement two-pointer approach
    while left >= 0:
        if (right - left > k):
            right -= 1
            while (arr[left] > arr[right]):
                right -= 1
            if (right == left):
                count += 1
 
        elif (arr[left] > arr[right]):
            count += 1
            right = left
 
        left -= 1
 
    return count
 
# Driver Code
if __name__ == "__main__":
 
    N = 5
    K = 1
    arr = [4, 3, 1, 2, 5]
    print(solve(N, K, arr))
 
    # This code is contributed by ukasp.


C#




// C# code to implement the above approach
using System;
 
public class GFG
{
 
// Function to count the elements
// whose values are greater than
// all k elements to its immediate right
static int solve(int n, int k, int[] arr)
{
    int count = 1;
    int left = n - 2, right = n - 1;
 
    // Checking base cases
    if (n == 0)
        return 0;
    else if (k == 0)
        return n;
 
    // Loop to implement two-pointer approach
    for(; left >= 0; left--)
    {
        if (right - left > k)
        {
            right--;
             
            while (arr[left] > arr[right])
                right--;
            if (right == left)
                count++;
        }
        else if (arr[left] > arr[right])
        {
            count++;
            right = left;
        }
    }
    return count;
}
 
// Driver Code
public static void Main(String[] args)
{
    int N, K;
    N = 5;
    K = 1;
    int[] arr = { 4, 3, 1, 2, 5 };
 
    Console.WriteLine(solve(N, K, arr));
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
// javascript code to implement the above approach
 
// Function to count the elements
// whose values are greater than
// all k elements to its immediate right
function solve(n , k, arr)
{
    var count = 1;
    var left = n - 2, right = n - 1;
 
    // Checking base cases
    if (n == 0)
        return 0;
    else if (k == 0)
        return n;
 
    // Loop to implement two-pointer approach
    for(; left >= 0; left--)
    {
        if (right - left > k)
        {
            right--;
             
            while (arr[left] > arr[right])
                right--;
            if (right == left)
                count++;
        }
        else if (arr[left] > arr[right])
        {
            count++;
            right = left;
        }
    }
    return count;
}
 
// Driver Code
var N, K;
N = 5;
K = 1;
var arr = [ 4, 3, 1, 2, 5 ];
 
document.write(solve(N, K, arr));
 
// This code is contributed by 29AjayKumar
</script>


Output

3

Time Complexity: O(N)
Auxiliary Space: O(1)

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!