Defuse the Bomb - Problem

๐ŸŽฏ Mission: Defuse the Bomb!

You're a bomb disposal expert with seconds left on the clock! Your informant has given you a circular array code of length n and a crucial decryption key k.

Decryption Rules:

  • If k > 0: Replace each number with the sum of the next k numbers
  • If k < 0: Replace each number with the sum of the previous k numbers
  • If k == 0: Replace each number with 0 (bomb is disabled!)

Important: The array is circular - after the last element comes the first, and before the first comes the last. All replacements happen simultaneously.

Example: code = [5,7,1,4], k = 3
โ€ข Position 0: sum of next 3 = 7+1+4 = 12
โ€ข Position 1: sum of next 3 = 1+4+5 = 10
โ€ข Result: [12,10,16,13]

Return the decrypted code to save the day!

Input & Output

example_1.py โ€” Basic Positive k
$ Input: code = [5,7,1,4], k = 3
โ€บ Output: [12,10,16,13]
๐Ÿ’ก Note: For k=3, each element is replaced by the sum of the next 3 elements: Position 0: 7+1+4=12, Position 1: 1+4+5=10 (wraps to start), Position 2: 4+5+7=16, Position 3: 5+7+1=13
example_2.py โ€” Negative k
$ Input: code = [1,2,3,4], k = -2
โ€บ Output: [7,9,1,3]
๐Ÿ’ก Note: For k=-2, each element is replaced by the sum of the previous 2 elements: Position 0: 4+3=7 (wraps to end), Position 1: 1+4=5, Position 2: 2+1=3, Position 3: 3+2=5
example_3.py โ€” Zero k
$ Input: code = [2,4,9,3], k = 0
โ€บ Output: [0,0,0,0]
๐Ÿ’ก Note: When k=0, the bomb is defused and all elements become 0

Visualization

Tap to expand
๐ŸŽฏ Circular Bomb Detection System571423Detection Window๐Ÿ’ฃ๐Ÿ” Sliding window efficiently processes each sensor position
Understanding the Visualization
1
Setup Window
Position the detection window at the first sensor
2
Calculate Initial
Sum the readings from the window's sensors
3
Slide Window
Move window to next position by removing old sensor and adding new one
4
Update Efficiently
Update sum with just two operations instead of recalculating everything
Key Takeaway
๐ŸŽฏ Key Insight: The sliding window technique transforms this from O(nร—k) to O(n) by reusing calculations - perfect for circular arrays!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through the array after initial window setup

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using constant extra space besides result array

n
2n
โœ“ Linear Space

Constraints

  • n == code.length
  • 1 โ‰ค n โ‰ค 100
  • 1 โ‰ค code[i] โ‰ค 100
  • -n โ‰ค k โ‰ค n
  • The array is circular - elements wrap around
Asked in
Amazon 15 Google 12 Microsoft 8 Meta 6
38.5K Views
Medium Frequency
~15 min Avg. Time
1.4K 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