Defuse the Bomb

Python solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
    def decrypt(self, code: List[int], k: int) -> List[int]:
        res = [0] * len(code)
        if k == 0:
            return res
        start, end = 1, k
        sum_val = 0
        if k < 0:
            k = -k
            start = len(code) - k
            end = len(code) - 1
        for i in range(start, end + 1):
            sum_val += code[i]
        for i in range(len(code)):
            res[i] = sum_val
            sum_val -= code[start % len(code)]
            start += 1
            end += 1
            sum_val += code[end % len(code)]
        return res

In this code:

  • We first initialize the result list res with zeros. If k is zero, we return this list immediately.
  • If k is not zero, we prepare for the main computation by defining the initial window and sum.
  • If k is negative, we adjust the window to the end of the list.
  • We then compute the initial sum based on the current window.
  • After that, we iterate over the list, updating the sum for the new window at each step, and storing this sum in the corresponding position in res.
  • The window is updated by removing the contribution of the old start, moving the start and end, and adding the contribution of the new end.
  • Finally, we return res which contains the decrypted code.