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 :)

    Reply Delete
    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

    Reply Delete
    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

Quasi FSM (Finite State Machine) problem + Vibe

Not really an FSM problem since the state isn't changing, it is just defined by the current input. Simply following the instructions should do it. Using VSCode IDE you can also engage the help of Cline or Copilot for a combo of coding and vibe coding, see below screenshot. Cheers, ACC. Process String with Special Operations I - LeetCode You are given a string  s  consisting of lowercase English letters and the special characters:  * ,  # , and  % . Build a new string  result  by processing  s  according to the following rules from left to right: If the letter is a  lowercase  English letter append it to  result . A  '*'   removes  the last character from  result , if it exists. A  '#'   duplicates  the current  result  and  appends  it to itself. A  '%'   reverses  the current  result . Return the final string  result  after processing all char...

Shortest Bridge – A BFS Story (with a Twist)

Here's another one from the Google 30 Days challenge on LeetCode — 934. Shortest Bridge . The goal? Given a 2D binary grid where two islands (groups of 1s) are separated by water (0s), flip the fewest number of 0s to 1s to connect them. Easy to describe. Sneaky to implement well. 🧭 My Approach My solution follows a two-phase Breadth-First Search (BFS) strategy: Find and mark one island : I start by scanning the grid until I find the first 1 , then use BFS to mark all connected land cells as 2 . I store their positions for later use. Bridge-building BFS : For each cell in the marked island, I run a BFS looking for the second island. Each BFS stops as soon as it hits a cell with value 1 . The minimum distance across all these searches gives the shortest bridge. πŸ” Code Snippet Here's the core logic simplified: public int ShortestBridge(int[][] grid) { // 1. Mark one island as '2' and gather its coordinates List<int> island = FindAndMark...

Classic Dynamic Programming IX

A bit of vibe code together with OpenAI O3. I asked O3 to just generate the sieve due to laziness. Sieve is used to calculate the first M primes (when I was using Miller-Rabin, was giving me TLE). The DP follows from that in a straightforward way: calculate the numbers from i..n-1, then n follows by calculating the min over all M primes. Notice that I made use of Goldbach's Conjecture as a way to optimize the code too. Goldbach's Conjecture estates that any even number greater than 2 is the sum of 2 primes. The conjecture is applied in the highlighted line. Cheers, ACC. PS: the prompt for the sieve was the following, again using Open AI O3 Advanced Reasoning: " give me a sieve to find the first M prime numbers in C#. The code should produce a List<int> with the first M primes " Minimum Number of Primes to Sum to Target - LeetCode You are given two integers  n  and  m . You have to select a multiset of  prime numbers  from the  first   m  pri...