Skip to content

ORIGINAL CODING QUESTION

Gentlest hiking trail effort

A team offsite hiking map stores an altitude for each cell. A trail runs from the top-left cell to the bottom-right cell through side-adjacent cells. Its effort is the largest absolute altitude change between two consecutive cells along it, and a single-cell trail has effort 0. Return the smallest effort any trail can achieve.

Open practice workspace

Original exercise · hard. Editorial role relevance does not imply a company has asked this question.

Input and output

rows cols, then rows×cols cell values in row-major order.

Constraints

1 ≤ rows,cols ≤ 8; 0 ≤ altitude ≤ 1000.

Example 1

Input

3 3 1 3 9 2 9 9 4 5 6

Output

2

Down the left column and along the bottom row (1,2,4,5,6) never changes by more than 2.

Example 2

Input

2 2 0 10 10 0

Output

10

Every trail must climb 10 and come back down.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

The cost of a trail is a maximum, not a sum, but shortest-path ideas still apply.

Hint 2

Run Dijkstra where reaching a neighbour costs max(current effort, altitude change).

Hint 3

Alternatively binary search the effort limit and test reachability with BFS.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →