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 |
The palindrome partitioning of a string means dividing the given string in such a way that each substring formed from the given string is a palindrome in itself. In the palindrome partitioning problem in Java, we return the minimum of cuts required to make each of...
7 min read
The Java ArrayList class is essentially a resizable array, indicating that its size can change dynamically based on the entries we add or remove. It can be found in the java.util package. The syntax listed below makes it simple to give an ArrayList as an argument...
3 min read
Java, a versatile and widely used programming language, provides developers with various tools and features to create robust and efficient applications. Two essential concepts in Java programming that often confuse developers are constraints and annotations. While both play crucial roles in enhancing code readability and functionality,...
7 min read
Java is an extremely popular object-oriented programming language for creating different apps. Java's ability to write generic methods is one of its most potent features. Any technique that can be used with several object types is referred to as generic. Developers can design reusable code...
7 min read
A byte array is a fundamental data structure used to store binary data, making it a versatile tool for various tasks. One common use case is to store images in a byte array. In this section, we will explore how to convert a byte array into...
6 min read
A Java 'ByteBuffer' is a container for a fixed number of bytes. The size of a 'ByteBuffer' is the number of bytes it can hold, and it is determined when the 'ByteBuffer' is created. We can create a 'ByteBuffer' with a specific size in bytes using...
5 min read
In order to maintain the stability and dependability of the system, it's critical to handle mistakes and exceptions gracefully when developing software. The concepts of fail-safe and fail-fast are frequently used to handle errors. Both strategies have benefits and drawbacks, and knowing the distinctions between them...
3 min read
Future is an interface in the Java language that is a part of the java.util.concurrent package. It serves as a symbol for the output of an asynchronously computation. The interface offers ways to determine whether a computation has finished, to wait for it to finish, and...
4 min read
In Java, Singleton class is a class that controls the object creation. It means the singleton class allows us to create a single object of the class, at a time. It is usually used to control access to resources, such as database connections or sockets. It...
3 min read
Pairs are useful when we want two values to be returned from a method. For example, if we have a method that calculates the square root of a number and we want to print the number with its square root, we can use the Pair...
9 min read
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