Quick Overview

This question evaluates string manipulation, lexicographic ordering, and algorithmic reasoning, including careful edge-case handling and time and space complexity analysis. Commonly asked in the Coding & Algorithms domain, it assesses practical application of algorithm design and correctness reasoning with emphasis on conceptual understanding and complexity trade-offs.

Break a palindrome to smallest non-palindrome

Company: Akuna Capital

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Take-home Project

Given a palindromic string s of lowercase English letters, change exactly one character to obtain a new string that is not a palindrome and is lexicographically smallest among all such possibilities. If no such string exists, return an empty string. Explain your algorithm, prove correctness, and analyze time and space complexity. Provide code in your preferred language.

Quick Answer: This question evaluates string manipulation, lexicographic ordering, and algorithmic reasoning, including careful edge-case handling and time and space complexity analysis. Commonly asked in the Coding & Algorithms domain, it assesses practical application of algorithm design and correctness reasoning with emphasis on conceptual understanding and complexity trade-offs.

You are given a palindromic string s consisting of lowercase English letters. Change exactly one character so that the resulting string is not a palindrome and is lexicographically smallest among all such possible strings. If it is impossible to make the string non-palindromic by changing exactly one character, return an empty string. A string a is lexicographically smaller than string b if at the first position where they differ, a has a smaller character than b.

Constraints

  • 1 <= len(s) <= 100000
  • s consists only of lowercase English letters
  • s is guaranteed to be a palindrome

Examples

Input: ("abccba",)

Expected Output: "aaccba"

Explanation: Changing the first non-'a' character in the first half ('b' at index 1) to 'a' gives 'aaccba', which is not a palindrome and is the smallest possible.

Input: ("a",)

Expected Output: ""

Explanation: A single-character string remains a palindrome no matter which character it is changed to, so it is impossible.

Hints

  1. To make the result lexicographically smallest, try to decrease the earliest possible character.
  2. Only characters in the first half need to be checked for replacing with 'a'. If they are all already 'a', think about changing the last character instead.

Loading coding console...