DEV Community

DSAwithSM
DSAwithSM

Posted on

5 LeetCode Problems #207, #572, #994, #112, #235 Explained | DSA Decoded

🧠 5 LeetCode Problems Explained with Code + Video

Part of the DSA Decoded series — step-by-step Python solutions with video walkthroughs.

Problems covered in this post:

  • 🟡 Course Schedule (LeetCode #207) · Medium · Graphs
  • 🟢 Subtree of Another Tree (LeetCode #572) · Easy · Trees
  • 🟡 Rotting Oranges (LeetCode #994) · Medium · Graphs
  • 🟢 Path Sum (LeetCode #112) · Easy · Trees
  • 🟢 Lowest Common Ancestor of a Binary Search Tree (LeetCode #235) · Easy · Trees

🟡 Course Schedule

Difficulty: Medium  |  Topic: Graphs  |  LeetCode #207

Problem

There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. Return true if you can finish all courses otherwise return false.

Solution

from collections import defaultdict

def can_finish(numCourses, prerequisites):
    graph = defaultdict(list)
    for a, b in prerequisites:
        graph[b].append(a)

    # 0=unvisited 1=visiting 2=done
    state = [0] * numCourses

    def dfs(node):
        if state[node] == 1: return False
        if state[node] == 2: return True
        state[node] = 1
        for nb in graph[node]:
            if not dfs(nb): return False
        state[node] = 2
        return True

    return all(dfs(i) for i in range(numCourses))
Enter fullscreen mode Exit fullscreen mode

🔗 Solve on LeetCode  ·  📺 Watch video explanation  ·  💻 Full solution + tests on GitHub


🟢 Subtree of Another Tree

Difficulty: Easy  |  Topic: Trees  |  LeetCode #572

Problem

Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise.

Solution

def is_subtree(root, subRoot):
    def is_same(p, q):
        if not p and not q: return True
        if not p or not q or p.val != q.val: return False
        return is_same(p.left, q.left) and is_same(p.right, q.right)

    if not root: return False
    if is_same(root, subRoot): return True
    return is_subtree(root.left, subRoot) or is_subtree(root.right, subRoot)
Enter fullscreen mode Exit fullscreen mode

🔗 Solve on LeetCode  ·  📺 Watch video explanation  ·  💻 Full solution + tests on GitHub


🟡 Rotting Oranges

Difficulty: Medium  |  Topic: Graphs  |  LeetCode #994

Problem

You are given an m x n grid where each cell can have value 0 (empty), 1 (fresh orange), or 2 (rotten orange). Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten. Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.

Solution

from collections import deque

def oranges_rotting(grid):
    rows, cols = len(grid), len(grid[0])
    fresh = 0
    queue = deque()
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == 2: queue.append((r, c, 0))
            elif grid[r][c] == 1: fresh += 1
    minutes = 0
    while queue:
        r, c, t = queue.popleft()
        for dr, dc in [(1,0),(-1,0),(0,1),(0,-1)]:
            nr, nc = r+dr, c+dc
            if 0<=nr<rows and 0<=nc<cols and grid[nr][nc]==1:
                grid[nr][nc] = 2
                fresh -= 1
                minutes = t + 1
                queue.append((nr, nc, t+1))
    return minutes if fresh == 0 else -1
Enter fullscreen mode Exit fullscreen mode

🔗 Solve on LeetCode  ·  📺 Watch video explanation  ·  💻 Full solution + tests on GitHub


🟢 Path Sum

Difficulty: Easy  |  Topic: Trees  |  LeetCode #112

Problem

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum. A leaf is a node with no children.

Solution

def has_path_sum(root, targetSum):
    if not root:
        return False
    if not root.left and not root.right:
        return root.val == targetSum
    return (has_path_sum(root.left, targetSum - root.val) or
            has_path_sum(root.right, targetSum - root.val))
Enter fullscreen mode Exit fullscreen mode

🔗 Solve on LeetCode  ·  📺 Watch video explanation  ·  💻 Full solution + tests on GitHub


🟢 Lowest Common Ancestor of a Binary Search Tree

Difficulty: Easy  |  Topic: Trees  |  LeetCode #235

Problem

Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes p and q in the BST. The LCA is defined as the lowest node that has both p and q as descendants (where a node can be a descendant of itself).

Solution

def lowest_common_ancestor(root, p, q):
    if p.val < root.val and q.val < root.val:
        return lowest_common_ancestor(root.left, p, q)
    if p.val > root.val and q.val > root.val:
        return lowest_common_ancestor(root.right, p, q)
    return root
Enter fullscreen mode Exit fullscreen mode

🔗 Solve on LeetCode  ·  📺 Watch video explanation  ·  💻 Full solution + tests on GitHub


🔔 Follow Along

New problems every 2 days — subscribe to stay consistent with your DSA prep!

Drop a comment with your approach — always curious to see other solutions!

Top comments (0)