Program to check we can reach leftmost or rightmost position or not in Python


Suppose we have a string containing letters of three types, R, B, and dot(.). Here R stands for our current position, B stands for a blocked position, and dot(.) stands for an empty position. Now, in one step, we can move to any adjacent position to our current position, as long as it is valid (empty). We have to check whether we can reach either the leftmost position or the rightmost position.

So, if the input is like s = "...........R.....BBBB.....", then the output will be True, as R can reach left most position, because there is no block.

To solve this, we will follow these steps −

  • r_pos := index of 'R' in s
  • return True when 'B' is not present in s[from index 0 to r_pos-1] or 'B' not in s[from index r_pos to end]

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, s):
      r_pos = s.find('R')
   return not 'B' in s[:r_pos] or not 'B' in s[r_pos:]
ob = Solution()
s = "...........R.....BBBB....."
print(ob.solve(s))

Input

"...........R.....BBBB....."

Output

True

Updated on: 07-Oct-2020

289 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements