Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Minimum Number of Moves to Make Palindrome

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2193" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

You are given a string s consisting only of lowercase English letters. In one move, you can select any two adjacent characters of s and swap them. Return the minimum number of moves needed to make s a palindrome. Note that the input will be generated such that s can always be converted to a palindrome. Example 1: Input: s = "aabb" Output: 2 Explanation: We can obtain two palindromes from s, "abba" and "baab". - We can obtain "abba" from s in 2 moves: "aabb" -> "abab" -> "abba". - We can obtain "baab" from s in 2 moves: "aabb" -> "abab" -> "baab". Thus, the minimum number of moves needed to make s a palindrome is 2. Example 2: Input: s = "letelt" Output: 2 Explanation: One of the palindromes we can obtain from s in 2 moves is "lettel". One of the ways we can obtain it is "letelt" -> "letetl" -> "lettel". Other palindromes such as "tleelt" can also be obtained in 2 moves. It can be shown that it is not possible to obtain a palindrome in less than 2 moves. Constraints: 1 <= s.length <= 2000 s consists only of lowercase English letters. s can be converted to a palindrome using a finite number of moves.

Explanation

Here's a breakdown of the approach and the Python code:

  • High-Level Approach:

    • Greedy Placement: The core idea is to greedily place characters from the edges of the string towards the center to form a palindrome. We try to bring characters from the right side that match the leftmost unmatched character to their correct position.
    • Index Tracking and Swapping: We maintain pointers to the leftmost and rightmost unmatched characters. When a matching character is found on the right, we move it to the correct mirrored position through a series of swaps. The count of these swaps contributes to the total moves.
    • Odd Length Handling: If the string has an odd length and a character appears an odd number of times, that single character needs to be moved to the center. The moves required to bring it to the center are also accumulated.
  • Complexity:

    • Runtime Complexity: O(n^2), where n is the length of the string. This is due to the potential need to search and swap characters in the inner loop.
    • Storage Complexity: O(n) (in-place modification of string).

Code

    def minMovesToMakePalindrome(s: str) -> int:
    """
    Calculates the minimum number of moves needed to make a string a palindrome by swapping adjacent characters.

    Args:
        s: The input string consisting of lowercase English letters.

    Returns:
        The minimum number of moves needed to make the string a palindrome.
    """
    s = list(s)  # Convert string to list for easier swapping
    n = len(s)
    moves = 0
    for i in range(n // 2):
        left = i
        right = n - 1 - i
        while left < right:
            if s[left] == s[right]:
                break
            right -= 1
        if left == right:
            # Find the middle, move to the center
            moves += n // 2 - i
            # Shift the char to center, simulate swap
            s.pop(right)
            s.insert(n // 2, s[i])

        else:
            for k in range(right, n - 1 - i):
                s[k], s[k + 1] = s[k + 1], s[k]
                moves += 1
    return moves

More from this blog

C

Chatmagic blog

2894 posts