Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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. 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 the leftmost position because there is no block between R and the left edge.
Algorithm
To solve this, we will follow these steps ?
- Find the index position of 'R' in the string
- Check if there are no 'B' characters between the start and R position (can reach left)
- Check if there are no 'B' characters between R position and the end (can reach right)
- Return True if either condition is satisfied
Example
Let us see the following implementation to get better understanding ?
class Solution:
def solve(self, s):
r_pos = s.find('R')
# Check if we can reach leftmost OR rightmost position
return 'B' not in s[:r_pos] or 'B' not in s[r_pos:]
# Test the solution
ob = Solution()
s = "...........R.....BBBB....."
print(ob.solve(s))
True
How It Works
The solution works by checking two conditions:
-
Left reachability:
'B' not in s[:r_pos]checks if there are no blocked positions between the start and R -
Right reachability:
'B' not in s[r_pos:]checks if there are no blocked positions from R to the end
If either condition is true, we can reach at least one edge, so the function returns True.
Additional Examples
class Solution:
def solve(self, s):
r_pos = s.find('R')
return 'B' not in s[:r_pos] or 'B' not in s[r_pos:]
ob = Solution()
# Test case 1: Can reach both sides
print("Test 1:", ob.solve("....R...."))
# Test case 2: Can only reach right side
print("Test 2:", ob.solve("BB..R...."))
# Test case 3: Cannot reach either side
print("Test 3:", ob.solve("BB.R.BB"))
# Test case 4: Can only reach left side
print("Test 4:", ob.solve("....R..BB"))
Test 1: True Test 2: True Test 3: False Test 4: True
Conclusion
This solution efficiently checks reachability in O(n) time by using string slicing and the in operator. The key insight is that we only need to reach either the leftmost or rightmost position, not both.
