Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern

Problem: A username is valid if it reads the same forwards and backwards after removing non-alphanumeric characters and ignoring case.

Problem: A username is valid if it reads the same forwards and backwards after removing non-alphanumeric characters and ignoring case.
def ok(s):
    i, j = 0, len(s) - 1
    while i < j:
        if not s[i].isalnum(): i += 1
        elif not s[j].isalnum(): j -= 1
        elif s[i].lower() != s[j].lower(): return False
        else: i += 1; j -= 1
    return True
print(ok("No 'x' in Nixon"), ok("0P"))
What is printed?
  1. A. True False
  2. B. True True
  3. C. False False
  4. D. False True

Correct answer: A. True False

Two pointers skip punctuation and compare case-insensitively: "noxinnixon" is a palindrome. "0P" compares '0' with 'p' – different, so False (a common bug is treating digits as non-alphanumeric). O(n), O(1) space.

More Coding Interview Problems questions

Exams that ask this topic