Frog Position After T Seconds - Problem
The Jumping Frog's Probability Adventure!

Imagine a clever frog exploring an undirected tree with n vertices numbered from 1 to n. Our amphibian friend starts at vertex 1 and follows some interesting rules:

Movement Rules:
  • Each second, the frog jumps to an unvisited adjacent vertex
  • If multiple unvisited vertices are available, it chooses randomly with equal probability
  • If no unvisited vertices remain, it stays put forever
  • The frog never revisits a vertex it has already been to

Given the tree's edges and a target vertex, calculate the probability that after exactly t seconds, our frog friend is sitting on the target vertex.

Goal: Return the probability as a decimal number (answers within 10-5 of the actual answer are accepted).

Input & Output

example_1.py โ€” Basic Tree
$ Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4
โ€บ Output: 0.16666666666666666
๐Ÿ’ก Note: The frog starts at vertex 1, then jumps to vertex 2 with probability 1/3, then jumps to vertex 4 with probability 1/2. So the probability is 1/3 * 1/2 = 1/6.
example_2.py โ€” Staying at Target
$ Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7
โ€บ Output: 0.3333333333333333
๐Ÿ’ก Note: The frog starts at vertex 1, then jumps to vertex 7 with probability 1/3.
example_3.py โ€” Cannot Reach Target
$ Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 20, target = 6
โ€บ Output: 0.16666666666666666
๐Ÿ’ก Note: The frog reaches vertex 6 at time 2 and stays there (no unvisited neighbors). Since 2 โ‰ค 20, the probability remains 1/6.

Constraints

  • 1 โ‰ค n โ‰ค 100
  • edges.length == n - 1
  • edges[i].length == 2
  • 1 โ‰ค ai, bi โ‰ค n
  • 1 โ‰ค t โ‰ค 50
  • 1 โ‰ค target โ‰ค n
  • Answers within 10-5 of the actual answer will be accepted

Visualization

Tap to expand
๐Ÿธ234๐ŸŽฏ1/21/21/21/2Journey MapStep 1: Start at ๐ŸธProbability: 1.0Step 2: Choose pathTo 2: 1/2 chanceTo 3: 1/2 chanceStep 3: From node 2To 4: 1/2 chanceTo ๐ŸŽฏ: 1/2 chanceFinal Probability:1/2 ร— 1/2 = 1/4Time taken: 2 stepsTarget reached! ๐ŸŽ‰
Understanding the Visualization
1
Start the Journey
Frog begins at vertex 1 with 100% certainty
2
Make Random Choices
At each vertex, frog randomly picks from unvisited neighbors
3
Calculate Path Probability
Multiply choice probabilities: 1/3 ร— 1/2 = 1/6
4
Handle Stopping Condition
If no unvisited neighbors remain, frog stays forever
Key Takeaway
๐ŸŽฏ Key Insight: In a tree, there's exactly one path to any target. Calculate probability by multiplying choice probabilities along this unique path, considering timing constraints and staying conditions.
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
38.5K Views
Medium Frequency
~25 min Avg. Time
1.2K 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