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 II INPUT 1 2 3 4 5 extra street n = 5 x = 2 y = 4 5 houses, street 2--4 creates a cycle Find pairs at each distance k (1 to n) ALGORITHM STEPS 1 Identify Cycle x=2, y=4 forms cycle of length 3 (2-3-4-2) 2 Count Direct Paths Adjacent pairs: n-1 = 4 Each at distance 1 3 Apply Shortcut 2--4 shortcut reduces some distances by 1 4 Sum All Pairs Use formula for each k Count pairs x 2 Distance Pairs Count k=1: (1,2)(2,3)(3,4)(4,5)(2,4) k=2: (1,3)(3,5)(2,5)(1,4) k=3: (1,5) k=4,5: none Each pair counted x2 FINAL RESULT Pairs at each distance k: k=1 10 k=2 8 k=3 2 k=4 0 k=5 0 Output: [10, 8, 2, 0, 0] Breakdown: 5 pairs at dist 1 x 2 = 10 4 pairs at dist 2 x 2 = 8 1 pair at dist 3 x 2 = 2 0 pairs at dist 4 or 5 Total pairs: C(5,2) = 10 Sum: 10+8+2+0+0 = 20 = 10 pairs x 2 [OK] Key Insight: The extra edge x--y creates a cycle, providing shortcuts between some house pairs. For each pair, the shortest path is min(direct_path, path_through_shortcut). Mathematical formulas allow O(1) calculation for each distance k, avoiding O(n^2) enumeration of all pairs. TutorialsPoint - Count the Number of Houses at a Certain Distance II | Mathematical Formula Approach
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