Final state of the string after modification in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string S. The length is n. These n boxes adjacent to each other, a character R at position i represents that i-th box is being pushed towards right. similarly, L at position i represents that i-th box is being pushed towards left, a dot '.' indicates an empty space. Starting from initial configuration, at every time unit, a box being pushed to the right side is able to push next box to right, same action can be applied for the left side also. We have to find the final positions of all boxes when no more movements are feasible.

So, if the input is like R..R...L., then the output will be RRRRR.LL.

To solve this, we will follow these steps −

  • N := size of string
  • movement := array of size N, fill with 0s
  • m := 0
  • for i in range 0 to N, do
    • if string[i] is same as 'R', then
      • m := N
    • otherwise when string[i] is same as 'L', then
      • m := 0
    • otherwise,
      • m := maximum of m - 1, 0
    • movement[i] := movement[i] + m
  • m := 0
  • for i in range N - 1 to -1, decrease by 1, do
    • if string[i] is same as 'L', then
      • m := N
    • otherwise when string[i] is same as 'R', then
      • m := 0
    • otherwise,
      • m := maximum of m - 1, 0
    • movement[i] := movement[i] - m
  • return make a string by adding dot if m is 0 otherwise 'R' when m > 0, otherwise 'L' for every element m in movement.

Example Code

Let us see the following implementation to get better understanding −

 Live Demo

def get_final_pos(string):
   N = len(string)
   movement = [0] * N
   m = 0
   for i in range(0, N):
      if string[i] == 'R':
         m = N
      elif string[i] == 'L':
         m = 0
      else:
         m = max(m - 1, 0)
      movement[i] += m
   m = 0
   for i in range(N - 1, -1, -1):
      if string[i] == 'L':
         m = N
      elif string[i] == 'R':
         m = 0
      else:
         m = max(m - 1, 0)
      movement[i] -= m
return "".join('.' if m == 0 else 'R' if m > 0 else 'L' for m in movement)
print(get_final_pos('R..R...L.'))

Input

'R..R...L.'

Output

RRRRR.LL.
raja
Published on 23-Jul-2020 11:50:22
Advertisements