Skip to main content

Maximum Consistent Columns in a Grid - Solution & Explanation

Practice this problem

Problem Statement

You are given a 2D integer array grid of size m x n, and an integer limit.

You may remove zero or more columns from the grid, but at least one column must remain. The relative order of the remaining columns must be preserved.

A grid is called consistent if for every row i, and for every pair of adjacent remaining columns a and b with a < b, the following holds: |grid[i][b] - grid[i][a]| <= limit.

Return the maximum number of columns that can remain such that the resulting grid is consistent.

 

Example 1:

Input: grid = [[-2,0,3]], limit = 2

Output: 2

Explanation:

  • Remove column 2 and keep columns 0 and 1, which gives |grid[0][1] − grid[0][0]| = |0 − (−2)| = 2 <= limit.
  • Thus, the maximum number of columns that can remain is 2.

Example 2:

Input: grid = [[1,-1,1],[2,2,2]], limit = 1

Output: 2

Explanation:

  • Remove column 1 and keep columns 0 and 2, which gives
    • |grid[0][2] − grid[0][0]| = |1 − 1| = 0 <= limit and
    • |grid[1][2] − grid[1][0]| = |2 − 2| = 0 <= limit.
  • Thus, the maximum number of columns that can remain is 2.

Example 3:

Input: grid = [[-5,5]], limit = 9

Output: 1

Explanation:

  • Remove either column 0 or column 1, since |grid[0][1] − grid[0][0]| = |5 − (−5)| = 10 > limit.
  • Thus, the maximum number of columns that can remain is 1.

 

Constraints:

  • 1 <= m == grid.length <= 250
  • 1 <= n == grid[i].length <= 250
  • -105 <= grid[i][j] <= 105
  • 0 <= limit <= 105​​​​​​​​​​​​​​​​

Approach Overview

Problem Overview: You need to find the maximum number of columns in a grid that can be treated as consistent under the problem’s row and column constraints. The core challenge is recognizing that columns with the same structural pattern behave identically, even when values are transformed or normalized.

Approach 1: Brute Force Column Comparison (Time: O(m * n2), Space: O(1))

The direct approach compares every pair of columns cell by cell. For each column, iterate through all remaining columns and verify whether their values satisfy the consistency rule across every row. This works for small grids because it does not require additional preprocessing or auxiliary structures. The downside is the quadratic comparison cost across columns, which becomes expensive when n is large.

Approach 2: Column Signature Hashing (Time: O(m * n), Space: O(n))

The optimized solution converts every column into a normalized signature and stores the frequency in a hash map. You iterate through each column, build a compact representation using its row values, and use hash lookup to count matching patterns in constant time. The key insight is that consistent columns share the same normalized structure, so repeated comparisons are unnecessary. This approach is the standard interview solution because it reduces repeated work and scales efficiently for dense grids.

Instead of comparing columns repeatedly, you preprocess each column once and group equivalent columns together. In most implementations, the signature is stored as a string, tuple, or bitmask depending on language constraints. Using a bitmask can further reduce memory overhead when the grid is binary. Problems built around pattern grouping often rely on hash maps, bit manipulation, and lightweight array traversal.

Approach 3: Bitmask Compression (Time: O(m * n), Space: O(n))

When the grid contains only binary values, each column can be compressed into an integer bitmask. As you iterate through rows, shift bits into the mask and use the final integer as the hash key. This avoids string construction costs and improves cache efficiency in lower-level languages like C++ and Java. The algorithmic complexity stays linear, but the implementation becomes more optimized for competitive programming constraints.

Recommended for interviews: Start with the brute force comparison to demonstrate that you understand the consistency condition. Then move to the hash-based grouping approach, since interviewers usually expect you to eliminate repeated column scans and reduce the complexity to O(m * n). If constraints are tight and the grid is binary, mentioning bitmask compression shows strong optimization awareness.

Solutions for this problem are being prepared.

Try solving it yourself

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Column ComparisonO(m * nΒ²)O(1)Small grids or when optimizing is unnecessary
Hash Map with Column SignaturesO(m * n)O(n)General case and interview-preferred solution
Bitmask CompressionO(m * n)O(n)Binary grids with tight memory or performance constraints

Video Solution

Leetcode 3989 | Maximum Consistent Columns in a Grid | Dynamic Programming | Weekly contest 510 β€’ CodeWithMeGuys β€’ 231 views views

Watch 4 more video solutions β†’

Frequently Asked Questions

Is Maximum Consistent Columns in a Grid easy or hard?
Maximum Consistent Columns in a Grid is generally classified as a hard problem because the main challenge is identifying the correct normalization strategy. The brute force solution is straightforward, but deriving the optimal hashing approach requires stronger pattern recognition skills.
Maximum Consistent Columns in a Grid Python/Java solution
Python solutions usually store column signatures as tuples or strings inside a dictionary. Java implementations commonly use HashMap<String, Integer> or integer bitmasks for binary grids. Both approaches achieve O(m * n) complexity.
How to solve Maximum Consistent Columns in a Grid in O(n)?
The standard optimized solution is effectively O(m * n) because every grid value must be read at least once. Build a normalized signature for each column and store it in a hash map. The highest frequency of any signature gives the maximum consistent columns.
What is the best approach for Maximum Consistent Columns in a Grid?
The best approach uses a hash map to group normalized column patterns. Each column is converted into a compact signature, and matching signatures are counted in O(1) average lookup time. This reduces the overall complexity to O(m * n).
Is Maximum Consistent Columns in a Grid asked at Google/Amazon/Meta?
Grid normalization and hash-based grouping problems appear frequently in interviews at Google, Amazon, and Meta. Variants involving row flips, column patterns, and binary matrix transformations are common in hard-level rounds.
What data structure is used in Maximum Consistent Columns in a Grid?
The primary data structure is a hash map that stores column signatures and their frequencies. Some optimized implementations also use bitmasks to compress binary column states into integers for faster lookup.
What is the time complexity of Maximum Consistent Columns in a Grid?
The optimal hashing solution runs in O(m * n) time, where m is the number of rows and n is the number of columns. Every cell is processed once while constructing column signatures. Space complexity is typically O(n) for storing frequencies.

Ready to solve this problem?

Practice Maximum Consistent Columns in a Grid with our built-in code editor and test cases.

Practice on FleetCode