#3015
Count the Number of Houses at a Certain Distance I
MediumBreadth-First SearchGraph TheoryPrefix SumGraph TheoryBreadth-First Search
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
In the optimal approach, we can leverage the structure of the problem and the properties of distances in a linear arrangement of houses. We can count pairs directly based on their distances without checking each pair.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a result array of size n with all zeros.
- 2Step 2: Calculate the number of pairs for distance 1, which includes all adjacent houses and the special connection between x and y.
- 3Step 3: For distances greater than 1, calculate pairs based on the distance formula and the total number of houses.
solution.py16 lines
1# Full working Python code
2
3def countHouses(n, x, y):
4 result = [0] * n
5 # Count pairs for distance 1
6 result[0] = (n - 1) * 2 # All adjacent pairs + (x, y) and (y, x) if they are adjacent
7 if abs(x - y) == 1:
8 result[0] += 2
9 # Count pairs for distance 2 and more
10 for k in range(2, n + 1):
11 if k <= n:
12 result[k - 1] = (n - k) * 2
13 return result
14
15# Example usage
16print(countHouses(3, 1, 3)) # Output: [6, 0, 0]ℹ
Complexity note: The time complexity is O(n) because we iterate through the houses a limited number of times. The space complexity is O(n) due to the result array.
- 1Understanding the structure of the problem allows for more efficient counting of pairs.
- 2Utilizing properties of distances in a linear arrangement can simplify calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.