Skip to content

Commit

Permalink
improve find duplicates problem description and tests (#142)
Browse files Browse the repository at this point in the history
  • Loading branch information
spring1843 committed Aug 19, 2024
1 parent 7668a1f commit b154793
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
6 changes: 4 additions & 2 deletions array/find_duplicate_in_array.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package array

import "math"

// FindDuplicate solves the problem in O(n) time and O(1) space.
func FindDuplicate(list []int) int {
for _, item := range list {
itemIndex := item - 1
itemIndex := int(math.Abs(float64(item))) - 1
if list[itemIndex] < 0 {
return list[itemIndex] * -1
return item
}
list[itemIndex] *= -1
}
Expand Down
5 changes: 4 additions & 1 deletion array/find_duplicate_in_array_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ TestFindDuplicate tests solution(s) with the following signature and problem des
FindDuplicate(list []int) int
Given a list of integers (1,2,...,n), find a duplicate number in O(n) time.
Given a list of n integers (3, 2, 1, 4, 5, 4,...,n) where each number is positive and smaller
than n find the duplicate integer.
*/
func TestFindDuplicate(t *testing.T) {
tests := []struct {
Expand All @@ -19,6 +20,8 @@ func TestFindDuplicate(t *testing.T) {
{[]int{1, 2, 3}, -1},
{[]int{1, 1, 2, 3}, 1},
{[]int{1, 2, 2, 3}, 2},
{[]int{1, 2, 3, 2, 4, 5}, 2},
{[]int{3, 2, 1, 4, 5, 4}, 4},
}

for i, test := range tests {
Expand Down

0 comments on commit b154793

Please sign in to comment.