We are given a string s of length n (2 ≤ n ≤ 10^5). There are m beautiful words (1 ≤ m ≤ 100), each length up to 1000. We need to count how many distinct beautiful words can appear as the visible string when the Martian opens two disjoint intervals [a,b] and [c,d] with 1 ≤ a ≤ b < c ≤ d ≤ n. He reads characters from left to right across the opened eyes (i.e., concatenation of s[a..b] and s[c..d]), yielding a string of length (b-a+1)+(d-c+1). Note that the two segments are non-overlapping and there is a gap between them (b < c). The Martian can choose any such a,b,c,d. So the set of possible visible strings is all strings that can be obtained by concatenating two (non-empty? Not necessarily; the problem says "opens two non-overlapping segments of consecutive eyes". Usually "segments" implies they could be of length at least 1? The phrase "segments of consecutive eyes" suggests each segment must contain at least one eye. Also in formal definition a ≤ b and c ≤ d, so both segments have at least one element. So each segment is non-empty. So the visible string is s[a..b] + s[c..d] with 1 ≤ a ≤ b < c ≤ d ≤ n.
We need to find among the m beautiful strings, which can be formed in this way for some choices of a,b,c,d.
Constraints: n up to 1e5, m ≤ 100, each beautiful word length up to 1000. Total length of beautiful words sum ≤ 100*1000 = 1e5 as well. So we can handle each beautiful word individually or together.
We need to compute for each beautiful word p, whether there exist indices a,b,c,d such that s[a..b] concatenated with s[c..d] equals p. Note that the concatenation is two substrings of s taken in order, with a gap in between (they don't overlap, and there is at least one index between b and c that is not included; but does that matter? The gap can be zero? The condition b < c, so there is at least one index not included; but that doesn't affect the string itself. The string p is formed by two substrings; they could also be adjacent if b+1 = c? But condition says b < c, so they are not overlapping but could be adjacent? If b+1 = c, then the two segments are adjacent but still separate; the concatenated string would be s[a..b] + s[b+1..d] which is actually s[a..d], i.e., a single contiguous substring. But note that the Martian opens two segments; if they are adjacent, that's allowed? The problem says "two non-overlapping segments". Adjacent segments are non-overlapping (they share no points). So yes it is allowed. So essentially the visible string is the concatenation of two disjoint (possibly adjacent) substrings of s, preserving order. That includes contiguous substrings as a special case when the gap is zero (b+1=c). So any string that is a contiguous substring of s is also obtainable (by taking a single segment as two adjacent segments of lengths L1 and L2? But we require two segments, each non-empty. If we want a contiguous substring of length L, we could split it into two non-empty parts: for any split point k (1 <= k < L), we take a..b corresponds to first k characters, and c..d corresponds to the remaining L-k characters, with c = b+1. So yes any contiguous substring of length at least 2 can be obtained by splitting into two non-empty parts. What about length 1? A single eye? But we need two segments, each non-empty, so the total length is at least 2. So length 1 strings cannot be obtained unless n≥2 and we open two segments each of length 1? That yields length 2. So length 1 strings are not obtainable. But beautiful words may be of length 1; we need to check if length 1 can be obtained. For a string of length 1, we need to open two segments but the concatenated string length must be 1. But total length is sum of lengths of two non-empty segments, which is at least 2. So impossible. So any beautiful word of length 1 is not obtainable. But careful: Could we open a segment of length 0? No, because a ≤ b so each segment has at least one eye. So length 1 cannot be formed. So we can safely rule out any beautiful word of length 1.
Thus the problem reduces to: Given s and a set of patterns p (length up to 1000), check if p can be represented as concatenation of two (non-empty) substrings of s (in order, possibly adjacent). Equivalent: there exists a split position k (1 ≤ k < |p|) such that the prefix p[1..k] occurs as a substring in s, and the suffix p[k+1..|p|] occurs as a substring in s, and additionally, there exist occurrences of these substrings at positions i..i+k-1 and j..j+|p|-k-1 respectively, such that i+k-1 < j (since b = i+k-1, c = j, and we need b < c). That is, the first occurrence must end before the second occurrence starts. The substrings could be anywhere in s, not necessarily disjoint? Actually they must be non-overlapping and with the first ending before the second starting (strictly). So we need to find a split and occurrences such that end position of first < start position of second.
If we can find any such pair (with possibly overlapping occurrences if they are not overlapping? Condition requires end < start, so they are disjoint and non-adjacent allowed, but overlapping would be invalid because then the same character would be used twice? The Martian opens two segments; if they overlap, then some eyes would be opened twice, but physically, they are patches removed from eyes; each eye can be opened only once, but opening overlapping segments would mean we open eyes twice? Actually the Martian "opens two non-overlapping segments". So the segments cannot overlap. So the occurrences must be disjoint and the first must end before the second starts. So we need end index < start index.
Thus, for each beautiful word p, we need to decide existence of split k and positions i,j with s[i:i+len1-1] = p[0:len1-1] and s[j:j+len2-1] = p[len1:], and i+len1-1 < j.
We can treat s as text. Since n up to 1e5 and total pattern lengths up to 1e5, we could use string matching algorithms like building a suffix automaton or suffix array, or using Z-alg for all occurrences. Simpler: For each pattern p, we can check all possible splits? Length of p up to 1000, so splits up to 999. For each split, we need to check if there exist occurrences with the order constraint. That seems feasible if we can quickly answer: given a pattern substring (prefix or suffix), does it occur in s? And can we also check the ordering condition? But ordering condition couples the two substrings: we need one occurrence of prefix and one occurrence of suffix such that the prefix occurrence ends before the suffix occurrence starts.
We could precompute for each position in s, the leftmost occurrence starting at each index? Actually we need to know if there exists any occurrence of prefix that ends before some occurrence of suffix starts. Equivalent to: Let L be the set of ending positions of occurrences of the prefix in s; let R be the set of starting positions of occurrences of the suffix. We need to check if there exists l in L and r in R such that l < r. That is, min(L) < max(R) is not sufficient because we need some l < some r. More precisely, we need min L < max R? Actually if min L < max R, it's possible that min L could be less than max R, but we need l < r for some pair. The condition that exists l in L and r in R with l < r is equivalent to min(L) < max(R) OR maybe more nuanced: If the smallest ending position is less than the largest starting position, then we can take that smallest ending and that largest starting, but we need to ensure that the smallest ending is indeed less than the largest starting? Wait: Suppose we have L = {5,10}, R = {6,7}. Then min(L)=5, max(R)=7, 5<7 and indeed there exist l=5,r=6 (5<6). So min(L) < max(R) is sufficient? Consider L = {8,9}, R = {1,2}. min(L)=8, max(R)=2, 8<2 false, but does there exist l<r? l can be 8, r=1 -> 8<1 false; l=8,r=2 false; l=9,r=1 false; l=9,r=2 false. So none. So the condition min(L) < max(R) seems necessary and sufficient? But consider L = {3,7}, R = {5,9}. min(L)=3, max(R)=9 => 3<9 true, exists l=3,r=5 (3<5) works. Good. Consider L = {4,6}, R={5,7}. min(L)=4, max(R)=7 => 4<7 true, we have l=4,r=5 works. So yes, existence of some l < r is equivalent to (min(L) < max(R)). But careful: What if the sets are such that all L are larger than all R? Then min(L) > max(R) so min(L) < max(R) false. If there is any overlap but not necessarily min<max? Actually if min(L) < max(R) then there exists at least one l < r: pick l = min(L) and r = max(R). If min(L) < max(R), then l < r. But is it possible that min(L) < max(R) but still no pair l<r? That would require that for every l in L and every r in R, l >= r. If min(L) < max(R), then there exists some l that is the minimum, and some r that is the maximum. If min(L) < max(R), then min(L) is less than max(R). However, it could be that the minimum l is actually less than the maximum r, but maybe the minimum l is from a position that is still >= all r? Wait, if min(L) < max(R), then we have l0 = min(L) and r0 = max(R). Since l0 < r0, that pair itself satisfies l0 < r0. So indeed that gives a valid pair. But is it guaranteed that l0 and r0 correspond to occurrences of the respective substrings? Yes, they are valid occurrences. However, we also need the segments to be non-overlapping: we need the ending position of the prefix (which is l) to be less than the starting position of the suffix (which is r). Wait careful: We defined L as ending positions of occurrences of prefix, and R as starting positions of occurrences of suffix. The condition is l < r. So if we take l = min(L) and r = max(R), then l < r suffices. But note: l = min(L) is the smallest ending position among all occurrences of prefix. r = max(R) is the largest starting position among all occurrences of suffix. If l < r, then indeed we have a pair where the ending is before the start. However, does the fact that l is the smallest ending and r is the largest start guarantee that they correspond to occurrences that are disjoint? Possibly the smallest ending could be from an occurrence that ends early, and the largest start could be from an occurrence that starts late, so indeed they are disjoint (since l < r). So condition min(L) < max(R) is sufficient. But is it necessary? If there exists some l < r, then obviously min(L) ≤ l < r ≤ max(R), so min(L) < max(R). So yes, equivalent.
Thus, for a given split, we can check existence by computing:
- For the prefix p[0:k-1] (0-indexed), find the minimal ending position of any occurrence in s.
- For the suffix p[k:], find the maximal starting position of any occurrence in s.
If minimal ending < maximal start, then there exists a pair. But careful: Could there be an issue with overlapping if the occurrences themselves are not valid because they might be the same occurrence? They are distinct segments? They are separate occurrences; they can even be the same physical location? They must be non-overlapping, but if we take minimal ending from one occurrence and maximal start from another, they could be overlapping if the minimal ending is from a long occurrence that extends beyond the start of the other? Wait: l is the ending index of the prefix occurrence. For an occurrence of the prefix that starts at i and length len1, its ending index is i+len1-1. The condition l < r ensures that the ending index of the first occurrence is strictly less than the starting index of the second occurrence. So if we pick l = min(L) and r = max(R), we are fine. However, we must ensure that the two occurrences are from different segments, but they could be overlapping if l >= r, but we have l < r. So no overlap. So condition is correct.
But wait: Is it always possible to combine these two occurrences? They are just two substrings; the Martian opens exactly those two intervals. There is no additional constraint that the two intervals cannot overlap other parts of s? They are just intervals; we can choose a = start of prefix occurrence, b = end of prefix occurrence, c = start of suffix occurrence, d = end of suffix occurrence. Provided b < c, which is l < r. So yes.
Thus, for each split k, we need to compute:
- min_end(prefix) = minimal (i+len1-1) over all occurrences of prefix in s.
- max_start(suffix) = maximal (j) over all occurrences of suffix in s.
If min_end < max_start, then p is achievable via that split.
But we also need to consider the case where the two occurrences might be the same substring if the prefix and suffix are the same? That's fine as long as they are disjoint intervals. But if the prefix and suffix are identical and occur at the same location? Then we would need two disjoint intervals; we can't use the same characters twice. So we must pick two different occurrences (or same string but non-overlapping). Our condition using min_end and max_start might inadvertently combine occurrences that are the same physical interval? No, because if we pick the minimal ending and maximal start, they are from possibly different occurrences. But what if the only occurrence of the prefix ends at position x, and the only occurrence of the suffix starts at position y, and x < y. That's fine even if those occurrences overlap? Overlap would require that the prefix's interval [i, i+len1-1] and suffix's interval [j, j+len2-1] intersect. If i+len1-1 < j, they are disjoint. So min_end < max_start ensures no overlap.
Thus the problem reduces to precomputing for any substring (of s) some information: the minimum ending index of its occurrence, and the maximum starting index of its occurrence. However, we have many queries (for each beautiful word and each split). The total number of substrings we query is sum over beautiful words of (len(p)-1) which is at most 100 * 1000 = 100k. So up to 100k queries. For each query we need to know: given a string x (the prefix or suffix), does it occur in s? If yes, compute its minimal ending index (i.e., the smallest i+|x|-1 over all occurrences) and maximal starting index (i.e., the largest i over all occurrences). We also need perhaps the maximum starting index of suffix and the minimal ending index of prefix.
We can preprocess s to answer substring existence and these extremal positions quickly. Since query strings are up to length 1000, we could build a suffix automaton (SAM) or suffix array with LCP, but we also need to compute min end and max start for each substring. The SAM can store for each state (which corresponds to a set of end positions) the min and max positions where the substring occurs. Actually, the SAM typically stores the end positions (or the length). For each state, we can compute the minimum ending position? Actually we need the minimal ending index for occurrences of that substring. Alternatively, we could compute the earliest occurrence (starting position) and the latest occurrence. But we need ending positions. However, we can derive ending from starting + length -1.
Better: For any substring, we need two values:
- The minimum possible ending position: min_{i where s[i:i+len-1]=x} (i+len-1)
- The maximum possible starting position: max_{i where s[i:i+len-1]=x} i
We can precompute for each substring? Not feasible for all substrings.
We can answer queries by using a data structure that can find any occurrence of a pattern and then compute its earliest ending and latest start. Since patterns are up to 1000 length, we could precompute rolling hash of s and then for each query pattern, find all occurrences? But there could be many occurrences (up to O(n) per pattern). That would be too slow if we iterate over all occurrences for each query (100k * n). Not acceptable.
We need a more efficient method.
Observation: n is up to 1e5, total pattern lengths is 1e5. We can build an Aho-Corasick automaton for all beautiful words and their prefixes/suffixes? But we need to check all splits. Actually we need to evaluate many substrings (prefixes and suffixes) of the beautiful words. There are up to sum(len(p)) such substrings (each prefix and suffix). That's about 2e5 maybe. Could process each substring separately using some precomputed data.
Alternatively, we can approach the problem by considering all possible ways to split p into two parts, and for each part, we need to know if there exists an occurrence in s with appropriate bounds.
We could precompute for s: For each position i, the longest prefix of s starting at i that is also a prefix of some beautiful word? Not exactly.
Another approach: For each beautiful word p, we want to know if there exist i<j such that s[i..i+len1-1] = p1 and s[j..j+len2-1]=p2 with i+len1-1 < j. This is similar to checking if p occurs as a subsequence of two substrings? But no.
We could precompute two arrays for s:
- For each position i, what is the earliest ending of an occurrence of a given pattern? Not pattern-specific.
Maybe we can use suffix array with LCP and then binary search for each query substring to find its occurrence range in the suffix array, and then from that range we can query a segment tree to get the minimum ending (or maximum start) among those suffixes? However, ending position = SA[idx] + len - 1. But len varies per query, so we cannot precompute static values. For each query substring, we need to consider only those suffixes that have the substring as prefix. That set corresponds to a contiguous interval in the suffix array (by LCP). Within that interval, we could query the minimum (SA[idx] + len - 1) and maximum SA[idx] (the start positions). But SA[idx] + len - 1 is not a fixed function over the interval because it adds len (the query length). However, if we know the set of start positions i where s[i:i+len-1] = x, then we can compute min(i+len-1) = (min i) + len - 1? Not exactly: min(i+len-1) = (min i) + len - 1 only if we take min over i; because adding len-1 is a constant shift for each i, so minimizing i+len-1 is equivalent to minimizing i. So min_end = (min_start) + len - 1, where min_start is the smallest starting index among occurrences. Similarly, max_start is simply the maximum starting index among occurrences. So we actually only need, for a given substring x, its minimum starting index and maximum starting index among all its occurrences. Because min_end = min_start + |x| - 1, max_start is needed directly. So we need two values per query: min_start(x) and max_start(x). If we can compute these quickly, we can answer the condition: min_start(prefix) + |prefix| - 1 < max_start(suffix). Equivalent to min_start(prefix) + len_prefix - 1 < max_start(suffix).
Thus we need a data structure to answer for arbitrary substring x (up to length 1000) its minimum and maximum occurrence start positions in s. We also need to know if x occurs at all (i.e., there is at least one occurrence). If no occurrence, then that split fails.
We have up to about 100k queries. Length of s is 1e5, so building a suffix array or suffix automaton can answer existence and also allow us to compute min and max start positions for each substring.
Let's explore using a suffix automaton. In a SAM, each state corresponds to a set of end positions of substrings that are in the equivalence class (i.e., the set of end positions of all occurrences of the substrings represented by that state). Actually, each state corresponds to a set of substrings (those with lengths in [link.len+1, state.len]) that share the same set of end positions (or rather, the set of end positions of the substrings is the set of end positions of the state's occurrences). More precisely, for each state we can compute the set of positions where the substrings belonging to that state end (the endpos set). But the SAM typically built online records the end positions when extending. Usually, we can compute for each state the minimum and maximum end position (or the min and max length?). But we need start positions, not end positions. However, if we know the end position e and the length len of the substring, then start = e - len + 1. But the state in SAM corresponds to many substrings of varying lengths. That complicates things: For a given query substring x of length L, we find the state that represents x (by traversing the automaton), and then we need the minimum start among occurrences of exactly x. The state's endpos set corresponds to all end positions of occurrences of x (and longer strings? Actually, if state v corresponds to a set of substrings that have the same endpos set, those substrings are the ones with lengths in (link(v).len, v.len]. For a specific substring x of length L, if we reach state v after processing x, then x is represented by state v (or possibly by some state on the link chain if L is less than v.len?). Actually, when we traverse the SAM with the characters of x, we end at a state that represents the set of substrings that are suffixes of x? Wait: The standard procedure: Starting from the initial state, for each character of x we follow the transition. If we can go through all characters, then the substring x is present, and the state we end at represents the set of all substrings that are suffixes of x that have the same endpos set? Actually, the state we reach after processing the entire string x corresponds to the equivalence class of substrings that are the longest strings with that endpos set. That state has a "length" which is the maximum length of substrings in its class. The substring x might be shorter than that length; in that case, x is represented by some state on the suffix link chain from that state (the state whose length equals L, or the one that has length in range). But we can still locate the exact state that corresponds to x's endpos set: It is the state on the suffix link chain whose length is exactly L (or we can store for each state the min and max start for all substrings of that state? However, for a specific length L, the set of end positions for substring x is a subset of the state's endpos set? Actually, for any state v, all substrings represented by v share the same endpos set. So if we have a state v, then for every length in (link(v).len, v.len], the substring defined by taking any occurrence's end position e and the length L (where L in that interval) yields a substring that ends at e. However, the substring of length L might also be represented by some other state if L is exactly the length of a state on the link chain? Actually, the SAM property: For each state v, the set of substrings it represents are those with lengths in (len(link(v)), len(v)]. And they all have exactly the same endpos set as v. So if we have a substring x of length L, and we traverse the SAM to reach some state after reading x, then x is a substring, but the state we end at may have len >= L. The exact set of end positions for x is the endpos set of the state on the suffix link chain whose length is exactly L (if such state exists) OR it's the same as the endpos set of v if L is in (len(link(v)), len(v)]? Actually, if we reach state v after processing x, then the path we took corresponds to x. The state v's longest string is some string w that has x as suffix. However, the endpos set of x is the same as the endpos set of the state that has length exactly L, which is the state we get by following suffix links from v until we find a state u with len(u) == L (or len(u) <= L but we can also compute that). In practice, to get the endpos set for x, we can climb suffix links until we find a state with length exactly L. But that state's endpos set is exactly the set of end positions of x. However, all states store the same endpos set for all substrings in their length range? Actually, each state's endpos set is the set of ending positions of all occurrences of the strings it represents. If we have a state u, then for any length L in (len(link(u)), len(u)], the substring of that length that is a suffix of the longest string of u will have the same endpos set as u. So the endpos set for x is the same as the endpos set of the state we get that has len exactly L (if we have a state with that exact len, but we might not have a state for each length; the SAM compresses, but there is a state for each distinct endpos set. For a given length L, the state representing substrings of length L with a particular endpos set is the state on the suffix link chain whose len is >= L and link.len < L. Actually, the state that has the correct endpos set is the one where len(v) is the maximum such that the represented set includes length L, i.e., L in (len(link(v)), len(v)]. That state v is the one we end at after traversing x (if we traverse all characters, the state we land at has len(v) >= L, and the correct state for the exact length L is actually the same v if len(link(v)) < L <= len(v). Because any substring of length L that is a suffix of the longest string of v will have the same endpos set as v. So x, being of length L, is a suffix of the longest string of v (since we traversed the whole x and ended at v, the longest string of v has x as a suffix). Therefore, x's endpos set is exactly the endpos set of v, provided that L > len(link(v)). If L <= len(link(v)), then x would be represented by some ancestor state. But we have traversed exactly L characters, so the state we end at after reading all L characters is a state that represents substrings of length up to len(v). However, it's possible that len(v) > L, but the condition for x's endpos set to equal v's is that L is not a length that corresponds to a different endpos set. The SAM construction ensures that each distinct endpos set corresponds to a state. The strings represented by state v are those with lengths in (len(link(v)), len(v)]. So if L lies in that interval, then x is represented by v and its endpos set is v's endpos set. If L is exactly len(link(v)), then x would be represented by link(v). Actually, if L = len(link(v)), then x is actually the longest string of link(v) and thus belongs to link(v). In the traversal algorithm, after reading L characters, we might be at state v, but if L = len(link(v)), then the correct state for x is link(v) because its endpos set is different? Let's recall: When we traverse a string x, we start at root and follow transitions. After processing the whole x, we end at some state p. That state p corresponds to the entire string x? Actually, if the path exists, the state we arrive at is the state that represents the set of end positions for all occurrences of x. However, the length of x may be less than len(p). Typically, the state we end at after reading x is the state that has x as its longest string? Not necessarily. For example, consider SAM of "ababa". If we traverse "aba", we might end at a state with longest string "aba"? Usually, the SAM built by online algorithm ensures that after adding each character, the "last" state corresponds to the whole prefix. When we traverse an existing substring, we follow transitions; the state we reach may have a longer longest string, but the set of end positions of x might be a superset? Let's think: In a SAM, each state corresponds to an equivalence class of substrings that have the same set of end positions. The transition function from the root following the characters of x leads to a state that represents a class where the longest string is some string that ends with x, but the class might contain strings longer than x. However, is it guaranteed that x itself belongs to that class? For x to be in the class, its set of end positions must be exactly that of the state. The transition from root by x gives us a state that represents the set of end positions of all occurrences of x? Actually, I recall: In a SAM, we can test if a string is a substring by traversing. If we can traverse all characters, then the string is present. The state we end at is not necessarily the state representing x; it could be a state whose longest string is longer than x, but x is a suffix of that longest string and shares the same end positions? Let's recall: In SAM, each state corresponds to a set of end positions. For a given substring x, the set of end positions of x is exactly the endpos set of the state that we would reach if we started from the initial state and followed the path labeled x, and then take the state's endpos set if its minimum length (link.len+1) <= |x| <= state.len? Actually, the standard property: For any state v, the set of substrings represented by v are those with lengths in (len(link(v)), len(v)] that are suffixes of the longest string of v. The longest string of v is the one we get by following some path? More concretely, after building SAM, we can compute for each state the list of end positions (or at least the size). To answer queries about occurrences of a pattern x, we can traverse the SAM to find the state corresponding to x: start at root, follow chars; if stuck, pattern not found. If we can follow, let's call the state we end at as p. Then, to get the number of occurrences of x, we typically use the size of the endpos set of p, but only if |x| is between link(p).len+1 and p.len. Actually, the number of occurrences of x is the size of the endpos set of the state that exactly represents x. But if |x| is less than or equal to link(p).len, then the endpos set of p might be larger? I need to recall precisely: In SAM, each state corresponds to a set of end positions for a set of substrings that are suffixes of the longest string of that state and have lengths in a specific interval. The state's endpos set is the same for all substrings it represents. If we traverse x and end at state p, then x is a substring; the state that represents x is either p itself if link(p).len < |x| ≤ p.len, otherwise it is the state reachable by following suffix links from p until we find a state q with q.len >= |x| > link(q).len. Actually, the correct state for x is the state whose length interval contains |x|. Since following transitions from root yields a state whose longest string is exactly x? Not exactly. Let's take a concrete example: s = "ababa". Build SAM. The substring "a" occurs at positions 1,3,5. The state for "a" likely has len=1. The state for "aba" occurs at positions 3? Actually "aba" occurs at positions 1 and 3? Let's build mentally. For s="ababa", the SAM states: I'll construct: start state 0. Add 'a' (position 1): new state 1, len=1, link to 0. Add 'b' (position 2): new state 2, len=2, link? It will link to state for "b"? Actually after adding 'b' to "ab", we have. Might be complex.
But there is known technique: To find all occurrences of a pattern x, we can traverse SAM to get the state representing x (the state after traversing, and if its length is too large we might need to follow suffix links until length matches). Actually, a common method to count occurrences is: For each state, we store its "occurrence count" (size of endpos set) by propagating from longer to shorter via suffix links. This count is the number of occurrences of any string represented by that state. But if we want the number of occurrences of a specific pattern x, we traverse to state p (the state after reading x). Then the occurrence count for x is the count of p, regardless of whether p.len > |x|? Wait, if p.len > |x|, does the count of p equal the number of occurrences of x? Consider pattern "a" in "aa". SAM of "aa": states: root, after 'a' first: state 1 len=1. After second 'a', new state 2 len=2, link to state 1 (since "a" is suffix). Traversing "a": from root follow 'a' leads to state 1? Actually from root, there is transition 'a' to state 1 (len=1). So state 1 is reached, len=1 matches |x|. Count of state 1 is 2 (occurrences of "a"). Good. If we traverse a pattern that is a suffix of a longer state, say pattern "aba" in "ababa". Possibly the state after traversing "aba" might have len=3 or more? I think in properly built SAM, the transitions are defined such that following the characters of x from the initial state leads to a state that represents the set of end positions of x. Because the SAM is a DFA of all substrings: each state corresponds to an equivalence class, and the transition function is defined for each character. When you follow the string x, you will end at the state that corresponds to the equivalence class of x (the set of end positions). Actually, that's correct: The SAM is a finite automaton that recognizes all substrings of s. The language accepted from the initial state to any state is the set of substrings. Moreover, each state corresponds to a set of substrings that share the same right context (i.e., same set of end positions). For a given substring x, the state reached by reading x is the state representing exactly the equivalence class of x. Because the transitions are deterministic, and the state you end in after reading x is uniquely defined. And that state's longest string is exactly x if x is the longest string in that equivalence class? Not necessarily; consider the case where there are multiple substrings with the same endpos set. For example, in string "aaaa", substrings "a", "aa", "aaa", "aaaa" all have different endpos sets? Let's compute: "a" occurs at {1,2,3,4}. "aa" occurs at {2,3,4}. "aaa" at {3,4}. "aaaa" at {4}. So they have distinct sets, so each will have its own state. Good. In string "abab", substrings "ab" and "b"? Actually "ab" occurs at positions 2,4; "b" occurs at 2,4? "b" occurs at 2? Let's list: s= a b a b. Positions:1:a,2:b,3:a,4:b. "b" occurs at {2,4}. "ab" occurs at {2,4}? Substring "ab" starting at 1? Actually "ab" starting at 1 is positions 1-2 -> "ab", that's an occurrence? Yes, "ab" occurs at start 1 and 3? Let's check: start 1: a b -> "ab"; start 3: a b -> "ab". So "ab" occurs at {1,3}? Wait end positions: For "ab", if we consider end index, the substring of length 2 ending at position 2? Typically when building SAM, end positions are the indices where the substring ends. "ab" ending at position 2? Actually substring of length 2 that ends at position 2 comprises s[1..2] = "ab". Similarly ending at position 4 comprises s[3..4]="ab". So end positions for "ab" are {2,4}. "b" ends at positions 2 and 4 as well. So "ab" and "b" have same endpos set {2,4}. In the SAM, there will be a state representing these substrings; the longest string in that class is "ab" (len=2), and the shortest is "b" (len=1). So state's len=2, link to state representing "b"? Actually the link would point to state with longest string "b" (len=1). In that case, if we traverse "b", we would go from root following 'b' and we would end at the state representing "b"? But the state for "b" is the link state of the "ab" state? Usually, transitions: from root, 'b' leads to the state representing "b". So there is a state for "b". In this SAM, "b" has its own state because its endpos set is {2,4} as well? Actually "b" and "ab" share same endpos set, so they belong to the same equivalence class? Wait the equivalence class is defined by equality of endpos sets. Since "b" and "ab" have the same endpos set, they should be in the same state. But does the SAM assign them to the same state? Let's recall SAM construction: Each state corresponds to a set of end positions. The set of substrings represented by a state are those that have that exact endpos set. So "ab" and "b" have same endpos set, so they belong to the same state. The state's longest string is "ab" (length 2) and its shortest length is length of link(state) + 1? Actually the substrings represented by that state are those with lengths in (len(link), len(state)]. Since link of that state is the state representing the longest suffix of "ab" that has a different endpos set. The longest suffix of "ab" is "b". But "b" has the same endpos set as "ab"? In this example, they do have the same endpos set, so the link of the state for "ab" would not point to the state for "b", because link must point to a state with a different endpos set that is the longest suffix with a different endpos set. Since "b" has same endpos set, the link should skip over it to a state with different endpos set, like maybe the state for empty string? Let's compute properly. For s="abab", the SAM: Many online resources confirm that "ab" and "b" are in same state? Actually I'm not entirely sure. Let's derive SAM properties: The endpos equivalence groups partition substrings. Two substrings are equivalent if they have the same set of ending positions. For "abab", endpos("b") = {2,4}. endpos("ab") = {2,4} as well. So they are in the same equivalence class. Therefore, the SAM state representing that class has longest string "ab" (len=2) and shortest string length? The class includes all substrings whose endpos is exactly {2,4}. Which substrings have that? "b", "ab". So the lengths are 1 and 2. So the state's len = 2, and its link should point to the state representing the longest suffix of "ab" that has a different endpos set. The longest suffix of "ab" is "b", but "b" has same endpos set, so we go to the next suffix: "" (empty) which has endpos set {0,1,2,3,4}? Actually empty string is not represented. So link points to the initial state (which represents empty string). So the link goes to root. So the state for "ab" has link to root, and its length is 2. Then, is there a separate state for "b"? No, because "b" belongs to this same state. So there is no state whose longest string is "b". However, when traversing from root with 'b', which state do we go to? The transition from root on 'b' must lead to a state that represents the substring "b". Since "b" is in the class with longest "ab", the state we go to is that same state? But then that state's longest string is "ab", not "b". However, the automaton must accept "b". When we read 'b', we should end in a state that represents the set of substrings that are suffixes of the current string and have the appropriate endpos. Actually, the transition function from root on 'b' should lead to the state representing the equivalence class of "b". Since "b" is in the class with "ab", the state for that class is the one with longest "ab". So yes, the transition leads to that state. So after reading "b", we are at state with len=2, but the string we have read is "b" of length 1. The state's len is 2, but that's okay; the state represents multiple substrings. The string "b" is represented by that state because 1 is in (len(link), len(state)] = (0,2] since link is root with len=0. So indeed "b" is in that state. So the state we end at after reading "b" is the correct state for "b". So indeed, for any substring x, traversing the SAM leads to a state p such that x is represented by p (i.e., its endpos set is p's endpos set). The length condition is that |x| must be in (len(link(p)), len(p)]. Since we followed transitions, we know that the longest string of p is some string that has x as suffix, and the length of x is ≤ len(p). But could it be that |x| ≤ len(link(p))? If that happened, then x would be represented by an ancestor state, not p. But can that happen when we traverse? Suppose we have state p with len=5, link(p) with len=3. If we read a string x of length 2, and following transitions we end at p. Is that possible? Let's test: In a DFA of substrings, transitions are defined such that from any state, reading a character leads to a state representing the longest suffix of the current string plus that character that appears. Actually, the SAM is built so that it is the minimal DFA accepting all substrings. The state we are in after reading a string w is the state that represents the equivalence class of w. So if w is of length 2 and we end at p, then p must be the equivalence class of w, so w belongs to p, so |w| must be in (len(link(p)), len(p)]. So it cannot be ≤ len(link(p)). Because if |w| ≤ len(link(p)), then w would be a suffix of the longest string of link(p) and would have the same endpos as link(p)? Actually, the definition of equivalence classes: If w's length is less than or equal to len(link(p)), then w's endpos set would be a superset of p's? Let's not overthink; it's known that after traversing a string w, we arrive at a state that represents w, i.e., the endpos set of w is exactly the endpos set of that state. Therefore, |w| is between link(p).len+1 and p.len inclusive. So it's safe: when we traverse x, we end at state p where x is represented by p. So we can use p's endpos set for x.
Thus, we can use SAM to answer queries for any substring x: if traversal succeeds, we get state p. Then we need to know, for that state, the minimum start position among occurrences of x? But the state's endpos set gives end positions of all occurrences of x. We need start positions: start = end - |x| + 1. Since |x| is known, we can compute min_start = min_{e in endpos(p)} (e - |x| + 1) = (min_endpos(p)) - |x| + 1? Actually min_start is not simply (min_endpos - |x| + 1) because the minimum start might come from a larger end position? Let's derive: For a fixed length L = |x|, start = end - L + 1. So minimizing start is equivalent to minimizing (end - L + 1) = (min_endpos) - L + 1, because subtract L+1 is monotonic. So the smallest start corresponds to the smallest end position. Similarly, the largest start corresponds to the largest end position? Actually max_start = max_{e} (e - L + 1) = (max_endpos) - L + 1. So indeed, if we know the minimum and maximum end positions in the endpos set of p, we can compute min_start and max_start as functions of L. However, careful: The endpos set for state p corresponds to all occurrences of all substrings represented by p. But we need the end positions specifically for the substring x, which is of length L. Since all substrings represented by p share the same endpos set, yes, the set of end positions for x is exactly the endpos set of p. So min_endpos(p) and max_endpos(p) are the min and max ending positions of occurrences of x. Therefore min_start = min_endpos(p) - L + 1, max_start = max_endpos(p) - L + 1.
But wait: Is it true that for any substring x represented by state p, its occurrences all end at positions that are exactly the endpos set of p? Yes, because the state's endpos set is the set of end positions of all occurrences of the substrings in its class. Since x is in the class, its occurrences end exactly at those positions (maybe not all? Actually, if a state p represents a set of substrings, they all have the same set of end positions. So for each occurrence of x, its end position is in endpos(p); conversely, each end position in endpos(p) corresponds to an occurrence of the longest string of p, but does it guarantee an occurrence of x? Since x is a substring of the longest string, and the end position e in endpos(p) means that the longest string of p occurs ending at e. Does that imply that x occurs ending at e? For x to occur ending at e, we need that the substring of length L ending at e equals x. Since the longest string of p ending at e has x as a suffix (because x is represented by p and is a suffix of the longest string of p), yes, x occurs ending at e. So indeed, the set of end positions for x is exactly endpos(p). So we can use p's endpos set.
Thus, for each query substring x, we can compute:
- L = len(x)
- p = state after traversing x (if fails, no occurrence)
- min_end = minimal end position in endpos(p) (call it min_e)
- max_end = maximal end position in endpos(p) (call it max_e)
- Then min_start = min_e - L + 1
- max_start = max_e - L + 1
But we need also to consider that the substring must occur at least once (obviously). Also we might need the earliest start and latest start. So if we can precompute for each SAM state the minimum and maximum end position (i.e., the smallest and largest ending index of any occurrence of strings in that state). This can be done during SAM construction: when we add each character at position i (1-indexed), we create a new state corresponding to the entire prefix up to i. That state's endpos initially is {i} (or we can set its min and max end to i). Then after building the SAM, we need to propagate the min and max (or just min and max) along the suffix links in a topological order (by length descending) to combine endpos sets for states that are linked? Actually, careful: In SAM, each state's endpos set is the union of endpos sets of its children (in the suffix link tree) if we consider the set of positions where the state's substrings end. However, the standard method to compute occurrence counts (size of endpos) is to do a DFS on states in order of decreasing length, adding the size of a state to its link. For min and max, we can similarly propagate. But we need for each state the minimal and maximal end position among all occurrences of its substrings. Since when we create a new state at position i, we set its min_e and max_e to i. Then for other states that are clones or existing, we may need to update. During construction, when we clone a state, we should initialize its min_e and max_e appropriately? Actually clones are created from an existing state; they represent the same endpos set initially? Wait clones get the same transitions as the original, but they are used to split endpos sets. After cloning, the original state's endpos set becomes a subset, and the clone gets the remaining? The standard approach: When we add a character at position i, we create a new state cur with len = last.len + 1, and we set its min_e and max_e to i. Then we traverse suffix links of last to set transitions. When we encounter a state p that lacks transition via c, we set it. When we find a state p that already has a transition via c to q, we may need to clone if len[p] + 1 != len[q]. In that case we create clone with len = len[p] + 1, copy transitions of q, and set link of clone to link of q, and set link of q and cur to clone. For min_e and max_e of clone: Initially, clone should have min_e and max_e set to something? The clone's endpos set will be the intersection of some sets? Actually, after cloning, the original state q will have its endpos set reduced (it loses some positions), and the clone gets some positions. But both q and clone need to have correct min_e and max_e values. However, we can compute these after construction by propagating along the suffix link tree: For each state, we have initially for the states that were created as "cur" during each addition (the states representing whole prefixes) we know their end position (i). For clones, we can set min_e = +inf, max_e = -inf initially. Then after building, we process states in order of decreasing length (topological order) and for each state v, we update its link: for link = slink[v], we set min_e[link] = min(min_e[link], min_e[v]), and max_e[link] = max(max_e[link], max_e[v]). This is similar to propagating occurrence counts but for min/max. However, careful: The suffix link tree represents inclusion of endpos sets: the endpos set of a state is a subset of the endpos set of its suffix link? Actually, the suffix link of a state points to a state whose endpos set is a superset. Because the strings represented by link(v) are suffixes of those of v, and they occur whenever v occurs (i.e., if a string occurs ending at some position, its suffixes also occur ending at the same position). Therefore, the endpos set of v is a subset of the endpos set of link(v). So when we propagate min and max from child to parent (i.e., from v to link(v)), we are essentially taking union: link(v) gets the min and max over all positions from its children (including v). But we also have initial positions from the "cur" states (the states that correspond to whole prefixes) that are leaves in this tree? Actually each "cur" state corresponds to a prefix, and they have an end position. The suffix link tree's leaves are states that are not linked to by others? The root is the top. So if we initialize min_e and max_e for each state as +inf and -inf, then for the states that are created as "cur" (the ones representing the entire prefix at each step), we set min_e[cur] = max_e[cur] = i (the position index). For clones, we leave as inf/-inf. Then we process states in decreasing order of len (i.e., from longest to shortest). For each state v, we look at its suffix link u = slink[v], and update u's min_e = min(u.min_e, v.min_e) and max_e = max(u.max_e, v.max_e). This way, after processing all states, each state will have min_e = minimum end position among all occurrences of