I came across a little problem that looks very easy but requires a bit more thought than I first assumed. It can also be solved in many different ways and, I think, would be a perfect interview question. So what solution would you write down?
Your input is a stream of pairs (x, y)
, with each x
and y
on a separate line. A short example, starting with the pair (fruit, apple)
:
fruit
apple
book
Harry Potter
book
Bible
vehicle
car
You're asked to print the first n
pairs, where adjacent pairs that all have the same x
are counted as one. So, for n=2
you should output these lines:
fruit
apple
book
Harry Potter
book
Bible
What's your most elegant way to solve this problem (in a language of your choice)?