Similar Problems

Similar Problems not available

Using A Robot To Print The Lexicographically Smallest String - Leetcode Solution

Companies:

LeetCode:  Using A Robot To Print The Lexicographically Smallest String Leetcode Solution

Difficulty: Medium

Topics: greedy hash-table stack string  

Problem:

Given two strings S and T, determine the lexicographically smallest string that can be formed by appending any number of the characters of T to the end of S.

Example: Input: S = "bat", T = "cat" Output: "batcat"

Solution:

One approach to solve this problem is to use a robot to print the lexicographically smallest string. The robot starts at the beginning of the S string and keeps moving forward until it reaches the end of the S string. At each step, the robot checks if it is possible to append any character of T to the current string formed by the robot, while still maintaining the lexicographically smallest order. If it is not possible, the robot stops and returns the final string formed.

Algorithm:

  1. Initialize a string variable 'result' to store the string formed by the robot
  2. Create two integer variables, 'i' and 'j', to keep track of the current indices for S and T respectively
  3. While 'i' is less than the length of S and 'j' is less than the length of T, do the following: a. Compare the character at index 'i' of S with the character at index 'j' of T b. If the character at index 'i' of S is lexicographically smaller than the character at index 'j' of T, append the character at index 'i' of S to 'result' and increment 'i' c. If the character at index 'i' of S is lexicographically larger than the character at index 'j' of T, append the character at index 'j' of T to 'result' and increment 'j' d. If the characters are equal, compare the remaining characters in S and T to decide which one to append. If all remaining characters of S are lexicographically smaller than T, append all characters of S to 'result' and stop. Otherwise, append the next character of T to 'result' and increment 'j'
  4. Append the remaining characters of T to 'result', if any
  5. Return the final string formed

Code in Python:

def lexSmallestString(S: str, T: str) -> str: result = "" i, j = 0, 0 while i < len(S) and j < len(T): if S[i] < T[j]: result += S[i] i += 1 elif S[i] > T[j]: result += T[j] j += 1 else: k = i l = j while k < len(S) and l < len(T) and S[k] == T[l]: k += 1 l += 1 if k == len(S) or (l < len(T) and T[l] < S[k]): result += T[j] j += 1 else: result += S[i] i += 1 return result + T[j:]

Using A Robot To Print The Lexicographically Smallest String Solution Code

1