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 Hash Map Character Tracking Approach INPUT Input String s: 'a' 'b' 'A' 'B' 'B' 0 1 2 3 4 Character Hash Map: 'a': present 'A': present 'b': present 'B': present Nice String Criteria: Every letter appears in BOTH uppercase and lowercase Input: s = "abABB" ALGORITHM STEPS 1 Build Character Set Track all chars in string 2 Find Bad Characters Chars without pair (a/A) 3 Divide at Bad Char Split string recursively 4 Return Longest Track max nice substring Character Pair Check: 'a' has 'A'? YES 'b' has 'B'? YES All pairs found! No bad characters found Entire string is NICE! Return full string FINAL RESULT Longest Nice Substring: 'a' 'b' 'A' 'B' 'B' Verification: 'a' and 'A' both present: OK 'b' and 'B' both present: OK String is NICE! Length: 5 characters Output: "abABB" Entire string returned Key Insight: Use divide-and-conquer with hash map: if a character lacks its case pair, it cannot be in any nice substring. Split at that character and recursively find the longest nice substring in each part. Time: O(n^2) worst case, Space: O(n) for recursion stack. When all pairs exist, return full string. TutorialsPoint - Longest Nice Substring | Hash Map Character Tracking
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