ποΈ Day 43 Bonus: Strings β Manipulation and Pattern Matching Techniques
π§ Concept Deep Dive
Strings are everywhere in programmingβAPI responses, user input, config files. Today, we focus on how to manipulate strings efficiently in TypeScript and understand patterns like sliding window and character counting.
π Core Concepts
Basic String Operations
const str = "hello world";
str.length; // 11
str.toUpperCase(); // "HELLO WORLD"
str.toLowerCase(); // "hello world"
str.includes("world"); // true
str.indexOf("o"); // 4
str.split(" "); // ["hello", "world"]
str.replace("world", "TS"); // "hello TS"String Immutability
Strings in JavaScript/TypeScript are immutableβmodifying a string creates a new one.
let original = "abc";
let modified = original.replace("a", "z");
// original remains "abc"π§© Pattern Matching Techniques
Sliding Window Technique
Used to solve problems involving substrings or character frequency.
Example: Longest Substring Without Repeating Characters
function lengthOfLongestSubstring(s: string): number {
let set = new Set();
let left = 0, right = 0, maxLen = 0;
while (right < s.length) {
if (!set.has(s[right])) {
set.add(s[right]);
maxLen = Math.max(maxLen, right - left + 1);
right++;
} else {
set.delete(s[left]);
left++;
}
}
return maxLen;
}Input: "abcabcbb" β Output: 3 ("abc")
Character Frequency Map
function characterFrequency(s: string): Record<string, number> {
const freq: Record<string, number> = {};
for (const char of s) {
freq[char] = (freq[char] || 0) + 1;
}
return freq;
}Input: "banana" β Output: { b:1, a:3, n:2 }
π¨ ASCII Visualization
s = "abcabcbb"
β
left
β
right
Set: keeps track of unique characters in the window
Slide left/right depending on duplicatesποΈ Homework (LeetCode-style)
Problem 1: Valid Anagram
function isAnagram(s: string, t: string): boolean {
if (s.length !== t.length) return false;
const count: Record<string, number> = {};
for (let i = 0; i < s.length; i++) {
count[s[i]] = (count[s[i]] || 0) + 1;
count[t[i]] = (count[t[i]] || 0) - 1;
}
return Object.values(count).every(v => v === 0);
}Input: s = "anagram", t = "nagaram" β Output: true
Problem 2: Reverse Words in a String
function reverseWords(s: string): string {
return s.trim().split(/\s+/).reverse().join(" ");
}Input: " hello world " β Output: "world hello"
Problem 3: Check for Palindrome
function isPalindrome(s: string): boolean {
const cleaned = s.toLowerCase().replace(/[^a-z0-9]/g, "");
let left = 0, right = cleaned.length - 1;
while (left < right) {
if (cleaned[left] !== cleaned[right]) return false;
left++;
right--;
}
return true;
}Input: "A man, a plan, a canal: Panama" β Output: true
π Summary
- Strings are immutable and full of built-in methods.
- Master pattern techniques like sliding windows and frequency maps.
- Practice substring problems for interviews.