LeetCode 1652: Defuse the Bomb

ArraySliding Window

Problem Description

Explanation

To solve this problem, we can iterate through each element in the circular array code and calculate the sum based on the given key k. We need to handle the cases where k is positive, negative, or zero, and ensure that we wrap around the circular array appropriately.

  1. For each element in the code array:

    • If k > 0, calculate the sum of the next k elements in a circular manner.
    • If k < 0, calculate the sum of the previous k elements in a circular manner.
    • If k == 0, replace the current element with 0.
  2. We can use modular arithmetic to handle wrapping around the circular array. By taking the modulo of the index, we can ensure that we access elements within the valid range.

  3. The time complexity of this solution is O(n) where n is the length of the code array. We iterate through the array once to calculate the decrypted code.

  4. The space complexity is O(n) as we use an additional array to store the decrypted code.

Solutions

class Solution {
    public int[] decrypt(int[] code, int k) {
        int n = code.length;
        int[] decrypted = new int[n];
        
        for (int i = 0; i < n; i++) {
            int sum = 0;
            if (k > 0) {
                for (int j = 1; j <= k; j++) {
                    sum += code[(i + j) % n];
                }
            } else if (k < 0) {
                for (int j = 1; j <= -k; j++) {
                    sum += code[(i - j + n) % n];
                }
            }
            decrypted[i] = sum;
        }
        
        return decrypted;
    }
}

Loading editor...