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 get final position of moving animals when they stops in Python
Suppose we have a string s representing the initial positions of animals in a line. Each character represents an animal's movement direction: L indicates the animal moves left, R indicates the animal moves right, and @ indicates the animal is standing still. Moving animals will influence other animals in their path unless they encounter a force from the opposite direction, which causes them to stop. We need to find the final orientation of each animal when all movement stops.
Problem Understanding
The algorithm uses a level-based approach where animals spread their influence outward. Animals moving in opposite directions meeting at the same time will neutralize each other and become stationary (@).
Example
If the input is s = "@@L@R@@@@L", the output will be "LLL@RRRLLL".
Algorithm Steps
The solution follows these steps:
Initialize tracking arrays: Create a levels array to track when each position is reached and a queue for breadth-first processing
Add initial moving animals: Find all
LandRcharacters and add them to the queue with level 0Simulate movement: Process animals level by level, spreading their influence to adjacent positions
Handle collisions: When two animals reach the same position at the same time with different directions, they neutralize each other
Implementation
from collections import deque
class Solution:
def solve(self, s):
levels = [-1 for i in s]
q = deque()
# Add initial moving animals to queue
for idx in range(len(s)):
if s[idx] == "R" or s[idx] == "L":
q.append((idx, 0, s[idx]))
animals = list(s)
# Process animals level by level
while q:
idx, new_level, direction = q.popleft()
if levels[idx] == -1:
# First time reaching this position
levels[idx] = new_level
animals[idx] = direction
# Spread influence to adjacent positions
if direction == "R" and idx + 1 < len(animals):
q.append((idx + 1, new_level + 1, direction))
elif direction == "L" and idx - 1 >= 0:
q.append((idx - 1, new_level + 1, direction))
elif levels[idx] == new_level:
# Same level collision - check for opposite directions
if animals[idx] != direction:
animals[idx] = "@"
return "".join(animals)
# Test the solution
solution = Solution()
s = "@@L@R@@@@L"
result = solution.solve(s)
print(f"Input: {s}")
print(f"Output: {result}")
Input: @@L@R@@@@L Output: LLL@RRRLLL
How It Works
The algorithm uses a breadth-first search approach where each "level" represents one time step. Moving animals influence adjacent positions in the next time step. When animals moving in opposite directions meet at the same position during the same time step, they cancel each other out and become stationary (@).
Time Complexity
The time complexity is O(n) where n is the length of the input string, as each position is visited at most once. The space complexity is also O(n) for the levels array and queue storage.
Conclusion
This level-based simulation effectively models animal movement and collisions using a breadth-first approach. The key insight is that animals meeting at the same time step with opposite directions neutralize each other, while others continue spreading their influence.
