π€ Strings
One-line summary: Immutable character sequences β master sliding window, two pointers, and hashing on strings for O(n) solutions to substring/pattern problems.
π Visual Learningβ
String Processing Techniquesβ
Visualization of sliding window technique for substring problems and pattern matching
String Algorithm Animationsβ
Interactive demonstration of string manipulation algorithms and optimization techniques
Two Pointers on Stringsβ
Visual guide to using two pointers for palindrome checking and string reversal
String Hashing Visualizationβ
Understanding how string hashing works for fast substring search and pattern matching
π― Core Conceptsβ
String Fundamentalsβ
- Immutability: Strings in JavaScript are immutable β operations create new strings
- Character Access: Use
s[i]ors.charAt(i)to access characters - Length:
s.lengthgives the number of characters - Conversion:
s.split('')converts string to character array for manipulation
Essential String Operationsβ
// Basic operations
s.charAt(i) // Get character at index i
s.charCodeAt(i) // Get ASCII/Unicode value
String.fromCharCode(c) // Convert ASCII to character
s.slice(start, end) // Extract substring
s.substring(start, end) // Similar to slice
s.indexOf(substr) // Find first occurrence
s.toLowerCase() // Convert to lowercase
s.toUpperCase() // Convert to uppercase
Key String Patternsβ
- Anagram Detection: Sort characters or use frequency counting
- Palindrome Check: Two pointers from ends moving inward
- Substring Search: Sliding window or KMP algorithm
- Pattern Matching: Regular expressions or manual parsing
When to Use String Algorithms?β
β Use when you need:
- Text processing and manipulation
- Pattern matching and searching
- Anagram or palindrome detection
- Substring operations
- Character frequency analysis
β Avoid when:
- Working with purely numerical data
- Simple boolean operations
- Array manipulations without text context
π§ Essential Patterns & Templatesβ
1οΈβ£ Anagram Detection - Two Approachesβ
Method 1: Sorting (Simple but O(n log n))
function isAnagram(s, t) {
if (s.length !== t.length) return false;
return s.split('').sort().join('') === t.split('').sort().join('');
}
// Time: O(n log n), Space: O(n)
// Use case: Simple anagram check
Method 2: Frequency Count (Optimal O(n))
function isAnagram(s, t) {
if (s.length !== t.length) return false;
const freq = {};
// Count characters in first string
for (const char of s) {
freq[char] = (freq[char] || 0) + 1;
}
// Decrement for second string
for (const char of t) {
if (!freq[char]) return false;
freq[char]--;
}
return true;
}
// Time: O(n), Space: O(1) - at most 26 letters
2οΈβ£ Palindrome Check - Two Pointersβ
function isPalindrome(s) {
// Clean string: remove non-alphanumeric, convert to lowercase
const cleaned = s.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
let left = 0, right = cleaned.length - 1;
while (left < right) {
if (cleaned[left] !== cleaned[right]) return false;
left++;
right--;
}
return true;
}
// Time: O(n), Space: O(1)
// Use case: Valid palindrome problems
3οΈβ£ Sliding Window - Longest Substring Without Repeating Charactersβ
function lengthOfLongestSubstring(s) {
const charSet = new Set();
let left = 0, maxLength = 0;
for (let right = 0; right < s.length; right++) {
// Shrink window until no duplicates
while (charSet.has(s[right])) {
charSet.delete(s[left]);
left++;
}
charSet.add(s[right]);
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
}
// Time: O(n), Space: O(min(m,n)) where m is charset size
// Use case: Substring problems with constraints
4οΈβ£ String Matching - KMP Algorithm Previewβ
function strStr(haystack, needle) {
if (needle.length === 0) return 0;
if (needle.length > haystack.length) return -1;
// Simple approach - for KMP, build failure function
for (let i = 0; i <= haystack.length - needle.length; i++) {
if (haystack.substring(i, i + needle.length) === needle) {
return i;
}
}
return -1;
}
// Time: O(n*m) simple, O(n+m) with KMP
// Use case: Pattern matching, substring search
5οΈβ£ Character Frequency Mapβ
function getCharFrequency(s) {
const freq = new Map();
for (const char of s) {
freq.set(char, (freq.get(char) || 0) + 1);
}
return freq;
}
// Use case: Anagrams, character analysis, permutations
β οΈ Common Pitfalls & How to Avoid Themβ
π« Performance Pitfallsβ
// β Wrong - O(nΒ²) string concatenation in loop
let result = '';
for (let i = 0; i < arr.length; i++) {
result += arr[i]; // Creates new string each time!
}
// β
Correct - O(n) using array join
const parts = [];
for (let i = 0; i < arr.length; i++) {
parts.push(arr[i]);
}
const result = parts.join('');
π« Character Access Confusionβ
// Both work in modern JavaScript
const char1 = str[i]; // β
Preferred - cleaner syntax
const char2 = str.charAt(i); // β
Safe - returns '' for invalid index
// Key difference:
str[999] // undefined for out-of-bounds
str.charAt(999) // '' (empty string) for out-of-bounds
π« Unicode and Emoji Issuesβ
const text = "Hello π World";
console.log(text.length); // 13 (not 12!) - emoji counts as 2
// β
For proper character counting with Unicode:
const properLength = [...text].length; // 12 - correct count
π« Case Sensitivity Mistakesβ
// β Wrong - case sensitive comparison
if (str1 === str2) { ... }
// β
Correct - case insensitive when needed
if (str1.toLowerCase() === str2.toLowerCase()) { ... }
π« Boundary Conditionsβ
// Always check for:
// - Empty strings
// - Single character strings
// - Null or undefined inputs
function safeStringOperation(s) {
if (!s || s.length === 0) return '';
// ... rest of logic
}
π‘ Pro Tipsβ
- Use
String.prototype.includes()for substring checking - Remember that
slice()can take negative indices - Use template literals for complex string building
- Consider regex for complex pattern matching
- Use
split()andjoin()for character manipulation
Practice Problemsβ
π Related Topicsβ
- Sliding Window β Essential for substring problems
- Two Pointers β Palindrome and string reversal
- Hashing β Character frequency and anagram detection
- Dynamic Programming β Edit distance and string matching
- Backtracking β String permutations and combinations
π― Quick Interview Prep Checklistβ
- Master anagram detection (both sorting and frequency methods)
- Understand palindrome checking with two pointers
- Practice sliding window for substring problems
- Know string manipulation techniques (reverse, rotate)
- Comfortable with character frequency counting
- Understand basic pattern matching algorithms
- Practice string parsing and validation
- Know when to use StringBuilder pattern (array + join)
β Back to Home Β· Β© sparshjaswal