Skip to content

Instantly share code, notes, and snippets.

@NateScarlet
Created July 20, 2020 09:17
Show Gist options
  • Save NateScarlet/9bbf1840200c573ce1ba6f394cae2281 to your computer and use it in GitHub Desktop.
Save NateScarlet/9bbf1840200c573ce1ba6f394cae2281 to your computer and use it in GitHub Desktop.
export function getCommonPrefix(v: string[]): string {
if (v.length === 0) {
return '';
}
if (v.length === 1) {
return v[0];
}
// return range is [0, w)
let w = v[0].length;
for (let i = 1; i < v.length; i++) {
while (w > 0) {
if (v[i - 1].slice(0, w) === v[i].slice(0, w)) {
break;
}
w--;
}
}
return v[0].slice(0, w);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment