Skip to content

Beginner: foundations · Arrays and strings · topic 8 of 61 · 35 min

Strings: building, comparing and counting

Explanation

A string is a sequence of characters that cannot be changed after it is made (it is immutable). Most string problems use the same tools as arrays: two pointers from both ends (palindromes), counting characters (anagrams), and building the answer in a list and joining it once. ord() and chr() convert between characters and numbers.

Strings are immutable sequences

A string is an ordered sequence of characters, so indexing s[i] is O(1) and len(s) is O(1), just like a list. The big difference is that strings are immutable: you cannot change a character in place. s[0] = "J" raises TypeError: 'str' object does not support item assignment. Every "change" creates a new string, which costs O(n).

For in-place style work, turn the string into a list of characters with list(s), change the list, and join it back with "".join(chars). Both conversions are O(n).

Characters are numbers underneath

Every character has a number called its code point. ord(c) gives the number and chr(n) gives the character back: ord("A") is 65, ord("a") is 97, ord("0") is 48 and chr(97) is "a". The letters a to z have consecutive numbers, so ord(c) − ord("a") turns a lowercase letter into 0 to 25, which is handy for a count array of size 26.

Palindromes: two ends moving inwards

A palindrome reads the same forwards and backwards, like "madam" or "racecar". s == s[::-1] works but builds a reversed copy, O(n) extra space. The two-pointer way compares s[left] with s[right] and moves both inwards: O(n) time and O(1) extra space. Real problems often say "ignore spaces, punctuation and case"; then skip characters that are not letters or digits (str.isalnum()) and compare lowercase.

python
def is_pal(s):
    left, right = 0, len(s) - 1
    while left < right:
        if s[left] != s[right]:
            return False
        left += 1
        right -= 1
    return True

print(is_pal("racecar"), is_pal("rupee"))   # Output: True False

Anagrams: same letters, same counts

Two words are anagrams if one is a rearrangement of the other, like "listen" and "silent". Sorting both and comparing is simple, O(n log n). Counting is faster: count each character of the first word, subtract for the second, and check all counts are zero. That is O(n) time; the counts take O(k) space, where k is the number of different characters.

python
from collections import Counter

print(sorted("listen") == sorted("silent"))     # Output: True
print(Counter("listen") == Counter("silent"))   # Output: True
print(Counter("aab"))                           # Output: Counter({'a': 2, 'b': 1})
Counter is a dict that counts items.

Building strings and useful methods

As in Module 1, never grow a long string with += in a loop. Collect pieces in a list and join once. Common methods, each O(n) in the length of the string:

MethodWhat it doesExample result
s.lower(), s.upper()Change case"Pune".lower() → "pune"
s.strip()Remove spaces at both ends" hi ".strip() → "hi"
s.split()Split on any run of spaces"a b".split() → ["a", "b"]
" ".join(words)Join with a separator" ".join(["a", "b"]) → "a b"
s.isalnum(), s.isdigit()Check the kind of characters"a1".isalnum() → True
s.find(t)Index of t, or −1 if missing"banana".find("na") → 2
s.count(t)Non-overlapping occurrences"banana".count("a") → 3

A note on Unicode and Hindi text

Python strings are sequences of Unicode code points, not of what you see as letters. "नमस्ते" looks like 3 or 4 letters, but len("नमस्ते") is 6, because the vowel signs and the half-letter mark (virama) are separate code points. Reversing such text code point by code point breaks how it displays. Interview problems usually use plain English letters, but say this if text in Indian languages is involved. In JavaScript, .length counts UTF-16 units, so "नमस्ते".length is also 6, while an emoji such as "😀" has length 2 in JavaScript and 1 in Python.

Common mistakes

  • Trying to change a character with s[i] = c. Fix: convert to a list, change it, then join.
  • Forgetting to normalise case or skip punctuation in palindrome problems. Fix: use .lower() and .isalnum(), and ask the interviewer what to ignore.
  • Checking anagrams by length only, or with sets (sets lose counts: "aab" and "abb" have the same set). Fix: compare full counts.
  • Using is to compare strings. Fix: always use == for string values.
  • Off-by-one in two pointers, such as while left <= right with extra moves. Fix: while left < right is enough; the middle character of an odd-length string needs no partner.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Strings: building, comparing and counting · 1/8

Strings

This lesson covers strings: why they cannot change, how to compare and count characters, and how to build new strings fast.

Prefer a video by a teacher? Find free videos on “string palindrome anagram problems python interview two pointers” on YouTube ↗

In real life: Cleaning names for KYC matching

Banks and fintech apps compare the name typed by a customer with the name on an identity document. "Ravi Kumar." and "ravi kumar" should match. A first step is normalising: lowercase, keep only letters and spaces, and collapse extra spaces. Real systems also handle initials, spelling variants and Indian-language scripts, but the core string tools are the same ones in this lesson.

python
def normalise(name):
    kept = [c.lower() for c in name if c.isalpha() or c == " "]
    return " ".join("".join(kept).split())

print(normalise("Ravi  Kumar."))
print(normalise("ravi kumar") == normalise("Ravi  Kumar."))
Shows ravi kumar, then True.

Practice (0/4 done)

Task 1 · Code · Python

Write is_palindrome(s) that returns True if s reads the same forwards and backwards when you IGNORE every character that is not a letter or digit, and ignore case. Use two pointers (O(1) extra space). Example: is_palindrome("A man, a plan, a canal: Panama") returns True.

Task 2 · Code · Python

Write is_anagram(s, t) that returns True if t uses exactly the same characters as s, each the same number of times (case matters, so "D" and "d" differ). Make it O(n) by counting with a dictionary or collections.Counter, not by sorting. Example: is_anagram("listen", "silent") returns True.

Task 3 · Code · Python

Write compress(s) that replaces each run of the same character with the character followed by the run length. Example: compress("aaabcc") returns "a3b1c2". Runs can be longer than 9 ("z" twelve times becomes "z12"). An empty string gives "". Build the result with a list and "".join, not +=.

Task 4 · Code · Javascript

Write reverseWords(s) in JavaScript. Words are separated by one or more spaces, and s may have spaces at the start or end. Return the words in reverse order joined by single spaces, with no spaces at the ends. Example: reverseWords(" the sky is blue ") returns "blue is sky the". An empty or all-space string gives "".

Quick quiz

Question 1

1.What happens with s = "cat" followed by s[0] = "b"?

Question 2

2.What is ord("c") − ord("a")?

Question 3

3.Why is comparing set("aab") with set("abb") a wrong anagram check?

Question 4

4.What is the extra space of the two-pointer palindrome check?

Question 5

5.What does len("नमस्ते") return in Python?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What happens with s = "cat" followed by s[0] = "b"?

Answer: A TypeError, because strings are immutable

Strings cannot be changed in place. Build a new string instead, for example "b" + s[1:].

What is ord("c") − ord("a")?

Answer: 2

The letters have consecutive code points, so c is 2 places after a.

Why is comparing set("aab") with set("abb") a wrong anagram check?

Answer: Sets keep only which characters appear, not how many times

Both sets are {"a", "b"}, but the counts differ, so they are not anagrams.

What is the extra space of the two-pointer palindrome check?

Answer: O(1)

It only keeps two index variables; s == s[::-1] would need an O(n) copy.

What does len("नमस्ते") return in Python?

Answer: 6

len counts Unicode code points: four consonants plus a vowel sign and a virama make 6.

What does strings.Fields(" a b ") return?Related

Answer: [a b]

Fields splits on runs of white space and drops empty parts.

From Strings, bytes and runes

What marks the end of a C string?Related

Answer: The null character '\0'

C functions read characters until they meet '\0'.

From Text: C strings and std::string

What does len("India 2024") give?Related

Answer: 10

India has 5 characters, the space is 1 and 2024 is 4 more: 5 + 1 + 4 = 10.

From Strings: working with text

What marks the end of a C string?Related

Answer: The null character \0

Every string function stops at \0.

From Strings are char arrays

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 2 more topics in “Arrays and strings” before its exam: Maximum subarray: Kadane's algorithm, 2-D arrays (matrices).
  2. Module 2 exam: Arrays and strings · 14 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Hashing, two pointers and sliding window. 61 topics left in the course before the final exam.

← Previous: Prefix sums and difference arrays