c2cedge
Data Structures & Algorithms · B — Linear Structures

Strings

String questions look varied but reduce to a few moves: count characters, scan with two pointers, or slide a window.

Test weight: Very highTime / question: 1–3 minDifficulty: Easy–Medium

A string is really an array of characters, so everything you know about arrays applies. Most placement string questions test palindromes, anagrams, character frequencies, and simple pattern searches.

Count or scan

Two ideas solve the majority of string problems: a frequency array (size 26 for lowercase letters) for anything about character counts, and two pointers for palindromes and reversals.

Palindrome check with two pointers
left = 0;  right = len - 1
while left < right:
    if s[left] != s[right]: return false
    left++;  right--
return true
O(n)O(1)
Single scan; a 26-size count array is constant space.
⚡ The edge
  • For anagrams, count characters with a 26-element array — that is O(n), beating the O(n log n) of sorting both strings.
  • For palindromes, two pointers from both ends stop at the first mismatch, so you rarely scan the whole string.
Worked example
Are 'listen' and 'silent' anagrams?
  1. Anagrams contain the same letters with the same counts, just reordered, so compare character frequencies.
  2. Count each: both have l, i, s, t, e, n exactly once.
  3. All counts match, so they are anagrams.
Worked example
Is 'madam' a palindrome?
left=0; right=4
compare s[0]='m' vs s[4]='m'  -> equal
compare s[1]='a' vs s[3]='a'  -> equal
left >= right -> stop
  1. Compare the outermost characters and move inward.
  2. m=m, then a=a; the middle character 'd' needs no comparison.
  3. No mismatch was found, so it reads the same both ways.
⚠ Watch out
  • Decide up front whether case and spaces matter (is 'Madam' a palindrome?).
  • A frequency array of size 26 assumes lowercase letters only — widen it for digits or mixed case.
  • Strings are often immutable; building a new string in a loop can be O(n²).
Practice this — take a timed mock →
1,300+ questions, scored, with a weak-area report.
Know who's ready. Not who finished.
HomeLibraryPrivacyTerms