Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Palindromic Substrings

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "647" 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

Given a string s, return the number of palindromic substrings in it. A string is a palindrome when it reads the same backward as forward. A substring is a contiguous sequence of characters within the string. Example 1: Input: s = "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c". Example 2: Input: s = "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". Constraints: 1 <= s.length <= 1000 s consists of lowercase English letters.

Explanation

Here's the breakdown of the solution:

  • Expand Around Center: Iterate through each character in the string and treat it as the potential center of a palindrome. Expand outwards from this center, checking for palindromes of both odd and even lengths.
  • Count Palindromes: For each center, count the number of palindromes that can be formed by expanding outwards.
  • Avoid Redundant Counting: The expansion process ensures that each palindromic substring is counted only once.

  • Time Complexity: O(n^2), where n is the length of the string.

  • Space Complexity: O(1)

Code

    def countSubstrings(s: str) -> int:
    """
    Counts the number of palindromic substrings in a given string.

    Args:
        s: The input string.

    Returns:
        The number of palindromic substrings.
    """
    n = len(s)
    count = 0

    def expand_around_center(left: int, right: int) -> int:
        """
        Expands around the center and counts palindromes.

        Args:
            left: The left index of the center.
            right: The right index of the center.

        Returns:
            The number of palindromes found.
        """
        cnt = 0
        while left >= 0 and right < n and s[left] == s[right]:
            cnt += 1
            left -= 1
            right += 1
        return cnt

    for i in range(n):
        # Odd length palindromes
        count += expand_around_center(i, i)
        # Even length palindromes
        count += expand_around_center(i, i + 1)

    return count

More from this blog

C

Chatmagic blog

2894 posts