You are given a string num representing a large integer. An integer is good if it meets the following conditions:
num with length 3.Return the maximum good integer as a string or an empty string "" if no such integer exists.
Note:
num or a good integer.Example 1:
Input: num = "6777133339"
Output: "777"Explanation: There are two distinct good integers: "777" and "333".
"777" is the largest, so we return "777".
Example 2:
Input: num = "2300019"
Output: "000"Explanation: "000" is the only good integer.
Example 3:
Input: num = "42352338"
Output: ""Explanation: No substring of length 3 consists of only one unique digit. Therefore, there are no good integers.
Constraints:
3 <= num.length <= 1000num only consists of digits.Before attempting this problem, you should be comfortable with:
We need to find the largest "good integer" in the string, where a good integer is a substring of length 3 consisting of the same digit repeated three times (like "111", "222", etc.). The straightforward approach is to scan through the string, check every window of size 3, and whenever we find three consecutive identical digits, we compare its numeric value to our current best and keep the larger one.
res as an empty string and val as 0 to track the largest good integer found.0 to len(num) - 2:val, update both val and res.res.Instead of tracking both the numeric value and the string separately, we can simplify by using string comparison. Since all good integers have the same length (3 characters), lexicographic comparison works correctly for finding the maximum. For example, "999" > "888" > "777" when compared as strings. We just need to handle the edge case where "000" is a valid result but we need to distinguish it from "no good integer found."
res to "0" as a baseline for comparison.res and keep the larger one.res is still "0" and "000" was never found, return an empty string. Otherwise, return res.We can optimize further by observing that we only need to track the digit itself, not the entire 3-character substring. Since all good integers are formed by repeating a single digit three times, we just need to find the largest digit that appears three times consecutively. At the end, we can construct the result by repeating that digit three times.
res to -1 to indicate no good integer found yet.res if it is larger.res is still -1, return an empty string. Otherwise, return the digit repeated three times.The problem asks for the largest good integer, but "000" is still a valid answer if it is the only one found. Initializing the result to an empty string and checking only for non-zero matches causes "000" to be incorrectly skipped. Handle "000" explicitly or use comparison logic that includes it.
If no three consecutive identical digits exist in the string, the answer should be an empty string. Returning "0", a default numeric value, or the last partial match leads to wrong answers. Always track whether any valid match was found before returning.