Loading

LeetCode problem#1652

Defuse the Bomb

Solved in 1 languageJava

Solve it on LeetCode(opens in a new tab)

Solution

75 lines
1class Solution {
2    // sliding window
3    // time O(n)
4    public int[] decrypt(int[] code, int k) {
5        int[] decryptedCode = new int[code.length];
6
7        if (k == 0) {
8            return decryptedCode;
9        }
10        
11        int sum = 0;
12        int startIndex = 1;
13        int endIndex = k;
14
15        if (k < 0) {
16            startIndex = code.length + k;
17            endIndex = code.length - 1;
18        }
19
20        // Calculate the initial window sum
21        for (int i = startIndex; i <= endIndex; i++) {
22            sum += code[i];
23        }
24
25        for (int i = 0; i < code.length; i++) {
26            decryptedCode[i] = sum;
27
28            // slide the window
29            sum -= code[startIndex];
30            startIndex = (startIndex + 1) % code.length;
31
32            endIndex = (endIndex + 1) % code.length;
33            sum += code[endIndex];
34        }
35
36        return decryptedCode;
37    }
38
39    // time O(n * k)
40    // public int[] decrypt(int[] code, int k) {
41    //     int[] decryptedCode = new int[code.length];
42
43    //     if (k == 0) {
44    //         return decryptedCode;
45    //     }
46
47    //     for (int i = 0; i < code.length; i++) {
48    //         int sum = 0;
49
50    //         if (k > 0) {
51    //             for (int j = 0; j < k; j++) {
52    //                 sum += code[(i + j + 1) % code.length];
53    //             }
54    //             decryptedCode[i] = sum;
55    //         }
56    //         else if (k < 0) {
57    //             for (int j = 0; j < -k; j++) {
58    //                 int newIndex = (i - j - 1) % code.length;
59    //                 if (newIndex < 0) {
60    //                     newIndex = code.length + newIndex;
61    //                 }
62    //                 sum += code[newIndex];
63    //             }
64    //             decryptedCode[i] = sum;
65    //         }
66    //         // The decryptedCode array elements are already initialized to 0
67    //         // with Java's new int[], so you can omit this:
68    //         // else { // (k == 0) 
69    //         //     decryptedCode[i] = 0;
70    //         // }
71    //     }
72
73    //     return decryptedCode;
74    // }
75}

Want a walkthrough of this Java solution?

Get a step-by-step explanation of the idea behind the code.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.