Sobes.tech
Junior — Middle

How to determine the execution time of removing duplicates from a sorted array?

sobes.tech AI

Answer from AI

The time complexity of removing duplicates from a sorted array is typically estimated as O(n), where n is the length of the array. This is because, in a sorted array, duplicates are adjacent, and only one pass through the array is sufficient to remove them.

Example in Java:

public int removeDuplicates(int[] nums) {
    if (nums.length == 0) return 0;
    int i = 0;
    for (int j = 1; j < nums.length; j++) {
        if (nums[j] != nums[i]) {
            i++;
            nums[i] = nums[j];
        }
    }
    return i + 1; // new length of the array without duplicates
}

Here, we traverse the array once, comparing the current element with the previous unique element, and copy unique elements forward. Thus, the algorithm runs in linear time O(n).