You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: solutions/1-1000/27-remove-element.md
+28-9Lines changed: 28 additions & 9 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -31,15 +31,34 @@ It does not matter what you leave beyond the returned k (hence they are undersco
31
31
-`0 <= nums[i] <= 50`
32
32
-`0 <= val <= 100`
33
33
34
+
<details>
35
+
<summary>Hint 1</summary>
36
+
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right?
37
+
</details>
38
+
39
+
<details>
40
+
<summary>Hint 2</summary>
41
+
We can move all the occurrences of this element to the end of the array. Use two pointers!
42
+
</details>
43
+
44
+
<details>
45
+
<summary>Hint 3</summary>
46
+
Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
47
+
</details>
48
+
34
49
## Intuition behind the Solution
35
50
The goal is to remove the elements in the array that are equal to `val`, and the order of the remaining elements is not important.
36
51
37
-
### Solution 1
52
+
### Solution 1 (easier to think of)
38
53
Then we only need to use the following elements that are not equal to `val` to occupy the elements that are equal to `val`.
39
54
40
-
### Solution 2
55
+

56
+
57
+
### Solution 2 (more concise and easier to code)
41
58
You only need to traverse the array once and keep all numbers that are not equal to `val` at the front of the array.
42
59
60
+
`slowIndex` is used to save the current front position.
61
+
43
62
## Complexity
44
63
* Time: `O(n)`.
45
64
* Space: `O(1)`.
@@ -73,7 +92,7 @@ class Solution {
73
92
}
74
93
```
75
94
76
-
### Solution 2: Fast and Slow Pointers (more concise)
95
+
### Solution 2: Fast and Slow Pointers (more concise and easier to code)
77
96
```java
78
97
classSolution {
79
98
publicintremoveElement(int[] nums, intval) {
@@ -115,7 +134,7 @@ class Solution:
115
134
return left
116
135
```
117
136
118
-
### Solution 2: Fast and Slow Pointers (more concise)
137
+
### Solution 2: Fast and Slow Pointers (more concise and easier to code)
0 commit comments