Solving Leetcode Interviews in Seconds with AI: Unique Length-3 Palindromic Subsequences
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1930" 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 unique palindromes of length three that are a subsequence of s. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once. A palindrome is a string that reads the same forwards and backwards. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. For example, "ace" is a subsequence of "abcde". Example 1: Input: s = "aabca" Output: 3 Explanation: The 3 palindromic subsequences of length 3 are: - "aba" (subsequence of "aabca") - "aaa" (subsequence of "aabca") - "aca" (subsequence of "aabca") Example 2: Input: s = "adc" Output: 0 Explanation: There are no palindromic subsequences of length 3 in "adc". Example 3: Input: s = "bbcbaba" Output: 4 Explanation: The 4 palindromic subsequences of length 3 are: - "bbb" (subsequence of "bbcbaba") - "bcb" (subsequence of "bbcbaba") - "bab" (subsequence of "bbcbaba") - "aba" (subsequence of "bbcbaba") Constraints: 3 <= s.length <= 105 s consists of only lowercase English letters.
Explanation
Here's a breakdown of the solution and the code:
High-Level Approach:
- Iterate through all possible middle characters (a to z).
- For each middle character, find the first and last occurrence in the string.
- Count the unique characters between the first and last occurrences of the middle character. These represent the outer characters of the palindrome.
Complexity:
- Runtime: O(26 * n) which simplifies to O(n), where n is the length of the string.
- Space: O(1) - Constant space used to store the unique characters.
Code
def count_palindromic_subsequences(s: str) -> int:
"""
Given a string s, return the number of unique palindromes of length three that are a subsequence of s.
"""
count = 0
for char_code in range(ord('a'), ord('z') + 1):
char = chr(char_code)
first_occurrence = -1
last_occurrence = -1
for i in range(len(s)):
if s[i] == char:
if first_occurrence == -1:
first_occurrence = i
last_occurrence = i
if first_occurrence != -1 and last_occurrence != first_occurrence:
unique_chars = set()
for i in range(first_occurrence + 1, last_occurrence):
unique_chars.add(s[i])
count += len(unique_chars)
return count