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
Find the minimum sum of distance to A and B from any integer point in a ring of size N in Python
We need to find the minimum sum of distances from any integer point X to two given points A and B on a ring of size N. The goal is to position X such that the total distance (distance from X to A + distance from X to B) is minimized, where X cannot be the same as A or B.
In a ring structure, we can move in two directions: clockwise and counter-clockwise. The optimal position for X will depend on which path gives us the minimum total distance.
Example Walkthrough
If N = 30, A = 10, B = 20, then by selecting X = 15:
Distance from X to A = 5
Distance from X to B = 5
Total distance = 5 + 5 = 10
Algorithm
To solve this problem, we follow these steps:
If a > b, swap a and b to ensure a ? b
Calculate clockwise distance: b - a
Calculate counter-clockwise distance: (a - 1) + (n - b + 1)
Find the minimum of both distances
If minimum distance is 1, return 3 (special case handling)
Otherwise, return the minimum distance
Implementation
def get_min_z(n, a, b):
if (a > b):
a, b = b, a
clock_wise_dist = b - a
counter_clock_wise_dist = (a - 1) + (n - b + 1)
minimum_dist = min(clock_wise_dist, counter_clock_wise_dist)
if (minimum_dist == 1):
return 3
return minimum_dist
# Test case
n = 30
a = 10
b = 20
result = get_min_z(n, a, b)
print(f"Minimum distance sum: {result}")
Minimum distance sum: 10
How It Works
The algorithm considers both possible paths around the ring:
| Path Type | Distance Calculation | Description |
|---|---|---|
| Clockwise | b - a | Direct distance between A and B |
| Counter-clockwise | (a - 1) + (n - b + 1) | Distance going around the other way |
The special case where minimum_dist == 1 returns 3 because when A and B are adjacent, the optimal position X would be at distance 1 from both, but since X cannot be at A or B, we need to place it at distance 2 from one and distance 1 from the other, giving a total of 3.
Additional Example
# Test with different values
test_cases = [
(10, 2, 8),
(15, 3, 12),
(8, 1, 2)
]
for n, a, b in test_cases:
result = get_min_z(n, a, b)
print(f"N={n}, A={a}, B={b} ? Minimum sum: {result}")
N=10, A=2, B=8 ? Minimum sum: 4 N=15, A=3, B=12 ? Minimum sum: 6 N=8, A=1, B=2 ? Minimum sum: 3
Conclusion
This algorithm efficiently finds the minimum sum of distances by comparing clockwise and counter-clockwise paths around the ring. The time complexity is O(1) and space complexity is O(1), making it an optimal solution for this problem.
