709865. Min Chars to Add for Palindrome

Hard

Min Chars to Add for Palindrome

Summary

Given a string, find the minimum number of characters that need to be added at the front to make it a palindrome. A palindrome is a string that reads the same backward as forward.

This problem involves manipulating strings and checking if they are palindromes. The key concept involved is the construction of a palindrome by adding characters at the front.

Detailed Explanation

To solve this problem, we can use a two-pointer approach. Initialize two pointers, left and right, to the end of the string. Move them towards each other until they meet in the middle (since the string is already a palindrome).

For each step, check if the characters at the left and right positions are the same. If they are not, add the character at the right position to the front of the string and decrement right. Continue this process until left and right meet in the middle.

Here's a step-by-step breakdown:

  1. Initialize left and right pointers to the end of the string.
  2. While left and right do not meet:
    • Check if the characters at positions left and right are the same.
    • If they are not, add the character at position right to the front of the string.
    • Decrement right.
  3. Return the number of characters added.

Time complexity: O(n), where n is the length of the string. Space complexity: O(1), since we only use a constant amount of space.

Optimized Solutions

Java

View on GeeksforGeeks
public int minCharsToMakePalindrome(String s) {
    int left = s.length() - 1;
    int right = s.length() - 1;
    int count = 0;

    while (left >= 0 && right < s.length()) {
        if (s.charAt(left) == s.charAt(right)) {
            left--;
            right--;
        } else {
            count++;
            right--;
        }
    }

    return count;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.