# Count The Number Of Houses At A Certain Distance II: Interview Notes

Count The Number Of Houses At A Certain Distance II shows up often in coding rounds. Here is how I talk through it when the interviewer is watching.

## Key idea

n houses on a line plus one extra edge (x,y). Count pairs at each distance 1..n-1. Without the extra edge, distance is |i-j|. The extra edge creates a shortcut: for each pair take min(|i-j|, |i-x|+1+|j-y|, |i-y|+1+|j-x|). Do it in O(n) with prefix/difference arrays rather than O(n^2).

## Steps to say out loud

1. Restate the input and the exact ask, and nail down constraints and overflow.
2. Name the pattern (binary search on the answer, monotonic stack or deque, interval / interval-DP, string hashing, graph traversal, or shortest paths) and why a nested scan or naive search fails.
3. Code it, then trace a short example plus one empty or already-solved edge case.

## Complexity

O(n).

## Common mistake

Running APSP or looping every pair when n is 1e5.

## Practice tip

Time yourself: two minutes to explain, ten to code, three to test edges. Disclosure: I work on Linkjob AI. I also keep a practice cheat sheet at undetectable AI interview copilot.