educative.io

Educative

Creating the subarrays from left to right instead of right to left

I don’t understand the explanation on why we create the subarray from right -> left, instead of left -> right

for (int i = right; i >= left; i--) {
        currentWindow.add(0,arr[i]);
        subarrays.add(new ArrayList<>(currentWindow));
}

Why won’t this work?

for (int i = left; i <= right; i++) {
        currentWindow.add(arr[i]);
        subarrays.add(new ArrayList<>(currentWindow));
}

Thanks

  • Nigel

The order of traversal can be either left → right or right → left.