Parse and Query Server Logs
Learn this problemProblem statement
Parse possibly malformed server-log lines, then apply a query and return all matching valid logs.
A valid input line has exactly four tab-separated fields:
- a timestamp in the exact form
YYYY-MM-DDTHH:MM:SSZ, - one of
DEBUG,INFO,WARN, orERROR, - a nonempty service token containing only ASCII letters, digits, underscores, or hyphens, and
- a nonempty message containing no tab.
A timestamp is syntactically valid when each numeric field has the displayed width, the year is from 1970 through 9999, the month is 01 through 12, the day is 01 through 31, the hour is 00 through 23, and minutes and seconds are 00 through 59. Discard every line that fails this grammar.
If the message contains a standalone token user_id=value, capture the first such value. The value must contain only ASCII letters, digits, underscores, or hyphens. Otherwise the user identifier is empty.
The query may begin with any of the operators level:value, service:value, userid:value, start:YYYY-MM-DD, and end:YYYY-MM-DD, each at most once. Operator names and level values are case-insensitive; service, user, and message matching are case-sensitive. The start date is inclusive and the end date is exclusive. Text after the leading operators is a case-sensitive message substring filter.
Retain matching logs in input order. Return a string array whose first element is the decimal match count. Each remaining element is the canonical form timestamp TAB level TAB service TAB message TAB userId, using the uppercase level and an empty final field when no user identifier exists.
Function
parseAndQueryServerLogs(logs: String[], query: String) → String[]Examples
Example 1
logs = ["2026-08-07T09:30:00Z\tERROR\tapi\trequest failed user_id=u7","bad line","2026-08-07T10:00:00Z\tINFO\tapi\trequest recovered","2026-08-08T01:00:00Z\tERROR\tworker\tjob failed user_id=u8"]query = "level:error service:api start:2026-08-07 failed"return = ["1","2026-08-07T09:30:00Z\tERROR\tapi\trequest failed user_id=u7\tu7"]Only the first valid line satisfies the level, service, date, and message filters. The malformed line is discarded before querying.
Constraints
1 <= logs.length <= 200000- Each line and the query contain at most 2000 characters.
- Service names and user identifiers contain at most 64 characters.
- The query is valid under the stated leading-operator grammar, with tokens separated by single ASCII spaces.