Skip to content

Commit b154793

Browse files
authored
improve find duplicates problem description and tests (#142)
1 parent 7668a1f commit b154793

File tree

2 files changed

+8
-3
lines changed

2 files changed

+8
-3
lines changed

array/find_duplicate_in_array.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
package array
22

3+
import "math"
4+
35
// FindDuplicate solves the problem in O(n) time and O(1) space.
46
func FindDuplicate(list []int) int {
57
for _, item := range list {
6-
itemIndex := item - 1
8+
itemIndex := int(math.Abs(float64(item))) - 1
79
if list[itemIndex] < 0 {
8-
return list[itemIndex] * -1
10+
return item
911
}
1012
list[itemIndex] *= -1
1113
}

array/find_duplicate_in_array_test.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ TestFindDuplicate tests solution(s) with the following signature and problem des
77
88
FindDuplicate(list []int) int
99
10-
Given a list of integers (1,2,...,n), find a duplicate number in O(n) time.
10+
Given a list of n integers (3, 2, 1, 4, 5, 4,...,n) where each number is positive and smaller
11+
than n find the duplicate integer.
1112
*/
1213
func TestFindDuplicate(t *testing.T) {
1314
tests := []struct {
@@ -19,6 +20,8 @@ func TestFindDuplicate(t *testing.T) {
1920
{[]int{1, 2, 3}, -1},
2021
{[]int{1, 1, 2, 3}, 1},
2122
{[]int{1, 2, 2, 3}, 2},
23+
{[]int{1, 2, 3, 2, 4, 5}, 2},
24+
{[]int{3, 2, 1, 4, 5, 4}, 4},
2225
}
2326

2427
for i, test := range tests {

0 commit comments

Comments
 (0)