Alice and Bob Playing Flower Game - Problem

Alice and Bob are playing a turn-based game on a field with two lanes of flowers between them. There are x flowers in the first lane and y flowers in the second lane.

Game Rules:

  • Alice takes the first turn
  • In each turn, a player must choose one lane and pick exactly one flower from that lane
  • The player who removes the last flower (making both lanes empty) wins the game

Given two integers n and m, count the number of pairs (x, y) where:

  • Alice wins the game with optimal play
  • 1 ≤ x ≤ n
  • 1 ≤ y ≤ m

Input & Output

Example 1 — Small Grid
$ Input: n = 3, m = 2
Output: 3
💡 Note: Alice wins for pairs: (1,2), (2,1), (3,2). These have odd sums: 3, 3, 5 respectively.
Example 2 — Symmetric Case
$ Input: n = 5, m = 4
Output: 10
💡 Note: Odd numbers 1-5: {1,3,5} (3 values), Even numbers 1-4: {2,4} (2 values). Total: 3×2 + 2×2 = 10.
Example 3 — Minimum Case
$ Input: n = 1, m = 1
Output: 0
💡 Note: Only pair (1,1) has sum 2 (even), so Bob wins. Alice wins in 0 cases.

Constraints

  • 1 ≤ n, m ≤ 105

Visualization

Tap to expand
Alice and Bob Playing Flower Game INPUT Game Field Visualization Alice Bob Lane 1: x flowers Lane 2: y flowers n = 3 m = 2 Constraints: 1 <= x <= n 1 <= y <= m Alice moves first ALGORITHM STEPS 1 Game Theory Analysis Total flowers = x + y Alice wins if total is ODD 2 Parity Condition x+y is odd when: x=odd, y=even OR x=even, y=odd 3 Count Valid Pairs odd_n = n/2, even_n = n/2 odd_m = m/2, even_m = m/2 For n=3, m=2: odd in [1,3]: 1,3 --> 2 even in [1,3]: 2 --> 1 odd in [1,2]: 1 --> 1 even in [1,2]: 2 --> 1 4 Formula ans = odd_n*even_m + even_n*odd_m ans = 2*1 + 1*1 = 3 FINAL RESULT Valid Pairs (x,y) where Alice wins: (1, 2) 1+2=3 (odd) - OK (2, 1) 2+1=3 (odd) - OK (3, 2) 3+2=5 (odd) - OK Invalid: (1,1), (2,2), (3,1) (even sums - Bob wins) Output: 3 3 winning pairs found Key Insight: In this Nim-like game, Alice wins if and only if the total number of flowers (x+y) is ODD. This happens when one value is odd and the other is even. The answer is simply: (n/2) * ((m+1)/2) + ((n+1)/2) * (m/2) = odd_count_n * even_count_m + even_count_n * odd_count_m TutorialsPoint - Alice and Bob Playing Flower Game | Optimal Solution O(1)
Asked in
Google 15 Microsoft 12
23.4K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen