Data structure removeat

I want to tell you that in the first part of Data Structures and Algorithms, specifically in the Arrays section of Video No. 7 removeAt() there is an error where the solution and the method you followed does not work if items.length == count Suppose we set the length of the array 2 and we want to delete Item #1 will cause an error, knowing that it could be a mistake in my writing because I’m writing in Python, but I developed a solution to this error is if the length is equal to count the same way is followed to avoid the error in def insert()

Hello,

I did not take that course but that’s interesting.
Could you put an example code so I could see the problem on my own?

It seems the course is not language specific which is good for an algorithm course.

Anyway removing an element at a specific position in an array is one of the exercices I did when I was trained (for sure a grand classic).

I do not know any English pseudo language to write a snippet but the principle to that is simply crushing the element at N (being the index you want to remove) by looping on the following elements and copying them to N-1. Then resizing the array to remove the last element.

Regards.

I am with UniqueNospaceShort here - it is difficult to help if you do not paste a code snippet showing the issue.

1 Like

There are only two hard things in Computer Science: cache invalidation, naming things, and off-by-one errors.

– Computer Scientists

Just got access to the course (decided to try the annual subscription at a discount) and you are correct. Mosh’s solution has an off-by-one error which is very common in programming. Instead of using i < count Mosh should have used i < count - 1 because you want to stop one before the last item.

public void removeAt(int index) {
  if (i < 0 || i >= count) {
    throw new IllegalArgumentException("Index out of bounds: " + index);
  }
  for (int i = index; i < count - 1; i++) {
    items[i] = items[i + 1];
  }
  count--;
}

Aside: this is why testing your code’s edge cases is important. I recommend Test-Driven Development to avoid this type of issue.