#1652
Easy Algorithms Defuse the bomb
Array Sliding Window
79.3% acceptance
Feb 25, 2026
1598
181
You have a bomb to defuse, and your time is running out! Your informer will
provide you with a circular array code of length n and a key k.
To decrypt the code, you must replace every number. All the numbers are
replaced simultaneously.
If k > 0, replace the ith number with the sum of the next k numbers.
If k < 0, replace the ith number with the sum of the previous |k| numbers.
If k == 0, replace the ith number with 0.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn decrypt(code: Vec<i32>, k: i32) -> Vec<i32> {
let n = code.len();
if k == 0 {
return vec![0; n];
}
let mut result = vec![0i32; n];
for i in 0..n {
if k > 0 {
for j in 1..=k as usize {
result[i] += code[(i + j) % n];
}
} else {
let kk = (-k) as usize;
for j in 1..=kk {
result[i] += code[(i + n - j) % n];
}
}
}
result
}
}