Microsoft | Sort words in a string
Anonymous User
1338

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.

  1. Find the number of words in the string

  2. start index i from number of words to 0

  3. 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:

  1. reverse the individual words
  2. reverse the substring from start of first word to end of second word.

Time-complexity : O(N^2)

Similar problems: Matches that of pan-cake sorting. Leetcode 969

Is there any better way to do it?

Comments (2)