0

I am confused. I am solving this problem on leetcode and I wrote this code where there's nested while loops. From the first look, one would think it is an O(N^2) solution, however, I am wondering if that is true since the inner while loop does not iterate over the entire array but just a part of it. Thus, I think it is O(N).

Please confirm my understanding

 var removeDuplicates = function(nums) {
    let i = 0, j = i + 1
   
    while(i < nums.length - 1 && j < nums.length){
        while(nums[i] == nums[j]){
            nums.splice(j, 1)
        }

        j++
        i++
    }
    
    return j
};
TanDev
  • 359
  • 3
  • 5
  • 13
  • 1
    Easiest way is to measure on different inputs and plot graph – JL0PD Mar 17 '21 at 04:43
  • Easy way to find out: Test for various values of *N*, like 1, 10, 100, 1000, etc. going up by a factor of 10 each time. You'll very quickly find out the performance characteristics. – tadman Mar 17 '21 at 04:43
  • If you're always incrementing both `i` and `j` identically maybe you really just need one variable `i` and use `i + 1` in place of `j`. – tadman Mar 17 '21 at 04:45
  • how does removing variable j optimize the solution or help it ? – TanDev Mar 17 '21 at 08:17

2 Answers2

2

It's O(n). Given a length of L, The outer loop iterates L times (worst-case), and the inner loop also iterates a total of L times (worst-case, in case all elements in the array are duplicates).

O(n) + O(n) = O(n).

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

@CertainPerformance already did the heavy work to convince us that the worst case that nums.splice(j, 1) runs at most O(n) times when nums consist of all duplicates.

O(splice) = O(n) per JavaScript runtime complexity of Array functions. This makes sense to me, worst case we remove 1 element at j = 2 means we need to copy n - 2 elements, then n - 3 etc.

O(removeDuplicates) = O(n^2)

You can make it O(nlogn) by sorting the list, then iterate through the sorted list and push the current value to a result list if it is different then the last one. O(n) is if you radix sort.

See also Remove duplicates from array in linear time and without extra arrays (note, some of these answer use O(n) space so they are not valid answers to that question).

Allan Wind
  • 23,068
  • 5
  • 28
  • 38