Data Structures & Algorithms · Module 2 · Lesson 21 min read

Strings & Two Pointers

Strings

A string is an array of characters. In Python, strings are immutable: every change creates a new string. To build one in a loop, collect parts in a list and "".join(parts) at the end, which is O(n) instead of O(n²).

The two-pointer technique

Use two indexes that move through the data, often from both ends toward the middle, or at different speeds. It turns many O(n²) "check every pair" problems into O(n).

When to use it

  • Checking palindromes
  • Finding a pair with a target sum in a sorted array
  • Reversing in place
  • Removing duplicates from a sorted array
  • Merging two sorted lists

Pair-sum example (sorted array)

  • Start with left = 0 and right = n - 1.
  • If the sum is too small, move left right (bigger numbers).
  • If it's too big, move right left (smaller numbers).
  • Stop when they meet.

Each step throws away one candidate, so it's O(n) with O(1) extra space.

Useful string tools

s.lower(), s.isalnum(), s[::-1] (reverse), s.split(), ord('a') / chr(97), collections.Counter(s) for letter counts.

Example

Python
def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        if not s[left].isalnum():
            left += 1
        elif not s[right].isalnum():
            right -= 1
        elif s[left].lower() != s[right].lower():
            return False
        else:
            left, right = left + 1, right - 1
    return True

def pair_with_sum(sorted_nums, target):
    left, right = 0, len(sorted_nums) - 1
    while left < right:
        total = sorted_nums[left] + sorted_nums[right]
        if total == target:
            return sorted_nums[left], sorted_nums[right]
        if total < target:
            left += 1
        else:
            right -= 1
    return None

print(is_palindrome("A man, a plan, a canal: Panama"))   # True
print(pair_with_sum([1, 2, 4, 7, 11, 15], 15))           # (4, 11)