Magicsheet logo

Count the Number of Houses at a Certain Distance I

Medium
62.5%
Updated 8/1/2025

Count the Number of Houses at a Certain Distance I

What is this problem about?

The Count the Number of Houses at a Certain Distance I coding problem describes a street with nn houses arranged in a line. Additionally, a shortcut exists between two specific houses xx and yy. For every distance dd from 1 to nn, you need to find how many pairs of houses (i,j)(i, j) have a shortest path distance exactly equal to dd.

Note that the path can follow the linear street or use the shortcut.

Why is this asked in interviews?

Oracle uses this problem to evaluate a candidate's ability to model a scenario as a graph. It tests knowledge of the BFS interview pattern or the shortest path pattern. Since nn is typically small in version I of this problem, it evaluates whether you can correctly identify the "shortcut" edges and run a standard graph algorithm efficiently.

Algorithmic pattern used

This problem is solved using Graph Construction and Breadth-First Search (BFS) (or the Floyd-Warshall algorithm).

  1. Build an adjacency list where each house ii is connected to i1i-1 and i+1i+1.
  2. Add the bidirectional edge (x,y)(x, y).
  3. For each house ii from 1 to nn:
    • Run a BFS to find the shortest distance to all other houses jj.
    • For every j>ij > i, increment the result count for the found distance dist[j].
  4. Output the results for all distances 1n1 \dots n.

Example explanation

n=3n = 3, x=1,y=3x=1, y=3.

  • Edges: (1,2), (2,3), (1,3) (the shortcut).
  • House 1:
    • Dist to 2: 1. (Dist 1 count: 1)
    • Dist to 3: 1 (via shortcut). (Dist 1 count: 2)
  • House 2:
    • Dist to 3: 1. (Dist 1 count: 3)
  • Final: Dist 1 has 3 pairs. Dist 2 has 0. Dist 3 has 0. (Result usually doubled if direction matters, e.g., 6, 0, 0).

Common mistakes candidates make

  • Not using the shortcut: Simply calculating ij|i-j| without checking if the path ioxoyoji o x o y o j is shorter.
  • Redundant work: Running BFS NN times when NN is small is fine, but for very large NN, a more mathematical approach is needed.
  • Directionality: Failing to account for whether the problem asks for unique pairs (i,j)(i, j) where i<ji < j or ordered pairs where (i,j)(i, j) and (j,i)(j, i) are different.

Interview preparation tip

Always visualize "shortcut" problems as adding a single edge to a regular graph (like a line or a ring). Most of the distances will still follow the original pattern, and only those "near" the shortcut will change. This intuition helps in moving from BFS to O(1)O(1) or O(N)O(N) mathematical solutions.

Similar Questions