Cut Trees in Increasing Height Order With the Fewest Steps
Last updated: November 29, 2026
Quick Overview
A forest grid has 0 for obstacles, 1 for walkable ground, and values above 1 for trees of that height. Starting at (0, 0), you must cut all trees in increasing height order; a cut tree becomes ground. Return the total steps, or -1 if any tree is unreachable.
0
0
0 solved
A forest grid has 0 for obstacles, 1 for walkable ground, and values above 1 for trees of that height. Starting at (0, 0), you must cut all trees in increasing height order; a cut tree becomes ground. Return the total steps, or -1 if any tree is unreachable.
An onsite question built around repeated shortest-path queries on a grid, the kind of planning a Maps-style routing system or field robot does. The interviewer checks that you decompose the task into ordered BFS legs and reason honestly about the cost of many BFS runs.
What the Interviewer Expects
- Sort trees by height to fix the visit order
- Run BFS between consecutive targets
- Sum the leg distances and fail on any unreachable leg
- Treat trees as walkable before being cut
- Discuss A* or Hadlock's algorithm to speed up legs
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
- Speed up each leg with A* and a Manhattan heuristic.
- What if you could cut trees in any order?
- What if cutting takes time proportional to tree height?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input: grid of ints; values above 1 are distinct tree heights.
- You may walk through trees (cut or not) but not through 0.
- Cut order is forced: ascending height.
- Output: total steps or -1....
High-Level Design
Since the order is fixed, the task is a sequence of independent shortest-path problems: start to tree 1, tree 1 to tree 2, and so on. Cutting a tree turns it into ground, which does not change walkabi...