Bird
Raised Fist0
Interview Prepmodified-binary-searchmediumAmazonGoogle

Capacity to Ship Packages

Choose your preparation mode4 modes available
▶
Steps
setup

Initialize Search Space

Set left to the maximum single package weight (10) and right to the sum of all weights (55). This defines the initial search space for ship capacity.

💡 The minimum capacity must be at least the heaviest package, and at most the sum of all packages if shipped in one day.
Line:left, right = max(weights), sum(weights)
💡 Establishes the bounds for binary searching the minimum feasible capacity.
📊
Capacity to Ship Packages - Watch the Algorithm Execute, Step by Step
Watching each step shows how the search space shrinks and why certain capacities are feasible or not, making the binary search on answer space intuitive.
Step 1/17
·Active fill★Answer cell
1
0
2
1
3
2
4
3
5
4
6
5
7
6
8
7
9
8
10
9
Next: lo=10 hi=55
Target: 32
1
0
2
1
3
2
4
3
5
4
6
5
7
6
8
7
9
8
10
9
Next: lo=10 hi=55
Target: 32
1
0
2
1
3
2
4
3
5
4
6
5
7
6
8
7
9
8
10
9
Next: lo=10 hi=32
Target: 32
1
0
2
1
3
2
4
3
5
4
6
5
7
6
8
7
9
8
10
9
Next: lo=10 hi=32
Target: 21
1
0
2
1
3
2
4
3
5
4
6
5
7
6
8
7
9
8
10
9
Next: lo=10 hi=32
Target: 21
1
0
2
1
3
2
4
3
5
4
6
5
7
6
8
7
9
8
10
9
Next: lo=10 hi=21
Target: 21
1
0
2
1
3
2
4
3
5
4
6
5
7
6
8
7
9
8
10
9
Next: lo=10 hi=21
Target: 15
1
0
2
1
3
2
4
3
5
4
6
5
7
6
8
7
9
8
10
9
Next: lo=10 hi=21
Target: 15
1
0
2
1
3
2
4
3
5
4
6
5
7
6
8
7
9
8
10
9
Next: lo=10 hi=15
Target: 15
1
0
2
1
3
2
4
3
5
4
6
5
7
6
8
7
9
8
10
9
Next: lo=10 hi=15
Target: 12
1
0
2
1
3
2
4
3
5
4
6
5
7
6
8
7
9
8
10
9
Next: lo=10 hi=15
Target: 12
1
0
2
1
3
2
4
3
5
4
6
5
7
6
8
7
9
8
10
9
Next: lo=13 hi=15
Target: 12
1
0
2
1
3
2
4
3
5
4
6
5
7
6
8
7
9
8
10
9
Next: lo=13 hi=15
Target: 14
1
0
2
1
3
2
4
3
5
4
6
5
7
6
8
7
9
8
10
9
Next: lo=13 hi=15
Target: 14
1
0
2
1
3
2
4
3
5
4
6
5
7
6
8
7
9
8
10
9
Next: lo=15 hi=15
Target: 14
1
0
2
1
3
2
4
3
5
4
6
5
7
6
8
7
9
8
10
9
Next: lo=15 hi=15
1
0
2
1
3
2
4
3
5
4
6
5
7
6
8
7
9
8
10
9
Next: lo=15 hi=15

Key Takeaways

✓ Binary search on answer space efficiently finds the minimal feasible capacity without enumerating all capacities.

This insight is hard to see from code alone because the search space is not array indices but capacity values.

✓ Feasibility checks with early stopping prevent unnecessary computation by stopping once days exceed the limit.

Watching the simulation of grouping packages clarifies how capacity affects day count.

✓ Adjusting left and right bounds based on feasibility results shows how the search space shrinks to the exact answer.

Seeing each update step-by-step reveals the logic behind binary search convergence.

Practice

(1/5)
1. Consider the following Python code implementing the min-heap approach to find the kth smallest element in a sorted matrix. Given the matrix [[1,3],[2,4]] and k = 3, what value does the function return?
easy
A. 2
B. 4
C. 3
D. 1

Solution

  1. Step 1: Initialize min-heap with first elements

    Push (1,0,0) and (2,1,0) into heap.
  2. Step 2: Extract elements until count == k

    Pop 1 (count=1), push 3 from row 0; pop 2 (count=2), push 4 from row 1; pop 3 (count=3), return 3.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Third smallest element is 3 [OK]
Hint: Trace heap pops and pushes carefully [OK]
Common Mistakes:
  • Off-by-one counting of popped elements
  • Returning wrong popped value
  • Confusing row and column indices
2. Consider the following code snippet implementing the optimal binary search to find the single element in a sorted array where every other element appears twice. What is the returned value when the input is [1,1,2,3,3]?
easy
A. 3
B. 1
C. 2
D. Error due to index out of range

Solution

  1. Step 1: Trace first iteration with low=0, high=4

    mid = 2 (even), nums[2]=2, nums[3]=3 not equal, so high = mid = 2
  2. Step 2: Trace second iteration with low=0, high=2

    mid = 1 (odd), nums[1]=1, nums[0]=1 equal, so low = mid + 1 = 2
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Loop ends with low=2, nums[2]=2 returned [OK]
Hint: Check parity and compare adjacent elements carefully [OK]
Common Mistakes:
  • Off-by-one errors in mid calculation
  • Confusing even/odd parity logic
  • Assuming index out of range error
3. The following code attempts to find the kth positive missing number from a sorted array arr. Which line contains a subtle bug that causes incorrect results for some inputs?
def findKthPositive(arr, k):
    n = len(arr)
    total_missing = arr[-1] - n
    if k > total_missing:
        return arr[-1] + (k - total_missing)
    left, right = 0, n - 1
    while left <= right:
        mid = (left + right) // 2
        missing = arr[mid] - mid  # Bug here
        if missing < k:
            left = mid + 1
        else:
            right = mid - 1
    return arr[right] + (k - (arr[right] - (right + 1)))
medium
A. Line returning arr[right] + (k - (arr[right] - (right + 1)))
B. Line calculating total_missing = arr[-1] - n
C. Line updating left = mid + 1
D. Line calculating missing = arr[mid] - mid

Solution

  1. Step 1: Identify the missing count formula

    The correct missing count at index mid is arr[mid] - (mid + 1), since indices are zero-based but numbers start at 1.
  2. Step 2: Analyze the bug impact

    Using arr[mid] - mid undercounts missing numbers by 1, causing incorrect binary search decisions and wrong final result.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Correct missing count formula is arr[mid] - (mid + 1) [OK]
Hint: Missing count must subtract (mid + 1), not mid [OK]
Common Mistakes:
  • Off-by-one in missing count calculation
  • Incorrect binary search boundary updates
  • Ignoring missing numbers before first element
4. What is the time complexity of the optimal binary search solution for finding the minimum speed to arrive on time, given n distances and a precision epsilon for floating point speed search?
medium
A. O(log n * (maxSpeed / epsilon))
B. O(n * maxSpeed)
C. O(n^2 * log(maxSpeed))
D. O(n * log((maxSpeed - minSpeed) / epsilon))

Solution

  1. Step 1: Identify the binary search iterations

    Binary search on speed range [minSpeed, maxSpeed] with precision epsilon takes O(log((maxSpeed - minSpeed)/epsilon)) steps.
  2. Step 2: Calculate per-iteration cost

    Each feasibility check sums over n distances, so O(n) per iteration.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Combining steps yields O(n log((maxSpeed - minSpeed)/epsilon)) [OK]
Hint: Binary search iterations times linear feasibility check [OK]
Common Mistakes:
  • Confusing maxSpeed with n
  • Ignoring epsilon precision in log factor
5. Suppose the problem is modified so that the array can contain multiple identical adjacent elements (plateaus), and you want to find any peak element efficiently. Which modification to the original modified binary search algorithm correctly handles this scenario without degrading to linear time?
hard
A. Change the comparison to nums[mid] <= nums[mid + 1] and recurse right if true, else left
B. Skip over equal adjacent elements by moving mid until nums[mid] != nums[mid + 1] before comparison
C. Use linear scan since binary search cannot handle plateaus correctly
D. Modify recursion to always recurse left half to find the first peak

Solution

  1. Step 1: Understand plateau challenge

    Equal adjacent elements break strict inequality assumptions in original binary search.
  2. Step 2: Modify comparison to handle equality

    Using ≤ ensures recursion moves right when plateau or increasing slope, preserving O(log n) time.
  3. Step 3: Avoid linear scan or skipping elements

    Skipping elements or linear scan can degrade performance; always recursing left loses efficiency.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Modified comparison handles plateaus without extra overhead [OK]
Hint: Use <= comparison to handle plateaus in binary search [OK]
Common Mistakes:
  • Trying to skip equal elements linearly
  • Assuming linear scan is necessary
  • Always recursing one side losing log n guarantee
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard