Skip to content

Instantly share code, notes, and snippets.

@alexharri
Created August 1, 2025 22:39
Show Gist options
  • Select an option

  • Save alexharri/82e96a93ff2b5c3137adddd3483a16c3 to your computer and use it in GitHub Desktop.

Select an option

Save alexharri/82e96a93ff2b5c3137adddd3483a16c3 to your computer and use it in GitHub Desktop.
interface TrieNode {
children?: { [key: string]: TrieNode }
value?: string
}
function mergeLeavesWithCommonValues(node: TrieNode) {
if (!node.children) {
return;
}
for (const child of Object.values(node.children)) {
mergeLeavesWithCommonValues(child)
}
const newChildren: Record<string, TrieNode> = {};
const keysByValue: Record<string, string[]> = {};
for (const [key, child] of Object.entries(node.children)) {
if (child.value) {
keysByValue[child.value] ??= [];
keysByValue[child.value].push(key)
} else {
newChildren[key] = child;
}
}
for (const [value, keys] of Object.entries(keysByValue)) {
newChildren[keys.join("")] = { value };
}
node.children = newChildren;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment