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.
💡 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
💡 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.
The key insight is that the frog can only reach the target at exactly time t, or arrive early and stay there if the target is a leaf node. Best approach uses DFS with early termination to explore all possible paths and calculate probabilities. Time: O(n), Space: O(n)
Common Approaches
✓
Sort First
⏱️ Time: N/A
Space: N/A
DFS Path Exploration
⏱️ Time: O(n)
Space: O(n)
Use depth-first search to explore all possible paths the frog can take. For each path, calculate the probability based on the number of choices at each step. Sum up probabilities for paths that reach the target at exactly time t.
DFS with Early Termination
⏱️ Time: O(n)
Space: O(n)
Enhanced DFS approach that calculates the minimum time needed to reach the target and terminates early if it's impossible to reach within the given time limit. Also handles the case where the frog arrives early and must stay at the target.
Algorithm Steps — Algorithm Steps
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int graph[101][101];
static int graph_size[101];
static int target;
double dfs(int node, int parent, int time_left) {
if (time_left == 0) {
return (node == target) ? 1.0 : 0.0;
}
// Get unvisited neighbors
int neighbors[101];
int neighbor_count = 0;
for (int i = 0; i < graph_size[node]; i++) {
if (graph[node][i] != parent) {
neighbors[neighbor_count++] = graph[node][i];
}
}
// If no unvisited neighbors, frog stays here
if (neighbor_count == 0) {
return (node == target) ? 1.0 : 0.0;
}
// Probability of reaching target from this state
double prob = 0.0;
for (int i = 0; i < neighbor_count; i++) {
prob += dfs(neighbors[i], node, time_left - 1) / neighbor_count;
}
return prob;
}
double solution(int n, int edges[][2], int edge_count, int t, int target_val) {
target = target_val;
// Initialize graph
for (int i = 0; i <= n; i++) {
graph_size[i] = 0;
}
// Build adjacency list
for (int i = 0; i < edge_count; i++) {
int a = edges[i][0];
int b = edges[i][1];
graph[a][graph_size[a]++] = b;
graph[b][graph_size[b]++] = a;
}
return dfs(1, -1, t);
}
int main() {
char line[1000];
// Read n
fgets(line, sizeof(line), stdin);
int n = atoi(line);
// Read edges
fgets(line, sizeof(line), stdin);
// Parse edges array
int edges[100][2];
int edge_count = 0;
char* ptr = line;
while (*ptr && *ptr != '[') ptr++;
ptr++; // Skip [
while (*ptr && *ptr != ']') {
while (*ptr && (*ptr == ' ' || *ptr == ',')) ptr++;
if (*ptr == '[') {
ptr++;
edges[edge_count][0] = (int)strtol(ptr, &ptr, 10);
while (*ptr && *ptr != ',') ptr++;
ptr++; // Skip comma
edges[edge_count][1] = (int)strtol(ptr, &ptr, 10);
edge_count++;
while (*ptr && *ptr != ']') ptr++;
if (*ptr == ']') ptr++;
} else {
break;
}
}
// Read t
fgets(line, sizeof(line), stdin);
int t = atoi(line);
// Read target
fgets(line, sizeof(line), stdin);
int target_val = atoi(line);
double result = solution(n, edges, edge_count, t, target_val);
printf("%g\n", result);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
n
2n
✓ Linear Growth
Space Complexity
n
2n
⚡ Linearithmic Space
15.2K Views
MediumFrequency
~35 minAvg. Time
445 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.