Core Module
12 min forge

String Basics

Master the nuances of character sequences, memory management, and common string manipulation algorithms.

πŸ”€ String Basics: Character Forging

In computer science, a string is a sequence of characters. While they behave similarly to arrays, they have unique properties (like immutability in some languages) that require specific algorithmic thinking.

πŸ’‘ The Logic (ELI5)

Think of a string as a beaded necklace:

  1. Each bead is a character ('a', '!', ' ').
  2. You can read the order of beads easily.
  3. In many languages, if you want to change one bead, you actually have to make a whole new necklace with the change. This is called Immutability.

πŸ” The Deep Dive

Immutability & Performance

In languages like JavaScript, Java, and Python, strings are immutable.

  • Doing str += "new char" in a loop actually creates $n$ temporary strings!
  • Complexity: $O(n^2)$ if not careful.
  • Solution: Use an array and join('') at the end, or a StringBuilder.

Common String Operations

OperationComplexityDescription
ConcatenationO(n + m)Creating a new string
SubstringO(k)Extracting $k$ characters
ComparisonO(n)Lexicographical checking
SearchO(n)Find index of a character

Important ASCII Knowledge

Characters are just numbers. Knowing the ranges can help you manipulate them:

  • 'a' to 'z': 97 - 122
  • 'A' to 'Z': 65 - 90
  • '0' to '9': 48 - 57

πŸ› οΈ Code Forge: Efficient Manipulation

javascript Standard
/** * REVERSING A STRING * Since strings are immutable, we convert to array first. */ function reverseString(str) { // Convert to array, reverse, then join return str.split('').reverse().join(''); } /** * CHECK IF TWO STRINGS ARE ANAGRAMS * Anagram: Words with the same characters in different order (e.g., 'listen', 'silent') */ function isAnagram(s1, s2) { if (s1.length !== s2.length) return false; // Use a frequency map (O(n) time, O(1) space for 26 chars) const count = new Array(26).fill(0); for (let i = 0; i < s1.length; i++) { count[s1.charCodeAt(i) - 97]++; // Increment for s1 count[s2.charCodeAt(i) - 97]--; // Decrement for s2 } // If all are zero, it's an anagram return count.every(val => val === 0); }

🎯 Interview Pulse

Key Patterns

  • Frequency Map: Always the first thought for character counting.
  • Two Pointers: Used for reversal, palindromes, and removing whitespace.
  • In-Place Modification: If the input is a character array char[], try to do it with O(1) space.

Common Questions

  • Reverse words in a sentence (e.g., "Hello World" -> "World Hello").
  • Longest Palindromic Substring.
  • Group Anagrams (using a HashMap).
  • Valid Parentheses. Blackwell