I was asked this question in an interview.
Given an array of characters, find the shortest word in a dictionary that contains all the characters. Also, propose an implementation for the dictionary that would optimize this function call.
for e.g. char[] chars = { ‘R’ , ‘C’ }. The result should be the word «CAR».
I could not come up with anything that would run reasonably quickly. I thought of pre-processing the dictionary by building a hash table to retrieve all words of a particular length. Then I could only think of retrieving all words in the increasing order of length and checking if the required characters were present in any of those ( maybe by using a bitmask . )
asked Feb 6, 2015 at 22:23
1
This is a common software interview question, and its solution is this: sort the dictionary itself by length and sort each value alphabetically. When given the characters, sort them and find the needed letters.
answered Feb 6, 2015 at 22:40
user3105700user3105700
3656 silver badges16 bronze badges
First sort the dictionary in ascending order of length.
For each letter, construct a bit map of the locations in the dictionary of the words containing that letter. Each bit map will be long, but there will not be many.
For each search, take the intersection of the bitmaps for the letters in the array. The first one bit in the result will be at the index corresponding to the location in the dictionary of the shortest word containing all the letters.
answered Feb 6, 2015 at 22:45
The other answers are better, but I realized this is entirely precomputable.
- For each word
- sort the letters and remove duplicates
- The sequence of letters can be viewed as a bitmask, A=0bit, B=1bit…Z=26bit. Set the bits of a mask A according to the letters in this word.
- For each combination of set bits in the mask A, make a subset mask B
- If there is already a word associated with this mask B
- and this word is shorter, replace the associated word with this one
- otherwise try next B
- If there is no word associated with mask B
- Associate this word with mask B.
- If there is already a word associated with this mask B
This would take a huge amount of setup time, and the subsequent association storage would be in the vicinity of 1.7GB, but you’d be able to find the shortest word containing a superset of the letters in O(1) time guaranteed.
answered Feb 6, 2015 at 22:53
Mooing DuckMooing Duck
62.8k19 gold badges98 silver badges157 bronze badges
The obvious preprocessing is to sort all words in the dictionary by their length and alphabetical re-ordering: «word» under «dorw», for example. Then you can use general search algorithms (e.g., regex) to search for the letters you need. An efficient (DFA) search requires only one pass over the dictionary in the worst case, and much less if the first match is short.
answered Feb 6, 2015 at 22:41
CharlesCharles
11.2k13 gold badges65 silver badges103 bronze badges
Here is a solution in C#:
using System.Collections.Generic;
using System.Linq;
public class ShortestWordFinder
{
public ShortestWordFinder(IEnumerable<string> dictionary)
{
this.dictionary = dictionary;
}
public string ShortestWordContaining(IEnumerable<char> chars)
{
var wordsContaining = dictionary.Where(s =>
{
foreach (var c in chars)
{
if (!s.Contains(c))
{
return false;
}
s = s.Remove(s.IndexOf(c), 1);
}
return true;
}).ToList();
if (!wordsContaining.Any())
{
return null;
}
var minLength = wordsContaining.Min(word => word.Length);
return wordsContaining.First(word => word.Length == minLength);
}
private readonly IEnumerable<string> dictionary;
}
Simple test:
using System.Diagnostics;
using Xunit;
public class ShortestWordFinderTests
{
[Fact]
public void Works()
{
var words = new[] { "dog", "moose", "gargoyle" };
var finder = new ShortestWordFinder(words);
Trace.WriteLine(finder.ShortestWordContaining("o"));
Trace.WriteLine(finder.ShortestWordContaining("oo"));
Trace.WriteLine(finder.ShortestWordContaining("oy"));
Trace.WriteLine(finder.ShortestWordContaining("eyg"));
Trace.WriteLine(finder.ShortestWordContaining("go"));
Assert.Null(finder.ShortestWordContaining("ooo"));
}
}
answered Feb 6, 2015 at 23:10
xofzxofz
5,5506 gold badges45 silver badges62 bronze badges
Pre processing
a. Sort words into alphabetic char arrays. Retain mapping from sorted to original word
b. Split dictionary by word length as you suggest
c. Sort entries in each word length set alphabetically
On function call
- Sort char array alphabetically
- Start with group of same length as array
- Loop through entries testing for characters until first letter of entry lexicographically greater than first in your char array then break. If match then return original word (see a above for mapping)
- Back to 2 for next longest word group
Interesting extensions. Multiple words might map to same entry in a. Which one (s) should you return…
answered Feb 6, 2015 at 22:59
J Richard SnapeJ Richard Snape
20.1k5 gold badges50 silver badges78 bronze badges
Eunoia, at six letters long, is the shortest word in the English language that contains all five main vowels. Seven letter words with this property include adoulie, douleia, eucosia, eulogia, eunomia, eutopia, miaoued, moineau, sequoia, and suoidea. (The scientific name iouea is a genus of Cretaceous fossil sponges.)
Simply so What is the longest video on YouTube? Jonathan Harchick has created and uploaded the longest YouTube video of all time, clocking in at 571 hours, 1 minute and 41 seconds.
What word has no vowels and no Y? Words with no vowels. Cwm and crwth do not contain the letters a, e, i, o, u, or y, the usual vowels (that is, the usual symbols that stand for vowel sounds) in English. … Shh, psst, and hmm do not have vowels, either vowel symbols or vowel sounds. There is some controversy whether they are in fact “words,” however.
also What is the shortest letter? The shortest letter in the world was written to a publisher by this man. All he wrote was… “?”, asking him if the man’s book, Les Miserables, was popular or not. The answer he received was also the shortest letter in the world. It was, “!”, which meant, wonderful!
Is there a word with all 26 letters?
An English pangram is a sentence that contains all 26 letters of the English alphabet. The most well known English pangram is probably “The quick brown fox jumps over the lazy dog”. My favorite pangram is “Amazingly few discotheques provide jukeboxes.”
Who was the first ever Youtuber? The first youtuber was Jawed Karim who was also a founder of YouTube.
What was the first ever video?
The first video recording (or more accurately, the oldest surviving film in existence) was the Roundhay Garden Scene. The silent short that’s only about 2 seconds in length was filmed at the Whitely Family house in Oakwood Grange Road, Roundhay (a suburb of Leeds, Yorkshire) Great Britain in 1888.
What is the longest game in the world? The longest game ever played in the World Series lasted 18 innings and ran for seven hours and 20 minutes, with only a final score of 3-2. The longest game ever played in the World Series took place not too long ago, when the Los Angeles Dodgers beat the Boston Red Sox 3-2 in Game 3 in 2018.
Is Shhh a word?
What type of word is ‘shhh’? Shhh is an interjection – Word Type.
Is there a word without a consonant? English. English has very few words of more than one syllable without a consonant, apart from proper names such as Aeaea, Aiea, Aia, Io, Eiao, Oea, and sometimes Iowa (below), and perhaps a few taxonomic terms such as Iouea below. The maned sloth, or ai, is pronounced with two syllables: /ˈɑːi/.
Is TV considered a word?
noun, plural TVs. television.
Who wrote the shortest letter? (WKBN) – Who holds the record for the shortest letter ever written? We travel back to 1862 in France. The great writer Victor Hugo had just finished his latest novel, “Les Miserables,” and had left on vacation.
What is the shortest letter that Paul wrote?
Philemon was a wealthy Christian, possibly a bishop of the house church that met in his home (Philemon 1:1–2) in Colossae. This letter is now generally regarded as one of the undisputed works of Paul. It is the shortest of Paul’s extant letters, consisting of only 335 words in the Greek text.
What is the 27th letter in the alphabet?
With its quirky shape, neither a letter nor symbol, more of a treble clef than type, the ampersand has grabbed our creative attention.
What start with E and ends with E? Answer: The answer is ENVELOPE. It starts with E, ends with E and has only one letter in it, i.e, you can keep only one letter inside the envelope. Nice riddle but not hard.
What is the most unknown word? The 15 most unusual words you’ll ever find in English
- Nudiustertian. …
- Quire. …
- Yarborough. …
- Tittynope. …
- Winklepicker. …
- Ulotrichous. …
- Kakorrhaphiophobia. If you suffer from this, then you would very much rather not have this word appear in a spelling bee, since it describes the fear of failure.
- Xertz. Who would have imagined it?
Who invented YouTube?
YouTube, Web site for sharing videos. It was registered on February 14, 2005, by Steve Chen, Chad Hurley, and Jawed Karim, three former employees of the American e-commerce company PayPal.
What was the 1st video on YouTube? The first ever YouTube video was uploaded on April 23, 2005 — exactly 15 years ago, today. YouTube co-founder Jawed Karim posted the 18-second video, titled “Me at the zoo.” It has since garnered over 90 million views. To this day, it is the only video on Karim’s channel.
Who has the diamond play button?
The Red Diamond Play Button at 100 million subscribers, made out of silver-plated metal inset with a large piece of dark red crystal. Currently, T-Series and PewDiePie are the only ones who have received this award.
Who was the first YouTuber to hit 1 million? Milestones and reactions
Channel | Subscriber milestone | Date achieved |
---|---|---|
FЯED | 1 million | April 7, 2009 |
nigahiga | 2 million | March 13, 2010 |
RayWilliamJohnson | 5 million | November 15, 2011 |
Smosh | 10 million | May 25, 2013 |
What was the first ever film?
Roundhay Garden Scene (1888)
The world’s earliest surviving motion-picture film, showing actual consecutive action is called Roundhay Garden Scene. It’s a short film directed by French inventor Louis Le Prince. While it’s just 2.11 seconds long, it is technically a movie.
How long is God of War? When focusing on the main objectives, God of War is about 21 Hours in length. If you’re a gamer that strives to see all aspects of the game, you are likely to spend around 51 Hours to obtain 100% completion.
What is the shortest video game?
The shortest: Bertie the Brain, a tic-tac-toe videogame from 1950: Bertie the Brain – Wikipedia .
What is the longest video ever? The Longest YouTube Video Ever Will Take You 23 Days To Watch. Jonathan Harchick has created and uploaded the longest YouTube video of all time, clocking in at 571 hours, 1 minute and 41 seconds.
-
#1
The BBC, along with the Oxford English Dictionary, is currently showing a weekly series, ‘Balderdash and Piffle’, which is shedding light on the meaning and origins of some very obscure (and not so obscure) English words, idioms, colloquialisms, etc.
Last night’s programme discussed the word ‘set’.
‘Set’ holds the record for being the shortest English word with the most meanings — some unabridged dictionaries give at least 200 meanings.
May I set in motion a discussion about the shortest word, in your own language. which has the most meanings?
On your marks, get set, go!
LRV
-
#2
I’d say the word «get» is the most common.
get sick
get up
get around
get going
get a gift
just to name a few.
-
#3
Hi,
From the top of my head, the first word I thought of in Spanish would be ya
¡Basta ya! — Enough!
Ya lo tengo – I´ve already got it.
¿Estás lista? — ¡Ya! — Are you ready? – Ready!
¡Ya quisiera! – I wish
Ya nomás me falta avisarle a Maria. – I only have to let Maria know. (but this might be a uniquely Mexican expression )
Ya llego. – I´ll be there soon.
Ya – yes
¿Ya? — Ready?
¡Ya se sabrá! — It will be known.
Ya sé que debo hacerlo. I know I´ve got to do it.
I¨m sure I´ll think of some more as soon as I post this. Let´s hope that other Spanish speakers will add more, or suggest another term.
Hasta, ¿ya?
P
-
#4
I know this isn’t exactly on topic but the shortest complete sentence in the English language is «It is»!
blancalaw — the word «get» in all those examples has a similar meaning…I think the topic is about different meaning of the individual word…sorry if you knew that already!
-
#5
Bueno pues, pues nada.
I suggest «pues» for español. Depending on the tone of voice, and the accompanying facial expressions and bodily gestures, it may mean almost anything one wants it to mean.
-
#6
whatonearth said:
I know this isn’t exactly on topic but the shortest complete sentence in the English language is «It is»!
What about «No»? Or «I»?
la reine victoria said:
May I set in motion a discussison about the shortest word, in your own language. which has the most meanings?
This is actually an easy question to answer in Portuguese, because we have a few words made up of just one letter. Looking in a dictionary, it seems to be a tie between a and é. The entry for the former has 8 lines in the dictionary I saw. The latter is an inflected form, so it’s not in the dictionary, but the entry for its infinitive, ser, has 9 lines. The last line, however, describes its use as a noun, which is not possible for é.
-
#7
whatonearth said:
I know this isn’t exactly on topic but the shortest complete sentence in the English language is «It is»!
blancalaw — the word «get» in all those examples has a similar meaning…I think the topic is about different meaning of the individual word…sorry if you knew that already!
Wouldn’t the shortest be «I am.»?!
Now, just to propose a not-so-common but oh-so-common word, I’ll propose «emo». According to urbandictionary.com, it has 697 meanings!
-
#8
Fortunately, in Finnish there are very few words that have several meanings, so its easy to understand and easy translate without misunderstanding. In my opinion it’s really unfortunate that the most popular language of the world, English, is just the opposite. According to the statistics the 500 most common English words have 14,000 different meanings. It’s nearly catastrophal for a translator or anybody who wants to learn English!
-
#9
whatonearth said:
blancalaw — the word «get» in all those examples has a similar meaning…I think the topic is about different meaning of the individual word…sorry if you knew that already!
You may think that they have a similar meaning but for example translating into Finnish I have to use 4 different verbs for those 5 «get».
-
#10
Papalote said:
Hi,
From the top of my head, the first word I thought of in Spanish would be ya
¡Basta ya! — Enough!
Ya lo tengo – I´ve already got it.
¿Estás lista? — ¡Ya! — Are you ready? – Ready!
¡Ya quisiera! – I wish
Ya nomás me falta avisarle a Maria. – I only have to let Maria know. (but this might be a uniquely Mexican expression )
Ya llego. – I´ll be there soon.
Ya – yes
¿Ya? — Ready?
¡Ya se sabrá! — It will be known.Ya sé que debo hacerlo. I know I´ve got to do it.
I¨m sure I´ll think of some more as soon as I post this. Let´s hope that other Spanish speakers will add more, or suggest another term.
Hasta, ¿ya?
P
Otra:
¡ya! = que te crees tú eso, no te lo crees ni tú
-
#12
I think in Spanish it’s por. It has 27 meanings in RAE’s dictionary and it’s a rather conservative dictionary. (Ya: 8, Pues: 9)
-
#13
whatonearth said:
I know this isn’t exactly on topic but the shortest complete sentence in the English language is «It is»!
blancalaw — the word «get» in all those examples has a similar meaning…I think the topic is about different meaning of the individual word…sorry if you knew that already!
whatonearth,
I have to disagree because thinking in Spanish, every expression I mention has a different Spanish word. If you look up get in the Spanish English dictionary, you will see a large page full of various translation. Each translation carries a different meaning of the word «get».
-
#14
balanclaw said:
I have to disagree because thinking in Spanish, every expression I mention has a different Spanish word. If you look up get in the Spanish English dictionary, you will see a large page full of various translation. Each translation carries a different meaning of the word «get».
While I agree that «get» has multiple uses, especially when paired as part of a phrasal verb, in this case, we’re talking about a single word in a single language which carries multiple, distinct definitions.
Per the dictionary I looked in, the word set has a total of fifty separate and distinct definitions. They are divided thusly:
27 definitions as a transitive verb;
8 definitions as an intransitive verb;
6 definitions as an adjective;
9 definitions as a noun.
In addition, set has 15 uses in phrasal verbs, before counting its use in any idiomatic expressions.
As for get, while it also has many definitions, it still falls far behind set. A breakdown of its definitions in parts of speech is as follows:
16 definitions as a transitive verb
5 definitions as an intransitive verb
2 definitions as a noun
No definitions as an adjective
On the other hand, get is used as a part of twenty phrasal verbs, before its use in any idomatic expressions.
-
#15
Well, let’s all get set to declare ¡ya! the winner.
-
#16
I won’t. As I said ya has 8 meanings according to RAE, por has 27.
edit: «de» has 27 meanings + letter D = 28.
PS: English doesn’t make a distinction between transitive and untransitive verbs. Lots of verbs have 2 meanings per se. That + being able to use a word almost freely as verb, adverb, noun, or whatever sums up to a lot of meanings.
-
#17
On ne pourrait pas trouver un mot plus court que «à»!
-
#18
Or at least 697 interpretations of its meaning…I’m not real up on the urban dictionary…seems real loose and more like a discussion that a «dictionary.»
irisheyes0583 said:
Now, just to propose a not-so-common but oh-so-common word, I’ll propose «emo». According to urbandictionary.com, it has 697 meanings!