Given a list of log entries logs, where each entry is a list [timestamp, event], and an integer window, sort the log entries by timestamp and find the most frequent pair of events that occur within the given time window.
A pair of events (A, B) is considered to occur within the time window if the absolute difference between their timestamps is less than or equal to window. The pair (A, B) is treated the same as (B, A).
Return the most frequent event pair as a sorted list of two event names. If there are ties in frequency, return the lexicographically smallest pair.
Function Signature
def most_frequent_event_pair(logs: list[list], window: int) -> list[str]:
Rules
-
Frequency counts pairs of log entries. Every two different entries whose timestamps differ by at most
window
add one to the pair of their event names. An entry is never paired with itself.
-
The two names in a pair may be equal, so
(error, error)
is a valid pair when two
error
entries are close enough in time.
-
Entries with equal timestamps are within the window of each other.
-
The entries in
logs
may be in any timestamp order.
-
Write each pair with its two names in ascending order. On a tie in frequency, compare pairs by first name, then by second name, using plain string comparison, and return the smallest.
Constraints
-
1 <= len(logs) <= 10^5
-
Each log entry is
[timestamp, event]
, where
timestamp
is a non-negative integer and
event
is a non-empty string of lowercase letters.
-
0 <= timestamp <= 10^9
-
1 <= window <= 10^9
-
There is at least one valid pair within the time window.
Examples
Input: logs = [[1,"login"],[2,"click"],[3,"login"],[10,"logout"],[11,"click"]], window = 2
Output: ["click","login"]
Within a window of 2, the qualifying entry pairs are times (1, 2) login and click, (1, 3) login and login, (2, 3) click and login, and (10, 11) logout and click. As sorted pairs, (click, login) appears 2 times, while (login, login) and (click, logout) appear once each, so the answer is ["click","login"].
Input: logs = [[5,"error"],[6,"warn"],[7,"error"],[8,"warn"],[20,"info"]], window = 3
Output: ["error","warn"]
Within a window of 3, the entries at times (5, 6), (5, 8), (6, 7) and (7, 8) each pair error with warn, (5, 7) pairs error with error, and (6, 8) pairs warn with warn. The entry at time 20 is too far from all the others. (error, warn) appears 4 times, more than any other pair.
Input: logs = [[5,"beta"],[1,"zeta"],[2,"alpha"],[6,"alpha"]], window = 1
Output: ["alpha","beta"]
Sorted by time, the entries are zeta at 1, alpha at 2, beta at 5 and alpha at 6. Only times (1, 2) and (5, 6) are within 1 of each other, which gives (alpha, zeta) and (alpha, beta) once each. On the tie, ["alpha","beta"] is smaller because "beta" comes before "zeta".