logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
instagramtwitterfacebookyoutubelinkedinmailgithubrss
Copyright © 2026 All rights reserved.
•
VIKI
Built with Vikramaditya Singh
Built with
VIKI - A posts created with Next.js and Tailwind.css
About
leetcode
Title
Table Of Contents
easy
13. Roman to Integer
14. Longest Common Prefix
20. Valid Parentheses
26. Remove Duplicates from Sorted Array
35. Search Insert Position
69. Sqrt(x)
70. Climbing Stairs
88. Merge Sorted Array (In-Place)
104. Maximum Depth of Binary Tree
118. Pascal's Triangle
121. Best Time to Buy and Sell Stock
205. Isomorphic Strings
242. Valid Anagram
283. Move Zeroes
345. Reverse Vowels of a String
605. Can Place Flowers
704. Binary Search
796. Rotate String
1071. Greatest Common Divisor of Strings
1299. Replace Elements with Greatest Element on Right Side
1431. Kids With the Greatest Number of Candies
1614. Maximum Nesting Depth of the Parentheses
1752. Check if Array Is Sorted and Rotated
1768. Merge Strings Alternately
1903. Largest Odd Number in String
2965. Find Missing and Repeated Values
hard
25. Reverse Nodes in k-Group
26. Remove Duplicates from Sorted Array
27. Remove Element
42. Trapping Rain Water
51. N-Queens
55. Jump Game
80. Remove Duplicates from Sorted Array II
88. Merge Sorted Array
121. Best Time to Buy and Sell Stock
122. Best Time to Buy and Sell Stock II
189. Rotate Array
274. H-Index
medium
2. Add Two Numbers
3. Longest Substring Without Repeating Characters
5. Longest Palindromic Substring
8. String to Integer (atoi)
11. Container With Most Water
15. 3Sum
17. Letter Combinations of a Phone Number
19. Remove Nth Node From End of List
22. Generate Parentheses
33. Search in Rotated Sorted Array
34. Find First and Last Position of Element in Sorted Array
48. Rotate Image
49. Group Anagrams
50. Pow(x, n)
53. Maximum Subarray
54. Spiral Matrix
56. Merge Intervals
61. Rotate List
73. Set Matrix Zeroes
74. Search a 2D Matrix
75. Sort Colors
78. Subsets
137. Single Number II
138. Copy List with Random Pointer
150. Evaluate Reverse Polish Notation
151. Reverse Words in a String
153. Find Minimum in Rotated Sorted Array
155. Min Stack
162. Find Peak Element
169. Majority Element
198. House Robber
207. Course Schedule
215. Kth Largest Element in an Array
227. Basic Calculator II
236. Lowest Common Ancestor of a Binary Tree
237. Delete Node in a Linked List
238. Product of Array Except Self
451. Sort Characters By Frequency
540. Single Element in a Sorted Array
560. Subarray Sum Equals K
636. Exclusive Time of Functions
875. Koko Eating Bananas
1011. Capacity To Ship Packages Within D Days
1101. The Earliest Moment When Everyone Become Friends
1283. Find the Smallest Divisor Given a Threshold
2140. Solving Questions With Brainpower
3169. Count Days Without Meetings
3481. Apply Substitutions
rotate-array-approach-1
189. Rotate Array (Approach 2 )
189. Rotate Array (Approach 1 )
number-of-islands-approach-1
200. Number of Islands (Approach 2)
200. Number of Islands (Approach 1)
meeting-rooms-ii-approach-1
253. Approach Using Priority Queue
253. Meeting Rooms II
misc
Calculate Floor & Ceiling
Find Nth Root Of M
Flatten A Linked List
Implement Lower Bound
Implement Upper Bound
Number of occurrence
take-u-forward
Recently Solved
arrays
The Ultimate Array Pattern Playbook
faqs-hard
Count Inversions in an Array
Find The Repeating And Missing Number
Majority Element II
Maximum Product Subarray
Merge Sorted Array (In-Place)
Reverse Pairs
faqs-medium
3. 3Sum
4. 4Sum
Maximum Subarray
Leaders in an Array
Majority Element
Next Permutation
Get specific element from Pascal's Triangle
Pascal's Triangle II (Row Generation)
Generate Pascal's Triangle (Full)
Spiral Matrix Traversal
Rearrange Array Elements by Sign
Rotate Image
Sort Colors (Dutch National Flag)
Two Sum
fundamentals
Check if Array is Sorted
Largest Element in an Array
Array Rotation (Left and Right)
Left Rotate Array by One
Linear Search
Max Consecutive Ones
Second Largest Element in an Array
Single Number
logic-building
Missing Number
Intersection of Two Sorted Arrays (with Duplicates)
Move Zeros to End
Remove Duplicates from Sorted Array
Union of Two Sorted Arrays
binary-search
About
d-arrays
Find Row With Maximum 1'S
Search In A 2D Matrix
faqs
Aggressive Cows
Allocate Books
Find Peak Element
Kth Element Of 2 Sorted Arrays
Minimise Max Distance to Gas Stations
Split Array - Largest Sum
fundamentals
Lower Bound
Binary Search
Upper Bound
logic-building
Count Occurrences in a Sorted Array
Find Minimum in Rotated Sorted Array
Find out how many times the array is rotated
Find First and Last Position of Element in Sorted Array
Floor and Ceil in Sorted Array
Kth Missing Positive Number
Search in Rotated Sorted Array
Search in Rotated Sorted Array II (With Duplicates)
Search Insert Position
Single Element in a Sorted Array
on-answers
Capacity To Ship Packages Within D Days
Find Nth Root of M
Find Square Root of a Number
Smallest Divisor Given a Threshold
Koko Eating Bananas (Minimum Rate)
Minimum Days to Make M Bouquets
Painter's Partition Problem
Split Array Largest Sum
hashing
Theory
faqs
Subarray Sum Equals K
Count Subarrays with Given XOR K
Largest Subarray with 0 Sum
Longest Consecutive Sequence
Longest Subarray with Sum K
recursion
faqs-medium
Combination Sum II (Unique Combinations)
Combination Sum (Unbounded)
Subset Sums
hard
Letter Combinations of a Phone Number
implementation-problems
Generate Parentheses
Power Function: pow(x, n)
Subsets (The Power Set)
subsequence-pattern-problems
Subsequence Sum Existence
Count All Subsequences With Sum K
sorting
Bubble Sort
Insertion Sort
Merge Sort
Quick Sort
Selection Sort
string
Isomorphic Strings
Largest Odd Number in String
Longest Common Prefix
Reverse Words in a String
Code Scratch›take u forward›binary search›on answers

Capacity To Ship Packages Within D Days

# Question

Given an array weights where weights[i] represents the weight of the iii-th package, and an integer days, return the minimum ship weight capacity needed to ship all packages within days days. Packages must be shipped in the exact order given.

# Solution

# Pattern

Binary Search on Answer (with Greedy Validation) We cannot easily calculate the exact capacity mathematically. Instead, we define the search space of all possible capacities (from the largest single package to the sum of all packages) and perform a binary search. For each guessed capacity, we use a greedy algorithm to simulate the shipping process and count how many days it takes.

# How to Identify

  • The problem asks for the minimum capacity/size/time to achieve a goal, or the maximum minimum.
  • You are required to maintain the contiguous order of an array (packages must be shipped in order).
  • Simulating the process for a fixed answer takes O(N)O(N)O(N) time.

# Description

Step-by-step explanation:

  1. Establish Bounds: The ship must be able to carry at least the heaviest single package (otherwise, that package can never be shipped). This is our left bound. The absolute maximum capacity needed is the sum of all packages (shipping everything in 1 day). This is our right bound.
  2. Binary Search: Loop while left < right. Calculate the mid capacity.
  3. Greedy Simulation: Pass the mid capacity into a helper function. Iterate through the packages in order. Add packages to the ship for the current day until adding the next package would exceed mid. When it exceeds, increment the day counter and start a new ship load.
  4. Evaluate and Halve: - If the total simulated days ≤\le≤ target days, this capacity is valid. We record it and try to find a smaller valid capacity by setting right = mid.
    • If the total simulated days > target days, this capacity is too small. We must increase it by setting left = mid + 1.
  5. Return: When the loop terminates (left == right), we have converged on the minimum valid capacity.

# The Intuition

Think of this like guessing a number between 1 and 100, but applied to physical limits. If you know the absolute smallest ship you could buy holds the heaviest single item, and the absolute largest holds everything at once, the perfect ship size is somewhere in between. You buy the middle-sized ship and test it. You load packages onto it until it's full, send it off, and repeat. If it takes you 6 days to ship everything but your boss gave you 5 days, the ship is too small. You throw away the lower half of your catalog and look at bigger ships. If it only takes 3 days, you spent too much money on a big ship; you throw away the upper half of the catalog and look at smaller ships.

# Complexity

LabelWorstAverage
Time ComplexityO(Nlog⁡(ΣW))O(N \log(\Sigma W))O(Nlog(ΣW))O(Nlog⁡(ΣW))O(N \log(\Sigma W))O(Nlog(ΣW))
Space ComplexityO(1)O(1)O(1)O(1)O(1)O(1)

# Time Complexity

The size of the search space is ΣW−max⁡(W)\Sigma W - \max(W)ΣW−max(W). We halve this space at each step, resulting in log⁡(ΣW)\log(\Sigma W)log(ΣW) binary search iterations. During each iteration, we perform a linear O(N)O(N)O(N) scan to simulate the days. Total time is O(Nlog⁡(ΣW))O(N \log(\Sigma W))O(Nlog(ΣW)).

# Space Complexity

We only allocate a few integer pointers (left, right, mid, currentLoad, days). Auxiliary space is strictly O(1)O(1)O(1).

# Code

class Solution {
    public int shipWithinDays(int[] weights, int days) {
        int left = 0; 
        int right = 0; 
 
        // left = max single weight (minimum possible capacity)
        // right = sum of all weights (maximum possible capacity)
        for (int w : weights) {
            left = Math.max(left, w);
            right += w;
        }
 
        while (left < right) {
            int mid = left + (right - left) / 2;
 
            if (daysRequired(weights, mid) <= days) {
                // Capacity works, but try to find a tighter (smaller) capacity
                right = mid;
            } else {
                // Capacity is too small, we took too many days
                left = mid + 1;
            }
        }
 
        return left;
    }
 
    private int daysRequired(int[] weights, int capacity) {
        int days = 1;
        int currentLoad = 0;
 
        for (int w : weights) {
            if (currentLoad + w &gt; capacity) {
                days++; // Ship departed, start a new day
                currentLoad = 0;
            }
            currentLoad += w; // Load package onto the new day
        }
 
        return days;
    }
}

# Caveats

  • Lower Bound Trap: A common mistake is initializing left = 0 or left = 1. If weights = [10] and capacity = 5, the helper function will incorrectly loop or return inaccurate days because the single package can never fit. The lower bound must be the maximum element in the array.
  • Array Order: You cannot sort the array. The problem explicitly states packages are loaded in the order given. Sorting the array destroys the problem constraints.

# Concepts to Think About

  • Binary Search on Answer: This is a flagship problem for this pattern. Once you master it, you can instantly solve LeetCode 875 (Koko Eating Bananas), LeetCode 410 (Split Array Largest Sum), and LeetCode 1482 (Minimum Number of Days to Make m Bouquets). They are identical algorithms wrapped in different story descriptions.
  • Monotonicity: Binary search only works because the relationship is monotonically decreasing: as capacity increases, the days required decreases.

# Logical Follow-up

Question: How would the algorithm change if the order of packages did NOT matter, and you could pick any package to load onto the ship to optimize daily capacity? Solution: If order doesn't matter, this becomes the classic "Bin Packing Problem," which is NP-Hard. You cannot use a simple greedy O(N)O(N)O(N) scan anymore. You would have to sort the array descending and use Backtracking/DFS to try different combinations to minimize the number of bins (days). For an exact optimal answer, the time complexity would skyrocket to exponential bounds O(2N)O(2^N)O(2N) or require advanced DP with bitmasking if NNN is small enough.

PreviousSingle Element in a Sorted ArrayNextFind Nth Root of M
CONTENTS
QuestionSolutionPatternHow to IdentifyDescriptionThe IntuitionComplexityCodeCaveatsConcepts to Think AboutLogical Follow-up