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 find final states of rockets after collision in python
We have a list of numbers representing rocket sizes and directions. Positive integers indicate rightward movement, negative numbers indicate leftward movement. The absolute value represents the rocket's size. When rockets collide, the smaller one is destroyed, and equal-sized rockets both get destroyed.
Problem Understanding
Given rockets moving in opposite directions, we need to simulate collisions and find the final state. Rockets moving in the same direction never collide.
Example
For nums = [3, 8, 5, -5], rockets 5 (right) and -5 (left) collide and both are destroyed, leaving [3, 8].
Algorithm
We'll use a simulation approach with these steps ?
- Initialize a list with the first rocket
- For each subsequent rocket:
- If moving right (positive), add to list
- If moving left (negative), simulate collisions with rightward rockets
- Handle collision outcomes: smaller destroyed, equal-sized both destroyed
Implementation
class Solution:
def solve(self, nums):
if not nums:
return []
ls = [nums[0]]
for i in range(1, len(nums)):
if nums[i] >= 0:
# Rightward rocket, no immediate collision
ls.append(nums[i])
else:
# Leftward rocket, check for collisions
ls.append(nums[i])
j = len(ls) - 2
# Check collisions with rightward rockets
while j >= 0 and ls[j] >= 0:
if abs(ls[-1]) > ls[j]:
# Left rocket destroys right rocket
ls.pop(j)
elif abs(ls[-1]) == ls[j]:
# Both rockets destroyed
ls.pop(j)
ls.pop(-1)
break
else:
# Right rocket destroys left rocket
ls.pop(-1)
break
j -= 1
return ls
# Test the solution
ob = Solution()
nums = [3, 8, 5, -5]
result = ob.solve(nums)
print("Input:", nums)
print("Output:", result)
Input: [3, 8, 5, -5] Output: [3, 8]
Step-by-Step Simulation
Let's trace through the example [3, 8, 5, -5] ?
def solve_with_trace(nums):
print(f"Initial rockets: {nums}")
ls = [nums[0]]
print(f"Step 0: {ls}")
for i in range(1, len(nums)):
current = nums[i]
print(f"\nProcessing rocket {current}")
if current >= 0:
ls.append(current)
print(f"Added rightward rocket: {ls}")
else:
ls.append(current)
j = len(ls) - 2
while j >= 0 and ls[j] >= 0:
left_size = abs(ls[-1])
right_size = ls[j]
if left_size > right_size:
print(f"Left rocket {ls[-1]} destroys right rocket {ls[j]}")
ls.pop(j)
elif left_size == right_size:
print(f"Both rockets {ls[j]} and {ls[-1]} destroyed")
ls.pop(j)
ls.pop(-1)
break
else:
print(f"Right rocket {ls[j]} destroys left rocket {ls[-1]}")
ls.pop(-1)
break
j -= 1
print(f"Current state: {ls}")
return ls
# Trace the example
nums = [3, 8, 5, -5]
result = solve_with_trace(nums)
print(f"\nFinal result: {result}")
Initial rockets: [3, 8, 5, -5] Step 0: [3] Processing rocket 8 Added rightward rocket: [3, 8] Processing rocket 5 Added rightward rocket: [3, 8, 5] Processing rocket -5 Both rockets 5 and -5 destroyed Current state: [3, 8] Final result: [3, 8]
Alternative Test Cases
ob = Solution()
# Test case 1: All moving right
test1 = [2, 4, 6]
print("Test 1:", test1, "?", ob.solve(test1))
# Test case 2: All moving left
test2 = [-2, -4, -6]
print("Test 2:", test2, "?", ob.solve(test2))
# Test case 3: Complex collisions
test3 = [10, 2, -5]
print("Test 3:", test3, "?", ob.solve(test3))
# Test case 4: Multiple collisions
test4 = [8, -8]
print("Test 4:", test4, "?", ob.solve(test4))
Test 1: [2, 4, 6] ? [2, 4, 6] Test 2: [-2, -4, -6] ? [-2, -4, -6] Test 3: [10, 2, -5] ? [10] Test 4: [8, -8] ? []
Conclusion
This solution simulates rocket collisions by processing each rocket sequentially and handling collisions with a stack-like approach. The algorithm efficiently handles all collision scenarios and returns the final surviving rockets.
