We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Golang
Time Complexity: O(n)
Space Complexity: O(n)
First: populates a hash map with all elements from the input array arr for quick lookups.
Second: For each element x, it checks if x - k and x + k exist in the hash map. if exist, count
The current element x is then removed from the hash map to prevent counting the same pair twice (e.g., counting (3, 5) when x=3 and then again when x=5)
func pairs(k int32, arr []int32) int32 {
exist := make(map[int32]bool)
for _, x := range arr {
exist[x] = true
}
count := int32(0)
for _, x := range arr {
if exist[x-k] {
count++
}
if exist[x+k] {
count++
}
exist[x] = false
}
return count
}
`
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Pairs
You are viewing a single comment's thread. Return to all comments →
Golang Time Complexity: O(n) Space Complexity: O(n)
First: populates a hash map with all elements from the input array arr for quick lookups.
Second: For each element x, it checks if x - k and x + k exist in the hash map. if exist, count
The current element x is then removed from the hash map to prevent counting the same pair twice (e.g., counting (3, 5) when x=3 and then again when x=5)
}
`