This content originally appeared on DEV Community and was authored by Giuseppe
Time Complexity O(n)
Space Complexity O(1)
class Solution {
public int removeDuplicates(int[] nums) {
if (nums.length <= 2) return nums.length;
int index = 2;
for (int i = 2; i < nums.length; i++) {
// Keep element if it's different from the element 2 positions back
if (nums[i] != nums[index - 2]) {
nums[index] = nums[i];
index++;
}
}
return index;
}
}
This content originally appeared on DEV Community and was authored by Giuseppe