Question of the Day - Distinct Lottery | Newton School - 20/03/2023

 



    Distinct Lottery:-

Problem Statement
You drew lottery N times. In the i-th draw, you got an item of the 
kind represented by a string Si. How many kinds of items did you get?

Input
The first line of the input consists of a single integer N. The next N lines consists of N strings.
N
S1
S2
.
.
.
SN

Constraints
1 ≤ N ≤ 2×10^5
Si consists of lowercase English letters and has a length between 1 and 10 (inclusive).

Output

Print the number of kinds of items you got.

Approach:-

In this problem we have drew the lottery N times. So the next N lines contains String si and we have to find 
how many types of items we can get from this. That means we have to find how many 
unique strings are present there. We have to count these 
unique strings. we don't have to count duplicate strings

Let's take one example

abc
def
hij
klm

So these are the 4 lotteries we have drew. So in this we have count the unique strings. We don't 
have to count duplicates.

here, both strings are unique so we can get total 4 types of items.

Lets take another example.

apple
orange
apple

So in this example we can get 2 types of items as we don't count the duplicates. In above example apple 
comes twice but we don't count the duplicates.

this is the problem statement.

Now let's see the solution.

Solution:-

Java Code:-

import java.io.*; // for handling input/output
import java.util.*; // contains Collections framework

// don't change the name of this class
// you can add inner classes if needed
class Main {
    public static void main (String[] args) {
        // Your code here
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();

        Set<String> set = new HashSet<>();

        for(int i=0; i<n; i++){
            String str=sc.next();

            set.add(str);
        }

        System.out.print(set.size());
        
    }
}

C++ Code:-

#include <bits/stdc++.h> // header file includes every Standard library
using namespace std;

int n;
string t;
set<string>s;
int main(){
    cin>>n;
    while(n--)cin>>t,s.insert(t);
    cout<<s.size()<<"\n";
}

JavaScript Code:-

// Your code here

function lottery(input) {
    const arr = input.trim().split('\n');
    const set = new Set(arr.slice(1))
    console.log(set.size)
}
lottery(require('fs').readFileSync('/dev/stdin', 'utf8'))

Python Code:-

// Your code here

N = int(input())
ans = set()
for _ in range(N):
    ans.add(input())
 
print(len(ans))


 If you like this article please do like subscribe and follow our page.

No comments:

Powered by Blogger.