Good Indices in a Digit String Problem
#3817
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3817.
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 <= 10^5sonly consists of digits from'0'to'9'.
Solution
Approach: Simulation
The string has at most 10^5 characters, so the decimal form of an index has at most 6 digits. For every index i, write i as text t of length k and compare it with the k characters of s that end at position i. If they are equal, i is good.
Complexity: O(n) time (each comparison looks at at most 6 characters) and O(1) extra space, where n is the length of s.
class Solution:
def goodIndices(self, s: str) -> List[int]:
ans = []
for i in range(len(s)):
t = str(i)
k = len(t)
if s[i + 1 - k : i + 1] == t:
ans.append(i)
return ans