Program to check whether string Is transformable with substring sort operations in Python

PythonServer Side ProgrammingProgramming

Suppose we have two numeric strings s and t, we want to transform from string s to t using the following operation any number of times: 1. Select a non-empty substring in s and sort it inplace so the characters are in ascending order. We have to check whether it is possible to transform string s into string t or not.

So, if the input is like s = "95643" t = "45963", then the output will be True because we can transform s into t using like "95643" -> "95463" -> "45963".

To solve this, we will follow these steps −

  • places := a map where default value type is list

  • for i in range size of s down to 0, do

    • key := s[i] as integer

    • insert i at the end of places[key]

  • for each e in t, do

    • key := e as integer

      • if places[key] is empty, then

        • return False

      • i := last element of places[key]

      • for j in range 0 to key - 1, do

        • if places[j] is non-empty and last element of places[j] < i, then

          • return False

      • delete last element from places[key]

  • return True

Example

Let us see the following implementation to get better understanding

from collections import defaultdict
def solve(s, t):
   places = defaultdict(list)
   for i in reversed(range(len(s))):
      key = int(s[i])
      places[key].append(i)

   for e in t:
      key = int(e)
      if not places[key]:
         return False
      i = places[key][-1]
      for j in range(key):
         if places[j] and places[j][-1] < i:
            return False
      places[key].pop()
   return True

s = "95643"
t = "45963"
print(solve(s, t))

Input

"95643", "45963"

Output

True
raja
Updated on 06-Oct-2021 09:36:07

Advertisements