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
Final state of the string after modification in Python
This problem simulates boxes being pushed in different directions until they reach a stable final state. Given a string where 'R' represents a box pushed right, 'L' represents a box pushed left, and '.' represents empty space, we need to find the final configuration after all movements stop.
Problem Understanding
Each box marked 'R' pushes subsequent boxes to the right, while boxes marked 'L' push preceding boxes to the left. The simulation continues until no more movement is possible ?
Algorithm Approach
We use a two-pass algorithm to calculate the net force on each position ?
- First pass (left to right): Calculate rightward forces from 'R' positions
- Second pass (right to left): Calculate leftward forces from 'L' positions
- Final step: Determine the final state based on net force at each position
Implementation
def get_final_pos(string):
N = len(string)
movement = [0] * N
m = 0
# First pass: left to right (rightward forces)
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
# Second pass: right to left (leftward forces)
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
# Generate final configuration
return "".join('.' if m == 0 else 'R' if m > 0 else 'L' for m in movement)
# Test the function
result = get_final_pos('R..R...L.')
print(result)
RRRRR.LL.
How It Works
The algorithm tracks the movement force at each position ?
| Character | Action | Effect |
|---|---|---|
| 'R' | Set force to N (maximum) | Strong rightward push |
| 'L' | Set force to 0 or N | Blocks/creates leftward push |
| '.' | Decrease force by 1 | Force weakens with distance |
Step-by-Step Example
For input 'R..R...L.' ?
Initial: R . . R . . . L . Left-right: 9 8 7 9 8 7 6 0 0 Right-left: 0 0 0 0 1 2 3 9 8 Net force: 9 8 7 9 7 5 3-9-8 Final: R R R R R . L L .
Alternative Example
# Test with different configurations
test_cases = [
"RR.L", # Two R's pushing toward one L
"..R..L..", # R and L with gaps
"R.......L", # R and L far apart
]
for test in test_cases:
result = get_final_pos(test)
print(f"'{test}' ? '{result}'")
'RR.L' ? 'RRLL' '..R..L..' ? '..RR.L..' 'R.......L' ? 'RRRR.LLLL'
Conclusion
This two-pass algorithm efficiently simulates box movements by calculating net forces. The time complexity is O(n) and space complexity is O(n), making it optimal for this problem.
