189. Circular Code Sums

A vault's keypad is a ring of digits stored in the array code; after the last position comes the first again. To scramble the ring, the security team replaces every value by the total of its neighbours.

Build a new array result of the same length. If k > 0, result[i] is the sum of the next k values after position i, wrapping around the ring. If k < 0, it is the sum of the previous |k| values before position i. If k == 0, every entry of result is 0. The original values are used for every sum.

Example 1

Input:
code = [2,4,9,3], k = 2
Output:
[13,12,5,6]
Explanation:

Position 0 adds the next two values 4 and 9 (13), position 1 adds 9 and 3 (12), position 2 wraps and adds 3 and 2 (5), position 3 wraps and adds 2 and 4 (6).

Example 2

Input:
code = [1,2,3,4,5], k = -2
Output:
[9,6,3,5,7]
Explanation:

Position 0 adds the two values before it, which wrap to 5 and 4 (9). Position 1 adds 1 and 5 (6), position 2 adds 2 and 1 (3), position 3 adds 3 and 2 (5), position 4 adds 4 and 3 (7).

Example 3

Input:
code = [8,6,7], k = 0
Output:
[0,0,0]
Explanation:

With k equal to 0 every sum is empty, so every entry is 0.

Constraints

1 ≤ code.length ≤ 100

1 ≤ code[i] ≤ 1000

-(code.length - 1) ≤ k ≤ code.length - 1

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…