899. Orderly Queue

899. Orderly Queue

ยท

3 min read

Hello, reader ๐Ÿ‘‹๐Ÿฝ ! Welcome to day 36 of the series on Problem Solving. Through this series, I aim to pick up at least one question everyday and share my approach for solving it.

Today, I will be picking up LeetCode's daily challenge problem: 899. Orderly Queue.


๐Ÿค” Problem Statement

  • Given a string s and an integer k, return the lexicographically smallest string that can be formed by choosing one of the first k letters of s and appending it at the end of the string.
  • The first k letters of s can be appended to the end of the string any number of times.

  • E.g.:

    • s = "cba", k = 1 => acb
    • s = "baaca", k = 3 => aabca

๐Ÿ’ฌ Thought Process - Sorting

  • When you manually try to form the lexicographically smallest string from the given examples, you'll be able to understand after a few iterations that this problem is divided into two sub-problems:
    1. When k = 1
    2. When k > 1
  • When k = 1, the solution is straightforward, we try to keep appending the 1st character to the end of string and check if it forms the lexicographically smallest string.
  • When k > 2, we can see that the string formed is actually the sorted string.

  • Hence, that's what we'll do. When k = 1, we will keep appending the first character to the end of the string and find the smallest string. When k > 1, we will return the sorted string.

  • Below image depicts two different moves to get the lexicographically smallest string for: s = "baaca", k = 2. baaca_k2.png

๐Ÿ‘ฉ๐Ÿฝโ€๐Ÿ’ป Solution - Sorting

class Solution {
    public String orderlyQueue(String s, int k) {
        if(k == 0) {
            return s;
        }

        if(k == 1) {
            String ans = s;
            int n = s.length();

            for(int i = 1; i<n; i++) {
                String moveFirstToBack = s.substring(i) + s.substring(0,i);
                if(moveFirstToBack.compareTo(ans) < 0) {
                    ans = moveFirstToBack;
                }
            }

            return ans;
        }

        char[] sArr = s.toCharArray();
        Arrays.sort(sArr);

        return new String(sArr);
    }
}
Time Complexity: O(N ^ 2)
  N = length of string
Space Complexity: O(N)
  N = length of string
      - when k = 1, we use extra space to form strings by chars appending to the end and when k > 1, use char array to sort.


Conclusion

That's a wrap for today's problem. If you liked my explanation then please do drop a like/ comment. Also, please correct me if I've made any mistakes or if you want me to improve something!

Thank you for reading!