Check if elements of Linked List are present in pair in Python

A linked list has elements in pairs when every element appears an even number of times. This problem can be efficiently solved using the XOR operation, which has a useful property: XORing identical numbers results in 0.

Algorithm Explanation

The XOR approach works because:

  • XORing any number with itself gives 0
  • XOR is commutative, so order doesn't matter
  • If all elements appear in pairs (even times), the final XOR result will be 0
  • If any element appears an odd number of times, the result will be non-zero

Implementation Steps

To solve this problem, we follow these steps ?

  • Initialize xor_res := 0 and current_node := head of linked list
  • While current_node is not null, do
    • xor_res := xor_res XOR value of current_node
    • current_node := next of current_node
  • Return False when xor_res is non-zero, otherwise True

Example

Let us see the following implementation to get better understanding ?

class ListNode:
    def __init__(self, data, next=None):
        self.val = data
        self.next = next

def make_list(elements):
    head = ListNode(elements[0])
    for element in elements[1:]:
        ptr = head
        while ptr.next:
            ptr = ptr.next
        ptr.next = ListNode(element)
    return head

def solve(head):
    xor_res = 0
    current_node = head
    while current_node != None:
        xor_res = xor_res ^ current_node.val
        current_node = current_node.next
    return False if xor_res else True

# Test case 1: All elements in pairs
head1 = make_list([2, 5, 5, 2, 3, 3])
print("List [2, 5, 5, 2, 3, 3]:", solve(head1))

# Test case 2: One element appears odd times
head2 = make_list([1, 2, 3, 2, 1])
print("List [1, 2, 3, 2, 1]:", solve(head2))

The output of the above code is ?

List [2, 5, 5, 2, 3, 3]: True
List [1, 2, 3, 2, 1]: False

How It Works

For the list [2, 5, 5, 2, 3, 3]:

  • XOR sequence: 0 ^ 2 ^ 5 ^ 5 ^ 2 ^ 3 ^ 3
  • Since 5^5 = 0, 2^2 = 0, and 3^3 = 0
  • Final result: 0 (all elements are paired)

Time and Space Complexity

  • Time Complexity: O(n) where n is the number of nodes
  • Space Complexity: O(1) as we only use constant extra space

Conclusion

The XOR approach provides an elegant O(1) space solution to check if linked list elements appear in pairs. This method leverages XOR's mathematical property where identical numbers cancel out to zero.

Updated on: 2026-03-25T15:00:42+05:30

381 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements