Python 1686.py
class Solution:
def stoneGameVI(self, aliceValues: List[int], bobValues: List[int]) -> int:
diffs = [ ( a, b ) for a, b in zip(aliceValues, bobValues) ]
# pick largest values first (either boosts own value or prevents opponent from doing so)
diffs.sort(reverse = True, key = lambda x : x[0] + x[1])
result = 0
player = 0 # alternate between 0 and 1
for d in diffs:
sign = 1 - 2 * player # Alice +1, Bob -1
result += d[player] * sign
player ^= 1
if result == 0:
return 0
return +1 if result > 0 else -1
Difficulty
and has an acceptance rate of about 61% (40k+ submissions).
Typical patterns to solve this problem:
- Array
- Game Theory
- Greedy
- Heap (Priority Queue)
- Math
- Sorting
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the two-player stone picking problem by converting the pair of values for each stone into a single sortable metric, then simulating an optimal alternating selection. The algorithm builds a list of paired values, orders the stones so that the most influential ones are considered first, and accumulates a signed score that reflects Alice’s advantage over Bob. The final sign of this accumulated score determines the winner.
Construction of Paired Values
The first logical step creates a list of tuples, each containing Alice’s and Bob’s valuation for the same stone.
diffs = [ ( a, b ) for a, b in zip(aliceValues, bobValues) ]
By using a list comprehension together with zip, the code efficiently pairs corresponding entries without an explicit loop, keeping the operation concise and cache-friendly.
Ordering by Combined Influence
The next phase sorts the list of tuples in descending order based on the sum of the two valuations.
diffs.sort(reverse = True, key = lambda x : x[0] + x[1])
Sorting by a + b ensures that stones with the highest total impact-whether they boost Alice’s score or deny Bob a large gain-are examined first. The reverse=True flag places the most critical stones at the front, allowing the subsequent simulation to process them in optimal order.
Alternating Turn Simulation
A variable result tracks the net advantage, while player toggles between the two participants.
result = 0
player = 0 # alternate between 0 and 1
for d in diffs:
sign = 1 - 2 * player # Alice +1, Bob -1
result += d[player] * sign
player ^= 1
The expression 1 - 2 * player yields +1 for Alice (when player is 0) and -1 for Bob (when player is 1). Multiplying the current player’s valuation by this sign adds Alice’s gain or subtracts Bob’s gain from the cumulative total. The use of the bitwise XOR operator ^= to flip player between 0 and 1 is a compact and fast way to alternate turns without conditional branching.
Determining the Outcome
After processing all stones, the code evaluates the sign of result.
if result == 0:
return 0
return +1 if result > 0 else -1
A zero total indicates a perfect balance, leading to a draw (0). A positive total means Alice’s accumulated advantage outweighs Bob’s, so the function returns +1. Conversely, a negative total yields -1, indicating Bob’s superiority.
Edge Cases Handled
When both players receive identical total scores, the result variable becomes exactly zero, and the function correctly returns a draw. The sorting step also gracefully handles stones where both valuations are zero; such entries are placed at the end of the list and have no effect on the final score. Additionally, the algorithm works for input lists of length one, where the single stone’s sum determines the order and the alternating logic still applies correctly.
Performance Optimizations
The code leverages several micro-optimizations. The list comprehension for building diffs avoids the overhead of repeatedly appending to a list inside a loop. Sorting with a simple lambda that computes x[0] + x[1] is inexpensive because it operates on integer addition, which is fast in Python. The turn-alternation uses a bitwise XOR (player ^= 1) instead of an if statement, reducing branch mispredictions. The sign calculation 1 - 2 * player is a constant-time arithmetic expression that eliminates the need for separate conditional branches for each player. Together, these choices keep the runtime tight while preserving readability.
ELI5 - Simplified Explanation
Imagine a game where two friends are picking up stones in a pile. Each stone has a number written on it showing how much it is worth to each person. Because some stones are more valuable than others, the friends decide to be very smart about which ones they grab. They add the value for both people together to figure out which stone is the most important one to take next. By doing this, they make sure they get the biggest prizes while keeping the other person from getting them.
The code starts by looking at all the stones and pairing up their values. Then, it sorts them from the biggest ones to the smallest ones based on that total value. Once the stones are lined up in order, the friends start taking turns. When it is the first friend's turn, they add their points to a score. When it is the second friend's turn, they take those points away from the total to show they are winning some. After all the stones are gone, the final score tells everyone who ended up with the most value. If the score is positive, the first friend won. If the score is negative, the second friend won. If the score is zero, it means they both finished with the exact same amount of value.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||
| WalkCCC | C++ | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| MacJim | C++ | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| MacJim | C++ | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 877: Stone Game
- problem 1140: Stone Game II
- problem 1406: Stone Game III
- problem 1510: Stone Game IV
- problem 1563: Stone Game V
- problem 1690: Stone Game VII
- problem 1872: Stone Game VIII
- problem 2029: Stone Game IX
Solved On The Same Day
- problem 2500: Delete Greatest Value in Each Row
- problem 1792: Maximum Average Pass Ratio
- problem 1969: Minimum Non-Zero Product of the Array Elements
- problem 2054: Two Best Non-Overlapping Events
- problem 2208: Minimum Operations to Halve Array Sum
- problem 2342: Max Sum of a Pair With Equal Sum of Digits
- problem 2456: Most Popular Video Creator
- problem 2512: Reward Top K Students
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality