VOOZH about

URL: https://www.geeksforgeeks.org/dsa/assign-mice-holes/

⇱ Assign Holes to Mice - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Assign Holes to Mice

Last Updated : 14 Feb, 2026

We are given two arrays mices[] and holes[] of same size. The mices[] represents the positions of the mice on a straight line, while holes[] represents the positions of the holes. Each hole can accommodate exactly one mouse. A mouse can either stay in its current position, move one step to the right, or move one step to the left, and each move takes one minute. We have to assign each mouse to a distinct hole in such a way that the time taken by the last mouse to reach its hole is minimized.

Examples: 

Input : mices[] = [4, -4, 2] , holes[] = [4, 0, 5]
Output : 4
Explanation: Assign the mouse at position 4 to the hole at position 4, so the time taken is 0 minutes.
Assign the mouse at position āˆ’4 to the hole at position 0, so the time taken is 4 minutes.
Assign the mouse at position 2 to the hole at position 5, so the time taken is 3 minutes. Hence, the maximum time required by any mouse is 4 minutes

Input : mices[] = [1, 2], holes[] = [20, 10]
Output : 18

[Approach] Using Sorting - O(nlogn) Time and O(1) Space

The idea is to sort both arrays and then greedily assign each mouse to the corresponding hole in order. This ensures that every mouse is matched to its nearest possible hole, and the maximum time taken by any mouse is minimized.

Steps to solve the problem:

  • Sort both arrays mices and holes.
  • For each index i (0 to nāˆ’1), compute the absolute difference |mices[i] āˆ’ holes[i]|.
  • Keep track of the maximum difference encountered so far.
  • That maximum value is the final answer.

Output
4
Comment
Article Tags:
Article Tags: