Reputation: 3403
Is sorting the letters in a string by the order they occur doable in linear time?
For instance, boyhood
would sort to boooyhd
.
Upvotes: 0
Views: 226
Reputation: 2280
Yes, here is an O(2n) solution in python:
import sys
word = raw_input("Enter string to sort:")
wordDict = {}
for letter in word:
if letter in wordDict:
wordDict[letter] = wordDict[letter] + 1
else:
wordDict[letter] = 1
for letter in word:
sys.stdout.write(letter*wordDict[letter])
wordDict[letter] = 0
Upvotes: 1