Skip to content

Volume ITechnology

4.0.12 — String Basics: Palindrome, Vowels, Frequency, Case, Pangram ​

Classic · Easy · LeetCode 125 (Valid Palindrome), LeetCode 1832 (Pangram)

These are the short string questions that fill the first round of most service-company tests. Each one is a single loop over the characters. The skill being tested is handling the messy details: capital letters, spaces and punctuation.

The problem ​

  1. Is the string a palindrome? "Madam" is, if you ignore case.
  2. Count the vowels and the consonants.
  3. Count how often each character appears, and find the most frequent.
  4. Swap upper case and lower case without swapcase().
  5. Does the sentence use every letter of the alphabet?

1. Palindrome string ​

A palindrome reads the same both ways. The simple Python check compares the string with its reverse.

python
def is_palindrome(s: str) -> bool:
    s = s.lower()
    return s == s[::-1]

print(is_palindrome("Madam"))     # → True
print(is_palindrome("hello"))     # → False

This builds a reversed copy, so it uses O(n) extra memory. The two-index version needs none. Compare the outer pair, move inward, and stop at the first mismatch.

python
def is_palindrome_clean(s: str) -> bool:
    left, right = 0, len(s) - 1
    while left < right:
        if not s[left].isalnum():          # (1)
            left += 1
        elif not s[right].isalnum():
            right -= 1
        elif s[left].lower() != s[right].lower():   # (2)
            return False
        else:
            left += 1
            right -= 1
    return True

print(is_palindrome_clean("A man, a plan, a canal: Panama"))   # → True
print(is_palindrome_clean("race a car"))                       # → False

(1) isalnum() is True for letters and digits. Skip anything else, like spaces and commas, on either side.

(2) Compare ignoring case.

This is LeetCode 125. It gets its own page at 4.5.1. It can also stop early, at the first mismatch, while the reverse-and-compare version always builds the whole copy first.

2. Vowels and consonants ​

python
def count_vowels_consonants(s: str) -> tuple[int, int]:
    vowels = set("aeiou")               # (1)
    v = c = 0
    for ch in s.lower():
        if ch.isalpha():                # (2)
            if ch in vowels:
                v += 1
            else:
                c += 1
    return v, c

print(count_vowels_consonants("Hello, World!"))   # → (3, 7)

(1) A set answers "is this a vowel?" in one step. A string also works for five letters, but a set is the habit to build.

(2) Only letters count. Spaces, digits and punctuation are neither vowels nor consonants. Forgetting this check is the usual bug. It would count the comma, space and ! as consonants.

3. Character frequency ​

This is Move 2 from 4.0.0, the counter.

python
def char_frequency(s: str) -> dict[str, int]:
    freq = {}
    for ch in s:
        freq[ch] = freq.get(ch, 0) + 1
    return freq

def most_frequent(s: str) -> str:
    freq = char_frequency(s)
    return max(freq, key=freq.get)      # (1)

print(char_frequency("hello"))      # → {'h': 1, 'e': 1, 'l': 2, 'o': 1}
print(most_frequent("programming")) # → r

(1) max over the keys, comparing them by their counts. When counts tie, max keeps the first one it saw. In "programming", r, g and m each appear twice. r comes first, so it wins. Python dictionaries remember the order keys were added, since Python 3.7.

With the standard library: collections.Counter(s).most_common(1) returns [('r', 2)].

If only lowercase letters appear, a list of 26 counts works instead of a dictionary. Position 0 is a, position 25 is z, and ord(ch) - ord('a') finds the position. That is the same character-code trick from 4.0.9. Two words are anagrams, built from the same letters, exactly when their 26 counts match. 4.4.2 solves that one.

4. Toggle case without swapcase() ​

In ASCII, 'A' is 65 and 'a' is 97. Every capital letter is exactly 32 below its small letter.

python
def toggle_case(s: str) -> str:
    out = []
    for ch in s:
        if "a" <= ch <= "z":
            out.append(chr(ord(ch) - 32))   # small to capital
        elif "A" <= ch <= "Z":
            out.append(chr(ord(ch) + 32))   # capital to small
        else:
            out.append(ch)                  # leave everything else alone
    return "".join(out)

print(toggle_case("Hello World 42"))   # → hELLO wORLD 42

Why 32? The people who designed ASCII in 1963 placed the two alphabets exactly 32 apart on purpose. 32 is a power of two, so the difference is a single bit. In binary, A is 1000001 and a is 1100001. Only the bit worth 32 differs. So chr(ord(ch) ^ 32) flips the case of any letter in one step. That XOR is the same operator as the swap in 4.0.1.

This trick only works for the English letters A to Z. For other alphabets, use Python's swapcase(), upper() and lower(), which know the rules of every language.

5. Pangram ​

A pangram uses every letter of the alphabet at least once. "The quick brown fox jumps over the lazy dog" is the famous one. Typists have used it since the 1800s to test every key.

python
def is_pangram(s: str) -> bool:
    letters = {ch for ch in s.lower() if "a" <= ch <= "z"}   # (1)
    return len(letters) == 26                              # (2)

print(is_pangram("The quick brown fox jumps over the lazy dog"))   # → True
print(is_pangram("Hello world"))                                   # → False

(1) Collect the distinct letters in a set. Repeats disappear automatically.

(2) A pangram has all 26.

6. Clean a string: remove spaces and special characters ​

python
s = "Hello, World! 2026"
print("".join(ch for ch in s if ch.isalnum()))   # → HelloWorld2026
print(s.replace(" ", ""))                         # → Hello,World!2026
print(" ".join(s.split()))                        # → Hello, World! 2026

The first keeps only letters and digits. The second removes spaces only. The third squeezes every run of spaces into one, which 4.0.11 used for reversing words.

Complexity ​

Every check here is one pass, O(n) time. The palindrome two-index check uses O(1) extra memory. The counters use memory for one entry per distinct character. For the English alphabet, that is at most 26 entries, which counts as O(1).

What the interviewer will push on ​

These are the questions that usually come right after you solve it. Each one has a short, plain answer you can say out loud.

"Check a palindrome, ignoring spaces, commas and capital letters." Use two indexes, one at each end. Skip any character that is not a letter or digit. Compare the rest with .lower(). This needs no cleaned copy of the string.

"Why does your vowel count say a comma is a consonant?" Because only letters should be counted. Check ch.isalpha() first. Spaces, commas and digits are neither vowels nor consonants.

"Find the most frequent character. What if two are tied?" Count with a dictionary, then take the key with the biggest count. With max, the first character seen wins a tie. Just say which one your code picks.

"Swap upper and lower case without built-in functions." In ASCII, every small letter is exactly 32 more than its capital letter. So add 32 to go from capital to small, and subtract 32 to go back.

One thing to volunteer: "If the string has only lowercase letters, a list of 26 counts is enough. It is smaller and faster than a dictionary."

Next: 4.0.13 First Non-Repeating Character and Removing Duplicates. The counter again, plus a second pass.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Volume I — Technology
Part 0 — Retention & Notation
Part 1 — Foundations of Computation
Part 2 — Operating Systems
2.1 The Kernel
2.2 Processes
2.3 Threads & Scheduling
2.4 Concurrency Under the Hood
2.5 Memory Management
2.6 File Systems
2.7 Input/Output
2.8 Linux for Engineers
2.9 Windows & macOS in Practice
Part 3 — Languages, Compilers & Runtimes
3.6 JavaScript & V8
3.7 TypeScript
3.8 Node.js Internals
3.13 Python & CPython
3.14 FastAPI & Production Python
Part 4 — Data Structures & Algorithms
4.0 Classic Problems — Before NeetCode
4.4 Arrays & Hashing — Problems
4.5 Two Pointers
4.6 Sliding Window
4.8 Stack — Problems
4.9 Linked List — Problems
4.11 Binary Search — Problems
4.13 Trees
4.14 Tree — Problems
4.15 Trie — Problems
4.17 Heap — Problems
4.18 Backtracking — Problems
4.19 Graphs
4.20 Graph — Problems
4.21 Advanced Graph — Problems
4.23 1-D DP — Problems
4.24 2-D DP — Problems
4.26 Greedy — Problems
4.27 Interval — Problems
4.28 Math & Geometry — Problems
4.30 Bit Manipulation — Problems
Part 5 — Networking & the Web
5.3 IP
5.4 Transport
5.6 HTTP
Part 6 — Frontend Engineering
6.1 Browser Internals
6.2 HTML & CSS Mastery
6.3 JavaScript in the Browser
6.4 React, from First Component to Full Shop
6.5 Frameworks & Rendering
6.8 UI Engineering & Patterns
Part 7 — Databases & Storage
7.2 SQL Mastery
7.3 Storage Engine Internals
7.4 Transactions
7.5 NoSQL Taxonomy
7.8 Analytics & Big Data
Part 8 — Security, Identity & Cryptography
8.2 Cryptography
8.3 Protocols of Trust
8.4 Identity: AuthN & AuthZ
8.5 Application Security
8.6 Infrastructure Security
Part 9 — Software Design (LLD)
9.2 OOP Foundations
9.3 Design Principles
9.4 Design Patterns
9.5 Concurrency
9.6 API Design
9.7 LLD Interview Machines
9.9 Node/Express Production Playbook
Part 10 — Distributed Systems & HLD
10.7 Consistency & Consensus
10.8 Messaging & Microservices
10.14 Caching
Building blocks from the design seat
Part 11 — System Design Case Studies
Part 12 — AI & ML Engineering
12.1 What AI Engineering Is
12.2 The Math You Need
12.3 Classical Machine Learning
12.4 Data for ML
12.5 Deep Learning
12.6 Embeddings & Vector Search
12.7 Transformers & LLMs
12.8 Building with LLMs
12.9 Retrieval-Augmented Generation
12.10 Agents
12.11 Adapting Models
12.12 Production AI
12.13 Multimodal AI
12.14 AI Security & Governance
12.15 Case Studies & Capstone
Part 13 — Cloud, DevOps & Infrastructure
13.11 Git, from First Commit to Team Workflow
Part 14 — Containers: Docker & Kubernetes
14.1 Foundations
14.2 Docker
14.3 Kubernetes
14.4 Kubernetes on Azure
Part 15 — The Craft & Career
Nothing picked yet