Skip to content

Instantly share code, notes, and snippets.

@benschac
Created November 16, 2020 13:43
Show Gist options
  • Save benschac/c716c9db36bf6b0b088490d2a0499b60 to your computer and use it in GitHub Desktop.
Save benschac/c716c9db36bf6b0b088490d2a0499b60 to your computer and use it in GitHub Desktop.
// Given an array of integers arr, a pair (n,m) is called “special” if arr[n] == arr[m], and n < m.
// Return the number of special pairs.
// Hint: Nested for loops can work for this one, but a hashmap solution will have a better runtime!
// $ specialPairs([1,2,3,1,1,3])
// $ 4 // (0,3), (0,4), (3,4), (2,5)
function specialPairs(arr) {
// let cache = {};
let count = 0;
for (let i = 0; i < arr.length; i++) {
for (let j = i + i; j < arr.length; j++) {
if (arr[i] === arr[j]) {
count += 1;
}
}
}
return count;
}
function specialPairsReduce(arr) {
let cache = arr.reduce((prev, curr, idx) => {
prev[curr] = Array.isArray(prev[curr]) ? prev[curr].concat([idx]) : [idx];
return prev;
}, {});
let count = 0;
Object.keys(cache).forEach((el) => {
if (cache[el].length > 1) {
if (cache[el].length % 2 === 0) {
count += cache[el].length;
} else {
count += cache[el].length - 1;
}
}
});
return count;
}
console.log(specialPairsReduce([1, 2, 3, 1, 1, 3, 1]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment