Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Find the Count of Good Integers

Updated
4 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "3272" 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 two positive integers n and k. An integer x is called k-palindromic if: x is a palindrome. x is divisible by k. An integer is called good if its digits can be rearranged to form a k-palindromic integer. For example, for k = 2, 2020 can be rearranged to form the k-palindromic integer 2002, whereas 1010 cannot be rearranged to form a k-palindromic integer. Return the count of good integers containing n digits. Note that any integer must not have leading zeros, neither before nor after rearrangement. For example, 1010 cannot be rearranged to form 101. Example 1: Input: n = 3, k = 5 Output: 27 Explanation: Some of the good integers are: 551 because it can be rearranged to form 515. 525 because it is already k-palindromic. Example 2: Input: n = 1, k = 4 Output: 2 Explanation: The two good integers are 4 and 8. Example 3: Input: n = 5, k = 6 Output: 2468 Constraints: 1 <= n <= 10 1 <= k <= 9

Explanation

Here's a solution to the problem, along with an explanation of the approach and complexity analysis.

  • High-Level Approach:

    • Generate all possible combinations of digit counts for a given n. We'll represent a combination as a dictionary where the keys are digits (0-9) and the values are their counts.
    • Check if a given digit count combination can form a k-palindromic number. This involves checking two conditions: (1) That all even positions contain equal digits, and that a rearrangement is possible so that the number is divisible by k. (2) To ensure the number doesn't have a leading zero, handle cases separately where zero must, or must not be placed in the first position.
    • Count the number of good integers that can be created from each valid digit combination. This requires using combinatorics (permutations with repetitions).
  • Complexity Analysis:

    • Runtime Complexity: O(10n) in the worst case because we iterate over all possible counts of each digit for the number n.
    • Storage Complexity: O(10) = O(1) since at most we will keep track of the counts of digits which are 10 in number.

Code

    from collections import Counter
from math import factorial

def solve():
    n = int(input())
    k = int(input())

    def is_k_palindromic(counts, first_digit_nonzero=False):
        """Checks if a digit combination can form a k-palindromic number."""

        total_digits = sum(counts.values())
        if total_digits != n:
            return False

        odd_count = 0
        for count in counts.values():
            if count % 2 != 0:
                odd_count += 1

        if n % 2 == 0 and odd_count > 0:
            return False
        if n % 2 != 0 and odd_count != 1:
            return False

        def check_divisibility(arr):
            num = 0
            for digit in arr:
                num = (num * 10 + digit) % k
            return num == 0

        import itertools

        def possible_numbers(counts):
            digits = []
            for digit, count in counts.items():
                digits.extend([digit] * count)


            if not first_digit_nonzero:
                for perm in itertools.permutations(digits):
                    yield list(perm)
            else:
                for digit in range(1,10):
                    if counts.get(digit,0) > 0:
                        temp_counts = counts.copy()
                        temp_counts[digit] -= 1
                        remaining_digits = []
                        for d, count in temp_counts.items():
                            remaining_digits.extend([d] * count)

                        for perm in itertools.permutations(remaining_digits):
                            yield [digit] + list(perm)


        for number in possible_numbers(counts):
           if check_divisibility(number) and is_palindrome(number):
              return True
        return False


    def is_palindrome(arr):
      return arr == arr[::-1]

    def count_arrangements(counts):
        total_count = sum(counts.values())
        numerator = factorial(total_count)
        denominator = 1
        for count in counts.values():
            denominator *= factorial(count)
        return numerator // denominator

    def count_arrangements_no_leading_zero(counts):
        total_count = sum(counts.values())
        if 0 not in counts or counts[0] == 0:
            return count_arrangements(counts)

        total_arrangements = count_arrangements(counts)

        counts_copy = counts.copy()
        counts_copy[0] -= 1

        if counts_copy[0] == 0:
            del counts_copy[0]

        arrangements_with_leading_zero = factorial(total_count-1)
        for count in counts.values():
           arrangements_with_leading_zero //= factorial(count)

        if counts_copy:
            arrangements_with_leading_zero = count_arrangements(counts_copy)
        else:
            arrangements_with_leading_zero = 1


        zeros = counts.get(0,0)

        if zeros > 0:
            total_count_with_zero = total_count -1
            numerator = factorial(total_count_with_zero)
            denominator = 1

            counts_copy = counts.copy()
            counts_copy[0] -= 1

            if counts_copy[0] == 0:
                del counts_copy[0]

            for count in counts_copy.values():
                denominator *= factorial(count)

            arrangements_with_leading_zero = numerator // denominator


        return total_arrangements - arrangements_with_leading_zero

    count = 0

    def generate_combinations(index, current_counts):
        nonlocal count
        if index == 9:
            current_counts[9] = n - sum(current_counts.values())
            if current_counts[9] >= 0:
                if is_k_palindromic(current_counts):
                    count += count_arrangements_no_leading_zero(current_counts)

            return

        for i in range(n + 1):
            new_counts = current_counts.copy()
            new_counts[index] = i
            if sum(new_counts.values()) <= n:
                generate_combinations(index + 1, new_counts)

    generate_combinations(0, {})
    print(count)

solve()

More from this blog

C

Chatmagic blog

2894 posts