For each element in the array, we can calculate the sum of the next k elements. If k is negative, we can calculate the sum of the previous k elements.
fun decrypt(code: IntArray, k: Int): IntArray {
val n = code.size
val result = IntArray(n)
if (k == 0) return result
for (i in code.indices) {
var sum = 0
if (k > 0) {
for (j in i + 1..i + k) {
sum += code[j % n]
}
} else {
for (j in i - 1 downTo i - (-k)) {
sum += code[(j + n) % n]
}
}
result[i] = sum
}
return result
}- Time Complexity:
O(n * k). - Space Complexity:
O(n).
/**
k = 3
0 1 2 3 4
0 1 2 i
i 1 2 3
i 2 3 4
0 i 3 4
0 1 i 4
k = -3
0 1 2 3 4
0 1 2 i
1 2 3 i
i 2 3 4
0 i 3 4
0 1 i 4
*/