Given N dolls of size A1, A2 … AN.
A Matryoshka doll refers to a set of wooden dolls of strictly decreasing size, placed one inside the other. Any doll can contain only one doll directly inside it.
Output “YES” if it is possible to nest them all and have one doll on the outside and “NO” otherwise.
EXPLANATION:
If any two dolls have same size, we can never nest them together. Otherwise, we just sort them in decreasing order and nest them.
So, we just have to check if there are any two numbers same in a list.
We can do this in many ways:
sort and check adjacent elements. Complexity: O(N log N)
check for each pair of i,j if Ai == Aj. Complexity: O(N * N)
Mark flag[Ai], for all i and check each element of flag array. Complexity: O(MAX[Ai]).
Use set from STL in C++ and keep inserting in order. If same element find already answer is NO. Complexity: O(N log N).
An alternate solution to the problem could be to hash each doll size to a hash table. A set of dolls can’t be placed inside one another if more than one doll is of the same size. Before inserting a value in the hash table we check whether it’s already present; if already present we can say the set of dolls can’t be placed inside one another.
There is no need to sort the doll sizes. This solution is O(N).
Buying through Art Gifted by God ensures the World Missions, Charities and Art Projects we support, receive 10% commission from the proceeds of the Sales. 5% will be allocated annually by the World Missions Committee of Christ Church, Cheltenham and 5% by the artists to Art Projects 2015/16. When you buy from Christian Art Gifts, your painting is packaged and delivered direct from the artist’s studio. All arranged ‘hassle free’ by ourselves.