Skip to content

Instantly share code, notes, and snippets.

@erineland
Created June 25, 2019 23:49
Show Gist options
  • Save erineland/1966c7a9208c9ef58bb89f95c6247791 to your computer and use it in GitHub Desktop.
Save erineland/1966c7a9208c9ef58bb89f95c6247791 to your computer and use it in GitHub Desktop.
A small Node util done as a coding exercise to find the unique values in 2 (or more!) arrays. Should have O(n) space and time complexity so is scalable.
// I wrote this in a local IDE (VSCode FTW) so that I could test it before writing it here, as there is limited tooling
// Only maps through each array once, and then the object (dictionary of elements and locations) once.
// Hence, this has linear O(n) time complexity and and O(n) space complexity. This is OK, could be better.
const reconcileHelpers = (firstArray, secondArray) => {
var elementLocations = {}; // empty dictionary for super fast O(1) lookups.
const arrayParser = (element, arrayName) => {
var existingLocations = elementLocations[element];
if (existingLocations) {
elementLocations[element].push(arrayName);
} else {
elementLocations[element] = [arrayName];
}
}
// Parse the first array elements and store location
firstArray.forEach(element => arrayParser(element, '1st'));
// Parse 2nd array and store arrays it is located in (could scale to more arrays!)
secondArray.forEach(element => arrayParser(element, '2nd'));
// Produces a 'map' something like...
// {
// '3': ['2nd', '1st'],
// '4': ['2nd', '1st'],
// '5': ['1st'],
// '6': ['2nd'],
// '10': ['2nd']
// }
// Now parse the elements and their locations, and the array they are unique to.
const uniqueFirstArrayElements = [];
const uniqueSecondArrayElements = [];
Object.keys(elementLocations).forEach(element => {
const currentElementLocations = elementLocations[element];
if (currentElementLocations.length === 1) {
// Then this must mean it's unique to one of the arrays!
// Determine which list element is unique to
const currentElementArrayName = currentElementLocations[0]; // 0th index because only 1 location!
if (currentElementArrayName === '1st') {
uniqueFirstArrayElements.push(element);
} else if (currentElementArrayName === '2nd') {
uniqueSecondArrayElements.push(element);
}
}
});
// Now print out the results
console.log("Numbers in array 1 that aren't in array 2:");
console.log(uniqueFirstArrayElements.toString());
console.log("Numbers in array 2 that aren't in array 1:");
console.log(uniqueSecondArrayElements.toString());
}
// Test the function...
var array1 = [5, 3, 4];
var array2 = [4, 3, 6, 10];
reconcileHelpers(array1, array2);
// You should see the expected results printed to the console...
//Numbers in array 1 that aren't in array 2:
//5
//Numbers in array 2 that aren't in array 1:
//6,10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment