Find palindrome with minimum difference – Java

by
Alexei Petrov
algorithm

Quick Fix: To enhance the solution’s functionality, modify the code to adjust characters at all positions, not just the first and last. Determine the optimal character at each position by finding the median of characters at that position and its mirrored position across all input words. This approach accommodates various input sizes and results in a more robust solution.

The Problem:

Given an array of strings of the same length m, where each string consists of lowercase English letters only. Define the error between two strings s1 and s2 as the sum of the absolute distance between the characters at corresponding positions of s1 and s2 in the English alphabet. Your task is to find the lexicographically smallest palindromic string alpha of length m such that the sum of the errors between alpha and all strings in the given array is minimized.

The Solutions:

Solution 1: Compute the median character at each index for the palindrome

1. Find the median of all characters present at a given index (and its mirrored index) in the input strings.
2. Append this median character to the result string.
3. Repeat the process for all indices in the range [0, (m + 1) / 2 – 1].
4. To complete the palindrome, append the reverse of the computed half to the result string.

This solution effectively finds the character with the minimum sum of distances to all characters in the input strings at each index, resulting in the smallest possible error. The complexity of this solution is dominated by the sorting operation used to find the median, which is O(26 * n * log(26)). Here’s an optimized Python implementation:

from collections import Counter

def solve(list):
    n = len(list)
    m = len(list[0])
    result = ""
    # Range of indices to consider for constructing the palindrome
    mid = (m + 1) // 2

    # Iterate through the indices up to the middle of the string
    for i in range(mid):
        # Count character occurrences at the current index and its mirrored index
        counter = Counter()
        j = m - 1 - i
        for word in list:
            counter[word[i]] += 1
            counter[word[j]] += 1

        # Find the median character based on the character counts
        median = min(counter, key=lambda c: counter[c] + counter[chr(ord(c) + 26 - m)])
        result += median

    # Complete the palindrome with the other half
    if m % 2 == 1:  # Odd-length palindrome, add the middle character
        result += min(counter, key=lambda c: counter[c] + counter[chr(ord(c) + 26 - m)])

    result += result[::-1]  # Append the reverse of the computed half
    return result

Q&A

What does the code actually do?

It finds the minimum lexicographically smallest palindromic string alpha of length m. The sum of the errors between this alpha and the array of strings is minimum.

What’s the approach of this code?

The code tries all kinds of characters in the first and last positions of the palindromic string and finds the minimum error caused by a palindromic string.

What’s the time complexity of this code?

The time complexity of this code is size of array * size of string and for every string it iterates over it. So, the complexity is O(n*m^2)

Video Explanation:

The following video, titled "Palindrome with minimum sum | 11 May POTD | C++ | Geeks for ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Hi I hope you were able to understand the problem solution. Here are a few links for you to check out.