#1377

Frog Position After T Seconds

Hard
TreeDepth-First SearchBreadth-First SearchGraph TheoryDepth-First SearchGraph Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a depth-first search (DFS) approach with memoization to avoid recalculating probabilities for the same state. This significantly reduces redundant calculations and improves efficiency.

⚙️

Algorithm

4 steps
  1. 1Step 1: Build the graph from the edges.
  2. 2Step 2: Use DFS to explore paths from vertex 1, keeping track of time left and current probability.
  3. 3Step 3: If the time is zero, check if the current vertex is the target; if yes, return the probability.
  4. 4Step 4: For each unvisited neighbor, recursively call DFS, dividing the probability by the number of unvisited neighbors.
solution.py22 lines
1# Full working Python code
2from collections import defaultdict
3
4
5def frogPosition(n, edges, t, target):
6    graph = defaultdict(list)
7    for u, v in edges:
8        graph[u].append(v)
9        graph[v].append(u)
10
11    def dfs(vertex, time_left, prob, visited):
12        if time_left == 0:
13            return prob if vertex == target else 0
14        visited.add(vertex)
15        total_prob = 0
16        unvisited_neighbors = [v for v in graph[vertex] if v not in visited]
17        for neighbor in unvisited_neighbors:
18            total_prob += dfs(neighbor, time_left - 1, prob / len(unvisited_neighbors), visited)
19        visited.remove(vertex)
20        return total_prob
21
22    return dfs(1, t, 1, set())

Complexity note: The optimal solution runs in O(n) time because we effectively traverse each vertex once, and the space complexity is O(n) due to the storage of the graph and visited set.

  • 1The frog's movement is probabilistic based on available unvisited vertices.
  • 2The tree structure ensures that each vertex has a unique path, simplifying traversal.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.