Java Program to Find Common Elements in All Rows of a Given Matrix2 May 2025 | 4 min read Problem DescriptionA matrix consisting of 'm' rows and 'n' columns is shown to you. The purpose is to identify the items that are common to all rows of the matrix. The solution should efficiently return these common elements, considering both time and space complexity. ApproachTo solve this problem, we use a hash-based solution. We maintain a hash map (or hash table) to track the frequency of each element across the rows. The algorithm involves the following steps:
File Name: CommonElementsMatrix.java Output: Common elements in all rows: [1,8] ExplanationThe Java code begins by defining the findCommonElements() function that takes a 2D integer array (matrix) as input. First, the code checks if the matrix is empty or null to handle edge cases. A hash map (map) is initialized to track the frequency of elements from the matrix's rows. The first row's elements are added to the map with an initial count of 1. For each subsequent row, the code only updates the counts for elements that were present in all previous rows using a temporary map (TempMap). If an element's count matches the row index, it indicates that the element is present in all rows up to that point. Finally, the elements that maintain the count equivalent to the total number of rows are considered common and added to the result list. Complexity AnalysisInitialization of the hash map for the first row takes (O(n)), where (n) is the number of columns. Processing the rows takes (O(m times n)) where (m) is the number of rows, as each element in the matrix is checked once. The Final collection of common elements takes (O(k)), where (k) is the number of common elements. Thus, the overall time complexity is (O(m times n)). Space Complexity AnalysisThe space required for storing elements in the hash map is (O(n)) for the worst case (if all elements are unique in the first row). Additional space for storing temporary results during row processing. Hence, the space complexity is (O(n)). In the provided example, 1 and 8 are the only elements that appear in all rows of the matrix. The algorithm efficiently identifies 1 and 8 by updating counts row by row and filtering out non-common elements. Advantages of the Approach
Alternative Approaches
ConclusionThe hash-based approach used in this code is optimal for finding common elements across rows of a matrix, maintaining a balance between simplicity and efficiency. Next TopicJava Graph |
We request you to subscribe our newsletter for upcoming updates.

We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India