Magicsheet logo

Largest 3-Same-Digit Number in String

Easy
100%
Updated 6/1/2025

Largest 3-Same-Digit Number in String

1. What is this problem about?

The Largest 3-Same-Digit Number in String is an accessible yet tricky string manipulation problem. You are given a string num representing a large integer. Your task is to find the largest "good" integer that appears as a substring of length 3. A "good" integer is defined as a substring consisting of three identical digits. For example, "777" is a good integer, while "778" is not. If multiple good integers exist, you must return the one with the maximum value. If none exist, return an empty string.

2. Why is this asked in interviews?

This Largest 3-Same-Digit Number in String coding problem is often used in screening rounds at companies like Google and Bloomberg. It tests basic string traversal, comparison logic, and the ability to handle edge cases (like "000" being valid but empty strings or no matches being invalid). It's a test of "clean code" skills—how simply and efficiently can you solve a problem that sounds easy but can be made over-complicated with too many nested loops.

3. Algorithmic pattern used

The core String interview pattern here is a single-pass traversal. You iterate through the string and check groups of three consecutive characters. A simple way is to check if num[i] == num[i-1] and num[i] == num[i-2]. By keeping track of the maximum digit found that satisfies this condition, you can determine the largest 3-same-digit number. Since there are only 10 possible "good" strings ("999", "888", ..., "000"), another approach is to search for these strings in descending order and return the first one you find.

4. Example explanation

Suppose the input string is num = "2300019992".

  1. We check indices 0-2: "230" (No)
  2. Indices 1-3: "300" (No)
  3. Indices 2-4: "000" (Yes! Current Max = "000")
  4. Indices 3-5: "001" (No)
  5. ...
  6. Indices 6-8: "999" (Yes! "999" > "000", so Current Max = "999") The result is "999".

5. Common mistakes candidates make

  • Overcomplicating the search: Using complex regular expressions or nested loops where a simple i and i+2 check would suffice.
  • Handling "000" incorrectly: Forgetting that "000" is a valid good integer and might be the largest one if no others exist.
  • Efficiency issues: Creating many new substring objects in a loop, which can be slow in some languages (though for this specific problem size, it usually passes).
  • Boundary errors: Accessing num[i+1] or num[i+2] without checking if the index is within the string length.

6. Interview preparation tip

For string problems involving fixed-length patterns, consider the "descending search" strategy. If there's a small, finite set of possible answers (like the 10 strings "000" through "999"), it's often easier to check for the presence of the best possible answer first. This makes the code very readable and less prone to logic errors.

Similar Questions