Python Programming Mastery Course Advanced

Excellent — now we move from API familiarity to problem-solving dominance.

STRING MASTERY – DAY 2 is 100% coding-interview driven.
No fluff. No repetition. Just patterns + traps + solutions.


🔥 STRING MASTERY — DAY 2

Sliding Window, Hashing Patterns & Tricky Interview Problems

Image
Image
Image
Image

🧠 DAY 2 GOAL

By the end of today, you will:

  • Instantly recognize string problem patterns
  • Solve 90% of string interview questions
  • Avoid hidden O(n²) traps
  • Explain solutions confidently (interview expectation)

🧩 CORE STRING PATTERNS (MEMORIZE THESE)

Every string interview problem reduces to one of these:

PatternUsed For
Frequency MapAnagram, counts
Sliding WindowSubstrings, windows
Two PointersPalindrome, reverse
Hash SetUniqueness
StackParentheses
GreedyCompression, removal

If you identify the pattern → solution is obvious.


1️⃣ SLIDING WINDOW — THE MOST IMPORTANT PATTERN

Used when:

  • Substring
  • Continuous window
  • Longest / shortest
  • Condition-based window

🔥 Q1. Longest Substring Without Repeating Characters

(Asked everywhere: FAANG, startups, services)

Problem

"abcabcbb" → 3 ("abc")

❌ Brute Force (DO NOT DO)

  • All substrings
  • O(n²)

✅ Optimal (Sliding Window + Set)

def longest_unique_substring(s):
    seen = set()
    left = 0
    max_len = 0

    for right in range(len(s)):
        while s[right] in seen:
            seen.remove(s[left])
            left += 1

        seen.add(s[right])
        max_len = max(max_len, right - left + 1)

    return max_len

Interview Explanation

  • Window expands with right
  • Shrinks when duplicate found
  • Always valid window

✔ Time: O(n)
✔ Space: O(k)


2️⃣ FREQUENCY MAP PATTERN

Used when:

  • Counting
  • Matching characters
  • Anagrams
  • First unique element

🔥 Q2. Check Anagram

"listen", "silent" → True

Best Answer (Pythonic)

from collections import Counter

def is_anagram(a, b):
    return Counter(a) == Counter(b)

Interview Tip

Mention:

  • Hashing
  • Equality comparison
  • O(n)

🔥 Q3. First Non-Repeating Character

"swiss" → 'w'

Solution

from collections import Counter

def first_unique(s):
    freq = Counter(s)
    for ch in s:
        if freq[ch] == 1:
            return ch
    return None

🧠 Why loop original string?

  • Preserves order

3️⃣ TWO POINTER PATTERN

Used when:

  • Palindrome
  • Reverse
  • Compare from both ends

🔥 Q4. Valid Palindrome

(ignore spaces, punctuation, case)

"A man, a plan, a canal: Panama" → True

Optimal Solution

def is_palindrome(s):
    left, right = 0, len(s) - 1

    while left < right:
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1

        if s[left].lower() != s[right].lower():
            return False

        left += 1
        right -= 1

    return True

✔ O(n)
✔ No extra memory


4️⃣ STRING COMPRESSION (GREEDY + BUILDER)

🔥 Q5. Compress String

"aabcccccaaa" → "a2b1c5a3"

❌ Trap

Using += in loop → O(n²)


✅ Correct

def compress(s):
    res = []
    count = 1

    for i in range(1, len(s)):
        if s[i] == s[i-1]:
            count += 1
        else:
            res.append(s[i-1] + str(count))
            count = 1

    res.append(s[-1] + str(count))
    return "".join(res)

5️⃣ STRING SPLIT VS PARTITION (INTERVIEW TRICK)

🔥 Q6. Parse key:value safely

s = "user:admin"

Best Answer

key, _, value = s.partition(":")

Why interviewers love this:

  • No exceptions
  • No list allocation
  • Always 3 parts

6️⃣ SUBSTRING SEARCH TRAPS

🔥 Q7. Count Overlapping Substrings

"aaaa", "aa" → 3

count() fails

"aaaa".count("aa")  # 2 ❌

✅ Correct

def count_overlap(s, sub):
    count = 0
    for i in range(len(s) - len(sub) + 1):
        if s[i:i+len(sub)] == sub:
            count += 1
    return count

7️⃣ HASH SET — UNIQUENESS CHECK

🔥 Q8. All characters unique?

def all_unique(s):
    return len(set(s)) == len(s)

Explain:

  • Hash set
  • O(n)

🧠 STRING INTERVIEW MENTAL MAP

When you see a string problem:

  1. Substring? → Sliding window
  2. Counting? → Frequency map
  3. Reverse / compare? → Two pointers
  4. Build string? → List + join
  5. Split key:value? → partition

If you say this out loud → interviewer knows you’re senior.


📝 DAY 2 ASSIGNMENT (VERY IMPORTANT)

1️⃣ Predict output (NO RUNNING)

print("aaaa".count("aa"))

2️⃣ Coding (Write clean code)

def longest_repeating_char_replacement(s, k):
    """
    LeetCode hard-favorite
    """

(Hint: sliding window + max frequency)


3️⃣ Explain (Interview style)

Why this is bad:

s = ""
for x in data:
    s += x

🔜 DAY 3 PREVIEW (FINAL STRING DAY 🔥)

STRING MASTERY – DAY 3

  • Unicode & encoding edge cases
  • casefold vs lower
  • Interning behavior
  • 20 rapid-fire string interview questions
  • Speed tricks interviewers love

👉 Say “CONTINUE STRING MASTERY – DAY 3” when ready.