Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python program to sort Palindrome Words in a Sentence

  • Difficulty Level : Medium
  • Last Updated : 01 Apr, 2021

Given a string S representing a sentence, the task is to reorder all the palindromic words present in the sentence in sorted order.


Input: S = “Please refer to the madam to know the level”
Output: Please level to the madam to know the refer
Explanation: Here “refer”, “madam”, “level” are the palindromic words. Sorting them generates the sequence {“level”, “madam”, “refer”}.

Input: S = “refer to dad”
Output: dad to refer

Approach: Follow the steps below to solve the problem:

Below is the implementation of the above approach:


# Python implementation of above program
# Function to check if a
# string is a palindrome or not
def palindrome(string):
    if(string == string[::-1]):
        return True
        return False
# Function to print the updated sentence
def printSortedPalindromes(sentence):
    # Stores palindromic words
    newlist = []
    # Stores the words split by spaces
    lis = list(sentence.split())
    # Traversing the list
    for i in lis:
        # If current word is palindrome
            # Update newlist
    # Sort the words in newlist
    # Pointer to iterate newlis
    j = 0
    # Traverse the list
    for i in range(len(lis)):
        # If current word is palindrome
            # Replacing word with
            # current word in newlist
            lis[i] = newlist[j]
            # Increment j by 1
            j = j + 1
    # Print the updated sentence
    for i in lis:
        print(i, end =" ")
# Driver Code
sentence = "please refer to the madam to know the level"
please level to the madam to know the refer

Time Complexity : O(N * logN)
Auxiliary Space : O(N)

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!