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?- A. True False
- B. True True
- C. False False
- 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
- Problem: Return True if one character can be deleted from a word to make it a palindrome (or it already is one). python def almost(s): def…
- Problem: Compress a string by replacing each run with the letter followed by the run length (only when the run is longer than 1). python…
- Problem: Reverse the order of words in a sentence, collapsing multiple spaces. python s = " the sky is blue " print("|" + "…
- Problem: Find the first non-repeating character in a string of lowercase letters; return its index or −1. java static int…
- Problem: Check whether s2 contains a permutation of s1 as a substring. python def hasperm(s1, s2): k = len(s1) need = [0] 26; win = [0] 26…
- Problem: Return the longest common prefix of a list of file paths. python def lcp(words): if not words: return "" p = words[0] for w in…