For the problem on Challenge 9: Re-arrange Positive & Negative Values, I have the following solution, using two-pointers pattern -
class CheckReArrange {
public static void reArrange(int[] arr) {
int[] sorted = new int[arr.length];
int neg = 0, pos = sorted.length-1;
for(int num: arr) {
if(num < 0) {
sorted[neg++] = num;
}
else {
sorted[pos--] = num;
}
}
arr = sorted;
}
}
I found a previous question asked by another user on this topic - Error in validating - #2 by FatimahAbdullah and in that case, the reason given was that because the array reference was being changed inside the method, it could not be preserved in main()
.
Well, that’s not really our headache, is it? We are only concerned with the implementation of the method here, not its verification. You can easily change the reArrange()
method’s return type to return an array instead of void
, and then you can very nicely check the contents of the returned array inside main()
. Just because your testing code is not properly written, that’s not a valid reason to not accept a totally correct solution.
Course: Data Structures for Coding Interviews in Java - Learn Interactively
Lesson: Challenge 9: Re-arrange Positive & Negative Values - Data Structures for Coding Interviews in Java
Course: Data Structures for Coding Interviews in Java - Learn Interactively
Lesson: Challenge 9: Re-arrange Positive & Negative Values - Data Structures for Coding Interviews in Java