Sponsored
Sponsored
This approach involves iterating through the string, checking every possible substring of length 3 to see if it consists of the same character. If it does, keep track of the largest such substring found.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1), constant space is used.
1function largestGoodInteger(num) {
2 let maxGood = "";
3 for (let i = 0; i <= num.length - 3; i++) {
4 if (num[i] === num[i+1] && num[i+1] === num[i+2]) {
5 let curr = num.substring(i, i + 3);
6 if (curr > maxGood) {
7 maxGood = curr;
8 }
9 }
10 }
11 return maxGood;
12}
13
14console.log(largestGoodInteger("6777133339"));
JavaScript utilizes similar logic with localized variables and checks for identifying and updating the largest good integer found by examining each triplet and comparing lexically.
This approach builds upon the basic iteration method, with an early termination feature if the maximum possible good integer ("999") is found. This can optimize cases where digits towards the start of the string quickly identify the upper bound, reducing unnecessary checks.
Time Complexity: Less than O(n) in the best case if "999" is early.
Space Complexity: O(1).
1
This Python version improves on the brute force by attempting to finish early if '999' is encountered, saving processing in cases where inputs allow it.