Facebook Pixel

3847. Find the Score Difference in a Game

MediumArraySimulation
LeetCode ↗

Problem Description

You are given an integer array nums, where nums[i] represents the points scored in the i-th game.

There are exactly two players in this scenario. At the start, the first player is the active player, and the second player is inactive. Only the active player scores points in a given game.

For each game i, the following rules are applied in order:

  1. Odd score swap: If nums[i] is odd, the active and inactive players swap their roles.
  2. Every 6th game swap: If the game is every 6th game (that is, the game indices 5, 11, 17, ...), the active and inactive players swap their roles.
  3. Scoring: After applying the above swap rules, the player who is now active plays game i and gains nums[i] points.

It is important to note that both swap conditions are checked separately for each game. If both conditions are true for the same game, the players swap twice, which means they end up back in their original roles for that game.

Your task is to compute the score difference, which is defined as:

  • The first player's total score minus the second player's total score.

Return this score difference as the final answer.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

How We Pick the Algorithm

Why Simulation / Basic DSA?

This problem maps to Simulation / Basic DSA through a short path in the full flowchart.

Simulationorstraightforward?yesFastlookup orcounting?noSimulation /Basic DSA

Simulates a two-player game with role swaps using a sign variable to track active player.

Open in Flowchart

Intuition

The key observation is that we don't actually need to track the names or identities of the two players separately. Since there are only two players and they simply swap the "active" role back and forth, we can represent the situation with a single sign variable.

Let us use a variable k to indicate who is currently active:

  • When k = 1, the first player is active.
  • When k = -1, the second player is active.

Why does this work? Because the answer we want is the first player's total score minus the second player's total score. If the first player gains nums[i] points, it contributes +nums[i] to the difference. If the second player gains nums[i] points, it contributes -nums[i] to the difference. This is exactly captured by adding k * nums[i] to the answer, since k is +1 or -1 depending on who is active.

Now, swapping the active and inactive players simply means flipping the sign of k, that is, k = -k. This naturally handles both swap rules:

  • If nums[i] is odd, we flip k.
  • If the game index satisfies i % 6 == 5 (the 6th, 12th, 18th, ... games), we flip k.

A neat consequence of using sign flips is that the "double swap" case is handled automatically. If both conditions are true for the same game, k gets multiplied by -1 twice, returning it to its original value, which correctly represents the players ending up back in their starting roles.

So the approach becomes straightforward: walk through each game, update k according to the two rules, and accumulate k * nums[i] into the answer. After processing all games, the accumulated value is exactly the score difference we need.

Solution Approach

Solution 1: Simulation

We use a variable k to represent the role of the current active player. Initially k = 1, where k = 1 means the first player is the active player, and k = -1 means the second player is the active player. We also use a variable ans to accumulate the score difference, starting at 0.

We iterate over each game with both its index i and its score x = nums[i]:

  1. Odd score swap: If x % 2 is true (meaning x is odd), we flip the active role by setting k *= -1.
  2. Every 6th game swap: If i % 6 == 5, we again flip the active role by setting k *= -1. Note that when both conditions hold in the same game, k is multiplied by -1 twice, returning it to its original value, which correctly models the players swapping twice.
  3. Scoring: After applying the swap rules, the player indicated by k plays the game. We add k * x to ans, contributing +x when the first player is active and -x when the second player is active.

After processing all games, ans holds the first player's total score minus the second player's total score, so we return ans.

The time complexity is O(n), where n is the length of the array nums, since we make a single pass through all games. The space complexity is O(1), as we only use a constant amount of extra variables.

Example Walkthrough

Let us trace through the solution with a small example: nums = [3, 4, 2, 1, 5, 6, 8].

We start with k = 1 (first player active) and ans = 0. We process each game by index i, applying the two swap rules in order, then scoring.

Game i = 0, x = 3:

  • Odd score swap: 3 is odd, so flip k. Now k = -1.
  • Every 6th game swap: 0 % 6 = 0, not 5, so no flip. k = -1.
  • Scoring: ans += k * x = (-1) * 3 = -3. Now ans = -3.

Game i = 1, x = 4:

  • Odd score swap: 4 is even, no flip. k = -1.
  • Every 6th game swap: 1 % 6 = 1, not 5, no flip. k = -1.
  • Scoring: ans += (-1) * 4 = -4. Now ans = -7.

Game i = 2, x = 2:

  • Odd score swap: 2 is even, no flip. k = -1.
  • Every 6th game swap: 2 % 6 = 2, not 5, no flip. k = -1.
  • Scoring: ans += (-1) * 2 = -2. Now ans = -9.

Game i = 3, x = 1:

  • Odd score swap: 1 is odd, flip k. Now k = 1.
  • Every 6th game swap: 3 % 6 = 3, not 5, no flip. k = 1.
  • Scoring: ans += (1) * 1 = 1. Now ans = -8.

Game i = 4, x = 5:

  • Odd score swap: 5 is odd, flip k. Now k = -1.
  • Every 6th game swap: 4 % 6 = 4, not 5, no flip. k = -1.
  • Scoring: ans += (-1) * 5 = -5. Now ans = -13.

Game i = 5, x = 6:

  • Odd score swap: 6 is even, no flip. k = -1.
  • Every 6th game swap: 5 % 6 = 5, this is a 6th game, so flip k. Now k = 1.
  • Scoring: ans += (1) * 6 = 6. Now ans = -7.

Game i = 6, x = 8:

  • Odd score swap: 8 is even, no flip. k = 1.
  • Every 6th game swap: 6 % 6 = 0, not 5, no flip. k = 1.
  • Scoring: ans += (1) * 8 = 8. Now ans = 1.

After processing all games, ans = 1.

Verification by tracking actual scores:

ixActive player (after swaps)First player totalSecond player total
03Second03
14Second07
22Second09
31First19
45Second114
56First714
68First1514

The first player scores 15 and the second player scores 14, giving a difference of 15 - 14 = 1, which matches the accumulated ans = 1. The sign variable k correctly captured each role swap without ever needing to track player identities explicitly.

Solution Implementation

1from typing import List
2
3
4class Solution:
5    def scoreDifference(self, nums: List[int]) -> int:
6        # `answer` accumulates the running result
7        # `sign` is the current multiplier applied to each element (+1 or -1)
8        answer, sign = 0, 1
9
10        for index, value in enumerate(nums):
11            # Flip the sign whenever we encounter an odd value
12            if value % 2:
13                sign *= -1
14
15            # Flip the sign again at every 6th position (0-based index 5, 11, ...)
16            if index % 6 == 5:
17                sign *= -1
18
19            # Add the signed value to the accumulated answer
20            answer += sign * value
21
22        return answer
23
1class Solution {
2    /**
3     * Computes a running score by accumulating each element multiplied
4     * by a sign multiplier. The sign multiplier flips under two conditions:
5     *   1. When the current element is odd.
6     *   2. When the current index is the 6th position within a group of 6
7     *      (i.e., index % 6 == 5).
8     *
9     * @param nums the input array of integers
10     * @return the accumulated score
11     */
12    public int scoreDifference(int[] nums) {
13        // Accumulated result.
14        int answer = 0;
15
16        // Sign multiplier, starts as +1 and flips based on the rules below.
17        int sign = 1;
18
19        for (int i = 0; i < nums.length; ++i) {
20            int value = nums[i];
21
22            // Rule 1: flip the sign whenever the current value is odd.
23            if ((value & 1) == 1) {
24                sign = -sign;
25            }
26
27            // Rule 2: flip the sign at the last element of each group of 6.
28            if (i % 6 == 5) {
29                sign = -sign;
30            }
31
32            // Add the signed value to the running total.
33            answer += sign * value;
34        }
35
36        return answer;
37    }
38}
39
1class Solution {
2public:
3    int scoreDifference(vector<int>& nums) {
4        int answer = 0;   // accumulated result
5        int sign = 1;     // current sign multiplier (+1 or -1)
6
7        for (int i = 0; i < static_cast<int>(nums.size()); ++i) {
8            int value = nums[i];
9
10            // Flip the sign whenever the current value is odd
11            if (value & 1) {
12                sign = -sign;
13            }
14
15            // Flip the sign again at the end of every block of 6 elements
16            if (i % 6 == 5) {
17                sign = -sign;
18            }
19
20            // Add the signed value to the running total
21            answer += sign * value;
22        }
23
24        return answer;
25    }
26};
27
1/**
2 * Computes a signed sum over the input array.
3 *
4 * The sign multiplier `sign` starts at 1 and is flipped under two conditions:
5 *   1. When the current element is odd.
6 *   2. When the current index is the last position of every 6-element block
7 *      (i.e. index % 6 === 5).
8 *
9 * Each element is then added to the accumulator after being multiplied by the
10 * current sign.
11 *
12 * @param nums - The input array of numbers.
13 * @returns The accumulated signed sum.
14 */
15function scoreDifference(nums: number[]): number {
16    // Accumulated result.
17    let answer = 0;
18
19    // Running sign multiplier, toggles between 1 and -1.
20    let sign = 1;
21
22    nums.forEach((value: number, index: number) => {
23        // Flip the sign whenever the current value is odd.
24        if (value % 2 !== 0) {
25            sign = -sign;
26        }
27
28        // Flip the sign at the end of each 6-element block.
29        if (index % 6 === 5) {
30            sign = -sign;
31        }
32
33        // Add the signed value to the running total.
34        answer += sign * value;
35    });
36
37    return answer;
38}
39

Time and Space Complexity

Time Complexity: O(n), where n is the length of the array nums. The code iterates through the array exactly once using enumerate, performing a constant amount of work (modulo checks, multiplication, and addition) for each element. Therefore, the total time scales linearly with the number of elements.

Space Complexity: O(1). The algorithm only uses a fixed number of variables (ans, k, i, and x), regardless of the input size. No additional data structures that grow with the input are allocated, so the extra space usage remains constant.

Pattern Learn more about how to find time and space complexity quickly.

Common Pitfalls

Pitfall 1: Treating the swaps as a "per-game reset" instead of a persistent state

The most frequent mistake is assuming that the active player resets to the first player at the start of each game, and that the swap rules only determine "who plays game i" without carrying over to the next game.

In reality, the role variable sign is stateful — every swap permanently changes which player is active for all subsequent games until another swap occurs. The swaps accumulate over time.

Wrong intuition (resets every game):

# INCORRECT — recomputes role from scratch each game
for index, value in enumerate(nums):
    sign = 1                      # ❌ resets the role every iteration
    if value % 2:
        sign *= -1
    if index % 6 == 5:
        sign *= -1
    answer += sign * value

Correct approach: Declare sign once outside the loop so its value persists across iterations:

answer, sign = 0, 1               # ✅ sign initialized once, before the loop
for index, value in enumerate(nums):
    if value % 2:
        sign *= -1
    if index % 6 == 5:
        sign *= -1
    answer += sign * value

Pitfall 2: Applying the odd-value swap after scoring instead of before

The problem states the rules are applied in order: swaps happen first, then the now-active player scores. A common error is to score first and then flip:

# INCORRECT — scores before applying the swap rules
for index, value in enumerate(nums):
    answer += sign * value        # ❌ scoring happens too early
    if value % 2:
        sign *= -1
    if index % 6 == 5:
        sign *= -1

This shifts every swap effect one game too late. The swap caused by an odd value must affect that same game's scoring, not the next one. Always perform both swap checks before adding sign * value.

Pitfall 3: Mishandling the "double swap" case

When both an odd value and a 6th-game position occur together, the players swap twice, returning to the original roles. Some attempts try to special-case this with an if/elif:

# INCORRECT — uses elif, so the two conditions become mutually exclusive
if value % 2:
    sign *= -1
elif index % 6 == 5:                # ❌ never runs when value is also odd
    sign *= -1

Using elif makes the conditions mutually exclusive, so a game that is both odd-scored and a 6th game would only swap once. The fix is to use two independent if statements so both swaps can apply, and sign *= -1 applied twice naturally returns sign to its original value.

Pitfall 4: Off-by-one error in the "6th game" check

The 6th game corresponds to 0-based index 5 (games 5, 11, 17, ...). Writing index % 6 == 0 would incorrectly trigger on games 0, 6, 12, ... (the 1st, 7th, 13th games), and using a 1-based count without adjustment leads to similar mistakes. The correct condition for 0-based indexing is:

if index % 6 == 5:                  # ✅ matches games 5, 11, 17, ...
    sign *= -1

Ready to land your dream job?

Unlock your dream job with a 5-minute quiz for a personalized study roadmap!

Get My Roadmap
Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Get a Personalized Study Roadmap:

In a binary min heap, the maximum element can be found in:


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More