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
The C solution implements a sliding window technique. We first determine the starting and ending indices of the window based on the sign of k. For k > 0, the window slides to the right, and for k < 0, we slide to the left by transforming into a positive index shift using modulo operations. This avoids reconstructing the window repeatedly.
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.
1#include <vector>
2#include <iostream>
3#include <cmath>
4using namespace std;
5
6vector<int> decrypt(vector<int>& code, int k) {
7 int n = code.size();
8 vector<int> result(n);
9
10 if (k == 0) return vector<int>(n, 0);
11
12 for (int i = 0; i < n; ++i) {
13 int sum = 0;
14 for (int j = 1; j <= abs(k); ++j) {
15 int index = (k > 0) ? (i + j) % n : (i - j + n) % n;
16 sum += code[index];
17 }
18 result[i] = sum;
19 }
20
21 return result;
22}
23
24int main() {
25 vector<int> code = {5, 7, 1, 4};
26 int k = 3;
27 vector<int> decrypted = decrypt(code, k);
28 for (int num : decrypted) {
29 cout << num << " ";
30 }
31 return 0;
32}
33
The C++ brute-force solution manually calculates the sum for each element in `code`, looping either forwards or backwards dependent on k's value. It thereby computes the indices using positive modulo techniques to handle bounds correctly.