Skip to content

Commit 4a910cc

Browse files
committed
Defuse the bomb
1 parent 7830307 commit 4a910cc

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

1652.defuse_the_bomb/defuse.py

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# 1652. Defuse the bomb
2+
# Topics: 'Array', 'Sliding Window'
3+
#
4+
# You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code of length of n and a key k.
5+
6+
# To decrypt the code, you must replace every number. All the numbers are replaced simultaneously.
7+
8+
# If k > 0, replace the ith number with the sum of the next k numbers.
9+
# If k < 0, replace the ith number with the sum of the previous k numbers.
10+
# If k == 0, replace the ith number with 0.
11+
12+
# As code is circular, the next element of code[n-1] is code[0], and the previous element of code[0] is code[n-1].
13+
14+
# Given the circular array code and an integer key k, return the decrypted code to defuse the bomb!
15+
16+
17+
18+
# Example 1:
19+
20+
# Input: code = [5,7,1,4], k = 3
21+
# Output: [12,10,16,13]
22+
# Explanation: Each number is replaced by the sum of the next 3 numbers. The decrypted code is [7+1+4, 1+4+5, 4+5+7, 5+7+1]. Notice that the numbers wrap around.
23+
24+
# Example 2:
25+
26+
# Input: code = [1,2,3,4], k = 0
27+
# Output: [0,0,0,0]
28+
# Explanation: When k is zero, the numbers are replaced by 0.
29+
30+
# Example 3:
31+
32+
# Input: code = [2,4,9,3], k = -2
33+
# Output: [12,5,6,13]
34+
# Explanation: The decrypted code is [3+9, 2+3, 4+2, 9+4]. Notice that the numbers wrap around again. If k is negative, the sum is of the previous numbers.
35+
36+
37+
38+
# Constraints:
39+
40+
# n == code.length
41+
# 1 <= n <= 100
42+
# 1 <= code[i] <= 100
43+
# -(n - 1) <= k <= n - 1
44+
45+
from typing import List
46+
47+
48+
class Solution:
49+
def decrypt(self, code: List[int], k: int) -> List[int]:
50+
if k == 0:
51+
return [0] * len(code)
52+
result = []
53+
if k < 0:
54+
window = None
55+
code.reverse()
56+
for i in range(len(code)):
57+
window = calculate_window(code, i+1, -k, window)
58+
result.append(window)
59+
result.reverse()
60+
else:
61+
window = None
62+
for i in range (len(code)):
63+
window = calculate_window(code, i+1, k, window)
64+
result.append(window)
65+
66+
return result
67+
68+
def calculate_window(code: List[int], start: int, k: int, window: int)-> int:
69+
if window is None:
70+
window = 0
71+
while k > 0:
72+
if start == len(code):
73+
start = 0
74+
window += code[start]
75+
start+=1
76+
k-=1
77+
else:
78+
window -= code[start-1]
79+
end = start + k - 1
80+
if end >= len(code):
81+
end = end - len(code)
82+
window += code[end]
83+
84+
return window
85+

0 commit comments

Comments
 (0)