Skip to main content

Minimum Moves to Get a Peaceful Board - Solution & Explanation

MediumPremiumFree on FleetCodeArrayGreedySortingCounting Sort7 min read
Practice this problem

Problem Statement

Given a 2D array rooks of length n, where rooks[i] = [xi, yi] indicates the position of a rook on an n x n chess board. Your task is to move the rooks 1 cell at a time vertically or horizontally (to an adjacent cell) such that the board becomes peaceful.

A board is peaceful if there is exactly one rook in each row and each column.

Return the minimum number of moves required to get a peaceful board.

Note that at no point can there be two rooks in the same cell.

 

Example 1:

Input: rooks = [[0,0],[1,0],[1,1]]

Output: 3

Explanation:

Example 2:

Input: rooks = [[0,0],[0,1],[0,2],[0,3]]

Output: 6

Explanation:

 

Constraints:

  • 1 <= n == rooks.length <= 500
  • 0 <= xi, yi <= n - 1
  • The input is generated such that there are no 2 rooks in the same cell.

Approach Overview

Problem Overview: You are given positions of rooks on an n x n chessboard. The board is peaceful when no two rooks share the same row or column. Each move relocates a rook to another cell and costs the Manhattan distance between the old and new position. The goal is to compute the minimum total moves needed to reach a configuration where every row and every column contains exactly one rook.

Approach 1: Greedy with Sorting (O(n log n) time, O(n) space)

The key observation: row conflicts and column conflicts are independent. If you assign exactly one rook to each row and each column, the board automatically becomes peaceful. Extract all row indices and column indices from the rook positions. Sort both arrays. Then greedily match them to the target sequence 0..n-1. The minimal cost for rows is sum(|sortedRows[i] - i|), and the same logic applies to columns. Sorting ensures the smallest displacement pairing, a classic greedy trick used in sorting and median-alignment problems.

Approach 2: Greedy with Counting Sort Optimization (O(n) time, O(n) space)

The row and column values are bounded by the board size n, so you can avoid comparison sorting. Count how many rooks appear in each row and column using frequency arrays. Then simulate matching them with the target row indices 0..n-1. Track cumulative surplus or deficit while iterating through the rows and columns; each imbalance represents rooks that must move across indices. Summing these movements produces the same minimal cost as the sorted approach but runs in linear time. This relies on ideas from counting sort and greedy balancing.

Why the Greedy Pairing Works

Moving rooks across rows does not affect column conflicts and vice versa. By treating both dimensions independently, the problem reduces to aligning two sets of coordinates to consecutive indices. Sorting guarantees the minimal total absolute distance because pairing the smallest available value with the smallest target avoids cross movements. This property frequently appears in greedy algorithms that minimize total displacement.

Recommended for interviews: Start with the greedy insight that rows and columns can be optimized independently. Implement the sorting-based solution first because it is easy to reason about and runs in O(n log n). If the interviewer pushes for optimization, mention the counting-sort style linear solution that leverages the bounded index range.

Solution

We can sort all the cars by their x-coordinates, and then allocate the cars to each row in order, calculating the sum of distances from each car to its target position. Then, sort all the cars by their y-coordinates and use the same method to calculate the sum of distances from each car to its target position. Finally, the sum of these two distances is the answer.

The time complexity is O(n times log n), and the space complexity is O(log n). Here, n is the number of cars.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Greedy with SortingO(n log n)O(n)General solution; easiest to implement and explain in interviews
Greedy with Counting SortO(n)O(n)When row/column indices are bounded by n and you want a linear-time optimization

Video Solution

3189. Minimum Moves to Get a Peaceful Board - Week 3/5 Leetcode August ChallengeProgramming Live with Larry418 views views

Watch 1 more video solutions →

Frequently Asked Questions

Is Minimum Moves to Get a Peaceful Board easy or hard?
Minimum Moves to Get a Peaceful Board is generally classified as Medium difficulty. The tricky part is recognizing that row and column adjustments are independent and that sorting coordinates minimizes total movement. Once that insight is clear, the implementation is straightforward.
Minimum Moves to Get a Peaceful Board Python/Java solution
Most implementations extract row and column coordinates, sort them, and compute the sum of absolute differences from 0..n-1. The same greedy logic works across Python, Java, C++, Go, and TypeScript. The algorithm is short and typically fits within 10–20 lines of code.
How to solve Minimum Moves to Get a Peaceful Board in O(n)?
Use frequency arrays for rows and columns instead of sorting. Count how many rooks appear in each index, then iterate from 0 to n-1 while tracking surplus or deficit of rooks that must shift positions. The accumulated movement equals the minimal number of moves. Because the indices are bounded by n, this approach runs in linear time.
What is the best approach for Minimum Moves to Get a Peaceful Board?
The optimal strategy uses a greedy observation: rows and columns can be optimized independently. Collect all rook row indices and column indices, sort them, and match them with target positions 0..n-1. The total minimum moves equal the sum of absolute differences between the sorted coordinates and their target indices. This runs in O(n log n) time and O(n) space.
Is Minimum Moves to Get a Peaceful Board asked at Google/Amazon/Meta?
Greedy alignment and coordinate pairing problems frequently appear in interviews at companies like Google, Amazon, and Meta. While the exact problem ID may vary, the underlying idea—sorting coordinates and minimizing total absolute displacement—is a common interview pattern.
What data structure is used in Minimum Moves to Get a Peaceful Board?
The solution mainly uses arrays or lists to store row and column indices. Sorting or counting-frequency arrays are applied to align these indices with target positions. No complex structures like trees or graphs are required.
What is the time complexity of Minimum Moves to Get a Peaceful Board?
The standard solution runs in O(n log n) time because it sorts the row and column arrays. Space complexity is O(n) for storing the coordinates. With a counting-sort style frequency approach, the complexity can be improved to O(n) time while keeping O(n) space.

Ready to solve this problem?

Practice Minimum Moves to Get a Peaceful Board with our built-in code editor and test cases.

Practice on FleetCode