KatInterview

practice a little every day — you've got this ♡

Trees & Graphs Interview Problems

Practice 5967 original coding, SQL, system design, machine learning and behavioral problems across 15 topics. Coding and SQL problems run against hidden test cases right in your browser; every problem has hints and a worked solution, free.

5967
Problems
2210
Auto-graded
15
Topics
272
Added today

Showing 31–60 of 85 results

  • Trees & GraphsMediumModel answer
    Validate-As-You-Go Calculator with Positive Integer Results

    Evaluate a split-based arithmetic expression, returning false the moment any literal or intermediate value is non-positive or non-integer.

    Trees & Graphsrecursionexpression-evaluationpost-orderparsing
  • Trees & GraphsHardModel answer
    Tree to String and Back: A Lossless Binary Tree Codec

    Build a pair of functions that flatten a binary tree of integers into a string and restore the identical tree from that string, with a clear format and a correctness argument.

    Trees & Graphsbinary-treeserializationpreorderstack
  • Trees & GraphsMediumModel answer
    Shared Ancestors: Binary Tree to Multi-Parent Graph

    Find the lowest common ancestor of two nodes in a binary tree, then generalize to a directed acyclic graph where several incomparable lowest common ancestors can exist.

    Trees & Graphslowest-common-ancestorbinary-treedagbfs
  • Trees & GraphsMediumModel answer
    Evaluate Grid Path Feasibility and Identify Top K Elements

    Determine matrix path reachability under obstacle constraints and extract the k most frequent elements from an array.

    Trees & Graphstrees-graphsheaps-sortingarrays
  • Trees & GraphsMediumModel answer
    Traverse a Concurrent Dependency Graph with Rate Control and Retries

    Discover the full transitive dependency graph of a package using sequential BFS and concurrent worker pools with retry handling and exact termination logic.

    Trees & Graphstrees-graphsdesign-dsstacks-queuesconcurrency
  • Trees & GraphsMediumModel answer
    Collect Every Reachable Page on a Single Host

    Write a function that explores a website from one starting URL, following only links on the same hostname, and returns each distinct page once while coping with link cycles.

    Trees & Graphsgraph-traversalbfsurl-normalizationdeduplication
  • Trees & GraphsMediumModel answer
    Resolve Out-of-Order Variable Assignments in a Mini Language

    Parse lines of integer assignments using only + and -, resolve forward and chained references, and report undefined names and cycles in a well-defined way.

    Trees & Graphstopological-sortparsingdependency-graphcycle-detection
  • Trees & GraphsEasyModel answer
    Lone-Parity Filter and Leftmost Node Per Tree Depth

    Write one function that returns the elements whose even/odd class appears exactly once in an array, plus the first node's value at every depth of a binary tree.

    Trees & Graphsbfsbinary-treelevel-ordercounting
  • Trees & GraphsHardModel answer
    Principal Types for a Tiny Lambda Calculus

    Build an AST for variables, lambdas and applications, then infer each expression's most general function type using unification, with an occurs check to reject infinite types.

    Trees & Graphstype-inferenceunificationhindley-milnerast
  • Trees & GraphsMediumModel answer
    Tallying a Tree of Message-Passing Processes

    Each tree node is an isolated process with only async send and blocking receive. Design a protocol so the root learns the tree size, tolerates lost and duplicate messages, and returns a structured result.

    Trees & Graphsdistributed-systemsconvergecastidempotencyretries
  • Trees & GraphsMediumModel answer
    Crawl a Web-Served Labyrinth Through Unreliable Responses

    Write a crawler that explores a maze of HTTP endpoints to find the exit, coping with cycles, transient 503 errors and malformed JSON, while guaranteeing termination.

    Trees & Graphsgraph-traversalbfshttpretries
  • Trees & GraphsMediumModel answer
    Concurrent Site Crawler with Fault-Tolerant Fetching

    Build a crawler that explores every page reachable from a seed URL using a slow, flaky link API, evolving from a sequential traversal to a thread pool with bounded, backoff-driven retries.

    Trees & Graphsweb-crawlerconcurrencybfsretries
  • Trees & GraphsMediumModel answer
    Crawl One Site: Sequential Traversal, Then a Parallel Version

    Collect every page reachable from a seed URL on the same host, ignoring URL fragments and fetching each page once, first with one thread and then with safe concurrency.

    Trees & Graphsweb-crawlerbfsconcurrencythread-safety
  • Trees & GraphsMediumModel answer
    Print a Reporting Hierarchy and List Two-Level-Down Pairs

    Turn manager rows into a tree, infer the root, print it with depth-based dot indentation, or list every (manager, employee) pair exactly two levels apart.

    Trees & Graphstreepreorderiterative-dfshash-map
  • Trees & GraphsMediumModel answer
    Thread-Pooled Link Crawler with Depth Limit and Dedup

    Implement a thread-safe crawler that explores links from a seed page to a given depth, never fetches a URL twice, and caps the number of simultaneous fetches.

    Trees & Graphsconcurrencybfsthread-poolgraph-traversal
  • Trees & GraphsMediumModel answer
    Round-Trip Text Encoding for Ordered Trees with Any Number of Children

    Define a text format for ordered trees with arbitrary branching, then write an encoder and decoder that rebuild the exact same values, structure and child order in linear time.

    Trees & Graphstreeserializationn-ary-treeiterative-dfs
  • Trees & GraphsHardModel answer
    Rewrite a Relational Plan: Sink Filters and Trim Columns

    Transform a tree of Scan, Filter, Project and Join operators by moving filters toward the leaves and removing unused columns, while keeping query results unchanged.

    Trees & Graphstree-rewritingquery-optimizationpredicate-pushdownprojection-pruning
  • Trees & GraphsMediumModel answer
    Count All Valid 4×4 Three-in-a-Row Game Sequences

    Use recursion and backtracking to enumerate every ordered move sequence on a 4×4 board where three consecutive marks (not four) wins.

    Trees & Graphsbacktrackingrecursiongame-treecombinatorics
  • Trees & GraphsMediumModel answer
    Currency Conversion Rates via Graph Traversal

    Build a weighted graph from currency pairs and answer conversion queries, then extend to directional rates and arbitrage detection.

    Trees & Graphsgraph-traversalshortest-pathbellman-fordfloating-point
  • Trees & GraphsMediumModel answer
    Minimum Spread Time for Contamination in a Grid

    Find how many steps a contamination spreads from multiple sources through a grid, or determine if some cells remain permanently unaffected.

    Trees & GraphsBFSmulti-source BFSgrid traversalshortest path
  • Trees & GraphsMediumModel answer
    Trace a Target String Through a Character Grid

    Decide whether a word can be spelled by a non-repeating, four-directional path of adjacent cells in a character matrix, with pruning and complexity analysis.

    Trees & Graphsbacktrackingdepth-first-searchgridpruning
  • Trees & GraphsMediumModel answer
    Collapsible Nested Menu with ARIA Support

    Design and code a React component that displays hierarchical data with interactive expand/collapse behavior and full keyboard accessibility.

    Trees & Graphsreactrecursionaccessibilitystate-management
  • Trees & GraphsMediumModel answer
    Threaded Comment Feed: Filtering, Nesting, and Persistent Sort

    Transform a flat array of comments into a sorted, nested, filterable tree while persisting the user's sort preference across sessions.

    Trees & Graphstree-constructiondfslocalStoragefrontend-data
  • Trees & GraphsMediumModel answer
    Content-Based Duplicate File Detector

    Recursively scan a directory tree, group files by size then content hash, and return every set of two or more paths that hold identical bytes.

    Trees & Graphshashingfile-systemtraversaldeduplication
  • Trees & GraphsMediumModel answer
    Find the Longest Path in an Undirected Tree

    Given a tree as an adjacency list, return the sequence of nodes forming its diameter — the longest simple path between any two nodes.

    Trees & GraphsBFSDFStree diameterpath reconstruction
  • Trees & GraphsHardModel answer
    Check Whether a Node Sequence Is a Valid BFS on a Tree

    Given an undirected tree and multiple permutations of its nodes, determine for each permutation whether it could be the dequeue order of some BFS starting at its first element.

    Trees & GraphsBFStreessimulationhashing
  • Trees & GraphsMediumModel answer
    Height-Balanced Nodes in Heap-Array Trees

    Traverse a binary tree stored in heap-index layout to find every node whose subtree is height-balanced, returning each with its tree level.

    Trees & Graphsbinary-treepost-orderheap-layoutbottom-up
  • Trees & GraphsMediumModel answer
    Nearest Depot and Peak-Load Routing on a Grid

    Given a grid with depot cells, find shortest paths from query locations to any depot, then extend to pick the depot maximizing a distance-penalized load score.

    Trees & GraphsBFSDijkstramulti-sourcegrid
  • Trees & GraphsMediumModel answer
    Propagating Allow/Deny Permissions Through an Inheritance DAG

    Given a DAG where each node carries allow and deny lists, compute every node's effective permissions by inheriting and merging rules along edges in topological order.

    Trees & Graphsgraphstopological-sortpermissionsDAG
  • Trees & GraphsMediumModel answer
    Rebuild a Binary Tree from Pre- and In-Order Sequences

    Given preorder and inorder traversal arrays of a binary tree with unique values, reconstruct the tree in O(n) time and O(n) space.

    Trees & Graphsbinary-treerecursionhash-maptraversal