Created
June 5, 2020 13:14
-
-
Save mkamranhamid/407adf31f781b3ac133b4b5c8c1ddaa9 to your computer and use it in GitHub Desktop.
Find value that occurs in odd number of elements.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// codility test prep questions | |
// For example, in array A such that: | |
// A[0] = 9 A[1] = 3 A[2] = 9 A[3] = 3 A[4] = 9 A[5] = 7 A[6] = 9 | |
// the elements at indexes 0, 2 and 4 have value 9, | |
// the elements at indexes 1 and 3 have value 3, | |
// the element at index 5 has value 7 and is unpaired. | |
function findPairs(arr){ | |
var hash = {} | |
arr.map((num)=>{ | |
if(!hash[num]){ | |
hash[num] = 1 | |
} else { | |
hash[num] += 1 | |
} | |
}) | |
return hash; | |
} | |
function findPairFrequency(hash, freq){ | |
return Object.keys(hash).filter(key=> hash[key]==freq)[0] | |
} | |
var randomArray = [9,3,9,3,9,7] | |
var pairingHash = findPairs(randomArray) | |
var noPair = findPairFrequency(pairingHash, 1) | |
console.log(noPair) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment