Frog Position After T Seconds - Problem

Given an undirected tree consisting of n vertices numbered from 1 to n. A frog starts jumping from vertex 1.

In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex.

The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi.

Return the probability that after t seconds the frog is on the vertex target. Answers within 10^-5 of the actual answer will be accepted.

Input & Output

Example 1 — Basic Tree Navigation
$ Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4
Output: 0.16666666666666666
💡 Note: Frog starts at 1. At t=1, it chooses between nodes 2,3,7 with probability 1/3 each. If it goes to 2, then at t=2 it chooses between 4,6 with probability 1/2 each. Total probability to reach 4 = (1/3) * (1/2) = 1/6 ≈ 0.1667
Example 2 — Early Arrival Case
$ Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 4, target = 4
Output: 0.16666666666666666
💡 Note: Frog can reach node 4 at t=2 with probability 1/6. Since node 4 is a leaf (no unvisited neighbors), frog stays there until t=4. Same probability as Example 1.
Example 3 — Impossible Target
$ Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 4
Output: 0.0
💡 Note: Node 4 requires at least 2 steps to reach from node 1 (1→2→4), but we only have t=1 second. Impossible to reach.

Constraints

  • 1 ≤ n ≤ 100
  • edges.length == n - 1
  • edges[i].length == 2
  • 1 ≤ ai, bi ≤ n
  • 1 ≤ t ≤ 50
  • 1 ≤ target ≤ n

Visualization

Tap to expand
Frog Position After T Seconds: Tree Navigation Problem12374651/31/31/31/21/2Path to Target 4t=0: At node 1t=1: Choose node 2 (P=1/3)t=2: Choose node 4 (P=1/2)Total: P = 1/3 × 1/2 = 1/6🐸 Frog starts at 1, randomly chooses unvisited neighborsResult: Probability = 0.1667 to reach target 4 at time t=2
Understanding the Visualization
1
Input Tree
Tree with n=7 vertices, frog starts at vertex 1, target=4, t=2
2
Path Exploration
Frog randomly chooses among unvisited neighbors at each step
3
Probability Result
Calculate probability of reaching target at exactly time t
Key Takeaway
🎯 Key Insight: The frog's path is determined by random choices at each node, and probability = product of choice probabilities along the path
Asked in
Google 15 Facebook 12 Amazon 8
15.2K Views
Medium Frequency
~35 min Avg. Time
445 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen