Defuse the Bomb - 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 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].

Return the decrypted code to defuse the bomb!

Input & Output

Example 1 — Positive k
$ Input: code = [5,7,1,4], k = 3
Output: [12,10,16,13]
💡 Note: For i=0: sum of next 3 elements = 7+1+4 = 12. For i=1: sum of next 3 elements = 1+4+5 = 10 (wraps around). For i=2: sum of next 3 elements = 4+5+7 = 16. For i=3: sum of next 3 elements = 5+7+1 = 13.
Example 2 — Negative k
$ Input: code = [1,2,3,4], k = -2
Output: [7,5,3,5]
💡 Note: For i=0: sum of previous 2 elements = 4+3 = 7 (positions -1,-2 wrap to indices 3,2). For i=1: sum of previous 2 elements = 1+4 = 5 (positions 0,-1 wrap to indices 0,3). For i=2: sum of previous 2 elements = 2+1 = 3 (positions 1,0). For i=3: sum of previous 2 elements = 3+2 = 5 (positions 2,1).
Example 3 — Zero k
$ Input: code = [2,4,9,3], k = 0
Output: [0,0,0,0]
💡 Note: When k=0, all elements are replaced with 0.

Constraints

  • n == code.length
  • 1 ≤ n ≤ 100
  • 1 ≤ code[i] ≤ 100
  • -(n-1) ≤ k ≤ n-1

Visualization

Tap to expand
Defuse the Bomb - Circular Array Decryption INPUT 5 i=0 7 i=1 4 i=3 1 i=2 Input Parameters: code = [5, 7, 1, 4] k = 3 (positive) Sum next k elements ALGORITHM STEPS 1 Sliding Window Init Create window of size k 2 Calculate First Sum Sum indices 1,2,3 for i=0 3 Slide Window Add next, remove first 4 Handle Circular Use modulo for wrap Calculations (k=3, sum next 3): i=0: sum(7+1+4) = 12 i=1: sum(1+4+5) = 10 i=2: sum(4+5+7) = 16 i=3: sum(5+7+1) = 13 O(n) time complexity O(n) space complexity FINAL RESULT 12 10 13 16 Decrypted Code: [12, 10, 16, 13] OK - Bomb Defused! Key Insight: Use a sliding window to maintain the running sum. When k > 0, sum the next k elements circularly. The modulo operator (index % n) handles circular wrapping. Slide window: add entering element, subtract leaving element. This achieves O(n) time instead of O(n*k) brute force approach. TutorialsPoint - Defuse the Bomb | Optimal Solution (Sliding Window)
Asked in
Amazon 15 Microsoft 8
28.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen