Count the Number of Houses at a Certain Distance II - Problem

You are given three positive integers n, x, and y. In a city, there exist houses numbered 1 to n connected by n streets.

There is a street connecting the house numbered i with the house numbered i + 1 for all 1 <= i <= n - 1. An additional street connects the house numbered x with the house numbered y.

For each k, such that 1 <= k <= n, you need to find the number of pairs of houses (house1, house2) such that the minimum number of streets that need to be traveled to reach house2 from house1 is k.

Return a 1-indexed array result of length n where result[k] represents the total number of pairs of houses such that the minimum streets required to reach one house from the other is k.

Note that x and y can be equal.

Input & Output

Example 1 — Basic Case
$ Input: n = 5, x = 2, y = 4
Output: [10,8,2,0,0]
💡 Note: With shortcut between houses 2 and 4, some pairs use linear path while others use the shortcut. Distance 1: 10 pairs, Distance 2: 8 pairs, Distance 3: 2 pairs.
Example 2 — No Shortcut Effect
$ Input: n = 4, x = 1, y = 1
Output: [6,4,2,0]
💡 Note: Since x = y, there's no actual shortcut. All distances are linear: 1→6 pairs, 2→4 pairs, 3→2 pairs.
Example 3 — Adjacent Shortcut
$ Input: n = 3, x = 1, y = 2
Output: [4,2,0]
💡 Note: Shortcut between adjacent houses doesn't change distances. Distance 1: 4 pairs, Distance 2: 2 pairs.

Constraints

  • 3 ≤ n ≤ 105
  • 1 ≤ x, y ≤ n

Visualization

Tap to expand
Count Houses at Distance: Input → Process → Output12345Input: n=5, x=2, y=4Distance 1:(1,2), (2,3), (3,4), (4,5)+ reverse= 8 pairsDistance 2:(1,3), (2,4), (3,5)+ reverse= 6 pairsDistance 3:(1,4), (1,5), (2,5)+ reverse= 6 pairsOutput: [10, 8, 2, 0, 0]
Understanding the Visualization
1
Input
Houses 1-n with linear connections plus shortcut x↔y
2
Process
Calculate shortest distance for each pair of houses
3
Output
Array where result[k] = number of pairs at distance k
Key Takeaway
🎯 Key Insight: The shortcut creates alternative paths - count pairs by their minimum distance using either linear or shortcut route
Asked in
Google 15 Meta 12 Amazon 10
12.0K Views
Medium Frequency
~25 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen