The Longest Nice Substring problem gives you a string s. A string is considered "nice" if, for every character in the string, both its uppercase and lowercase equivalents appear within the string. For example, "aAa" is nice because both 'a' and 'A' appear. "abA" is not nice because 'b' appears, but 'B' does not. Your task is to find the longest nice substring of s.
This is a popular entry-level String problem because it introduces candidates to the concept of Divide and Conquer. While it has an Easy rating and can be solved with a brute-force sliding window, interviewers love to push candidates towards the more elegant recursive solution. It tests string parsing, hash set lookups, and recursive state management.
The most elegant solution uses Divide and Conquer. You first put all characters of the current string into a Hash Set. Then, you iterate through the string. If you find a character whose upper or lower case counterpart is missing from the set, you know this character cannot possibly be part of any "nice" substring. Therefore, it acts as an invalid boundary. You split the string at this character and recursively call your function on the left part and the right part, returning the longest valid result.
Consider the string "YazaAay".
Y, a, z, A, y.Y: 'y' is in the set. Okay.a: 'A' is in the set. Okay.z: 'Z' is NOT in the set! This 'z' ruins everything."Ya", Right is "aAay"."Ya":
Y, a.Y lacks 'y'. Divide at 'Y'. Left "", Right "a". Both fail. "Ya" yields ""."aAay":
a, A, y.a has 'A'. A has 'a'.y lacks 'Y'. Divide at 'y'. Left "aAa", Right ""."aAa":
a, A. All characters have their pairs! It returns "aAa".
The maximum nice substring is "aAa".A common mistake in the brute-force approach is creating complex nested loops with multiple maps that reset clumsily, leading to messy, bug-prone code. In the Divide and Conquer approach, candidates sometimes forget that if multiple substrings have the same maximum length, the problem usually requires returning the one that occurs first. You must use strict greater-than (>) when comparing left and right recursive results to preserve the earliest occurrence.
When dealing with the Longest Nice Substring interview pattern, practice recognizing "invalid boundary" characters. If a string problem requires a global condition to be met (like all characters having pairs), finding a character that irreparably breaks that condition gives you a perfect pivot point to split the problem in half using Divide and Conquer.