Hackerrank Java Hashset Solution
1 min read

Hackerrank Java Hashset Solution

Hackerrank Java Hashset Solution

In computer science, a set is an abstract data type that can store certain values, without any particular order, and no repeated values(Wikipedia).  is an example of a set, but  is not a set. Today you will learn how to use sets in java by solving this problem.

You are given  pairs of strings. Two pairs  and  are identical if  and . That also implies  is not same as . After taking each pair as input, you need to print number of unique pairs you currently have.

Complete the code in the editor to solve this problem.

Input Format

In the first line, there will be an integer  denoting number of pairs. Each of the next  lines will contain two strings seperated by a single space.


  • Length of each string is atmost  and will consist lower case letters only.

Output Format

Print  lines. In the  line, print number of unique pairs you have after taking  pair as input.

Sample Input

john tom
john mary
john tom
mary anna
mary anna

Sample Output



  • After taking the first input, you have only one pair: (john,tom)
  • After taking the second input, you have two pairs: (john, tom) and (john, mary)
  • After taking the third input, you still have two unique pairs.
  • After taking the fourth input, you have three unique pairs: (john,tom), (john, mary) and (mary, anna)
  • After taking the fifth input, you still have three unique pairs.

Solution in java8

Approach 1.

Approach 2.

HashSet<String> hs = new HashSet<>();
for(int i=0;i<t;i++){
    hs.add(pair_left[i]+" "+pair_right[i]);

Approach 3.

        Set<String> set = new HashSet<>();
        for (int i=0; i<t; i++) {
            set.add(pair_left[i] +" "+ pair_right[i]);

Enjoying these posts? Subscribe for more

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.