Bird
Raised Fist0
Interview Prepgreedy-algorithmsmediumAmazonGoogle

Minimum Cost to Connect Sticks

Choose your preparation mode4 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
📋
Problem

Imagine you have several wooden sticks and want to connect them all into one stick. Each time you connect two sticks, it costs you the sum of their lengths. How do you minimize the total cost?

Given an array of integers sticks where sticks[i] is the length of the i-th stick, you can connect any two sticks of lengths x and y into one stick by paying a cost of x + y. The new stick length is also x + y. Return the minimum cost to connect all the sticks into one stick.

1 ≤ sticks.length ≤ 10^51 ≤ sticks[i] ≤ 10^4
Edge cases: Single stick [5] → cost 0 because no connections neededAll sticks equal length [1,1,1,1] → cost accumulates merging smallest pairsLarge number of sticks with minimum length [1,1,...,1] → tests efficiency
</>
IDE
def min_cost_connect_sticks(sticks: list[int]) -> int:public int minCostConnectSticks(int[] sticks)int minCostConnectSticks(vector<int> &sticks)function minCostConnectSticks(sticks)
def min_cost_connect_sticks(sticks: list[int]) -> int:
    # Write your solution here
    pass
class Solution {
    public int minCostConnectSticks(int[] sticks) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int minCostConnectSticks(vector<int> &sticks) {
    // Write your solution here
    return 0;
}
function minCostConnectSticks(sticks) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: Wrong total cost higher than expectedMerging sticks in arbitrary order instead of always merging the two smallest sticks first.Use a min-heap to repeatedly merge the two smallest sticks and accumulate cost.
Wrong: Non-zero cost for single stick inputMissing base case for single stick where no merges are needed.Return 0 immediately if sticks length is 1.
Wrong: TLE or timeout on large inputUsing brute force or repeated sorting instead of min-heap approach.Implement min-heap based greedy algorithm with O(n log n) complexity.
Wrong: Incorrect cost due to merging largest sticks firstGreedy trap merging largest sticks first instead of smallest.Always merge the two smallest sticks using a min-heap.
Wrong: Incorrect cost due to unbounded merges or off-by-one errorsConfusing 0/1 merge problem with unbounded merges or incorrect loop conditions.Merge exactly two sticks at a time until only one stick remains, using a min-heap.
Test Cases
t1_01basic
Input{"sticks":[9]}
Expected14

Connect sticks 2 and 3 for cost 5, then connect 5 and 4 for cost 9, total cost = 5 + 9 = 14.

t1_02basic
Input{"sticks":[17]}
Expected30

Merge 1+3=4(cost 4), then 4+5=9(cost 9), then 9+8=17(cost 17), total cost = 4+9+17=30.

t2_01edge
Input{"sticks":[5]}
Expected0

Only one stick, no merges needed, cost is 0.

t2_02edge
Input{"sticks":[4]}
Expected8

Merge 1+1=2(cost 2), merge 1+1=2(cost 2), merge 2+2=4(cost 4), total cost = 2+2+4=8.

t2_03edge
Input{"sticks":[30]}
Expected30

Only two sticks, merge once with cost 10+20=30.

t3_01corner
Input{"sticks":[22]}
Expected47

Merge 1+2=3(cost 3), merge 3+5=8(cost 8), merge 6+8=14(cost 14), merge 14+8=22(cost 22), total cost = 3+8+14+22=47 (recalculate carefully).

t3_02corner
Input{"sticks":[15]}
Expected33

Merge 1+2=3(cost 3), merge 3+3=6(cost 6), merge 4+5=9(cost 9), merge 6+9=15(cost 15), total cost = 3+6+9+15=33.

t3_03corner
Input{"sticks":[9]}
Expected21

Merge 1+2=3(cost 3), merge 2+2=4(cost 4), merge 3+4=7(cost 7), merge 7+2=9(cost 9), total cost = 3+4+7+9=23 (recalculate carefully).

t4_01performance
Input{"sticks":[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]}
⏱ Performance - must finish in 2000ms

n=100 sticks all length 1, O(n log n) min-heap approach must complete within 2 seconds.

Practice

(1/5)
1. Consider the following code snippet implementing the peak-valley approach to maximize stock profit. What is the final returned profit when the input prices are [1, 2, 3]?
def maxProfit(prices):
    i = 0
    profit = 0
    n = len(prices)
    while i < n - 1:
        while i < n - 1 and prices[i] >= prices[i + 1]:
            i += 1
        valley = prices[i]
        while i < n - 1 and prices[i] <= prices[i + 1]:
            i += 1
        peak = prices[i]
        profit += peak - valley
    return profit
easy
A. 2
B. 0
C. 3
D. 1

Solution

  1. Step 1: Trace first while loop to find valley

    i=0, prices[0]=1, prices[1]=2, 1 < 2 so inner loop skips, valley=1
  2. Step 2: Trace second while loop to find peak

    i increments while prices[i] <= prices[i+1]: i=0 to 1 (2 <= 3), i=1 to 2 (3 no next), peak=3
  3. Step 3: Calculate profit and return

    profit += 3 - 1 = 2, loop ends, return 2
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Profit matches sum of positive differences (2) [OK]
Hint: Sum of (3-1) = 2 profit [OK]
Common Mistakes:
  • Off-by-one error missing last peak
  • Confusing valley and peak assignments
  • Returning zero if no decreasing sequence found
2. You have a list of tasks represented by characters, each task takes 1 unit of time to execute. The CPU must wait for at least n units of time before executing the same task again. Which approach guarantees the minimum total time to finish all tasks?
easy
A. Dynamic Programming that tries all permutations of task orders to find the minimal schedule
B. Greedy algorithm using a max-heap to always schedule the most frequent available task next
C. Simple round-robin scheduling without considering cooldown intervals
D. Sorting tasks by frequency and inserting idle slots greedily without priority queue

Solution

  1. Step 1: Understand the cooldown constraint

    The CPU must wait n units before repeating the same task, so scheduling must consider task frequencies and cooldowns.
  2. Step 2: Why max-heap greedy works best

    Using a max-heap prioritizes tasks with the highest remaining frequency, ensuring minimal idle time by always picking the most urgent task available.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Max-heap approach matches known optimal solution [OK]
Hint: Max-heap greedily schedules highest frequency tasks first [OK]
Common Mistakes:
  • Assuming DP or brute force is needed
  • Ignoring cooldown leads to incorrect minimal time
  • Greedy without priority queue misses optimal order
3. The following code attempts to solve the Jump Game problem. Identify the line that contains a subtle bug that causes incorrect results on some inputs.
def canJump(nums):
    maxReach = 0
    for i, jump in enumerate(nums):
        # Bug: missing check if current index is beyond maxReach
        maxReach = max(maxReach, i + jump)
        if maxReach >= len(nums) - 1:
            return True
    return False
medium
A. Line 2: Initialization of maxReach
B. Line 3: for loop header enumerating nums
C. Line 4: Missing check if i > maxReach before updating maxReach
D. Line 6: Checking if maxReach reaches or exceeds last index

Solution

  1. Step 1: Understand the missing condition

    The code does not check if the current index i is beyond maxReach, which means it may continue even when stuck.
  2. Step 2: Identify the bug line

    Line 4 updates maxReach without verifying if i is reachable, causing false positives on inputs with unreachable indices.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Adding "if i > maxReach: return False" fixes the bug [OK]
Hint: Check if current index is reachable before updating maxReach [OK]
Common Mistakes:
  • Forgetting to check i > maxReach
  • Assuming maxReach update alone suffices
4. Suppose the problem is modified so that the input list can contain negative integers as well. Which of the following approaches correctly adapts the algorithm to handle negatives and still produce the largest concatenated number?
hard
A. Convert negatives to positive strings before sorting with the comparator, then prepend '-' to those in final output
B. Filter out negative numbers since they cannot contribute to the largest concatenation
C. Separate negatives and positives, sort positives with comparator, sort negatives by absolute value descending, then concatenate positives followed by negatives
D. Convert all numbers to strings including negatives, then sort with the same comparator comparing concatenations

Solution

  1. Step 1: Recognize negatives affect ordering and concatenation semantics

    Negative numbers cannot be treated the same as positives because concatenation with '-' changes lex order.
  2. Step 2: Separate positives and negatives, sort positives with original comparator, sort negatives by absolute value descending

    Concatenate positives first (largest number), then negatives to maintain largest overall concatenation.
  3. Step 3: This approach preserves ordering logic and handles negatives correctly

    Other options either ignore negatives or mishandle signs causing incorrect results.
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    Separating and sorting by sign handles negatives correctly [OK]
Hint: Negatives require separate handling, not just string comparison [OK]
Common Mistakes:
  • Treating negatives as strings directly
  • Ignoring negatives
  • Converting negatives to positives incorrectly
5. Suppose now you can reuse boxes infinitely (unlimited supply of each box type). Which modification to the algorithm correctly computes the maximum units that can be loaded on the truck?
hard
A. Use dynamic programming to consider all combinations of boxes up to truckSize, since greedy no longer works
B. Use the same greedy approach but do not reduce truckSize after picking boxes, since supply is unlimited
C. Sort boxTypes by units per box descending and fill the truck entirely with the box type having the highest units per box
D. Sort boxTypes ascending by units per box and pick boxes until truckSize is full

Solution

  1. Step 1: Understand unlimited supply impact

    With infinite boxes, the best strategy is to fill the truck entirely with the box type having the highest units per box.
  2. Step 2: Identify correct algorithm

    Sorting descending by units per box and taking all truckSize boxes from the top box type yields maximum units efficiently.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Greedy fill with highest unit box type maximizes units [OK]
Hint: With infinite supply, pick only highest unit box type [OK]
Common Mistakes:
  • Not reducing truckSize leading to infinite loop
  • Using DP unnecessarily
  • Sorting ascending which is suboptimal