Split an Escaped Record

MediumArrays & Hashing

Problem

A legacy export writes each record as its fields joined by commas. Since fields may contain commas, the format escapes them with a caret: a literal , inside a field is written ^, and a literal ^ is written ^^. Any other character is written as is.

Given a valid record, return its fields in order. A record always has at least one field, so the empty string is a single empty field.

Example 1

Input:
record = "red,gr^,een,blue"
Output:
["red", "gr,een", "blue"]

'^,' is a literal comma, so 'gr,een' is one field.

Example 2

Input:
record = "a^^b,,c"
Output:
["a^b", "", "c"]

'^^' is a literal caret, and ',,' surrounds an empty field.

Example 3

Input:
record = ""
Output:
[""]

Constraints

  • 0 ≤ record.length ≤ 10^5
  • Every '^' is followed by ',' or '^' (the record is valid).

Hint

Show the first hint

Is a comma always a separator? How can you tell?

Walkthrough

How to approach it

01Clarify before coding

  • Which characters can be escaped? Only ',' and '^'.
  • How is an empty record handled? It is one empty field, so the result is [""].
  • Can a record end with a comma? Yes, which produces a trailing empty field.

02Brute force

Split on every ',' and merge a piece with the next when it ends with '^'.

Cost: Linear but incorrect: in '^^,' the caret before the comma is itself escaped, so 'ends with ^' is the wrong test; fixing it means counting runs of carets.

The rest of the walkthrough is in the app

The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.

This problem is part of Pro.