Count the Number of Houses at a Certain Distance I - Problem
You are given a city with n houses numbered from 1 to n, connected by streets forming a linear chain. Each house
Your task is to count how many pairs of houses have each possible shortest distance from 1 to n streets. For each distance
Goal: Return an array where
Example: With houses 1-2-3 and shortcut 1โ3, the shortest path from house 1 to 3 is 1 street (using shortcut) instead of 2 streets (via house 2).
i is connected to house i+1. Additionally, there's a special shortcut street connecting house x to house y.Your task is to count how many pairs of houses have each possible shortest distance from 1 to n streets. For each distance
k, find the number of house pairs (house1, house2) where the minimum streets needed to travel from house1 to house2 is exactly k.Goal: Return an array where
result[k] represents the total number of house pairs with shortest distance k.Example: With houses 1-2-3 and shortcut 1โ3, the shortest path from house 1 to 3 is 1 street (using shortcut) instead of 2 streets (via house 2).
Input & Output
example_1.py โ Basic Linear Chain with Shortcut
$
Input:
n = 3, x = 1, y = 3
โบ
Output:
[4, 2, 0]
๐ก Note:
Houses: 1-2-3 with shortcut 1โ3. Distance 1: (1,2), (2,1), (1,3), (3,1) = 4 pairs. Distance 2: (2,3), (3,2) = 2 pairs. Distance 3: none = 0 pairs.
example_2.py โ No Shortcut Effect
$
Input:
n = 5, x = 2, y = 4
โบ
Output:
[8, 6, 4, 2]
๐ก Note:
Houses: 1-2-3-4-5 with shortcut 2โ4. The shortcut creates new shortest paths, changing the distance distribution compared to a simple linear arrangement.
example_3.py โ Self-Loop Edge Case
$
Input:
n = 4, x = 2, y = 2
โบ
Output:
[6, 4, 2]
๐ก Note:
When x equals y, the shortcut has no effect. This becomes a simple linear chain: 1-2-3-4. Distance counts follow the standard linear pattern.
Visualization
Tap to expand
Understanding the Visualization
1
Linear City Setup
Houses 1-2-3-4-5 connected in a chain with shortcut 2โ4
2
Without Shortcut
Distance from 2 to 4 would be 2 steps (2โ3โ4)
3
With Shortcut
Distance from 2 to 4 becomes 1 step (2โ4 directly)
4
Count All Pairs
BFS from each house reveals all shortest distances for counting
Key Takeaway
๐ฏ Key Insight: BFS efficiently finds shortest paths in unweighted graphs, and running it from each house gives us the complete distance distribution needed to solve this counting problem.
Time & Space Complexity
Time Complexity
O(nยฒ)
We run BFS from each of the n houses, and each BFS takes O(n) time to visit all houses
โ Quadratic Growth
Space Complexity
O(n)
We need space for the adjacency list and BFS queue, plus the result array
โก Linearithmic Space
Constraints
- 1 โค n โค 100
- 1 โค x, y โค n
- x and y can be equal (shortcut has no effect)
- Return array is 1-indexed where result[k] = count of pairs with distance k
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code