EasyNo. 1763
Longest Nice Substring — LeetCode 1763 Python Solution
- Pattern
- Sliding Window
- Topics
- Bit Manipulation, Hash Table, String, Divide and Conquer, Sliding Window
- Reading time
- 3 min
- Source
- leetcode.com
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
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 ansComplexity
- Time
- O(n)
- Space · auxiliary
- O(n)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0187 | Repeated DNA Sequences | Medium |
| 0395 | Longest Substring with At Least K Repeating Characters | Medium |
| 1016 | Binary String With Substrings Representing 1 To N | Medium |
| 0003 | Longest Substring Without Repeating Characters | Medium |
| 0030 | Substring with Concatenation of All Words | Hard |
| 0076 | Minimum Window Substring | Hard |
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.