KatInterview

Evaluate Grid Path Feasibility and Identify Top K Elements

Trees & GraphsModel answer
MediumModel answerTrees & Graphstrees-graphsheaps-sortingarrays

Last updated

Determine matrix path reachability under obstacle constraints and extract the k most frequent elements from an array.

This assessment consists of two independent algorithmic parts commonly combined in technical screening rounds.

Part A: Grid Path Existence

Given a 2D matrix grid of size $m \times n$ containing values 0 (traversable) and 1 (obstacle), determine whether a valid path exists from the top-left cell (0, 0) to the bottom-right cell (m - 1, n - 1).

Rules & Constraints:

  • You can move in 4 cardinal directions: Up, Down, Left, or Right.
  • You cannot enter cells marked as 1 or move outside the grid boundaries.
  • Return true if a path exists, and false otherwise.
  • The input matrix may be empty or contain invalid start/end positions.

Part B: Most Frequent K Integers

Given an unsorted array of integers nums and an integer k, return an array containing the k most frequent numbers.

Rules & Constraints:

  • The order of elements in the output does not matter.
  • If multiple elements tie in frequency, any set of valid top k elements is accepted.
  • Explain the performance trade-offs of different selection strategies (e.g., Min-Heap, Sorting, Bucket Sort).

Hints

Hint 1

For Part A, consider why iterative Breadth-First Search (BFS) is preferred over recursive Depth-First Search (DFS) on large grids in production environments.

Hint 2

Ensure cells are marked as visited as soon as they are added to the traversal queue to prevent unnecessary duplicate processing.

Hint 3

For Part B, notice that the maximum possible frequency of any number is bounded by the size of the input array N. How can this property be used to achieve linear time complexity?