Skip to content

1652. Defuse the Bomb 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  vector<int> decrypt(vector<int>& code, int k) {
    const int n = code.size();
    vector<int> ans(n);
    if (k == 0)
      return ans;

    int sum = 0;
    int start = k > 0 ? 1 : n + k;  // the start of the next k numbers
    int end = k > 0 ? k : n - 1;    // the end of the next k numbers

    for (int i = start; i <= end; ++i)
      sum += code[i];

    for (int i = 0; i < n; ++i) {
      ans[i] = sum;
      sum -= code[start++ % n];
      sum += code[++end % n];
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public int[] decrypt(int[] code, int k) {
    final int n = code.length;
    int[] ans = new int[n];
    if (k == 0)
      return ans;

    int sum = 0;
    int start = k > 0 ? 1 : n + k; // the start of the next k numbers
    int end = k > 0 ? k : n - 1;   // the end of the next k numbers

    for (int i = start; i <= end; ++i)
      sum += code[i];

    for (int i = 0; i < n; ++i) {
      ans[i] = sum;
      sum -= code[start++ % n];
      sum += code[++end % n];
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
  def decrypt(self, code: list[int], k: int) -> list[int]:
    n = len(code)
    ans = [0] * n
    if k == 0:
      return ans

    summ = 0
    start = 1 if k > 0 else n + k  # the start of the next k numbers
    end = k if k > 0 else n - 1  # the end of the next k numbers

    for i in range(start, end + 1):
      summ += code[i]

    for i in range(n):
      ans[i] = summ
      summ -= code[start % n]
      start += 1
      end += 1
      summ += code[end % n]

    return ans