Problem 1601

Abstract / Summary

Given requests to move items between buckets with limits, find the largest number of requests that can be fully completed.

Note

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

Python 1601.py

class Solution:
    def maximumRequests(self, n: int, requests: List[List[int]]) -> int:
        size = len(requests)

        result = 0
        for i in range(2**size):
            mask = bin(i)[2:].zfill(size)
            num = mask.count("1")
            if num <= result:
                continue

            buildings = [0] * n
            for pos, consider in enumerate(mask):
                if consider == "1":
                    leave, enter = requests[pos]
                    buildings[leave] -= 1
                    buildings[enter] += 1

            if max(buildings) == 0:
                result = num

        return result
22 lines | 665 bytes | submitted September 28, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 65% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Backtracking
  • Bit Manipulation
  • Enumeration
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 Solution class implements a brute-force enumeration to determine the maximum number of transfer requests that can be satisfied while keeping the net change of employees in each building equal to zero. The method maximumRequests receives the number of buildings n and a list of transfer requests, each expressed as a pair [leave, enter]. By iterating over every possible subset of requests, the algorithm evaluates whether the subset maintains a balanced count for all buildings and records the size of the largest feasible subset.

Key Steps

Determining the Search Space

size = len(requests)

The variable size captures the total number of requests, which defines the cardinality of the power set that will be examined. The subsequent loop iterates over the integer range 0 to 2**size - 1, where each integer encodes a distinct subset via its binary representation.

Subset Generation and Early Pruning

for i in range(2**size):
    mask = bin(i)[2:].zfill(size)
    num = mask.count("1")
    if num <= result:
        continue

For each integer i, the binary string mask of length size indicates which requests are selected ('1') and which are omitted ('0'). The count num reflects the number of selected requests. The conditional if num <= result: continue discards any subset that cannot improve the current best answer, thereby avoiding unnecessary work for smaller subsets.

Simulating the Effect of a Subset

buildings = [0] * n
for pos, consider in enumerate(mask):
    if consider == "1":
        leave, enter = requests[pos]
        buildings[leave] -= 1
        buildings[enter] += 1

An array buildings of length n tracks the net employee change for each building. For every request marked '1' in the mask, the algorithm decrements the count at the departure building and increments the count at the arrival building. This simulation respects the directionality of each transfer.

Validating Balance

if max(buildings) == 0:
    result = num

After processing the selected requests, the subset is considered valid if every building’s net change is zero. Because the array is initialized with zeros and only modified by increments and decrements, a simple check that the maximum value equals zero suffices to confirm that all entries are zero. When a valid subset is found, result is updated to the size of that subset.

Returning the Answer

return result

The method concludes by returning the largest number of requests that can be simultaneously satisfied while preserving balance across all buildings.

Edge Cases Handled

When the request list is empty (size == 0), the outer loop executes exactly once with i == 0. The mask becomes an empty string, num is zero, and the early-pruning condition does not trigger because result is also zero. The buildings array remains all zeros, the balance check passes, and the method returns 0, correctly indicating that no requests can be fulfilled.

If all requests involve the same building as both source and destination (e.g., [0, 0]), the simulation adds and subtracts from the same index, leaving the net change unchanged. The balance condition still holds, allowing the algorithm to count such requests toward the maximum.

When n is larger than the number of distinct buildings referenced in the requests, the extra entries in buildings stay at zero throughout the simulation. The balance check, which examines the maximum value, naturally ignores these untouched entries, ensuring correctness regardless of unused building indices.

Performance Optimizations Observed

The primary optimization is the early-pruning step that skips any subset whose size does not exceed the current best result. By comparing num to result before performing the more expensive simulation, the algorithm reduces the number of full evaluations, especially as larger feasible subsets are discovered early in the enumeration.

Another subtle optimization is the use of a fixed-size list buildings initialized once per subset rather than a dictionary or other dynamic structure. List indexing provides constant-time updates for each request, keeping the inner loop tight.

The balance verification leverages max(buildings) == 0 instead of iterating through the entire list to check each entry individually. Since the list contains only integer deltas, a single pass to compute the maximum is sufficient to confirm that all entries are zero, saving a full scan in the common case where the subset is invalid early.

Collectively, these choices keep the brute-force approach as efficient as possible within its exponential search space, allowing it to solve instances where the number of requests is modest.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a neighborhood with a row of colorful houses. Sometimes people want to move from their house to a different house. This code is like a game where you decide which moving requests to say yes to.

First, the code looks at every possible set of requests. It uses a long list of zeros and ones to represent the choices. A one means we say yes to a move, and a zero means we say no. It goes through every combination possible to see which ones work.

For each group of chosen moves, the code keeps track of how many people are in each building. When someone moves out of a house, that house loses a person, and when someone moves into a house, that house gains a person.

The goal is to make sure that the number of people in every single house stays exactly the same as when the game started. If everyone ends up with the same number of neighbors they had before, then that group of moves is perfectly balanced. The code keeps a count of how many moves were made in each successful group and remembers the biggest group found so far. It keeps checking until every combination has been tested to find the largest amount of moves that keeps the neighborhood perfectly balanced.

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 | μ = 6.19 | σ = 1.70

Complexity Analysis

Time: exponential
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

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
leetcode.ca C++ JS Java C# Go Python TS
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
JoshCrozier JS
keineahnung2345 C++
suxrobGM C#
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
suxrobGM C#
wisdompeak C++
24 links | 12 authors | 7 languages

Videos

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

Solved On The Same Day

32 solutions   September 28, 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