Skip to main content

Good Indices in a Digit String - Solution & Explanation

MediumPremiumFree on FleetCodeMathString6 min read
Practice this problem

Problem Statement

You are given a string s consisting of digits.

An index i is called good if there exists a substring of s that ends at index i and is equal to the decimal representation of i.

Return an integer array of all good indices in increasing order.

 

Example 1:

Input: s = "0234567890112"

Output: [0,11,12]

Explanation:​​​​​​​

  • At index 0, the decimal representation of the index is "0". The substring s[0] is "0", which matches, so index 0 is good.

  • At index 11, the decimal representation is "11". The substring s[10..11] is "11", which matches, so index 11 is good.

  • At index 12, the decimal representation is "12". The substring s[11..12] is "12", which matches, so index 12 is good.

No other index has a substring ending at it that equals its decimal representation. Therefore, the answer is [0, 11, 12].

Example 2:

Input: s = "01234"

Output: [0,1,2,3,4]

Explanation:

For every index i from 0 to 4, the decimal representation of i is a single digit, and the substring s[i] matches that digit.

Therefore, a valid substring ending at each index exists, making all indices good.

Example 3:

Input: s = "12345"

Output: []

Explanation:

No index has a substring ending at it that matches its decimal representation.

Therefore, there are no good indices and the result is an empty array.

 

Constraints:

  • 1 <= s.length <= 105
  • s only consists of digits from '0' to '9'.

Approach Overview

Problem Overview: You are given a string of digits. An index is considered good if the sum of digits on its left equals the sum of digits on its right. The task is to scan the string and return all indices that satisfy this balance condition.

Approach 1: Brute Force Simulation (O(n^2) time, O(1) space)

Check every index independently. For each position i, iterate over the substring [0..i-1] to compute the left digit sum and over [i+1..n-1] to compute the right digit sum. If the two sums match, record the index as good. This approach uses plain iteration and no extra data structures, but it recomputes the same sums repeatedly, leading to quadratic time for long strings.

Approach 2: Prefix Sum Simulation (O(n) time, O(1) space)

Precompute the total sum of all digits. While iterating through the string, maintain a running leftSum. For index i, compute the right side using rightSum = totalSum - leftSum - digit[i]. If leftSum == rightSum, the index is good. After the check, update leftSum += digit[i]. This eliminates repeated summation and reduces the complexity to linear time. The technique is a standard optimization when dealing with cumulative values in math and string problems.

The key insight is that you never need to recompute sums for each side of the index. Maintaining a running prefix value and deriving the suffix value from the total keeps the algorithm efficient and easy to implement.

Recommended for interviews: The prefix-sum simulation is the expected solution. Starting with the brute force method shows you understand the definition of a good index. Transitioning to the prefix-based optimization demonstrates awareness of common mathematical accumulation patterns and how to reduce repeated work from O(n^2) to O(n).

Solution

We observe that the maximum length of string s is 10^5, and the length of the decimal representation of index i is at most 6 (since the decimal representation of 10^5 is 100000, which has a length of 6). Therefore, we only need to check for each index i whether the substring corresponding to its decimal representation is equal to it.

The time complexity is O(n), where n is the length of the string s. The space complexity is O(1), ignoring the space required for the answer.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force SimulationO(n^2)O(1)Useful for understanding the definition of a good index or when input size is very small
Prefix Sum SimulationO(n)O(1)General case; avoids repeated summation and is the optimal interview solution

Video Solution

leetcode 3817 Good Indices in a Digit String | linear time solution with arithmetics • Code-Yao • 32 views views

Frequently Asked Questions

Is Good Indices in a Digit String easy or hard?
The problem is typically classified as Medium because it requires recognizing the prefix-sum optimization. The brute force idea is straightforward, but identifying how to maintain running sums efficiently is the key step that leads to the optimal O(n) solution.
Good Indices in a Digit String Python/Java solution
In Python or Java, iterate through the string while converting each character to its numeric digit. Maintain a running prefix sum and compute the right-side sum using the total digit sum. This single-pass simulation keeps the implementation short and runs in O(n) time.
How to solve Good Indices in a Digit String in O(n)?
First compute the total sum of all digits in the string. Traverse the string while maintaining a running left sum. For index i, compute the right sum as totalSum - leftSum - digit[i]. If both sides are equal, record the index as good, then update the left sum.
What is the best approach for Good Indices in a Digit String?
The prefix sum simulation approach is the most efficient. Maintain a running sum of digits to the left of the current index and derive the right-side sum from the total digit sum. This allows you to check each index in constant time, producing an overall O(n) time complexity with O(1) extra space.
Is Good Indices in a Digit String asked at Google/Amazon/Meta?
Problems involving prefix sums and digit-string processing appear frequently in interviews at companies like Google, Amazon, and Meta. Variants that require balancing prefix and suffix values or scanning strings with running totals are common interview patterns.
What data structure is used in Good Indices in a Digit String?
The solution primarily relies on simple variables and arithmetic rather than complex data structures. A running prefix sum and the total digit sum are sufficient to compute the right-side sum dynamically while iterating through the string.
What is the time complexity of Good Indices in a Digit String?
The optimal solution runs in O(n) time where n is the length of the digit string. Each index is processed exactly once while maintaining a running prefix sum. The brute force approach that recomputes left and right sums for every index takes O(n^2) time.

Ready to solve this problem?

Practice Good Indices in a Digit String with our built-in code editor and test cases.

Practice on FleetCode