Home > Enterprise >  remove target element in array using two pointers --index out of bound?
remove target element in array using two pointers --index out of bound?

Time:11-05

I am trying to remove target element from an array , if input is [3,3,2,2,3,3] and my target is 3 , I should get [2,2]. the logic is simple, using slow and fast pointers and if we need copy, move slow pointer, otherwise move fast pointer to skip the target .

but I am keep getting index out of bound error and can not figure out why ?

public int[] removeElement(int[] input, int value) {
    int slow = 0;
    int fast = 0;
    while (fast < input.length) {
        while (input[fast] == value && fast < input.length) {
            fast  ;
        }
        input[slow  ] = input[fast  ];
    }
    return Arrays.copyOfRange(input, 0, slow);
}

CodePudding user response:

Too many happen. Best seen in debugger or on paper. Best not use inside complexer expressions.

Not surprising, as it can be done simpler:

public int[] removeElement(int[] input, int value) {
    int slow = 0;
    int fast = 0;
    while (fast < input.length) {
        if (input[fast] != value) {
            input[slow  ] = input[fast];
        } 
          fast;
    }
    return Arrays.copyOf(input, slow);
}

CodePudding user response:

your array : [3,3,2,2,3,3]
The first issue is with this:

while (input[fast] == value && fast < input.length) {
            fast  ;
}

the last index is 5 and is less than its size(6) -> fast -> now fast=6
now in next iteration,
input[6]==value will result in index out of bound error.

CodePudding user response:

i think you need to put a -1 behind the two input.length

its because input.length returns the size in a way how humans think (if there is one entry it returns 1), but if you talk to arrays they need it in a computer way (starting from 0)

like this:

public static int[] removeElement(int[] input, int value) {
        int slow = 0;
        int fast = 0;
        while (fast < input.length-1) {
            while (input[fast] == value && fast < input.length-1) {
                fast  ;
            }
            input[slow  ] = input[fast  ];
        }
        return Arrays.copyOfRange(input, 0, slow);
    }
  • Related