1444. Always Ahead Count
In a student-council election, candidate A receives a ballots and candidate B receives b ballots. The ballots are counted one by one in some order, and the order of the individual ballots only matters through which candidate each one names, so an ordering is a sequence of a letters A and b letters B.
Return how many orderings keep A strictly ahead of B after every non-empty prefix of the count (so A leads from the first ballot on and never ties), modulo 1000000007. If a <= b, the answer is 0. Trying every ordering is hopeless; a closed form with factorials runs in O(a + b) time and O(1) extra space.
Example 1
- Input:
- a = 2, b = 1
- Output:
- 1
- Explanation:
Of the orderings AAB, ABA and BAA only AAB keeps A strictly ahead throughout, so the answer is 1.
Example 2
- Input:
- a = 3, b = 1
- Output:
- 2
- Explanation:
AAAB and AABA keep A strictly ahead throughout, but ABAA ties after two ballots and BAAA starts behind, so the answer is 2.
Example 3
- Input:
- a = 2, b = 2
- Output:
- 0
- Explanation:
The counts are tied, so A cannot finish strictly ahead and the answer is 0.
Constraints
0 ≤ a, b ≤ 106
Answer modulo 1000000007. Products of residues exceed 253, so use BigInt or a split multiplication in JavaScript.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,600 msC++ 400 msJava 800 msJavaScript 800 msTypeScript 800 ms
Expected complexity
- Time
- O(a + b)
- Space
- O(1)