Set Union

Given two sets of integers, print the set containing the union of the two input sets. For example, g…

Click here to read the complete problem statement.

If you need help solving this problem, mention your approach and ask specific questions. Please avoid sharing your code and asking the Community to figure out “what’s wrong”. why WA?

Your code is fine except for the printing part. You were printing too many spaces in between and one extra space at the end.

I have made a submission using your code with a small modification at the end.

This SO should help: python - Print a list of space-separated elements - Stack Overflow

1 Like

I’m new in python. Thanks.

using namespace std;

int main()
    int n, m, hit=1;
    int *set1, *set2;
    vector<int> v(m+n);
    vector<int>::iterator it, ls;

    set1 = (int *)malloc(sizeof(int)*n);
    set2 = (int *)malloc(sizeof(int)*m);

    for(int i=0; i<n; i++) {
    for(int i=0; i<m; i++) {

    ls = set_union(set1, set1+n, set2, set2+m, v.begin());

    for(it = v.begin(); it != ls; it++) {
        if(hit == 1) {
            hit = 0;
        else {
            cout<<" "<<*it;

    return 0;

why I am getting WA for this code?

k,l= map(int,input().split())
o= {int(x) for x in input().split()}
p= {int(y) for y in input().split()}
x= o.union(p)
for z in x:
    print(z, end=" ")

#where is my problem ?

I tried to manipulate your code many ways but I just couldn’t fix it.
The std::set_union seems to be very problematic.

You can just use std::set from C++ STL;
Here is my code,

#include <bits/stdc++.h>
using namespace std;

int main()
    int n, m;
    set <int, less <int> > s;
	int input, k = m+n;

	for(int i = 0; i < k; ++i) {
		cin >> input;

	auto it = s.begin();
	cout << *it;
    for(it++; it != s.end(); it++)
    	cout << " " << *it;
    cout << endl;
    return 0;
1 Like

@corrupted_brain , the union function just appends new elements from the second set after the last element of the first set; thus , you have to sort the answer.
try to replace the line with this.

x = sorted(list(o.union(p)))
1 Like

k,l= map(int,input().split())
o= {int(x) for x in input().split()}
p= {int(y) for y in input().split()}
x= sorted(list(o.union(p)))
for z in x:
print(z, end=" ")

Again My code still Wrong :disappointed:
What should I do

It shouldn’t be wrong @corrupted_brain

Oh! it seems to be that you are printing an extra space at the end of every line @corrupted_brain. Fix it and your code should be accepted.

@touhidur I have become fail to find my wrong
Where is it printing a extra space. ?

:worried: Find me my problem plz @touhidur

@corrupted_brain i run your code in Ideone here. And tested it on uDebug. Here is what I got. (as expected)

A space at the end cannot be seen. If you still cannot find your problem, then I will request you not to make any more posts in this topic. Others might have problems too, so the topic must not be overflown. You can always message me on Toph here. Just click the message button and you can find me. I will try to help you within my limits.

and also see the link that overly_detached has shared.

also you can click the uDebug button in the right of the problem name and your output in uDebug.

RE: Click the image to zoom it.

package javaapplication31;
import java.util.ArrayList;
import java.util.Scanner;
public class solution {

    public static void main(String[] args) {
        Scanner sc= new Scanner (;
        ArrayList<Integer> set1 = new ArrayList<Integer>();
        ArrayList<Integer> set2 = new ArrayList<Integer>(); 
        int i;
        set1.add( sc.nextInt());
        ArrayList<Integer> union =new ArrayList<Integer>();
        System.out.println("union set");
        union.addAll( set1);

i tried this code
but my loop is running to infinity please help

@ph3nixsabit Please see the sample input given in the problem statement:

5 5
1 3 5 7 8
2 3 4 7 9

Notice that the first line has two integers. These two integers tell you how many numbers are there in the following two lines (i.e. members of set 1 and set 2).

Looking at your code, I can see that you didn’t take this into consideration.

Your code should first take input the two integers (say N and M). Then it should run a loop with N iterations taking the input for set 1. Then it should run a loop with M iterations taking the input for set 2.

Finally, you should compute the union of these two sets and then print the contents of this resulting set. You should not print anything else.

@touhidur I think @ph3nixsabit didn’t intend to submit this code. He has already solved many problems on Toph. Those println calls are probably there for him to help debug/run the problem locally.

Imagine you are trying to test a C++ code in console fill up a vector from the input with the thought of values after that using EOF input like this:

while ( cin >> num ) {
    vector.push_back( num ) ;

what will happen?

As expected your code will take inputs as long as it crashes as you input some unexpected character, or will keep taking inputs until it exhausts your memory.

The hasNext() method used by @ph3nixsabit bro works simillarly.

hasNext() method returns true if there are some more characters left when charcters are read from an input file.
if the input reaches the End Of File of EOF shortly.

But it is when one is taking inputs from an input file, the length of which is probably not infinity.
So, when it reaches the End of the input file, it will detect EOF and return the value false.

Since, in Online Judges, the input is literally taken from the input files they have. Thus, it will exit the loop successfully.

But it is not the same for console because there is actually no limit to how much text ia printed or written in the console because the console erases previous texts automatically if the output text become big enough. Thus, there is no EOF in console and hasNext() does not work. And so it feels like an infinity loop.

I had taken into consideration that @ph3nixsabit bro might have shared the code for testing purposes only. And I know that he knows how to solve a problem in a Toph. But, his codes are usually more clear and thoughts are reflected in them more clearly. So, I didn’t expected it to be like that.

I hope that you will understand how I feel with the determination of fixing a code and finding it poorly written bro @hjr265 and bro @ph3nixsabit.

And ofcourse, sorry for the sudden odd reply. I will delete it.

I understand. Thanks for the detailed reply.

Let’s just be helpful to everyone. :slight_smile:

If I see that a lot of people are facing from similar issues (e.g. new sport programmers are having trouble taking input) I may prepare some tutorials for them specifically and share them on Toph. That way, in the future, we can always point them to those tutorials whenever needed.

1 Like

Why wrong answer at test case 2??
here is my code:

k, l = map(int, input().split())
o = [int(x) for x in input().split()]
p = [int(y) for y in input().split()]
x = sorted(o + p)
y = []
for i in x:
    if i not in y:
for z in y:
    if x.index(z) < (len(x)-1):
        print(z, end=" ")
print(x[-1], end="")

Can you please explain your code/approach?

You do not need the last loop. (line 9 to 11)
Just sort the list y and print it.
Cause after the first loop (line 6 to 8), all the elements of the set union is already present in list y but not in sorted order.
So, you just need to sort and print them.