Is Univalue List

Is Univalue List

Return true if every node in the list holds the same value. An empty list counts as univalue.

isUnivalueList(head)

Input format: space-separated node values.

Examples

7 → 7 → 7   // → true
7 → 7 → 8   // → false
(empty)     // → true

Walkthrough

Thinking it through

Checking whether every node shares the same value is a search for a counterexample: the list is univalue unless you find at least one node that breaks the pattern. That reframing tells you exactly what to look for, and when you're allowed to stop.

Choosing a reference value

To decide "all values are the same," you need something to compare against. The first node's value works: if every other node matches it, the whole list is univalue — "all equal" just means "all equal to any one of them."

Building the approach

  1. Handle the empty list first: with no nodes, nothing could disagree, so it's vacuously univalue — return true immediately.
  2. Otherwise, remember the head's value as your reference.
  3. Walk the rest of the list, checking each node against the reference.
  4. The moment a value differs, you have your counterexample — stop and return false.
  5. If you make it through without a mismatch, return true.

Why you can stop early on a mismatch

Proving something is not true only needs one counterexample, so the moment you find a differing node, you're done. But proving something is true requires checking everything, since a mismatch could be lurking anywhere, including the very last node.

Why the empty list needs explicit handling here

Unlike sum-list, where zero makes the empty case fall out for free, there's no reference value to compare against if there's no head node — so the empty list needs an explicit check rather than relying on a loop that happens not to run.

Why this is efficient and can't be beaten

In the worst case (all match, or the mismatch is at the very end), you inspect every node once — linear time, and there's no way around that, since skipping even one node risks missing the counterexample. Only one value needs to be remembered throughout, so extra memory stays constant.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.