Algorithmsmiddle logic

Middle Element Logic — Length vs Two Pointer

TT
Testlaa Team
May 14, 20261 min read

You can count n then walk n//2, or use two pointers. Trade time passes: two-pointer avoids a second scan but needs careful loop conditions.

Try this in Python

from __future__ import annotations
from dataclasses import dataclass


@dataclass
class Node:
    val: int
    next: Node | None = None


def to_list(head: Node | None) -> list[int]:
    out: list[int] = []
    while head:
        out.append(head.val)
        head = head.next
    return out


def from_list(vals: list[int]) -> Node | None:
    dummy = Node(0)
    cur = dummy
    for x in vals:
        cur.next = Node(x)
        cur = cur.next
    return dummy.next


def middle_by_len(head: Node | None) -> int | None:
    n = 0
    t = head
    while t:
        n += 1
        t = t.next
    t = head
    for _ in range(n // 2):
        t = t.next  # type: ignore
    return t.val if t else None

print(middle_by_len(from_list([1, 2, 3, 4])))

Key takeaways

  • Two-pass is still O(n) time and easy to reason about.
  • Useful when you also need length for splitting lists.
  • Pick one style and stay consistent in a contest.

Tags:

Linked listsPythonStudents