Skip to content

What a Nice String

Samuel Reque Zambrana edited this page Aug 10, 2024 · 3 revisions

Unit 7 Session 2 (Click for link to problem statements)

Problem Highlights

  • 💡 Difficulty: Medium
  • Time to complete: 20 mins
  • 🛠️ Topics: Divide and Conquer, Recursion, Strings

1: U-nderstand

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?
  • Q: What should the function return if no "nice" substring exists?
    • A: If no "nice" substring exists, the function should return an empty string.
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'.

2: M-atch

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:

  • Splitting the string and finding the longest "nice" substring in each part, then comparing results.

3: P-lan

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

  • Overlooking substrings that cross the middle of the string segment.
  • Not correctly identifying all characters in both cases (upper and lower).

4: I-mplement

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

5: R-eview

Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.

  • Test the function with input "YazaAay" to ensure it returns "aAa".
  • Validate with input "Bb" to confirm it returns "Bb" as expected.

6: E-valuate

Evaluate the performance of your algorithm and state any strong/weak or future potential work.

  • Time Complexity: Potentially O(n^2) in the worst case, depending on the distribution of characters and the length of the string as the entire string is checked at each recursion level.
  • Space Complexity: O(n) for the recursion stack, especially if the recursion depth approaches the length of the string.
Clone this wiki locally