Last active
November 9, 2018 21:04
-
-
Save AlexeiDarmin/a5f4d02c5123334a6a7d32a8cfb0716e to your computer and use it in GitHub Desktop.
getCommonEntries(arr1: number[], arr2: number[])
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const array1 = [13, 27, 35, 40, 49, 55, 59] | |
const array2 = [17, 35, 39, 40, 55, 58, 60] | |
// Goal: Get common entries of two arrays, both arrays are the same length and consist of all unique elements. | |
// Best concievable run time = O(A) || O(B) | |
function getCommonEntries(arr1: number[], arr2: number[]) { | |
let index1 = 0 | |
let index2 = 0 | |
const arraySize = arr1.length | |
const commonEntries = [] | |
while (index1 < arraySize && index2 < arraySize) { | |
const v1 = arr1[index1] | |
const v2 = arr2[index2] | |
if (v1 === v2) { | |
commonEntries.push(v1) | |
index1++ | |
index2++ | |
} else if (v1 < v2) { | |
index1++ | |
} else if (v2 < v1) { | |
index2++ | |
} | |
} | |
return commonEntries | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment