#1652
Defuse the Bomb
EasyArraySliding WindowSliding WindowArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a sliding window technique to efficiently calculate the sums. Instead of recalculating the sum for each index, we maintain a running sum, adjusting it as we move through the array.
⚙️
Algorithm
5 steps- 1Step 1: Initialize an empty result array of the same length as the input array.
- 2Step 2: If k is 0, return an array of zeros.
- 3Step 3: Calculate the initial sum of the first k elements (or the last -k elements if k < 0).
- 4Step 4: Use a loop to fill in the result array by adjusting the sum for each index using the sliding window technique.
- 5Step 5: Return the result array.
solution.py21 lines
1# Full working Python code
2
3def decrypt(code, k):
4 n = len(code)
5 result = [0] * n
6 if k == 0:
7 return result
8 sum_value = 0
9 if k > 0:
10 for j in range(1, k + 1):
11 sum_value += code[j % n]
12 for i in range(n):
13 result[i] = sum_value
14 sum_value += code[(i + k) % n] - code[i + 1]
15 else:
16 for j in range(-k):
17 sum_value += code[(n + j) % n]
18 for i in range(n):
19 result[i] = sum_value
20 sum_value += code[i - 1] - code[(i + k - 1 + n) % n]
21 return resultℹ
Complexity note: The time complexity is O(n) because we make a single pass through the array to calculate the initial sum and then another pass to fill the result array. The space complexity is O(n) due to the result array we create.
- 1Understanding circular arrays is crucial for proper index handling.
- 2Using a sliding window can significantly reduce time complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.