Skip to content

Commit f9c7560

Browse files
authored
Merge pull request #41 from khairalanam/khair
Add Remove Duplicates Problem
2 parents 3bc5e12 + b668318 commit f9c7560

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# Palindrome (L-I)
2+
3+
## Problem
4+
5+
- Write a function in JavaScript that takes a sorted array of integers as input and returns an array with unique elements
6+
7+
- Example Inputs and Outputs:
8+
9+
- Input: `[0, 0, 1, 1, 1, 2, 2, 3, 3, 4]` -> Output: `[ 0, 1, 2, 3, 4 ]`
10+
- Input: `[1, 1, 1, 2, 2, 3, 3, 4, 6, 7, 8, 8, 9]` -> Output: `[
11+
1, 2, 3, 4,
12+
6, 7, 8, 9
13+
]`
14+
15+
## Solution
16+
17+
```javascript
18+
const RemoveDuplicates = (nums) => {
19+
i = 1;
20+
21+
size = nums.length;
22+
23+
while (i < size) {
24+
if (nums[i] === nums[i - 1]) {
25+
nums.splice(i, 1);
26+
size -= 1;
27+
} else i += 1;
28+
}
29+
30+
return nums;
31+
};
32+
```
33+
34+
## How it works
35+
36+
- The function takes an array `nums` as input and returns `nums` with unique elements.
37+
38+
- We initialise an index `i` to be `1` and `size` to be the length of `nums`.
39+
40+
- We run a while loop whenever `i < size`.
41+
42+
- if the current element at index `i` is equal to the previous element, then remove the current element from `nums`
43+
44+
- If not, then increment `i` by `1`.
45+
46+
- After the while loop terminates, we return the `nums` array.
47+
48+
## References
49+
50+
- [Leetcode](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)
51+
52+
## Problem Added By
53+
54+
- [GitHub](https://www.github.com/khairalanam)
55+
- [LinkedIn](https://www.linkedin.com/in/khair-alanam-b27b69221/)
56+
- [Twitter](https://twitter.com/khair_alanam)
57+
58+
## Contributing
59+
60+
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
const RemoveDuplicates = (nums) => {
2+
i = 1;
3+
4+
size = nums.length;
5+
6+
while (i < size) {
7+
if (nums[i] === nums[i - 1]) {
8+
nums.splice(i, 1);
9+
size -= 1;
10+
} else i += 1;
11+
}
12+
13+
return nums;
14+
};
15+
16+
nums = [1, 1, 1, 2, 2, 3, 3, 4, 6, 7, 8, 8, 9];
17+
18+
console.log(RemoveDuplicates(nums));

0 commit comments

Comments
 (0)