Similar Problems

Similar Problems not available

Longest Nice Substring - Leetcode Solution

Companies:

LeetCode:  Longest Nice Substring Leetcode Solution

Difficulty: Easy

Topics: string sliding-window bit-manipulation hash-table  

Problem statement: Given a string s, find the longest substring which contain only unique characters consisting of both uppercase and lowercase letters. If no nice substring is found, return an empty string.

Example: Input: s = "YazaAay" Output: "aAa"

Solution: To solve this problem, we can use a sliding window approach. We start by initializing two pointers, left and right, at the beginning of the string. We then keep moving the right pointer to the right until we find a non-unique character. When this occurs, we move the left pointer to the right until the substring is once again "nice".

We can keep track of the longest nice substring found so far and update it whenever we find a longer one.

Here is the step-by-step algorithm:

  1. Initialize two pointers, left and right, both pointing to the beginning of the string.
  2. Initialize a variable, max_len, to 0 to keep track of the maximum length of a nice substring found so far.
  3. Initialize an empty set, char_set, to keep track of the unique characters in the current substring.
  4. Initialize an empty string, longest_substring, to keep track of the longest nice substring found so far.
  5. While the right pointer is less than the length of the string: a. Add the character at the right pointer to the char_set. b. If the char_set contains a non-unique character, move the left pointer to the right until the substring is once again "nice". c. If the length of the current substring is greater than max_len, update max_len and longest_substring. d. Move the right pointer one step to the right.
  6. Return longest_substring.

Here is the Python code implementing this algorithm:

def longestNiceSubstring(s: str) -> str: left, right = 0, 0 max_len = 0 longest_substring = "" while right < len(s): char_set = set() while right < len(s) and (s[right] not in char_set or s[right].swapcase() not in char_set): char_set.add(s[right]) right += 1 if len(char_set) == right - left: if right - left > max_len: max_len = right - left longest_substring = s[left:right] else: while s[left] in char_set and s[left].swapcase() in char_set: char_set.remove(s[left]) left += 1 left += 1 return longest_substring

Time Complexity: O(n^2) in the worst case where there are no unique characters in the string. In the best case, the time complexity is O(n) when the string contains only unique characters.

Space Complexity: O(n) to store the char_set.

Longest Nice Substring Solution Code

1