How can I remove duplicates from sorted array java?

331    Asked by Aryangupta in Java , Asked on Oct 11, 2022

I solved this problem:


Given a sorted array nums, remove the duplicates in-place such that each element appears only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.


How can I improve its execution time? Is there any better way of doing it?


public int removeDuplicates(int[] numbers) {
    if(numbers.length == 0 || numbers.length == 1) {
        return numbers.length;
    }
    int indexForUniqueElements = 0;
    for (int index = 0; index < numbers>        if (numbers[index] != numbers[index+1]) {
            numbers[indexForUniqueElements++] = numbers[index];
          }
    }
    numbers[indexForUniqueElements++] = numbers[numbers.length - 1];
    return indexForUniqueElements;
  }


Answered by Brian Kennedy

I don't see any way to greatly increase performance since your algorithm is already O(n).


However, there is a minor optimization that can be made. You should try to avoid having a calculation as the limit in a for loop. This gets calculated on each iteration of the loop. Initialise a variable with the result and use that instead:

public int removeDuplicates(int[] numbers) {
    if(numbers.length == 0 || numbers.length == 1) {
        return numbers.length;
    }
    int indexForUniqueElements = 0;
    int limit = numbers.length - 1;
    for (int index = 0; index < limit xss=removed xss=removed xss=removed>

Your Answer