Given an array arr[] consisting of N integers and an integer R, denoting the cutoff rank, the task is to count the number of array elements with rank at most R such that the equal array element are ranked the same and distinct array elements are ranked based on their positions in the array arr[].
Examples:
Input: arr[] = {100, 50, 50, 25}, R = 3
Output: 3
Explanation:
The players are ranked as: {1, 2, 2, 4}. The players having ranked at most R(= 3) is {1, 2, 2}. Therefore, the total count is 3.Input: arr[] = {2, 2, 3, 4, 5}, R = 4
Output: 5
Approach: The given problem can be solved by using the concept of Sorting. Follow the below step to solve this problem:
- Sort the given array arr[] in decreasing order.
- Initialize two variables, say rank as 1 to store the rank of the array elements and say count as 0 to store the required result.
- Traverse the given array arr[], using the variable i, and perform the following steps:
- If the arr[i] is equal to the previous element then assign the same rank as the previous rank to the current element.
- Otherwise, assign the value of (count + 1)th rank to the current element.
- If the rank is greater than R then break. Otherwise, increment the count by 1.
- After completing the above steps, print the value of count as the answer.
Below is the implementation of the above approach:
C++
// C++Â program for above approach#include <algorithm>#include <iostream>using namespace std;Â
// Function to find the count of array// elements having rank at most Rint countElements(int R, int N, int arr[]){Â
  // Sort the array arr[] in the  // decreasing order  sort(arr, arr + N, greater<int>());Â
  // Stores the rank and required  // count of array elements  int rank = 1, count = 0;Â
  // store the previou element  int prevScore = arr[0], score;Â
  // Traverse the array  for (int i = 0; i < N; i++) {    score = arr[i];Â
    // If score is less than the    // prevScore    if (score < prevScore) {      rank = count + 1;    }Â
    // If the rank is greater than R    if (rank > R) {      break;    }Â
    // Increment count by 1    count++;Â
    // update prevscore    prevScore = score;  }Â
  // return count  return count;}Â
// Driver codeint main(){Â Â int arr[] = { 100, 50, 50, 25 };Â Â int R = 2;Â Â int N = sizeof(arr) / sizeof(arr[0]);Â Â cout << countElements(R, N, arr);Â Â return 0;}Â
// This code is contributed by Parth Manchanda |
Java
// Java program for the above approachimport java.util.*;Â
class GFG {Â Â static void reverse(int a[])Â Â {Â Â Â Â int n = a.length;Â Â Â Â int[] b = new int[n];Â Â Â Â int j = n;Â Â Â Â for (int i = 0; i < n; i++) {Â Â Â Â Â Â b[j - 1] = a[i];Â Â Â Â Â Â j = j - 1;Â Â Â Â }Â Â }Â
  // Function to find the count of array  // elements having rank at most R  static int countElements(int R, int N, int[] arr)  {Â
    // Sort the array arr[] in the    // decreasing order    Arrays.sort(arr);    reverse(arr);Â
    // Stores the rank and required    // count of array elements    int rank = 1;    int count = -1;Â
    // Stores the previous element    int prevScore = arr[0];Â
    // Traverse the array    for(int score : arr)    {Â
      // If score is less than the      // prevScore      if (score < prevScore)        rank = count + 1;Â
      // If the rank is greater than R      if (rank > R)        break;Â
      // Increment count by 1      count = count + 1;Â
      // Update prevScore      prevScore = score;    }Â
    // Return the result    return count;  }Â
  // Driver Code  public static void main(String[] args)  {    int[] arr = { 100, 50, 50, 25 };    int R = 2;    int N = arr.length;Â
    // Function Call    System.out.println(countElements(R, N, arr));  }}Â
// This code is contributed by sanjoy_62. |
Python3
# Python program for the above approachÂ
# Function to find the count of array# elements having rank at most Rdef countElements(R, N, arr):Â
    # Sort the array arr[] in the    # decreasing order    arr.sort(reverse = True)Â
    # Stores the rank and required    # count of array elements    rank = 1    count = 0Â
    # Stores the previous element    prevScore = arr[0]Â
    # Traverse the array    for score in arr:Â
        # If score is less than the        # prevScore        if score < prevScore:            rank = count + 1Â
        # If the rank is greater than R        if rank > R:            break                     # Increment count by 1        count += 1Â
        # Update prevScore        prevScore = scoreÂ
    # Return the result    return countÂ
Â
# Driver Codearr = [100, 50, 50, 25]R = 2N = len(arr)Â
# Function Callprint(countElements(R, N, arr)) |
C#
// C# program for the above approachusing System;Â
class GFG{     // Function to find the count of array// elements having rank at most Rstatic int countElements(int R, int N, int[] arr){         // Sort the array arr[] in the    // decreasing order    Array.Sort(arr);    Array.Reverse(arr);Â
    // Stores the rank and required    // count of array elements    int rank = 1;    int count = 0;Â
    // Stores the previous element    int prevScore = arr[0];Â
    // Traverse the array    foreach(int score in arr)    {                 // If score is less than the        // prevScore        if (score < prevScore)            rank = count + 1;Â
        // If the rank is greater than R        if (rank > R)            break;Â
        // Increment count by 1        count = count + 1;Â
        // Update prevScore        prevScore = score;    }         // Return the result    return count;}Â
Â
// Driver codestatic public void Main(){Â Â Â Â int[] arr = { 100, 50, 50, 25 };Â Â Â Â int R = 2;Â Â Â Â int N = arr.Length;Â
    // Function Call    Console.WriteLine(countElements(R, N, arr));}}Â
// This code is contributed by target_2. |
Javascript
<script>Â
// JavaScript program for the above approachÂ
// Function to find the count of array// elements having rank at most Rfunction countElements(R, N, arr){         // Sort the array arr[] in the    // decreasing order    arr.sort(function(a, b){ return b - a; });Â
    // Stores the rank and required    // count of array elements    let rank = 1;    let count = 0;Â
    // Stores the previous element    let prevScore = arr[0];Â
    // Traverse the array    for(let score of arr)    {                 // If score is less than the        // prevScore        if (score < prevScore)            rank = count + 1;Â
        // If the rank is greater than R        if (rank > R)            break;Â
        // Increment count by 1        count = count + 1;Â
        // Update prevScore        prevScore = score;    }         // Return the result    return count;}Â
// Driver Codelet arr = [ 100, 50, 50, 25 ];let R = 2;let N = arr.length;Â
// Function Calldocument.write(countElements(R, N, arr));Â
// This code is contributed by lokeshpotta20Â
</script> |
3
Â
Time Complexity: O(N*log N)
Auxiliary Space: O(1)
 Method 2:using a heap data structureÂ
One method to solve the problem of finding the count of array elements having rank at most R is by using a heap data structure. This method involves creating a max heap of size R and traversing the array elements. For each element, if it is greater than the smallest element in the heap, then remove the smallest element from the heap and add the current element to the heap. At the end of the traversal, the count of elements in the heap is the required answer.
C++
#include <iostream>#include <queue>#include <vector>Â
using namespace std;Â
int countElements(int R, int N, vector<int> arr){Â Â Â Â // Create a min heap of size RÂ Â Â Â priority_queue<int, vector<int>, greater<int> > heap;Â
    for (int i = 0; i < R; i++) {        heap.push(arr[i]);    }Â
    // Traverse the array elements    for (int i = R; i < N; i++) {        if (arr[i] > heap.top()) {            heap.pop();            heap.push(arr[i]);        }    }Â
    // Return the count of elements in heap    return heap.size();}Â
// Driver Codeint main(){Â Â Â Â vector<int> arr = { 100, 50, 50, 25 };Â Â Â Â int R = 2;Â Â Â Â int N = arr.size();Â
    // Function Call    cout << countElements(R, N, arr);    return 0;} |
Java
import java.util.PriorityQueue;import java.util.Vector;Â
public class Main {    public static int countElements(int R, int N,                                    Vector<Integer> arr)    {Â
        // Create a min heap of size R        PriorityQueue<Integer> heap            = new PriorityQueue<Integer>();Â
        for (int i = 0; i < R; i++) {            heap.add(arr.get(i));        }Â
        // Traverse the array elements        for (int i = R; i < N; i++) {            if (arr.get(i) > heap.peek()) {                heap.poll();                heap.add(arr.get(i));            }        }Â
        // Return the count of elements in heap        return heap.size();    }Â
    // Driver Code    public static void main(String[] args)    {        Vector<Integer> arr = new Vector<Integer>();        arr.add(100);        arr.add(50);        arr.add(50);        arr.add(25);        int R = 2;        int N = arr.size();Â
        // Function Call        System.out.println(countElements(R, N, arr));    }} |
Python3
import heapqÂ
Â
def countElements(R, N, arr):Â
    # Create a max heap of size R    heap = []Â
    for i in range(R):        heapq.heappush(heap, arr[i])Â
    # Traverse the array elements    for i in range(R, N):        if arr[i] > heap[0]:            heapq.heappop(heap)            heapq.heappush(heap, arr[i])Â
    # Return the count of elements in heap    return len(heap)Â
Â
# Driver Codearr = [100, 50, 50, 25]R = 2N = len(arr)Â
# Function Callprint(countElements(R, N, arr)) |
C#
using System;using System.Collections.Generic;Â
public class Program {    public static int CountElements(int R, int N,                                    List<int> arr)    {        // Create a min heap of size R        var heap = new PriorityQueue<int>();        for (int i = 0; i < R; i++) {            heap.Enqueue(arr[i]);        }Â
        // Traverse the array elements        for (int i = R; i < N; i++) {            if (arr[i] > heap.Peek()) {                heap.Dequeue();                heap.Enqueue(arr[i]);            }        }Â
        // Return the count of elements in heap        return heap.Count;    }Â
    // Driver Code    public static void Main()    {        var arr = new List<int>{ 100, 50, 50, 25 };        int R = 2;        int N = arr.Count;Â
        // Function Call        Console.WriteLine(CountElements(R, N, arr));    }}Â
public class PriorityQueue<T> where T : IComparable<T> {Â Â Â Â private List<T> list;Â Â Â Â public PriorityQueue() { list = new List<T>(); }Â
    public void Enqueue(T value)    {        list.Add(value);        int i = list.Count - 1;        while (i > 0) {            int j = (i - 1) / 2;            if (list[j].CompareTo(list[i]) <= 0) {                break;            }            T temp = list[i];            list[i] = list[j];            list[j] = temp;            i = j;        }    }Â
    public T Dequeue()    {        int last = list.Count - 1;        T frontItem = list[0];        list[0] = list[last];        list.RemoveAt(last);Â
        last--;Â
        int i = 0;        while (true) {            int left = i * 2 + 1;            int right = i * 2 + 2;            if (left > last) {                break;            }            int j = left;            if (right <= last                && list[right].CompareTo(list[left]) < 0) {                j = right;            }            if (list[i].CompareTo(list[j]) <= 0) {                break;            }            T temp = list[i];            list[i] = list[j];            list[j] = temp;            i = j;        }        return frontItem;    }Â
    public T Peek()    {        T frontItem = list[0];        return frontItem;    }Â
    public int Count    {        get { return list.Count; }    }}// This code is contributed by user_dtewbxkn77n |
Javascript
function countElements(R, N, arr) {  let heap = new PriorityQueue();  for (let i = 0; i < R; i++) {    heap.add(arr[i]);  }  // Traverse the array elements  for (let i = R; i < N; i++) {    if (arr[i] > heap.peek()) {      heap.poll();      heap.add(arr[i]);    }  }  return heap.size();}// Create a min heap of size Rclass PriorityQueue {  constructor() {    this.heap = [];  }Â
  add(val) {    this.heap.push(val);    this.bubbleUp(this.heap.length - 1);  }Â
  poll() {    if (this.heap.length === 0) {      return null;    }    const min = this.heap[0];    const last = this.heap.pop();    if (this.heap.length > 0) {      this.heap[0] = last;      this.bubbleDown(0);    }    return min;  }Â
  peek() {    return this.heap.length > 0 ? this.heap[0] : null;  }Â
  bubbleUp(idx) {    const element = this.heap[idx];    while (idx > 0) {      const parentIdx = Math.floor((idx - 1) / 2);      const parent = this.heap[parentIdx];      if (element >= parent) {        break;      }      this.heap[parentIdx] = element;      this.heap[idx] = parent;      idx = parentIdx;    }  }Â
  bubbleDown(idx) {    const element = this.heap[idx];    const length = this.heap.length;    while (true) {      const leftChildIdx = idx * 2 + 1;      const rightChildIdx = idx * 2 + 2;      let leftChild, rightChild;      let swap = null;Â
      if (leftChildIdx < length) {        leftChild = this.heap[leftChildIdx];        if (leftChild < element) {          swap = leftChildIdx;        }      }Â
      if (rightChildIdx < length) {        rightChild = this.heap[rightChildIdx];        if (          (swap === null && rightChild < element) ||          (swap !== null && rightChild < leftChild)        ) {          swap = rightChildIdx;        }      }Â
      if (swap === null) {        break;      }      this.heap[idx] = this.heap[swap];      this.heap[swap] = element;      idx = swap;    }  }Â
  size() {           // Return the count of elements in heap    return this.heap.length;  }}// Driver Codelet arr = [100, 50, 50, 25];let R = 2;let N = arr.length;// Function Callconsole.log(countElements(R, N, arr));Â
// This code is contributed by shiv1o43g |
2
The time complexity of the above implementation using the heapq module is O(NlogR), where N is the length of the input array and R is the given rank.
The auxiliary space complexity of this implementation is O(R), since we are using a max heap of size R to keep track of the top R elements
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
