Basic Encoding - Unstop Solution (Java)
Given problem statement:
Input Format
First line contains a single integer denoting the number of queries.
Second line onwards: two space separated integers denoting the queries
Output Format
Display a single integer, representing the absolute difference between the number that appears most number of times and least number of times.
Constraints
1<=q<=100000.
1<=a,b<=100000.
Sample Testcase 1
Testcase Input
4
1 2
1 3
2 5
4 4
Testcase Output
2
Explanation
As per the question:
2 occurs 1 time
3 occurs 1 time
5 occurs 2 times
4 occurs 4 times
Therefore the we need to get the difference between the number occuring most number of times (4) and the number ocuring least number of times(2, 3).
As we want maximum difference the answer is: 4-2 = 2.
Solution in Java:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
// Mapping number to its frequency
Map<Integer, Integer> map = new HashMap<>();
// Loop through the queries
for (int i = 0; i < n; i++) {
int frequency = scanner.nextInt();
int number = scanner.nextInt();
// Updating the frequency of the number
map.put(number, map.getOrDefault(number, 0) + frequency);
}
int maxFrequency = 0;
int maxNumber = 0;
int minFrequency = Integer.MAX_VALUE;
int minNumber = 0;
// Finding the number with maximum and minimum frequencies
for (int key : map.keySet()) {
int frequency = map.get(key);
if (frequency > maxFrequency || (frequency == maxFrequency && key > maxNumber)) {
maxFrequency = frequency;
maxNumber = key;
}
if (frequency < minFrequency || (frequency == minFrequency && key < minNumber)) {
minFrequency = frequency;
minNumber = key;
}
}
// Calculating and printing the absolute difference
System.out.println(Math.abs(maxNumber - minNumber));
}
}
We loop n times to process each query: Inside the loop, we read two integers: number
and frequency
. We update the frequency of the number in the map using map.put(number, map.getOrDefault(number, 0) + frequency)
. This line ensures that if the number is already present in the map, its frequency is incremented by frequency. If not, it adds the number to the map with frequency as its initial value.
After processing all queries, we find the maximum and minimum keys (numbers) in the map using Collections.max
and Collections.min
methods. We calculate the absolute difference between the maximum and minimum keys using the Math.abs
method.
Thank you for reading! ๐
Subscribe to my newsletter
Read articles from Dhanush directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Dhanush
Dhanush
Software Developer