You are given a string num
representing a large integer. Return the largest-valued 3-digit combination that consists of the same digit. If no such combination exists, return an empty string.
num
is non-empty and contains only digit characters.To solve this problem, we will perform the following steps:
Here’s how you can implement this strategy in Python:
def largest_good_integer(num):
largest = ""
n = len(num)
for i in range(n - 2):
if num[i] == num[i+1] == num[i+2]:
candidate = num[i:i+3]
if candidate > largest:
largest = candidate
return largest
# Example usage
print(largest_good_integer("6777133339")) # Output: "777"
print(largest_good_integer("2300019")) # Output: "000"
print(largest_good_integer("42352338")) # Output: ""
The time complexity of the solution is (O(n)), where (n) is the length of the input string. This is because we are iterating through the string once and performing constant time checks for each set of three characters.
The space complexity is (O(1)) since we are using a constant amount of extra space for the largest
variable and a few temporary variables.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?