Find the position of box which occupies the given ball in Python

Given two arrays A and B, where A represents the number of boxes in each row and B contains ball numbers, we need to find the row and column position for each ball. Ball i with value B[i] will be placed in the B[i]-th box when counting from the beginning.

Problem Understanding

Array A defines the grid structure where A[i] is the number of boxes in row i. Array B contains ball numbers, and each ball B[i] goes to the B[i]-th position when boxes are numbered sequentially from 1.

Example

For A = [3, 4, 5, 6] and B = [1, 3, 5, 2]:

  • Row 1 has 3 boxes (positions 1, 2, 3)

  • Row 2 has 4 boxes (positions 4, 5, 6, 7)

  • Row 3 has 5 boxes (positions 8, 9, 10, 11, 12)

  • Row 4 has 6 boxes (positions 13, 14, 15, 16, 17, 18)

Algorithm Steps

  • Convert A to cumulative sum to find position boundaries

  • For each ball B[i], use binary search to find which row it belongs to

  • Calculate column position within that row

Solution

import bisect

def get_position(A, B):
    # Create a copy to avoid modifying original array
    cumulative = A.copy()
    
    # Convert to cumulative sum
    for i in range(1, len(cumulative)):
        cumulative[i] += cumulative[i - 1]
    
    results = []
    
    for ball in B:
        # Find which row this ball belongs to
        row = bisect.bisect_left(cumulative, ball)
        
        # Calculate column position
        if row >= 1:
            box_num = ball - cumulative[row - 1]
        else:
            box_num = ball
        
        results.append((row + 1, box_num))
    
    return results

# Test the function
A = [3, 4, 5, 6]
B = [1, 3, 5, 2]

positions = get_position(A, B)
for pos in positions:
    print(pos)
(1, 1)
(1, 3)
(2, 2)
(1, 2)

How It Works

The algorithm transforms A into a cumulative sum array [3, 7, 12, 18]. Using binary search on this array helps locate which row each ball position falls into. The column is calculated by subtracting the previous cumulative sum from the ball number.

Step-by-Step Trace

  • Ball 1: Falls in row 1 (cumulative[0] = 3 >= 1), column = 1

  • Ball 3: Falls in row 1 (cumulative[0] = 3 >= 3), column = 3

  • Ball 5: Falls in row 2 (cumulative[1] = 7 >= 5), column = 5 - 3 = 2

  • Ball 2: Falls in row 1 (cumulative[0] = 3 >= 2), column = 2

Conclusion

This solution uses cumulative sums and binary search to efficiently find ball positions in O(n log n) time. The bisect module provides the binary search functionality to locate the correct row for each ball.

Updated on: 2026-03-25T09:55:06+05:30

304 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements