DSA Strings

A string is a sequence of characters such as letters, digits, and symbols. Names, messages, passwords, and web addresses are all strings. Programs read and change strings constantly, so knowing how they work gives you a strong base for many problems.

Picture a row of lockers, each holding exactly one character. Every locker has a number starting from zero. That number is the index, and it lets you open any locker instantly.

How a String Looks in Memory

String: "HELLO"

Index:   0    1    2    3    4
       +----+----+----+----+----+
       | H  | E  | L  | L  | O  |
       +----+----+----+----+----+
Negative: -5   -4   -3   -2   -1

Python accepts negative indexes. The index -1 points to the last character, which saves you from calculating the length.

Basic String Operations

Accessing Characters

word = "HELLO"
print(word[0])    # H
print(word[-1])   # O
print(len(word))  # 5

Access by index takes O(1) time. Finding the length takes O(1) because Python stores it.

Slicing

A slice cuts out a piece of the string. The start index is included and the end index is excluded.

word = "HELLO"
print(word[1:4])   # ELL
print(word[:2])    # HE
print(word[2:])    # LLO

Slicing copies the characters, so it takes O(k) time for a slice of length k.

Joining and Splitting

sentence = "learn data structures"
parts = sentence.split(" ")
print(parts)             # ['learn', 'data', 'structures']
print("-".join(parts))   # learn-data-structures

Strings Cannot Change

Python strings are immutable. After you create a string, its characters stay fixed. Code that tries to change one character raises an error.

word = "HELLO"
word[0] = "J"      # TypeError

Every edit builds a brand new string. Adding characters inside a long loop creates many temporary strings and slows the program. Collect the pieces in a list and join them once at the end.

pieces = []
for i in range(5):
    pieces.append(str(i))
result = "".join(pieces)   # "01234"

Classic Problem: Reverse a String

Slicing with a step of -1 walks the string backward.

def reverse_text(text):
    return text[::-1]

print(reverse_text("DATA"))   # ATAD

Classic Problem: Palindrome Check

A palindrome reads the same forward and backward. Words like "level" and "radar" qualify.

def is_palindrome(text):
    return text == text[::-1]

print(is_palindrome("level"))   # True
print(is_palindrome("tree"))    # False

Classic Problem: Anagram Check

Two words are anagrams when they contain the same letters in any order. "listen" and "silent" are a pair. Counting letters solves the problem in O(n) time.

def is_anagram(a, b):
    if len(a) != len(b):
        return False
    counts = {}
    for ch in a:
        counts[ch] = counts.get(ch, 0) + 1
    for ch in b:
        if ch not in counts or counts[ch] == 0:
            return False
        counts[ch] -= 1
    return True

print(is_anagram("listen", "silent"))   # True
Counting "listen":
l:1  i:1  s:1  t:1  e:1  n:1

Reading "silent" subtracts one from each letter.
Every count ends at 0, so the words match.

Classic Problem: Count Vowels

def count_vowels(text):
    total = 0
    for ch in text.lower():
        if ch in "aeiou":
            total += 1
    return total

print(count_vowels("Data Structures"))   # 5

Time Cost of Common Operations

  • Access by index takes O(1).
  • Search for a character takes O(n).
  • Concatenation takes O(n) because Python copies both strings.
  • Comparison takes O(n) in the worst case.

Real-Life Uses of Strings

Search engines compare typed words against billions of pages. Text editors check spelling by matching words against a dictionary. Messaging apps scan and format text as people type. Login forms verify that a password meets the length and character rules. Each of these tasks depends on the string operations covered above.

Common Mistakes

Many learners expect word.upper() to change the original string. The method returns a new string and leaves the old one alone. Store the result in a variable to keep it. Off-by-one errors in slices form another frequent trap, because the end index is excluded. Print small slices to confirm the exact range.

Practice Ideas

Try counting how many times each letter appears in a sentence. Write a function that checks whether a word starts and ends with the same letter. Build a program that converts a sentence to title case without calling the built-in method. Small exercises like these train your eye for indexes, slices, and loops.

Key Points

  • A string stores characters in order, and each character has an index.
  • Negative indexes count from the end.
  • Slicing returns a new string and leaves the original untouched.
  • Strings are immutable, so edits create new strings.
  • Use a list and join() to build long strings efficiently.
  • Palindrome and anagram checks appear often in practice problems.