CSES Solutions - Distinct Numbers
Last Updated :
01 May, 2024
You are given a list of N integers arr[], and your task is to calculate the number of distinct values in the list.
Examples:
Input: N = 5, arr[] = {2, 2, 3, 3, 2}
Output: 2
Explanation: There are only two distinct elements: 2 and 3 in the array arr[].
Input: N = 6, arr[] = {1, 1, 2, 2, 3, 4}
Output: 4
Explanation: There are only 4 distinct elements: 1, 2, 3 and 4 in the array arr[].
Approach: To solve the problem, follow the below idea:
The problem can be solved by storing all the numbers in the set. Storing all the numbers in the set will ensure that we only have unique elements in the set. Finally, we can print the size of the set.
Step-by-step algorithm:
- Maintain a set to store all the distinct elements of arr[].
- Iterate through all the elements in arr[] and insert them into the set.
- After pushing all the elements into the set, print the size of the set as the final answer.
Below is the implementation of the approach:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Sample Input
int N = 5;
int arr[] = { 2, 2, 3, 3, 2 };
// Set to store all the elements
set<int> s;
for (int i = 0; i < N; i++) {
s.insert(arr[i]);
}
cout << s.size();
}
Java
import java.util.HashSet;
import java.util.Set;
public class SetExample {
public static void main(String[] args)
{
// Sample Input
int N = 5;
int[] arr = { 2, 2, 3, 3, 2 };
// Set to store all the elements
Set<Integer> set = new HashSet<>();
for (int i = 0; i < N; i++) {
set.add(arr[i]);
}
System.out.println(set.size());
}
}
// This code is contributed by rambabuguphka
Python
def main():
# Sample Input
N = 5
arr = [2, 2, 3, 3, 2]
# Set to store all the elements
unique_elements = set()
for num in arr:
unique_elements.add(num)
print(len(unique_elements))
if __name__ == "__main__":
main()
C#
using System;
using System.Collections.Generic;
class GFG
{
static void Main()
{
// Sample Input
int N = 5;
int[] arr = { 2, 2, 3, 3, 2 };
// HashSet to store all the elements
HashSet<int> set = new HashSet<int>();
for (int i = 0; i < N; i++)
{
set.Add(arr[i]);
}
Console.WriteLine(set.Count);
}
}
JavaScript
// Sample Input
const N = 5;
const arr = [2, 2, 3, 3, 2];
// Set to store all the elements
const s = new Set();
// Insert elements into the set
for (let i = 0; i < N; i++) {
s.add(arr[i]);
}
// Print the number of unique elements
console.log(s.size);
Time Complexity: O(NlogN), where N is the size of input array arr[].
Auxiliary Space: O(N)
Approach 2 (Using Map)
Create a function and inside create an unordered map to store the frequency of each element in the input vector. Iterate through the input vector using a range-based for loop. For each element , increment its frequency in the unordered map. After counting the frequencies of all elements, return the size of the map, which represents the number of distinct values in the input vector.
Step-by-Step Implementation
- Define a function called that takes a constant reference to a vector of integers as input and returns an integer representing the number of distinct values in the vector.
- Inside the function, initialize an unordered map with int as both key and value types. This map will store the frequency of each distinct element in the vector.
- Use a for loop to iterate through each element of the input vector. Inside the loop, update the frequency map by incrementing the count for the current element in vector.
- After iterating through the entire vector, return the size of the frequency map, which represents the number of distinct values in the vector.
Below is the implementation of above approach :
C++
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
int DistinctValuesMap(const vector<int>& arr) {
unordered_map<int, int> freqMap;
for (int num : arr) {
freqMap[num]++;
}
return freqMap.size();
}
int main() {
vector<int> arr = {1, 2, 3, 4, 4, 4, 5, 5, 6, 7, 7, 7};
cout << "Number of distinct values are : " << DistinctValuesMap(arr) << endl;
return 0;
}
Java
import java.util.HashMap;
import java.util.Map;
public class DistinctValues {
static int distinctValuesMap(int[] arr) {
Map<Integer, Integer> freqMap = new HashMap<>();
for (int num : arr) {
freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
}
return freqMap.size();
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 4, 4, 5, 5, 6, 7, 7, 7};
System.out.println("Number of distinct values are : " + distinctValuesMap(arr));
}
}
Python3
def distinct_values_map(arr):
freq_map = {} # Create an empty dictionary to store frequency of each element
for num in arr:
freq_map[num] = freq_map.get(num, 0) + 1 # Increment frequency count for each element
return len(freq_map) # Return the number of distinct values
# Main function
def main():
arr = [1, 2, 3, 4, 4, 4, 5, 5, 6, 7, 7, 7]
# Call the distinct_values_map function to get the number of distinct values
distinct_count = distinct_values_map(arr)
# Print the number of distinct values
print("Number of distinct values are:", distinct_count)
# Execute main function
if __name__ == "__main__":
main()
JavaScript
function distinctValuesMap(arr) {
let freqMap = new Map();
for (let num of arr) {
if (freqMap.has(num)) {
freqMap.set(num, freqMap.get(num) + 1);
} else {
freqMap.set(num, 1);
}
}
return freqMap.size;
}
// Main function
function main() {
let arr = [1, 2, 3, 4, 4, 4, 5, 5, 6, 7, 7, 7];
console.log("Number of distinct values are:", distinctValuesMap(arr));
}
// Call the main function
main();
OutputNumber of distinct values are : 7
Time Complexity: O(n)
Space Complexity: O(n)
Similar Reads
CSES Solutions - Two Sets Given N numbers 1,2,3,... N. Your task is to divide the numbers into two sets of equal sum. Print "YES", if the division is possible, and "NO" otherwise. If the division is possible, print how to create the sets. First, print the number of elements in the first set followed by the elements themselve
10 min read
CSES Solutions - Subarray Distinct Values Given an array of N integers arr[] and an integer K, your task is to calculate the number of subarrays that have at most K distinct values. Examples: Input: N = 5, K = 2, arr[] = {1, 2, 1, 2, 3}Output: 10Explanation: There are 12 subarrays with at most 2 distinct values: {1}, {2}, {1}, {2}, {3}, {1,
8 min read
Numbers having Unique (or Distinct) digits Given a range, print all numbers having unique digits. Examples : Input : 10 20Output : 10 12 13 14 15 16 17 18 19 20 (Except 11)Input : 1 10Output : 1 2 3 4 5 6 7 8 9 10Approach:As the problem is pretty simple, the only thing to be done is :-1- Find the digits one by one and keep marking visited di
10 min read
Number of solutions to Modular Equations Given A and B, the task is to find the number of possible values that X can take such that the given modular equation (A mod X) = B holds good. Here, X is also called a solution of the modular equation.Examples: Input : A = 26, B = 2Output : 6Explanation:X can be equal to any of {3, 4, 6, 8, 12, 24}
13 min read
Find the count of distinct numbers in a range Given an array of size N containing numbers only from 0 to 63, and you are asked Q queries regarding it.Queries are as follows: 1 X Y i.e Change the element at index X to Y2 L R i.e Print the count of distinct elements present in between L and R inclusive Examples: Input: N = 7 ar = {1, 2, 1, 3, 1,
15 min read