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
Complete CP Guide
Basics
Bit manipulation
DP for CP
Advanced
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Binary Indexed Tree or Fenwick TreeBinary Indexed Trees are used for problems where we have following types of multiple operations on a fixed sized.Prefix Operation (Sum, Product, XOR, OR, etc). Note that range operations can also be solved using prefix. For example, range sum from index L to R is prefix sum till R (included minus pr
15 min read
Array Range QueriesThe array range query problem can be defined as follows: Given an array of numbers, the array range query problem is to build a data structure that can efficiently answer queries of a particular type mentioned in terms of an interval of the indices. The specific query can be of type - maximum elemen
3 min read