Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Largest Palindromic Number

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2384" 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 num consisting of digits only. Return the largest palindromic integer (in the form of a string) that can be formed using digits taken from num. It should not contain leading zeroes. Notes: You do not need to use all the digits of num, but you must use at least one digit. The digits can be reordered. Example 1: Input: num = "444947137" Output: "7449447" Explanation: Use the digits "4449477" from "444947137" to form the palindromic integer "7449447". It can be shown that "7449447" is the largest palindromic integer that can be formed. Example 2: Input: num = "00009" Output: "9" Explanation: It can be shown that "9" is the largest palindromic integer that can be formed. Note that the integer returned should not contain leading zeroes. Constraints: 1 <= num.length <= 105 num consists of digits.

Explanation

Here's a breakdown of the solution:

  • Count Digits: Count the occurrences of each digit (0-9) in the input string num.
  • Build Palindrome: Construct the largest possible palindrome by taking pairs of digits from the counts, starting with the largest digits. A single digit will be left in the middle if there's an odd count for any digit.
  • Handle Leading Zeros: Remove leading zeros while ensuring at least one digit remains.

  • Runtime Complexity: O(n), where n is the length of the input string. Storage Complexity: O(1) - constant space for the digit counts.

Code

    def largestPalindromic(num: str) -> str:
    counts = [0] * 10
    for digit in num:
        counts[int(digit)] += 1

    left = ""
    middle = ""

    for i in range(9, -1, -1):
        count = counts[i]
        pairs = count // 2
        if pairs > 0:
            left += str(i) * pairs
        if count % 2 != 0 and middle == "":
            middle = str(i)

    result = left + middle + left[::-1]

    # Remove leading zeros
    first_digit_index = 0
    while first_digit_index < len(result) - 1 and result[first_digit_index] == '0':
        first_digit_index += 1

    result = result[first_digit_index:]

    return result if result else "0"

More from this blog

C

Chatmagic blog

2894 posts

Solving Leetcode Interviews in Seconds with AI: Largest Palindromic Number