Two Furthest Houses With Different Colors - Problem
Two Furthest Houses With Different Colors

Imagine walking down a beautiful street lined with n colorfully painted houses. Each house has been painted with a specific color, and you want to find the maximum distance between any two houses that have different colors.

You are given a 0-indexed integer array colors of length n, where colors[i] represents the color of the i-th house.

Goal: Return the maximum distance between two houses with different colors.

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

Example: If we have houses with colors [1, 1, 1, 6, 1, 1, 1], the maximum distance would be between house 0 (color 1) and house 3 (color 6), giving us a distance of abs(0 - 3) = 3.

Input & Output

example_1.py โ€” Basic Case
$ Input: [1,1,1,6,1,1,1]
โ€บ Output: 3
๐Ÿ’ก Note: The houses at indices 0 and 3 have different colors (1 and 6). The distance is abs(0 - 3) = 3. This is the maximum distance possible.
example_2.py โ€” Multiple Colors
$ Input: [1,8,3,8,3]
โ€บ Output: 4
๐Ÿ’ก Note: The houses at indices 0 and 4 have different colors (1 and 3). The distance is abs(0 - 4) = 4. This gives us the maximum distance.
example_3.py โ€” Alternating Colors
$ Input: [0,1]
โ€บ Output: 1
๐Ÿ’ก Note: The houses at indices 0 and 1 have different colors (0 and 1). The distance is abs(0 - 1) = 1.

Constraints

  • 2 โ‰ค n โ‰ค 100
  • 0 โ‰ค colors[i] โ‰ค 100
  • At least two houses have different colors

Visualization

Tap to expand
House 0Color: 1House 1Color: 1House 2Color: 8House 3Color: 3House 4Color: 7House 5Color: 1Maximum Distance: 4๐Ÿ“ธ Start๐Ÿ“ธ Best ShotPhotographer's Dream ShotMaximum contrast achieved!
Understanding the Visualization
1
Survey the Street
Look at all the colorfully painted houses lined up
2
Key Insight
The maximum distance must include either the first or last house
3
Check Both Ends
Find the furthest different colored house from each end
4
Take the Best Shot
Choose the maximum distance for the most dramatic photo
Key Takeaway
๐ŸŽฏ Key Insight: The maximum distance between houses with different colors must always include either the first house (leftmost) or the last house (rightmost) as one of the endpoints. This allows us to solve the problem efficiently in O(n) time!
Asked in
Google 12 Amazon 8 Meta 6 Microsoft 4
28.5K Views
Medium Frequency
~12 min Avg. Time
920 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