Minimize String Length — LeetCode 2716 Python Solution

EasyHash TableString
Problem
#2716
Pattern
Hash Map
Reading time
2 min

The problem

Given a string s, you have two types of operation: Choose an index i in the string, and let c be the character in position i. Delete the closest occurrence of c to the left of i (if exists).

Python solution

Python
class Solution:
    def minimizedStringLength(self, s: str) -> int:
        return len(set(s))

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string \textit{s}
SpaceO(|\Sigma|), where \Sigma is the character set auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2716. Minimize String Length is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2716. Minimize String Length?
LeetCode 2716. Minimize String Length is rated Easy on LeetCode.
What is the time complexity of LeetCode 2716. Minimize String Length?
The Python solution on this page runs in O(n), where n is the length of the string \textit{s}.
What is the space complexity of LeetCode 2716. Minimize String Length?
The Python solution on this page uses O(|\Sigma|), where \Sigma is the character set auxiliary space.
What topics does LeetCode 2716. Minimize String Length cover?
LeetCode 2716. Minimize String Length is tagged 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