Frog Position After T Seconds — LeetCode 1377 Python Solution

HardTreeDepth-First SearchBreadth-First SearchGraph
Problem
#1377
Reading time
4 min

The problem

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

Example

Input
n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4
Output
0.16666666666666666
Explanation
The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after second 1 and then jumping with 1/2 probability to vertex 4 after second 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666.

Python solution

Python
class Solution:
    def frogPosition(
        self, n: int, edges: List[List[int]], t: int, target: int
    ) -> float:
        g = defaultdict(list)
        for u, v in edges:
            g[u].append(v)
            g[v].append(u)
        q = deque([(1, 1.0)])
        vis = [False] * (n + 1)
        vis[1] = True
        while q and t >= 0:
            for _ in range(len(q)):
                u, p = q.popleft()
                cnt = len(g[u]) - int(u != 1)
                if u == target:
                    return p if cnt * t == 0 else 0
                for v in g[u]:
                    if not vis[v]:
                        vis[v] = True
                        q.append((v, p / cnt))
            t -= 1
        return 0

Complexity

MeasureComplexity
TimeO(V+E)
SpaceO(V) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1377. Frog Position After T Seconds is filed here because LeetCode tags it Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1377. Frog Position After T Seconds?
LeetCode 1377. Frog Position After T Seconds is rated Hard on LeetCode.
What is the time complexity of LeetCode 1377. Frog Position After T Seconds?
The Python solution on this page runs in O(V+E).
What is the space complexity of LeetCode 1377. Frog Position After T Seconds?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 1377. Frog Position After T Seconds cover?
LeetCode 1377. Frog Position After T Seconds is tagged Tree, Depth-First Search, Breadth-First Search and Graph on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview