Problem · String

Generate Table of Contents

Learn this problem
EasyJPMorgan Chase logoJPMorgan ChaseFULLTIMEOA

Problem statement

You are given a document as an array of strings.

  • A chapter is any line that starts with # .
  • A section is any line that starts with ## and belongs to the most recent chapter.
  • All other lines should be ignored.

Build a table of contents using chapter numbers 1, 2, 3, ... and section numbers such as 1.1, 1.2, 2.1, and so on. Return the result as a String[].

Function

generateTableOfContents(text: String[]) → String[]

Examples

Example 1

text = ["# Algorithms", "This chapter covers the most basic algorithms.", "## Sorting", "Quicksort is fast and widely used in practice", "Merge sort is a deterministic algorithm", "## Searching", "DFS and BFS are widely used graph searching algorithms", "Some variants of DFS are also used in game theory applications", "# Data Structures", "This chapter is all about data structures", "It's a draft for now and will contain more sections in the future", "# Binary Search Trees"]return = ["1. Algorithms", "1.1. Sorting", "1.2. Searching", "2. Data Structures", "3. Binary Search Trees"]

Only chapter and section markers contribute to the table of contents, and sections are numbered relative to the latest chapter.

Constraints

  • 1 <= text.length <= 1000
  • 1 <= text[i].length <= 100
  • The first valid heading in the document is guaranteed to be a chapter.

More JPMorgan Chase problems

drafts saved locally
public String[] generateTableOfContents(String[] text) {
  // write your code here
}
text["# Algorithms", "This chapter covers the most basic algorithms.", "## Sorting", "Quicksort is fast and widely used in practice", "Merge sort is a deterministic algorithm", "## Searching", "DFS and BFS are widely used graph searching algorithms", "Some variants of DFS are also used in game theory applications", "# Data Structures", "This chapter is all about data structures", "It's a draft for now and will contain more sections in the future", "# Binary Search Trees"]
expected["1. Algorithms", "1.1. Sorting", "1.2. Searching", "2. Data Structures", "3. Binary Search Trees"]
checking account