VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-pair-rows-binary-matrix-maximum-bit-difference/

⇱ Find pair of rows in a binary matrix that has maximum bit difference - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find pair of rows in a binary matrix that has maximum bit difference

Last Updated : 23 Jul, 2025

Given a Binary Matrix. The task is to find the pair of row in the Binary matrix that has maximum bit difference Examples:

Input: mat[][] = {{1, 1, 1, 1},
 {1, 1, 0, 1},
 {0, 0, 0, 0}};
Output : (1, 3)
Bit difference between row numbers 1 and 3
is maximum with value 4. Bit difference 
between 1 and 2 is 1 and between 2 and 3
is 3.

Input: mat[][] = {{1 ,1 ,1 ,1 }
 {1 ,0, 1 ,1 }
 {0 ,1 ,0 ,0 }
 {0, 0 ,0 ,0 }} 
Output : (2, 3)
Bit difference between rows 2 and 3 is 
maximum which is 4.

Input: mat[][] = {{1 ,0 ,1 ,1 }
 {1 ,1 ,1 ,1 }
 {0 ,1 ,0 ,1 }
 {1, 0 ,0 ,0 }} 
Output : (1, 3) or (2 ,4 ) or (3 ,4 ) 
They all are having maximum bit difference
that is 3

Simple solution of this problem is that pick each row of binary matrix one -by -one and compute maximum bit difference with rest of the rows of matrix .at last return rows those have maximum bit difference . 

An Efficient solution using Trie Data Structure. Below is algorithm.

1). Create an empty Trie. Every node of Trie contains
 two children for 0 and 1 bits.
2). Insert First Row of Binary matrix into Trie 

3).Traverse rest of the rows of given Binary Matrix 
 a). For Each Row First we search maximum bit difference
 with rows that we insert before that in Trie and 
 count bit difference 
 b). For every search we update maximum bit_diff count
 if needed else not store pair of index that have
 maximum bit difference 
 c). At Last Print Pair 

Implementation:


Output
(1, 3)

Time Complexity:O(n)
Auxiliary Space: O(n)

Comment
Article Tags: