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.
7 → 7 → 7 // → true
7 → 7 → 8 // → false
(empty) // → true
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.
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."
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.
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.
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.
def is_univalue_list(head):
if head is None:
return True
node = head.next
while node is not None:
if node.val != head.val:
return False
node = node.next
return True
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.