Skip to main content

Defuse the Bomb - Solution & Explanation

EasyArraySliding Window25 min readAsked at: Amazon, Microsoft, Meta +2
Practice this problem

Problem Statement

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 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.

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.length
  • 1 <= n <= 100
  • 1 <= 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.

The C solution implements a sliding window technique. We first determine the starting and ending indices of the window based on the sign of k. For k > 0, the window slides to the right, and for k < 0, we slide to the left by transforming into a positive index shift using modulo operations. This avoids reconstructing the window repeatedly.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), where n is the length of the `code` array. Each element is processed once with constant-time window updates.
Space Complexity: O(1) auxiliary space (excluding the output array).

Try this approach in the editor →

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.

The C implementation iterates over each element in the code for every ith position, calculating indices either forward or backward with the consideration of code's circular nature via modulus operation. Simple yet clear, this needs careful attention to negative index wrapping.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n*k) with n as length of `code` and k an absolute value.
Space Complexity: O(1) extra space beyond output.

Try this approach in the editor →

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 k is a positive number, then the value at position i is the sum of the values at the k positions after position i, that is:

$ ans[i] = sum_{j=i+1}^{i+k} code[j bmod n]

  • 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, 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)$.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

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.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Two-Pointer Sliding Window Technique

Time Complexity: O(n), where n is the length of the `code` array. Each element is processed once with constant-time window updates.
Space Complexity: O(1) auxiliary space (excluding the output array).

Brute Force Approach

Time Complexity: O(n*k) with n as length of `code` and k an absolute value.
Space Complexity: O(1) extra space beyond output.

Simulation—
Prefix Sum—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force IterationO(n * |k|)O(n)Useful as a baseline or when constraints are very small and clarity matters more than optimization.
Two-Pointer Sliding WindowO(n)O(1) extraBest choice for large arrays. Efficiently maintains a running sum while moving a circular window.

Video Solution

Defuse the Bomb - Leetcode 1652 - Python • NeetCodeIO • 15,933 views views

Watch 9 more video solutions →

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.

Ready to solve this problem?

Practice Defuse the Bomb with our built-in code editor and test cases.

Practice on FleetCode