educative.io

Error in validating

The below code gives out the expected solution but the test case fails it.

public  void reArrange(int[] arr) {

    //Write - Your - Code 
    int[] orderedArr = new int[arr.length];
    int posCounter = 0;
    int negCounter = arr.length-1;

    for(int i : arr) {

        if(i < 0) {
            orderedArr[posCounter++] = i;
        } else {
            orderedArr[negCounter--] = i;
        }

    }
    arr  = orderedArr;
}

Hi @Vinodh_Thiagarajan,

This is Fatimah Abdullah from Educative. I noticed your feedback on the here, and I’m glad you reached out to us.

Vinodh, your solution is completely correct logically. However, there is a technical issue in it that is caused by the nature of the Java language. You see that, it is correct to say that in Java, data is passed by value to a function. However, in the case of the non-primitive data types, i.e arrays, and objects of classes, the data is passed by the value of the “reference”. Therefore, modification of values inside the objects is also reflected outside the function. However, we can not change the actual “reference” of such an object. This change will only persist inside the function. Let me give you an example of a Java program that you can run.

import java.util.Arrays;
public class Demo{
    public static void myFunc1(int[] arr) {
        int[] arr2 = {1, 2, 3};
        arr  = arr2;
    }
    public static void myFunc2(int[] arr) {
        arr[0]  = 1;
        arr[1] = 2;
        arr[2] = 3;
    }
    public static void main(String []args){
        int[] arr1 = {4, 5, 6};
        int[] arr2 = {4, 5, 6}; 
        myFunc1(arr1);
        myFunc2(arr2);
        System.out.println(Arrays.toString(arr1));
        System.out.println(Arrays.toString(arr2));
    }
}

The output of this program will be the following:

[4, 5, 6]
[1, 2, 3]

As you can see, the function myFunc1() tried to modified the reference of the array. However, in the main() the modified value did not persist. On the other hand, the function myFunc2() only modified the values inside the array object. And, as we can see, the modified values are also returned back to the main() function.

Similarly, in your solution the following line is also trying to modify the reference.

arr  = orderedArr;

I suggest that if you want to copy the whole array, then use a for loop for this purpose instead.

Thank you again for reaching out! I hope my answer helped you understand this issue.

We hope Educative has inspired to further your learning, and please drop us a note if you have any other questions or concerns.

Best Regards,
Fatimah Abdullah | Developer Advocate
Educative Inc.