Back to articles
How Word Scramble Solvers Use the Same Algorithm as Spell Checkers
How-To

How Word Scramble Solvers Use the Same Algorithm as Spell Checkers

via Dev.to BeginnersMichael Lip

Given the scrambled letters "AELPP", find all valid English words. The answer includes "APPLE", "PALE", "LEAP", "PLEA", "APE", "LAP", "PAL", "PEA", and others. A human might find 5-10 of these through trial and error. An algorithm finds all of them in milliseconds. The algorithmic approach is elegant and teaches a useful pattern: using sorted character signatures as lookup keys. The anagram signature approach The key insight: two words are anagrams of each other if and only if they have the same sorted characters. "LISTEN" and "SILENT" both sort to "EILNST". This means you can build an index of all English words keyed by their sorted character signature. function getSignature ( word ) { return word . toLowerCase (). split ( '' ). sort (). join ( '' ); } // Build the index const dictionary = loadDictionary (); // ~270,000 English words const index = {}; for ( const word of dictionary ) { const sig = getSignature ( word ); if ( ! index [ sig ]) index [ sig ] = []; index [ sig ]. push ( w

Continue reading on Dev.to Beginners

Opens in a new tab

Read Full Article
7 views

Related Articles