DDSA Solutions

Is Linked List Length Even

Time: O(n)
Space: O(1)
Advertisement

Intuition

Check if linked list has even length. Count nodes or advance two pointers.

Algorithm

  1. 1Fast pointer: advance by 2 each step. If fast reaches null: even. If fast.next reaches null: odd.

Common Pitfalls

  • O(n/2) with fast pointer. Or simply count and check % 2.
Is Linked List Length Even.java
Java
// Approach: Move pointer two steps at a time; if null, length is even; if null after one step, odd.
// Time: O(n) Space: O(1)
class Solution {
    public boolean isLengthEven(Node head) {
        Node curr = head;

        int len = 0;
        while (curr != null) {
            curr = curr.next;
            len++;
        }

        return len % 2 == 0;
    }
}
Advertisement
Was this solution helpful?