Created
April 14, 2024 12:08
-
-
Save AriTedeschi/36edbc3424bf1df69314af2e2e48e687 to your computer and use it in GitHub Desktop.
Solution to Single Number Problem
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
#Linear solution O(n) | |
#Constant space | |
def uniqueNumber(sequence) -> int: | |
# flags which stores repeated numbers | |
# It works for 3 repetions only | |
once = 0 | |
twice = 0 | |
for num in sequence: | |
once, twice = canBeSettedInFlag(num,once,twice) | |
twice, once = canBeSettedInFlag(num,twice,once) | |
return once | |
# Checks whether e (element) is already on destinationFlag, case not it will try set | |
# Before set in destinationFlag it validates whether another flag contains it, case not it will be setted | |
def canBeSettedInFlag(e, destinationFlag, otherFlag): | |
destinationFlag = (destinationFlag ^ e) & ~ otherFlag | |
return destinationFlag, otherFlag | |
sequence = [2,1,1,1,2,2,3] | |
print(uniqueNumber(sequence)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment