911. Online Election

1. Description

You are given two integer arrays persons and times. In an election, the ith vote was cast for persons[i] at time times[i].
For each query at a time t, find the person that was leading the election at time t. Votes cast at time t will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins.
Implement the TopVotedCandidate class:

  • TopVotedCandidate(int[] persons, int[] times) Initializes the object with the persons and times arrays.
  • int q(int t) Returns the number of the person that was leading the election at time t according to the mentioned rules.

2. Example

Example 1:
[“TopVotedCandidate”, “q”, “q”, “q”, “q”, “q”, “q”]
[[[0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]], [3], [12], [25], [15], [24], [8]]
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]);
topVotedCandidate.q(3); // return 0, At time 3, the votes are [0], and 0 is leading.
topVotedCandidate.q(12); // return 1, At time 12, the votes are [0,1,1], and 1 is leading.
topVotedCandidate.q(25); // return 1, At time 25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the most recent vote.)
topVotedCandidate.q(15); // return 0
topVotedCandidate.q(24); // return 0
topVotedCandidate.q(8); // return 1

3. Note

  • 1 <= persons.length <= 5000
  • times.length == persons.length
  • 0 <= persons[i] < persons.length
  • 0 <= times[i] <= $10^9$
  • times is sorted in a strictly increasing order.
  • times[0] <= t <= $10^9$
  • At most $10^4$ calls will be made to q.

4. Solutions

n = persons.size()
Time complexity: O(n)
Space complexity: O(n)

class TopVotedCandidate {
private:
    vector<int> vote_times;
    map<int, int> winner_at_time;

public:
    TopVotedCandidate(vector<int> &persons, vector<int> &times) {
        vote_times = times;

        map<int, int> candidate_votes;
        int last_voted_candidate = INT_MAX;
        int most_voted_canddate = INT_MIN;
        for (int i = 0; i < times.size(); ++i) {
            ++candidate_votes[persons[i]];

            if (candidate_votes[persons[i]] >= candidate_votes[most_voted_canddate]) {
                most_voted_canddate = persons[i];
            }

            winner_at_time[times[i]] = most_voted_canddate;
        }
    }

    int q(int t) {
        // since the size of persons is only 5000
        // we can calculate all possible values to reach a O(1) time complexity

        int max_valid_time;
        for (int left = 0, right = vote_times.size(); left < right;) {
            int mid = (left + right) / 2;

            vote_times[mid] <= t ? max_valid_time = vote_times[mid], left = mid + 1 : right = mid;
        }

        return winner_at_time[max_valid_time];
    }
};
comments powered by Disqus