Optimal Partition of String — LeetCode 2405 Python Solution

MediumGreedyHash TableString
Problem
#2405
Pattern
Greedy
Reading time
2 min

The problem

Given a string s, partition the string into one or more substrings such that the characters in each substring are unique. That is, no letter appears in a single substring more than once.

Example

Input
s = "abacaba"
Output
4
Explanation
Two possible partitions are ("a","ba","cab","a") and ("ab","a","ca","ba").

Python solution

Python
class Solution:
    def partitionString(self, s: str) -> int:
        ans, mask = 1, 0
        for x in map(lambda c: ord(c) - ord("a"), s):
            if mask >> x & 1:
                ans += 1
                mask = 0
            mask |= 1 << x
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string s
SpaceO(1) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2405. Optimal Partition of String is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2405. Optimal Partition of String?
LeetCode 2405. Optimal Partition of String is rated Medium on LeetCode.
What is the time complexity of LeetCode 2405. Optimal Partition of String?
The Python solution on this page runs in O(n), where n is the length of the string s.
What is the space complexity of LeetCode 2405. Optimal Partition of String?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2405. Optimal Partition of String cover?
LeetCode 2405. Optimal Partition of String is tagged Greedy, Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview