Shortest Path Around Rectangular Obstacles
Updated
Problem statement
You are given an N by M grid of cells. A cell has coordinates (x, y), where 0 <= x < N and 0 <= y < M.
There are K axis-aligned rectangular obstacles. Rectangle i covers every cell whose coordinates satisfy X1[i] <= x <= X2[i] and Y1[i] <= y <= Y2[i]. Covered cells are blocked, and rectangles may overlap.
Start at (0, 0). In one step, you may move to an unblocked cell directly above, below, left, or right of your current cell. Return the minimum number of steps needed to reach (N - 1, M - 1).
Return -1 if no such path exists. In particular, return -1 when the start or destination cell is blocked.
Function
solution(N: int, M: int, X1: int[], Y1: int[], X2: int[], Y2: int[]) → intExamples
Example 1
N = 6M = 4X1 = [2,1,4]Y1 = [0,1,3]X2 = [2,3,4]Y2 = [2,1,3]return = 10One shortest route is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (1,3) -> (2,3) -> (3,3) -> (3,2) -> (4,2) -> (5,2) -> (5,3). It uses 10 steps and avoids every blocked cell.
Constraints
NandMare positive integers.X1,Y1,X2, andY2have the same lengthK;Kmay be zero.- For every
i,0 <= X1[i] <= X2[i] < Nand0 <= Y1[i] <= Y2[i] < M. - Rectangle coordinates are zero-indexed and inclusive.
More DRW Online Assessment questions
- Count Balanced Nodes in a Rooted TreeOA · Seen Sep 2026
- Largest Number With Even Digit FrequenciesOA · Seen Sep 2026
- 2020 Account Balance with Monthly Card FeesOA · Seen Aug 2026
- Nested In-Memory Database TransactionsOA · Seen Aug 2026
- Password Requirement CheckOA · Seen Aug 2026
- Remove Excess Consecutive CharactersOA · Seen Aug 2026
- Last Round for Each PlayerOA · Seen Jul 2026
- Shortest Compressed Length After RemovalOA · Seen Jul 2026
- Doctor Appointment Slot AssignmentOA · Seen Jul 2026
- Maximum Even-Sum Neighboring PairsOA · Seen Jul 2026
Similar questions at other companies
- Shortest Increasing Path to a TargetUber · ONSITE INTERVIEWUber interview questions
- Find and Reconstruct a Binary-Matrix PathMeta · PHONE SCREEN · ONSITE INTERVIEWMeta interview questions
- Find the Safest Path in a GridAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Shortest Distance from All BuildingsWaymo · PHONE SCREENWaymo interview questions
- Split a Matrix Into Four Partitions by Average (Forward Deployed Engineer)Boston Consulting Group · OABoston Consulting Group interview questions
- Minimum MovesHarness · OA
- Minimum Knight MovesMcKinsey & Company · OAMcKinsey & Company interview questions
- House Bounds in a Ragged GridRippling · OA · PHONE SCREENRippling interview questions
- Grid Path With the Most ClearanceDocuSign · OADocuSign interview questions
- Minimum MovesGoldman Sachs · OAGoldman Sachs interview questions