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
Difficulty
and has an acceptance rate of about 65% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Backtracking
- Bit Manipulation
- Enumeration
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 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.
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.
Code Quality
Complexity Analysis
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
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 | ||||||
| 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++ |
Videos
Solved On The Same Day
- problem 880: Decoded String at Index
- problem 912: Sort an Array
- problem 923: 3Sum With Multiplicity
- problem 973: K Closest Points to Origin
- problem 1010: Pairs of Songs With Total Durations Divisible by 60
- problem 1054: Distant Barcodes
- problem 1079: Letter Tile Possibilities
- problem 1090: Largest Values From Labels
- problem 1347: Minimum Number of Steps to Make Two Strings Anagram
- problem 1366: Rank Teams by Votes
- problem 1419: Minimum Number of Frogs Croaking
- problem 1738: Find Kth Largest XOR Coordinate Value
- problem 1814: Count Nice Pairs in an Array
- problem 1985: Find the Kth Largest Integer in the Array
- problem 2018: Check if Word Can Be Placed In Crossword
- problem 2150: Find All Lonely Numbers in the Array
- problem 2182: Construct String With Repeat Limit
- problem 2225: Find Players With Zero or One Losses
- problem 2232: Minimize Result by Adding Parentheses to Expression
- problem 2244: Minimum Rounds to Complete All Tasks
- problem 2284: Sender With Largest Word Count
- problem 2343: Query Kth Smallest Trimmed Number
- problem 2526: Find Consecutive Integers from a Data Stream
- problem 2844: Minimum Operations to Make a Special Number
- problem 2860: Happy Students
- problem 906: Super Palindromes
- problem 992: Subarrays with K Different Integers
- problem 1106: Parsing A Boolean Expression
- problem 2081: Sum of k-Mirror Numbers
- problem 2122: Recover the Original Array
- problem 2416: Sum of Prefix Scores of Strings
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