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 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].
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code