You are given a string ‘S’ of length ‘N’. You have to return all the characters in the string that are duplicated and their frequency.
Example:-N = 5
S = ‘GEEK’
ANSWER:- The answer should be [(‘E’,2)] because ‘E’ is the only character that is duplicated and has frequency 2.
The first line contains a single integer ‘T’ representing the number of test cases. Then each test case follows.
The first line of every test case contains an integer ‘N’ denoting the length of the string.
The next line of every test case contains a string ‘S’ denoting the string given.
Output Format :
For each test case, return the duplicate characters in the string S and their frequency.
The output of each test case should be printed in a separate line.
Note :
You are not required to print anything, it has already been taken care of. Just implement the function.
1 <= T <= 5
1 <= N <= 10^5
Time Limit = 1 sec
2
5
APPLE
6
BANANA
P 2
A 3
N 2
In the first test case, the character ‘P’ has frequency 2 and is the only duplicate character in the string.
In the second test case, the character ‘A’ has frequency 3 and the character ‘N’ has frequency 2.
1
5
AAAAA
A 5
Store the frequency of all the characters in an array.
Iterate through the string and store the frequency of every character in an array. Then iterate through the array and check if the frequency is greater than 1, if yes add the character and its frequency in the answer.
Algorithm:-
O(N), where N is the length of the string ‘S’.
We are iterating through the string ‘S’ once, so the time complexity is O(N^2).
O(K), where K is the number of characters possible in the string ‘S’.
We are using an array of size ‘K’ to store the frequencies, so the space complexity is O(K).