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:

  1. 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.
  2. Whenever the number just taken is divisible by 2 (including 0), 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 has 5). Because 5 is odd, [4, 1, 3] keeps its order.
    • Turn 2 (Player B): takes 4 (Player B has 4). Because 4 is even, [1, 3] flips to [3, 1].
    • Turn 3 (Player A): takes 3 (Player A has 5 + 3 = 8). Because 3 is odd, [1] stays [1].
    • Turn 4 (Player B): takes 1 (Player B has 4 + 1 = 5). Sequence is now empty.
    • Score margin: 8 - 5 = 3.

Example 2

  • Input: nums = [6, 2, 10, 4]
  • Output: -6
  • Explanation:
    • Turn 1 (Player A): takes 6 (Player A has 6). Even pick flips [2, 10, 4] into [4, 10, 2].
    • Turn 2 (Player B): takes 4 (Player B has 4). Even pick flips [10, 2] back into [2, 10].
    • Turn 3 (Player A): takes 2 (Player A has 6 + 2 = 8). Even pick flips [10] into [10].
    • Turn 4 (Player B): takes 10 (Player B has 4 + 10 = 14). Sequence is now empty.
    • Score margin: 8 - 14 = -6.

Constraints

  • 0 <= len(nums) <= 10^4
  • 0 <= nums[i] <= 10^6

Step-by-step walkthrough

  1. Restate the rules

    Player A (you) and Player B alternate drawing numbers from nums, beginning with Player A:

    1. Each turn, the active player removes whichever number currently sits at the front of the sequence and adds it to their own total.
    2. Whenever the drawn value is even (picked_value % 2 == 0), the remaining sequence flips end-to-end before the other player moves.
    3. Once nums runs out of elements, we return player_a_score - player_b_score.

    Two quick observations simplify our state right away:

    • Rather than tracking two separate totals, a single score_diff counter suffices: add picked_value on your turn and subtract picked_value on the rival's turn.
    • Zero is divisible by 2 (0 % 2 == 0), so drawing 0 leaves score_diff unchanged while still flipping the remaining sequence.
  2. Why physically reversing a list is too slow

    A direct simulation copies nums into a Python list, calls arr.pop(0) every turn, and calls arr.reverse() after each even draw.

    Both list methods touch every remaining element:

    • arr.pop(0) shifts all k remaining elements one slot left (O(k) work).
    • arr.reverse() swaps pairs across all k remaining elements (O(k) work).

    Across n turns, paying O(k) per turn adds up to n + (n - 1) + ... + 1 = n * (n + 1) / 2, or O(n^2) time. We can drop every turn to O(1) work with one structural insight.

  3. 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:

    1. Load nums into a collections.deque (a double-ended queue, which supports popleft() from the left end and pop() from the right end in O(1) constant time).
    2. Keep a boolean is_reversed:
      • is_reversed == False: read the front from the left via remaining.popleft().
      • is_reversed == True: read the front from the right via remaining.pop().
    3. Whenever picked_value % 2 == 0, toggle is_reversed = not is_reversed in O(1) time.
  4. Exact order of operations inside one turn

    The four phases inside each iteration must mirror the turn rules in exact order:

    1. Pop from the active end first: inspect is_reversed to pull from the left or right end of remaining.
    2. Update score_diff: add picked_value when is_my_turn is True, otherwise subtract picked_value.
    3. Flip is_reversed afterward on even values: use is_reversed = not is_reversed (never is_reversed = True), because a second even draw restores left-to-right order.
    4. 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
    
  5. 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 how 0 behaves:

    • Turn 1 (Player A): popleft() -> 0, score_diff = 0. Since 0 % 2 == 0, is_reversed flips to True, turning logical [7, 1] into [1, 7].
    • Turn 2 (Player B): pop() -> 1, score_diff = -1. Since 1 is odd, is_reversed stays True.
    • Turn 3 (Player A): pop() -> 7, score_diff = -1 + 7 = 6. Final result: 6.
  6. 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_reversed is False, the logical front is the left end (remaining.popleft()).
  • When is_reversed is True, 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 toggle is_reversed = not is_reversed.

Walk through Example 1 (nums = [5, 4, 1, 3]):

  1. Turn 1 (Player A): is_reversed is False, so pop left -> 5 (score_diff = +5). 5 is odd, so is_reversed stays False and remaining holds [4, 1, 3].
  2. Turn 2 (Player B): is_reversed is False, so pop left -> 4 (score_diff = 5 - 4 = 1). 4 is even, so is_reversed flips to True while remaining holds [1, 3].
  3. Turn 3 (Player A): is_reversed is True, so pop right -> 3 (score_diff = 1 + 3 = 4). 3 is odd, so is_reversed stays True and remaining holds [1].
  4. Turn 4 (Player B): is_reversed is True, so pop right -> 1 (score_diff = 4 - 1 = 3). remaining is now empty, returning 3.

Complexity

  • Time: O(n), where n = len(nums). Building deque(nums) copies the n integers once in O(n), and each of the n turns runs one O(1) popleft() or pop(), one arithmetic update, and two O(1) boolean flips.
  • Space: O(n) to hold the n unpicked integers inside remaining without mutating the caller's list (or O(1) auxiliary space with the two-pointer variant below).

Edge cases

  • Empty input (nums = []): while remaining: executes zero iterations and returns 0.
  • Single element (nums = [7] or [0]): Player A takes the lone value on Turn 1; any flag flip afterward does nothing because remaining is already empty.
  • Zero values (0): 0 % 2 == 0, so 0 counts as even! Drawing 0 adds nothing to either score yet still flips the remaining order (on [0, 5, 1], 0 flips [5, 1] so Player B draws 1 and Player A draws 5, returning 4).
  • All odd values: is_reversed remains False throughout, reducing to nums[0] - nums[1] + nums[2] - ....
  • All even values: is_reversed alternates left, right, left, right, ... every turn, giving Player A the first ceil(n / 2) elements from the left and Player B the last floor(n / 2) elements from the right.

Common mistakes

  • Assigning is_reversed = True instead of is_reversed = not is_reversed: flipping an already-flipped sequence restores left-to-right order, so a second even pick must toggle is_reversed back to False.
  • 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: 0 is falsy in Python, which would misclassify 0 as odd and skip its flip.
  • Calling list.pop(0) instead of deque.popleft(): even with a direction flag, list.pop(0) shifts every remaining element left on each forward draw, leaving worst-case time at O(n^2).

Alternative approaches

  • Two-pointer scan (O(1) extra space): a two-pointer approach maintains left = 0 and right = len(nums) - 1 bounding the unpicked slice nums[left..right] directly inside nums, advancing left += 1 when reading forward and right -= 1 when 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 index 0 and calling .reverse() on each even pick? Both list.pop(0) and list.reverse() touch all k remaining elements, costing O(k) per turn. Summing k from n down to 1 produces n * (n + 1) / 2 operations — even when zero even numbers appear, pop(0) alone forces O(n^2) total time! Switching to a deque (or two index pointers) with a direction boolean drops each turn to O(1) and total runtime to O(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 item 0 is 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 index 0 (always even), so every turn flips, picks alternate left, right, left, right, ..., and the answer collapses directly to sum(nums[:(n + 1) // 2]) - sum(nums[(n + 1) // 2:]). If it means the element's original index in nums (or turn index 0, 1, 2, ...), the two-pointer loop already tracks left and right, so testing picked_index % 2 == 0 still runs in O(n) time and O(1) space — and because flip decisions no longer depend on the numbers themselves, which player claims each slot is predetermined by n alone.

Follow-up questions

Similar questions

More Adia interview questions

All 2 Adia questions →