LeetCode 80: Remove Duplicates from Sorted Array II Solution
Master LeetCode problem 80 (Remove Duplicates from Sorted Array II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
80. Remove Duplicates from Sorted Array II
Problem Explanation
Explanation
To solve this problem, we will use two pointers approach. We will maintain a current pointer and a count variable to keep track of the number of occurrences of the current element. If the current element is the same as the previous element, we increment the count. If the count is less than or equal to 2, we copy the current element to the correct position in the array. If the count exceeds 2, we move the current pointer to the next element, effectively skipping over the duplicates. At the end, the current pointer will give us the final length of the array.
- Time complexity: O(n) where n is the length of the input array nums.
- Space complexity: O(1)
Solution Code
class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length <= 2) {
return nums.length;
}
int current = 2;
for(int i = 2; i < nums.length; i++) {
if(nums[i] != nums[current-2]) {
nums[current] = nums[i];
current++;
}
}
return current;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 80 (Remove Duplicates from Sorted Array II)?
This page provides optimized solutions for LeetCode problem 80 (Remove Duplicates from Sorted Array II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 80 (Remove Duplicates from Sorted Array II)?
The time complexity for LeetCode 80 (Remove Duplicates from Sorted Array II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 80 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 80 in Java, C++, or Python.