You are given a log of operations performed on a system, where each operation is represented by a string. Given an integer k, return the k most frequently performed operations from the log.
The returned list must be sorted in descending order of frequency. If two operations have the same frequency, they must be sorted in lexicographical (alphabetical) order to break ties.
Function Signature
def top_k_frequent_operations(operations: list[str], k: int) -> list[str]:
Rules
-
The frequency of an operation is the number of times its exact string appears in
operations
.
-
Return exactly
k
distinct operation names, highest frequency first.
-
Operations with equal frequency appear in ascending lexicographical order. With this tie rule the answer is unique.
Constraints
-
1 <= len(operations) <= 10^5
-
1 <= len(operations[i]) <= 50
-
operations[i]
consists of lowercase English letters.
-
k
is between 1 and the number of unique operations in
operations
, inclusive.
Examples
Input: operations = ["login","logout","login","view","login","logout","view","delete"], k = 2
Output: ["login","logout"]
"login" appears 3 times, "logout" and "view" 2 times each, and "delete" once. "login" takes the first slot, and "logout" gets the second because it ties with "view" at 2 and comes first alphabetically.
Input: operations = ["a","b","c","a","b","a"], k = 3
Output: ["a","b","c"]
The frequencies are a=3, b=2 and c=1, so sorting by descending frequency gives ["a","b","c"] with no ties to break.