KatInterview

Maximum Straight-Line Distance Through Dangerous Zones

Arrays & HashingAuto-graded · 20 test cases
MediumAuto-gradedArrays & Hashingbinary-searchgridgeometry

Last updated

Tests efficient grid reasoning with blocked regions and directional movement constraints using binary search.

You have a rectangular grid with num_rows rows and num_cols columns. Certain positions contain hazards that make entire rows and columns impassable. Specifically, a hazard located at position (r, c) renders every cell in row r unsafe and every cell in column c unsafe.

A vehicle begins at position (start_row, start_col). While the vehicle's initial position remains safe regardless of hazards, it must travel in a single straight line (up, down, left, or right) without changing direction. The vehicle can only move through cells that are:

  • Within grid boundaries
  • Not made unsafe by any hazard

Note that the safety of the starting position does not extend to any other cell, including the very first cell the vehicle enters.

Determine the maximum number of cells the vehicle can pass through when moving optimally in one of the four cardinal directions. The starting cell itself does not count toward this total. If no safe movement exists in any direction, return 0.

Coordinates: All positions use 1-based indexing. Rows range from 1 to num_rows, and columns range from 1 to num_cols.

Constraints:

  • 1 ≤ num_rows, num_cols ≤ 10^9
  • 1 ≤ start_row ≤ num_rows
  • 1 ≤ start_col ≤ num_cols
  • 0 ≤ len(hazard_positions) ≤ 10^5
  • Each hazard position [r, c] satisfies 1 ≤ r ≤ num_rows and 1 ≤ c ≤ num_cols

Examples

Example 1

Input: max_straight_distance(8, 8, 5, 3, [[1, 6], [2, 8]])

Output: 3

Example 2

Input: max_straight_distance(5, 5, 3, 3, [[1, 1], [5, 5]])

Output: 1

Example 3

Input: max_straight_distance(10, 12, 5, 6, [])

Output: 6

Hints

Hint 1

A hazard blocks an entire row and an entire column. You don't need to simulate individual cells.

Hint 2

Moving vertically keeps you in the same column. If that column is blocked, vertical movement is impossible.

Hint 3

Use binary search to find the nearest blocked row or column in each direction.