Similar Problems

Similar Problems not available

Defuse The Bomb - Leetcode Solution

Companies:

LeetCode:  Defuse The Bomb Leetcode Solution

Difficulty: Easy

Topics: sliding-window array  

Problem Statement:

You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code of length of n and a key k.

To decrypt the code, you must replace every number in the code with a sum of k of the numbers that follow it in the code. This is because each number in the code can be interpreted as a digit and the sum of k digits ahead of it in the code is its decrypt value.

Write a function to decrypt this code. You are provided with a helper function, check(), to help you check the correct decryption of the code.

The code is a circular array of length n with elements from 1 to 9. You will be given a key k and a code array code with length n, where code[i] suggests the digit from 1 to 9 corresponding to the i-th (0-indexed) digit of the circular code. Determine the decrypted code of the given circular array.

The defused code should also be a circular array of the same length.

Example:

Input: code = [5,7,1,4], k = 3

Output: [2,3,6,5]

Explanation: Each digit is replaced by the sum of the next 3 digits. The decrypted code is [2,3,6,5] which is a circular array of length 4.

Solution:

The problem can be solved by iterating through the code array and replacing each digit by the sum of the next k digits. However, since the code is circular, we need to take care when the sum goes beyond the end of the array.

We can handle the circularity by using the modulo operator. For each index i, the indices of the next k digits are given by (i+1)%n, (i+2)%n, ..., (i+k)%n. We can then compute the sum of these indices and store it in the result array for index i.

If the sum of the indices goes beyond the end of the array, we can split the sum into two parts, one before the end of the array and one after. We can then add these two parts together to get the final sum.

Code:

def decrypt(code, k): n = len(code) result = [0] * n for i in range(n): total = 0 for j in range(k): total += code[(i+j+1)%n] result[i] = total return result

The time complexity of this solution is O(n*k), where n is the length of the code array and k is the key. The space complexity is O(n) for the result array.

Defuse The Bomb Solution Code

1