Skip to content

Instantly share code, notes, and snippets.

@cdaz5
Last active September 23, 2017 13:42
Show Gist options
  • Select an option

  • Save cdaz5/047e7f9ceecdc751bc9c49e7cadafa64 to your computer and use it in GitHub Desktop.

Select an option

Save cdaz5/047e7f9ceecdc751bc9c49e7cadafa64 to your computer and use it in GitHub Desktop.
HackerRank Anagram Solution
function main() {
// provided by hackerrank
var a = readLine();
var b = readLine();
// split the input into an array
aArray = a.split('')
bArray = b.split('')
// declare a variable set equal to an empty object
let hashTable = {}
// loop through aArray..
for (let i = 0; i < aArray.length; i++) {
// if a key of the letter doesn't exist create it and set the value equal to 1.
// if it does exist increment the value by 1.
if (!hashTable[aArray[i]]) {
hashTable[aArray[i]] = 1
} else {
hashTable[aArray[i]] += 1
}
}
// declare a variable count and set it equal to 0
let count = 0
// loop through bArray...
for (let j = 0; j < bArray.length; j++) {
// if our object contains a key with the current iterative letter AND it's value
// is greater than 0 decrement it and increment the count variable by 2 (since we
// would need to delete both).
if (hashTable[bArray[j]] && hashTable[bArray[j]] > 0) {
hashTable[bArray[j]] -= 1
count += 2
}
}
// add the lengths of aArray and bArray and subtract it by count
total = (aArray.length + bArray.length) - (count)
console.log(total)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment