← Back to Tutorials

2. Strings (Days 15—29)

Valid Palindrome

def isPalindrome(s: str) -> bool:
    l, r = 0, len(s) - 1
    while l < r:
        while l < r and not s[l].isalnum(): l += 1
        while l < r and not s[r].isalnum(): r -= 1
        if s[l].lower() != s[r].lower(): return False
        l += 1; r -= 1
    return True

Longest Common Prefix

// Java
public String longestCommonPrefix(String[] strs) {
    if (strs.length == 0) return "";
    String prefix = strs[0];
    for (int i = 1; i < strs.length; i++) {
        while (strs[i].indexOf(prefix) != 0) {
            prefix = prefix.substring(0, prefix.length() - 1);
        }
    }
    return prefix;
}

Valid Anagram

def isAnagram(s: str, t: str) -> bool:
    if len(s) != len(t): return False
    counts = [0] * 26
    for c in s: counts[ord(c) - 97] += 1
    for c in t: counts[ord(c) - 97] -= 1
    return all(c == 0 for c in counts)

More Problems

ProblemPatternComplexity
Reverse StringTwo pointers, swapO(n), O(1)
Isomorphic StringsCharacter mapping, bijectionO(n), O(1)
Add StringsSchoolbook addition, carryO(n), O(n)
FizzBuzzModulo, string buildingO(n), O(1)
Roman to IntegerLeft-to-right, subtractive ruleO(n), O(1)
✏️ Exercise: Implement Valid Palindrome (ignore non-alphanumeric) and Longest Common Prefix. Write unit tests for edge cases (empty string, single char, all same).