Course contentsShow
← Computer Science
Lesson 268 of 2,8726. Arrays and Basic CollectionsFree lesson

Common String Algorithms

Implementing fundamental string operations like reversing, palindrome checking, and character frequency counting.

Common String Algorithms

What you'll learn: You'll implement three foundational string operations—reversing, palindrome checking, and counting character frequencies—using only loops and character-level access.

The Core Idea

Strings are just arrays of characters, so the array operations you've mastered transfer directly to solving classic string problems. These three algorithms appear constantly in real-world code:

  1. Reversing a string – swap characters from both ends moving inward
  2. Checking palindromes – verify if a string reads the same forwards and backwards
  3. Counting character frequencies – track how many times each character appears

Think of these like recipes: once you know the pattern, you can apply it anywhere strings need processing.

Reversing a String

Create a new array, loop backward through the original string, and copy each character:

result = empty array
for i from length-1 down to 0:
    result.append(string[i])

Palindrome Checking

Compare characters from opposite ends, moving inward. If any pair mismatches, it's not a palindrome:

left = 0
right = length - 1
while left < right:
    if string[left] != string[right]:
        return false
    left = left + 1
    right = right - 1
return true

Character Frequency Counting

Use an array of size 256 (for ASCII) where each index represents a character code. Loop through the string and increment counters:

frequency = array of 256 zeros
for each character in string:
    index = character code
    frequency[index] = frequency[index] + 1

Now frequency[65] tells you how many times 'A' appeared (since 'A' is ASCII 65).

Key Takeaway: String algorithms build on array operations—reversing uses two-pointer swapping, palindromes use symmetric comparison, and frequency counting uses arrays as counters indexed by character codes.