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 with0(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
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
โ Linear Growth
Space Complexity
O(1)
Only using constant extra space besides result array
โ Linear Space
Constraints
- n == code.length
- 1 โค n โค 100
- 1 โค code[i] โค 100
- -n โค k โค n
- The array is circular - elements wrap around
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code