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
}
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. Given the following Python code for assigning cookies to children, what is the final returned value when g = [1, 2, 3] and s = [1, 1]?
easy
A. 0
B. 1
C. 2
D. 3

Solution

  1. Step 1: Trace first iteration

    g and s sorted: g=[1,2,3], s=[1,1]. i=0, j=0, count=0. s[0]=1 ≥ g[0]=1 -> count=1, i=1, j=1.
  2. Step 2: Trace second iteration

    i=1, j=1, count=1. s[1]=1 < g[1]=2 -> j=2. Loop ends as j=2 equals len(s).
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Only one cookie satisfies a child's greed [OK]
Hint: Trace pointer increments carefully [OK]
Common Mistakes:
  • Counting cookies not sufficient for greed
  • Off-by-one in loop conditions
  • Ignoring pointer increments
2. Consider the following code snippet for the Jump Game problem. What is the value of maxReach after the third iteration (i = 2) when the input is [2, 3, 1, 1, 4]?
def canJump(nums):
    maxReach = 0
    for i, jump in enumerate(nums):
        if i > maxReach:
            return False
        maxReach = max(maxReach, i + jump)
        if maxReach >= len(nums) - 1:
            return True
    return False
easy
A. 3
B. 4
C. 5
D. 2

Solution

  1. Step 1: Trace maxReach updates for each iteration

    i=0: maxReach = max(0, 0+2) = 2 i=1: maxReach = max(2, 1+3) = 4 i=2: maxReach = max(4, 2+1) = 4
  2. Step 2: Identify maxReach after i=2

    After third iteration (i=2), maxReach remains 4.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    maxReach does not decrease; it stays at 4 after i=2 [OK]
Hint: maxReach never decreases, track max(i+jump) [OK]
Common Mistakes:
  • Off-by-one in iteration count
  • Confusing maxReach update with i only
3. Consider the following buggy code for the Gas Station problem. Which line contains the subtle bug that can cause incorrect results?
def canCompleteCircuit(gas, cost):
    n = len(gas)
    net = [gas[i] - cost[i] for i in range(n)]
    # Bug: missing total gas check
    prefix = [0] * (2 * n + 1)
    for i in range(2 * n):
        prefix[i+1] = prefix[i] + net[i % n]
    for i in range(n):
        if prefix[i+n] - prefix[i] >= 0:
            return i
    return -1
medium
A. Line 3: net array computation
B. Line 4: missing total gas vs total cost check
C. Line 6: prefix sums computation loop
D. Line 8: checking prefix sums for valid start

Solution

  1. Step 1: Identify missing total gas check

    The code does not check if sum(net) < 0 before proceeding, which can cause incorrect start index or false positives.
  2. Step 2: Verify other lines

    Net array, prefix sums, and prefix difference checks are correct and standard.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Missing total gas check leads to incorrect results [OK]
Hint: Always check total gas >= total cost before searching start [OK]
Common Mistakes:
  • Forgetting total gas check
  • Misusing modulo in prefix sums
  • Resetting start without resetting tank
4. Suppose the problem changes: you can reuse indices multiple times (cycles allowed). Which modification to the BFS approach ensures correct minimum jumps without infinite loops?
hard
A. Remove the visited set to allow revisiting indices for better paths.
B. Keep the visited set but reset it after each BFS level to allow revisits in next level.
C. Keep the visited set as is to prevent revisiting and infinite loops.
D. Use a distance array to track minimum jumps to each index and update it if a shorter path is found.

Solution

  1. Step 1: Understand cycles and revisits

    Allowing reuse means indices can be revisited, so visited set alone blocks better paths.
  2. Step 2: Use distance array for shortest paths

    Tracking minimum jumps per index and updating when a shorter path is found prevents infinite loops and finds optimal jumps.
  3. Step 3: Why other options fail

    Removing visited causes infinite loops; resetting visited loses pruning; keeping visited blocks revisits.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    Distance array with updates handles cycles correctly [OK]
Hint: Distance array needed when revisits allowed [OK]
Common Mistakes:
  • Removing visited set causing infinite loops
  • Resetting visited incorrectly
  • Assuming original BFS works unchanged
5. Suppose the problem is modified so that characters can be reused unlimited times (infinite supply), and you want to generate a string of length n with no two adjacent characters the same. Which modification to the max heap approach is necessary to handle this variant correctly?
hard
A. No change needed; the original heap approach works as is for infinite reuse
B. Track only the last used character and pick any other character from the set for the next position
C. Use a queue instead of a heap to cycle through characters ensuring no adjacency
D. Remove frequency counts and always push characters back immediately after use to allow reuse

Solution

  1. Step 1: Understand infinite reuse implication

    Since characters can be reused infinitely, frequency counts are irrelevant; characters must be available again immediately after use.
  2. Step 2: Modify heap usage

    Remove frequency decrement logic and always push characters back immediately after use to allow reuse while avoiding adjacency.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Immediate pushback enables infinite reuse without adjacency violation [OK]
Hint: Infinite reuse means no frequency decrement [OK]
Common Mistakes:
  • Assuming original approach works unchanged
  • Using queue without frequency logic
  • Ignoring adjacency constraints