Break a Palindrome solution explained

Break a Palindrome has a two-rule answer: scan the first half of the string and turn the first letter that is not 'a' into 'a'; if every letter there is already 'a', change the last letter to 'b'. A single-character string cannot be broken, so return an empty string. It runs in O(n) time.

By Published 7 min read

Problem statement in our words

You are given a word made of lowercase letters that reads the same forward and backward. Replace exactly one of its letters with any lowercase letter so that the new word does not read the same both ways. Among all such words, return the one that comes first in dictionary order. If no single replacement can do it, return an empty string.

Palindromes chosen for this page and their answers
InputOutputReason
levelaevelThe first letter is not 'a', so it becomes 'a'.
abbaaabaPosition 0 is already 'a'; position 1 is the first that can drop.
abaabbThe only non-'a' letter is the middle, which cannot break symmetry, so the last letter becomes 'b'.
aaaaaaabEvery letter is 'a'; raising the last one costs the least.
azaazbTurning the middle 'z' into 'a' gives aaa, still a palindrome.
q(empty string)Any one-letter word is a palindrome.
Palindromes chosen for this page and their answers. Scroll sideways on a small screen.

Clarify two things up front. Must the replacement letter differ from the original? It must, in practice, because an unchanged word is still a palindrome. And is dictionary order the plain comparison of strings of the same length? Here every candidate has the same length, so yes.

Why it is a good screening question

The code is a few lines, but each line hides a reason, and interviewers listen for the reasons. Why only the first half? Why skip the middle? Why 'b' at the end and not at the front? A candidate who can answer all three has shown careful thinking about lexicographic order, which turns up again in harder string problems.

Brute force: try every single-letter change

For each position, try each of the 26 letters other than the current one, build the new word, and keep it if it is not a palindrome and is smaller than the best so far. There are about 25n candidates, building and checking each costs O(n), so the total is O(n²) with a constant of 25. It is slow but leaves no room for a wrong idea, which makes it the right tool for testing.

from string import ascii_lowercase

def break_by_search(word):
    best = ""
    for i in range(len(word)):
        for ch in ascii_lowercase:
            if ch == word[i]:
                continue
            candidate = word[:i] + ch + word[i + 1:]
            if candidate != candidate[::-1] and (best == "" or candidate < best):
                best = candidate
    return best
Brute force: every position, every replacement letter.

Main approach: two rules from dictionary order

A word gets smaller when an earlier letter gets smaller, and 'a' is the smallest letter. So the best possible move lowers the leftmost letter that is not already 'a'. Look only in the first half, positions 0 up to n // 2 minus 1. Changing a letter in the first half breaks the symmetry because its mirror in the second half stays the same. The middle letter of an odd-length word is its own mirror, so changing it can never break anything. A non-'a' letter that appears only in the second half has a mirror in the first half, so the scan would already have found it.

If the scan finds nothing, every letter in the first half is 'a', and by symmetry so is every letter in the second half. Any change now must raise some letter, which makes the word larger. Raising a letter as far right as possible, by the smallest amount, does the least damage. That means changing the last letter to 'b'. The last letter is never the middle unless the word has length one, and a word of length one has no valid answer at all.

def break_palindrome(word):
    n = len(word)
    if n <= 1:
        return ""
    for i in range(n // 2):
        if word[i] != "a":
            return word[:i] + "a" + word[i + 1:]
    return word[:-1] + "b"
Python: scan the left half, else bump the last letter.
function breakPalindrome(word) {
  const n = word.length;
  if (n <= 1) return "";
  for (let i = 0; i < Math.floor(n / 2); i++) {
    if (word[i] !== "a") {
      return word.slice(0, i) + "a" + word.slice(i + 1);
    }
  }
  return word.slice(0, n - 1) + "b";
}
JavaScript: strings are immutable, so rebuild with slice.

Trace aza. The length is 3, so the scan looks at index 0 only. It holds 'a', so nothing happens. The fallback replaces the last letter and returns azb. Note that the middle 'z' was never touched, which is the point.

Cost

Work done for a word of length n
ApproachTimeMemory beyond the output
Try every letter at every positionO(26 · n²)O(n) per candidate
Left-half scan with fallbackO(n)O(1), plus the new string
Work done for a word of length n. Scroll sideways on a small screen.

Building the returned string is O(n) in both Python and JavaScript, since neither language lets you edit a string in place. If the interviewer asks for O(1) extra space, convert to a list or character array first and say that the conversion itself takes O(n).

Edge cases to test

  • Length one, any letter: return an empty string.
  • Length two of the same letter, such as zz: the scan changes index 0 to give az.
  • Length two of 'a', aa: the fallback gives ab.
  • Odd length where only the middle is not 'a', such as aaxaa: the answer is aaxab, not aaaaa.
  • Long strings of 'a': the answer ends in 'b' and nothing else moves.

Mistakes interviewers see often

  • Scanning the whole word instead of the first half. On aba the loop reaches the middle 'b', changes it to 'a', and returns aaa, which is still a palindrome.
  • Changing the first letter to 'b' in the fallback. That gives a larger word than changing the last letter.
  • Forgetting the length-one case and returning 'b' for the input 'a'. A one-letter word is always a palindrome.
  • Using n / 2 in JavaScript without flooring, which allows a fractional bound and lets the loop reach the middle index.
  • Skipping the reasoning. The rule looks like a trick unless you explain the mirror argument.

Possible follow-ups

  • Return the largest result instead. Mirror the logic: find the first letter in the left half that is not 'z' and make it 'z'; if all are 'z', lower the last letter to 'y'.
  • Change exactly one letter so the word becomes a palindrome. A different problem: count mismatched mirror pairs and check whether there is exactly one, or zero with an odd length.
  • Allow uppercase letters. Decide the ordering rule first; in ASCII, capitals sort before lowercase, which changes what the smallest letter is.

A spoken version

Fictional example

How a candidate might explain the rules
Candidate
To make the word as small as possible, I want to lower the earliest letter I can, and the lowest letter is 'a'.
Candidate
I only look in the first half. A change there breaks the mirror, and the middle of an odd word is its own mirror, so it never helps.
Candidate
If the first half is all 'a', I have to make the word bigger, so I do it at the very end by changing the last letter to 'b'. Length one returns empty.

More in this batch

Largest Number is another problem decided entirely by string comparison, and Minimum Deletions to Make Character Frequencies Unique is a second string task where a short greedy rule needs a careful corner case. The JavaScript interview questions page covers string immutability and slicing in more depth.

How Natively helps you practice

When you rehearse on your own, Natively can read a screenshot of a short string problem, suggest an approach and draft code, giving you something to check your own reasoning against once you have finished. It can also transcribe a mock round on your computer, so you can look back and see whether you explained the middle-letter case or skipped it. Here is how an AI interview assistant works on Mac and Windows.

Questions people ask

How do you solve Break a Palindrome?

If the string has one letter, return an empty string. Otherwise scan the first half and change the first letter that is not 'a' into 'a'. If the whole first half is 'a', change the last letter to 'b'.

Why not change the middle letter?

In an odd-length palindrome the middle letter is its own mirror, so changing it leaves the word a palindrome. Scanning only the first half skips it automatically.

Why change the last letter to 'b' instead of the first?

When the first half is all 'a', every valid change makes the word larger. Raising the last letter by one step makes it larger by the smallest amount, so it gives the smallest valid result.

What is the time complexity of Break a Palindrome?

O(n) time, since you scan at most half the string and build one new string. Extra space is O(n) for the returned string in languages with immutable strings.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP