# Background

A matryoshka doll (or Russian nesting doll) is a set of dolls that fit inside of each other. I've accidentally mixed up my collection of matryoshka dolls and I don't remember which one goes inside which.

# Objective

Given a list of unique strings, sort them into nested matryoshka dolls. Each string is an individual doll, and a matryoshka doll is a list of strings.

# Rules

Let min(a,b) be the lexicographic min of strings a and b. Let a ⊂ b denote that a is a substring of b. Then,

1. The list of matryoshka dolls must be sorted lexicographically
2. String a can fit into string b if a ⊂ b
3. If a ⊂ b and a ⊂ c, then a will go inside min(b,c)
4. If both a ⊂ c and b ⊂ c, but a ⊄ b b ⊄ a, then only min(a,b) will go inside c
5. If both a ⊂ c and b ⊂ c, and also a ⊂ b, then only b will go inside c. I.e., superstrings go before substrings so that the matryoshka isn't prematurely terminated.

# Examples

In:
hahaha, hah, lol, lololol, bahaha, bah, haha, ah

Out:
bahaha, bah, ah
hahaha, haha, hah
lololol, lol

In:
aa, aaaa, a, aaaaaaaaaa

Out:
aaaaaaaaaa, aaaa, aa, a

• First post here, please point out anything dumb / fixes needed. Commented Jan 16, 2018 at 1:22
• Welcome to PPCG! If you're not sure if the post is good enough, you can post it in the Sandbox first. Commented Jan 16, 2018 at 1:28
• It's not mandatory, just keep it here. The community like it. Commented Jan 16, 2018 at 1:42
• @sujeet in the future, try to post to the sandbox first. It's a place to get feedback about your challenges before you post them on the main site. Don't worry about it now, since this challenge seems fine as is, but it's something to consider for the future. Commented Jan 16, 2018 at 2:01
• What should be the result of ab, ba, aba, bab? By rule 3, both ab and ba should go into aba, and by rule 4, ba cannot go into either aba or bab. Commented Jan 16, 2018 at 10:28

# Python 2, 298 bytes

def f(x,E=enumerate):
o=[]
while any(x):
for k,p in E(x):
e=0
if sum(i(p,j)for j in x)<1:
for d,r in E(o):
if i(p,r[-1])*((r[-1]<e)or e==0):m,e=d,r[-1]
if e:o[m]+=[p]
else:o+=[[p]]
x[k]=''
print sorted(o)
i=lambda p,b:(b!=p)*any([p==b[j:j+len(p)]for j in range(len(b)-len(p)+1)])


Try it online!

-28 bytes with tips from @dylnan, bug find by @Dennis, and bug fix by @Mr.Xcoder

• 301 bytes. Just turned i into a lambda function and changed the variable name out to o. Commented Jan 16, 2018 at 6:09
• 297 bytes (E=enumerate) Commented Jan 16, 2018 at 6:14
• Functions have to be reusable, but the out variable never changes. Try it online! Commented Jan 16, 2018 at 14:09
• To fix that issue, 298 bytes. Also, out, 3-char variable name... Seriously :P? Commented Jan 16, 2018 at 15:43