Unit 7 Session 2 (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
HAPPY CASE
Input: "YazaAay"
Output: "aAa"
Explanation: "aAa" is the longest "nice" substring.
EDGE CASE
Input: "Bb"
Output: "Bb"
Explanation: The whole string is "nice" because it contains both uppercase and lowercase 'b'.
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
This problem is a variation on searching for patterns within strings, suitable for a divide and conquer approach:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Divide the string into halves, recursively find the longest "nice" substring in each half, and return the longest of them.
1) Check if the current string segment is "nice."
2) If not, split the string in half.
3) Recursively find the longest "nice" substring in each half.
4) Return the longer of the two "nice" substrings.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
def longestNiceSubstringRec(s: str) -> str:
if len(s) < 2:
return ''
seen = set(s)
for i, c in enumerate(s):
if c.swapcase() not in seen:
prefix = longestNiceSubstring(s[:i])
suffix = longestNiceSubstring(s[i + 1:])
return max(prefix, suffix, key=len)
return s
Alternative solution without recursion:
def longestNiceSubstring(s: str) -> str:
n = len(s)
ans = ''
for i in range(n):
lower = upper = 0
for j in range(i, n):
if s[j].islower():
lower |= 1 << (ord(s[j]) - ord('a'))
else:
upper |= 1 << (ord(s[j]) - ord('A'))
if lower == upper and len(ans) < j - i + 1:
ans = s[i : j + 1]
return ans
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Evaluate the performance of your algorithm and state any strong/weak or future potential work.