Two Furthest Houses With Different Colors - Problem

There are n houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array colors of length n, where colors[i] represents the color of the ith house.

Return the maximum distance between two houses with different colors.

The distance between the ith and jth houses is abs(i - j), where abs(x) is the absolute value of x.

Input & Output

Example 1 — Basic Case
$ Input: colors = [1,1,1,6,1,1,1]
Output: 3
💡 Note: The house at index 3 has color 6, which differs from houses at indices 0 and 6 (both color 1). Distance from index 0 to 3 is |0-3| = 3, and from index 6 to 3 is |6-3| = 3. Maximum distance is 3.
Example 2 — Different Colors at Ends
$ Input: colors = [1,8,3,8,3]
Output: 4
💡 Note: House at index 0 (color 1) and house at index 4 (color 3) have different colors. The distance is |0-4| = 4, which is the maximum possible.
Example 3 — Minimum Length
$ Input: colors = [0,1]
Output: 1
💡 Note: Only two houses with different colors (0 and 1). Distance between indices 0 and 1 is |0-1| = 1.

Constraints

  • 2 ≤ colors.length ≤ 100
  • 0 ≤ colors[i] ≤ 100
  • Test cases are generated such that at least two houses have different colors.

Visualization

Tap to expand
Two Furthest Houses With Different Colors INPUT i=0 c=1 i=1 c=1 i=2 c=1 i=3 c=6 i=4 c=1 i=5 c=1 i=6 c=1 colors array: [1, 1, 1, 6, 1, 1, 1] n = 7 houses Color 1 Color 6 ALGORITHM STEPS 1 Check first house Compare colors[0] with colors[n-1] to colors[1] 2 Check last house Compare colors[n-1] with colors[0] to colors[n-2] 3 Find first different Stop when color differs Distance = |i - j| 4 Return maximum max(dist1, dist2) Greedy Check: From i=0: colors[0]=1 colors[6]=1 (same) colors[3]=6 (diff!) d=3 From i=6: colors[0]=1 (diff!) d=6 FINAL RESULT i = 0 Color 1 i = 3 Color 6 Distance = 3 OUTPUT 3 max(|0-3|, |6-3|) = max(3, 3) = 3 OK Key Insight: The maximum distance must involve either the first house (index 0) or the last house (index n-1). We greedily check from both ends: find the furthest house with different color from index 0, and the furthest from index n-1. Return the maximum of these two distances. Time: O(n), Space: O(1) TutorialsPoint - Two Furthest Houses With Different Colors | Greedy Optimization
Asked in
Google 15 Microsoft 12
25.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen