Rewritten algorithm for finding unique directory path