Lexicographically smallest string that can be created after an unlimited number of moves (Difficulty : Easy)

Rohan Krishna Ullas
1 min readFeb 25, 2021

Problem Statement : You are given a string of length N and a parameter k. The string can be manipulated by taking one of the first k letters and moving it to the end.

Write a program to determine the lexicographically smallest string that can be created after an unlimited number of moves.

For example, suppose we are given the string daily and k = 1. The best we can create in this case is ailyd.

Here, we are only interested in the final string as result and not in the number of moves it takes. So after a checking a bunch of test cases we can identify that whenever k>1 the result is always the lexicographically smallest string that can be created from all the characters in the input string!

This can be found by simply sorting the string. And for the case when k=1,

We can check all possible rotations of the string one by one (takes O(n) time) and see which is the lexicographically smallest string.

--

--

Rohan Krishna Ullas

Caught in an endless loop of building and breaking stuff 😄 SDE-1 @ Microsoft