Program to find out the position of a ball after n reversals in Python

Suppose there are n balls arranged in positions 1, 2, 3, 4, ..., n. These balls undergo a series of reversals where each reversal starts from a different position, moving one step to the right each time. We need to find the final position of a ball that was initially at a given index.

Understanding the Problem

Let's trace through an example with 5 balls and find where the ball at index 2 ends up ?

Initial arrangement: 1, 2, 3, 4, 5

Reversal operations:

  • Reverse from position 0 to 4: 5, 4, 3, 2, 1
  • Reverse from position 1 to 4: 5, 1, 2, 3, 4
  • Reverse from position 2 to 4: 5, 1, 4, 3, 2
  • Reverse from position 3 to 4: 5, 1, 4, 2, 3

The ball originally at index 2 (value 3) is now at position 4.

Algorithm

After analyzing the pattern, we can determine the final position using a simple formula ?

  • If index < balls // 2, then final position = 2 * index + 1
  • Otherwise, final position = 2 * (balls - index - 1)

Implementation

def solve(balls, index):
    if index < balls // 2:
        return 2 * index + 1
    else:
        return 2 * (balls - index - 1)

# Test with the example
balls = 5
index = 2
result = solve(balls, index)
print(f"Ball initially at index {index} is now at position: {result}")
Ball initially at index 2 is now at position: 4

Testing with Multiple Examples

def solve(balls, index):
    if index < balls // 2:
        return 2 * index + 1
    else:
        return 2 * (balls - index - 1)

# Test cases
test_cases = [(5, 0), (5, 1), (5, 2), (5, 3), (5, 4)]

for balls, index in test_cases:
    result = solve(balls, index)
    print(f"Balls: {balls}, Index: {index} ? Final position: {result}")
Balls: 5, Index: 0 ? Final position: 1
Balls: 5, Index: 1 ? Final position: 3
Balls: 5, Index: 2 ? Final position: 4
Balls: 5, Index: 3 ? Final position: 2
Balls: 5, Index: 4 ? Final position: 0

How It Works

The algorithm exploits the mathematical pattern that emerges after all reversals. The key insight is that balls in the first half of the array follow one formula, while balls in the second half follow another. This eliminates the need to simulate all the reversal operations.

Conclusion

The ball position problem can be solved efficiently using a mathematical formula based on whether the initial index is in the first or second half of the array. This approach has O(1) time complexity compared to simulating all reversals.

---
Updated on: 2026-03-26T18:18:18+05:30

326 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements