Skip to content

Commit

Permalink
feat(LeetCode #26): remove duplicates from sorted array
Browse files Browse the repository at this point in the history
  • Loading branch information
Angelica Hjelm Gardner committed Jan 19, 2025
1 parent 8e3536a commit a56ceca
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
20 changes: 20 additions & 0 deletions LeetCode/problem026_RemoveDuplicatesSortedArray.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package leetcode

// Time complexity: O(n)
// Space complexity: O(1)
func RemoveDuplicates(nums []int) int {
if len(nums) == 0 {
return 0
}

uniqueElements := 1

for i := 1; i < len(nums); i++ {
if nums[i] != nums[i-1] {
nums[uniqueElements] = nums[i]
uniqueElements++
}
}

return uniqueElements
}
26 changes: 26 additions & 0 deletions LeetCode/problem026_RemoveDuplicatesSortedArray_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package leetcode

import "testing"

func TestRemoveDuplicates(t *testing.T) {
var tests = []struct {
name string
input []int
expected []int
output int
}{
{"Short array", []int{1, 1, 2}, []int{1, 2}, 2},
{"Longer array", []int{0, 0, 1, 1, 1, 2, 2, 3, 3, 4}, []int{0, 1, 2, 3, 4}, 5},
{"Empty array", []int{}, []int{}, 0},
{"Only duplicates", []int{1, 1, 1, 1}, []int{1}, 1},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := RemoveDuplicates(tt.input)
if result != tt.output {
t.Errorf("RemoveDuplicates(%v) = %v; want %v", tt.input, result, tt.output)
}
})
}
}

0 comments on commit a56ceca

Please sign in to comment.