Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1377: Frog Position After T Seconds

In this guide, we solve Leetcode #1377 Frog Position After T Seconds in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Tree, Depth-First Search, Breadth-First Search, Graph

Intuition

The data forms a graph, so we should explore nodes and edges systematically.

A traversal ensures we visit each node once while maintaining the needed state.

Approach

Build an adjacency list and traverse with BFS or DFS.

Aggregate results as you visit nodes.

Steps:

  • Build the graph.
  • Traverse with BFS/DFS.
  • Accumulate the required output.

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

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

The time complexity is O(V+E). The space complexity is O(V).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy