Skip to main content
Back to problems
#3015
Medium Algorithms

Count the number of houses at a certain distance i

Breadth-First Search Graph Theory Prefix Sum
57.3% acceptance
Feb 25, 2026
209
45
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.

Solution

Rust
Time O(n * m)
Space O(n * m)
LeetCode
solution.rs
impl Solution {
  pub fn count_of_pairs(n: i32, x: i32, y: i32) -> Vec<i32> {
    let n = n as usize;
    let x = x as usize - 1;
    let y = y as usize - 1;
    let mut dist = vec![vec![i32::MAX; n]; n];
    for i in 0..n { dist[i][i] = 0; }
    for i in 0..n-1 { dist[i][i+1] = 1; dist[i+1][i] = 1; }
    dist[x][y] = 1; dist[y][x] = 1;
    // Floyd-Warshall
    for k in 0..n {
      for i in 0..n {
        for j in 0..n {
          if dist[i][k] != i32::MAX && dist[k][j] != i32::MAX {
            dist[i][j] = dist[i][j].min(dist[i][k] + dist[k][j]);
          }
        }
      }
    }
    let mut res = vec![0i32; n];
    for i in 0..n {
      for j in 0..n {
        if i != j && dist[i][j] > 0 { res[dist[i][j] as usize - 1] += 1; }
      }
    }
    res
  }
}