Strings are everywhere—from passwords to DNA sequences. Mastering string manipulation unlocks powerful algorithms in pattern matching, text processing, and optimization.
1️⃣ What is a String?
A string is a sequence of characters. In most languages, strings are immutable and indexed like arrays.
Python Example:
s = "hello"C++ Example:
print(s[1]) # Output: 'e'
string s = "hello";Java Example:
cout << s[1]; // Output: 'e'
String s = "hello";2️⃣ Common String Operations:
System.out.println(s.charAt(1)); // Output: 'e'
• Concatenation
• Substring
• Comparison
• Reversal
• Search
• Replace
Python – Reversal:
s = "hello"C++ – Substring:
print(s[::-1]) # Output: 'olleh'
string s = "hello";Java – Replace:
cout << s.substr(1, 3); // Output: 'ell'
String s = "hello";3️⃣ Pattern Matching – Naive vs Efficient
System.out.println(s.replace("l", "x")); // Output: 'hexxo'
Naive Approach: Check every substring
Efficient: Use hashing or KMP (Knuth-Morris-Pratt)
Python – Naive Pattern Search:
def search(text, pattern):4️⃣ Hashing for Fast Lookup
for i in range(len(text) - len(pattern) + 1):
if text[i:i+len(pattern)] == pattern:
print(f"Found at index {i}")
search("abracadabra", "abra") # Output: Found at index 0, 7
Use hash maps to store character counts, frequencies, or indices.
Python – First Unique Character:
from collections import Counter5️⃣ Two Pointers Technique
def first_unique_char(s):
count = Counter(s)
for i, ch in enumerate(s):
if count[ch] == 1:
return i
return -1
print(first_unique_char("leetcode")) # Output: 0
Used for problems like palindromes, anagrams, or substring windows.
Python – Valid Palindrome:
def is_palindrome(s):6️⃣ Practice Tasks:
s = ''.join(filter(str.isalnum, s)).lower()
left, right = 0, len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
print(is_palindrome("A man, a plan, a canal: Panama")) # Output: True
✅ Implement pattern search (naive)
✅ Find first non-repeating character
✅ Check if a string is a palindrome
✅ Use two pointers to reverse vowels in a string
✅ Try Rabin-Karp or KMP for pattern matching
💬 Double Tap ❤️ for Part-5