Count substrings and generate TOC
J.P. MorganSoftware Engineer · Technical ScreenLast updated
This question evaluates string processing, pattern recognition, and parsing competencies—covering counting and grouping in binary substrings and structured line parsing and numbering for a table of contents—within the Coding & Algorithms domain.
Solve the following two coding problems.
- Count valid binary substrings
Given a string s consisting only of '0' and '1', count how many substrings satisfy both conditions:
- The substring contains the same number of
0s and1s. - All
0s in the substring are contiguous, and all1s in the substring are contiguous.
In other words, a valid substring must consist of exactly two consecutive groups, such as "0011", "1100", "01", or "10".
Return the total number of valid substrings.
- Generate a table of contents
You are given an array of strings lines, where each element represents one line in a document. Build a table of contents using the following rules:
- A line starting with
"##"is a section and belongs to the most recent chapter. - Otherwise, a line starting with
"#"is a chapter. - All other lines should be ignored.
Number chapters and sections in the order they appear:
- A chapter should be output as
"<chapter_number>. <title>" - A section should be output as
"<chapter_number>.<section_number>. <title>"
When a new chapter appears, its section numbering starts again from 1.
Return the generated table of contents as an array of strings.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.