Subtree Removal Game with Fibonacci Tree - Problem

A Fibonacci tree is a binary tree created using the order function order(n):

  • order(0) is the empty tree
  • order(1) is a binary tree with only one node
  • order(n) is a binary tree that consists of a root node with the left subtree as order(n - 2) and the right subtree as order(n - 1)

Alice and Bob are playing a game with a Fibonacci tree with Alice starting first. On each turn, a player selects a node and removes that node and its subtree. The player that is forced to delete root loses.

Given the integer n, return true if Alice wins the game or false if Bob wins, assuming both players play optimally.

A subtree of a binary tree is a tree that consists of a node in tree and all of this node's descendants. The tree could also be considered as a subtree of itself.

Input & Output

Example 1 — Small Fibonacci Tree
$ Input: n = 1
Output: true
💡 Note: Fibonacci tree order(1) has only one node. Since Alice goes first and there are no other moves available, Alice wins because the game ends immediately with her move being the winning move according to the mathematical pattern n%3≠0.
Example 2 — Larger Tree
$ Input: n = 3
Output: false
💡 Note: Fibonacci tree order(3) has root with left=order(1) and right=order(2). Alice can remove non-root nodes, but optimal play leads to Bob winning.
Example 3 — Pattern Example
$ Input: n = 4
Output: true
💡 Note: Following the mathematical pattern, since 4 % 3 = 1 ≠ 0, Alice wins with optimal play.

Constraints

  • 1 ≤ n ≤ 100

Visualization

Tap to expand
Subtree Removal Game with Fibonacci Tree INPUT Fibonacci Tree order(1) Root order(0) = empty order(1) = single node order(n) = root + subtrees n = 1 Input parameter Alice starts first Delete root = LOSE ALGORITHM STEPS 1 Analyze Tree Size Count nodes in order(n) 2 Game Theory Check Apply Sprague-Grundy 3 n=1 Special Case Only root exists 4 Determine Winner First move decides For n=1: Tree has only 1 node (root) Alice must pass turn Bob forced to delete root FINAL RESULT Game Outcome: ALICE WINS OK - Victory! Game Flow: Alice: No valid move Bob: Must delete root true Output value Key Insight: For n=1, the tree contains only the root node. Alice cannot select any node without removing the root (which would make her lose). So she passes, forcing Bob to delete root on his turn. Bob loses! Pattern: For Fibonacci trees, winner depends on parity of non-root removable nodes. TutorialsPoint - Subtree Removal Game with Fibonacci Tree | Optimal Solution
Asked in
Google 25 Microsoft 18
25.8K Views
Medium Frequency
~25 min Avg. Time
890 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