Custom Sort String: Modified BubbleSort

Problem is here (#416th in my solved list): https://leetcode.com/problems/custom-sort-string/

S and T are strings composed of lowercase letters. In S, no letter occurs more than once.
S was sorted in some custom order previously. We want to permute the characters of T so that they match the order that Swas sorted. More specifically, if x occurs before y in S, then x should occur before y in the returned string.
Return any permutation of T (as a string) that satisfies this property.
Example :
Input: 
S = "cba"
T = "abcd"
Output: "cbad"
Explanation: 
"a", "b", "c" appear in S, so the order of "a", "b", "c" should be "c", "b", and "a". 
Since "d" does not appear in S, it can be at any position in T. "dcba", "cdba", "cbda" are also valid outputs.

Note:
  • S has length at most 26, and no character is repeated in S.
  • T has length at most 200.
  • S and T consist of lowercase letters only.
Here is the approach I used: the heart of the solution will be a modified BubbleSort (BubbleSort should work fine here given the small input size). First add all the elements of S to a hash table to indicate the position of each letter. Next, copy the letters in T to a StringBuilder (since you'll need to manipulate it) but do it in a way that you copy to the front the letters that appear in S, and to the back the letters that do not appear in S. Do not worry about the order of letters at this point, just split these two sets (set 1: in S. Set 2: not in S). Then perform a standard BubbleSort but when comparing the elements, reference the hash table to see which one is larger. That's about it. Code is below, cheers, ACC.


public class Solution
{
    public string CustomSortString(string S, string T)
    {
        Hashtable order = new Hashtable();

        for (int i = 0; i < S.Length; i++)
        {
            order.Add(S[i], S.Length - i);
        }

        StringBuilder sb = new StringBuilder(T);

        int left = 0;
        int right = T.Length - 1;
        for (int i = 0; i < T.Length; i++)
        {
            if (order.ContainsKey(T[i]))
            {
                sb[left++] = T[i];
            }
            else
            {
                sb[right--] = T[i];
            }
        }

        bool sorted = false;
        while (!sorted)
        {
            sorted = true;
            for (int i = 0; i < T.Length - 1; i++)
            {
                if (order.ContainsKey(sb[i]) && order.ContainsKey(sb[i + 1]) && (int)order[sb[i]] < (int)order[sb[i + 1]])
                {
                    char temp = sb[i];
                    sb[i] = sb[i + 1];
                    sb[i + 1] = temp;
                    sorted = false;
                }
            }
        }

        return sb.ToString();
    }
}

Comments

  1. Since S has at most 26 chars I didn't even bother to build an index and perform "slow" searches:

    class Solution:
    def customSortString(self, S: str, T: str) -> str:
    return "".join(sorted(T, key=lambda char: S.find(char)))

    And we've got a one-liner :)

    ReplyDelete
    Replies
    1. actually this can be made shorter:

      class Solution:
      def customSortString(self, S: str, T: str) -> str:
      return "".join(sorted(T, key=S.find))

      Delete
  2. Missed you, my friend!!! Solid as always, I missed the fact that |S| <= 26, which simplifies things a lot indeed

    ReplyDelete
    Replies
    1. there was some problem with blogger that was preventing me from commenting, but now looks like things are back to normal, so be ready for my spam ) The fact that we have such a small alphabet also can be leveraged to build a very efficient array based index.

      Thanks for your solutions! Looking forward for the next one!

      Delete

Post a Comment

Popular posts from this blog

Advent of Code - Day 6, 2024: BFS and FSM

Golang vs. C#: performance characteristics (simple case study)

Advent of Code - Day 7, 2024: Backtracking and Eval