Winner of the Linked List Game

Updated on 15 July, 2025
Winner of the Linked List Game header image

Problem Statement

In this problem, you're provided with the head of a linked list composed of an even number of nodes. Each node is filled with integers and indexed such that each odd-indexed node contains an odd integer, and each even-indexed node contains an even integer. Nodes are paired sequentially: the node at index 0 forms a pair with the node at index 1, index 2 with index 3, and so forth.

For each pair, a competition is held where:

  • The "Odd" team scores if the value in the odd-indexed node (second in the pair) is greater than the value in the even-indexed node (first in the pair).
  • Conversely, the "Even" team scores if the value in the even-indexed node exceeds the value in the odd-indexed node.

Your task is to traverse the entire linked list, tally up the scores of each team from all the pairs, and determine the winning team. If the scores are equal, you are required to return "Tie".


Examples

Example 1

Input:

head = [2,1]

Output:

"Even"

Explanation:

There is only one pair in this linked list and that is (2,1). Since 2 > 1, the Even team gets the point.

Example 2

Input:

head = [2,5,4,7,20,5]

Output:

"Odd"

Explanation:

There are 3 pairs:
(2,5) → Odd team scores  
(4,7) → Odd team scores  
(20,5) → Even team scores  
Odd: 2 points, Even: 1 point → Odd wins.

Example 3

Input:

head = [4,5,2,1]

Output:

"Tie"

Explanation:

Two pairs:
(4,5) → Odd team scores  
(2,1) → Even team scores  
Both teams have 1 point → Tie.

Constraints

  • The number of nodes in the list is in the range [2, 100].
  • The number of nodes is even.
  • 1 <= Node.val <= 100
  • Odd-indexed nodes have odd values.
  • Even-indexed nodes have even values.

Approach and Intuition

Given the structured nature of the linked list and the clear rules for scoring, our approach can be straightforward:

  1. Initialize counters for both the "Odd" and "Even" team scores.

  2. Traverse the linked list in steps of two:

    • Let even_node be the current node.

    • Let odd_node be even_node.next.

    • Compare their values:

      • If odd_node.val > even_node.val, Odd team scores.
      • Else if even_node.val > odd_node.val, Even team scores.
  3. Compare totals after traversal:

    • Return "Odd" if the Odd team has more points.
    • Return "Even" if the Even team has more points.
    • Return "Tie" if scores are equal.

This is a single-pass O(n) algorithm with constant space (excluding input), making it efficient and easy to implement for the given constraints.

Solutions

  • C++
cpp
class Solution {
public:
    string determineWinner(ListNode* start) {
        ListNode* traverseNode = start;
        int scoreDiff = 0;
    
        while (traverseNode != nullptr) {
            if (traverseNode->next != nullptr) {
                scoreDiff += (traverseNode->val > traverseNode->next->val) ? 1 : -1;
            }
            traverseNode = traverseNode->next->next; // Move to the next applicable node
        }
    
        if (scoreDiff < 0)
            return "Odd";
        else if (scoreDiff > 0)
            return "Even";
        else
            return "Tie";
    }
};

The given C++ program defines a class Solution with a function determineWinner which determines the winner of a game played with a linked list where nodes represent game elements. Here's a step-by-step breakdown of how the function works:

  1. Initialize a pointer traverseNode to the start of the linked list and an integer scoreDiff to zero to track the difference in scores.
  2. Iterate through the linked list using a while loop which continues until traverseNode becomes nullptr.
  3. Inside the loop, if the next node (traverseNode->next) is not nullptr, compare the current node's value (traverseNode->val) with the next node’s value:
    • If the current node’s value is greater, increase scoreDiff by 1.
    • Otherwise, decrease scoreDiff by 1.
  4. Move traverseNode two nodes forward each time (skipping one node) to only check every second node, simulating turn-based scoring.
  5. After the loop, determine the winner based on scoreDiff:
    • If scoreDiff is less than 0, return "Odd".
    • If scoreDiff is greater than 0, return "Even".
    • If scoreDiff is 0, return "Tie".

By the end of the function, receive a string indicating the winner ("Odd", "Even", or "Tie") based on the scoring differences computed between adjacent nodes in the linked list. This provides a simple mechanism to evaluate winner scenarios in scenarios where values in a sequence (the linked list) are competed against their immediate neighbors.

  • Java
java
class Solution {
    public String calculateWinner(ListNode root) {
        ListNode current = root;
        int scoreDiff = 0;
    
        while (current != null) {
            if (current.next != null) {
                scoreDiff += (current.val > current.next.val) ? 1 : -1;
            }
            current = current.next.next;
        }
    
        if (scoreDiff < 0)
            return "Odd";
        else if (scoreDiff > 0)
            return "Even";
        else
            return "Tie";
    }
}

The Java solution provided is designed to determine the winner of a game played using a linked list where nodes represent game scores. The logic to determine the "Winner of the Linked List Game" involves iterating through the linked list to compare the values of adjacent nodes. Below illustrates how the solution functions:

  • Initialize the traversal of the linked list starting from the root.
  • Use a variable scoreDiff to keep track of the score difference between consecutive nodes.
  • Loop through the linked list:
    • For each node, if it has a next node, update the scoreDiff based on whether the current node's value is greater than the next node's value. Increment scoreDiff by 1 if the current is greater, otherwise decrement by 1.
    • Skip to the node after the next one (current.next.next) in each iteration.
  • After completing the traversal, determine the winner:
    • If scoreDiff is negative, return "Odd".
    • If scoreDiff is positive, return "Even".
    • If scoreDiff is zero, return "Tie".

This solution ensures that each pair of consecutive nodes are compared once and that the overall winner is based on the cumulative score differences, effectively deducing if the "even"-positioned or "odd"-positioned nodes generally hold higher values, or if it’s a tie. The approach used capitalizes on linked list traversal and conditional checks to solve the problem efficiently.

  • Python
python
class Solution:
    def calculateWinner(self, start_node: Optional[ListNode]) -> str:
        node_pointer, score_margin = start_node, 0
    
        while node_pointer:
            score_margin += (node_pointer.val > node_pointer.next.val) - (node_pointer.val < node_pointer.next.val)
            node_pointer = node_pointer.next.next
    
        if score_margin > 0:
            return "Even"
        elif score_margin < 0:
            return "Odd"
        else:
            return "Tie"

The provided Python function calculateWinner determines the outcome of a linked list game where two players labeled 'Even' and 'Odd' alternate turns to compare the values of linked list nodes. The methodology applied in this function is as follows:

  • The function accepts a starting node of a linked list.
  • Traverses through the list with the help of a pointer, analyzing the node values in pairs - one node per each player per turn.
  • Calculates a score margin by incrementing for 'Even' if the value of the current node (node_pointer.val) is greater than the next node (node_pointer.next.val), and decrementing for 'Odd' if less.
  • Skips every second node to simulate the turns of the two players by moving the pointer two nodes forward each iteration.
  • After the traversal, evaluates the accumulated score_margin:
    • Returns "Even" if the score margin is positive, indicating player Even scored higher.
    • Returns "Odd" if it is negative, meaning player Odd scored higher.
    • Returns "Tie" if the score is zero, indicating an equal score between players.

Ensure the linked list has an even number of nodes to avoid errors during the game, as the logic assumes pairs of nodes are present for comparison between players. If input linked lists are not formatted as expected, additional checks might be required.

Comments

No comments yet.