Try this recursive query which is linear-time in input (timing study [here][1]) prefixTrie := Query[GroupBy[First], If[First@# == {}, First@#, byPrefix[#]] &, Rest] Variations on the above are possible and useful (see Antonov's Trie page [here][2] developed in 2013 but without Dataset). For simplicity the above assumes filenames have been split into path component lists, eg `"a/b/c"` --> `{"a","b","c"}` after import: `flatFiles = FileNames["*.gsheet", "~/Google Drive/...", Infinity] // Dataset` Then: flatFiles[All, StringSplit[#, "/"] &][prefixTrie] [1]: http://mathematica.stackexchange.com/questions/69942/10-0-2-breaks-a-recursive-trie-query [2]: https://mathematicaforprediction.wordpress.com/2013/12/06/tries-with-frequencies-for-data-mining/