Similar Problems

Similar Problems not available

Largest Odd Number In String - Leetcode Solution

Companies:

  • adobe
  • amazon

LeetCode:  Largest Odd Number In String Leetcode Solution

Difficulty: Easy

Topics: greedy string math  

Problem Statement:

Given a string str, find the largest odd number that can be formed using the digits in the string. If no odd number can be formed, return an empty string.

Solution:

The problem can be solved by iterating through all the characters in the given string and building a list of digits. We can then iterate through this list to find the largest odd number.

First, we will initialize an empty list of digits. Then, we will iterate through all the characters in the input string. For each character, we will check if it is a digit. If it is, we will append it to our list of digits.

Once we have built a list of digits, we will iterate through it to find the largest possible odd number. To do this, we will start with the largest possible odd number (9) and iterate down to 1. For each odd number, we will check if we can form a number using our list of digits that is divisible by this odd number. If we can, we have found our largest odd number and we can return it.

If we iterate through all the odd numbers and do not find an odd number that can be formed using our list of digits, we return an empty string.

Here is the Python code for the solution:

def largestOddNumber(self, num: str) -> str: digits = [] for c in num: if c.isdigit(): digits.append(int(c)) largest_odd = "" for odd in range(9, 0, -2): if any(digit % 2 != 0 and digit % odd == 0 for digit in digits): largest_odd = "".join(str(digit) for digit in digits if digit % 2 != 0 and digit % odd == 0) break return largest_odd

The time complexity of this solution is O(n), where n is the length of the input string. The space complexity is also O(n), as we are building a list of digits.

Largest Odd Number In String Solution Code

1