Skip to content

Commit 6f9038b

Browse files
authored
Create elimination-game.py
1 parent 1ab96ad commit 6f9038b

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Python/elimination-game.py

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Time: O(logn)
2+
# Space: O(1)
3+
4+
# There is a list of sorted integers from 1 to n. Starting from left to right,
5+
# remove the first number and every other number afterward until you reach the end of the list.
6+
#
7+
# Repeat the previous step again, but this time from right to left,
8+
# remove the right most number and every other number from the remaining numbers.
9+
#
10+
# We keep repeating the steps again, alternating left to right and right to left,
11+
# until a single number remains.
12+
#
13+
# Find the last number that remains starting with a list of length n.
14+
#
15+
# Example:
16+
#
17+
# Input:
18+
# n = 9,
19+
# 1 2 3 4 5 6 7 8 9
20+
# 2 4 6 8
21+
# 2 6
22+
# 6
23+
#
24+
# Output:
25+
# 6
26+
27+
class Solution(object):
28+
def lastRemaining(self, n):
29+
"""
30+
:type n: int
31+
:rtype: int
32+
"""
33+
start, step, direction = 1, 2, 1
34+
while n > 1:
35+
start += direction * (step * (n / 2) - step / 2)
36+
n /= 2
37+
step *= 2
38+
direction *= -1
39+
return start

0 commit comments

Comments
 (0)