Java Program to Find the Minimum Distance Between Array Elements7 Jan 2025 | 6 min read Finding the minimum distance between two specified elements in an array is a common problem in computer science and data analysis. This task involves calculating the smallest distance between the first occurrences of two distinct elements within a given array. Such a problem is pertinent in applications that involve optimizing search algorithms, analyzing data patterns, and processing data structures efficiently. Input: Output: Minimum distance between 8 and 5 is 3. 1. Brute-Force MethodIterate through all pairs: For every pair of indices i and j in the array, check if the elements at these indices are equal to x and y. Calculate distance: When both elements are found, calculate the distance between their indices. Track minimum distance: Keep track of the minimum distance encountered during the traversal. File Name: MinimumDistanceBruteForce.java Output: Minimum distance between 5 and 3 is 1 Minimum distance between 8 and 5 is 2 Time Complexity: O(n2) - It is due to the nested loop, where each element is compared with every other element. Space Complexity: O(1) - No additional space is required apart from a few variables. Pros:
Cons:
2. Single-Pass with Index TrackingTrack indices: Traverse the array once while keeping track of the last seen indices of the two elements x and y. Calculate distance: Whenever both elements are encountered, compute the distance between their indices. Update minimum distance: Maintain the minimum distance found during the traversal. File Name: MinimumDistanceIndexTracking.java Output: Minimum distance between 5 and 3 is 1 Minimum distance between 8 and 5 is 2 Time Complexity: O(n) - Single pass through the array. Space Complexity: O(1) - Only a few variables are used for tracking indices and distance. Pros:
Cons:
3. Using HashMapStore indices in a HashMap: Traverse the array and store the indices of occurrences of both elements in a HashMap. Calculate distance: Once both elements have been encountered, calculate the distance using the stored indices. Track minimum distance: Update the minimum distance if the current distance is smaller. File Name: MinimumDistanceHashMap.java Output: Minimum distance between 5 and 3 is 1 Minimum distance between 8 and 5 is 2 Time Complexity: O(n) - Single traversal of the array. Space Complexity: O(n) - HashMap requires additional space proportional to the number of elements. Pros:
Cons:
ConclusionWhen solving the problem of finding the minimum distance between two specified elements in an array, there are three standard methods: the brute-force method, the single-pass method with index tracking, and the method using hash maps. Each has its own pros and cons, making them suitable for different scenarios based on performance and memory considerations. The choice of method depends on the specific requirements and constraints of the problem. For small arrays or simple applications, the brute-force method may suffice. However, for large datasets or performance-critical applications, the single-pass method with index tracking or the hash map method is more suitable due to their efficiency. Consider the available memory and the need for simplicity versus performance when selecting the best approach. |
DecimalFormat getMaximumIntegerDigits() method in Java
One of the java.text's built-in method is getMaximumIntegerDigits(). The Java class DecimalFomrat is used to determine the maximum number of digits that can be included in a number's integral portion. The portion of a number that appears before the decimal point (.) is known as the...
2 min read
Multiset Interface in Java
In Java, basic sets like HashSet belong to Java. Through its use of the tilde symbol, a util package, and the mathematical properties of a set, which are that its members are different and not repeatable. But there are some use cases like frequency table, which is...
7 min read
Java 10 var Keyword
In the ever-evolving landscape of programming languages, Java has consistently maintained its relevance by embracing modern programming paradigms while preserving its core principles. One such evolution is the introduction of the var keyword in Java 10. This innovative feature has sparked both excitement and debate within...
3 min read
Package getPackages() method in Java with Examples
The Java.lang.Package has getPackages() function. The caller's class loader defines the Packages, which can be obtained via the package class. An array of Package objects is the method's return value for the packages. Syntax: public boolean getPackages(String desiredVersion) Parameter: There are no parameters accepted...
2 min read
What is Is-A-Relationship in Java
? In object-oriented programming, one of the fundamental concepts is inheritance. In Java, inheritance allows us to create new classes based on existing ones, inheriting their properties and behaviors. The relationship between classes is often referred to as an "is-a" relationship. In this section, we will explore...
5 min read
Padding in Java
Java is a versatile programming language recognized for its flexibility in managing various data structures. A vital idea in Java, referred to as padding, performs a critical function in managing memory, aligning records successfully, and optimizing statistics processing. In this section, we will discuss what padding...
5 min read
Rotate A Matrix By 180 Degree in Java
In this section, we will discuss how to rotate a matrix by 180 degree in Java. In this problem, a square matrix is given, and we have to rotate it by 1800. Example 1: Input: 4 6 7 8 9 3 2 1 9 0 4 5 8 0 3 2 Output: 2 3...
10 min read
Java Program to Add two Complex Numbers
Complex numbers consist of two components - a real number and an imaginary number, which are distinct from each other. These numbers are widely used in mathematics, particularly in algebra. The standard format for a complex number is a + bi, where "a" represents the real...
4 min read
Java Optional Class orElseThrow() Method
The Optional class from Java is an explicit container object that holds an object of the non-null value which may or may not exist. It was first used in Java 8 to provide a more capable, costly, and more safe approach for handling values that...
4 min read
Java Email Validation
In designing forms, email plays an important role. The email can be of our username or login id. An email has its own structure, and before using it, we need to validate it. In Java, email validation is performed by using the regular expression. Email validation is...
3 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