# AI solution for JavaScript Coding Question on BFE.dev

147. Pick up stones

Here's one solution using recursion and memoization to avoid redundant calculations:

`function winningStonePicking(n) { const memo = new Map(); function canWin(numStones) { if (numStones <= 0) { return false; } if (numStones === 1 || numStones === 2) { return true; } if (memo.has(numStones)) { return memo.get(numStones); } const canWinTakingOne = !canWin(numStones - 1); const canWinTakingTwo = !canWin(numStones - 2); const result = canWinTakingOne || canWinTakingTwo; memo.set(numStones, result); return result; } if (canWin(n)) { return 'A'; } return 'B';}`

The `canWin(numStones)`

function recursively determines whether the player whose turn it is to move can win with `numStones`

remaining in the pile. We first check for the base cases where there are only 1 or 2 stones left, since in that case the player who moves first (A) can win by simply taking that number of stones. If there are no stones left, the current player cannot move and therefore cannot win, so we return `false`

in that case.

If we have not seen this `numStones`

value before (i.e., it's not in the memoization map), we recursively calculate whether we can win by taking 1 or 2 stones. If taking 1 stone results in the opponent winning (i.e., `!canWin(numStones - 1)`

), or if taking 2 stones results in the opponent winning (i.e., `!canWin(numStones - 2)`

), then the current player can win by taking either 1 or 2 stones, respectively. Otherwise, the opponent has a winning strategy, so we return `false`

.

Once we've determined whether A can win with `n`

stones, we return `'A'`

if she can, or `'B'`

otherwise.

This solution has a time complexity of O(n), where n is the number of stones, since we only have to compute `canWin`

once for each possible number of stones. The space complexity is also O(n), since we use a memoization map to store the results of previous calculations.