diff --git a/LeetCode/problem026_RemoveDuplicatesSortedArray.go b/LeetCode/problem026_RemoveDuplicatesSortedArray.go new file mode 100644 index 0000000..b3f4ce4 --- /dev/null +++ b/LeetCode/problem026_RemoveDuplicatesSortedArray.go @@ -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 +} diff --git a/LeetCode/problem026_RemoveDuplicatesSortedArray_test.go b/LeetCode/problem026_RemoveDuplicatesSortedArray_test.go new file mode 100644 index 0000000..be91a71 --- /dev/null +++ b/LeetCode/problem026_RemoveDuplicatesSortedArray_test.go @@ -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) + } + }) + } +}