Split only at top-level commas

Problem

Implement split_top_level(text). Split at commas whose parenthesis depth is zero, trim surrounding whitespace in each field, preserve empty fields, and raise ValueError for unbalanced parentheses. Parentheses may be nested; quotes and escapes are outside the input contract.

Reveal answer or reference solution

Scan once while maintaining a depth counter. An opening parenthesis increments depth, a closing parenthesis decrements it, and a comma ends a field only when depth is zero. Negative depth or nonzero final depth is invalid. The scan is O(n)O(n) time, excluding the returned strings.

def split_top_level(text: str) -> list[str]:
    fields: list[str] = []
    start = 0
    depth = 0
    for index, character in enumerate(text):
        if character == "(":
            depth += 1
        elif character == ")":
            depth -= 1
            if depth < 0:
                raise ValueError("unbalanced parentheses")
        elif character == "," and depth == 0:
            fields.append(text[start:index].strip())
            start = index + 1
    if depth != 0:
        raise ValueError("unbalanced parentheses")
    fields.append(text[start:].strip())
    return fields

Public tests

  • split_top_level("a,(b,c),d") → ['a', '(b,c)', 'd']
  • split_top_level(" f(a,(b,c)) , , z ") → ['f(a,(b,c))', '', 'z']
  • split_top_level("") → ['']
  • split_top_level("a),b") → raises ValueError
  • split_top_level("a,(b,c") → raises ValueError
Outcome

Previous attempts

Loading attempts saved in this browser…

    Review Screening Results