I was asked this question in the screening round at Microsoft Hyderabad.
Given a string of words, sort the words in lexicographical order in place.
Ex: "I love leetcode"
Ans: "I leetcode love"
Approach:
Following approach was taken by me which is a variant of bubblesort.
Find the number of words in the string
start index i from number of words to 0
start index j from 0 to i
a. At every step compare the jth word with j+1th word. if they are equal or less continue to next iteration. Otherwise swap two words in-place
For swapping two words in place, use the following algo:
Time-complexity : O(N^2)
Similar problems: Matches that of pan-cake sorting. Leetcode 969
Is there any better way to do it?