Logger Pattern Formatter

Difficulty: Hard · Topics: State Machine, Parsing, Formatting · Acceptance: 100.0% of 1 submissions

Difficulty: Hard  |  Tags: Parsing, State Machine, Formatting

Description

Implement a pattern-based message formatter (similar to Java's MessageFormat). The pattern contains literal text mixed with placeholders in the form {index} or {index, type} or {index, type, style}.

Placeholder syntax: {argumentIndex [, formatType [, formatStyle]]}

Implement:

applyPattern(pattern) → parsed format object
format(pattern, args...) → String

Examples

Example 1 — Simple:

Input:
  pattern = "Hello, {0}! You have {1} messages."
  args = ["Alice", 5]

Output: "Hello, Alice! You have 5 messages."

Example 2 — Typed:

Input:
  pattern = "Date: {0, date}. Amount: {1, number, currency}"
  args = [Date(2026-02-19), 1234.56]

Output: "Date: Feb 19, 2026. Amount: $1,234.56"

Example 3 — Escaped braces:

Input:
  pattern = "Use '{'curly braces'}' like this: {0}"
  args = ["test"]

Output: "Use {curly braces} like this: test"

Example 4 — Invalid pattern:

Input:  pattern = "Hello, {0"

Output: Error — "Unmatched braces in the pattern."

Supported Format Types

TypeStyles
numberdefault, currency, percent, integer, custom pattern
dateshort, medium, long, full, custom SimpleDateFormat
timeshort, medium, long, full, custom SimpleDateFormat
choiceChoiceFormat pattern

Constraints

Hints

Hint 1

Build a state machine with segments: RAW, INDEX, TYPE, MODIFIER. Switch states on encountering {, }, and ,.

---

## Algorithms

Practice this problem

Related problems