Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python program to find the smallest word in a sentence

  • Difficulty Level : Basic
  • Last Updated : 16 Feb, 2021

Given a string S of lowercase English alphabets, the task is to print the smallest word in the given string.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: S = “sky is blue”
Output: “is”
Explanation:  
Length of “sky” is 3.
Length of is “is” 2.
Length of “blue” is 4.
Therefore, the smallest word is “is”.



Input: S = “geeks for geeks”
Output: “for”

Searching-based Approach: Refer to this article to solve this problem by performing the following steps:

  • Iterate over the characters of the string.
  • Check if the current character encountered is a space or end of the string is reached.
  • If the current character is found to be so, update the maximum length of a word obtained.
  • Finally, print the longest word obtained using substr() method.

Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(1)

Approach using sorted() method: The idea is to split the words of the string into a list and sort the list in increasing order of length of words using the sorted() method. Finally, print the first string present in the list.

Below is the implementation of the above approach:

Python3




# Python3 program for the above approach
  
# Function to print the
# smallest word in the string s
  
  
def smallestWord(s):
  
    # Using sorted() method
    s = sorted(s, key = len)
  
    # Print first word
    print(s[0])
  
  
# Driver Code
if __name__ == "__main__":
  
    # Given string
    s = "sky is blue"
  
    # Convert string to list
    l = list(s.split(" "))
  
    smallestWord(l)
Output:
is

Time Complexity: O(N * LogN)
Auxiliary Space: O(1)




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!