Skip to content

Add implementation for leetcode problems 102, 207#1636

Open
rishigoswamy wants to merge 1 commit intosuper30admin:masterfrom
rishigoswamy:master
Open

Add implementation for leetcode problems 102, 207#1636
rishigoswamy wants to merge 1 commit intosuper30admin:masterfrom
rishigoswamy:master

Conversation

@rishigoswamy
Copy link
Copy Markdown

No description provided.

@super30admin
Copy link
Copy Markdown
Owner

Level Order Traversal in Binary tree (leetcode_102.py)

Your exploration of multiple approaches (DFS with level tracking, BFS with queue) is commendable. However, the active DFS implementation has a few issues:

  1. You need to initialize a new list for a level when first encountered. Before appending to self.array[ht], you should ensure that there is a list at that index. You can do this by:
    if len(self.array) <= ht:
         self.array.append([])
    Then you can safely append to self.array[ht].
  2. Avoid using instance variables (like self.array and self.htMax) for recursive functions because they make the solution stateful and not reusable. Instead, define these variables inside the method and pass them as arguments to the recursive function or use a helper class.

Alternatively, the BFS solution you provided (commented out) is correct and efficient. I recommend using that because it is more straightforward for level-order traversal. Here's a cleaned-up version:

from collections import deque
from typing import List, Optional

class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        if not root:
            return []
        queue = deque([root])
        result = []
        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)
            result.append(level)
        return result

This BFS approach is standard and avoids recursion, which can be easier to understand.

VERDICT: NEEDS_IMPROVEMENT


Scheduling Courses (leetcode_207.py)

Your solution is well-written and correctly implements Kahn's algorithm for topological sorting. Here are some points to consider for improvement:

  1. Redundant Check: The check if len(queue)==numCourses is an optimization that can help in cases with no prerequisites, but it's not necessary for correctness. You can remove it without affecting the algorithm, as the main loop will process all nodes quickly in that case. However, it's a valid optimization.

  2. Edge Cases: Your solution handles the case where there are no zero-indegree nodes (cycle) correctly. Also, it handles the case with no prerequisites (all indegree zero) correctly. However, consider that the graph might not include all courses (if some courses have no prerequisites and are not prerequisites themselves). Your indegreeCount array is initialized for all courses from 0 to numCourses-1, which is correct.

  3. Code Clarity: The code is clear and well-commented. However, you might want to add a brief comment explaining why the algorithm works (i.e., if there is a cycle, the nodes in the cycle will never have indegree zero and won't be processed).

  4. Efficiency: The solution is efficient with O(V+E) time and space. One minor improvement: instead of iterating over indegreeCount at the end to check for non-zero values, you could maintain a count of how many nodes were processed. If the count of processed nodes equals numCourses, then there is no cycle. This would avoid the final loop and be slightly more efficient.

Example modification:

count = 0
while queue:
    currCourse = queue.popleft()
    count += 1
    for childCourse in adjMap[currCourse]:
        indegreeCount[childCourse] -= 1
        if indegreeCount[childCourse] == 0:
            queue.append(childCourse)

return count == numCourses

This change would make the code slightly more efficient and concise.

Overall, your solution is correct and efficient. Good job!

VERDICT: PASS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants