As I am learning the data structures, I'm trying to implement the dynamic array in Java using the static array and trying to calculate the time complexities for each method.
For the remove method which takes an element as the parameter, my code contains an if statement to check if the given element is found in the array. Only if the element exists, it performs the remove operation. I'm struggling to find the time complexity for this method. Is it O(n)? Can someone explain?
public boolean remove(int ele) {
for (int i = 0; i < numberOfElements; i++) {
if (arr[i] == ele) {
removeAt(i);
return true;
}
}
return false;
}
public void removeAt(int index) {
if (index > numberOfElements) {
throw new IllegalArgumentException();
} else {
for (int i = index; i < numberOfElements - 1; i++) {
arr[i] = arr[i + 1];
}
numberOfElements--;
}
}
The complexity seems to be O(N), with N to iterate over the array and N to do the shift operation once. One time the element is remove, the 'if' iterate over the rest of elements to do the shift, doing 'i' iterations to find the elements and 'n - i' iterations to shift it. In the end of the 'if', the outer 'for' is broken because the return and the operation finish.
I think you need to iterate until 'numberOfElements' and not work with 'array.length' directly.