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:
- Each bead is a character (
'a','!',' '). - You can read the order of beads easily.
- 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
| Operation | Complexity | Description |
|---|---|---|
| Concatenation | O(n + m) | Creating a new string |
| Substring | O(k) | Extracting $k$ characters |
| Comparison | O(n) | Lexicographical checking |
| Search | O(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