Defuse the Bomb

easy sliding window circular array

Problem

A bomb's code is a circular array of n digits plus a key k. To decrypt it, every position is replaced simultaneously: if k > 0, position i becomes the sum of the next k numbers; if k < 0, it becomes the sum of the previous |k| numbers; if k = 0, it becomes 0. Because the array is circular, sums wrap around either end.

Constraints: 1 ≤ n ≤ 100, 1 ≤ code[i] ≤ 100, and −(n − 1) ≤ k ≤ n − 1. Return the decrypted array.

Inputcode = [5,7,1,4], k = 3
Output[12,10,16,13]
Each digit becomes the sum of the next 3, wrapping around: 7+1+4=12, 1+4+5=10, 4+5+7=16, 5+7+1=13.

def decrypt(code, k):
    n = len(code)
    res = [0] * n
    if k == 0:
        return res
    lo, hi = (1, k) if k > 0 else (n + k, n - 1)
    win = sum(code[j % n] for j in range(lo, hi + 1))
    for i in range(n):
        res[i] = win
        win -= code[lo % n]
        win += code[(hi + 1) % n]
        lo += 1
        hi += 1
    return res
function decrypt(code, k) {
  const n = code.length;
  const res = new Array(n).fill(0);
  if (k === 0) return res;
  let lo = k > 0 ? 1 : n + k;
  let hi = k > 0 ? k : n - 1;
  let win = 0;
  for (let j = lo; j <= hi; j++) win += code[j % n];
  for (let i = 0; i < n; i++) {
    res[i] = win;
    win -= code[lo % n];
    win += code[(hi + 1) % n];
    lo++; hi++;
  }
  return res;
}
int[] decrypt(int[] code, int k) {
    int n = code.length;
    int[] res = new int[n];
    if (k == 0) return res;
    int lo = k > 0 ? 1 : n + k;
    int hi = k > 0 ? k : n - 1;
    int win = 0;
    for (int j = lo; j <= hi; j++) win += code[j % n];
    for (int i = 0; i < n; i++) {
        res[i] = win;
        win -= code[lo % n];
        win += code[(hi + 1) % n];
        lo++; hi++;
    }
    return res;
}
vector<int> decrypt(vector<int>& code, int k) {
    int n = code.size();
    vector<int> res(n, 0);
    if (k == 0) return res;
    int lo = k > 0 ? 1 : n + k;
    int hi = k > 0 ? k : n - 1;
    int win = 0;
    for (int j = lo; j <= hi; j++) win += code[j % n];
    for (int i = 0; i < n; i++) {
        res[i] = win;
        win -= code[lo % n];
        win += code[(hi + 1) % n];
        lo++; hi++;
    }
    return res;
}
Time: O(n) Space: O(n)