Topological Sort on grid
Last updated: April 23, 2026
Quick Overview
Given a directed acyclic graph (DAG) represented as a grid, implement a function to perform a topological sort on the grid. The function should return a list of nodes in a linear order such that for every directed edge from node A to node B, node A comes before node B in the ordering. The input will be a 2D array representing the grid, and the output should be a list of nodes in topologically sorted order.
Square/Block
April 23, 20268
2
3,863 solved
Given a directed acyclic graph (DAG) represented as a grid, implement a function to perform a topological sort on the grid. The function should return a list of nodes in a linear order such that for every directed edge from node A to node B, node A comes before node B in the ordering. The input will be a 2D array representing the grid, and the output should be a list of nodes in topologically sorted order.
This coding problem is frequently asked during Take-home Project at Square/Block. The interviewer is testing your ability to translate a problem into clean, working code while discussing time and space complexity. Square/Block expects candidates to write production-quality code, not just solve the puzzle.
What the Interviewer Expects
- Identify the correct data structure and algorithm for the problem
- Write clean, bug-free code with proper variable naming
- Analyze time and space complexity correctly
- Handle basic edge cases (empty input, single element)
- Communicate your thought process while coding
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would your solution change if the input was sorted?
- Can you optimize the space complexity of your solution?
- How would you modify your solution to handle streaming input?
- What is the worst-case input for your solution?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Problem Analysis
The problem presents a directed acyclic graph (DAG) represented as a grid. Each cell in the grid can be viewed as a node in the graph, and the directed edges can be represented by the adjacency relati...
Approach
- Building the Graph: We will first construct the graph from the grid by iterating through each cell. For each cell, we will check its adjacent cells (right and down) to establish directed edges....