Find the Length of the Longest Common Prefix
MediumArrayHash TableStringTrie
Solution
Solution1: Set
export function longestCommonPrefix(arr1: number[], arr2: number[]): number {
const prefixes = new Set<number>();
for (const num of arr1) {
for (const prefix of getPrefix(num)) {
prefixes.add(prefix);
}
}
let answer = 0;
for (const num of arr2) {
for (const prefix of getPrefix(num)) {
if (prefixes.has(prefix)) {
answer = Math.max(answer, Math.floor(Math.log10(prefix)) + 1);
}
}
}
return answer;
}
function* getPrefix(num: number) {
let curr = num;
while (0 < curr) {
yield curr;
curr = Math.floor(curr / 10);
}
}
Complexity
- Time:
O(M+N)
- Space:
O(M)
Soltuion2: Trie
export function longestCommonPrefix(arr1: number[], arr2: number[]): number {
const trie = new Trie(arr1);
return arr2.reduce((prev, num) => Math.max(prev, trie.findLongestPrefix(num)), 0);
}
class TrieNode {
children: Array<TrieNode | null>;
constructor() {
this.children = new Array(10).fill(null);
}
}
class Trie {
private readonly root: TrieNode;
constructor(arr: number[]) {
this.root = new TrieNode();
arr.forEach((num) => this.insert(num));
}
insert(num: number): void {
let node = this.root;
for (const digit of String(num)) {
const i = parseInt(digit);
const childNode = node.children[i];
if (childNode !== null) {
node = childNode;
} else {
const newNode = new TrieNode();
node.children[i] = newNode;
node = newNode;
}
}
}
findLongestPrefix(num: number): number {
let node = this.root;
let maxLength = 0;
for (const digit of String(num)) {
const i = parseInt(digit);
const childNode = node.children[i];
if (childNode === null) {
break;
}
node = childNode;
maxLength += 1;
}
return maxLength;
}
}
Complexity
- Time:
O(M+N)
- Space:
O(M)