DSAintermediate 9 min
Work with text: indexing, reversing, palindromes, anagrams and the two-pointer technique.
How strings behave as arrays of characters, and how to solve classic problems: reversing, palindromes and anagrams, using counting and two pointers.
Text is everywhere: search boxes, usernames, URLs, logs. String problems also appear in nearly every coding interview, and they reuse tools you already know: arrays, hash maps and loops.
A string is a sequence of characters. You can read by index (s[0]) and ask its length, but in JavaScript strings are immutable: you cannot change a character in place. Every "change" creates a new string.
Useful tools:
s.split("") turns a string into an array of characters. arr.join("") turns it back.s.toLowerCase(), s.slice(a, b), s.includes(x), s.indexOf(x).for (const ch of s).Three patterns to know:
s[left] with s[right].join at the end, because repeated string concatenation in a loop can be slow in some languages.Complexity: most of these are O(n), one pass over the text.
reverse splits "hello" into letters, reverses the array and joins it: olleh.isPalindrome removes spaces, punctuation and case, giving amanaplanacanalpanama.true. For "hello", h and o differ, so it prints false.isAnagram counts the letters of the first word, then subtracts for each letter of the second. If any count is missing, they are not anagrams. listen and silent use the same letters: true. abc and abd do not: false.Write countVowels(s) that returns the number of vowels in a string, then test it on "Data Structures".
s[0] = "x". Strings are immutable.left < right, not <=.Next: recursion, functions that call themselves.
function reverse(s) {
return s.split("").reverse().join("");
}
function isPalindrome(s) {
const clean = s.toLowerCase().replace(/[^a-z0-9]/g, "");
let left = 0;
let right = clean.length - 1;
while (left < right) {
if (clean[left] !== clean[right]) return false;
left++;
right--;
}
return true;
}
function isAnagram(a, b) {
if (a.length !== b.length) return false;
const counts = new Map();
for (const ch of a) counts.set(ch, (counts.get(ch) || 0) + 1);
for (const ch of b) {
if (!counts.get(ch)) return false;
counts.set(ch, counts.get(ch) - 1);
}
return true;
}
console.log(reverse("hello"));
console.log(isPalindrome("A man, a plan, a canal: Panama"));
console.log(isPalindrome("hello"));
console.log(isAnagram("listen", "silent"));
console.log(isAnagram("abc", "abd"));