Created
August 1, 2025 22:39
-
-
Save alexharri/82e96a93ff2b5c3137adddd3483a16c3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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