Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Second Largest Digit in a String

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1796" 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 an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist. An alphanumeric string is a string consisting of lowercase English letters and digits. Example 1: Input: s = "dfa12321afd" Output: 2 Explanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2. Example 2: Input: s = "abc1111" Output: -1 Explanation: The digits that appear in s are [1]. There is no second largest digit. Constraints: 1 <= s.length <= 500 s consists of only lowercase English letters and digits.

Explanation

Here's the approach to solve the problem, followed by the Python code:

  • Identify Unique Digits: Iterate through the string and extract the unique digits present.
  • Find Largest and Second Largest: Efficiently determine the largest and second largest digit from the extracted unique digits.
  • Handle Edge Cases: Return -1 if there are fewer than two distinct digits.

  • Runtime Complexity: O(n) - due to iterating through the string once. Storage Complexity: O(1) - as we store at most 10 digits (0-9).

Code

    def secondHighest(s: str) -> int:
    digits = set()
    for char in s:
        if char.isdigit():
            digits.add(int(char))

    if len(digits) < 2:
        return -1

    largest = -1
    second_largest = -1

    for digit in digits:
        if digit > largest:
            second_largest = largest
            largest = digit
        elif digit > second_largest and digit != largest:
            second_largest = digit

    return second_largest

More from this blog

C

Chatmagic blog

2894 posts