Sponsored
Sponsored
This approach uses a sliding window technique to efficiently calculate the sum of required elements. By maintaining a running sum for the window and updating it as you slide, you can achieve the necessary transformation in linear time. The key is to account for the circular nature of the array using modulo operations to wrap around indices.
Time Complexity: O(n), where n is the length of the `code` array. Each element is processed once with constant-time window updates.
Space Complexity: O(1) auxiliary space (excluding the output array).
Solve with full IDE support and test cases
This Python solution maintains the sliding window sum and adjusts it while traversing over code using modulo operations. It initializes the sum with the first k values or their complements based on k being positive or negative. Such index calculations handle the array's circular nature effectively.
This approach is straightforward but less efficient, involving a direct sum computation for each index by wrapping around using the modulo operator. Each element's circular context is individually recalculated, following conditions for the sign of k.
Time Complexity: O(n*k) with n as length of `code` and k an absolute value.
Space Complexity: O(1) extra space beyond output.
1import java.util.Arrays;
2
3public class Solution {
4 public int[] decrypt(int[] code, int k) {
5 int n = code.length;
6 int[] result = new int[n];
7
8 if (k == 0) return result;
9
10 for (int i = 0; i < n; i++) {
11 int sum = 0;
12 for (int j = 1; j <= Math.abs(k); j++) {
13 int index = (k > 0) ? (i + j) % n : (i - j + n) % n;
14 sum += code[index];
15 }
16 result[i] = sum;
17 }
18
19 return result;
20 }
21
22 public static void main(String[] args) {
23 Solution sol = new Solution();
24 int[] code = {5, 7, 1, 4};
25 int k = 3;
26 System.out.println(Arrays.toString(sol.decrypt(code, k)));
27 }
28}
29
The Java algorithm clearly reiterates for each index, adding component indices which are calculated using the modulus for effective circular array handling, and updates result row-wise as directed by positive or negative k directions.