You are given a list of strings logs, the lines of a corrupted log file. A valid line has the form YYYY-MM-DD HH:MM:SS LEVEL MESSAGE, where LEVEL is one of INFO, WARN or ERROR, and MESSAGE is a non-empty string that may contain spaces.
Some lines are malformed: they are missing fields, have an invalid timestamp, or use an unknown level. Other lines are valid but carry extra whitespace (leading or trailing spaces, or several spaces between fields). Clean and parse the file: normalize the whitespace, discard the malformed lines, and return the number of valid ERROR entries.
After whitespace is normalized, a line is valid only if all of these hold:
-
It starts with a well-formed timestamp
YYYY-MM-DD HH:MM:SS
.
-
The token right after the timestamp is exactly
INFO
,
WARN
or
ERROR
.
-
At least one more token, the message, follows the level.
Function Signature
def count_error_logs(logs: list[str]) -> int:
Rules
-
Normalize a line by removing leading and trailing whitespace and treating every run of whitespace as a single space. Extra whitespace alone never makes a line malformed.
-
The date and the time are the first two tokens. The date is four digits, a hyphen, two digits, a hyphen and two digits. The time is two digits, a colon, two digits, a colon and two digits. Digits are the ASCII characters
0
to
9
.
-
Only the shape of the timestamp is checked, not the field ranges, so
2024-13-40 25:61:61
counts as well-formed.
-
Level matching is case-sensitive:
error
and
Error
are unknown levels.
Constraints
-
1 <= len(logs) <= 10^4
-
Each
logs[i]
is a non-empty string.
Examples
Input: logs = ["2024-01-15 10:23:45 INFO Server started", "2024-01-15 10:24:01 ERROR Database connection failed", "BAD LINE WITHOUT TIMESTAMP", "2024-01-15 10:24:05 ERROR Retry attempt 1", "2024-01-15 10:24:10 WARN High memory usage"]
Output: 2
The database failure and the retry attempt are the two valid ERROR entries. The third line has no timestamp, so it is discarded, and the INFO and WARN lines are valid but are not errors.
Input: logs = ["2024-02-01 00:00:00 INFO boot", "2024-02-01 00:00:01 DEBUG ignored level", "2024-02-01 00:00:02 ERROR", "2024-02-01 00:00:03 ERROR something broke", " 2024-02-01 00:00:04 ERROR extra spaces "]
Output: 2
The DEBUG line has an unknown level and the 00:00:02 line has no message, so both are discarded. The last line normalizes to 2024-02-01 00:00:04 ERROR extra spaces, which is valid, so it joins something broke for a count of 2.
Input: logs = ["2024-03-10 09:15:00 error lowercase level", "2024-3-10 09:15:00 ERROR one-digit month", "2024-03-10 09:15:00 ERROR disk full", "2024-03-10T09:15:00 ERROR missing space", "2024-13-40 25:61:61 ERROR ranges not checked"]
Output: 2
The lowercase level, the one-digit month and the T separator each break the format. The disk full line is valid, and so is the last line, because its timestamp has the right shape even though the month and the time are out of range.