Skip to content
Advertisement

Mutate Java Array

I’m working on a coding problem where we have to mutate an existing array into a new array. The rules are that an element at the arrays index is equal to, a[i – 1] + a[i] + a[i + 1]. The catch is that if the a[i – 1] or a[i + 1] doesn’t exist, they should be counted as zero.

My test cases are passing for every value up to the last value, and I can’t understand why it isn’t being calculated, when every other value is,

int[] mutateTheArray(int n, int[] a) 
{
    int b[] = new int[a.length + 1];
    if(a.length == 1) 
    {
        return a;
    }
    for(int i = 0; i < a.length - 1; i++) 
    {
        if(i == 0) 
        {
            b[0] = 0 + a[i] + a[i + 1];
        }
        if(i == a.length)
        {
            b[a.length] = a[i - 1] + a[i] + 0;
        }
        else if(i != a.length && i != 0)
        {
            b[i] = a[i - 1] + a[i] + a[i + 1];
        }
    }

    return b;
}

The output should be for an array a = [4, 0, 1, -2, 3], output should be: [4, 5, -1, 2, 1]. I’m getting the answer except for the last value, which is calculating to 0. I know the issue is in accessing the array index – 1, but I don’t know how to get each element without it going out of bounds. Any help is appreciated, thanks 🙂

Advertisement

Answer

  1. Your array b should have the size a.length, not a.length + 1.
  2. You should change the condition of your for-loop to i < a.length, as the last element should be included.
  3. Your second if-condition should be i == a.length - 1. (Note: Array.length returns the amount of elements in the Array, which is the last index + 1.)
    Also, you can use else if, as this condition can not be met if the first one was.
  4. The last if-condition is unnecessary as the condition is always false now. Just use else.

Btw.: You may want to look into the ternary operator.

All in all, your code would look like this:

int[] mutateTheArray(int n, int[] a) 
{
    int b[] = new int[a.length];
    if(a.length == 1)
        return a;
    for(int i = 0; i < a.length; i++) 
    {
        if(i == 0) 
        {
            b[0] = 0 + a[i] + a[i + 1];
        }
        else if(i == a.length-1)
        {
            b[a.length-1] = a[i - 1] + a[i] + 0;
        }
        else
        {
            b[i] = a[i - 1] + a[i] + a[i + 1];
        }
    }
    return b;
}

… or when using the ternary operator:

int[] mutateTheArray(int n, int[] a) 
{
    int b[] = new int[a.length];
    if(a.length == 1)
        return a;
    for(int i = 0; i < a.length; i++) 
    {
            b[i] = (i == 0 ? 0 : a[i - 1]) + a[i] + (i == a.length-1 ? 0 : a[i + 1]);
    }
    return b;
}

PS: Edited from b[a.length] = ... to b[a.length-1] = ... at line 15.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement