#80

Remove Duplicates from Sorted Array II

Medium
ArrayTwo PointersTwo PointersArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses a two-pointer technique to keep track of where to place the next valid number while iterating through the array. This avoids the need for extra space and reduces time complexity.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a pointer 'i' to track the position of the last valid element.
  2. 2Step 2: Iterate through the array with a second pointer 'j'.
  3. 3Step 3: For each element, check if it can be added (i.e., it appears at most twice).
  4. 4Step 4: If valid, increment 'i' and place the element at 'i'.
  5. 5Step 5: Return 'i + 1' as the new length of the modified array.
solution.py11 lines
1# Full working Python code
2
3def removeDuplicates(nums):
4    if not nums:
5        return 0
6    i = 0
7    for j in range(1, len(nums)):
8        if nums[j] != nums[i] or (i > 0 and nums[j] != nums[i - 1]):
9            i += 1
10            nums[i] = nums[j]
11    return i + 1

Complexity note: The time complexity is O(n) because we only traverse the array once. The space complexity is O(1) since we are modifying the array in place without using any additional data structures.

  • 1Use two pointers to efficiently manage the position of valid elements.
  • 2Keep track of the last valid element to ensure duplicates are limited.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.