Skip to content

Commit 9e86581

Browse files
authored
Merge pull request #2088 from PradnyaGaitonde/PradnyaGaitonde-patch-32
Create 0080-remove-duplicates-from-sorted-array-II.md
2 parents 544cae5 + 0b5647a commit 9e86581

File tree

1 file changed

+156
-0
lines changed

1 file changed

+156
-0
lines changed
Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
---
2+
id: remove-duplicates-from-sorted-array-II
3+
title: Remove Duplicates from Sorted Array II(LeetCode)
4+
sidebar_label: 0080-Remove Duplicates from Sorted Array II
5+
tags:
6+
- Array
7+
- Two Pointers
8+
description: Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice.
9+
---
10+
11+
## Problem Statement
12+
13+
Given an integer array `nums` sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same.
14+
15+
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array `nums`. More formally, if there are `k` elements after removing the duplicates, then the first `k` elements of `nums` should hold the final result. It does not matter what you leave beyond the first `k` elements.
16+
17+
Return `k` after placing the final result in the first `k` slots of `nums`.
18+
19+
Do not allocate extra space for another array. You must do this by modifying the input array in-place with `O(1)` extra memory.
20+
21+
Custom Judge:
22+
23+
The judge will test your solution with the following code:
24+
25+
```
26+
int[] nums = [...]; // Input array
27+
int[] expectedNums = [...]; // The expected answer with correct length
28+
29+
int k = removeDuplicates(nums); // Calls your implementation
30+
31+
assert k == expectedNums.length;
32+
for (int i = 0; i < k; i++) {
33+
assert nums[i] == expectedNums[i];
34+
}
35+
```
36+
37+
If all assertions pass, then your solution will be accepted.
38+
39+
### Examples
40+
41+
**Example 1:**
42+
43+
```plaintext
44+
Input: nums = [1,1,1,2,2,3]
45+
Output: 5, nums = [1,1,2,2,3,_]
46+
Explanation: Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
47+
It does not matter what you leave beyond the returned k (hence they are underscores).
48+
```
49+
50+
**Example 2:**
51+
52+
```plaintext
53+
Input: nums = [0,0,1,1,1,1,2,3,3]
54+
Output: 7, nums = [0,0,1,1,2,3,3,_,_]
55+
Explanation: Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively.
56+
It does not matter what you leave beyond the returned k (hence they are underscores).
57+
```
58+
59+
### Constraints
60+
61+
- `1 <= nums.length <= 3 * 104`
62+
- `-104 <= nums[i] <= 104`
63+
- `nums` is sorted in non-decreasing order.
64+
65+
## Solution
66+
67+
### Approach
68+
69+
The approach employs a two-pointer strategy to remove duplicates from a sorted array such that each element appears at most twice. The variable j is used to keep track of the current position in the modified array where elements are being stored without violating the constraint. The loop iterates through the array, and for each element, it checks whether it is the same as the element two positions behind the current j. If it is, it means there are already two occurrences of this element in the modified array, and we should skip adding another one to adhere to the constraint. Otherwise, the element is added to the modified array at position j, and j is incremented.
70+
71+
#### Algorithm
72+
73+
1. Initialization:
74+
* Initialize `j` to 1 since the first element (at index 0) is always considered part of the modified array.
75+
2. Iteration:
76+
* Loop through the array starting from index 1 (i.e., i = 1).
77+
* For each element `nums[i]`:
78+
* Compare `nums[i]` with `nums[j - 2]`.
79+
* If they are different (i.e., `nums[i] != nums[j - 2]`), add `nums[i]` to the modified array at position `j` and increment `j`.
80+
* If they are the same, skip adding `nums[i]` to the modified array.
81+
3. Final Result:
82+
* The final length of the modified array is equal to `j`.
83+
* The modified array contains elements adhering to the constraint of at most two occurrences of each element.
84+
85+
#### Implementation
86+
87+
Java:
88+
89+
```Java
90+
class Solution {
91+
public int removeDuplicates(int[] nums) {
92+
int j = 1;
93+
for (int i = 1; i < nums.length; i++) {
94+
if (j == 1 || nums[i] != nums[j - 2]) {
95+
nums[j++] = nums[i];
96+
}
97+
}
98+
return j;
99+
}
100+
}
101+
```
102+
103+
C++
104+
105+
```C++
106+
class Solution {
107+
public:
108+
int removeDuplicates(std::vector<int>& nums) {
109+
int j = 1;
110+
for (int i = 1; i < nums.size(); i++) {
111+
if (j == 1 || nums[i] != nums[j - 2]) {
112+
nums[j++] = nums[i];
113+
}
114+
}
115+
return j;
116+
}
117+
};
118+
```
119+
120+
Python:
121+
122+
```Python
123+
class Solution:
124+
def removeDuplicates(self, nums: List[int]) -> int:
125+
j = 1
126+
for i in range(1, len(nums)):
127+
if j == 1 or nums[i] != nums[j - 2]:
128+
nums[j] = nums[i]
129+
j += 1
130+
return j
131+
```
132+
133+
Rust:
134+
135+
```Rust
136+
impl Solution {
137+
pub fn remove_duplicates(nums: &mut Vec<i32>) -> i32 {
138+
let mut j = 1;
139+
for i in 1..nums.len() {
140+
if j == 1 || nums[i] != nums[j - 2] {
141+
nums[j] = nums[i];
142+
j += 1;
143+
}
144+
}
145+
j as i32
146+
}
147+
}
148+
```
149+
### Complexity Analysis
150+
151+
- **Time complexity**: $O(N)$
152+
- **Space complexity**: $O(1)$
153+
154+
### Conclusion
155+
156+
The two-pointer approach effectively removes duplicates from a sorted array in-place such that each element appears at most twice. By maintaining two pointers, i for iteration and j for tracking the position in the modified array, the algorithm efficiently achieves the desired result with a single pass through the array. The time complexity is O(n), and the space complexity is O(1), making this solution both time and space efficient.

0 commit comments

Comments
 (0)