Why This Problem Is Interesting
At first glance, this looks like a basic array problem.
But hereβs the twist:
π If you try solving it βnormally,β youβll overthink it.
π If you observe patterns, it becomes one of the easiest O(n) problems.
This is exactly the kind of question interviewers use to test:
- Do you brute force blindly?
- Or do you see patterns in constraints?
π Problem Link
https://leetcode.com/problems/two-furthest-houses-with-different-colors/
π§© Problem Breakdown (Understand Like a Beginner)
You are given:
Each index = house
Each value = color
You need to:
π Pick two houses with different colors
π Maximize the distance between them
Distance formula:
π§ First Thought (What Most People Do)
βLet me check all pairsβ¦β
Yes, it works. Butβ¦
π Thatβs O(nΒ²)
π Completely unnecessary for n β€ 100? Maybe fine
π But logically inefficient
π‘ Approach 1: Brute Force (Baseline Thinking)
π» Code
β± Time Complexity (Why O(nΒ²)?)
- Outer loop β runs n times
- Inner loop β runs n times
π Total = n * n = O(nΒ²)
β Why This Is Wasteful
You are:
- Checking close houses (useless)
- When the answer depends on far houses
π‘ Key Turning Point (Where Real Thinking Starts)
Ask yourself:
π βTo maximize |i - j|, what do I need?β
Answer:
π Make i and j as far apart as possible
That means:
- i should be near 0
- j should be near n-1
π₯ Critical Observation
π The answer will always involve either:
- First house (index 0), OR
- Last house (index n-1)
Why?
Because they give maximum possible distance
π’ Approach 2: Two Direction Scan
Now your idea makes perfect sense:
Step 1
Fix first element β find farthest different color
Step 2
Fix last element β find farthest different color
π» Your Code
π Dry Run (Deep Understanding)
Input:
πΉ First Loop (Fix index 0)
Compare:
π max1 = 3
πΉ Second Loop (Fix last index)
Compare:
π max2 = 3
β Final Answer:
β± Time Complexity (Why O(n)?)
- First loop β O(n)
- Second loop β O(n)
π Total = O(n) + O(n) = O(n)
π’ Approach 3: Cleaner Optimization (Best Version)
We can compress both loops into one:
π» Code
π Why This Works (Core Insight)
We only check:
- Distance from start
- Distance from end
Because:
π Any maximum distance pair must include one endpoint
This avoids:
- Redundant comparisons
- Nested loops
π§ Mental Model (Remember This)
Instead of thinking:
β βCheck all pairsβ
Think:
β βWhere can maximum distance even exist?β
π― Final Takeaways
- Always question brute force
- Distance problems β think endpoints first
- Constraints often hide optimizations
- Observations > Code




