#3021
Alice and Bob Playing Flower Game
MediumMathMathematical CountingParity Checking
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(1) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(1)Space O(1)
Instead of checking every pair, we can derive the count of valid pairs based on the parity of n and m. The key insight is that Alice wins if x and y have different parities.
⚙️
Algorithm
4 steps- 1Step 1: Calculate the number of odd and even numbers in the range [1, n].
- 2Step 2: Calculate the number of odd and even numbers in the range [1, m].
- 3Step 3: The valid pairs are formed by combining odd x with even y and even x with odd y.
- 4Step 4: Return the sum of these combinations.
solution.py6 lines
1def countWinningPairs(n, m):
2 odd_n = (n + 1) // 2
3 even_n = n // 2
4 odd_m = (m + 1) // 2
5 even_m = m // 2
6 return odd_n * even_m + even_n * odd_mℹ
Complexity note: This complexity is constant because we are performing a fixed number of arithmetic operations regardless of the input size.
- 1Alice wins if x and y have different parities.
- 2Counting odds and evens allows for a quick calculation of valid pairs.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.