Skip to content

Instantly share code, notes, and snippets.

@ilyasfoo
Created November 9, 2018 04:13
Show Gist options
  • Save ilyasfoo/79d0f2001334827eeb69e0e128b1a07a to your computer and use it in GitHub Desktop.
Save ilyasfoo/79d0f2001334827eeb69e0e128b1a07a to your computer and use it in GitHub Desktop.
class Solution:
def lastRemaining(self, n):
"""
:type n: int
:rtype: int
"""
odd = True
remainder = n
startNum = 1
power = 1
while remainder > 1:
if remainder == 2:
return startNum+power if odd else startNum
elif remainder == 3:
return startNum+power
# startNum increases only by 2 case, if the remainder is odd OR if the step is odd
startNum += power if remainder % 2 == 1 or odd else 0
power *= 2
# Divide by 2 and floor
remainder //= 2
odd = not odd
# n == 1 returns 1
return 1
@ilyasfoo
Copy link
Author

ilyasfoo commented Nov 9, 2018

Space complexity: O(1)
Time complexity: O(log n)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment