Skip to content

Instantly share code, notes, and snippets.

@AriTedeschi
Created April 14, 2024 12:08
Show Gist options
  • Save AriTedeschi/36edbc3424bf1df69314af2e2e48e687 to your computer and use it in GitHub Desktop.
Save AriTedeschi/36edbc3424bf1df69314af2e2e48e687 to your computer and use it in GitHub Desktop.
Solution to Single Number Problem
#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