-
Notifications
You must be signed in to change notification settings - Fork 255
Defuse the Bomb
Raymond Chen edited this page Aug 1, 2024
·
4 revisions
TIP102 Unit 1 Session 1 Advanced (Click for link to problem statements)
- 💡 Difficulty: Easy
- ⏰ Time to complete: 10 mins
- 🛠️ Topics: Arrays
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
- The function
defuse()
should take a circular array code and an integer k, returning a new array where each element is replaced based on the value of k.
HAPPY CASE
Input: code = [5, 7, 1, 4], k = 3
Expected Output: [12, 10, 16, 13]
Input: code = [2, 4, 9, 3], k = -2
Expected Output: [12, 5, 6, 13]
EDGE CASE
Input: code = [1, 2, 3, 4], k = 0
Expected Output: [0, 0, 0, 0]
Input: code = [5], k = 1
Expected Output: [5]
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Depending on the value of k, either sum the next k elements or the previous k elements for each element in the array. Use modulo arithmetic to handle the circular nature of the array.
1. Initialize `result` as a list of zeros with the same length as `code`.
2. If `k == 0`, return `result`.
3. Iterate through each element in `code`:
- Initialize `sum_val` to 0.
- If `k > 0`, sum the next `k` elements:
- For `j` from 1 to `k`, add `code[(i + j) % n]` to `sum_val`.
- If `k < 0`, sum the previous `k` elements:
- For `j` from 1 to `-k`, add `code[(i - j) % n]` to `sum_val`.
- Set `result[i]` to `sum_val`.
4. Return `result`
- Not handling the circular nature of the array correctly.
- Off-by-one errors in indexing elements for summation.
Implement the code to solve the algorithm.
def defuse(code, k):
n = len(code)
result = [0] * n
if k == 0:
return result
for i in range(n):
sum_val = 0
if k > 0:
for j in range(1, k + 1):
sum_val += code[(i + j) % n]
else:
for j in range(1, -k + 1):
sum_val += code[(i - j) % n]
result[i] = sum_val
return result