class Solution { private fun findMinDistance( n: Int, graph: List>, ): Int { val dp = IntArray(n) for (u in (0..n - 2).reversed()) { dp[u] = graph[u].minOfOrNull { v -> 1 + dp[v] } ?: n } return dp[0] } fun shortestDistanceAfterQueries( n: Int, queries: Array, ): IntArray { val distances = IntArray(queries.size) // Construct initial graph val graph = (1..n).map { mutableListOf(it) }.toList() graph.last().removeLast() // Process queries for (query in queries.withIndex()) { val (u, v) = query.value[0] to query.value[1] graph[u].add(v) distances[query.index] = findMinDistance(n, graph) } return distances } }