Frog Position After T Seconds

Probability that a frog starting at node 1 lands on target after exactly T seconds — BFS with branching probabilities.

Hard
Time O(n) Space O(n)
LeetCode
6 min read
tree bfs probability

Problem#

A frog starts at node 1 of an undirected tree. Each second, it must jump uniformly at random to an unvisited adjacent node. If no unvisited neighbor exists, it stays. Return the probability that it is on target after exactly t seconds.

Examples#

  • n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 41/6.
  • t = 1, target = 71/3.

Constraints#

  • 1 <= n <= 100, 1 <= t <= 50, 1 <= target <= n.

Hints#

Hint 1
BFS from node 1 tracking the running probability of being at each visited node.
Hint 2
When the frog is at a leaf (no unvisited children) it stays; that’s only valid if the elapsed time has reached t.

Approach#

BFS from root 1. For each node, count its unvisited neighbors. If the frog has reached target: it’s valid if t == 0 OR (t > 0 and target is a leaf with no unvisited children, but only counted at the moment of arrival). Carry probability as a double divided by branch count at each step.

Solution#

Frog Position After T Seconds
class Solution {
public:
double frogPosition(int n, vector<vector<int>>& edges, int t, int target) {
if (n == 1) return target == 1 ? 1.0 : 0.0;
vector<vector<int>> g(n + 1);
for (auto& e : edges) { g[e[0]].push_back(e[1]); g[e[1]].push_back(e[0]); }
vector<int> seen(n + 1, 0);
queue<tuple<int,int,double>> q; // (node, timeUsed, prob)
q.push({1, 0, 1.0});
seen[1] = 1;
while (!q.empty()) {
auto [u, time, prob] = q.front(); q.pop();
int unvisited = 0;
for (int v : g[u]) if (!seen[v]) ++unvisited;
if (u == target) {
// Reached target. Valid if time == t, or if frog is stuck here (unvisited == 0) and time <= t.
if (time == t) return prob;
if (unvisited == 0) return 0.0;
return 0.0;
}
if (time == t) continue;
for (int v : g[u]) if (!seen[v]) {
seen[v] = 1;
q.push({v, time + 1, prob / unvisited});
}
}
return 0.0;
}
};

Editorial#

Trees are loop-free, so once we mark a node visited, the frog can never return. The frog “stops” only at leaves (zero unvisited children); reaching a leaf early means it stays there permanently. We return early at target: if time == t the probability is exact; otherwise the probability is zero unless the frog was forced to stop at target — and in trees if you arrive earlier and have a child, you must move on, hence return 0 in the non-leaf case.

Complexity#

  • Time: O(n) since each node is enqueued once.
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.