Python 1695.py
class Solution:
def maximumUniqueSubarray(self, nums: List[int]) -> int:
result = 0
left = 0
have = set()
current = 0 # equals sum(have), just a speed trick
for right in range(len(nums)):
n = nums[right]
while n in have:
have.discard(nums[left])
current -= nums[left]
left += 1
have.add(n)
current += n
result = max(result, current)
return result
Difficulty
and has an acceptance rate of about 64% (400k+ submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- Sliding Window
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 maximumUniqueSubarray method computes the greatest possible sum of a contiguous sub-array that contains no repeated values. It walks through the input list once, maintaining a sliding window that always satisfies the uniqueness constraint. As the window expands and contracts, the algorithm keeps track of the current window sum and records the highest sum observed.
Initialization
At the start, several variables are prepared:
result = 0
left = 0
have = set()
current = 0 # running sum of the elements inside the window
result stores the best sum found so far. left marks the beginning of the sliding window. have is a set that records which numbers are currently inside the window, enabling constant-time membership checks. current mirrors the sum of the elements in have, avoiding the need to recompute the sum from the set on each iteration.
Sliding Window Expansion
The main loop iterates over the right boundary of the window:
for right in range(len(nums)):
n = nums[right]
right moves from the first to the last index, and n holds the candidate element to be added to the window.
Duplicate Resolution
If the incoming element already exists in the window, the left side of the window is shifted rightward until the duplicate is removed. This guarantees that the window always contains distinct values.
while n in have:
have.discard(nums[left])
current -= nums[left]
left += 1
The while loop repeatedly discards the element at the left index from have, subtracts its value from current, and advances left. The use of discard ensures that the operation is safe even if the element were somehow absent, and the subtraction updates the running sum in constant time.
Incorporating the New Element
Once the duplicate has been eliminated, the new element is added to the window, the running sum is updated, and the best result is possibly refreshed.
have.add(n)
current += n
result = max(result, current)
Adding n to have restores the uniqueness invariant. Updating current reflects the new window sum, and result captures the maximum sum encountered.
Return Value
After the loop finishes, the method returns the highest sum recorded:
return result
Edge Cases Handled
The algorithm gracefully deals with several boundary conditions:
- Empty input - When
numsis empty, the loop body never executes, leavingresultat its initial value of0, which is the correct maximum sum for an empty sub-array. - All elements identical - The window never grows beyond a single element because each new element triggers the duplicate-resolution loop, shrinking the window back to size one. The result ends up being the largest single element value.
- All elements distinct - The
whilecondition never activates, allowing the window to expand to cover the entire list. The finalresultbecomes the sum of the whole array. - Negative numbers - The algorithm does not rely on positivity; it still maintains uniqueness and updates the sum accordingly. If the best sub-array consists of a single negative number,
resultwill reflect that value. - Large integer values - Since the sum is accumulated incrementally in
current, the method can handle very large numbers without overflow concerns in Python’s arbitrary-precision integer arithmetic.
Performance Optimizations
Several deliberate choices improve execution speed:
- Set for membership testing - Using a hash set (
have) provides average-case O(1) checks for the presence of a value, enabling rapid detection of duplicates. - Running sum (
current) - Maintaining the window sum as a separate variable avoids recomputing the sum of the set on each iteration, which would be linear in the window size. discardinstead ofremove-discarddoes not raise an exception if the element is missing, eliminating the need for an explicit existence check before removal.- Single pass - The left and right pointers each move forward at most
len(nums)steps, ensuring that the total work performed is proportional to the length of the input list.
These techniques together yield an implementation that processes the input efficiently while preserving clarity.
ELI5 - Simplified Explanation
Imagine a long row of colorful building blocks laid out on the floor. The goal is to pick up a line of these blocks, one after another, but there is a special rule. Every block held in your hand must be a different color. No two blocks can look the same.
Think of the blocks as numbers in a list. Two markers, named left and right, move along the row to keep track of which blocks are currently in the hand. The right marker walks forward, picking up a new block one by one. If a new block is a color already held, the left marker quickly puts a block back on the floor from the start of the current hand. This happens over and over until the block can be picked up safely without any repeats.
As each new block is added to the hand, the total value of all the held blocks is added up. Whenever a new block makes the group larger than a previous group, a note is made to remember that this new stack is the best one found so far. The process continues until the right marker reaches the very end of the row, having checked every possible group that follows the special rule. The final answer is the memory of the biggest stack that was ever held during the whole walk.
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++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | Rust | TS | |||
| MemoryLimitExceeded | C++ | Python | |||||||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fpdjsns | C++ | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| YuriSpiridonov | Python | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fpdjsns | C++ | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
Solved On The Same Day
- problem 1400: Construct K Palindrome Strings
- problem 1442: Count Triplets That Can Form Two Arrays of Equal XOR
- problem 1519: Number of Nodes in the Sub-Tree With the Same Label
- problem 1577: Number of Ways Where Square of Number Is Equal to Product of Two Numbers
- problem 1593: Split a String Into the Max Number of Unique Substrings
- problem 1604: Alert Using Same Key-Card Three or More Times in a One Hour Period
- problem 1638: Count Substrings That Differ by One Character
- problem 1726: Tuple with Same Product
- problem 1368: Minimum Cost to Make at Least One Valid Path in a Grid
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