githubEdit

11. Equalize the Towers

βœ… GFG solution to the Equalize the Towers problem: find minimum cost to make all towers equal height using weighted median optimization technique. πŸš€

The problem can be found at the following link: πŸ”— Question Linkarrow-up-right

🧩 Problem Description

You are given an array heights[] representing the heights of towers and another array cost[] where each element represents the cost of modifying the height of respective tower.

The goal is to make all towers of same height by either adding or removing blocks from each tower. Modifying the height of tower 'i' by 1 unit (add or remove) costs cost[i]. Return the minimum cost to equalize the heights of all the towers.

πŸ“˜ Examples

Example 1

Input: heights[] = [1, 2, 3], cost[] = [10, 100, 1000]
Output: 120
Explanation: The heights can be equalized by either "Removing one block from 3 and adding one in 1" 
or "Adding two blocks in 1 and adding one in 2". Since the cost of operation in tower 3 is 1000, 
the first process would yield 1010 while the second one yields 120.

Example 2

Input: heights[] = [7, 1, 5], cost[] = [1, 1, 1]
Output: 6
Explanation: The minimum cost to equalize the towers is 6, achieved by setting all towers to height 5.

πŸ”’ Constraints

  • $1 \le \text{heights.size()} = \text{cost.size()} \le 10^5$

  • $1 \le \text{heights}[i] \le 10^4$

  • $1 \le \text{cost}[i] \le 10^3$

βœ… My Approach

The optimal approach uses the Weighted Median technique to find the target height that minimizes the total cost:

Weighted Median Optimization

  1. Create Height-Cost Pairs:

    • Combine heights and costs into pairs (height, cost).

    • Sort these pairs by height in ascending order.

  2. Find Weighted Median:

    • Calculate total sum of all costs.

    • Traverse sorted pairs and accumulate costs.

    • When accumulated cost reaches or exceeds half of total cost (total + 1) / 2, that height is the optimal target.

  3. Calculate Minimum Cost:

    • For the target height found, calculate the total cost.

    • Sum up |heights[i] - target| * cost[i] for all towers.

    • This gives the minimum cost to equalize all towers to the target height.

  4. Mathematical Intuition:

    • The weighted median minimizes the sum of weighted absolute deviations.

    • It balances the cost on both sides, ensuring optimal distribution.

πŸ“ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n log n), where n is the number of towers. The sorting step dominates the complexity, followed by a linear scan to find the weighted median and calculate the final cost.

  • Expected Auxiliary Space Complexity: O(n), as we create additional space for storing height-cost pairs in the sorted array. This space is necessary for maintaining the pairing during sorting.

πŸ§‘β€πŸ’» Code (C++)

chevron-right⚑ View Alternative Approaches with Code and Analysishashtag

πŸ“Š 2️⃣ Ternary Search Approach

πŸ’‘ Algorithm Steps:

  1. Define search range as minimum to maximum height in array.

  2. Divide range into three parts using mid1 and mid2 points.

  3. Calculate total cost at both midpoints using cost function.

  4. Eliminate one-third of search space based on cost comparison.

  5. Continue until convergence to find optimal height.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n log(max-min)) - Ternary search iterations with linear cost calculation at each step

  • Auxiliary Space: πŸ’Ύ O(1) - Constant extra space, no additional data structures needed

βœ… Why This Approach?

  • Works on continuous search space efficiently without sorting.

  • No sorting required, preserves original array structure.

  • Standard template for unimodal optimization problems.

  • Excellent for scenarios where sorting overhead is undesirable.

πŸ“Š 3️⃣ Prefix Sum Optimization

πŸ’‘ Algorithm Steps:

  1. Sort heights with their costs maintaining pair association.

  2. Build prefix sums for costs and weighted heights.

  3. For each position, calculate left and right side costs using prefix sums.

  4. Find position with minimum total cost using mathematical formulation.

  5. Update result incrementally as we move to next sorted height.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n log n) - Dominated by sorting operation, followed by linear prefix sum construction and traversal

  • Auxiliary Space: πŸ’Ύ O(n) - Additional arrays for pairs and prefix sums to optimize cost calculation

βœ… Why This Approach?

  • Avoids recalculating entire cost for each candidate height.

  • Uses mathematical optimization with cumulative sums for efficiency.

  • More efficient than brute force for large datasets.

  • Incremental cost updates reduce redundant calculations.

πŸ†š πŸ” Comparison of Approaches

πŸš€ Approach

⏱️ Time Complexity

πŸ’Ύ Space Complexity

βœ… Pros

⚠️ Cons

🏷️ Weighted Median

🟒 O(n log n)

🟑 O(n)

🎯 Direct mathematical solution

πŸ”§ Requires sorting overhead

πŸ” Ternary Search

🟑 O(n log R)

🟒 O(1)

πŸ’Ύ Minimal space usage

⏱️ More iterations, multiple passes

πŸ”„ Prefix Sum

🟒 O(n log n)

🟑 O(n)

⚑ Optimized cost calculation

🧠 Complex implementation logic

πŸ† Best Choice Recommendation

🎯 Scenario

πŸŽ–οΈ Recommended Approach

πŸ”₯ Performance Rating

πŸ… Optimal time complexity

πŸ₯‡ Weighted Median

β˜…β˜…β˜…β˜…β˜…

πŸ“– Memory constrained environments

πŸ₯ˆ Ternary Search

β˜…β˜…β˜…β˜…β˜†

🎯 Production systems, large datasets

πŸ… Prefix Sum

β˜…β˜…β˜…β˜…β˜…

β˜• Code (Java)

🐍 Code (Python)

🧠 Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: πŸ“¬ Any Questions?arrow-up-right. Let's make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


πŸ“Visitor Count

Visitor counter

Last updated