Largest 3-Same-Digit Number in String - Problem

You are given a string num representing a large integer. An integer is good if it meets the following conditions:

  • It is a substring of num with length 3.
  • It consists of only one unique digit.

Return the maximum good integer as a string or an empty string "" if no such integer exists.

Note:

  • A substring is a contiguous sequence of characters within a string.
  • There may be leading zeroes in num or a good integer.

Input & Output

Example 1 — Multiple Good Integers
$ Input: num = "6777133"
Output: "777"
💡 Note: The good integers are "777" and "333". Since "777" > "333", we return "777".
Example 2 — No Good Integer
$ Input: num = "2300019"
Output: "000"
💡 Note: The only good integer is "000" (three consecutive zeros).
Example 3 — No Valid Triplets
$ Input: num = "42352338"
Output: ""
💡 Note: No substring of length 3 consists of only one unique digit.

Constraints

  • 3 ≤ num.length ≤ 1000
  • num only consists of digits.

Visualization

Tap to expand
Largest 3-Same-Digit Number in String INPUT String: num = "6777133" 6 i=0 7 i=1 7 i=2 7 i=3 1 i=4 3 i=5 3 i=6 Window of 3 Good Integers Found: "777" Only one good integer found in this string Input Value num = "6777133" ALGORITHM STEPS 1 Initialize result = "" (empty) 2 Slide Window i from 0 to len-3 3 Check 3 Same num[i]==num[i+1]==num[i+2] 4 Update Max Keep larger substring Iteration Check i=0: "677" -- NO i=1: "777" -- OK i=2: "771" -- NO i=3: "713" -- NO i=4: "133" -- NO FINAL RESULT Maximum Good Integer "777" Found at index 1 Three consecutive 7s Why "777" is Maximum? Only good integer found "777" > "111", "222", etc. Output "777" Key Insight: Single pass O(n) solution: Slide a window of size 3 across the string. Check if all 3 chars are same. Track maximum by comparing digit values (e.g., "999" > "888" > "777"). No sorting needed! Time: O(n), Space: O(1) - Just track result string, constant extra space. TutorialsPoint - Largest 3-Same-Digit Number in String | Optimized Single Pass
Asked in
Google 15 Amazon 12 Microsoft 8
23.4K Views
Medium Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen