26. Remove Duplicates from Sorted Array
Explanation:
To solve this problem, we can use a two-pointer approach where one pointer will iterate over the array, and the other pointer will keep track of the position where the next unique element should be placed. As the array is already sorted, duplicate elements will be adjacent to each other. We can compare the current element with the next element and only move the unique elements to the front of the array.
- Initialize two pointers:
i
for iterating over the array andj
for placing unique elements. - Iterate over the array from index 1 to the end.
- If the current element is different from the previous element, place it at index
j
and incrementj
. - After iterating, the first
j
elements will contain the unique elements. - Return the value of
j
as the number of unique elements.
Time Complexity: O(n) where n is the number of elements in the array.
Space Complexity: O(1) as we are using constant extra space.
class Solution {
public int removeDuplicates(int[] nums) {
if (nums.length == 0) return 0;
int j = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[i - 1]) {
nums[j] = nums[i];
j++;
}
}
return j;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.