Skip to the code
cf.
+10 XP

#687 Live Poll Tally

easy

A live poll has options numbered 0 to n - 1. Votes keep arriving, and the results panel shows totals for groups of neighboring options. Write a class PollTally:

  • new PollTally(n) starts every option at 0 votes.
  • vote(option, count) adds count votes to option.
  • total(left, right) returns the votes for options left to right, inclusive.

Both methods should be O(log n).

Each example lists the calls in order, then each call's arguments. The first call creates the object with new PollTally(…); the output lists what each call returns (null for the constructor and for methods that return nothing).

Example 1

Input: ["PollTally","vote","vote","vote","total","total"]
[[5],[0,3],[2,4],[4,1],[0,2],[1,4]]
Output: [null,null,null,null,7,5]

Options 0 to 2 have 3 + 0 + 4 = 7 votes; options 1 to 4 have 0 + 4 + 0 + 1 = 5.

Example 2

Input: ["PollTally","total"]
[[3],[0,2]]
Output: [null,0]

No votes yet.

Constraints

  • 1 <= n <= 10^5
  • 1 <= count <= 1000
  • 0 <= left <= right < n
  • At most 10^5 calls.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).