PracHub
QuestionsPremiumCoachesLearningGuidesInterview Prep

Quick Overview

This set of problems evaluates proficiency in core data structures and algorithms, specifically binary tree traversals (including zigzag/level-order patterns), directed graph cycle detection and topological ordering, and sliding-window techniques for substring analysis.

  • Medium
  • Google
  • Coding & Algorithms
  • Software Engineer

Solve tree, graph, sliding-window problems

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: Medium

Interview Round: Technical Screen

##### Question LeetCode 103. Binary Tree Zigzag Level Order Traversal – given a binary tree root, return its zigzag level-order traversal. LeetCode 207. Course Schedule – given course prerequisites, determine if all courses can be finished by detecting cycles with topological sort. LeetCode 340. Longest Substring with At Most K Distinct Characters – given string s and integer k, return the length of the longest substring containing at most k distinct characters. https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/description/ https://leetcode.com/problems/course-schedule/description/ https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/description/

Quick Answer: This set of problems evaluates proficiency in core data structures and algorithms, specifically binary tree traversals (including zigzag/level-order patterns), directed graph cycle detection and topological ordering, and sliding-window techniques for substring analysis.

Part 1: Binary Tree Zigzag Level Order Traversal

You are given a binary tree in level-order array form, where each element is either an integer or None for a missing child. Return the zigzag level-order traversal of the tree's node values. In a zigzag traversal, the first level is read from left to right, the second from right to left, the third from left to right, and so on.

Constraints

  • 0 <= len(root) <= 2000
  • Each non-None node value is an integer in the range [-10^4, 10^4]
  • The input list represents a valid binary tree in level-order form

Examples

Input: ([3, 9, 20, None, None, 15, 7],)

Expected Output: [[3], [20, 9], [15, 7]]

Explanation: Level 1 is read left-to-right, level 2 right-to-left, and level 3 left-to-right.

Input: ([1],)

Expected Output: [[1]]

Explanation: A single-node tree has only one level.

Input: ([],)

Expected Output: []

Explanation: An empty tree has no levels to traverse.

Input: ([1, 2, 3, 4, None, None, 5],)

Expected Output: [[1], [3, 2], [4, 5]]

Explanation: The second level is reversed, while the first and third remain left-to-right.

Solution

def solution(root):
    from collections import deque

    if not root:
        return []

    class TreeNode:
        def __init__(self, val):
            self.val = val
            self.left = None
            self.right = None

    values = iter(root)
    first = next(values)
    if first is None:
        return []

    tree_root = TreeNode(first)
    build_queue = deque([tree_root])

    while build_queue:
        node = build_queue.popleft()
        try:
            left_val = next(values)
        except StopIteration:
            break
        if left_val is not None:
            node.left = TreeNode(left_val)
            build_queue.append(node.left)

        try:
            right_val = next(values)
        except StopIteration:
            break
        if right_val is not None:
            node.right = TreeNode(right_val)
            build_queue.append(node.right)

    result = []
    bfs_queue = deque([tree_root])
    left_to_right = True

    while bfs_queue:
        level = []
        for _ in range(len(bfs_queue)):
            node = bfs_queue.popleft()
            level.append(node.val)
            if node.left:
                bfs_queue.append(node.left)
            if node.right:
                bfs_queue.append(node.right)

        if not left_to_right:
            level.reverse()
        result.append(level)
        left_to_right = not left_to_right

    return result

Time complexity: O(n). Space complexity: O(n).

Hints

  1. A breadth-first search naturally processes the tree one level at a time.
  2. You can collect each level left-to-right, then reverse every other level before appending it to the answer.

Part 2: Course Schedule

There are num_courses courses labeled from 0 to num_courses - 1. You are given a list of prerequisite pairs [a, b], meaning you must take course b before course a. Determine whether it is possible to finish all courses. This is equivalent to checking whether the prerequisite graph contains a cycle.

Constraints

  • 1 <= num_courses <= 10^5
  • 0 <= len(prerequisites) <= 2 * 10^5
  • Each prerequisite pair has length 2
  • 0 <= course, prerequisite < num_courses

Examples

Input: (2, [[1, 0]])

Expected Output: True

Explanation: Course 0 can be taken first, then course 1.

Input: (2, [[1, 0], [0, 1]])

Expected Output: False

Explanation: The two courses depend on each other, forming a cycle.

Input: (1, [])

Expected Output: True

Explanation: With one course and no prerequisites, finishing is always possible.

Input: (4, [[1, 0], [2, 0], [3, 1], [3, 2]])

Expected Output: True

Explanation: A valid order is 0, 1, 2, 3 or 0, 2, 1, 3.

Input: (5, [[1, 0], [0, 1], [3, 4]])

Expected Output: False

Explanation: Courses 0 and 1 form a cycle, so not all courses can be completed.

Solution

def solution(num_courses, prerequisites):
    from collections import deque

    graph = [[] for _ in range(num_courses)]
    indegree = [0] * num_courses

    for course, prereq in prerequisites:
        graph[prereq].append(course)
        indegree[course] += 1

    queue = deque([i for i in range(num_courses) if indegree[i] == 0])
    finished = 0

    while queue:
        current = queue.popleft()
        finished += 1
        for nxt in graph[current]:
            indegree[nxt] -= 1
            if indegree[nxt] == 0:
                queue.append(nxt)

    return finished == num_courses

Time complexity: O(num_courses + len(prerequisites)). Space complexity: O(num_courses + len(prerequisites)).

Hints

  1. Think of courses as nodes in a directed graph and prerequisites as directed edges.
  2. If you repeatedly take courses with indegree 0 and cannot process all nodes, a cycle exists.

Part 3: Longest Substring with At Most K Distinct Characters

Given a string s and an integer k, return the length of the longest substring that contains at most k distinct characters.

Constraints

  • 0 <= len(s) <= 2 * 10^5
  • 0 <= k <= len(s)
  • s may contain any standard characters

Examples

Input: ("eceba", 2)

Expected Output: 3

Explanation: The longest valid substring is 'ece', which has length 3.

Input: ("aa", 1)

Expected Output: 2

Explanation: The whole string contains only one distinct character.

Input: ("", 3)

Expected Output: 0

Explanation: An empty string has no substrings, so the answer is 0.

Input: ("a", 0)

Expected Output: 0

Explanation: With k = 0, no non-empty substring is allowed.

Input: ("abaccc", 2)

Expected Output: 4

Explanation: The longest valid substring is 'accc', which contains only 'a' and 'c'.

Solution

def solution(s, k):
    if k == 0 or not s:
        return 0

    counts = {}
    left = 0
    best = 0

    for right, ch in enumerate(s):
        counts[ch] = counts.get(ch, 0) + 1

        while len(counts) > k:
            left_ch = s[left]
            counts[left_ch] -= 1
            if counts[left_ch] == 0:
                del counts[left_ch]
            left += 1

        best = max(best, right - left + 1)

    return best

Time complexity: O(len(s)). Space complexity: O(min(len(s), k)).

Hints

  1. A sliding window can maintain a valid substring while expanding to the right.
  2. Keep character counts in the current window, and shrink from the left whenever the number of distinct characters exceeds k.
Last updated: May 26, 2026

Loading coding console...

PracHub

Master your tech interviews with 8,500+ real questions from top companies.

Product

  • Questions
  • Learning Tracks
  • Interview Guides
  • Resources
  • Premium
  • For Universities
  • Student Access

Browse

  • By Company
  • By Role
  • By Category
  • Topic Hubs
  • SQL Questions
  • Compare Platforms
  • Discord Community

Support

  • support@prachub.com
  • (916) 541-4762

Legal

  • Privacy Policy
  • Terms of Service
  • About Us

© 2026 PracHub. All rights reserved.

Related Coding Questions

  • Find Containing Range - Google (medium)
  • Rearrange Tasks With Cooldown - Google (medium)
  • Solve Three Array and Matrix Path Problems - Google (medium)
  • Consolidate On-Call Rotation Segments - Google (medium)
  • Solve Flower Placement and Directory Deletion - Google (medium)