Problem Statement
leetcode problem link
Brute Force [Accepted]
class Solution:
def largestGoodInteger(self, num: str) -> str:
l, r = 0, 0
curr_len = 0
max_len = 0
res = None
for r in range(len(num)):
if num[r] == num[l]:
curr_len += 1
else:
curr_len = 1
l = r
if curr_len >= max_len and curr_len == 3:
if res:
res = max(res, int(num[l]))
else:
res = int(num[l])
max_len = curr_len
return str(res) * 3 if res is not None else ""
Editorial
Approach 1: Multiple Iterations, One For Each Digit.
class Solution:
def largestGoodInteger(self, num: str) -> str:
same_digit_numbers = ["999", "888", "777", "666", "555", "444", "333", "222", "111", "000"]
# Check whether the 'num' string contains the 'same_digit_number' string or not.
def contains(same_digit_number):
for index in range(len(num) - 2):
if num[index] == same_digit_number[0] and \
num[index + 1] == same_digit_number[1] and \
num[index + 2] == same_digit_number[2]:
return True
return False
# Iterate on all 'same_digit_numbers' and check if the string 'num' contains it.
for same_digit_number in same_digit_numbers:
if contains(same_digit_number):
# Return the current 'same_digit_number'.
return same_digit_number
# No 3 consecutive same digits are present in the string 'num'.
return ""
Approach 2: Single Iteration
class Solution:
def largestGoodInteger(self, num: str) -> str:
# Assign 'max_digit' to NUL character (smallest ASCII value character)
max_digit = '\0'
# Iterate on characters of the num string.
for index in range(len(num) - 2):
# If 3 consecutive characters are the same,
# store the character in 'max_digit' if it's bigger than what it already stores.
if num[index] == num[index + 1] == num[index + 2]:
max_digit = max(max_digit, num[index])
# If 'max_digit' is NUL, return an empty string; otherwise, return a string of size 3 with 'max_digit' characters.
return '' if max_digit == '\0' else max_digit * 3