Online Election — LeetCode 911 Python Solution

MediumDesignArrayHash TableBinary Search
Problem
#911
Reading time
4 min

The problem

You are given two integer arrays persons and times. In an election, the ith vote was cast for persons[i] at time times[i].

Example

Input
["TopVotedCandidate", "q", "q", "q", "q", "q", "q"]
Output
[null, 0, 1, 1, 0, 0, 1]
Explanation
TopVotedCandidate topVotedCandidate = new TopVotedCandidate([0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]);

Python solution

Python
class TopVotedCandidate:

    def __init__(self, persons: List[int], times: List[int]):
        cnt = Counter()
        self.times = times
        self.wins = []
        cur = 0
        for p in persons:
            cnt[p] += 1
            if cnt[cur] <= cnt[p]:
                cur = p
            self.wins.append(cur)

    def q(self, t: int) -> int:
        i = bisect_right(self.times, t) - 1
        return self.wins[i]


# Your TopVotedCandidate object will be instantiated and called as such:
# obj = TopVotedCandidate(persons, times)
# param_1 = obj.q(t)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Binary Search

Halve the search space each step — over an array, or over the answer itself. LeetCode 911. Online Election is filed here because LeetCode tags it Binary Search, which is the vocabulary this hub collects.

The binary search guide has the Python template for the pattern and the 254 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 911. Online Election?
LeetCode 911. Online Election is rated Medium on LeetCode.
What is the time complexity of LeetCode 911. Online Election?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 911. Online Election?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 911. Online Election cover?
LeetCode 911. Online Election is tagged Design, Array, Hash Table and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview