Site icon Console Flare Blog

HackerRank Set Union Python Solution Explained in 5 Easy Steps

HackerRank Set Union Python solution explained with code example

HackerRank Set Union Python Solution Explained in 5 Easy Steps

The HackerRank Set Union Python Solution might look simple at first, but it’s a great example to understand how sets work in Python.
If you’re learning Python or preparing for coding interviews, this challenge helps you practice real problem-solving logic.

The Meaning of the Question

Some students read the English paper. Some people read the French one. Some people read both.
You need to find out how many students read at least one paper.

If a student is on both lists, count them only once.
That’s all there is. Not hard, right?

So, in short, we combine two sets.

Before Coding: What is .union() Function?

In Python, a set can only contain unique values. The union() function joins two sets and automatically eliminates duplicates.

Example:

A = {1, 2, 3}

B = {3, 4, 5}

print(A.union(B))

Output:

{1, 2, 3, 4, 5}

Clean results, no duplicates.

Input Format for the HackerRank Set Union Python Solution

Four lines of input will be given to you:

  1. Number of subscribers to English newspapers
  2. Number of subscribers to English newspapers
  3. The quantity of French newspaper readers
  4. Subscriber rolls for French newspapers

Printing the number of distinct students who read at least one newspaper is your aim.

Full Code: HackerRank Set Union Python Solution

n = int(input())

s1 = set(input().split())

m = int(input())

s2 = set(input().split())

print(len(s1.union(s2)))

Now let’s go through it line by line.

Line-by-Line Explanation

Line 1:

n = int(input())

Reads the number of subscribers in English.
Although HackerRank requires it for input format, we don’t use it afterwards.

Line 2:

s1 = set(input().split())

Takes English roll numbers.
.split() separates the numbers by spaces.
set() removes duplicates.

Line 3:

m = int(input())

French subscribers face the same issue.

Line 4:

s2 = set(input().split())

keeps a set of French roll numbers in storage.

Line 5:

print(len(s1.union(s2)))

.union() joins both sets.

The number of unique roll numbers that are left is counted by len().

Example Run of HackerRank Set Union Python Solution

Input:

9

1 2 3 4 5 6 7 8 9

9

10 1 2 3 11 21 55 6 8

Output:

13

A total of 13 pupils read at least one newspaper.

In a Brief Summary

What were we doing, then?

Review both lists.
created sets out of them.
Merged using.union()
Len() was used to count the number of distinct numbers.

Visit YouTube to View the Complete Solution

Check out my YouTube tutorial, where I run and walk through this exact code in real time, if you want a step-by-step video explanation.

YouTube Video:-


Do you want to learn more? Here are a few places to visit:

Python Sets Documentation

Related Post:

 

Console Flare

Exit mobile version