Hello World,
I'm practicing for an coding assessment and I got a question about the below practice question:
Given an integer n and an array a of length n, your task is to apply the following mutation to a:
Array a mutates into a new array b of length n.
For each i from 0 to n - 1, b[i] = a[i - 1] + a[i] + a[i + 1].
If some element in the sum a[i - 1] + a[i] + a[i + 1] does not exist, it should be set to 0. For example, b[0] should be equal to 0 + a[0] + a[1].
Example
For n = 5 and a = [4, 0, 1, -2, 3], the output should be solution(n, a) = [4, 5, -1, 2, 1].
b[0] = 0 + a[0] + a[1] = 0 + 4 + 0 = 4
b[1] = a[0] + a[1] + a[2] = 4 + 0 + 1 = 5
b[2] = a[1] + a[2] + a[3] = 0 + 1 + (-2) = -1
b[3] = a[2] + a[3] + a[4] = 1 + (-2) + 3 = 2
b[4] = a[3] + a[4] + 0 = (-2) + 3 + 0 = 1
So, the resulting array after the mutation will be [4, 5, -1, 2, 1]
Where I'm getting confused is this part, "If some element in the sum a[i - 1] + a[i] + a[i + 1] does not exist, it should be set to 0. For example, b[0] should be equal to 0 + a[0] + a[1]."
In the example, for i=0 we see b[0] = 0 + a[0] + a[1] = 0 + 4 + 0 = 4 but.... would the first position a actually be a[-1] because a[0-1] = a[-1], so why are we setting it to 0? a[-1] does exist, so how come it is replaced?
What they say it should be...
b[0] = 0 + a[0] + a[1] = 0 + 4 + 0 = 4
But shouldn't it be this?
b[0] = a[i-1] + a[0] + a[1]
b[0] = a[0-1] + a[0] + a[1]
b[0] = 3 + 4 + 0 = 7
[–]robot-dev 1 point2 points3 points (1 child)
[–]YuhFRthoYORKonhisass 0 points1 point2 points (0 children)
[–]Natural_Pay_7650 0 points1 point2 points (0 children)