diff --git a/src/data-structures/trie/trie.ts b/src/data-structures/trie/trie.ts index 65503f8..05c23dc 100644 --- a/src/data-structures/trie/trie.ts +++ b/src/data-structures/trie/trie.ts @@ -454,7 +454,12 @@ export class Trie extends IterableElementBase> { if (prefix) { for (const c of prefix) { const nodeC = startNode.children.get(c); - if (nodeC) startNode = nodeC; + if (nodeC) { + startNode = nodeC; + } else { + // Early return if the whole prefix is not found + return []; + } } } diff --git a/test/unit/data-structures/trie/trie.test.ts b/test/unit/data-structures/trie/trie.test.ts index 59e02f9..4b87714 100644 --- a/test/unit/data-structures/trie/trie.test.ts +++ b/test/unit/data-structures/trie/trie.test.ts @@ -836,6 +836,22 @@ describe('Trie operations', () => { expect(words).toEqual(['apple', 'appetizer']); }); + it('Get no words when prefix not found, with no match from the first character', () => { + trie.add('apple'); + trie.add('appetizer'); + trie.add('banana'); + const words = trie.getWords('cd'); + expect(words).toEqual([]); + }); + + it('Get no words when prefix not found, with no match from the second character', () => { + trie.add('apple'); + trie.add('appetizer'); + trie.add('banana'); + const words = trie.getWords('ab'); + expect(words).toEqual([]); + }); + it('Tree Height', () => { trie.add('apple'); trie.add('banana');