5. All four-digit numbers from 1000 to 9999 are written in a row without spaces. Kostya underlined \( k \) consecutive digits in this sequence, and Andrey underlined other \( k \) consecutive digits in this sequence. It turned out that the \( k \)-digit numbers underlined by the boys are equal. For what largest \( k \) could this have happened?
Answer: $k=7$.

Solution. An example of a seven-digit number that satisfies the condition of the problem is 2229223. Indeed, Kostya could underline the fragment «2229223» at the junction of the numbers 2229 and 2230, and Andrey - at the junction of the numbers 9222 and 9223.

Now we will show that it is impossible to choose an eight-digit fragment. First, note the obvious fact: if the second-to-last digits of two consecutive four-digit numbers are different, then the smaller number ends in 9, and the larger one ends in 0. Suppose the boys underlined an eight-digit fragment «abcdefgh». It can be highlighted in the string in one of four ways, as shown in the diagram:

$$
\underbrace{a b c d}_{i} \underbrace{e f g h}_{i+1} \underbrace{* a b c}_{j} \underbrace{d e f g}_{j+1} \underbrace{h * * *}_{j+2} \underbrace{* * a b}_{k} \underbrace{c d e f}_{k+1} \underbrace{g h * *}_{k+2} \underbrace{* * * a}_{m} \underbrace{b c d e}_{m+1} \underbrace{f g h *}_{m+2}
$$

(here $i, j, k, m$ are four-digit numbers, and asterisks denote some digits). Note that Kostya and Andrey used different methods, otherwise they would have underlined the same block. Suppose Kostya chose his block in the first way, and Andrey in the second. Then $c$ and $g$ are the last digits of adjacent numbers $j$ and $j+1$, so they are different. Therefore, the numbers $i$ and $i+1$ have different second-to-last digits. According to the above remark, the number $i+1$ ends in 0, that is, $h=0$. But this is impossible, since the number $j+2$ is a four-digit number. Other configurations are analyzed similarly.