Open In App

CSES Solutions – Distinct Numbers

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:

Below is the implementation of the approach:

#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();
}
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
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()
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);
    }
}
// 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);

Output
2

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

Below is the implementation of above approach :

#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;
}
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));
    }
}
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()
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();

Output
Number of distinct values are : 7

Time Complexity: O(n)
Space Complexity: O(n)


Article Tags :