Data Structures & AlgorithmsVery hardTCS Digital · Infosys SP

Can a string become a palindrome by deleting at most one character? Two pointers try skipping either side on the first mismatch. What is printed?

Can a string become a palindrome by deleting at most one character? Two pointers try skipping either side on the first mismatch. What is printed?
def ok(s, skip=True):
    i, j = 0, len(s) - 1
    while i < j:
        if s[i] != s[j]:
            return skip and (ok(s[i + 1:j + 1], False) or ok(s[i:j], False))
        i += 1; j -= 1
    return True
print([ok(w) for w in ['abca', 'abccdba', 'abcda', 'eeccccbebaeeabebccceea']])
  1. A. [True, False, False, False]
  2. B. [True, False, True, False]
  3. C. [True, True, False, False]
  4. D. [False, False, False, False]

Correct answer: C. [True, True, False, False]

On the first mismatch both choices (drop the left or drop the right character) must be tried; trying only one side misses cases like 'cbbcc'. Output: [True, True, False, False].

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic