Category: LeetCode Solutions

  • LeetCode 210: Course Schedule II — Python Solution

    Solve LeetCode 210: Course Schedule II in Python with a topological ordering approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

    This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

    DifficultyMedium
    TopicGraph General
    Reusable patterntopological ordering
    ComplexityO(V+E) time and O(V+E) space

    What the problem is testing

    Use Kahn’s algorithm and append each removed zero-indegree course to the order; return it only if every course is processed.

    Algorithm

    1. Use Kahn’s algorithm and append each removed zero-indegree course to the order; return it only if every course is processed.
    2. Maintain this invariant: Every appended course has all prerequisites earlier in the output.
    3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

    Python solution

    from collections import Counter, defaultdict, deque, OrderedDict
    import random
    
    class Solution:
        def findOrder(self, numCourses, prerequisites):
            graph = [[] for _ in range(numCourses)]; indegree = [0] * numCourses
            for course, prerequisite in prerequisites:
                graph[prerequisite].append(course); indegree[course] += 1
            queue = deque(i for i, degree in enumerate(indegree) if degree == 0)
            order = []
            while queue:
                course = queue.popleft(); order.append(course)
                for following in graph[course]:
                    indegree[following] -= 1
                    if indegree[following] == 0: queue.append(following)
            return order if len(order) == numCourses else []

    Why this is correct

    The proof follows the maintained state: Every appended course has all prerequisites earlier in the output. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

    Complexity

    O(V+E) time and O(V+E) space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

    Edge cases

    A cycle returns an empty list; isolated courses begin with zero indegree.

    Tested reference code

    This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


    Browse the searchable 100 LeetCode Python Solutions hub. Previous: 207. Course Schedule · Next: 909. Snakes and Ladders

  • LeetCode 637: Average of Levels in Binary Tree — Python Solution

    Solve LeetCode 637: Average of Levels in Binary Tree in Python with a level aggregation approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

    This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

    DifficultyEasy
    TopicBinary Tree BFS
    Reusable patternlevel aggregation
    ComplexityO(n) time and O(w) space

    What the problem is testing

    For each BFS level, sum exactly its current queue length and divide by that length.

    Algorithm

    1. For each BFS level, sum exactly its current queue length and divide by that length.
    2. Maintain this invariant: Before moving to the next level, every node from the current level contributes once to its sum.
    3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

    Python solution

    LeetCode provides the list, tree, or graph node definition used by the method.

    from collections import Counter, defaultdict, deque, OrderedDict
    import random
    
    class Solution:
        def averageOfLevels(self, root):
            queue, answer = deque([root]), []
            while queue:
                level_size = len(queue)
                total = 0
                for _ in range(level_size):
                    node = queue.popleft(); total += node.val
                    if node.left: queue.append(node.left)
                    if node.right: queue.append(node.right)
                answer.append(total / level_size)
            return answer

    Why this is correct

    The proof follows the maintained state: Before moving to the next level, every node from the current level contributes once to its sum. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

    Complexity

    O(n) time and O(w) space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

    Edge cases

    Use numeric division; values may be negative.

    Tested reference code

    This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


    Browse the searchable 100 LeetCode Python Solutions hub. Previous: 199. Binary Tree Right Side View · Next: 102. Binary Tree Level Order Traversal

  • LeetCode 102: Binary Tree Level Order Traversal — Python Solution

    Solve LeetCode 102: Binary Tree Level Order Traversal in Python with a breadth-first levels approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

    This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

    DifficultyMedium
    TopicBinary Tree BFS
    Reusable patternbreadth-first levels
    ComplexityO(n) time and O(w) space

    What the problem is testing

    Process exactly the queue length captured at the start of each level and append discovered children for the next level.

    Algorithm

    1. Process exactly the queue length captured at the start of each level and append discovered children for the next level.
    2. Maintain this invariant: The nodes removed in one batch all have the same depth.
    3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

    Python solution

    LeetCode provides the list, tree, or graph node definition used by the method.

    from collections import Counter, defaultdict, deque, OrderedDict
    import random
    
    class Solution:
        def levelOrder(self, root):
            if not root:
                return []
            queue, answer = deque([root]), []
            while queue:
                level = []
                for _ in range(len(queue)):
                    node = queue.popleft(); level.append(node.val)
                    if node.left: queue.append(node.left)
                    if node.right: queue.append(node.right)
                answer.append(level)
            return answer

    Why this is correct

    The proof follows the maintained state: The nodes removed in one batch all have the same depth. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

    Complexity

    O(n) time and O(w) space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

    Edge cases

    An empty tree yields no levels.

    Tested reference code

    This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


    Browse the searchable 100 LeetCode Python Solutions hub. Previous: 637. Average of Levels in Binary Tree · Next: 103. Binary Tree Zigzag Level Order Traversal

  • LeetCode 103: Binary Tree Zigzag Level Order Traversal — Python Solution

    Solve LeetCode 103: Binary Tree Zigzag Level Order Traversal in Python with a alternating level output approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

    This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

    DifficultyMedium
    TopicBinary Tree BFS
    Reusable patternalternating level output
    ComplexityO(n) time and O(w) space

    What the problem is testing

    Run ordinary BFS and reverse the collected values on alternating levels.

    Algorithm

    1. Run ordinary BFS and reverse the collected values on alternating levels.
    2. Maintain this invariant: Each level is collected left-to-right before the direction flag determines output order.
    3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

    Python solution

    LeetCode provides the list, tree, or graph node definition used by the method.

    from collections import Counter, defaultdict, deque, OrderedDict
    import random
    
    class Solution:
        def zigzagLevelOrder(self, root):
            if not root:
                return []
            queue, answer, reverse = deque([root]), [], False
            while queue:
                level = []
                for _ in range(len(queue)):
                    node = queue.popleft(); level.append(node.val)
                    if node.left: queue.append(node.left)
                    if node.right: queue.append(node.right)
                answer.append(level[::-1] if reverse else level)
                reverse = not reverse
            return answer

    Why this is correct

    The proof follows the maintained state: Each level is collected left-to-right before the direction flag determines output order. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

    Complexity

    O(n) time and O(w) space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

    Edge cases

    The root level is left-to-right; direction flips after every level.

    Tested reference code

    This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


    Browse the searchable 100 LeetCode Python Solutions hub. Previous: 102. Binary Tree Level Order Traversal · Next: 530. Minimum Absolute Difference in BST

  • LeetCode 530: Minimum Absolute Difference in BST — Python Solution

    Solve LeetCode 530: Minimum Absolute Difference in BST in Python with a inorder adjacent difference approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

    This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

    DifficultyEasy
    TopicBinary Search Tree
    Reusable patterninorder adjacent difference
    ComplexityO(n) time and O(h) recursion space

    What the problem is testing

    Inorder traversal visits BST values in sorted order, so the minimum absolute difference appears between adjacent visited values.

    Algorithm

    1. Inorder traversal visits BST values in sorted order, so the minimum absolute difference appears between adjacent visited values.
    2. Maintain this invariant: prev is the greatest value visited before the current node.
    3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

    Python solution

    LeetCode provides the list, tree, or graph node definition used by the method.

    from collections import Counter, defaultdict, deque, OrderedDict
    import random
    
    class Solution:
        def getMinimumDifference(self, root):
            previous, best = None, float("inf")
            def inorder(node):
                nonlocal previous, best
                if not node: return
                inorder(node.left)
                if previous is not None: best = min(best, node.val - previous)
                previous = node.val
                inorder(node.right)
            inorder(root)
            return best

    Why this is correct

    The proof follows the maintained state: prev is the greatest value visited before the current node. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

    Complexity

    O(n) time and O(h) recursion space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

    Edge cases

    Initialize without a numeric sentinel so negative values are safe.

    Tested reference code

    This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


    Browse the searchable 100 LeetCode Python Solutions hub. Previous: 103. Binary Tree Zigzag Level Order Traversal · Next: 230. Kth Smallest Element in a BST

  • LeetCode 230: Kth Smallest Element in a BST — Python Solution

    Solve LeetCode 230: Kth Smallest Element in a BST in Python with a iterative inorder approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

    This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

    DifficultyMedium
    TopicBinary Search Tree
    Reusable patterniterative inorder
    ComplexityO(h+k) typical time and O(h) space

    What the problem is testing

    Push left descendants, pop the next smallest node, decrement k, and then explore its right subtree.

    Algorithm

    1. Push left descendants, pop the next smallest node, decrement k, and then explore its right subtree.
    2. Maintain this invariant: The next stack pop is the smallest unvisited BST value.
    3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

    Python solution

    LeetCode provides the list, tree, or graph node definition used by the method.

    from collections import Counter, defaultdict, deque, OrderedDict
    import random
    
    class Solution:
        def kthSmallest(self, root, k):
            stack = []
            while True:
                while root:
                    stack.append(root); root = root.left
                root = stack.pop(); k -= 1
                if k == 0: return root.val
                root = root.right

    Why this is correct

    The proof follows the maintained state: The next stack pop is the smallest unvisited BST value. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

    Complexity

    O(h+k) typical time and O(h) space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

    Edge cases

    k is one-based and guaranteed valid.

    Tested reference code

    This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


    Browse the searchable 100 LeetCode Python Solutions hub. Previous: 530. Minimum Absolute Difference in BST · Next: 98. Validate Binary Search Tree

  • LeetCode 98: Validate Binary Search Tree — Python Solution

    Solve LeetCode 98: Validate Binary Search Tree in Python with a recursive value bounds approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

    This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

    DifficultyMedium
    TopicBinary Search Tree
    Reusable patternrecursive value bounds
    ComplexityO(n) time and O(h) recursion space

    What the problem is testing

    Pass strict lower and upper bounds into each subtree; every node must lie inside its inherited interval.

    Algorithm

    1. Pass strict lower and upper bounds into each subtree; every node must lie inside its inherited interval.
    2. Maintain this invariant: The bounds represent every ancestor constraint that applies to the current subtree.
    3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

    Python solution

    LeetCode provides the list, tree, or graph node definition used by the method.

    from collections import Counter, defaultdict, deque, OrderedDict
    import random
    
    class Solution:
        def isValidBST(self, root):
            def valid(node, lower, upper):
                if not node: return True
                if not lower < node.val < upper: return False
                return valid(node.left, lower, node.val) and valid(node.right, node.val, upper)
            return valid(root, float("-inf"), float("inf"))

    Why this is correct

    The proof follows the maintained state: The bounds represent every ancestor constraint that applies to the current subtree. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

    Complexity

    O(n) time and O(h) recursion space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

    Edge cases

    Duplicates are invalid because inequalities are strict.

    Tested reference code

    This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


    Browse the searchable 100 LeetCode Python Solutions hub. Previous: 230. Kth Smallest Element in a BST · Next: 200. Number of Islands

  • LeetCode 200: Number of Islands — Python Solution

    Solve LeetCode 200: Number of Islands in Python with a grid flood fill approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

    This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

    DifficultyMedium
    TopicGraph General
    Reusable patterngrid flood fill
    ComplexityO(mn) time and O(mn) worst-case recursion space

    What the problem is testing

    When an unvisited land cell is found, count one island and flood-fill all orthogonally connected land.

    Algorithm

    1. When an unvisited land cell is found, count one island and flood-fill all orthogonally connected land.
    2. Maintain this invariant: Every changed land cell belongs to the island currently being removed from future consideration.
    3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

    Python solution

    from collections import Counter, defaultdict, deque, OrderedDict
    import random
    
    class Solution:
        def numIslands(self, grid):
            if not grid: return 0
            rows, cols, islands = len(grid), len(grid[0]), 0
            def flood(r, c):
                if r < 0 or c < 0 or r == rows or c == cols or grid[r][c] != "1": return
                grid[r][c] = "0"
                flood(r + 1, c); flood(r - 1, c); flood(r, c + 1); flood(r, c - 1)
            for r in range(rows):
                for c in range(cols):
                    if grid[r][c] == "1": islands += 1; flood(r, c)
            return islands

    Why this is correct

    The proof follows the maintained state: Every changed land cell belongs to the island currently being removed from future consideration. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

    Complexity

    O(mn) time and O(mn) worst-case recursion space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

    Edge cases

    Only horizontal and vertical neighbors connect; an all-water grid returns zero.

    Tested reference code

    This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


    Browse the searchable 100 LeetCode Python Solutions hub. Previous: 98. Validate Binary Search Tree · Next: 130. Surrounded Regions

  • LeetCode 124: Binary Tree Maximum Path Sum — Python Solution

    Solve LeetCode 124: Binary Tree Maximum Path Sum in Python with a postorder gain DP approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

    This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

    DifficultyHard
    TopicBinary Tree General
    Reusable patternpostorder gain DP
    ComplexityO(n) time and O(h) recursion space

    What the problem is testing

    Return the best downward gain from each node while updating a global answer with the path that uses both positive child gains through that node.

    Algorithm

    1. Return the best downward gain from each node while updating a global answer with the path that uses both positive child gains through that node.
    2. Maintain this invariant: The returned gain is the best path starting at the node and extending through at most one child.
    3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

    Python solution

    LeetCode provides the list, tree, or graph node definition used by the method.

    from collections import Counter, defaultdict, deque, OrderedDict
    import random
    
    class Solution:
        def maxPathSum(self, root):
            best = float("-inf")
            def gain(node):
                nonlocal best
                if not node:
                    return 0
                left = max(0, gain(node.left))
                right = max(0, gain(node.right))
                best = max(best, node.val + left + right)
                return node.val + max(left, right)
            gain(root)
            return best

    Why this is correct

    The proof follows the maintained state: The returned gain is the best path starting at the node and extending through at most one child. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

    Complexity

    O(n) time and O(h) recursion space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

    Edge cases

    Negative child gains are discarded; an all-negative tree returns its largest node.

    Tested reference code

    This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


    Browse the searchable 100 LeetCode Python Solutions hub. Previous: 129. Sum Root to Leaf Numbers · Next: 173. Binary Search Tree Iterator

  • LeetCode 173: Binary Search Tree Iterator — Python Solution

    Solve LeetCode 173: Binary Search Tree Iterator in Python with a lazy inorder stack approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

    This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

    DifficultyMedium
    TopicBinary Tree General
    Reusable patternlazy inorder stack
    ComplexityO(1) amortized next time and O(h) space

    What the problem is testing

    Push the left spine initially and after each pop push the left spine of its right child.

    Algorithm

    1. Push the left spine initially and after each pop push the left spine of its right child.
    2. Maintain this invariant: The stack top is the smallest not-yet-returned BST node.
    3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

    Python solution

    LeetCode provides the list, tree, or graph node definition used by the method.

    from collections import Counter, defaultdict, deque, OrderedDict
    import random
    
    class BSTIterator:
        def __init__(self, root):
            self.stack = []
            self._push_left(root)
    
        def _push_left(self, node):
            while node:
                self.stack.append(node)
                node = node.left
    
        def next(self):
            node = self.stack.pop()
            self._push_left(node.right)
            return node.val
    
        def hasNext(self):
            return bool(self.stack)

    Why this is correct

    The proof follows the maintained state: The stack top is the smallest not-yet-returned BST node. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

    Complexity

    O(1) amortized next time and O(h) space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

    Edge cases

    A right subtree can add several nodes, but each node is pushed and popped once.

    Tested reference code

    This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


    Browse the searchable 100 LeetCode Python Solutions hub. Previous: 124. Binary Tree Maximum Path Sum · Next: 222. Count Complete Tree Nodes