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
Understanding the Visualization
1
Input
Array of house colors with indices
2
Process
Find pairs with different colors and calculate distances
3
Output
Maximum distance between any two different colored houses
Key Takeaway
🎯 Key Insight: Maximum distance is most likely between houses at opposite ends of the street
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code