Skip to content

3062. Winner of the Linked List Game 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  string gameResult(ListNode* head) {
    int even = 0;
    int odd = 0;

    while (head != nullptr) {
      if (head->val > head->next->val)
        ++even;
      else if (head->val < head->next->val)
        ++odd;
      head = head->next->next;
    }

    if (even > odd)
      return "Even";
    if (even < odd)
      return "Odd";
    return "Tie";
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public String gameResult(ListNode head) {
    int even = 0;
    int odd = 0;

    while (head != null) {
      if (head.val > head.next.val)
        ++even;
      else if (head.val < head.next.val)
        ++odd;
      head = head.next.next;
    }

    if (even > odd)
      return "Even";
    if (even < odd)
      return "Odd";
    return "Tie";
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def gameResult(self, head: ListNode | None) -> str:
    even = 0
    odd = 0

    while head:
      if head.val > head.next.val:
        even += 1
      elif head.val < head.next.val:
        odd += 1
      head = head.next.next

    if even > odd:
      return 'Even'
    if even < odd:
      return 'Odd'
    return 'Tie'