pythonstringoptimization

Finding the minimum length word in a given string


Here's the problem statement from a coding platform -

Given a string S (that can contain multiple words), you need to find the word which has minimum length. Note : If multiple words are of same length, then answer will be first minimum length word in the string. Words are separated by single space only. Constraints : 1 <= Length of String S <= 10^5

I am aware of an efficient solution, but this is what I tried in my first attempt -

string = input().strip()
n=len(string)
words=string.split()
dic={}
for word in words:
    dic[word]=len(word)
word=""
if n!=0:
    mini = len(words[0])
    word=words[0]
    for wordss in dic:
        if (dic[wordss]<mini):
            word = wordss
            mini = dic[wordss]
print(word)

The problem is that it passes only 2 of the 5 test cases, which are hidden (not available to me). I am not really sure about the problem with this approach. What kind of edge cases am I missing out?


Solution

  • Why bother with a dictionary at all? You can just find the minimum as you go along.

    string = input().strip()
    minlen = len( string ) + 1
    bestword = ""
    for word in string.split():
        L = len( word )
        if L < minlen:
            minlen = L
            bestword = word
    print( bestword )
    

    Example:

    Three blind mice see how they run
    see