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. However, "abA" is not nice because 'b' appears lowercase, but 'B' does not appear uppercase.

Given a string s, return the longest substring of s that is nice. If there are multiple longest nice substrings, return the substring of the earliest occurrence. If there are no nice substrings, return an empty string.

Input & Output

Example 1 — Complete Nice String
$ Input: s = "abABB"
Output: "abABB"
💡 Note: The whole string is nice because 'a' and 'A' both appear, 'b' and 'B' both appear. This is the longest (and only) nice substring.
Example 2 — Partial Nice Substring
$ Input: s = "YazaAay"
Output: "aAa"
💡 Note: The character 'Y' appears but 'y' does not, and 'z' appears but 'Z' does not. The substring "aAa" is nice because 'a' and 'A' both appear.
Example 3 — No Nice Substring
$ Input: s = "Bb"
Output: "Bb"
💡 Note: Both 'B' and 'b' appear, making the entire string nice. Length is 2.

Constraints

  • 1 ≤ s.length ≤ 100
  • s consists of uppercase and lowercase English letters.

Visualization

Tap to expand
Longest Nice Substring ProblemInput: "abABB"abABBa ↔ Ab ↔ BEvery character has its case partner!Nice Substring"abABB"Output: "abABB" (length 5)
Understanding the Visualization
1
Input Analysis
Examine string "abABB" for character case pairs
2
Validation
Check if each character has its uppercase/lowercase partner
3
Result
Return the longest valid nice substring
Key Takeaway
🎯 Key Insight: A nice substring requires every character to have both its uppercase and lowercase versions present
Asked in
Microsoft 15 Amazon 8
23.0K 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