Skip to content

Instantly share code, notes, and snippets.

@tangjeff0
Last active November 6, 2018 14:28
Show Gist options
  • Save tangjeff0/e16c84645e18b20677e05af22b2cfebe to your computer and use it in GitHub Desktop.
Save tangjeff0/e16c84645e18b20677e05af22b2cfebe to your computer and use it in GitHub Desktop.
const assert = require('assert')
/* takes in two strings, and returns if they are anagrams */
function isAnagram(a,b) {
if (a.length != b.length) {
return false
}
var o1 = {}
var o2 = {}
var i
/* TODO: how could you refactor these two loops? */
for (i = 0; i < a.length; i++) {
var ch = a[i]
if (ch in o1) {
o1[ch] += 1
} else {
o1[ch] = 1
}
}
for (i = 0; i < b.length; i++) {
var ch = b[i]
if (ch in o2) {
o2[ch] += 1
} else {
o2[ch] = 1
}
}
/* TODO: why do we only need to iterate over o1 and not o2 as well */
for (var k in o1) {
if (o1[k] != o2[k]) {
return false
}
}
return true
}
/* test */
assert(isAnagram('aba', 'aab') === true)
assert(isAnagram('aa', 'aab') === false)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment