Skip to content

Instantly share code, notes, and snippets.

@iconifyit
Last active March 5, 2020 04:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iconifyit/7148719444a2c3ad0616feeed2382aad to your computer and use it in GitHub Desktop.
Save iconifyit/7148719444a2c3ad0616feeed2382aad to your computer and use it in GitHub Desktop.
30 Days of Algorithms : 04 - Find shared items between two lists.
/**
* Find shared elements between two lists.
* @param {array} x
* @param {array} y
* @returns {[]}
*/
const shared_items = ( x, y ) => {
x.sort();
y.sort();
let i = 0,
j = 0;
const shared = [];
while ( i < x.length && j < y.length ) {
/*
* If x[i] and y[j] are not equal, Increment
* the appropriate counter and move on. We can
* be confident that whichever item is "less than"
* the other will not appear in the other list later
* since we sorted the lists before starting the
* comparison.
*/
if ( x[i] < y[j] ) i++;
else if ( y[j] < x[i] ) j++;
/*
* If x[i] and y[j] are equal,
* add the shared element to the shared list.
*/
else {
shared.push( x[i] );
i++;
j++;
}
}
return shared;
}
console.log( shared_items(
['red', 'blue', 'green', 'apple', 'cat', 'dog'],
['purple', 'black', 'pink', 'moose', 'cow', 'dog', 'cat']
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment