- Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathfind_original_array_from_doubled_array.go
48 lines (43 loc) · 966 Bytes
/
find_original_array_from_doubled_array.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package main
import"sort"
funcfindOriginalArray(changed []int) []int {
//if the total len is odd, return empty array
iflen(changed)%2!=0 {
return []int{}
}
//sort the array
sort.Ints(changed)
//populate the frequency map
freq:=make(map[int]int)
for_, val:=rangechanged {
freq[val]++
}
result:= []int{}
//iterate thru the original array
for_, val:=rangechanged {
cnt:=freq[val]
//no need for check for existence ; element would be present
ifcnt>0 {
//if the count is greater than 0
//reduce the count
freq[val]--
//check for double
dbl:=val*2
//if present and value is greater than 0
//then it is candidate
//however if not present or count is not greater
//than zero then return empty array
ifv, ok:=freq[dbl]; ok {
ifv>0 {
result=append(result, val)
freq[dbl]--
} else {
return []int{}
}
} else {
return []int{}
}
}
}
returnresult
}