Array Programs in Java

In this tutorial we are going to see some array program that are commonly asked in a Java interview. We will also be doing the complexity analysis of the programs.

Q1: Java Program to find the second most significant element in a sorted matrix.

In a sorted matrix, the rows and columns of the elements are placed in ascending order. We can navigate the matrix and note the largest and second-largest elements to determine the second-largest element. The second-largest element will have been stored when the traverse is complete.

The program uses a simple approach to find the second-largest element in a sorted matrix. It applies a nested loop to traverse the matrix in reverse order and compares each element with the largest and second-largest elements found so far. The program updates the largest and second-largest variables accordingly. Finally, it prints the value of the second largest element.

FileName: SecondLargestInSortedMatrix.java

Output:

```Second largest element in the sorted matrix:8
```

Complexity Analysis:

Time Complexity: O(rows * cols), where rows and cols are the dimensions of the matrix.

Space Complexity: O(1), as we use constant additional space.

Q2: Java Program to find the kth smallest element in a sorted matrix.

In a sorted matrix, elements are arranged in ascending order, both row-wise and column-wise. The task is to find the kth smallest element in the matrix.

The program uses a min-heap implemented with a PriorityQueue to find the kth smallest element in a sorted matrix. The "findKthSmallest" method initializes the minHeap and adds the elements from the first column. It then performs k-1 iterations, extracting the minimum element, finding its indices, and adding the next element from the same row to the minHeap. Finally, the method returns the kth smallest element. The main function showcases the method by providing a sample matrix and k value.

FileName: KthSmallestInSortedMatrix.java

Output:

```The 4th smallest element in the sorted matrix is:6
```

Complexity Analysis:

Time Complexity: The time complexity is O(k * log(rows)).

Space Complexity: The space complexity is O(rows) for storing the elements in the min-heap.

Q3: Java Program to remove duplicates from a sorted array.

In a sorted array, duplicate elements may occur consecutively. To put off duplicates from a looked-after array, we need to adjust the array in-area, making sure that each detail appears most effective as soon as. The Java program removes duplicates from a sorted array using the "RemoveDuplicates" class. The method "removeDuplicates" returns the new length of the modified array without duplicates. It checks if the array is empty, initializes "nextUnique" to 1, and traverses the array starting from the second element. It assigns unique elements to the position of "nextUnique" and increments it. After the loop, "nextUnique" represents the new length. The "main" function showcases the method by printing the modified array.

FileName: RemoveDuplicates.java

Output:

```Modified Array: 1 2 3 4 5
```

Complexity Analysis:

Time Complexity is O(n), where n is the array's element count.

Space complexity is O(1) since the array is modified directly without additional data structures.

Q4: Java Program to find the frequency of each word in a string array.

We shall calculate the frequency of each word in a string array using a Java program. In a list of strings, we want to know how frequently each word appears. To calculate the frequency of each word in a string array, the program employs a hash map. A simple approach separates each string into words, and the number of each word is then saved in the hash map. After initializing a blank HashMap, the program loops through each string in the array. It determines if a word is present in the HashMap for each one it encounters. If it does, the frequency increases; if not, it is set to 1, and the word is added to the hash map. Finally, the program prints the word-frequency pairs stored in the HashMap. The approach efficiently tracks and counts the occurrences of each word, allowing for accurate frequency analysis of the words in the string array.

FileName: WordFrequency.java

Output:

```Word: Java, Frequency: 3
Word: world, Frequency: 1
Word: Hello, Frequency: 2
Word: powerful, Frequency: 1
Word: is, Frequency: 2
Word: great, Frequency: 1
```

Complexity Analysis:

The time complexity is O(n*m), Wherein n represents the number of strings within the array and m is the huge common sort of phrase in every string.

The space complexity of the program is O(n), where n is the total wide variety of words inside the array.

Q5: Java Program to find the missing number in a sorted array of consecutive integers.

Using the binary search method, we locate the missing integer in a sorted array of succeeding integers. The first detail's index is low, and the remaining is high. We set up whether or not the missing integer is on the left or proper side of the array by computing the expected fee for the middle element, which ought to be the same as the primary element plus the center index. The operation is repeated until there is only one element left in the search space, at which point we update low or high as necessary. The missing number will be the expected value at the index low.

FileName: MissingNumberInSortedArray.java

Output:

```Missing number: 5
```

Complexity Analysis:

Time Complexity: The binary search approach has a time complexity of O(log n), where n is the size of the array

Space Complexity: The program has a space complexity of O(1), only using a few variables to track the low, high, and mid indices and the expected value.

Q6: Java Program to find the element that appears only once in an array.

The technique used to find the element that appears most effective as soon as in an array is primarily based on the XOR operation. By XORing all the factors within the array, the factors that seem a fair quantity of instances will cancel out, leaving only the detail that appears best once. To enforce this approach, we initialize a variable 'unique' to zero. Then, we iterate thru each detail inside the array and XOR it with the 'particular' variable. The result is stored back in 'unique.' At the end of the iteration, 'unique' will hold the element's value that appears only once.

FileName: FindUniqueElement.java

Output:

```The element that appears only once: 4
```

Complexity Analysis:

The time complexity of this technique is O(n), wherein n is the length of the array.

The area complexity is O(1) because we simplest use an unmarried variable to keep the result.

Q7: Java Program to check if an array is a palindrome.

To check if an array is a palindrome, we will use a -pointer method wherein one pointer starts evolving at the start of the array and the alternative on the quit. The elements are as compared to those suggestions, and we move them closer and nearer collectively until they meet within the center. We conclude that the array is not a palindrome if the elements at any point at the pointers are not equal. Otherwise, if the loop completes without finding any unequal elements, then the array is a palindrome. The two-pointer approach allows us to efficiently check for palindromicity by eliminating the need for additional space.

FileName: PalindromeArray.java

Output:

```The array is palindrome.
```

Complexity Analysis:

The time complexity of the above approach is O(n), where n is the length of the array.

The space complexity is O(1) as we are not using any extra space.

Q8: Java Program to shuffle the elements of an array.

To shuffle the elements of an array, we use the Fisher-Yates shuffle algorithm is commonly used. The procedure ensures that each array's item is randomly permuted. Starting with the final entry in the array, the process iterates through the array in reverse order to get started. Each time, the current element is added to the range of the remaining unshrunk elements to create a random index. The element at the current index is then swapped with the element at the randomly generated index. The swapping continues until the first element is reached, resulting in a shuffled array with elements in random order.

FileName: ShuffleArray.java

Output:

```Original array:
1 2 3 4 5
Shuffled array:
2 3 5 4 1
```

Complexity Analysis:

The time complexity of this technique is O(N), wherein N is the size of the array.

The space complexity is O(1) since we use a consistent quantity of extra area for the random wide variety.

Q9: Java Program to check if two matrices are orthogonal.

To examine if two matrices are orthogonal, we evaluate the dot manufactured from corresponding rows or columns from the matrices. The matrices are said to be orthogonal if the dot product is 0 for all pairs. The algorithm iterates thru the rows or columns, then calculates the dot product and returns false if any dot product is non-0. It then checks for appropriate dimensions. If all dot products are zero, it returns true to indicate that the matrices are orthogonal.

FileName: OrthogonalMatrices.java

Output:

```The matrices are not orthogonal.
```

Complexity Analysis:

The time complexity of this technique is O(n), in which n is the range of rows or columns in the matrices.

The space complexity is O(1), as no additional data structures are used.

Q10: Java Program to find the maximum element in a two-dimensional array.

We initialize the variable'max' with the smallest value conceivable given the data type of the array elements to determine the greatest element in a two-dimensional array. The next step is to loop separately via the array's rows and factors. Every element is compared to the modern fee of "max," and if the detail is more, "max" is up to date. The maximum element in the two-dimensional array will be contained in'max' once all items have been iterated through. By comparing each element to the current maximum value, the method enables us to quickly determine the maximum element.

FileName: MaximumElementIn2DArray.java

Output:

```The maximum element in the array is:9
```

Complexity Analysis:

The time complexity of this approach is O(n * m), where n is the number of rows and m is the number of columns in the two-dimensional array.

The space complexity is O(1) when you consider that we aren't the usage of any extra area that grows with the entered size.

Q11: Java Program to find the sum of each diagonal in a matrix.

To find the sum of each diagonal in a matrix, we iterate via the elements and calculate the diagonal index for every element by summing its row and column indices. We then add the element's value to the corresponding diagonal sum in an array. After processing all elements, the array will contain the sum of each diagonal.

FileName: DiagonalSum.java

Output:

```Sum of each diagonal:
1
6
15
14
9
```

Complexity Analysis:

The approach has a time complexity of O(m * n), where m is the number of rows and n is the number of columns in the matrix.

The space complexity is O(m + n), as we must store the diagonal sums in an array.

Q12: Java Program to find the element with the maximum frequency in an array.

We use a HashMap to record the frequency of each element in the array to locate the element with the highest frequency. The element with the highest frequency can be recognized via looping through the array and updating the frequency within the hash map. Then, by comparing the frequency counts in the HashMap, we identify the element with the maximum frequency. The approach allows us to efficiently find the element with the highest frequency in the array.

FileName: MaximumFrequencyElement.java

Output:

```Element with maximum frequency:3
```

Complexity Analysis:

The time complexity of this technique is O(n), where n is the size of the array.

The area complexity is O(n) because HashMap can save up to n unique elements inside the worst case.

Q13: Java Program to rotate a two-dimensional array clockwise.

To rotate a two-dimensional array clockwise, we can follow a two-step approach: transposing the array and reversing each row. Firstly we iterate via the array and switch each detail at function (i,j) with the detail at the role (j, i), then successfully transpose the array. After, we iterate through each row of the transposed array and reverse it by swapping the elements from the start and end of the row until they meet in the middle. The process rotates the array clockwise.

FileName: RotateArray.java

Output:

```Original Matrix:
1 2 3
4 5 6
7 8 9

Rotated Matrix:
7 4 1
8 5 2
9 6 3
```

Complexity Analysis:

The time complexity of this approach is O(N^2), where N is the size of the array.

The space complexity is O(1) as we carry out the rotation in-area without using any additional statistics systems.

Q14: Java Program to sort a two-dimensional array by a specific column.

We construct a custom comparator that compares rows based on the required column to sort a two-dimensional array by that particular column. The Arrays.sort() method is then called with the custom comparator as an argument. The sorting algorithm employs a comparator to compare rows according to the selected column and arrange them correctly. We can quickly sort the two-dimensional array by a particular column using the method.

FileName: SortByColumn.java

Output:

```Original Matrix:
13 12 11
6 5 4
19 18 17

Sorted Matrix by Column 1:
6 5 4
13 12 11
19 18 17
```

Complexity Analysis:

The time complexity of this approach is O(n log n), where n is the number of rows in the matrix.

The space complexity is O(1) since the sorting is done in place.

Q15: Java Program to perform matrix exponentiation to efficiently compute Fibonacci numbers.

We might also describe the Fibonacci sequence as a matrix and calculate matrix multiplication to speedily compute the Fibonacci numbers using matrix exponentiation. The manner includes creating a transformation matrix that represents the Fibonacci series, utilizing matrix multiplication and exponentiation strategies, and then elevating the matrix to the necessary strength using the powerMatrix approach. By deleting the Fibonacci number from the following matrix, we can also quickly calculate Fibonacci numbers.

FileName: FibonacciMatrix.java

Output:

```Fibonacci number at position 10: 55
```

Complexity Analysis:

The time complexity of this approach is O(log n) since we perform matrix multiplication using the exponentiation by squaring technique.

The space complexity is O(1) since we only need a fixed-size matrix and a few additional variables.

Q16: Given an array of integers, rearrange the array such that all even numbers appear before all odd numbers.

Note: maintaining the relative order is not relevant for this problem.

We can use a two-pointer technique to reorder an array so that all even numbers appear before all odd numbers While the right pointer begins at the end and advances backward, the left pointer moves ahead from the beginning. The elements pointed by the left and right pointers are examined at each step, and swaps are made as needed. All even numbers will be arranged before odd numbers by the time the loop is complete.

FileName: RearrangeArray.java

Output:

```Original Array:
1 2 3 4 5 6 7 8 9
Rearranged Array:
8 2 6 4 5 3 7 1 9
```

Complexity Analysis:

The time complexity of this approach is O(n), where n is the number of elements in the array.

The space complexity is O(1) as we perform the rearrangement in place without using any additional data structures.

Q17: Java Program to Find the Smallest Missing Positive Number in an Unsorted Array.

We can rearrange the array by assigning each positive integer to its appropriate index to discover the smallest missing positive number in an unsorted array. You can accomplish this by looping through the array and switching each element with a positive integer with the one at the desired index. The array is iterated once more to locate the first index where an element no longer corresponds to the required value after the rearrangement. The index corresponds to the smallest missing positive number. If all elements match their desired values, the smallest missing positive number is the next positive integer after the array size.

FileName: SmallestMissingPositiveNumber.java

Output:

```Smallest Missing Positive Number: 2
```

Complexity Analysis:

The approach ensures a time complexity of O(n) and a space complexity of O(1) as we perform the rearrangement and search in place without additional data structures.

Q18: Java Program to Find the Intersection of Two Arrays

The best approach to finding the intersection of two arrays is to use a HashSet data structure. We create a HashSet and add all elements from one array to it. Then, we iterate through the second array and check if each element exists in the HashSet. If it does, we add it to the result ArrayList and remove it from the HashSet to avoid duplicates.

FileName: IntersectionOfArrays.java

Output:

```Intersection: [2]
```

Complexity Analysis:

The time complexity of this approach is O(n), where n is the size of the larger array.

The space complexity is O(m), where m is the size of the HashSet.

Q19: Java Program to find the longest subarray with an equal number of 0s and 1s.

Utilizing the prefix sum method, we can determine the longest subarray that contains an equal number of 0s and 1s. We can calculate the running sum while traversing the array by assigning a value of 1 for every 1 and -1 for every 0. When the running sum reaches zero, the amount of 0s and 1s we have seen thus far is equal. To find the longest subarray, we store the running sum in a HashMap and its corresponding index. If the same running sum appears again, we update the maximum length by subtracting the stored index from the current index. By keeping track of the maximum length throughout the iteration, we can find the longest subarray with equal 0s and 1s.

FileName: LongestSubarrayWithEqualZerosAndOnes.java

Output:

```Length of the longest subarray with equal 0s and 1s:6
```

Complexity Analysis:

The time complexity of this approach is O(n) since we iterate through the array once.

The space complexity is O(n) as we store the running sum and its corresponding index in the HashMap.

Q20: Java Program to find the maximum product of two integers in an array.

To find the maximum product of two integers in an array, we iterate through the array and keep track of the maximum and second maximum elements. We initialize max1 and max2 to the smallest possible integer values. Then for each element, we compare it with max1 and update max2 and max1 accordingly. After iterating through the array, the maximum product is the product of max1 and max2, as max1 will hold the largest element and max2 will hold the second largest element.

FileName: MaximumProduct.java

Output:

```Maximum Product: 20
```

Complexity Analysis:

The time complexity of this approach is O(n), where n is the size of the array.

The space complexity is O(1) since we only use constant extra space to store the maximum and second maximum elements.

Q21: Java Program to find the smallest subarray length with a sum greater than a given value.

To find the smallest subarray length with a sum greater than a given value, we can utilize the sliding window technique. The approach involves maintaining a window that expands and contracts while calculating the current sum. We start with an empty window and gradually expand it by adding elements from the right end. If the current sum exceeds the given value, we update the minimum length of the subarray. Then, until the current total is less than or equal to the specified value, we contract the window from the left end by eliminating items. Until we reach the end of the array, we keep doing this.

FileName: SmallestSubarray.java

Output:

```Smallest Subarray Length: 3
```

Complexity Analysis:

The time complexity of this approach is O(n), where n is the size of the array.

The space complexity is O(1) since we only use constant extra space to store variables.

Q22: Java Program to find the triplet with the smallest sum in an array.

We can take help of three variables (an integer array of size three will also do the work) and using a loop we can find the minimum elements present in the given array. We will be looking of the minimum elements as we have to find the smallest sum.

FileName: SmallestTripletSum.java

Output:

```The Triplet with the smallest sum is: {-4, -3, -2}
```

Complexity Analysis:

The time complexity of this approach is O(n) since we are only using one loop in the program.

The space complexity is O(1), as we are not using any extra space that grows with the input size.