#3017

Count the Number of Houses at a Certain Distance II

Hard
Graph TheoryPrefix SumGraph TheoryPrefix Sum
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach leverages the structure of the problem and the properties of distances in a linear graph. We can calculate the number of pairs at each distance more efficiently without checking every pair.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a result array of size n with all zeros.
  2. 2Step 2: Calculate the total pairs for distance k without the additional street: result[k] = 2 * (n - k).
  3. 3Step 3: Adjust the counts for the special case of the additional street between x and y.
solution.py8 lines
1def countHouses(n, x, y):
2    result = [0] * n
3    for k in range(1, n + 1):
4        result[k - 1] = 2 * (n - k)
5    if abs(x - y) <= n:
6        distance = abs(x - y)
7        result[distance - 1] -= 2
8    return result

Complexity note: The time complexity is O(n) because we only loop through the distances once. The space complexity is O(n) due to the result array.

  • 1Understanding the structure of the graph helps to optimize the solution.
  • 2Counting pairs based on distance rather than checking each pair directly saves time.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.