Skip to content

Commit 00282eb

Browse files
committed
26. Remove Duplicates from Sorted Array.
- Language: Golang. - Time complexity: O(n). - Space complexity: O(1). - Solution based on: https://algo.monster/liteproblems/80
1 parent 75b1b93 commit 00282eb

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

golang_solutions/26_remove_duplicates_from_sorted_array/main.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,16 @@ func removeDuplicatesV1(nums []int) int {
2828
}
2929
return i + 1
3030
}
31+
32+
// Time complexity: O(n). Space complexity: O(1).
33+
// Solution based on https://algo.monster/liteproblems/80
34+
func removeDuplicatesV2(nums []int) int {
35+
writeIndex := 0
36+
for i := range nums {
37+
if writeIndex < 1 || nums[i] != nums[writeIndex-1] {
38+
nums[writeIndex] = nums[i]
39+
writeIndex += 1
40+
}
41+
}
42+
return writeIndex
43+
}

golang_solutions/26_remove_duplicates_from_sorted_array/main_test.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,10 @@ func TestRemoveDuplicatesV1(t *testing.T) {
1616
testRemoveDuplicates(t, removeDuplicatesV1)
1717
}
1818

19+
func TestRemoveDuplicatesV2(t *testing.T) {
20+
testRemoveDuplicates(t, removeDuplicatesV2)
21+
}
22+
1923
func testRemoveDuplicates(t *testing.T, function fn) {
2024
testCases := []struct {
2125
nums []int

0 commit comments

Comments
 (0)