1358. Partial Ballot Ranking

A club holds a vote in which every ballot ranks some teams from best to worst by listing distinct capital letters, one letter per team, and a ballot may name only a few teams. A team takes part in the contest if its letter shows up on at least one ballot. A team's count at rank r is the number of ballots that place it exactly in position r. Order the teams by most first-place votes, then by most second-place votes, and so on through twenty-sixth place; if two teams tie at every position, the earlier letter of the alphabet goes first. Return all teams in this order as one string. Aim for O(total ballot length + 26 * 26 * log 26) time.

Example 1

Input:
ballots = ["MKP","KPM","KMP","MPK"]
Output:
"KMP"
Explanation:

K and M tie at every rank, so the earlier letter K goes first; P never wins a first place, so it is last.

Example 2

Input:
ballots = ["D","E","DE"]
Output:
"DE"
Explanation:

D has two first-place votes and E has one, so D is ahead.

Example 3

Input:
ballots = ["HG","GH"]
Output:
"GH"
Explanation:

G and H tie in both positions, so alphabetical order puts G first.

Constraints

1 ≤ n ≤ 1000

each ballot has 1 to 26 distinct letters 'A'-'Z'

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(total length + 26^2 log 26)
Space
O(26^2)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…