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 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 returnb + 1If
a + b >= n, then returnn - 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 haveb + 1positions (from having 0 to b people behind us).Case 2: When
a + b >= n, the constraints overlap, limiting us ton - apositions.
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.
