Find the longest word from letters

dCode

Search for a tool

Longest Word Solver

Tool/Solver to search for the longest word made out of some letters. Longest word is a game letter whose purpose is to find the longest word possible using some given letters, a concept close to anagramming.

Results

Longest Word Solver

Tag(s) : Word Games

Share

Share

dCode and more

dCode is free and its tools are a valuable help in games, maths, geocaching, puzzles and problems to solve every day!
A suggestion ? a feedback ? a bug ? an idea ? Write to dCode!

  1. Games and Solvers
  2. Word Games
  3. Longest Word Solver

Make the Longest Word with these Letters

Play/Generate random letters

Answers to Questions (FAQ)

What is the longest word game? (Definition)

The longest word is a part of the Countdown TV program, whose purpose is to find the longest word by using only some selected letters (e.g. to rearrange letters in order to make a word from letters).

There are many letter games whose purpose is to make a word from letters (Scrabble, Wordox, Words with Friends, etc.). Most are similar to the longest word game, for example if the goal is to use all letters, it is an anagram.

In the original rules, a word list (dictionary reference) tells which word is an accepted solution or not (no proper noun). The program here is not limited and allows all kind of words, including conjugated verbs and sometimes some proper nouns.

What are the variants of the longest word game?

In its original version, the player has to try to make an anagram of the letters, or remove some of them to get the longest/biggest word possible.

Example: ABCDEFGHIJ gives JIGHEAD (7 letters)

There are variants where letters can be used multiple times (repeating letters).

Example: ABCDEFGHIJ giving CHIFFCHAFF (10 letters)

It is also possible to search a word without scrambling the letters

Example: ABCDEFGHIJ allows A_C____HI_ (ACHI) (4 letters)

Finally, it is possible to mix the two options

Example: ABCDEFGHIJ gives BEEF (4 letters)

See also dCode solvers: Scrabble, Boggle, Words containing… etc.

When was the TV Show ‘Countdown’ invented?

In 1965, in a French TV Show by Armand Jammot, completed in 1972 by countdown numbers rounds.

How to perform a random letters selection for the longest word game?

What is the longest word in english?

The longest word varies according to the dictionary used:

pneumonoultramicroscopicsilicovolcanoconiosis, but technical

hippopotomonstrosesquipedaliophobia, a word that has been created to describe the fear of long words.

antidisestablishmentarianism, found in all major dictionaries

Source code

dCode retains ownership of the «Longest Word Solver» source code. Except explicit open source licence (indicated Creative Commons / free), the «Longest Word Solver» algorithm, the applet or snippet (converter, solver, encryption / decryption, encoding / decoding, ciphering / deciphering, translator), or the «Longest Word Solver» functions (calculate, convert, solve, decrypt / encrypt, decipher / cipher, decode / encode, translate) written in any informatic language (Python, Java, PHP, C#, Javascript, Matlab, etc.) and all data download, script, or API access for «Longest Word Solver» are not public, same for offline use on PC, mobile, tablet, iPhone or Android app!
Reminder : dCode is free to use.

Cite dCode

The copy-paste of the page «Longest Word Solver» or any of its results, is allowed as long as you cite dCode!
Exporting results as a .csv or .txt file is free by clicking on the export icon
Cite as source (bibliography):
Longest Word Solver on dCode.fr [online website], retrieved on 2023-04-14, https://www.dcode.fr/longest-word-solver

French (Français)

Summary

https://www.dcode.fr/longest-word-solver

© 2023 dCode — The ultimate ‘toolkit’ to solve every games / riddles / geocaching / CTF.

 

I’m guessing this is something like finding possible words given a set of Scrabble tiles, so that a character can be repeated only as many times as it is repeated in the original list.

The trick is to efficiently test each character of each word in your word file against a set containing your source letters. For each character, if found in the test set, remove it from the test set and proceed; otherwise, the word is not a match, and go on to the next word.

Python has a nice function all for testing a set of conditions based on elements in a sequence. all has the added feature that it will «short-circuit», that is, as soon as one item fails the condition, then no more tests are done. So if your first letter of your candidate word is ‘z’, and there is no ‘z’ in your source letters, then there is no point in testing any more letters in the candidate word.

My first shot at writing this was simply:

matches = []
for word in wordlist:
    testset = set(letters)
    if all(c in testset for c in word):
        matches.append(word)

Unfortunately, the bug here is that if the source letters contained a single ‘m’, a word with several ‘m’s would erroneously match, since each ‘m’ would separately match the given ‘m’ in the source testset. So I needed to remove each letter as it was matched.

I took advantage of the fact that set.remove(item) returns None, which Python treats as a Boolean False, and expanded my generator expression used in calling all. For each c in word, if it is found in testset, I want to additionally remove it from testset, something like (pseudo-code, not valid Python):

all(c in testset and "remove c from testset" for c in word)

Since set.remove returns a None, I can replace the quoted bit above with «not testset.remove(c)», and now I have a valid Python expression:

all(c in testset and not testset.remove(c) for c in word)

Now we just need to wrap that in a loop that checks each word in the list (be sure to build a fresh testset before checking each word, since our all test has now become a destructive test):

for word in wordlist:
    testset = set(letters)
    if all(c in testset and not testset.remove(c) for c in word):
        matches.append(word)

The final step is to sort the matches by descending length. We can pass a key function to sort. The builtin len would be good, but that would sort by ascending length. To change it to a descending sort, we use a lambda to give us not len, but -1 * len:

matches.sort(key=lambda wd: -len(wd))

Now you can just print out the longest word, at matches[0], or iterate over all matches and print them out.

(I was surprised that this brute force approach runs so well. I used the 2of12inf.txt word list, containing over 80,000 words, and for a list of 10 characters, I get back the list of matches in about 0.8 seconds on my little 1.99GHz laptop.)

Suppose we have a list of words and a string called letters, we have to find the size of the longest word that can be made by rearranging the given letters. In the letters there may be asterisk character (*) it can match any character. And it is not necessary to use all the letters.

So, if the input is like words = [«prince», «rice», «price», «limit», «hello»] letters = «*r**ce*», then the output will be 6, as the longest word we can make is «prince» the length is 6.

To solve this, we will follow these steps:

  • has := a map containing letters and frequencies of each element in letters
  • Define a function valid() . This will take s
  • need := a map containing letters and frequencies of each element in s
  • extra := sum of all elements of (maximum of 0 and need[char] — has[char] for all char in need)
  • return true when extra <= has[«*»]
  • From the main method do the following:
  • return maximum of all elements in the list [size of word for all word in words when word is valid]

Let us see the following implementation to get better understanding:

Example 

Live Demo

from collections import Counter

class Solution:
   def solve(self, words, letters):
      has = Counter(letters)

      def valid(s):
         need = Counter(s)
         extra = sum([max(0, need[char] - has[char]) for char in need])
         return extra <= has["*"]

      return max([len(word) for word in words if valid(word)])

ob = Solution()
words = ["prince", "rice", "price", "limit", "hello"]
letters = "*r**ce*"
print(ob.solve(words, letters))

Input

["prince", "rice", "price", "limit", "hello"], "*r**ce*"

Output

6

My friend gave me a problem that he says is easy, but I can’t figure out a good algorithm to use to do it.

You are given an input of 100 random English words. You have to find the longest string of words where the last letter in one word matches the first letter in the next word. You can only use each word once.

For example, if you were given the words «cat», «dog», «that», the longest string you could make would be «cat -> that». If you were given the words «mouse», «moose», «unicorn», the longest string you could make would just be one word (since none of those words link). If you were given the words «bird», «dish», «harb», the longest string you could make would be «harb -> bird -> dish» (or «dish -> harb -> bird» or «bird -> dish -> harb»).

I came up with the idea of modeling this as a directed cyclic graph. Each node would just be a word, with vertices going to each word/node that started with the letter this word ended with.

+-------+          +------+
|  cat  |-----------| that |
+-------+         / +------+
    |                  |
   |/                 |
+-------+ /            |
|  the  |--------------+
+-------+ 

This problem appears to be a longest path search, which is NP-Hard.

Is there a better way to do it? Or even some sort of approximation algorithm that could be used? Or some way to exploit qualities of English to reduce the search space?

asked Aug 11, 2013 at 7:11

Abe Tool's user avatar

15

I think this is related to the longest path (LP) problem that you mentioned, but it’s a little different. The primary difference is that the LP problem has a higher degree of connectivity than what your suggested problem does. By restricting your connections to the last and first letters, you remove a large number of potential combinations.

Here’s how I would recommend tackling this one:

  1. For each word in the list, count the possible connections in and connections out.
  2. Discard any words that have 0 ins and 0 outs.
  3. Identify an initial set of «starter words» with the lowest numbers of ins and outs, and the outs must be greater than 0.
  4. Each starter word receives its own working copy of the ins / outs connection count. This forms the head of the chain.
  5. For each chain, identify a list of «next words» based upon:
    • last letter of starter or previous word
    • lowest number of of ins and outs connections (again, the outs must be greater than 0)
  6. For each next word, repeat step 5 until the chain terminates.

Keep in mind that:

  • You’ll need to keep track of the length of the chains and have some global mechanism to identify the longest chain.

  • You’ll also need to remove each word from the working copy of the connection counts in order to avoid a recursive loop.

  • At some point, your chain will terminate and you have to select a word with a 0 connection out count.

  • You may have to recalculate ins / outs as words are removed from the working lists. At first glance, I don’t think this will be necessary as the overall sets will be relatively small. If you scaled out to 1000 words, then having static counts may slow down the algorithm from converging.

I kind of saw this as a packing problem. To me, the connections in and out identify the shape to be packed. The lower the connections, the more odd the shape. The more odd the shape, the sooner I want to pack it as I perceived having decreasing odds of being able to pack an odd shape the later I got into the chain.

As an example:

{dog, gopher, alpha, cube, elegant, this, that, bart}

dog     0, 1
gopher  1, 0
alpha   0, 0
cube    0, 1
elegant 1, 2
this    3, 0
that    2, 1
bart    0, 2

//alpha is dropped with 0 in and 0 out.
//two candidates found: dog, cube

//chain 1
dog => gopher
//chain 2
cube => elegant => that => this

//Note 1: the following chain won't occur due to selection rules
//that takes priority over this because of output count
cube => elegant => this

//Note 2: this chain won't occur either due to selection rules
bart => that => this

answered Aug 14, 2013 at 17:54

5

If you make 26X26 matrix to represent directed graph of vertex as each alphabet and words as edge.
For example word — APPLE connect vertex A and E with edge directed from A to E.
Now the problem reduces to finding largest Eulerian trail (path which includes maximum number of edges, visiting each edge once wit possible repetition of vertices) in the graph.
One of the O(E) algorithm would be to start randomly from a pair of vertices.
Find a path between them. Than keep relaxing the path till it is possible.

update
@GlenH7 I solved a similar question on www.hackerearth/jda recently, there was relative marks with respect to best solution and I scored the highest marks with the following approch-

Given list of words. Find the longest chain that can be formed by them. A chain is valid if every word begin with a letter *ending at the ending of last word.

Approch =

1)make the graph of alphabets as vertices and words as edges.
In place of using multiple edges use one with weight equal to
number of edges.

2)find the strongly connected component of graph with
maximum edges. Temporarily discard other edges.

3)For each vertex make its indegree equal to its outdegree.

4)Now their exists eulerian circuit in graph. Find it.

5)Now in remaining graph(w.r.t orignal graph find the longest
trail with first vertex in chosen strongly connected
component. I think this is NP hard.

6)Include the above trail in Elerian circuit converting eulerian
circuit into trail.

Why — I accept that this question is most probably NP hard(guess, not mathematically speaking). But the above approach works best when there is a long list(1000+) of uniformly distributed words(i.e. not intended to be w.c. for above approach).
Let us assume that after converting given list to graph mentioned above, it luckily turns out to be a eulerian graph(see http://en.wikipedia.org/wiki/Eulerian_path for conditions), then without any doubt we can say that answer to above question is P and is actually the eulerian path in the graph(see http://www.graph-magics.com/articles/euler.php for a very simple approch to do so and see this to verify that your graph has single http://www.geeksforgeeks.org/strongly-connected-components/ and if not temporarily clean other small scc because eulerian path exists for single scc). Thus for not lucky cases(which are almost all cases) I try to convert them to lucky cases(i.e eulerian trail condition are fulfilled). How to do this? I tried do increasing depth search for irrelevant edges(the set of edges in a path staring from vertex with outdegree greater than indegree and ending at vertex with indegree greater than outdegree). Increasing depth search means that first I searched for all such set of one edge in path than two edges in path and so on. It may seem at first look that ith depth search would take O(nodes^i) thus total time complexity of O(nodes + nodes^2 + nodes^3 + ….) till it is a lucky case. But amortized analysis will revel it is O(edges). Once it is reduced lucky case find eulerian circuit.

Till here it was all polynomial time. This would give almost the best solution. But to further increase your solution(perfect solution is NP hard) try some greedy approach in remaining graph to find a long trail staring with one of vertices in chosen scc. Now add this to above found eulerian trail to further increase it.

answered Jun 25, 2014 at 20:25

vishfrnds's user avatar

1

Idea:

First, create two maps (hashes), say, S, and E, from alphabet letters to words; the first, S, maps starting letters to words, the second, E, does the same with ending letters.

E.g., if the dictionary is made of:

bird, dish, dog, harb

we have:

S:

a -> [ ]
b -> [ bird ]
c -> [ ]
d -> [ dish, dog ]
...
h -> [ harb ]
...

and,

E:

a -> [ ]
b -> [ harb ]
c -> [ ]
d -> [ bird ]
...
g -> [ dog ]
h -> [ dish ]
...

Next, using S and E for fast lookups, create a forest (set of trees), of the same size as the dictionary, with roots at each word, and not allowing a word to appear more than once in a tree — cache the trees’ depths as you construct them:

bird (depth: 2)
   dish
      harb
   dog

dish (depth: 3)
   harb
      bird
         dog

dog (depth: 0)

harb (depth: 2)
   bird
      dish
      dog

Finally, iterate over the forest and find the tree(s) of greatest depth.

The solution(s) will be on the descendant axis of those trees.

E.g.,

dish / harb / bird / dog

above.

answered Mar 7, 2016 at 15:33

YSharp's user avatar

YSharpYSharp

8986 silver badges10 bronze badges

Like this post? Please share to your friends:
  • Find the international word выберите один ответ house football foreigner play
  • Find the hidden words in the word search
  • Find the hidden word перевод
  • Find the hidden word in a sentence
  • Find the group word for these words