Longest Nice Substring — LeetCode 1763 Python Solution

EasyBit ManipulationHash TableStringDivide and ConquerSliding Window
Problem
#1763
Reading time
3 min

The problem

A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, "abABB" is nice because 'A' and 'a' appear, and 'B' and 'b' appear.

Example

Input
s = "YazaAay"
Output
"aAa"
Explanation
"aAa" is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear.

Python solution

Python
class Solution:
    def longestNiceSubstring(self, s: str) -> str:
        n = len(s)
        ans = ''
        for i in range(n):
            ss = set()
            for j in range(i, n):
                ss.add(s[j])
                if (
                    all(c.lower() in ss and c.upper() in ss for c in ss)
                    and len(ans) < j - i + 1
                ):
                    ans = s[i : j + 1]
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1763. Longest Nice Substring is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1763. Longest Nice Substring?
LeetCode 1763. Longest Nice Substring is rated Easy on LeetCode.
What is the time complexity of LeetCode 1763. Longest Nice Substring?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1763. Longest Nice Substring?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1763. Longest Nice Substring cover?
LeetCode 1763. Longest Nice Substring is tagged Bit Manipulation, Hash Table, String, Divide and Conquer and Sliding Window 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