Created
May 21, 2024 13:08
-
-
Save mauricioabreu/16739374d72fd21e6870f73ab71ae6b9 to your computer and use it in GitHub Desktop.
Univalue list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# recursive approach | |
# time = O(n) | |
# space = O(n) | |
def is_univalue_list(head, prev=None): | |
if not head: | |
return True | |
if head.val == prev or not prev: | |
return is_univalue_list(head.next, head.val) | |
else: | |
return False | |
# iterative approach | |
# time = O(n) | |
# space = O(1) | |
def is_univalue_list(head): | |
first = head.val | |
head = head.next | |
while head: | |
if head.val != first: | |
return False | |
head = head.next | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment