Score Margin in an Even-Flip Array Game
Easy · Coding & Algorithms · Data Scientist · Technical Screen
Problem Statement
Two players compete by drawing numbers from a sequence of non-negative integers nums. Player A (you) and Player B (your rival) alternate turns until no numbers remain, starting with Player A on turn 1.
Each turn follows two steps in order:
- The active player takes the element currently sitting at index
0(the front of the remaining sequence) and adds that value to their own cumulative score. - Whenever the number just taken is divisible by
2(including0), the order of all remaining elements in the sequence is flipped end-to-end before the next turn starts. Odd values leave the remaining order untouched.
Implement calculate_score_difference(nums) to return Player A's final score minus Player B's final score.
def calculate_score_difference(nums: List[int]) -> int:
Examples
Example 1
- Input:
nums = [5, 4, 1, 3] - Output:
3 - Explanation:
- Turn 1 (Player A): takes
5(Player A has5). Because5is odd,[4, 1, 3]keeps its order. - Turn 2 (Player B): takes
4(Player B has4). Because4is even,[1, 3]flips to[3, 1]. - Turn 3 (Player A): takes
3(Player A has5 + 3 = 8). Because3is odd,[1]stays[1]. - Turn 4 (Player B): takes
1(Player B has4 + 1 = 5). Sequence is now empty. - Score margin:
8 - 5 = 3.
- Turn 1 (Player A): takes
Example 2
- Input:
nums = [6, 2, 10, 4] - Output:
-6 - Explanation:
- Turn 1 (Player A): takes
6(Player A has6). Even pick flips[2, 10, 4]into[4, 10, 2]. - Turn 2 (Player B): takes
4(Player B has4). Even pick flips[10, 2]back into[2, 10]. - Turn 3 (Player A): takes
2(Player A has6 + 2 = 8). Even pick flips[10]into[10]. - Turn 4 (Player B): takes
10(Player B has4 + 10 = 14). Sequence is now empty. - Score margin:
8 - 14 = -6.
- Turn 1 (Player A): takes
Constraints
0 <= len(nums) <= 10^40 <= nums[i] <= 10^6
Step-by-step walkthrough
Restate the rules
Player A (you) and Player B alternate drawing numbers from
nums, beginning with Player A:- Each turn, the active player removes whichever number currently sits at the front of the sequence and adds it to their own total.
- Whenever the drawn value is even (
picked_value % 2 == 0), the remaining sequence flips end-to-end before the other player moves. - Once
numsruns out of elements, we returnplayer_a_score - player_b_score.
Two quick observations simplify our state right away:
- Rather than tracking two separate totals, a single
score_diffcounter suffices: addpicked_valueon your turn and subtractpicked_valueon the rival's turn. - Zero is divisible by
2(0 % 2 == 0), so drawing0leavesscore_diffunchanged while still flipping the remaining sequence.
Why physically reversing a list is too slow
A direct simulation copies
numsinto a Pythonlist, callsarr.pop(0)every turn, and callsarr.reverse()after each even draw.Both list methods touch every remaining element:
arr.pop(0)shifts allkremaining elements one slot left (O(k)work).arr.reverse()swaps pairs across allkremaining elements (O(k)work).
Across
nturns, payingO(k)per turn adds up ton + (n - 1) + ... + 1 = n * (n + 1) / 2, orO(n^2)time. We can drop every turn toO(1)work with one structural insight.Key idea: toggle which end of a deque acts as the front
Watch what happens to
[2, 10, 4]when we flip it once, and then flip it a second time:Initial orientation: [ 2, 10, 4 ] <-- logical front is LEFT (2) After 1st flip: [ 4, 10, 2 ] <-- logical front is RIGHT (4 in original) After 2nd flip: [ 2, 10, 4 ] <-- logical front is LEFT again!Flipping never scrambles interior neighbors — at every moment, the unpicked numbers form one contiguous slice of the original
nums, read either left-to-right or right-to-left.So we never need to move elements in memory:
- Load
numsinto acollections.deque(a double-ended queue, which supportspopleft()from the left end andpop()from the right end inO(1)constant time). - Keep a boolean
is_reversed:is_reversed == False: read the front from the left viaremaining.popleft().is_reversed == True: read the front from the right viaremaining.pop().
- Whenever
picked_value % 2 == 0, toggleis_reversed = not is_reversedinO(1)time.
- Load
Exact order of operations inside one turn
The four phases inside each iteration must mirror the turn rules in exact order:
- Pop from the active end first: inspect
is_reversedto pull from the left or right end ofremaining. - Update
score_diff: addpicked_valuewhenis_my_turnisTrue, otherwise subtractpicked_value. - Flip
is_reversedafterward on even values: useis_reversed = not is_reversed(neveris_reversed = True), because a second even draw restores left-to-right order. - Hand over the turn: toggle
is_my_turn = not is_my_turn.
from typing import List from collections import deque def calculate_score_difference(nums: List[int]) -> int: # remaining: double-ended queue of unpicked integers in their original order, # e.g. deque([6, 2, 10, 4]). We never physically reverse it; we pop from either end in O(1). remaining = deque(nums) # is_reversed: False -> logical front is the left end (popleft); # True -> logical front is the right end (pop). is_reversed = False # You move first; score_diff tracks (your_score - opponent_score) directly. is_my_turn = True score_diff = 0 while remaining: # Phase 1: remove the element at the current logical front. if is_reversed: picked_value = remaining.pop() else: picked_value = remaining.popleft() # Phase 2: add to score_diff on your turn, subtract on the opponent's turn. if is_my_turn: score_diff += picked_value else: score_diff -= picked_value # Phase 3: if the removed number is even (note 0 % 2 == 0, so 0 is even too), # reversing the remaining elements simply swaps which end acts as the front. if picked_value % 2 == 0: is_reversed = not is_reversed # Phase 4: pass the turn to the other player. is_my_turn = not is_my_turn return score_diff- Pop from the active end first: inspect
Walk through Example 2 and a zero-value case
Trace Example 2 (
nums = [6, 2, 10, 4]):Start: remaining = deque([6, 2, 10, 4]), is_reversed = False (front = LEFT), score_diff = 0 Turn 1 (Player A): front is LEFT -> popleft() gives 6 score_diff -> 0 + 6 = 6 6 is even -> is_reversed becomes True (front = RIGHT) remaining -> deque([2, 10, 4]) (represents logical [4, 10, 2]) Turn 2 (Player B): front is RIGHT -> pop() gives 4 score_diff -> 6 - 4 = 2 4 is even -> is_reversed becomes False (front = LEFT) remaining -> deque([2, 10]) (represents logical [2, 10]) Turn 3 (Player A): front is LEFT -> popleft() gives 2 score_diff -> 2 + 2 = 4 2 is even -> is_reversed becomes True (front = RIGHT) remaining -> deque([10]) (represents logical [10]) Turn 4 (Player B): front is RIGHT -> pop() gives 10 score_diff -> 4 - 10 = -6 10 is even -> is_reversed becomes False remaining -> deque([]) (done -> return -6)Now check
nums = [0, 7, 1]to confirm how0behaves:- Turn 1 (Player A):
popleft()->0,score_diff = 0. Since0 % 2 == 0,is_reversedflips toTrue, turning logical[7, 1]into[1, 7]. - Turn 2 (Player B):
pop()->1,score_diff = -1. Since1is odd,is_reversedstaysTrue. - Turn 3 (Player A):
pop()->7,score_diff = -1 + 7 = 6. Final result:6.
- Turn 1 (Player A):
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from collections import deque def calculate_score_difference(nums: List[int]) -> int: # remaining: double-ended queue of unpicked integers in their original order, # e.g. deque([6, 2, 10, 4]). We never physically reverse it; we pop from either end in O(1). remaining = deque(nums) # is_reversed: False -> logical front is the left end (popleft); # True -> logical front is the right end (pop). is_reversed = False # You move first; score_diff tracks (your_score - opponent_score) directly. is_my_turn = True score_diff = 0 while remaining: # Phase 1: remove the element at the current logical front. if is_reversed: picked_value = remaining.pop() else: picked_value = remaining.popleft() # Phase 2: add to score_diff on your turn, subtract on the opponent's turn. if is_my_turn: score_diff += picked_value else: score_diff -= picked_value # Phase 3: if the removed number is even (note 0 % 2 == 0, so 0 is even too), # reversing the remaining elements simply swaps which end acts as the front. if picked_value % 2 == 0: is_reversed = not is_reversed # Phase 4: pass the turn to the other player. is_my_turn = not is_my_turn return score_diff✅ Submit now — all tests should pass.
Intuition & how it works
Picture a line of numbered tiles resting face-up on a table. Whenever someone picks up an even tile, the game rules say to flip the entire remaining row end-to-end. Physically rearranging thousands of tiles after every even draw would take ages — yet flipping the row never changes which tiles sit beside each other; it merely swaps which end serves as the front! Leaving the tiles stationary and moving a small pointer token between the left end and the right end on each even draw makes every turn instantaneous.
Simulating the literal rules on a Python list is costly for two reasons: arr.pop(0) shifts all k remaining items left in O(k) time, and arr.reverse() swaps all k remaining items in O(k) time. Across n turns, n + (n - 1) + ... + 1 totals O(n^2) work.
Instead, we place nums inside a deque (a double-ended queue from collections.deque that removes from either its left or right end in O(1) constant time) and track a boolean is_reversed:
- When
is_reversedisFalse, the logical front is the left end (remaining.popleft()). - When
is_reversedisTrue, the logical front is the right end (remaining.pop()). - Whenever the drawn integer has even parity (divisible by
2, i.e.,picked_value % 2 == 0), we toggleis_reversed = not is_reversed.
Walk through Example 1 (nums = [5, 4, 1, 3]):
- Turn 1 (Player A):
is_reversedisFalse, so pop left ->5(score_diff = +5).5is odd, sois_reversedstaysFalseandremainingholds[4, 1, 3]. - Turn 2 (Player B):
is_reversedisFalse, so pop left ->4(score_diff = 5 - 4 = 1).4is even, sois_reversedflips toTruewhileremainingholds[1, 3]. - Turn 3 (Player A):
is_reversedisTrue, so pop right ->3(score_diff = 1 + 3 = 4).3is odd, sois_reversedstaysTrueandremainingholds[1]. - Turn 4 (Player B):
is_reversedisTrue, so pop right ->1(score_diff = 4 - 1 = 3).remainingis now empty, returning3.
Complexity
- Time:
O(n), wheren = len(nums). Buildingdeque(nums)copies thenintegers once inO(n), and each of thenturns runs oneO(1)popleft()orpop(), one arithmetic update, and twoO(1)boolean flips. - Space:
O(n)to hold thenunpicked integers insideremainingwithout mutating the caller's list (orO(1)auxiliary space with the two-pointer variant below).
Edge cases
- Empty input (
nums = []):while remaining:executes zero iterations and returns0. - Single element (
nums = [7]or[0]): Player A takes the lone value on Turn 1; any flag flip afterward does nothing becauseremainingis already empty. - Zero values (
0):0 % 2 == 0, so0counts as even! Drawing0adds nothing to either score yet still flips the remaining order (on[0, 5, 1],0flips[5, 1]so Player B draws1and Player A draws5, returning4). - All odd values:
is_reversedremainsFalsethroughout, reducing tonums[0] - nums[1] + nums[2] - .... - All even values:
is_reversedalternatesleft, right, left, right, ...every turn, giving Player A the firstceil(n / 2)elements from the left and Player B the lastfloor(n / 2)elements from the right.
Common mistakes
- Assigning
is_reversed = Trueinstead ofis_reversed = not is_reversed: flipping an already-flipped sequence restores left-to-right order, so a second even pick must toggleis_reversedback toFalse. - Flipping before popping: the current player removes the front element first, and only after that draw does an even value flip what remains for the next turn.
- Writing
if picked_value and picked_value % 2 == 0:0is falsy in Python, which would misclassify0as odd and skip its flip. - Calling
list.pop(0)instead ofdeque.popleft(): even with a direction flag,list.pop(0)shifts every remaining element left on each forward draw, leaving worst-case time atO(n^2).
Alternative approaches
- Two-pointer scan (
O(1)extra space): a two-pointer approach maintainsleft = 0andright = len(nums) - 1bounding the unpicked slicenums[left..right]directly insidenums, advancingleft += 1when reading forward andright -= 1when reading backward:
def calculate_score_difference_two_pointers(nums: List[int]) -> int:
left = 0
right = len(nums) - 1
is_reversed = False
is_my_turn = True
score_diff = 0
while left <= right:
if is_reversed:
picked_value = nums[right]
right -= 1
else:
picked_value = nums[left]
left += 1
if is_my_turn:
score_diff += picked_value
else:
score_diff -= picked_value
if picked_value % 2 == 0:
is_reversed = not is_reversed
is_my_turn = not is_my_turn
return score_diff
Follow-up questions
- What happens to the asymptotic runtime if you store the elements in a plain Python
list, popping index0and calling.reverse()on each even pick? Bothlist.pop(0)andlist.reverse()touch allkremaining elements, costingO(k)per turn. Summingkfromndown to1producesn * (n + 1) / 2operations — even when zero even numbers appear,pop(0)alone forcesO(n^2)total time! Switching to adeque(or two index pointers) with a direction boolean drops each turn toO(1)and total runtime toO(n). - Could you reduce memory usage if the input integers arrived one at a time from a forward-only stream instead of an in-memory sequence? A streaming algorithm reads values once from front to back without random access to the tail. While every arriving integer is odd, no flip has happened yet, so you can immediately add or subtract each odd value in
O(1)memory and discard it. However, the instant the first even integer arrives, the very next turn requires the final element of the entire stream — which cannot be known until the stream ends! Consequently, from the first even element onward you must buffer all remaining arrivals (O(n)worst-case memory if item0is even), unless the underlying storage (such as a seekable file on disk) allows reading backward from the end. - How would your algorithm and runtime change if reversals triggered on even index positions rather than even element values? First clarify whether "index" refers to the current remaining sequence or the original input
nums. If it means the index within the current sequence, every draw removes current index0(always even), so every turn flips, picks alternateleft, right, left, right, ..., and the answer collapses directly tosum(nums[:(n + 1) // 2]) - sum(nums[(n + 1) // 2:]). If it means the element's original index innums(or turn index0, 1, 2, ...), the two-pointer loop already tracksleftandright, so testingpicked_index % 2 == 0still runs inO(n)time andO(1)space — and because flip decisions no longer depend on the numbers themselves, which player claims each slot is predetermined bynalone.
Follow-up questions
- What happens to the asymptotic runtime if you store the elements in a plain Python `list`, popping index `0` and calling `.reverse()` on each even pick?
- Could you reduce memory usage if the input integers arrived one at a time from a forward-only stream instead of an in-memory sequence?
- How would your algorithm and runtime change if reversals triggered on even index positions rather than even element values?
Similar questions
- Per-Stream Playback Event Tallies
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One