C++ 0474.cpp
class Solution {
struct hashPair
{
template <typename T, typename U>
size_t operator()(const std::pair<T, U> &x) const
{
return std::hash<T>()(x.first) ^ std::hash<U>()(x.second);
}
};
public:
int findMaxForm(vector<string>& strs, int m, int n) {
vector<pair<int, int>> data;
data.reserve(strs.size());
for (auto& s : strs)
{
int one = 0;
int zero = 0;
for (auto c : s)
if (c == '0')
zero++;
else
one++;
data.push_back({ zero, one });
}
map<pair<int, int>, int> dp;
dp[{ 0, 0 }] = 0;
int maxx = 0;
int iteration = 0;
unordered_map<pair<int, int>, int, hashPair> next;
for (auto x : data)
{
iteration++;
int left = strs.size() - iteration;
for (auto i : dp)
{
auto key = i.first;
auto depth = i.second + 1;
// can't be better ?
if (maxx > depth + left)
continue;
auto mm = x.first + key.first;
auto nn = x.second + key.second;
if (mm > m)
continue;
if (nn > n)
continue;
next[{ mm, nn }] = max(dp[{ mm, nn }], depth);
if (maxx < depth)
maxx = depth;
}
for (auto i : next)
dp[i.first] = i.second;
next.clear();
}
return maxx;
}
};
Difficulty
and has an acceptance rate of about 53% (600k+ submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the classic “maximum number of strings with limited zeros and ones” problem using a dynamic-programming approach that iterates over the input strings and builds a state map keyed by the cumulative count of zeros and ones. The algorithm first converts each string into a pair of integer counts, then incrementally updates a map that records the best depth (number of strings selected) achievable for each resource usage. Throughout the process it employs pruning based on the remaining strings and a running maximum to avoid unnecessary work.
Data Preparation
The first phase transforms the list of binary strings into a compact representation of resource consumption.
vector<pair<int, int>> data;
data.reserve(strs.size());
for (auto& s : strs)
{
int one = 0;
int zero = 0;
for (auto c : s)
if (c == '0')
zero++;
else
one++;
data.push_back({ zero, one });
}
By counting zeros and ones in a single pass per string, the code creates a vector of (zeroCount, oneCount) pairs. The reserve call prevents repeated reallocations, which is beneficial when strs is large.
Dynamic-Programming Core
A map dp stores the best depth for each reachable (zero, one) combination. It is seeded with the base case of using no resources.
map<pair<int, int>, int> dp;
dp[{ 0, 0 }] = 0;
The main loop iterates over the pre-computed data. For each string’s resource pair x, it examines every existing state in dp and attempts to extend it by including the current string.
for (auto x : data)
{
iteration++;
int left = strs.size() - iteration;
for (auto i : dp)
{
auto key = i.first;
auto depth = i.second + 1;
// pruning condition
if (maxx > depth + left)
continue;
auto mm = x.first + key.first;
auto nn = x.second + key.second;
if (mm > m)
continue;
if (nn > n)
continue;
next[{ mm, nn }] = max(dp[{ mm, nn }], depth);
if (maxx < depth)
maxx = depth;
}
for (auto i : next)
dp[i.first] = i.second;
next.clear();
}
The inner loop computes the new resource totals mm and nn. If they stay within the limits m and n, the candidate depth is merged into a temporary unordered map next. After processing all current states, next is merged back into dp, and the temporary container is cleared for the next iteration.
Pruning Logic
Two pruning mechanisms reduce the search space:
-
Future-capacity bound - The condition
if (maxx > depth + left) continue;discards any state that cannot possibly exceed the current best solution, because even if all remaining strings were added, the depth would fall short ofmaxx. -
Resource limits - The checks
if (mm > m) continue;andif (nn > n) continue;immediately reject extensions that would exceed the allowed number of zeros or ones.
These early exits prevent the algorithm from exploring hopeless branches, saving both time and memory.
State Merging
The temporary unordered map next is used to accumulate updates for the current iteration without interfering with the iteration over dp. This separation ensures that newly created states do not affect the processing of older states within the same round.
unordered_map<pair<int, int>, int, hashPair> next;
...
next[{ mm, nn }] = max(dp[{ mm, nn }], depth);
...
for (auto i : next)
dp[i.first] = i.second;
next.clear();
By using a custom hash functor hashPair, the unordered map can efficiently store and retrieve pairs as keys.
Edge Cases Handled
The algorithm gracefully handles several boundary conditions:
- When the input vector
strsis empty, the initialdpcontains only the zero-resource state, and the loop body never executes, resulting in a return value of0. - If the limits
mornare zero, any string containing a disallowed character is filtered out by the resource-limit checks, leaving only strings that consist exclusively of the allowed character. - Strings composed entirely of zeros or entirely of ones are correctly represented as
(length, 0)or(0, length), and the algorithm treats them like any other pair. - The
reservecall ondataensures that even whenstrscontains a large number of short strings, the vector allocation overhead remains minimal.
Performance Optimizations
Several deliberate choices contribute to the efficiency of the solution:
- Pre-allocation - Reserving space for
dataeliminates repeated growth operations during the conversion of strings to count pairs. - Map vs. Unordered Map - The primary state container
dpuses an orderedmap, which provides deterministic iteration order and logarithmic lookup, while the temporary containernextuses anunordered_mapwith a custom hash to achieve constant-time insertions for the newly generated states. - Pruning based on remaining items - By calculating
leftas the number of strings yet to be processed and comparingmaxxagainst the theoretical maximum depth achievable from the current branch, the algorithm cuts off large portions of the search tree early. - In-place maximum update - The expression
max(dp[{ mm, nn }], depth)updates the depth for a state only if the new depth is better, avoiding unnecessary overwrites. - Minimal copying - The loop iterates over copies of
dpentries (for (auto i : dp)) which is acceptable because the map’s value type is a small integer pair, and the temporarynextmap is cleared after each iteration, keeping memory usage bounded by the number of distinct resource combinations reachable at any step.
Collectively, these techniques enable the solution to handle inputs with a substantial number of strings while staying within practical time and memory limits.
ELI5 - Simplified Explanation
Imagine you have a big pile of toy blocks. Some blocks have a zero painted on them and some blocks have a one painted on them. You have two empty toy boxes. One box can only fit a certain number of zero blocks, and the other box can only fit a certain number of one blocks. The goal is to see how many total blocks can be fit into these boxes without going over the space inside each one.
This code acts like a very organized robot trying to figure out the best way to pick blocks. First, the robot looks at every string of blocks and counts how many zeros and ones are in each one. It keeps a note of these counts on a piece of paper.
Then, the robot starts testing combinations. It keeps track of how many blocks it has already put into the boxes. It carefully checks if adding one more set of blocks will make the total number of zeros or ones too big for the boxes. If adding the blocks fits, the robot records the new total number of blocks collected. If it does not fit, the robot skips those blocks and looks at other possibilities.
While playing this game, the robot keeps track of the highest number of blocks it has managed to fit so far. Every time it finds a new combination that holds more blocks than the last record, it updates its number. By the time the robot is done checking every single way to combine the blocks, the highest number it wrote down is the final answer.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | Python | Rust | Go | TS | |||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | black-shadows | C++ | |||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fpdjsns | C++ | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| MacJim | C++ | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| withaarzoo | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fpdjsns | C++ | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| MacJim | C++ | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| withaarzoo | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 600: Non-negative Integers without Consecutive Ones
- problem 2031: Count Subarrays With More Ones Than Zeros
- problem 2155: All Divisions With the Highest Score of a Binary Array
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality