Skip to main content

πŸ”€ 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​

String Processing Overview Visualization of sliding window technique for substring problems and pattern matching

String Algorithm Animations​

String Processing Flow Interactive demonstration of string manipulation algorithms and optimization techniques

Two Pointers on Strings​

Two Pointers Technique Visual guide to using two pointers for palindrome checking and string reversal

String Hashing Visualization​

String Hashing 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] or s.charAt(i) to access characters
  • Length: s.length gives 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() and join() for character manipulation

Practice Problems​

ProblemDifficultySolution
LC 14 β€” Longest Common PrefixEasy
LC 28 β€” Implement strStr()Easy
LC 58 β€” Length of Last WordEasy
LC 125 β€” Valid PalindromeEasy
LC 242 β€” Valid AnagramEasy
LC 344 β€” Reverse StringEasy
LC 345 β€” Reverse Vowels of a StringEasy
LC 383 β€” Ransom NoteEasy
LC 387 β€” First Unique Character in a StringEasy
LC 389 β€” Find the DifferenceEasy
LC 415 β€” Add StringsEasy
LC 459 β€” Repeated Substring PatternEasy
LC 520 β€” Detect CapitalEasy
LC 541 β€” Reverse String IIEasy
LC 557 β€” Reverse Words in a String IIIEasy
LC 680 β€” Valid Palindrome IIEasy
LC 709 β€” To Lower CaseEasy
LC 771 β€” Jewels and StonesEasy
LC 796 β€” Rotate StringEasy
LC 819 β€” Most Common WordEasy
LC 859 β€” Buddy StringsEasy
LC 925 β€” Long Pressed NameEasy
LC 1002 β€” Find Common CharactersEasy
LC 1108 β€” Defanging an IP AddressEasy
LC 1221 β€” Split a String in Balanced StringsEasy
CC β€” String Basics (STRBASIC)Easy
CC β€” Character Count (CHARCOUNT)Easy
CC β€” Palindrome Check (PALCHECK)Easy
LC 3 β€” Longest Substring Without Repeating CharactersMedium
LC 5 β€” Longest Palindromic SubstringMedium
LC 6 β€” Zigzag ConversionMedium
LC 8 β€” String to Integer (atoi)Medium
LC 12 β€” Integer to RomanMedium
LC 13 β€” Roman to IntegerMedium
LC 17 β€” Letter Combinations of a Phone NumberMedium
LC 22 β€” Generate ParenthesesMedium
LC 49 β€” Group AnagramsMedium
LC 71 β€” Simplify PathMedium
LC 91 β€” Decode WaysMedium
LC 139 β€” Word BreakMedium
LC 151 β€” Reverse Words in a StringMedium
LC 165 β€” Compare Version NumbersMedium
LC 179 β€” Largest NumberMedium
LC 187 β€” Repeated DNA SequencesMedium
LC 227 β€” Basic Calculator IIMedium
LC 271 β€” Encode and Decode StringsMedium
LC 290 β€” Word PatternMedium
LC 394 β€” Decode StringMedium
LC 424 β€” Longest Repeating Character ReplacementMedium
LC 438 β€” Find All Anagrams in a StringMedium
LC 443 β€” String CompressionMedium
LC 516 β€” Longest Palindromic SubsequenceMedium
LC 567 β€” Permutation in StringMedium
LC 647 β€” Palindromic SubstringsMedium
LC 692 β€” Top K Frequent WordsMedium
LC 763 β€” Partition LabelsMedium
LC 791 β€” Custom Sort StringMedium
LC 856 β€” Score of ParenthesesMedium
LC 890 β€” Find and Replace PatternMedium
LC 929 β€” Unique Email AddressesMedium
LC 1071 β€” Greatest Common Divisor of StringsMedium
LC 1209 β€” Remove All Adjacent Duplicates in String IIMedium
LC 1249 β€” Minimum Remove to Make Valid ParenthesesMedium
LC 1456 β€” Maximum Number of Vowels in a Substring of Given LengthMedium
CC β€” String Manipulation (STRMANIP)Medium
CC β€” Pattern Matching (PATMATCH)Medium
CC β€” Anagram Problems (ANAGRAM)Medium
LC 10 β€” Regular Expression MatchingHard
LC 30 β€” Substring with Concatenation of All WordsHard
LC 32 β€” Longest Valid ParenthesesHard
LC 44 β€” Wildcard MatchingHard
LC 68 β€” Text JustificationHard
LC 72 β€” Edit DistanceHard
LC 76 β€” Minimum Window SubstringHard
LC 87 β€” Scramble StringHard
LC 115 β€” Distinct SubsequencesHard
LC 126 β€” Word Ladder IIHard
LC 140 β€” Word Break IIHard
LC 214 β€” Shortest PalindromeHard
LC 224 β€” Basic CalculatorHard
LC 269 β€” Alien DictionaryHard
LC 301 β€” Remove Invalid ParenthesesHard
LC 316 β€” Remove Duplicate LettersHard
LC 336 β€” Palindrome PairsHard
LC 472 β€” Concatenated WordsHard
LC 564 β€” Find the Closest PalindromeHard
LC 726 β€” Number of AtomsHard
LC 727 β€” Minimum Window SubsequenceHard
LC 1044 β€” Longest Duplicate SubstringHard
LC 1092 β€” Shortest Common SupersequenceHard
LC 1316 β€” Distinct Echo SubstringsHard
LC 1392 β€” Longest Happy PrefixHard
CC β€” Advanced String Algorithms (ADVSTR)Hard
CC β€” KMP Algorithm (KMPALGO)Hard
CC β€” String Hashing (STRHASH)Hard


🎯 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