0

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);
}

3 Answers 3

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.