Wednesday, February 8, 2023
HomeSoftware DevelopmentDiscover integers such that A accommodates precisely X distinct integers better than...

Discover integers such that A accommodates precisely X distinct integers better than A{i]


Given an array A[] of N integers, the duty is to print the variety of integers i from 1 to N, for which A accommodates precisely X distinct integers (for X = 0 to N-1) better than Ai

Examples:

Enter: N = 6, A[] = {2, 7, 1, 8, 2, 8}
Output: {2, 1, 2, 1, 0, 0}
Clarification: Allow us to take into account X = 2.
A[1] = 2: A accommodates 2 distinct integers better than 2 (7 and eight)
A[2] = 7: A accommodates 1 distinct integer better than 7 (8)
A[3] = 1: A accommodates 3 distinct integers better than 1 (2, 7 and eight)
A[4] = 8: A doesn’t comprise any distinct integers better than 8
A[5] = 2: A accommodates 2 distinct integers better than 2 (7 and eight)
A[6] = 8: A doesn’t comprise any distinct integers better than 8
So, the given situation is happy for i=1 and 5 in case of X=2.

Enter: N = 1, A[] = {1}
Output: 1

Strategy: To unravel the issue observe the under observations:

Observations:

If we retailer frequency of every component of array in a hashmap and type it in reducing order by the keys, then:

Let the hashmap be – ((u1, f1), (u2, f2)….(un, fn)) the place fi is the frequency of component ui and u1 > u2 > ……un.

  • For every i = 1 to n, there are i – 1 distinct integers that’s better than ui. So, for every X=0 to n-1 the reply for X could be fX+1.
  • Reply for X = n to N – 1 could be 0.

Primarily based on the above statement following strategy can be utilized to unravel the issue:

  • Declare a map (say mp) and insert the weather of array A into it.
  • Iterate the map from the top and print the frequencies of the weather.
  • For the remaining parts (i.e. N-n), print N-n zeroes.

Following is the code based mostly on the above strategy :

C++

#embody <bits/stdc++.h>

utilizing namespace std;

#outline int lengthy lengthy

  

void Clear up(int N, int A[])

{

  

    

    map<int, int> mp;

  

    

    for (int i = 0; i < N; i++) {

        mp[A[i]]++;

    }

  

    

    int n = (int)mp.measurement();

  

    

    

    for (auto it = mp.rbegin(); it != mp.rend(); it++) {

        cout << it->second << " ";

    }

  

    

    for (int i = 1; i <= N - n; i++) {

        cout << 0 << " ";

    }

}

  

int32_t most important()

{

    int N = 6;

    int A[] = { 2, 7, 1, 8, 2, 8 };

  

    

    Clear up(N, A);

    return 0;

}

Time Complexity: O(N*log(N))
Auxiliary House: O(N)



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments