Edit: Because i wansn't clear i'm just gonna copy the question (my answer is the code).
Given a string obtain the alphabetically smallest string possible by swapping either adjacent 'a' and 'b' characters or adjacent 'b' and 'c' character any number of times .
Example: s = "abaacbac" The alphabetically smallest possible string is obtained by applying the following operations:
'c' ad index 5 is swapped with 'b' ad index 6 so "abaacbac" becomes "abaabcac".
Then 'b' at index 2 is swapped with 'a' at index 3 so 'abaabcac' becomes "aababac".
Finally 'b' at index 3 is swapped with 'a' at index 4 to obtain the final answer "aaabbcac".
Another example: input baacba output aabbca
here is my code
def smallestString(s):
# Write your code here
cons = 10 ** 5
if len(s) > cons:
return False
s = list(s)
counter = 0
while counter < len(s):
for i in range(len(s)):
if i + 1 < len(s):
if s[i] == "b" and s[i + 1] == "a":
s[i], s[i + 1] = s[i + 1], s[i]
elif s[i] == "a" and s[i + 1] == "b" and "c" in s[:i]:
s[i + 1], s[i] = s[i], s[i + 1]
elif s[i] == "c" and s[i + 1] == "b":
s[i], s[i + 1] = s[i + 1], s[i]
counter += 1
return ''.join(s)
Is there anyway i optimize my code so it will work for very large input (max 10 seconds or it times out). ps any suggestion for different approach/modification will be good also