A string is considered "nice" if for every letter of the alphabet that appears in the string, both its uppercase and lowercase versions are present.

For example:

  • "abABB" is nice because 'A' and 'a' both appear, and 'B' and 'b' both appear
  • "abA" is not nice because 'b' appears but 'B' does not
  • "YazaAay" is nice because 'Y','y', 'a','A', and 'z','Z' all have their pairs

Goal: Find the longest substring that is nice. If multiple substrings have the same maximum length, return the one that appears earliest in the string. If no nice substring exists, return an empty string.

Input & Output

example_1.py — Basic Nice String
$ Input: s = "abABB"
Output: "abABB"
💡 Note: The whole string is nice because 'a' and 'A' are both present, and 'b' and 'B' are both present. This is the longest possible nice substring.
example_2.py — Partial Nice String
$ Input: s = "abA"
Output: ""
💡 Note: The string contains 'b' but not 'B', so no substring can be nice. The longest nice substring has length 0.
example_3.py — Multiple Nice Substrings
$ Input: s = "YazaAay"
Output: "aAay"
💡 Note: There are nice substrings like "aA" (length 2) and "aAay" (length 4). We return "aAay" as it's the longest nice substring.

Visualization

Tap to expand
Ballroom: Y a z a A a yFind dance partners (case pairs)YNo partner 'y'!azNo partner 'Z'!aAyPartners connectedSPLIT HEREY aNot nicea A a y✓ Nice! (length 4)(empty)🎯 Result: "aAay" - The largest valid dance group!Time: O(n) | Space: O(n)
Understanding the Visualization
1
Identify Solo Dancers
Find characters that don't have their case partner in the string - these are 'solo dancers' who can't participate in any nice dance group
2
Split the Ballroom
Divide the ballroom (string) at solo dancer positions since they can't be part of any valid dance group
3
Check Each Section
Recursively check each section of the ballroom to find the largest valid dance group
4
Return Best Group
Compare all valid dance groups found and return the largest one
Key Takeaway
🎯 Key Insight: Characters without case partners act as natural "barriers" that split the problem, making divide-and-conquer the optimal approach with O(n) time complexity.

Time & Space Complexity

Time Complexity
⏱️
O(n³)

O(n²) to generate all substrings, O(n) to check each substring

n
2n
Quadratic Growth
Space Complexity
O(1)

Only using a constant amount of extra space for tracking characters

n
2n
Linear Space

Constraints

  • 1 ≤ s.length ≤ 100
  • s consists of uppercase and lowercase English letters only
  • Nice substring must have at least 2 characters
Asked in
Facebook 25 Amazon 18 Google 15 Microsoft 12
28.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen