FastPrepFormat CSV Rows as an ASCII Table
Problem · Array

Format CSV Rows as an ASCII Table

Learn this problem
EasyAmazon logoAmazonNEW GRADPHONE SCREEN
See Amazon hiring insights

Problem statement

The array rows contains an in-memory CSV table. Every row has the same number of comma-separated fields. Fields use the simple unquoted CSV subset described in the constraints.

Format the data as a readable ASCII table:

  • Set each column's width to the longest field in that column.
  • Left-align every field and pad it with spaces to its column width.
  • Put one space on each side of every field, separate columns with |, and put | at both ends.

Return one formatted string per input row. Do not add horizontal border rows.

Function

formatCsvTable(rows: String[]) → String[]

Examples

Example 1

rows = ["name,age","Ada,36","Grace,37"]return = ["| name  | age |","| Ada   | 36  |","| Grace | 37  |"]

Grace sets the first-column width to five and age sets the second-column width to three.

Example 2

rows = ["a,b","long,x","mid,xyz"]return = ["| a    | b   |","| long | x   |","| mid  | xyz |"]

The second row determines the first width, while the third determines the second width.

Example 3

rows = ["solo","x"]return = ["| solo |","| x    |"]

A one-column table still has a pipe at each end.

Constraints

  • 1 <= rows.length <= 1000.
  • Every row has between 1 and 20 fields, and all rows have the same number of fields.
  • Each field has length at most 50 and contains only ASCII letters, digits, and spaces.
  • Fields may be empty but have no leading or trailing spaces.
  • Fields do not contain commas, quotes, pipes, or line breaks.

More Amazon problems

drafts saved locally
public String[] formatCsvTable(String[] rows) {
  // write your code here
}
rows["name,age","Ada,36","Grace,37"]
expected["| name | age |", "| Ada | 36 |", "| Grace | 37 |"]
checking account