Chef loves games! But he likes to invent his own. Now he plays game "Digit Jump". Chef has sequence of digits S1, S2,..., SN,. He is staying in the first digit (S1) and want to reach the last digit (SN) in the minimal number of jumps.
While staying in some digit x with index i (digit Si) Chef can jump into digits with indices i - 1 (Si-1) and i + 1 (Si+1) but he can't jump out from sequence. Or he can jump into any digit with the same value x.
Help Chef to find the minimal number of jumps he need to reach digit SN from digit S1.
Input
Input contains a single line consist of string S of length N- the sequence of digits.
Output
In a single line print single integer - the minimal number of jumps he needs.
Constraints
1 ≤ N ≤ 10^5
Each symbol of S is a digit from 0 to 9.
Example
Input:
01234567890
Output:
1
Input:
012134444444443
Output:
4
Explanation
In the first case Chef can directly jump from the first digit (it is 0) to the last (as it is also 0).
In the second case Chef should jump in such sequence (the number of digits from 1: 1-2-4-5-15).
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to parse the problem: given a string S of digits (length N up to 1e5), each character '0'..'9'. Chef starts at position 1 (first character, index 0). He wants to reach position N (last character, index N-1). He can perform jumps: from current position i, he can go to i-1 (if >=0) or i+1 (if < N) (adjacent positions), or he can jump to any other position j such that S[j] == S[i] (i.e., any digit with the same value). We need minimal number of jumps.
This is a classic shortest path problem on a graph with N nodes. Edges: for each i, edges to i-1, i+1 (if exist) with cost 1, and edges to all nodes with same digit as i (also cost 1). However N up to 1e5, edges to all same-digit nodes could be many (e.g., all '1's). But we can optimize: because all same-digit edges are cost 1 and many, we can treat it as a BFS with a trick: once we have visited a digit value, we can "use" all nodes of that digit and then remove them from further consideration, because from any node of that digit we can jump to any other node of the same digit in one step. So BFS on graph where we also have "teleportation" within groups.
Standard solution: BFS from start node (0). For each node we process, we consider neighbors: i-1, i+1 if not visited. Also, for the digit value d = S[i], we consider all nodes j that have digit d (except i) that haven't been visited. However, after we use that digit group once, we can mark all nodes of that digit as visited with distance = dist[i] + 1 (if not visited). And we should then remove them from the group so that we don't process them again. This works because from any node with digit d, you can reach any other node with same digit in exactly one jump. So if you encounter a digit group for the first time, you can "teleport" to all nodes in that group. But careful: If you later encounter a node of same digit from another path, you would attempt to teleport again, but all nodes of that group would already be visited, so you can skip. However, the teleport edges are symmetric, so once any node of the group is visited, all others can be reached in +1 step from that node. But we need to ensure BFS order: The first time we pop a node with digit d from the queue, we should enqueue all unvisited nodes in the group with distance +1. But they should be visited at that moment, and we should also consider that they might be reachable also via adjacent moves. But BFS ensures minimal distances because when we first visit any node in the group, that distance is minimal (since BFS explores increasing distances). Actually, could there be a case where a node in the group is visited earlier via a different path (e.g., from adjacent) before the group is expanded? That's fine: when we later pop a node from the queue, we check if its digit group is still unprocessed. If some nodes in the group were already visited (maybe via adjacent moves) they have already been processed or in queue. But we still need to teleport from the current node to all nodes in the group, but if they are already visited, the distances are already known and likely ≤ current dist + 1. So we only need to expand the group once, i.e., when we first encounter a node with that digit value (the first time we pop any node of that digit from the queue, we process the group). However, careful: It could be that the first time we encounter digit d is when we pop a node that was visited via a path that gave it a certain distance, but there might be another node of the same digit that could be reached earlier from another digit group? Actually, BFS: We start from node 0. We explore adjacent and same-digit teleport. Suppose node 0 has digit a. When we process node 0, we will teleport to all nodes with digit a (including the last node if it's a). So the group of the starting digit is processed at distance 0? Actually, distance of node 0 is 0. When we process node 0, we consider neighbors (1 and -1 none) and same-digit group: all nodes j with S[j]==S[0] should get distance 1? But wait: from node 0, a jump to any node with same digit is allowed, so distance to those nodes should be 1. So we set dist[j] = 1 (if not visited). So we process group at that time. That's fine. So we need to handle groups at the moment we first pop a node of that digit, but we must also handle that from the start node we pop it (distance 0). But what about later when we pop another node of the same digit that we already processed? We should skip processing the group again because it's already done. So we can maintain an array or set for each digit indicating whether that digit's group has been "expanded" (i.e., we have already added all its nodes). Alternatively, we can upon first encountering a digit, push all nodes of that digit into the queue with distance current_dist+1 (if not visited). Then we clear the list for that digit, so that future encounters of the same digit will not reprocess.
Thus algorithm:
Input string S of length N.
Build adjacency: for each digit (0-9) store a list of indices where that digit occurs. We'll use a dictionary or list of lists: groups[digit] = list of indices (could be a vector).
BFS: distance array dist size N, initialize to -1.
Queue for BFS (deque). Start with index 0, dist[0]=0, push.
Also maintain a boolean array visited or just use dist.
While queue not empty:
pop node u.
if u == N-1: break (we can early exit).
For neighbor v in [u-1, u+1] if within bounds and dist[v]==-1:
set dist[v] = dist[u] + 1, push v.
For digit d = S[u]:
if groups[d] has not been processed (i.e., not empty or a flag):
For each index v in groups[d]:
if dist[v]==-1:
dist[v] = dist[u] + 1, push v.
Clear groups[d] (or mark processed) so that we don't process again.
Output dist[N-1].
But careful: When we process group from u, we should also consider that u itself is in the group. But we are already at u, and we might have already visited some nodes of the group via other means? For nodes in group[d] that are already visited (dist != -1), we shouldn't update them because they may have smaller distance. But if they have been visited with a smaller distance, then fine. If they were visited with larger distance? That shouldn't happen because BFS processes in order; if we process group from u, and some node v in group had already been visited from a different path with distance > dist[u]+1? Actually, BFS ensures that when we first pop u, dist[u] is the minimal distance to u. However, a node v in the same group might have been visited earlier (since we push nodes as we discover them). Could v have been visited before we process group from u? Possibly if v is reachable via adjacent moves before we process group from any node of that digit. For example: start node 0 has digit '1'. Group '1' includes index 5 and index 2. Suppose index 2 is adjacent to index 1, which is adjacent to index 0. BFS from 0: we push 0 (dist0). Process 0: neighbors: 1 (dist1). Also group '1': we will push all nodes in group '1' except 0 (i.e., 2 and 5) with dist1. But we also push 1. Now queue: 1 (dist1), 2 (dist1), 5 (dist1). But note that node 2 might also be adjacent to node 1. However we already set dist[2]=1 from group teleport. When we later pop node 1 (dist1), we consider neighbor 2, but it's already visited, so skip. That's fine. So group processing from 0 yields correct distances.
Now consider scenario: Suppose digit '2' appears at indices 3 and 6. Start is index 0 digit '0'. BFS expands. The first time we encounter a node with digit '2' might be index 3 (maybe via adjacent moves). At that moment, dist[3] is some value d (e.g., 3). We pop node 3 and we see group '2' has not been processed. So we teleport to index 6 with distance d+1 = 4. But is it possible that index 6 could have been reached earlier via another path with distance ≤ d? Perhaps from index 5 adjacent? If index 5 is digit something else, and we haven't visited 6 yet. But if index 6 had been visited earlier, then group processing would skip it. So we need to ensure that we process group at the earliest possible time, i.e., when we first pop a node of that digit. However, could it be that the first time we visit a node of that digit is via teleport from some other group, and that node gets visited with a certain distance, but then later we pop that node and then teleport? Actually, the moment we visit a node (i.e., set its dist) we also push it to the queue. The group processing is done when we pop the node. So the earliest we process a group is when the first node of that group is popped from the queue. But there could be a scenario where a node of that group is visited earlier but not yet popped (i.e., it's in the queue). However, we only process the group when we pop that node. Could there be a scenario where another node of the same group is visited via a different path with a smaller distance before we pop the first one? That would imply that the group is already visited via another node? But the first time any node of the group gets visited, we push it. Then when we later pop it, we process the group. But what if before we pop that node, we have already visited other nodes of the group via some other means? That would require some path to those nodes not through the group, but that's possible: e.g., via adjacent moves. So group processing might be delayed after some nodes of the group are already visited. But it's still fine: when we finally process the group, we teleport to any unvisited nodes, which might be beneficial. But we must ensure that we don't miss the chance to teleport to other nodes of the group from the first visited node. However, BFS ordering: we start BFS from start, we push start (0). We process start, we push its neighbors (adjacent) and teleport from start to its group. So the start's group is processed early. For other groups, it's fine as described.
But there is a nuance: When we process group from u, we set dist[v] = dist[u] + 1 for all v in group[d] that are unvisited. However, some of those v might already be in the queue (but unvisited? Actually if dist[v]==-1 they are not visited, if we set dist[v] and push, they become visited and enqueued. So it's fine). But what about the case where some v in the group had already been visited but with a distance greater than dist[u] + 1? BFS ensures distances are minimal; if v was visited earlier, that means it was discovered via some path with distance <= dist[u]+1, because BFS processes nodes in increasing distance order. If it was visited earlier, then its distance must be less or equal to the distance at which we are now processing u. Wait: u is popped from queue with dist[u]. If v was visited earlier (dist[v] set earlier), then when v was discovered, its dist was set. Since BFS processes nodes in order of non-decreasing distance, v's distance is ≤ dist[u] because we discovered v earlier (earlier in BFS order). But could v's distance be larger than dist[u] + 1? Possibly if v was discovered later but its distance is higher? But if v was discovered earlier, its distance must be smaller or equal to the current distance? Not necessarily: BFS queue processes nodes in order of distance; we only push nodes when we set their dist. If v was visited earlier, that means its dist was set at some earlier point in the BFS, and that earlier point would have had distance less than or equal to dist[u] (since we process nodes in order of increasing distance). So dist[v] ≤ dist[u] generally (since we discovered v earlier, but could it be that v's distance is larger? Let's reason: BFS expands from start; we push nodes with distance 0, then 1, then 2, etc. The queue processes nodes in FIFO order but ensures that all nodes at distance d are processed before nodes at distance d+1 if we use a simple queue and all edges have weight 1. However, when we add nodes from processing a node at distance d, we set their distances to d+1, and they are enqueued. So when we pop a node at distance d, any node with distance ≤ d has already been popped or is still in queue but with distance ≤ d. The queue may contain nodes at distance d and d+1 intermixed? Actually, BFS with a queue: Initially queue has distance 0. When we pop node at distance d, we push its neighbors with distance d+1. So all nodes with distance d are processed before any node with distance d+1? Not exactly; because nodes at distance d are in the queue before any nodes at distance d+1 that are generated from them? In a simple BFS, if we start with source at level 0, then we push its neighbors (level 1). Then we process level 1 nodes, pushing level 2 nodes, etc. The queue order is such that all level d nodes are processed before level d+1 nodes, because nodes are enqueued as we discover them, and we only discover level d+1 when processing level d. Since we don't push any nodes from level d+1 before finishing level d (unless we have prior nodes of level d+1 from earlier levels? Actually, if we process a node of level d, we push its neighbors that are not visited; these neighbors get level d+1. Those nodes are enqueued after all current nodes of level d (and possibly some nodes of level d that are already in queue). Since we start with only level 0, after processing level 0 we have level 1 enqueued. Then we process all level 1, enqueue level 2, etc. So indeed, BFS processes nodes in non-decreasing order of distance, and when we pop a node at distance d, all nodes with distance < d have already been popped, and any node with distance = d may still be in queue, but all nodes with distance > d have not yet been enqueued? Actually, nodes with distance d+1 are enqueued while processing nodes at distance d. So they are added after all nodes at distance d are already in the queue (some may have been popped). But the queue may contain nodes from both d and d+1 simultaneously: suppose we have many level d nodes; as we process each, we add level d+1 nodes to the back. So while we are processing level d, the front of the queue always contains level d nodes until all level d nodes are processed. After that, the queue contains level d+1 nodes. So yes, BFS ensures that when we pop a node with distance d, all nodes with distance less than d are already popped, and any node with distance d is being processed; nodes with distance d+1 are not yet processed but are in the queue behind. So if v was visited earlier and its distance is d' < d, then dist[v] < dist[u]; if v was visited earlier but its distance is exactly d, that means v was discovered at the same level, maybe from a different node processed earlier in the same level. In that case dist[v] == dist[u]. Could dist[v] be d+1? That would be discovered later (from a node at distance d). But that would happen after processing some node at distance d, but before that node is popped? Actually, if we are currently processing node u at distance d, and we discover v with distance d+1 from u, then v is set to d+1 and enqueued. But if v had already been visited, that means we discovered it earlier, so its distance would be ≤ d (since earlier discovery would be from nodes at distance ≤ d-1). So it can't be d+1. So any already visited node v will have dist[v] ≤ dist[u]. Therefore, if we are at node u and we consider teleporting to group nodes, any node already visited has distance ≤ dist[u], so dist[u] + 1 would be >= that distance, so we don't need to update. So it's safe to only set for unvisited nodes.
Now, we need to ensure that we process the group only once. The typical implementation is: maintain a list of vectors for each digit; when we first encounter a digit (i.e., when we process a node with that digit and the vector for that digit is non-empty), we iterate over all indices in that vector, and for each index not visited, we set distance and enqueue. Then we clear the vector (or set a flag) to indicate that this digit's group has been processed. But note: the node u itself is part of the group. In the vector, we have all indices for that digit, including u itself. However, u is already visited (dist[u] set). So we can skip it. Alternatively, we could remove u from the vector beforehand, but easier: when iterating, if index != u and dist[index]==-1, then set and push. But careful: what if the vector contains indices that have been visited already through other means (adjacent moves) before we processed the group? Those indices would have dist != -1, and we skip them. That's okay. After processing, we clear the vector to prevent future processing. However, note that if we clear the vector, we lose the list of indices for that digit. But that's fine because we no longer need them. But what about the node u itself? It's fine.
But there is a subtle point: what about the start node's group? At the start, we process node 0, and we will teleport to all same-digit nodes (including maybe the target). That's fine. After processing, we clear that digit's list, so later if we encounter another node with same digit, we won't reprocess.
Thus algorithm is O(N + E) but with group processing each node visited once and each digit group processed once, leading to O(N) time. Because each node is added to queue once, and each edge (adjacent) is considered once (each node checks up to two neighbors, but each neighbor check may lead to duplicate checks? Actually we check neighbors only when we pop a node, and each neighbor may be considered from two nodes (left and right) but we only set dist if unvisited, so it's O(N). The group processing: we iterate over all nodes of a digit exactly once when that digit is first encountered. So total across digits is sum of sizes of groups = N. So O(N).
Thus the solution is straightforward.
Now implement in Python: N up to 100k, which is fine. Use deque for BFS.
Let's test on examples.
Example1: S = "01234567890" -> indices 0..10? Actually length? "01234567890": digits: 0,1,2,3,4,5,6,7,8,9,0 => N=11. Groups: digit 0: indices 0 and 10. BFS: start at 0 dist0. Process 0: neighbors: index1 (dist1), index -1 none. Group '0' not processed? Let's say we maintain a list for each digit: groups[0] = [0,10]; groups[1]=[1]... etc. Process group '0': for each v in groups[0] if v != u and not visited: v=10 not visited -> dist[10]=1, push. Then clear groups[0] (set to empty). Later, when we pop node 10, we see it's the target. Answer 1. Works.
Example2: S = "012134444444443" (N=15? Let's count: digits: 0,1,2,1,3,4,4,4,4,4,4,4,4,4,3? Actually string: "012134444444443" length? Let's count: positions: 0:0,1:1,2:2,3:1,4:3,5:4,6:4,7:4,8:4,9:4,10:4,11:4,12:4,13:4,14:3? Wait last char is '3'? The string ends with "443"? Actually given "012134444444443" let's count:
Indices: 0:0
1:1
2:2
3:1
4:3
5:4
6:4
7:4
8:4
9:4
10:4
11:4
12:4
13:4
14:4? Hmm, we need to compute length properly. The string: "012134444444443" - after 01213 there are many 4's then 3. Let's count characters:
0: '0'
1: '1'
2: '2'
3: '1'
4: '3'
5: '4'
6: '4'
7: '4'
8: '4'
9: '4'
10: '4'
11: '4'
12: '4'
13: '4'
14: '4'? Wait, they said "4444444443" maybe 9 fours? Actually "4444444443" would be 9 fours and a 3, total length: 5 (01213) + 9 (four) + 1 (3) = 15. Let's check: after "01213" we have "4444444443"? The string is "012134444444443". Count: after "01213" we have "4444444443"? That's 9 fours? Let's count the 4's: "444444444" is 9 fours? Actually "444444444" is 9 if you count: but the string given: "444444444"?? It says "444444444"? Wait, they wrote "012134444444443" - between the 3 and the final 3 there are many 4's. Let's count the characters: The substring after "01213" is "4444444443"? That would be 9 fours then a 3 -> total length = 5+9+1 = 15. But the example says output 4. We'll trust.
We'll simulate: groups: digit 0: [0]; digit1: [1,3]; digit2: [2]; digit3: [4,14]; digit4: [5,6,7,8,9,10,11,12,13]; Actually index 14? Let's assume N=15: indices 0..14. So last index is 14? Yes. So start 0 (digit 0) dist0. Process 0: neighbors: 1 (dist1). Group 0: only [0]? Actually group 0: index0 only, so no other. So queue: [1]. Process 1 (digit1 dist1): neighbors: 0 (visited), 2 (dist2). Group 1: indices [1,3]? Actually group 1: indices 1 and 3. Process group 1: for index3 if not visited: set dist[3]=2, push. Clear group1. So now queue: [2,3] (dist2, dist2). Process 2 (digit2 dist2): neighbors:1 (visited),3? index3 maybe visited? Actually index3 visited (dist2). But we also have neighbor? index2+1 =3, visited. Group2: [2] only. So nothing new. Process 3 (digit1 dist2): but group1 already cleared, so skip. Neighbors: 2 (visited),4 (dist3). So queue gets 4 (dist3). Process 4 (digit3 dist3): neighbors:3 (visited),5 (dist4). Group3: indices [4,14]. Process group3: index14 not visited => dist[14] = dist[4]+1 = 4, push. Clear group3. So we have target index14 dist4. Later processing might find better? But we found dist4. So answer 4. Works.
Thus algorithm yields 4.
Edge cases: N=1? Then start and end are same, minimal jumps 0. Should output 0. Our BFS: start with index0, dist[0]=0; then process? We'll have while queue: pop, check if u==N-1, break; but we might output dist[N-1] after BFS, which will be 0. Or we can output after BFS. Works.
Implementation details:
Read input string S, strip newline.
N = len(S)
groups = [[] for _ in range(10)] # 10 digits
for i,ch in enumerate(S):
d = int(ch)
groups[d].append(i)
dist = [-1]*N
dist[0]=0
from collections import deque
q = deque([0])
While q:
u = q.popleft()
if u == N-1: break # optional early exit
Process left and right
for v in (u-1, u+1):
if 0 <= v < N and dist[v] == -1:
dist[v] = dist[u] + 1
q.append(v)
d = int(S[u])
if groups[d]: # not processed yet?
# For each index in groups[d] that is not visited
for v in groups[d]:
if dist[v] == -1:
dist[v] = dist[u] + 1
q.append(v)
groups[d] = [] # clear to mark processed
print(dist[N-1])
But careful: What if groups[d] includes u? For u we already visited, so we skip (dist[u] is 0 or something, not -1). So it's fine.
But we must also consider that after clearing groups[d], later we may pop another node with same digit d but groups[d] is empty, so we skip. That's fine.
But there is a subtle case: What if we clear groups[d] before processing all indices? But we process all indices in the group at that moment. However, we may have visited some indices from that group via adjacent moves already. But those visited indices we skip. So after we clear, we lose the list. That's fine.
But what about the scenario where we first encounter a digit d from a node that is not the first node visited of that digit? That can't happen because the first node visited of that digit will be either via start or via adjacent moves or via teleport from another digit. When we first visit any node of digit d, we set its dist and push it into queue. When we later pop it, we process the group if not yet processed. But what if we have visited multiple nodes of digit d before we pop the first one? Is that possible? Since we process nodes in BFS order, it's possible that we visit some nodes of digit d via adjacent moves before we pop the node that will process the group. For example, suppose we have digit '2' at indices 5 and 10. Suppose start at 0 digit '0'. BFS: we move adjacent, eventually we may reach index 5 via a path of length say 5 (dist5). When we first discover index5 (dist5), we push it. But we haven't popped it yet. Meanwhile, we might also reach index10 via a different path of length 6? Possibly, but that would require discovering index10 before we process index5. Since index5 is discovered earlier (dist5) and index10 might be discovered later via a longer path, but could it be discovered before we pop index5? Let's examine BFS queue order: nodes are enqueued when discovered. The queue order is roughly by distance, but ties may be interleaved. Suppose we discover index5 at distance 5 and enqueue it. Then while processing nodes at distance 5 (maybe some other nodes) we could discover index10 also at distance 6 from some other node? Actually, to discover index10 at distance 6, we must process a node at distance 5 that is adjacent to index10 or teleport from a digit group. If index10 is not adjacent to any node at distance 5 except perhaps index5? But if index5 is not yet processed, we could process another node at distance 5 that can teleport? But teleport from a digit group only occurs when we process a node of that digit. If we haven't processed any node of digit '2', we cannot teleport to index10 from other digits? However, index10 might be adjacent to some node at distance 5 (like index9 or index11) that we process before index5. That's possible. So we could discover index10 via adjacent move from a node at distance 5 that is not digit '2' before we process index5. In that case, index10 would be visited with dist6 (since from neighbor dist5+1). And it would be enqueued after index5? Actually, it would be enqueued after we process that neighbor. The order: we have a queue containing nodes at distance 5 (including index5) and maybe some nodes at distance 4, etc. When we process the neighbor (distance 5), we discover index10 (dist6) and enqueue it. The queue currently has index5 (dist5) and then other nodes; after we finish processing all distance 5 nodes, we will process distance 6 nodes. So index5 (dist5) will be popped before index10 (dist6) because it's earlier in queue. So we will pop index5 first. So before index10 is processed (popped), we will have popped index5. So we will process group digit '2' when we pop index5 (assuming groups[d] not processed yet). At that moment, index10 may have been discovered with dist6 (if visited via adjacent) or not yet discovered. But we need to handle both cases:
If index10 has not been visited (dist == -1), we set dist[10] = dist[5] + 1 = 6? Actually dist[5] = 5, so dist[10] = 6, which matches the adjacent path maybe. But if index10 had already been visited with dist6 (from adjacent), we skip. So no issue.
If index10 was visited with dist6 before we process index5, it's fine; we don't update. Could it have been visited with dist less than 6? Possibly if there is a shorter path via some other digit group? But then that path would have involved some other digit's teleport that may have given distance <6. But then that would require that we had processed some other node of digit '2' earlier? No, because the only way to get to index10 without using digit '2' teleport is via adjacent moves. The shortest adjacent path from start to index10 is the index difference (10) if no teleport, but with teleport via other digits maybe shorter? For example, if start digit 0 teleports to some other 0, then moves. But that's possible. But if we haven't processed digit '2' yet, then we can't teleport within digit 2. So index10 might be reached via some other path with distance <6? Possibly if a teleport from another digit lands near index10, but still we need to consider that the shortest distance to index10 might be less than dist[5]+1. However, BFS ensures that when we pop index5, dist[5] is minimal (5). The distance to index10 via any path that does not use digit 2 teleport could be less than 6? For example, if there is a teleport from start to a node near index10. But then that would have been discovered earlier. In any case, if index10 already has a distance ≤ 6, it's already set; if it's >6 (but BFS ensures distances are monotonic, so it can't be >6 because we haven't processed any node that could assign a distance >6 to index10 at that stage? Actually, if index10 hasn't been visited yet, its dist is -1. So when we process group from index5, we set dist[10] = 6, which is at most any path that doesn't use digit 2 teleport? Could there be a path that gives distance 5 to index10? Possibly if there is a teleport from start directly to index10 via some other digit? Only if start digit equals digit at index10, which is 2; but start digit is 0, not 2. So not. Or if there is a chain of teleports via other digits that yields distance 5. For example, start teleports to some node, then moves, etc. But the BFS ensures that the distance we set for index10 when we first encounter it via any means is the minimal. So if we set it via group from index5 as 6, but there could be a shorter path via another node of digit 2? That would be teleport from some other node of digit 2, but we haven't processed any other node of digit 2 yet. Actually, if there is another node of digit 2, say index2? But we only have index5 and 10. So no. So it's fine. More generally, there could be multiple nodes of digit 2: index a, b, c. The first time we pop any node of digit 2, we teleport to all others. This yields distances dist[a]+1 to others. However, it's possible that some other node of digit 2 (say b) has already been visited with a smaller distance than dist[a]+1. That could happen if b was reached earlier via adjacent moves or via other teleports. In that case, dist[b] < dist[a]+1, so we don't update b. That's fine. Could it happen that dist[b] > dist[a]+1? That would mean we discovered b via some longer path before we had the chance to teleport from a. But is that possible? b could be discovered via adjacent moves from some node at distance d, giving dist[b] = d+1. If a is discovered at distance dist[a] which is ≤ d? Or maybe a is discovered later? Let's consider a scenario: digit 2 appears at positions 5 and 20. Suppose start at 0. There is a long path via adjacent moves to 20, but there is a shorter path via teleport from 5 to 20. However, BFS may discover 20 via adjacent moves before discovering 5? Possibly if the BFS explores in a way that reaches 20 via adjacent moves earlier than it processes 5? Let's simulate: BFS expands outward from start. If the index 20 is far to the right, the BFS will gradually expand to the right and left. Since BFS explores nodes level by level, the distance to index 20 via only adjacent moves is |20-0| = 20. So dist[20] from adjacent-only would be 20. But if there is a teleport from index 5, which is at distance 5 from start (via adjacent moves), then via teleport we could get to 20 in distance 6 (5+1). So the minimal distance is 6. BFS will first discover nodes at distance 1, then 2, etc. It will discover index 5 at distance 5 (since adjacent moves). When index 5 is discovered (at distance 5), we set dist[5]=5 and enqueue it. At the same time, nodes at distance 6, 7, ... will be discovered later. At the moment we discover index5, we also discover its neighbors (4,6) and teleport to all digit2 nodes. But note: we don't teleport immediately upon discovery; we only teleport when we pop the node from the queue. However, we could also teleport earlier if we process a different node of digit2 first. But suppose index5 is the first digit2 node discovered. The queue will have index5 at distance 5. Before we process index5, we will process nodes at distance 5 that are ahead of it in the queue? The order depends on insertion order. We also have other nodes at distance 5 that were discovered earlier? Actually, when we discover nodes at distance 5, we may discover many nodes, all enqueued. The order in which they are processed is the order they were enqueued (FIFO). If we discovered index5 earlier than some other nodes at distance 5, it will be earlier in the queue. But regardless, before we process any node at distance 6, we will process all nodes at distance 5 (since they are enqueued before any distance 6 nodes are enqueued? Not exactly: when we process a node at distance 4, it enqueues nodes at distance 5. So all nodes at distance 5 are enqueued before any node at distance 6 is processed. However, while we are processing nodes at distance 5, we may enqueue nodes at distance 6. But those distance 6 nodes are added to the back of the queue, after the remaining distance 5 nodes. So we will finish processing all distance 5 nodes before we start processing distance 6 nodes. Therefore, index5 (distance 5) will be popped and processed before any distance 6 node is processed. When we process index5, we will teleport to index20 and set dist[20] = 6, and enqueue it. So index20 gets distance 6. This is before we could ever visit index20 via adjacent moves with distance 20, because that would require processing nodes at distances up to 20. So the teleport gives a shorter distance, and BFS will set it correctly.
But consider the scenario where there is another node of digit2, say index 10, which is closer to start than index5? Actually, the first digit2 node we encounter might not be the one with smallest distance from start? But BFS ensures that nodes are discovered in order of increasing distance. So the first time we discover any node of digit2, it will be the one with the smallest distance among all digit2 nodes. Because BFS expands in layers: all nodes at distance d are discovered before any node at distance d+1. So the first digit2 node discovered will have the minimal distance among all digit2 nodes. When we later pop it (which will happen before processing any node at distance d+1), we will teleport to all other digit2 nodes, giving them distance d+1. This is optimal because any path to another digit2 node must go through at least one digit2 node first (since teleports only from digit2). Could there be a path to a digit2 node that is shorter than d+1? Possibly if that digit2 node itself is the one with minimal distance d (i.e., the one we popped). Others could be reached via a different digit2 node with distance also d? But that would require another digit2 node also at distance d, which would be discovered at the same time (maybe also at distance d). If there are multiple digit2 nodes at distance d, they will all be discovered and enqueued at distance d. The order among them could be arbitrary. Suppose we have two digit2 nodes, A and B, both at distance d. BFS might discover A first, then B (both at distance d). But when we process A (pop A), we will teleport to B, but B may already have been discovered with distance d (since it was discovered via adjacent moves? Actually, if both are at distance d, they are discovered via BFS from nodes at distance d-1. They would both be discovered and enqueued with distance d. At the moment we process A, B might already have been visited (dist[B] = d). So we skip setting it to d+1 (which would be worse). So it's fine. So the algorithm works.
One nuance: Should we process teleport edges from a node even if its digit group has already been processed? In our method we check if groups[d] is non-empty. This works because we clear it after first processing. But what if groups[d] is empty because all nodes of that digit have been visited? Then we skip. That's correct.
But careful: When we process a node, we also need to consider that the node itself might be the only one in its group, and groups[d] contains only that node. After processing, we clear the group, which is fine. However, consider the case where we first visit a node via teleport from another group, and its own group hasn't been processed yet. When we later pop that node, we will process its group. That's correct.
Potential issue: What if we process the group from a node, but we also need to consider teleporting to nodes that are in the same digit but have not been visited yet because they were not in groups[d]? Actually, groups[d] initially contains all indices of that digit. When we process the group for the first time, we iterate over all indices in groups[d]. Some may have been visited already, we skip; the rest we set distance and enqueue. Then we clear groups[d]. So any later node of that digit that we might encounter (say we later discover a node of that digit via adjacent moves after group processing? But if we cleared the group, that means we have already visited all nodes of that digit? Not necessarily. Could there be nodes of that digit that were not in groups[d] because they were not added? Wait, groups[d] initially includes all indices of digit d. We clear it after processing. However, it's possible that some nodes of digit d have not been visited yet at the time we process the group, but they are still in groups[d]. We will process them: we will set their distance and enqueue them. So after processing, all nodes of digit d become visited (or at least those we set). But is it possible that some nodes of digit d are not visited yet because they were not in groups[d]? groups[d] initially contains all indices; after we clear, we don't have them. So after processing, we might have set dist for all nodes of that digit. However, what about the node we are currently processing? It is already visited. So all nodes of that digit are now visited. So indeed after processing a digit group once, all nodes of that digit become visited (or at least have dist set). But could there be nodes of that digit that are not reachable via teleport because they were not in the original list? That would mean they are not in groups[d], but they are digit d. That can't happen. So after we process group for digit d, all nodes with digit d are visited. So no further need to process that digit. Thus clearing groups is safe.
But one more nuance: Suppose we have digit d, and we first encounter a node of digit d via teleport from another digit. At that moment, when we pop that node, we will process the group for digit d. That will set distances for all other nodes of digit d, including perhaps some nodes that are not yet visited. That is correct. However, consider that the node we popped had distance D. We set other nodes to D+1. But is it possible that some of those other nodes could have been reached with distance D (i.e., the same as the node we popped) if there was another node of digit d also at distance D? That would have been discovered earlier if it existed. But if there were multiple nodes at distance D, the BFS would have discovered all of them at distance D (since they are at the same distance from start). How could they be discovered? They could be discovered via adjacent moves or teleports from other digits. If there is another node of digit d at distance D, then when the first node of digit d is popped, the other might still be unvisited if it hasn't been discovered yet. But could that happen? Since both are at distance D, they are both in the same BFS layer. BFS discovers nodes at distance D from nodes at distance D-1. It could be that one of them is discovered earlier than the other, but they are both discovered (i.e., dist set) before any node at distance D is popped? Not necessarily: The BFS algorithm we implemented sets dist when we first encounter a node, and enqueues it. So when we process nodes at distance D-1, we may discover multiple nodes at distance D. They are all enqueued with distance D. The order of enqueuing may intermix nodes of different digits. The BFS loop: we pop nodes from the front. So while we are processing distance D-1 nodes, we are adding distance D nodes to the back. After we finish all distance D-1 nodes, we start popping distance D nodes. At that point, all distance D nodes are already in the queue, but not necessarily all have been "discovered"? Actually, by the time we finish processing all distance D-1 nodes, all nodes at distance D that are reachable from them have been discovered. So all nodes at distance D are known and enqueued. So if there is another node of digit d at distance D, it must have been discovered and enqueued by the time we start processing distance D nodes. Therefore, when we pop the first node of digit d (which could be any of them), the other nodes of digit d at distance D are already visited (dist set to D). So when we process the group from that first node, those other nodes will already have dist = D, which is less than D+1, so we skip them. So it's fine.
Thus algorithm is correct.
Edge Cases: Large N, string with many same digit: all '0's. Then groups[0] contains all indices. Starting at index0, we process group: set distances to all other indices to 1. So dist[N-1]=1 if N>1. BFS processes many nodes, but we can handle up to 1e5.
Now we should also consider performance: groups as list of lists of ints. Clear each group after processing by setting to empty list. Python will free memory later? It's okay.
Potential improvement: We can also avoid checking neighbor indices that are out of bounds. Use conditions.
We also need to be careful about input: There may be trailing newline.
Now implement solve().
Pseudo:
import sys
from collections import deque
def solve():
s = sys.stdin.readline().strip()
n = len(s)
if n == 0: # unlikely
print(0)
return
groups = [[] for _ in range(10)]
for i,ch in enumerate(s):
d = ord(ch) - 48 # int
groups[d].append(i)
code
dist = [-1] * n
dist[0] = 0
q = deque([0])
while q:
u = q.popleft()
d = ord(s[u]) - 48
# neighbors
if u-1 >= 0 and dist[u-1] == -1:
dist[u-1] = dist[u] + 1
q.append(u-1)
if u+1 < n and dist[u+1] == -1:
dist[u+1] = dist[u] + 1
q.append(u+1)
# teleport group
if groups[d]:
for v in groups[d]:
if dist[v] == -1:
dist[v] = dist[u] + 1
q.append(v)
groups[d] = [] # clear
# early exit if target reached (optional)
if u == n-1:
break
print(dist[n-1])
But note: When we process group, we are iterating over the original list which includes u itself. u is already visited, but we check dist[v]==-1, so we skip u. That's fine.
But we need to ensure we clear groups[d] after processing, even if some indices were not visited? Actually we visited all unvisited indices and set them, so after processing they should all be visited. However, if for some reason some indices were visited earlier (like via adjacent) we skip them but still they are visited. So groups[d] can be cleared anyway.
Potential bug: If groups[d] is large and we iterate over it for each node of that digit before clearing, but we clear after first processing. So it's okay.
But what if the start node's digit group is processed, we clear groups[digit]. Later we might encounter another node with same digit (maybe from teleport from other digit) but groups[digit] is empty, so we skip. That's fine because all nodes of that digit are already visited.
Now test with examples:
Input: "01234567890" -> output 1. Our algorithm: process start 0: group 0 includes indices 0 and 10. For v=10, set dist[10]=1. So answer 1.
Input: second example: output 4. Works.
Edge: N=1, S="5" -> groups[5] = [0]. dist[0]=0. q contains 0. Pop u=0, neighbors none; group d=5 has list [0]; iterate, v=0 dist[0]!=-1 skip; clear groups[5]; loop ends. dist[0]=0 printed.
Now we need to ensure BFS does not revisit nodes or set dist multiple times. Using dist == -1 check ensures that.
Complexity: O(N) time, O(N) space.
One more nuance: The problem says Chef can jump to any digit with the same value. This includes the digit itself? Probably not needed but allowed. It doesn't matter.
Now we can finalize the solution.
But before finalizing, consider if there is any scenario where we need to process group before processing the node? Because teleport edges are symmetric and weight 1, the BFS approach with group expansion on pop is correct. However, some solutions expand group on first visitation (i.e., when we first set dist for a node of that digit, we immediately expand the group). But that may be more efficient because it teleports earlier. But our approach is standard and correct.
One more nuance: When we pop a node, we process its group. But what if the group was already processed earlier by a different node of the same digit? Then groups[d] is empty, we skip. That's correct.
Now consider a case where a node's group is processed but later we encounter that same node again? Not possible because we only push each node once (when dist set), and we only pop each node once (since we check dist==-1 before setting). So each node is processed at most once.
Thus final answer.
But there's an alternative: treat the graph as having edges to same-digit nodes and BFS with preprocessing to reduce complexity. We have implemented that.
We'll produce final code.
But we must be careful about Python recursion? Not needed.
Edge: Input may have spaces? The problem says a single line consist of string S. So we can strip.
Now output.
Now I'll produce the final answer.
But wait: There is one more nuance: When we clear groups[d] after processing, we lose the list, but what if we later need to process the group for digit d from another node? That won't be needed because all nodes of that digit are already visited. But what about the node we just popped? It is visited. So it's fine.
However, what about the possibility that some node of digit d was not visited because it was not in groups[d]? But groups[d] originally contained all indices. So after processing, all nodes of that digit have been visited (or at least their dist set). But consider scenario: when we process group from u, we iterate over groups[d] and set dist for those not visited. But what if some node in groups[d] is currently already in the queue (dist set but not yet popped)? That's fine; we skip because dist[v] != -1. So after this, all nodes in groups[d] have dist set (either previously or now). So we can clear.
Thus done.
Now consider memory: groups is list of up to 10 lists, each containing indices. That's fine.
Now, is there any chance that we might need to process teleport edges from a node that is not the first in its digit but the group list is empty because we cleared it, but there are still unvisited nodes of that digit? That would mean that some nodes of that digit were not in the original groups[d]? impossible. Or we might have cleared groups[d] before processing all nodes of that digit because we visited them via other means and removed from groups? But we clear after processing the group once. If we clear, we lose the list; but if later we find a node of that digit that is not visited (maybe due to some bug?), we would never process its group, and that node would not be visited via teleport from other nodes of same digit. But BFS would still reach it via adjacent moves eventually. However, if it's not visited via teleport, it might still be reached, but could the shortest path use teleport from a later discovered node? That would be longer because teleport adds 1. So it's fine? Not necessarily: If there is a node of digit d that is unvisited