Write a method makeConsecutiveByN that could be added to the ArrayIntList class that takes an integer n as a parameter, removes any list element that does not differ from the previous element by exactly n. For example, both 8 and 2 differ from 5 by exactly 3. Your method should return true if the list was changed and false if not. For example, suppose elementData stores the following element values: [1, 3, -6, 1]. We need to compare every set of pairs. If we remove an element we need to compare the next element in the list to the last non-removed element. If n were 2 and we made a call on the previous list we would compare 1 and 3, keep 3 and then compare 3 and -6. We would discard -6 and so then compare 3 and the last 1. Our call would return true. You may not use any other arrays, lists, or other data structures to help you solve this problem, though you can create as many simple variables as you like.
I'm looking for better/other ways to write this code. I noticed that I wasn't able to iterate from the right-to-left because this problem depends on the direction of traversal. With that in mind, are there other ways I can think about solving this problem? Also looking for general feedback to cleaning up my code for the future. It is also worth noting that this is code that would be added to a custom ArrayIntList class.
public boolean makeConsecutiveByN(int n) {
boolean isChanged = false;
for (int i = 0; i + 1 < size; i++) {
if (Math.abs(elementData[i] - elementData[i + 1]) != n) {
remove(i + 1);
i--;
isChanged = true;
}
}
return isChanged;
}