DEV Community

Vansh Aggarwal
Vansh Aggarwal

Posted on

LeetCode Solution: 2264. Largest 3-Same-Digit Number in String

Uncovering Triple Trouble: Finding the Largest 'Good' Number in Your String!

Hey everyone! 👋 Vansh here, ready to dive into another fun LeetCode challenge that's perfect for beginners but offers some neat insights. Today, we're tackling problem 2264: "Largest 3-Same-Digit Number in String." Don't let the long name scare you; this one is super approachable and a great way to flex your string manipulation muscles!

The Problem: What's a "Good" Number Anyway?

Imagine you're given a really long number as a string, like "6777133339". Your goal is to find special little segments within this string. We call these segments "good integers" if they meet two simple rules:

  1. Length 3: They must be exactly three characters long.
  2. Same Digit: All three characters must be the exact same digit. Think "777", "333", or even "000".

Your task is to find all such "good integers" and then return the largest one among them. If there are no good integers at all, you should just return an empty string "".

Quick Examples to clarify:

  • Input: num = "6777133339"
    • "777" is a good integer.
    • "333" is another good integer.
    • Between "777" and "333", "777" is larger. So, the output is "777".
  • Input: num = "2300019"
    • "000" is the only good integer. Output: "000".
  • Input: num = "42352338"
    • No three consecutive identical digits exist. Output: "".

A small but important note: leading zeros are totally fine! "000" is a valid good integer.

Intuition: The "Aha!" Moment 💡

When I first read this problem, my brain immediately went to: "Okay, I need to look for patterns of three identical characters." Since we're dealing with a string, the most straightforward way to do this is to simply slide a window of size 3 across the string.

Imagine a magnifying glass that can only see three characters at a time. You start at the beginning, check those three. Then, you slide it one position to the right, check those three, and so on, until you reach the end of the string.

Every time our magnifying glass shows three identical digits (like [7, 7, 7]), we've found a "good integer." Now, how do we find the largest one? Since we're comparing numbers like "999" vs "888" vs "000", and they're all represented as 3-digit strings, comparing them lexicographically (alphabetically, essentially) will work perfectly! "999" is indeed "greater" than "888" in string comparison. This simplifies things a lot!

Approach: Step-by-Step Logic

Let's break down the strategy into clear, executable steps:

  1. Initialize a best variable: We'll need a way to keep track of the largest good integer we've found so far. Let's start it as an empty string (""). This serves two purposes:

    • It acts as a placeholder for when no good integers have been found yet.
    • If no good integers are ever found, this "" will be our final return value, as required by the problem.
  2. Iterate through the string: We need to check every possible substring of length 3. If num has N characters, and we're looking at num[i], num[i+1], and num[i+2], then the index i can go from 0 all the way up to N-3. Why N-3? Because if i is N-3, then i+2 would be N-1, which is the last character of the string. We can't go any further than that!

  3. Check for "goodness": Inside our loop, for each i, we'll check if num[i], num[i+1], and num[i+2] are all the same. This means num[i] == num[i+1] AND num[i+1] == num[i+2].

  4. Update best: If we find a "good" integer (i.e., the condition in step 3 is true):

    • Extract this 3-character substring. Let's call it currentGood. (e.g., num.substr(i, 3)).
    • Compare currentGood with our best good integer found so far. We can use the max() function for strings. best = max(best, currentGood). This will automatically pick the lexicographically (and numerically, in this case) larger string. If best is "", the first currentGood will become best.
  5. Return best: After the loop finishes checking all possible substrings, our best variable will hold the largest good integer, or "" if none were found. Simply return it!

The Code (C++)

Here's the elegant C++ solution embodying this approach:

class Solution {
public:
    string largestGoodInteger(string num) {
        string best = ""; // Initialize an empty string to store the largest good integer found

        // Iterate through the string, stopping 2 characters before the end
        // because we need a substring of length 3 (num[i], num[i+1], num[i+2])
        for (int i = 0; i + 2 < num.size(); i++) {
            // Check if the current character and the next two are identical
            if (num[i] == num[i+1] && num[i] == num[i+2]) {
                // If they are, we found a "good" integer.
                // Extract this 3-digit substring.
                string currentGood = num.substr(i, 3);

                // Compare it with our 'best' found so far.
                // Since 'best' starts empty, the first good integer will be assigned.
                // For subsequent good integers, 'max' will correctly pick the numerically larger one
                // because string comparison works lexicographically (e.g., "999" > "888").
                best = max(best, currentGood);
            }
        }

        // Return the largest good integer found, or "" if none existed.
        return best;
    }
};
Enter fullscreen mode Exit fullscreen mode

Time & Space Complexity Analysis

Let's break down how efficient our solution is:

  • Time Complexity: O(N)

    • We iterate through the num string exactly once using a for loop.
    • Inside the loop, operations like character comparisons (num[i] == num[i+1]) and substr(i, 3) (which extracts a fixed-length 3 substring) take constant time, O(1).
    • The max(best, currentGood) operation also compares two fixed-length 3 strings, taking O(1) time.
    • Therefore, the total time complexity is directly proportional to the length of the input string num. If N is the length of num, it's O(N). This is excellent!
  • Space Complexity: O(1)

    • We use a few extra variables: best and currentGood.
    • Both best and currentGood strings are always of a maximum length of 3. This means the amount of extra memory we use is constant, regardless of how long the input string num is.
    • Hence, the space complexity is O(1). This is as good as it gets!

Key Takeaways

This problem, while seemingly simple, reinforces some fundamental programming concepts:

  1. Sliding Window: It's a classic technique for problems that involve inspecting contiguous subsequences or substrings of a fixed size.
  2. String Comparison: For numbers represented as strings of the same length, lexicographical comparison (max or > operators) works perfectly to find the numerically largest value.
  3. Edge Case Handling: Initializing best to "" elegantly handles the case where no "good" integers are found.
  4. Simplicity Wins: Sometimes, the most straightforward approach is also the most optimal. No complex data structures or algorithms needed here!

I hope this walkthrough helped you understand and appreciate this LeetCode problem! Happy coding!


Author Account: Vansh2710
Published: 2026-04-12 22:50:06

Top comments (0)