Count substrings and generate TOC | J.P. Morgan Interview Question