Print all words of a sentence having length n in sorted order

Updated

Given a sentence and a integer n(length of word) , :

The task is to print all the words which are having length n in that sentence in sorted order. :

Examples :

Input : sentence ="keep calm and code on"  ;
n=4
Output : calm code keep
Explanation :
Here "keep", "code" ,"calm" are three words which are having length 4
.

Input : sentence ="misha walked and looked around"
n=6
Output : around looked walked

Approach :

  1. Scan the sentence and n.
  2. Store the sentence in list separated by spaces using split() function.
  3. Sort the list using sort() function.
  4. Traverse the list
  5. If the length of word is equal to given length n then print that word

Implementation :

# function to print all words of given length in sorted order
def printSortedWords(lis, n):
    # sorting the list
    lis.sort()
    # traversing the list
    for i in lis:
        # checking if length of word is equal to n
        if(len(i) == n):
            # end is used to print with spaces
            print(i, end=" ")


# function to split the string
def splitString(string, n):
        # split() the string and store in list
    lis = list(string.split())
    # passing list and given number to printSortedWords function
    printSortedWords(lis, n)


# Driver code
n = 4
string = "keep calm and code on"
splitString(string, n)

Output :

calm code keep

Time Complexity : O(n)

Comment
Mithlesh Upadhyay Published 28 Nov 2026 · 2 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials