Skip to content
Advertisement

Remove last occurrence of a specific integer from an array

For some reason, my solution is not complete. I got 80/100 from hidden spec tests.

  1. What’s wrong with my solution? There is probably a certain use case that I’m not thinking of.
  2. How would space/time complexity change using an ArrayList instead of an array?
  3. Is there a better way to tackle this problem?

My current solution handles:

  • an empty input array
  • negative/positive integer values in the input array
  • duplicates in the input array
  • sorted/unsorted input array

Instructions:

Write a Java method removeLastOccurrence(int x, int[] arr), which removes the last occurrence of a given integer element x from a given array of integer elements arr.

The method should return a new array containing all elements in the given array arr except for the last occurrence of element x. The remaining elements should appear in the same order in the input and the returned arrays.

The code on the right shows you a code framework in which the implementation of one static method is still missing. Provide this implementation and check that it is correct by either writing more tests yourself or using the provided tests and specification tests.

My code:

JavaScript

Passing Unit Tests

JavaScript

Advertisement

Answer

This is the answer thank you very much!

Also, if there is no x to find, yours crashes … mine doesn’t. Maybe that’s where the twenty marks went?

I was already checking for this but too late in my code. So I just had to move

if (last_index == -1) return arr; before the while loop, and I got 100/100 scores.

enter image description here


Would your prof prefer this? Just another way, and I don’t think any more efficient than your answer. But maybe they like to see the java classes used …

Does your prof not tell you where you lost marks? You can’t improve if they don’t tell you what they were expecting for full marks. But here was another way … again, no better in my opinion, and not worth twenty more marks. I’ll just post it, because it is ‘another way.’

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement