Bird
Raised Fist0
DSA Typescriptprogramming

Palindrome Detection in DSA Typescript

Choose your learning style10 modes available
Mental Model
A palindrome reads the same forwards and backwards. We check if the first and last characters match, then move inward.
Analogy: Like checking if a word is the same when read from left to right and right to left, like 'madam' or 'racecar'.
head -> [m] -> a -> d -> a -> m -> tail
indexes: 0    1    2    3    4
Dry Run Walkthrough
Input: string: 'madam'
Goal: Check if 'madam' is a palindrome by comparing characters from both ends moving inward.
Step 1: Compare characters at start=0 and end=4 ('m' and 'm')
m (start=0) == m (end=4) -> move inward
Why: First and last characters must match for palindrome
Step 2: Compare characters at start=1 and end=3 ('a' and 'a')
a (start=1) == a (end=3) -> move inward
Why: Next pair must also match
Step 3: Compare characters at start=2 and end=2 ('d' and 'd')
d (start=2) == d (end=2) -> middle reached
Why: Middle character matches itself, palindrome confirmed
Result:
String 'madam' is a palindrome
Annotated Code
DSA Typescript
class PalindromeDetector {
  static isPalindrome(s: string): boolean {
    let start = 0;
    let end = s.length - 1;
    while (start < end) {
      if (s[start] !== s[end]) {
        return false; // mismatch means not palindrome
      }
      start++; // move start pointer inward
      end--;   // move end pointer inward
    }
    return true; // all matched, it is palindrome
  }
}

// Driver code
const input = 'madam';
const result = PalindromeDetector.isPalindrome(input);
console.log(`String '${input}' is${result ? '' : ' not'} a palindrome`);
if (s[start] !== s[end]) {
Check if characters at start and end differ -- if yes, stop and return false
start++;
Move start pointer inward to next character
end--;
Move end pointer inward to previous character
return true;
If all pairs matched, confirm palindrome
OutputSuccess
String 'madam' is a palindrome
Complexity Analysis
Time: O(n) because we compare pairs of characters moving inward once through half the string
Space: O(1) because we use only two pointers and no extra space
vs Alternative: Compared to reversing the string and comparing, this method uses less space and stops early on mismatch
Edge Cases
Empty string
Returns true because empty string reads the same forwards and backwards
DSA Typescript
while (start < end) {
Single character string
Returns true because a single character is always a palindrome
DSA Typescript
while (start < end) {
String with mismatched characters
Returns false as soon as a mismatch is found
DSA Typescript
if (s[start] !== s[end]) {
When to Use This Pattern
When you need to check if a sequence reads the same forwards and backwards, use two pointers moving inward from both ends to compare characters.
Common Mistakes
Mistake: Comparing characters but forgetting to move pointers inward
Fix: Increment start and decrement end pointers after each successful comparison
Mistake: Checking only half the string but using incorrect loop condition
Fix: Use 'while (start < end)' to ensure pointers meet or cross correctly
Summary
Checks if a string reads the same forwards and backwards.
Use when you want to verify palindrome property efficiently.
Compare characters from both ends moving inward until pointers meet or mismatch.

Practice

(1/5)
1. What does it mean if a string is a palindrome?
easy
A. The string has no spaces
B. The string reads the same forwards and backwards
C. The string contains only letters
D. The string is all uppercase

Solution

  1. Step 1: Understand palindrome definition

    A palindrome is a word or phrase that reads the same forwards and backwards.
  2. Step 2: Compare options with definition

    Only The string reads the same forwards and backwards matches this definition exactly.
  3. Final Answer:

    The string reads the same forwards and backwards -> Option B
  4. Quick Check:

    Palindrome = same forwards and backwards [OK]
Hint: Palindrome means same forwards and backwards [OK]
Common Mistakes:
  • Confusing palindrome with uppercase or letter-only strings
  • Thinking palindrome means no spaces
  • Assuming palindrome means all lowercase
2. Which of the following TypeScript code snippets correctly checks if a string str is a palindrome?
easy
A. return str === str.split().reverse().join();
B. return str === str.reverse();
C. return str === str.split('').reverse().join('');
D. return str === str.split('').reverse();

Solution

  1. Step 1: Understand string reversal in TypeScript

    To reverse a string, split it into characters, reverse the array, then join back.
  2. Step 2: Check each option's correctness

    return str === str.split('').reverse().join(''); uses split(''), reverse(), join('') correctly. Others miss correct methods or arguments.
  3. Final Answer:

    return str === str.split('').reverse().join(''); -> Option C
  4. Quick Check:

    Correct string reversal syntax = return str === str.split('').reverse().join(''); [OK]
Hint: Use split(''), reverse(), join('') to reverse strings [OK]
Common Mistakes:
  • Using reverse() directly on string (not an array)
  • Using split() without arguments returns whole string as one element
  • Forgetting to join array back to string
3. What will be the output of this TypeScript code?
function isPalindrome(s: string): boolean {
  const cleaned = s.toLowerCase().replace(/[^a-z0-9]/g, '');
  return cleaned === cleaned.split('').reverse().join('');
}
console.log(isPalindrome('A man, a plan, a canal: Panama'));
medium
A. true
B. false
C. SyntaxError
D. undefined

Solution

  1. Step 1: Clean the string

    The string is converted to lowercase and non-alphanumeric characters removed, resulting in 'amanaplanacanalpanama'.
  2. Step 2: Check palindrome condition

    This cleaned string equals its reverse, so function returns true.
  3. Final Answer:

    true -> Option A
  4. Quick Check:

    Cleaned string equals reversed = true [OK]
Hint: Clean string before checking palindrome for accurate result [OK]
Common Mistakes:
  • Not cleaning string before palindrome check
  • Assuming spaces or punctuation affect palindrome
  • Confusing true/false output
4. Find the error in this palindrome check function:
function checkPalindrome(str: string): boolean {
  const reversed = str.split('').reverse();
  return str === reversed;
}
medium
A. reverse() does not work on strings
B. Function missing return type
C. split('') is incorrect usage
D. reversed is an array, not a string

Solution

  1. Step 1: Analyze reversed variable type

    reversed is an array after split and reverse, not a string.
  2. Step 2: Compare string with array

    Comparing string to array returns false always; need to join array back to string.
  3. Final Answer:

    reversed is an array, not a string -> Option D
  4. Quick Check:

    Compare string to string, not array [OK]
Hint: Join reversed array back to string before comparing [OK]
Common Mistakes:
  • Comparing string directly to array
  • Forgetting to join reversed array
  • Assuming split('') returns string
5. You want to check if a sentence is a palindrome ignoring spaces, punctuation, and case. Which approach is best?
hard
A. Convert to lowercase, remove non-alphanumeric chars, then compare with reversed
B. Compare original string with reversed string directly
C. Remove spaces only, then compare
D. Convert to uppercase and compare with reversed uppercase

Solution

  1. Step 1: Understand palindrome ignoring spaces and punctuation

    We must clean the string by removing spaces and punctuation and normalize case.
  2. Step 2: Choose correct cleaning and comparison

    Convert to lowercase, remove non-alphanumeric chars, then compare with reversed cleans string by removing non-alphanumeric characters and lowercases it before comparing with reversed.
  3. Final Answer:

    Convert to lowercase, remove non-alphanumeric chars, then compare with reversed -> Option A
  4. Quick Check:

    Clean and normalize before palindrome check [OK]
Hint: Clean string fully before palindrome check for accuracy [OK]
Common Mistakes:
  • Only removing spaces but not punctuation
  • Comparing without case normalization
  • Assuming uppercase conversion alone is enough
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard