It's a very easy interview question really. Because you know there's at most 1025 distinct integers in the first set, you can use that number of bits to represent whether each of those numbers is found or not in input sets. So, if you want the answer to print each distinct number exactly once, the logic is:
- zero all the 1025 bits in bitset A
- for each number in the first set, set the corresponding bit in A
- zero all the 1025 bits in bitset B
- for each number int he second set, set the corresponding bit in B
- for i from 0 to 1024: if that bit is set in both A and B, output i as part of your answer
Now, to create a bitset of 1025 bits might not be supported directly by your language, so what you sometimes have to do is use an array of bytes, each of which has 8 bits. Then, say you want to set bit "k", you'll find the byte at index k / 8, then set the bit at position k % 8. To do the latter, you have to convert from a bit position (0 through 7) to a bit value (bit 0 represents value 1, bit 1 value 2, bit 2 value 4... bit 7 value 128 - all the powers of two). To get these values, you take the number 1 and bitshift it left by the "bit position". So, 1 << 0 is still 1, while 1 << 7 is 128. You can then:
- ask if a byte has that bit on by ANDing the shifted value with the byte's value and seeing if you get a non-0 result - for example, in C and C++:
if (array[k / 8] & (1 << (k % 8))) ...it's on...
- record a 1 at a particular bit position in a byte by ORing the value with the byte - in C and C++:
array[k / 8] |= (1 << (k % 8));
There are more efficient ways to do this if there happens to be a lot less than 1025 values in either set, but this is a good general solution.