Loading
Leetcode / 1652. Defuse the Bomb

Pick a programming language:

Here is the source code for the solution to this problem.

class Solution {
    // sliding window
    // time O(n)
    public int[] decrypt(int[] code, int k) {
        int[] decryptedCode = new int[code.length];

        if (k == 0) {
            return decryptedCode;
        }
        
        int sum = 0;
        int startIndex = 1;
        int endIndex = k;

        if (k < 0) {
            startIndex = code.length + k;
            endIndex = code.length - 1;
        }

        // Calculate the initial window sum
        for (int i = startIndex; i <= endIndex; i++) {
            sum += code[i];
        }

        for (int i = 0; i < code.length; i++) {
            decryptedCode[i] = sum;

            // slide the window
            sum -= code[startIndex];
            startIndex = (startIndex + 1) % code.length;

            endIndex = (endIndex + 1) % code.length;
            sum += code[endIndex];
        }

        return decryptedCode;
    }

    // time O(n * k)
    // public int[] decrypt(int[] code, int k) {
    //     int[] decryptedCode = new int[code.length];

    //     if (k == 0) {
    //         return decryptedCode;
    //     }

    //     for (int i = 0; i < code.length; i++) {
    //         int sum = 0;

    //         if (k > 0) {
    //             for (int j = 0; j < k; j++) {
    //                 sum += code[(i + j + 1) % code.length];
    //             }
    //             decryptedCode[i] = sum;
    //         }
    //         else if (k < 0) {
    //             for (int j = 0; j < -k; j++) {
    //                 int newIndex = (i - j - 1) % code.length;
    //                 if (newIndex < 0) {
    //                     newIndex = code.length + newIndex;
    //                 }
    //                 sum += code[newIndex];
    //             }
    //             decryptedCode[i] = sum;
    //         }
    //         // The decryptedCode array elements are already initialized to 0
    //         // with Java's new int[], so you can omit this:
    //         // else { // (k == 0) 
    //         //     decryptedCode[i] = 0;
    //         // }
    //     }

    //     return decryptedCode;
    // }
}
Did you like the lesson? 😆👍
Consider a donation to support our work: