Program to find number of possible position in n-person line with few person at front and back in Python

Suppose we have three numbers n, a and b. Consider we are in a line of n people, and we are unaware about our position in the line. But we know there are at least a number of people in front of us and at most b number of people behind us. We have to find the number of possible positions for us.

So, if the input is like n = 10, a = 3, b = 4, then the output will be 5. There are 10 people in the line with at least 3 people in front and at most 4 people behind us. We can be at positions 4, 5, 6, 7, or 8 (using 1-based indexing), giving us 5 possible positions.

Logic

To solve this, we follow these steps ?

  • If a + b < n, then return b + 1

  • If a + b >= n, then return n - a

Example

Let us see the following implementation to get better understanding ?

def solve(n, a, b):
    if a + b < n:
        return b + 1
    if a + b >= n:
        return n - a

n = 10
a = 3
b = 4
print(solve(n, a, b))

The output of the above code is ?

5

How It Works

The algorithm considers two cases:

  • Case 1: When a + b < n, we have enough space for all constraints, so we can have b + 1 positions (from having 0 to b people behind us).

  • Case 2: When a + b >= n, the constraints overlap, limiting us to n - a positions.

Another Example

Let's test with different values ?

def solve(n, a, b):
    if a + b < n:
        return b + 1
    if a + b >= n:
        return n - a

# Test case 1: a + b < n
print("Test 1:", solve(15, 3, 5))  # Should return 6

# Test case 2: a + b >= n  
print("Test 2:", solve(8, 4, 6))   # Should return 4
Test 1: 6
Test 2: 4

Conclusion

This problem uses simple arithmetic to count valid positions based on constraints. The key insight is handling two cases: when constraints don't overlap versus when they do overlap in the line.

Updated on: 2026-03-26T15:17:06+05:30

219 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements