Problem 474

Abstract / Summary

Given a limit on ones and zeros, choose the best subset of binary strings to maximize the total number of ones within the limit.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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;
    }
};

70 lines | 1754 bytes | submitted August 8, 2023 | GitHub   1% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 53% (600k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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:

  1. 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 of maxx.

  2. Resource limits - The checks if (mm > m) continue; and if (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 strs is empty, the initial dp contains only the zero-resource state, and the loop body never executes, resulting in a return value of 0.
  • If the limits m or n are 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 reserve call on data ensures that even when strs contains 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 data eliminates repeated growth operations during the conversion of strings to count pairs.
  • Map vs. Unordered Map - The primary state container dp uses an ordered map, which provides deterministic iteration order and logarithmic lookup, while the temporary container next uses an unordered_map with a custom hash to achieve constant-time insertions for the newly generated states.
  • Pruning based on remaining items - By calculating left as the number of strings yet to be processed and comparing maxx against 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 dp entries (for (auto i : dp)) which is acceptable because the map’s value type is a small integer pair, and the temporary next map 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.89 | σ = 1.59

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
41 links | 26 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

19 easy 42 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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