Defuse the Bomb solution and explanation
9 more videos on this problem
Defuse the Bomb - Leetcode 1652 - PythonNeetCodeIO · 13:57 · 15K views
Defuse the Bomb | Detailed for Beginners | Leetcode 1652 | codestorywithMIKcodestorywithMIK · 21:21 · 8K views
Defuse the Bomb | Leetcode 1652Techdose · 19:32 · 4K views
1652. Defuse the Bomb | Sliding Window | 2 ApproachesAryan Mittal · 12:49 · 3K views
1652. Defuse the Bomb (Leetcode Easy)Programming Live with Larry · 4:48 · 2K views
Defuse the Bomb | Leetcode 1652 | Amazon Google Facebook interview questionSuper Lazy Coder · 14:46 · 2K views
LeetCode 1652. [easy] Defuse the BombFrancesco Manicardi · 4:44 · 2K views
Solving LeetCode 1652 Defuse the Bomb | Sliding Window | Amazon | Detailed ExplanationCode Harmony · 22:32 · 1K views
DEFUSE THE BOMB | LEETCODE 1652 | PYTHON SLIDING WINDOW SOLUTIONCracking FAANG · 8:03 · 930 views
1652. Defuse the Bomb | LeetCode 1652 | Java Solution ExplainedCode Wizard · 9:11 · 508 views
The problem
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.
To decrypt the code, you must replace every number. All the numbers are replaced simultaneously.
- If
k > 0, replace theithnumber with the sum of the nextknumbers. - If
k < 0, replace theithnumber with the sum of the previousknumbers. - If
k == 0, replace theithnumber with0.
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].
Given the circular array code and an integer key k, return the decrypted code to defuse the bomb!
Example 1:
Input: code = [5,7,1,4], k = 3 Output: [12,10,16,13] 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.
Example 2:
Input: code = [1,2,3,4], k = 0 Output: [0,0,0,0] Explanation: When k is zero, the numbers are replaced by 0.
Example 3:
Input: code = [2,4,9,3], k = -2 Output: [12,5,6,13] 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.
Constraints:
n == code.length1 <= n <= 1001 <= code[i] <= 100-(n - 1) <= k <= n - 1
Approach overview
Problem Overview: You are given a circular array code and an integer k. Each element must be replaced by the sum of the next k elements if k > 0, the previous |k| elements if k < 0, or 0 if k == 0. Because the array is circular, indices wrap around the end.
The key challenge is handling the circular nature efficiently while computing multiple range sums.
Approach 1: Brute Force Iteration (O(n * |k|) time, O(n) space)
The straightforward solution iterates through every index and manually sums the required k neighbors. For each position i, run another loop that adds the next or previous |k| elements while applying modulo arithmetic to wrap around the array. This guarantees correctness and is easy to implement, especially when first understanding the circular behavior.
The downside is repeated work. Each element recomputes a sum from scratch, leading to O(n * |k|) time complexity. When k approaches n, performance degrades significantly. Space complexity remains O(n) because a separate result array is required. This approach mainly serves as a baseline before optimizing.
Approach 2: Two-Pointer Sliding Window Technique (O(n) time, O(1) extra space)
The optimal solution treats the required k elements as a sliding window over the circular array. Instead of recomputing each sum, maintain a running window sum and shift the window by one position at every step.
If k > 0, initialize a window covering indices 1 through k. If k < 0, build the window from n-|k| through n-1. After computing the first window sum, move both window boundaries forward using two pointers while updating the sum: subtract the element leaving the window and add the new element entering it. Use modulo arithmetic to keep indices within bounds of the circular array.
This technique avoids redundant summation. Each element enters and leaves the window exactly once, producing O(n) time complexity and O(1) auxiliary space beyond the output array. The pattern is a classic application of Sliding Window optimization on a circular Array. Managing the boundaries with two pointers makes the transitions predictable and efficient.
Recommended for interviews: Start by describing the brute force method to demonstrate understanding of the circular indexing rules. Then move to the sliding window optimization. Interviewers typically expect the O(n) two-pointer solution because it eliminates repeated work and shows familiarity with sliding window patterns applied to circular arrays.
Approach 1: Two-Pointer Sliding Window Technique
This approach uses a sliding window technique to efficiently calculate the sum of required elements. By maintaining a running sum for the window and updating it as you slide, you can achieve the necessary transformation in linear time. The key is to account for the circular nature of the array using modulo operations to wrap around indices.
def decrypt(code, k):
n = len(code)
result = [0] * n
if k == 0:
return result
start, end = (1, k) if k > 0 else (n-k, n-1)
sum_vals = sum(code[i % n] for i in range(start, end + 1))
for i in range(n):
result[i] = sum_vals
sum_vals -= code[start % n]
sum_vals += code[(end + 1) % n]
start += 1
end += 1
return result
# Example usage
code = [5, 7, 1, 4]
k = 3
print(decrypt(code, k))import java.util.Arrays;
public class Solution {
public int[] decrypt(int[] code, int k) {
int n = code.length;
int[] result = new int[n];
if (k == 0) return result;
int start, end;
if (k > 0) {
start = 1;
end = k;
} else {
k = -k;
start = n - k;
end = n - 1;
}
int sum = 0;
for (int i = start; i <= end; i++) {
sum += code[i % n];
}
for (int i = 0; i < n; i++) {
result[i] = sum;
sum -= code[start % n];
sum += code[(end + 1) % n];
start++;
end++;
}
return result;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] code = {5, 7, 1, 4};
int k = 3;
System.out.println(Arrays.toString(sol.decrypt(code, k)));
}
}#include <vector>
#include <iostream>
using namespace std;
vector<int> decrypt(vector<int>& code, int k) {
int n = code.size();
vector<int> result(n, 0);
if (k == 0) return result;
int start = 1, end = k, sum = 0;
if (k < 0) {
k = -k;
start = n - k;
end = n - 1;
}
for (int i = start; i <= end; ++i) {
sum += code[i % n];
}
for (int i = 0; i < n; ++i) {
result[i] = sum;
sum -= code[start % n];
sum += code[(end + 1) % n];
start++;
end++;
}
return result;
}
int main() {
vector<int> code = {5, 7, 1, 4};
int k = 3;
vector<int> decrypted = decrypt(code, k);
for (int num : decrypted) {
cout << num << " ";
}
return 0;
}function decrypt(code, k) {
const n = code.length;
const result = new Array(n).fill(0);
if (k === 0) return result;
let start = k > 0 ? 1 : n + k;
let end = k > 0 ? k : n - 1;
let sum = 0;
for (let i = start; i <= end; i++) {
sum += code[i % n];
}
for (let i = 0; i < n; i++) {
result[i] = sum;
sum -= code[start % n];
sum += code[(end + 1) % n];
start++;
end++;
}
return result;
}
// Example usage
let code = [5, 7, 1, 4];
let k = 3;
console.log(decrypt(code, k));#include <stdio.h>
#include <stdlib.h>
int* decrypt(int* code, int codeSize, int k, int* returnSize) {
*returnSize = codeSize;
int* result = (int*)malloc(sizeof(int) * codeSize);
if (k == 0) {
for (int i = 0; i < codeSize; i++) {
result[i] = 0;
}
} else {
int start = 1, end = k;
if (k < 0) {
k = -k;
start = codeSize - k;
end = codeSize - 1;
}
int sum = 0;
for (int i = start; i <= end; i++) {
sum += code[i % codeSize];
}
for (int i = 0; i < codeSize; i++) {
result[i] = sum;
sum -= code[start % codeSize];
sum += code[(end + 1) % codeSize];
start++;
end++;
}
}
return result;
}
int main() {
int code[] = {5, 7, 1, 4};
int k = 3;
int returnSize;
int* decrypted = decrypt(code, 4, k, &returnSize);
for (int i = 0; i < returnSize; i++) {
printf("%d ", decrypted[i]);
}
free(decrypted);
return 0;
}using System;
public class Solution {
public int[] Decrypt(int[] code, int k) {
int n = code.Length;
int[] result = new int[n];
if (k == 0) return result;
int start = k > 0 ? 1 : n + k;
int end = k > 0 ? k : n - 1;
int sum = 0;
for (int i = start; i <= end; i++) {
sum += code[i % n];
}
for (int i = 0; i < n; i++) {
result[i] = sum;
sum -= code[start % n];
sum += code[(end + 1) % n];
start++;
end++;
}
return result;
}
public static void Main() {
Solution sol = new Solution();
int[] code = {5, 7, 1, 4};
int k = 3;
Console.WriteLine(string.Join(", ", sol.Decrypt(code, k)));
}
}This Python solution maintains the sliding window sum and adjusts it while traversing over code using modulo operations. It initializes the sum with the first k values or their complements based on k being positive or negative. Such index calculations handle the array's circular nature effectively.
Time Complexity: O(n).
Space Complexity: O(n) for the result list, as additional storage is not significant.
Approach 2: Brute Force Approach
This approach is straightforward but less efficient, involving a direct sum computation for each index by wrapping around using the modulo operator. Each element's circular context is individually recalculated, following conditions for the sign of k.
def decrypt(code, k):
n = len(code)
result = [0] * n
if k == 0:
return result
for i in range(n):
total = 0
for j in range(1, abs(k) + 1):
index = (i + j) % n if k > 0 else (i - j + n) % n
total += code[index]
result[i] = total
return result
# Example usage
code = [5, 7, 1, 4]
k = 3
print(decrypt(code, k))import java.util.Arrays;
public class Solution {
public int[] decrypt(int[] code, int k) {
int n = code.length;
int[] result = new int[n];
if (k == 0) return result;
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = 1; j <= Math.abs(k); j++) {
int index = (k > 0) ? (i + j) % n : (i - j + n) % n;
sum += code[index];
}
result[i] = sum;
}
return result;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] code = {5, 7, 1, 4};
int k = 3;
System.out.println(Arrays.toString(sol.decrypt(code, k)));
}
}#include <vector>
#include <iostream>
#include <cmath>
using namespace std;
vector<int> decrypt(vector<int>& code, int k) {
int n = code.size();
vector<int> result(n);
if (k == 0) return vector<int>(n, 0);
for (int i = 0; i < n; ++i) {
int sum = 0;
for (int j = 1; j <= abs(k); ++j) {
int index = (k > 0) ? (i + j) % n : (i - j + n) % n;
sum += code[index];
}
result[i] = sum;
}
return result;
}
int main() {
vector<int> code = {5, 7, 1, 4};
int k = 3;
vector<int> decrypted = decrypt(code, k);
for (int num : decrypted) {
cout << num << " ";
}
return 0;
}function decrypt(code, k) {
const n = code.length;
const result = new Array(n).fill(0);
if (k === 0) return result;
for (let i = 0; i < n; i++) {
let sum = 0;
for (let j = 1; j <= Math.abs(k); j++) {
const index = k > 0 ? (i + j) % n : (i - j + n) % n;
sum += code[index];
}
result[i] = sum;
}
return result;
}
// Example usage
let code = [5, 7, 1, 4];
let k = 3;
console.log(decrypt(code, k));#include <stdio.h>
#include <stdlib.h>
int* decrypt(int* code, int codeSize, int k, int* returnSize) {
*returnSize = codeSize;
int* result = (int*)malloc(sizeof(int) * codeSize);
if (k == 0) {
for (int i = 0; i < codeSize; i++) {
result[i] = 0;
}
} else {
for (int i = 0; i < codeSize; i++) {
int sum = 0;
for (int j = 1; j <= abs(k); j++) {
int index = (k > 0) ? (i + j) % codeSize : (i - j + codeSize) % codeSize;
sum += code[index];
}
result[i] = sum;
}
}
return result;
}
int main() {
int code[] = {5, 7, 1, 4};
int k = 3;
int returnSize;
int* decrypted = decrypt(code, 4, k, &returnSize);
for (int i = 0; i < returnSize; i++) {
printf("%d ", decrypted[i]);
}
free(decrypted);
return 0;
}using System;
public class Solution {
public int[] Decrypt(int[] code, int k) {
int n = code.Length;
int[] result = new int[n];
if (k == 0) return result;
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = 1; j <= Math.Abs(k); j++) {
int index = (k > 0) ? (i + j) % n : (i - j + n) % n;
sum += code[index];
}
result[i] = sum;
}
return result;
}
public static void Main() {
Solution sol = new Solution();
int[] code = {5, 7, 1, 4};
int k = 3;
Console.WriteLine(string.Join(", ", sol.Decrypt(code, k)));
}
}The Python implementation applies a straightforward nested loop to compute the sum for each element's neighboring indices accordingly, flexibly supporting an index adjustment for k values in either direction using modulo arithmetic.
Time Complexity: O(n*k).
Space Complexity: O(n) for storage of the resultant output sequence.
Approach 3: Simulation
We define an answer array ans of length n, initially all elements are 0. According to the problem, if k is 0, return ans directly.
Otherwise, we traverse each position i:
- If
kis a positive number, then the value at positioniis the sum of the values at thekpositions after positioni, that is:
$
ans[i] = sum_{j=i+1}^{i+k} code[j bmod n]
- If
kis a negative number, then the value at positioniis the sum of the values at the|k|positions before positioni, that is:
ans[i] = sum_{j=i+k}^{i-1} code[(j+n) bmod n]
The time complexity is O(n times |k|), ignoring the space consumption of the answer, the space complexity is O(1)$.
function decrypt(code: number[], k: number): number[] {
const n: number = code.length;
const ans: number[] = Array(n).fill(0);
if (k === 0) {
return ans;
}
for (let i = 0; i < n; ++i) {
if (k > 0) {
for (let j = i + 1; j < i + k + 1; ++j) {
ans[i] += code[j % n];
}
} else {
for (let j = i + k; j < i; ++j) {
ans[i] += code[(j + n) % n];
}
}
}
return ans;
}func decrypt(code []int, k int) []int {
n := len(code)
ans := make([]int, n)
if k == 0 {
return ans
}
for i := 0; i < n; i++ {
if k > 0 {
for j := i + 1; j < i+k+1; j++ {
ans[i] += code[j%n]
}
} else {
for j := i + k; j < i; j++ {
ans[i] += code[(j+n)%n]
}
}
}
return ans
}Approach 4: Prefix Sum
In Solution 1, for each position i, we need to traverse k positions, which involves a lot of repeated calculations. We can optimize this by using prefix sums.
We duplicate the code array (this can be achieved without actually duplicating the array, but by cyclically traversing with modulo operation), resulting in an array of twice the length. We then calculate the prefix sum of this array, resulting in a prefix sum array s of length 2 times n + 1.
If k is a positive number, then the value at position i is the sum of the values at the k positions after position i, i.e., ans[i] = s[i + k + 1] - s[i + 1].
If k is a negative number, then the value at position i is the sum of the values at the |k| positions before position i, i.e., ans[i] = s[i + n] - s[i + k + n].
The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the code array.
function decrypt(code: number[], k: number): number[] {
const n: number = code.length;
const ans: number[] = Array(n).fill(0);
if (k === 0) {
return ans;
}
const s: number[] = Array((n << 1) | 1).fill(0);
for (let i = 0; i < n << 1; ++i) {
s[i + 1] = s[i] + code[i % n];
}
for (let i = 0; i < n; ++i) {
if (k > 0) {
ans[i] = s[i + k + 1] - s[i + 1];
} else {
ans[i] = s[i + n] - s[i + k + n];
}
}
return ans;
}func decrypt(code []int, k int) []int {
n := len(code)
ans := make([]int, n)
if k == 0 {
return ans
}
s := make([]int, n<<1|1)
for i := 0; i < n<<1; i++ {
s[i+1] = s[i] + code[i%n]
}
for i := range code {
if k > 0 {
ans[i] = s[i+k+1] - s[i+1]
} else {
ans[i] = s[i+n] - s[i+k+n]
}
}
return ans
}Complexity comparison
| Approach | Complexity |
|---|---|
| Two-Pointer Sliding Window Technique | Time Complexity: O(n). |
| Brute Force Approach | Time Complexity: O(n*k). |
| Simulation | – |
| Prefix Sum | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Iteration | O(n * |k|) | O(n) | Useful as a baseline or when constraints are very small and clarity matters more than optimization. |
| Two-Pointer Sliding Window | O(n) | O(1) extra | Best choice for large arrays. Efficiently maintains a running sum while moving a circular window. |
Frequently asked questions
Is Defuse the Bomb easy or hard?
Defuse the Bomb is classified as an Easy problem on LeetCode with a high acceptance rate around 79%. The main challenge is recognizing the sliding window optimization and correctly handling circular indexing with modulo operations.
Defuse the Bomb Python/Java solution
Most implementations follow the same logic across languages: compute the first window sum, then slide the window across the circular array while updating the sum. This pattern translates cleanly into Python, Java, C++, C#, and JavaScript with identical O(n) complexity.
How to solve Defuse the Bomb in O(n)?
Use a sliding window to maintain the sum of the required k elements. Initialize the window for the first index, compute the sum once, then move the window forward by subtracting the outgoing element and adding the incoming element. Apply modulo indexing to handle the circular array behavior.
What is the best approach for Defuse the Bomb?
The most efficient approach uses a sliding window with two pointers. Instead of recomputing sums for every index, maintain a running window sum and slide it across the circular array. Each element enters and leaves the window exactly once, resulting in O(n) time complexity and O(1) extra space.
Is Defuse the Bomb asked at Google/Amazon/Meta?
This problem represents a common sliding window pattern on circular arrays. Similar patterns frequently appear in interviews at companies like Amazon and Google, especially when testing understanding of window-based optimizations and modular indexing.
What data structure is used in Defuse the Bomb?
The problem primarily uses an array along with a sliding window technique. Two pointers track the window boundaries while a running sum maintains the current window total. No advanced data structures such as heaps or hash maps are required.
What is the time complexity of Defuse the Bomb?
The brute force approach runs in O(n * |k|) time because each element recomputes the sum of k neighbors. The optimized sliding window approach reduces this to O(n) time since the window sum is updated incrementally as the window moves across the circular array.
