Array Programs for Interviews 1727455838
Array Programs for Interviews 1727455838
ni
Pa
ra
Why This Guide is Unique
Professional Coding Standards: Follow industry standards with clean and modular code.
d
Step-by-Step Explanations: Clear breakdowns of inputs, processing, and outputs to understand
actions and their purpose.
en
Comprehensive Comments: Fully commented code for beginners, with quick logic insights for
advanced users.
Multiple Solutions: Alternative approaches for complex problems to enhance problem-solving skills.
ar
Focus on Edge Cases: Covers tricky scenarios like empty arrays and null values, vital for interviews.
Real-World Coding Techniques: Utilizes modular functions and efficient data structures for interview
m
readiness.
JavaDoc Documentation: Well-documented methods and clear comments for easy understanding.
Ready to Start?
A
Open your IDE, work through the problems, and build your confidence to crack
technical interviews.
Let’s Begin.
This guide isn’t just a document; it’s your secret weapon for
mastering array programming and getting hired.
1. How do you Remove the Duplicates from an Array Using HashSet
2. How do you delete duplicates from a sorted array using the index in Java?
3. How do you find the duplicate elements in an array using index in Java?
4. How do you find the duplicate elements in an array using a HashSet in Java?
5. How do you find the sum of all the elements in an array in Java?
6. How do you separately print the even and odd numbers in a given array in Java?
ni
7. How do you compare two arrays in Java without using any inbuilt methods?
Pa
9. How do you find the missing element in an array in Java?
10. How do you find the maximum and minimum elements in a given array in Java?
ra
11. How do you search for a given element in an array in Java?
15. How do you receive input from the user and save it into an array in Java?
ar
17. How do you find the number of elements in a given array in Java?
m
20. How do you swap the first and last elements of an array in Java?
21. How do you multiply the corresponding elements of two arrays in Java?
22. How do you find the first occurrence of a given element in an array without using a
specific algorithm in Java?
23. How do you find the first occurrence of a given element in a sorted array using an
algorithm in Java?
24. How do you sort an array in ascending order using built-in functions in Java?
25. How do you sort an array in descending order using built-in functions in Java?
26. How do you join two arrays in Java? Provide all possible solutions.
27. How do you calculate the average of an array in Java using a simple loop, Java 8 streams,
and the Google Guava library?
ni
28. How do you shift all zero elements to the right side of the array in Java?
Pa
29. How do you check the equality of two arrays in Java?
31. How do you reverse an array in Java without using any built-in method and without using
ra
any extra array?
32. How do you find the second largest element in an array in Java?
d
33. How do you find the second smallest element from an array in Java?
en
34. How do you find all possible pairs of elements in an array in Java?
35. How do you find the first repeating element in an array in Java?
ar
36. How do you find the first occurrence and last occurrence of an element in an array in
Java?
m
37. How do you find the common elements in multiple arrays in Java?
A
38. How do you rearrange the positive and negative elements of an array in Java?
39. How do you find the second smallest element in an array without sorting in Java?
42. How do you count all possible pairs from an array in Java?
1. Question: How do you Remove the Duplicates from an
Array Using HashSet
Key Concept:
In this problem, you're asked to remove duplicate elements from an array. Using a HashSet is
an efficient approach because it automatically handles duplicate elements. A HashSet in Java
only allows unique elements, so when we add elements from the array into the HashSet, it
will automatically discard any duplicates.
ni
Solution:
Pa
package array;
import java.util.HashSet;
import java.util.Scanner;
ra
import java.util.Set;
import java.util.Arrays;
d
public class RemoveDuplicatesFromArray {
en
int index = 0;
ni
resultArray[index++] = num;
Pa
// Step 4: Output the result
}
en
Explanation of Steps:
ar
1. Input Handling: First, the program takes input for the array size and its elements.
m
2. Using HashSet: All elements of the array are added to the HashSet. Since a HashSet
does not allow duplicate values, any duplicates in the array are automatically
A
removed.
4. Edge Case Handling: If the array contains only one element or no duplicates, the
program still works correctly.
Input/Output Examples:
• Example 1:
▪ Elements: 1, 2, 2, 3, 4, 4
ni
o Input: Enter the number of elements: 5
Pa
o Output: Array after removing duplicates: [10, 20, 30, 40, 50]
o
ra
Input: Enter the number of elements: 4
▪ Elements: 5, 5, 5, 5
d
o Output: Array after removing duplicates: [5]
en
Edge Cases:
1. Empty Array: If the array has no elements, the program should gracefully handle it by
ar
2. Single Element Array: If the array has only one element, the result is the same as the
m
Key Concept:
When the array is sorted, the duplicates will always be next to each other. This allows us to
traverse the array using a two-pointer technique. One pointer (index) will keep track of the
position where the unique element should be placed, while the other pointer will scan
through the array to check for duplicates.
Solution:
package array;
import java.util.Scanner;
import java.util.Arrays;
ni
public class RemoveDuplicatesSortedArray {
Pa
public static void main(String[] args) {
}
A
if (n == 0 || n == 1) {
return;
}
// Step 3: Use index to keep track of the unique elements
// Traverse the array and compare each element with the previous one
ni
index++; // Move the index forward
Pa
}
scanner.close();
m
}
A
Explanation of Steps:
1. Input Handling: The program takes input for the size and elements of a sorted array.
2. Handling Special Cases: If the array has only one element or is empty, no duplicates
need to be removed.
3. Two-pointer Approach:
o The first pointer (index) tracks where to store unique elements.
o The second pointer (i) scans through the array, comparing each element with
the previous one.
o When a new unique element is found, it's placed at the current index
position.
ni
5. Edge Case Handling: If there are no duplicates or the array has one element, the
output remains unchanged.
Pa
Input/Output Examples:
• Example 1:
o
ra
Input: Enter the number of elements: 7
▪ Elements: 1, 1, 2, 2, 3, 3, 4
d
o Output: Array after removing duplicates: [1, 2, 3, 4]
en
o Output: Array after removing duplicates: [10, 20, 30, 40, 50]
m
▪ Element: 42
1. Empty Array: If the input array is empty, the program should return an empty array.
2. Array with One Element: If the input array has only one element, the output is the
same as the input because there are no duplicates.
ni
array using index in Java?
Key Concept:
Pa
In this problem, we need to identify the duplicate elements in an array. By using a two-loop
approach, we can compare each element of the array with the subsequent elements and
check for duplicates. This approach is simple but can be optimized using more advanced
ra
methods, like sorting or hashing.
Solution:
d
en
package array;
import java.util.Scanner;
ar
ni
// Outer loop to pick each element
Pa
for (int i = 0; i < n; i++) {
hasDuplicates = true;
ar
}
A
if (!hasDuplicates) {
Explanation of Steps:
1. Input Handling: The program takes input for the array size and its elements.
2. Two-Loop Comparison:
ni
o The outer loop picks one element at a time.
Pa
o The inner loop compares the current element with the subsequent elements
in the array.
o When a duplicate is found, it's printed, and the inner loop breaks to avoid
ra
printing the same duplicate again.
3. Edge Case Handling: If no duplicates are found, a message stating "No duplicates
d
found" is displayed.
Input/Output Examples:
en
• Example 1:
ar
▪ Elements: 1, 2, 2, 3, 4, 4
m
Edge Cases:
1. Empty Array: If the array is empty, no duplicates exist, and the program will print "No
duplicates found."
2. Single Element Array: If the array has only one element, the program will also print
"No duplicates found" as there are no duplicates.
ni
Time Complexity:
Pa
• The time complexity of this solution is O(n²) due to the nested loops, where n is the
number of elements in the array. For large arrays, this could be inefficient, but it is
simple and easy to understand for smaller inputs.
ra
4. Question: How do you find the duplicate elements in an
d
array using a HashSet in Java?
en
Key Concept:
ar
In this problem, we use a HashSet to efficiently find duplicates in an array. A HashSet only
allows unique elements. As we iterate through the array, if an element is already present in
the HashSet, we know it's a duplicate. This approach is more efficient than using nested
m
Solution:
A
package array;
import java.util.HashSet;
import java.util.Scanner;
ni
System.out.println("Enter " + n + " elements of the array: ");
Pa
for (int i = 0; i < n; i++) {
}
ra
// Step 2: Use HashSet to find duplicates
d
HashSet<Integer> elements = new HashSet<>(); // Set to store unique elements
en
if (!elements.add(arr[i])) {
duplicates.add(arr[i]);
A
if (duplicates.isEmpty()) {
scanner.close();
ni
}
Pa
Explanation of Steps:
1. Input Handling: The program takes input for the array size and elements.
2. Using HashSet:
ra
o The HashSet named elements is used to store unique elements.
If the element is already present in the HashSet (i.e., add() returns false), it is
d
o
3. Output Handling:
Input/Output Examples:
• Example 1:
A
▪ Elements: 1, 2, 3, 4, 4, 5, 2
▪ Elements: 3, 3, 7, 7, 7, 9
ni
Edge Cases:
1. Empty Array: If the array is empty, the program should print "No duplicates found."
Pa
2. Single Element Array: If the array has only one element, the program will print "No
duplicates found" as there are no duplicates.
ra
Time Complexity:
• The time complexity of this solution is O(n) where n is the number of elements in the
d
array. This is because HashSet operations like add() take constant time, making this
approach much more efficient than using nested loops.
en
in an array in Java?
m
Key Concept:
In this problem, we need to calculate the sum of all elements in an array. The approach is
A
straightforward: initialize a variable to store the sum and then iterate through the array,
adding each element to the sum.
Solution:
package array;
import java.util.Scanner;
public class SumOfArrayElements {
ni
int[] arr = new int[n]; // Create an array of the given size
Pa
System.out.println("Enter " + n + " elements of the array: ");
int sum = 0;
// Step 3: Traverse the array and add each element to the sum
ar
}
A
scanner.close();
}
}
Explanation of Steps:
1. Input Handling: The program first asks the user to input the number of elements in
the array and then takes the array elements.
2. Sum Calculation:
ni
o A for loop is used to iterate through the array and accumulate the sum of the
elements.
Pa
3. Output the Sum: After the loop, the sum is printed.
Input/Output Examples:
• Example 1:
ra
o Input: Enter the number of elements: 5
d
▪ Elements: 1, 2, 3, 4, 5
en
• Example 2:
ar
▪ Element: 42
1. Empty Array: If the array is empty (n = 0), the sum is 0. In this case, the program can
handle the empty input without crashing.
2. Negative Elements: If the array contains negative numbers, they are correctly
included in the sum.
Time Complexity:
• The time complexity of this solution is O(n), where n is the number of elements in
ni
the array. This is because the array is traversed once.
Pa
6. Question: How do you separately print the even and
odd numbers in a given array in Java?
ra
Key Concept:
d
In this problem, we need to classify the elements of an array into even and odd numbers
and print them separately. An even number is divisible by 2, while an odd number is not. The
en
solution involves iterating through the array and checking whether each element is even or
odd using the modulus operator (%).
ar
Solution:
package array;
m
import java.util.Scanner;
A
ni
// Step 2: Print the even numbers
Pa
System.out.println("Even numbers in the array are: ");
if (arr[i] % 2 == 0) {
ra
System.out.print(arr[i] + " ");
d
}
en
if (arr[i] % 2 != 0) {
Explanation of Steps:
1. Input Handling: The program takes the array size and the array elements as input.
ni
o A for loop iterates through the array.
Pa
o For each element, we check if the number is divisible by 2 (arr[i] % 2 == 0). If
true, the number is even; otherwise, it is odd.
3. Printing Even and Odd Numbers: Two separate loops are used to print even and odd
ra
numbers.
Input/Output Examples:
d
• Example 1:
en
▪ Elements: 1, 2, 3, 4, 5, 6
ar
o Output:
o Output:
o Output:
ni
Edge Cases:
1. Empty Array: If the array is empty, no even or odd numbers exist, and the program
Pa
will print nothing.
2. Single Element Array: If the array has only one element, the program will print that
element in either the even or odd list based on its value.
ra
Time Complexity:
d
• The time complexity of this solution is O(n), where n is the number of elements in
the array. This is because the array is traversed once for even numbers and once for
en
odd numbers.
ar
3. If the lengths are the same, compare each element of one array with the
corresponding element in the other array.
4. If all elements match, the arrays are considered equal; otherwise, they are different.
Solution:
package array;
import java.util.Scanner;
ni
// Step 1: Accept input for the first array
Pa
System.out.println("Enter the number of elements in the first array: ");
}
ar
}
// Step 3: Compare the arrays
if (n1 != n2) {
areEqual = false;
} else {
ni
// Compare elements one by one
Pa
for (int i = 0; i < n1; i++) {
if (arr1[i] != arr2[i]) {
areEqual = false;
ra
break; // No need to compare further if a mismatch is found
d
}
en
}
ar
if (areEqual) {
m
} else {
scanner.close();
}
Explanation of Steps:
2. Length Comparison:
o If the lengths of the two arrays are not the same, the arrays are not equal.
ni
3. Element-by-Element Comparison:
Pa
o If the lengths are the same, we compare each corresponding element of the
two arrays.
Input/Output Examples:
• Example 1:
ar
o Input:
m
▪ First array: 1, 2, 3, 4, 5
▪ Second array: 1, 2, 3, 4, 5
A
o Input:
▪ First array: 1, 2, 3
▪ Second array: 1, 2, 3, 4
o Output: Arrays are not equal.
o Input:
ni
Edge Cases:
1. Empty Arrays: If both arrays are empty, they are considered equal.
Pa
2. Single Element Arrays: If both arrays have only one element, they are equal if that
single element is the same. ra
Time Complexity:
• The time complexity of this solution is O(n), where n is the number of elements in
d
the arrays. This is because we compare each element once.
Key Concept: Java provides several predefined methods to compare two arrays, including:
1. Arrays.equals(): This method compares two arrays for equality. It returns true if both
m
arrays have the same length and contain the same elements in the same order.
4. Arrays.mismatch(): Returns the index of the first mismatch between two arrays.
package array;
import java.util.Arrays;
import java.util.Scanner;
ni
public static void main(String[] args) {
Pa
Scanner scanner = new Scanner(System.in);
if (areEqual) {
ni
} else {
Pa
System.out.println("Arrays are not equal.");
Explanation of Steps:
ar
1. Input Handling: We take input for two arrays (first and second) from the user.
2. Using Arrays.equals() Method: This method is used to compare both arrays. It returns
m
true if:
3. Output the Result: Based on the result of the Arrays.equals() method, the program
prints whether the arrays are equal or not.
Input/Output Examples:
• Example 1:
o Input:
▪ First array: 1, 2, 3, 4, 5
▪ Second array: 1, 2, 3, 4, 5
ni
• Example 2 (Different Lengths):
o Input:
Pa
▪ First array: 1, 2, 3
▪ Second array: 1, 2, 3, 4
o
m
The Arrays.mismatch() method returns the index of the first differing element between two
arrays. If no mismatch is found, it returns -1.
package array;
import java.util.Arrays;
import java.util.Scanner;
ni
int n1 = scanner.nextInt(); // Size of the first array
Pa
int[] arr1 = new int[n1]; // Create the first array
if (mismatchIndex == -1) {
} else {
ni
// Closing scanner to avoid memory leaks
Pa
scanner.close();
}
ra
Input/Output Examples:
d
• Example 1:
en
o Input:
▪ First array: 1, 2, 3, 4, 5
ar
▪ Second array: 1, 2, 3, 4, 5
o Input:
A
ni
Key Concept:
Pa
(nested arrays), as it compares the content of each array and any sub-arrays
recursively.
When to Use:
d
• When comparing nested arrays (multi-dimensional arrays) or arrays of objects that
en
package array;
m
import java.util.Arrays;
if (areEqual) {
} else {
ni
}
Pa
}
Explanation of Steps:
ra
1. Multi-Dimensional Arrays: The program defines two 2D arrays (array1 and array2).
d
2. Using Arrays.deepEquals(): This method compares the elements of the arrays deeply,
including any nested arrays.
en
3. Output: The result is printed depending on whether the arrays are deeply equal.
Input/Output Examples:
ar
• Example 1:
m
o Input: array1 = { {1, 2, 3}, {4, 5, 6} } and array2 = { {1, 2, 3}, {4, 5, 6} }
o Input: array1 = { {1, 2, 3}, {4, 5, 6} } and array2 = { {1, 2, 3}, {4, 0, 6} }
Key Concept:
o It returns:
ni
▪ 0 if both arrays are lexicographically equal.
Pa
▪ A negative number if the first array is lexicographically smaller.
When to Use:
ra
• When you need to compare arrays in a lexicographical order, especially for sorting
purposes.
d
Code Example for Arrays.compare():
en
package array;
import java.util.Arrays;
ar
} else {
ni
}
Pa
}
Explanation of Steps:
ra
1. Array Declaration: The program defines two one-dimensional arrays (array1 and
array2).
d
2. Using Arrays.compare(): This method compares the arrays element by element,
en
3. Result Interpretation:
ar
Input/Output Examples:
• Example 1:
• Example 2:
o Input: array1 = {10, 20, 30} and array2 = {10, 20, 30}
• Example 3:
ni
Summary of Solutions:
Pa
1. Arrays.equals(): Compares two one-dimensional arrays element by element for
equality.
2. Arrays.mismatch(): Returns the index of the first differing element or -1 if the arrays
are identical.
ra
3. Arrays.deepEquals(): Compares multi-dimensional arrays or arrays that contain
arrays.
d
4. Arrays.compare(): Compares arrays lexicographically and returns a value based on
en
These predefined methods provide different ways to compare arrays based on your specific
ar
needs: simple equality, lexicographical comparison, or deep comparison for nested arrays.
m
Key Concept:
In this problem, you are typically given an array containing n-1 elements, and these
elements are from a sequence of n consecutive numbers. One element is missing from the
sequence, and the task is to find that missing element.
There are several approaches to solve this problem, but a commonly used and efficient
solution involves calculating the expected sum of all numbers in the sequence and then
subtracting the actual sum of the array elements. The difference will give the missing
number.
Approach:
ni
Sum=n×(n+1)2\text{Sum} = \frac{n \times (n+1)}{2}Sum=2n×(n+1)
Pa
o Iterate through the array and calculate the sum of its elements.
o
ra
Subtract the sum of the array elements from the expected sum of n
consecutive numbers. The result will be the missing element.
d
Solution:
en
package array;
import java.util.Scanner;
ar
int n = scanner.nextInt() + 1; // The array should have n-1 elements, but we want n for
sum calculation
int[] arr = new int[n - 1]; // Create an array of size n-1 (one element is missing)
ni
// Step 2: Calculate the expected sum of the first n natural numbers
Pa
int expectedSum = n * (n + 1) / 2;
int actualSum = 0;
ra
for (int i = 0; i < n - 1; i++) {
d
actualSum += arr[i];
en
}
ar
scanner.close();
}
}
Explanation of Steps:
1. Input Handling: The program first takes input for the size of the array (n-1 elements).
The number n is calculated by adding 1 to the size of the array.
2. Expected Sum Calculation: We calculate the expected sum of the first n natural
numbers using the formula n * (n + 1) / 2.
ni
3. Actual Sum Calculation: The program iterates through the array and calculates the
sum of the given elements.
Pa
4. Finding the Missing Element: The missing element is found by subtracting the actual
sum from the expected sum.
• Example 1:
d
o Input: Enter 4 elements (from numbers 1 to 5): 1, 2, 3, 5
en
• Example 2:
ar
Edge Cases:
A
1. Small Arrays: For arrays with only two elements (from numbers 1 to 3), the solution
should work correctly.
2. Missing First or Last Element: The solution works even if the missing number is the
first or last in the sequence.
Time Complexity:
• The time complexity of this solution is O(n), where n is the number of elements in
the array. This is because we calculate the sum of the elements by iterating through
the array once.
ni
Key Concept:
Pa
To find both the maximum and minimum elements in an array, we can iterate through the
array once and keep track of both the maximum and minimum values as we compare each
element. This approach ensures an optimal time complexity of O(n) since we traverse the
array only once.
ra
Solution:
d
package array;
en
import java.util.Scanner;
if (n <= 0) {
return;
}
ni
// Step 2: Initialize variables for max and min with the first element
Pa
int max = arr[0];
}
ar
}
A
Explanation of Steps:
1. Input Handling: The program takes input for the array size and the array elements. It
ni
also checks if the array has at least one element (to avoid errors).
2. Initialization: We initialize two variables max and min with the first element of the
Pa
array.
3. Array Traversal: The program iterates through the array starting from the second
element:
ra
o If the current element is greater than max, we update max.
Input/Output Examples:
ar
• Example 1:
▪ Elements: 3, 1, 4, 1, 5
o Output:
A
• Example 2:
▪ Element: 42
ni
o Output:
Pa
▪ Minimum element in the array is: 42
Edge Cases:
ra
1. Single Element Array: If the array has only one element, both the maximum and
minimum will be that element.
d
2. Negative Numbers: The solution works for arrays that contain negative numbers as
en
well.
Time Complexity:
ar
• The time complexity is O(n) because we traverse the array only once, where n is the
number of elements in the array.
m
an array in Java?
Key Concept:
To search for an element in an array, we can use linear search, which is the simplest
method. In linear search, we traverse the array element by element, comparing each
element with the target value. If the target value is found, we return the index at which it is
located; otherwise, we return that the element is not found.
Solution:
package array;
import java.util.Scanner;
ni
// Step 1: Accept input for the array
Pa
System.out.println("Enter the number of elements in the array: ");
}
ar
if (arr[i] == target) {
if (index != -1) {
ni
} else {
Pa
System.out.println("Element " + target + " not found in the array.");
Explanation of Steps:
ar
1. Input Handling: The program first takes input for the array size and its elements.
2. Target Input: The program prompts the user to enter the element they want to
m
3. Linear Search:
A
o We initialize an index variable to -1, which indicates that the element is not
found.
o We traverse the array using a for loop and compare each element with the
target.
o If the target element is found, we update the index to the current position
and exit the loop using break.
4. Result Output: If the element is found, we print its index; otherwise, we print a
message indicating that the element is not found.
Input/Output Examples:
• Example 1:
o Input:
ni
▪ Elements: 10, 20, 30, 40, 50
▪ Target: 30
Pa
o Output: Element 30 found at index: 2
• Example 2: ra
o Input:
▪ Target: 25
o Input:
m
▪ Elements: 3, 6, 9
▪ Target: 3
Edge Cases:
1. Empty Array: If the array has no elements, the program should immediately print
that the element is not found.
2. Target Not Present: The program correctly handles the case where the target
element is not present in the array.
3. Single Element Array: If the array has only one element, the search will either find
the target or return that it's not found.
Time Complexity:
• The time complexity of linear search is O(n), where n is the number of elements in
the array, because we may need to check every element in the worst case.
ni
Pa
12. Question: How do you print the elements of an array in
Java?
Key Concept:
ra
To print the elements of an array in Java, we can either use a loop to iterate through the
array and print each element, or use the Arrays.toString() method for single-dimensional
d
arrays or Arrays.deepToString() for multi-dimensional arrays.
en
package array;
ar
import java.util.Scanner;
m
ni
for (int i = 0; i < n; i++) {
Pa
System.out.print(arr[i] + " "); // Print each element followed by a space
Explanation of Steps:
ar
1. Input Handling: The program takes input for the array size and its elements.
2. Using a Loop: A for loop is used to iterate through the array and print each element,
m
followed by a space.
Input/Output Examples:
A
• Example 1:
o Input:
▪ Elements: 1, 2, 3, 4, 5
o Input:
ni
Solution 2: Using Arrays.toString() Method
Pa
If you want a more concise way to print the array elements, Java provides the
Arrays.toString() method that prints the array in a readable format.
package array;
ra
import java.util.Arrays;
import java.util.Scanner;
d
public class PrintArrayUsingToString {
en
scanner.close();
Explanation:
ni
• Arrays.toString(arr) converts the array into a string format that looks like [1, 2, 3, 4, 5]
and prints it all at once.
Pa
Input/Output Examples:
• Example 1:
o Input:
ra
▪ Enter the number of elements: 5
d
▪ Elements: 1, 2, 3, 4, 5
en
• Example 2:
ar
o Input:
o Output: The elements in the array are: [10, 20, 30, 40]
Solution 3: Printing a Multi-Dimensional Array Using Arrays.deepToString()
If you are working with multi-dimensional arrays, you can use the Arrays.deepToString()
method to print the array.
package array;
import java.util.Arrays;
ni
public static void main(String[] args) {
Pa
// Define a 2D array
}
ar
Explanation:
method recursively converts each sub-array into a string and outputs them.
Input/Output Example:
A
• Output: The elements in the 2D array are: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Time Complexity:
• The time complexity of all the solutions is O(n), where n is the number of elements in
the array, as we need to iterate through the array to print its contents.
13. Question: How do you sort the elements in an array
using built-in functions in Java?
Key Concept:
To sort an array in Java, you can use the Arrays.sort() method from the java.util.Arrays class.
This method sorts the array in ascending order by default. If you need to sort the array in
descending order, you can combine Arrays.sort() with a custom comparator or use
Collections.reverseOrder() for certain types like Integer[].
ni
Solution 1: Sorting in Ascending Order Using Arrays.sort()
Pa
Steps:
import java.util.Arrays;
import java.util.Scanner;
ar
Arrays.sort(arr);
ni
System.out.println("The array sorted in ascending order is: " +
Arrays.toString(arr));
Pa
// Close the scanner to avoid memory leaks
scanner.close();
}
ra
}
d
Explanation:
en
Input/Output Example:
m
• Input:
o Elements: 5, 1, 3, 2, 4
• Output:
Steps:
ni
package array;
Pa
import java.util.Arrays;
import java.util.Collections; ra
import java.util.Scanner;
Integer[] arr = new Integer[n]; // Create an Integer array of the given size (non-
A
primitive)
}
// Step 2: Sort the array in descending order
Arrays.sort(arr, Collections.reverseOrder());
ni
scanner.close();
Pa
}
Explanation:
•
ra
We use Integer[] instead of int[] because Collections.reverseOrder() requires an
object array.
d
• Arrays.sort(arr, Collections.reverseOrder()) sorts the array in descending order.
en
Input/Output Example:
• Input:
ar
o Elements: 5, 1, 3, 2, 4
m
• Output:
A
package array;
import java.util.Arrays;
ni
public static void main(String[] args) {
Pa
// Define a 2D array
int[][] arr = {
{3, 2, 1},
ra
{6, 5, 4},
d
{9, 8, 7}
en
};
Arrays.sort(arr[i]);
m
}
A
System.out.println(Arrays.toString(row));
}
}
Explanation:
Input/Output Example:
• Output:
ni
• The 2D array with sorted rows is:
Pa
[1, 2, 3]
[4, 5, 6] ra
[7, 8, 9]
Time Complexity:
d
• The time complexity of Arrays.sort() is O(n log n) where n is the number of elements
en
in the array. This is due to the Timsort algorithm used internally, which is highly
efficient for sorting.
ar
m
A
14. Question: How do you reverse an array in Java
using Java Collections?
Key Concept:
In Java, you can reverse an array using the Collections.reverse() method. However, since
Collections.reverse() works only with Lists, you'll need to first convert the array into a List,
perform the reversal, and if needed, convert the list back to an array.
ni
Steps:
Pa
1. Convert the array to a List using Arrays.asList().
2. Use Collections.reverse() to reverse the List.
3. (Optional) Convert the List back to an array if required.
ra
Solution:
d
package array;
en
import java.util.Arrays;
import java.util.Collections;
ar
import java.util.List;
import java.util.Scanner;
m
ni
// Step 2: Convert the array to a List
Pa
// Step 3: Reverse the list using Collections.reverse()
Collections.reverse(list);
ra
// Step 4: Print the reversed array (which is now a reversed list)
scanner.close();
}
ar
}
m
Explanation of Steps:
1. Input Handling: The program first takes input for the array size and elements.
A
• Input:
o Enter the number of elements: 5
o Elements: 1, 2, 3, 4, 5
• Output:
o The reversed array is: [5, 4, 3, 2, 1]
ni
If you need the reversed list back as an array, you can convert it using the toArray() method.
Pa
Code Example:
package array; ra
import java.util.Arrays;
import java.util.Collections;
d
import java.util.List;
en
import java.util.Scanner;
Integer[] arr = new Integer[n]; // Create an Integer array of the given size (for
Collections.reverse)
ni
Collections.reverse(list);
Pa
// Step 4: Convert the List back to an array
scanner.close();
}
ar
• Converting Back to Array: After reversing the list, we convert the List back into an
A
Input/Output Example:
• Input:
o Enter the number of elements: 5
o Elements: 1, 2, 3, 4, 5
o
• Output:
o The reversed array is: [5, 4, 3, 2, 1]
Time Complexity:
15. Question: How do you receive input from the user and
ni
save it into an array in Java?
Pa
Key Concept:
In Java, you can use the Scanner class to receive input from the user. For storing multiple
inputs into an array, you can:
ra
1. Create an array with a specified size.
2. Use a loop to repeatedly prompt the user for input and store each value in the array.
d
en
Solution:
package array;
ar
import java.util.Scanner;
// Step 2: Prompt the user to enter the number of elements for the array
// Step 4: Loop through to get 'n' inputs from the user and store them in the
array
ni
for (int i = 0; i < n; i++) {
Pa
}
scanner.close();
m
}
A
Explanation of Steps:
Input/Output Example:
• Input:
o Enter the number of elements you want to store in the array: 5
ni
o Enter 5 elements: 10 20 30 40 50
• Output:
Pa
o You entered the following elements: 10 20 30 40 50
Edge Cases: ra
1. Empty Array: If the user enters 0 for the number of elements, no input is stored in
the array.
d
2. Non-integer Input: The program will throw an error if non-integer input is provided,
as it expects integer input for both the size and elements.
en
Time Complexity:
ar
• The time complexity for inputting and printing the array is O(n), where n is the
number of elements.
m
A
16. Question: How do you reverse the elements of an array
in Java?
Key Concept:
Reversing an array means rearranging its elements so that the first element becomes the
last, the second element becomes the second-to-last, and so on. This can be done by
swapping elements from the start and end, moving towards the middle.
ni
Solution (Reversing the Array Manually by Swapping:
Pa
package array;
import java.util.Scanner;
// Step 2: Prompt the user to enter the number of elements in the array
ar
// Step 4: Loop through to get 'n' inputs from the user and store them in the
array
ni
arr[start] = arr[end];
Pa
arr[end] = temp;
}
ar
scanner.close();
m
}
A
Explanation:
o The for loop now handles both the initialization (start = 0, end = n - 1), the
condition (start < end), and the update (start++ and end--) in a single
structure. This makes the loop more concise and easier to read.
Input/Output Example:
• Input:
o Enter 5 elements: 1 2 3 4 5
• Output:
ni
Edge Cases:
Pa
1. Single Element Array: If the array contains only one element, reversing it will result in
the same array. ra
2. Empty Array: If the array is empty (size 0), the program will print nothing as there are
no elements to reverse.
d
Time Complexity:
en
• The time complexity for reversing the array is O(n), where n is the number of
elements in the array. This is because we swap elements only once, and we iterate
over half the array.
ar
m
Key Concept:
In Java, the size of an array (i.e., the number of elements in the array) can be easily found
using the array's built-in property length. This property returns the total number of elements
in the array, which is useful when you need to iterate through or access the size of the array.
Solution:
package array;
import java.util.Scanner;
ni
// Step 1: Create a Scanner object to receive input
Pa
// Step 2: Prompt the user to enter the number of elements in the array
// Step 4: Loop through to get 'n' inputs from the user and store them in the
array
ar
scanner.close();
Explanation of Steps:
1. Input Handling: The user is prompted to enter the size of the array and its elements.
ni
2. Array Length: The number of elements in the array is accessed using the arr.length
property, which returns the total number of elements stored in the array.
Pa
3. Output: The number of elements is printed to the console.
Input/Output Example:
• Input:
ra
o Enter the number of elements you want to store in the array: 5
d
o Enter 5 elements: 10, 20, 30, 40, 50
en
• Output:
Key Points:
m
1. arr.length Property: This property gives you the total number of elements in the
A
array. It's a simple and efficient way to get the size of an array in Java.
2. Time Complexity: Accessing the length property is done in constant time O(1).
18. Question: How do you perform a right rotation of an
array by n positions in Java?
Key Concept:
In a right rotation of an array, elements are shifted to the right by a specified number of
positions. The elements that are shifted beyond the end of the array wrap around to the
beginning. For example, rotating the array [1, 2, 3, 4, 5] by 2 positions would result in [4, 5,
1, 2, 3].
ni
Approach:
Pa
1. Modular Arithmetic: Use modulo (%) to calculate the effective number of rotations
since rotating the array by its length results in the same array. Therefore, rotating by
n is equivalent to rotating by n % array.length.
ra
2. Reversing Parts of the Array: You can achieve the rotation in an optimal way by using
the reversal algorithm:
d
o Reverse the whole array.
en
package array;
m
import java.util.Scanner;
A
arr[end] = temp;
start++;
end--;
ni
// Function to right rotate the array by n positions
Pa
public static void rightRotate(int[] arr, int n) {
n = n % length;
reverse(arr, 0, n - 1);
}
public static void main(String[] args) {
// Step 2: Prompt the user to enter the number of elements in the array
ni
int n = scanner.nextInt(); // Size of the array
Pa
int[] arr = new int[n];
// Step 4: Loop through to get 'n' inputs from the user and store them in the
array
ra
System.out.println("Enter " + n + " elements:");
d
for (int i = 0; i < n; i++) {
en
}
ar
rightRotate(arr, rotations);
scanner.close();
ni
Explanation of Steps:
Pa
1. Reverse Helper Function: The reverse() function is used to reverse a portion of the
array between two indices (start and end).
3. Main Program: The program prompts the user for input, rotates the array by the
m
Input/Output Example:
A
• Input:
o Enter 5 elements: 1 2 3 4 5
o
• Output:
Edge Cases:
2. n Larger than Array Length: The modulo operation (n % length) handles cases where
n is greater than the length of the array.
ni
3. Empty Array: If the array is empty, the program should handle it without errors.
Time Complexity:
Pa
• The time complexity of this approach is O(n), where n is the number of elements in
the array. This is because each element is swapped only a constant number of times
during the reversal operations.
ra
19. Question: How do you perform a left rotation of an
d
array by n positions in Java?
en
Key Concept:
ar
In a left rotation of an array, elements are shifted to the left by a specified number of
positions. The elements that are shifted beyond the start of the array wrap around to the
end. For example, rotating the array [1, 2, 3, 4, 5] by 2 positions to the left would result in [3,
m
4, 5, 1, 2].
Approach:
A
1. Modular Arithmetic: Use modulo (%) to calculate the effective number of rotations,
because rotating by the length of the array brings the array back to its original state.
Therefore, rotating by n is equivalent to rotating by n % array.length.
2. Reversing Parts of the Array: The same reversal algorithm used for right rotation can
be used for left rotation, but with different parts of the array:
o Reverse the first n elements.
package array;
import java.util.Scanner;
ni
// Helper function to reverse part of the array
Pa
public static void reverse(int[] arr, int start, int end) {
start++;
end--;
ar
}
m
if (length == 0 || n <= 0) {
return;
}
n = n % length;
reverse(arr, 0, n - 1);
ni
reverse(arr, n, length - 1);
Pa
// Step 4: Reverse the whole array
}
ra
public static void main(String[] args) {
d
// Step 1: Create a Scanner object to receive input
en
// Step 2: Prompt the user to enter the number of elements in the array
ar
// Step 4: Loop through to get 'n' inputs from the user and store them in the
array
ni
leftRotate(arr, rotations);
Pa
// Step 7: Print the rotated array
scanner.close();
ar
}
m
Explanation of Steps:
A
1. Reverse Helper Function: The reverse() function is used to reverse a portion of the
array between two indices (start and end).
3. Main Program: The program prompts the user for input, rotates the array by the
specified number of positions, and prints the rotated array.
Input/Output Example:
ni
• Input:
Pa
o Enter 5 elements: 1 2 3 4 5
2. n Larger than Array Length: The modulo operation (n % length) handles cases where
ar
3. Empty Array: If the array is empty, the program should handle it without errors.
m
Time Complexity:
• The time complexity of this approach is O(n), where n is the number of elements in
A
the array. This is because each element is swapped only a constant number of times
during the reversal operations.
20. Question: How do you swap the first and last elements
of an array in Java?
Key Concept:
ni
3. Assigning the value stored in the temporary variable to the last position.
Pa
Solution: Swapping First and Last Elements of an Array
package array;
import java.util.Scanner;
ra
public class SwapFirstLast {
// Step 2: Prompt the user to enter the number of elements in the array
");
// Step 4: Loop through to get 'n' inputs from the user and store them in the
array
// Step 5: Swap the first and last elements if the array has more than 1 element
if (n > 1) {
ni
arr[0] = arr[n - 1]; // Assign the last element to the first position
Pa
arr[n - 1] = temp; // Assign the temp (first element) to the last position
}
ar
scanner.close();
m
}
A
Explanation of Steps:
1. Input Handling: The program takes input for the array size and its elements.
2. Swapping Logic:
o The value stored in temp (initially the first element) is assigned to the last
position.
3. Output: The modified array is printed after swapping the first and last elements.
Input/Output Example:
• Input:
ni
o Enter the number of elements you want to store in the array: 5
o Enter 5 elements: 10 20 30 40 50
Pa
• Output:
1. Single Element Array: If the array contains only one element, the array remains
d
unchanged, as there's nothing to swap.
en
2. Empty Array: If the array is empty (n = 0), no swap is performed, and the program
handles this without errors.
ar
Time Complexity:
m
• The time complexity of this operation is O(1) because swapping the first and last
elements involves only constant-time operations (accessing and assigning two array
elements).
A
Solution: Swap First and Last Elements Without Using a Third Variable
package array;
import java.util.Scanner;
ni
// Step 1: Create a Scanner object to receive input
Pa
// Step 2: Prompt the user to enter the number of elements in the array
// Step 4: Loop through to get 'n' inputs from the user and store them in the
array
ar
// Step 5: Swap the first and last elements without using a third variable (if
array has more than 1 element)
if (n > 1) {
arr[0] = arr[0] + arr[n - 1]; // Step 1: arr[0] becomes the sum of arr[0] and
arr[n - 1]
arr[n - 1] = arr[0] - arr[n - 1]; // Step 2: arr[n - 1] becomes the original
arr[0]
arr[0] = arr[0] - arr[n - 1]; // Step 3: arr[0] becomes the original arr[n - 1]
System.out.println("The array after swapping first and last elements is: ");
ni
for (int i = 0; i < n; i++) {
Pa
}
scanner.close();
ra
}
d
}
en
Explanation:
ar
1. No Temporary Variable:
▪ arr[0] = arr[0] + arr[n - 1]; — The first element (arr[0]) becomes the
A
▪ arr[n - 1] = arr[0] - arr[n - 1]; — The last element (arr[n - 1]) becomes
the original first element by subtracting the new arr[0] value (sum)
from the last element.
▪ arr[0] = arr[0] - arr[n - 1]; — The first element (arr[0]) becomes the
original last element by subtracting the new arr[n - 1] value from the
sum.
2. No Extra Space: This approach avoids using a third variable, as the swap is performed
directly within the array using basic arithmetic.
Input/Output Example:
• Input:
o Enter 5 elements: 10 20 30 40 50
ni
• Output:
Pa
Edge Cases:
1. Single Element Array: If the array contains only one element, the array remains
unchanged.
ra
2. Empty Array: If the array is empty, no operations are performed.
d
Time Complexity:
en
• The time complexity remains O(1) since only constant-time arithmetic operations are
performed to swap the elements.
ar
Key Concept:
A
2. Loop through the arrays and multiply the elements at the same index in both arrays.
package array;
import java.util.Scanner;
ni
// Step 1: Create a Scanner object to receive input
Pa
// Step 2: Prompt the user to enter the size of the arrays
ni
}
Pa
// Step 8: Print the resulting array
scanner.close();
ar
}
m
Explanation of Steps:
A
1. Input Handling:
o The program first takes input for the size of both arrays.
2. Multiplying Elements:
3. Output: The program prints the result array containing the products of the
corresponding elements from both arrays.
Input/Output Example:
• Input:
ni
o Enter 3 elements for the first array: 1 2 3
Pa
• Output:
1. Empty Arrays: If the arrays are of size 0, the program will print nothing as there's no
d
element to multiply.
en
2. Single Element Arrays: If the arrays contain only one element, the result will simply
be the product of the two elements.
ar
Time Complexity:
• The time complexity is O(n), where n is the number of elements in each array, since
we need to iterate through all the elements once.
m
A
22. Question: How do you find the first occurrence of a
given element in an array without using a specific
algorithm in Java?
Key Concept:
To find the first occurrence of a given element in an array, you can simply iterate through the
array and check each element. Once you find the element, return its index. If the element is
ni
not found in the array, return an indicator such as -1.
Pa
package array;
import java.util.Scanner;
// Step 2: Prompt the user to enter the number of elements in the array
ar
ni
for (int i = 0; i < n; i++) {
Pa
if (arr[i] == target) {
if (index != -1) {
ar
} else {
scanner.close();
}
Explanation of Steps:
1. Input Handling:
o The program first takes the size of the array and its elements as input from
the user.
o Then, the program prompts the user for the target element to search for in
the array.
ni
o A simple for loop is used to iterate through the array.
Pa
o If the current element matches the target element, the index is stored, and
the loop breaks to stop further searching.
• Input:
o Enter 5 elements: 10 20 30 40 50
• Output:
A
o Enter 5 elements: 10 20 30 40 50
Edge Cases:
1. Element Not Found: If the target element is not in the array, the program returns -1
to indicate that the element was not found.
2. Empty Array: If the array is empty (n = 0), the program should immediately print that
the element is not found.
ni
3. Single Element Array: If the array has only one element, the search will either find
Pa
the target or return that it is not found.
Time Complexity:
• The time complexity of this approach is O(n), where n is the number of elements in
ra
the array. This is because, in the worst case, you might have to check every element
of the array.
d
en
Java?
Key Concept:
m
If the array is sorted, you can use binary search to efficiently find the first occurrence of the
given element. In a sorted array, binary search helps reduce the search space by half in each
A
iteration, making it much faster than a linear search. However, the regular binary search
algorithm only finds an occurrence of the element, not necessarily the first occurrence. To
find the first occurrence, you can modify the binary search algorithm.
Approach:
2. When you find the target element, continue searching on the left to check if it's the
first occurrence.
3. Return the index of the first occurrence or -1 if the element is not found.
ni
Solution: Binary Search for First Occurrence
Pa
package array;
import java.util.Scanner; ra
public class FirstOccurrenceBinarySearch {
int mid = low + (high - low) / 2; // Calculate mid point to avoid overflow
if (arr[mid] == target) {
A
result = mid; // Found target, but continue to search left for first occurrence
} else {
low = mid + 1; // Search in the right half
ni
// Step 1: Create a Scanner object to receive input
Pa
Scanner scanner = new Scanner(System.in);
// Step 2: Prompt the user to enter the number of elements in the array
if (index != -1) {
} else {
ni
System.out.println("Element " + target + " not found in the array.");
Pa
// Close the scanner to avoid memory leaks
scanner.close();
}
ra
}
d
Explanation of Steps:
en
1. Input Handling:
o The program takes input for the size and elements of a sorted array.
ar
o The final value of result will be the index of the first occurrence.
3. Output: The program prints the index of the first occurrence of the target element or
notifies the user that the element was not found.
Input/Output Example:
• Input:
• Output:
ni
o First occurrence of element 2 is at index: 1
Pa
o Enter the number of elements in the sorted array: 6
o
ra
Enter the element to find the first occurrence: 7
• Output:
d
o Element 7 not found in the array.
en
Edge Cases:
1. Element Not Found: If the target element is not present in the array, the algorithm
ar
returns -1.
2. Single Element Array: If the array has only one element, the search will either find
m
3. All Elements the Same: If all elements in the array are the same as the target, the
A
Time Complexity:
• The time complexity of this modified binary search is O(log n), where n is the number
of elements in the array. This is because binary search reduces the search space by
half in each iteration.
Space Complexity:
• The space complexity is O(1), as we are using a constant amount of extra space
(variables for pointers and the result).
you can use the predefined method Arrays.binarySearch() from the java.util.Arrays class to
search for an element in a sorted array. However, by default, Arrays.binarySearch() returns
the index of any occurrence of the target element in the array, not necessarily the first
ni
occurrence.
Pa
1. Use Arrays.binarySearch() to locate an occurrence of the element.
2. If the element is found, manually check the previous elements to find the first
occurrence.
ra
Approach Using Arrays.binarySearch():
d
1. Use Arrays.binarySearch() to find an occurrence of the element.
en
2. If found, check the elements to the left to find the first occurrence.
3. Return the index of the first occurrence or -1 if the element is not found.
ar
package array;
m
import java.util.Arrays;
A
import java.util.Scanner;
ni
System.out.println("Enter " + n + " sorted elements:");
Pa
for (int i = 0; i < n; i++) {
}
ra
// Step 5: Input the element to search for
d
System.out.println("Enter the element to find the first occurrence: ");
en
if (index >= 0) {
A
index--; // Move to the left if the previous element is also the target
scanner.close();
ni
}
Pa
Explanation of Steps:
1. Input Handling:
o The program takes input for the size and elements of the sorted array, as well
ra
as the target element.
2. Using Arrays.binarySearch():
d
o The predefined method Arrays.binarySearch(arr, target) is used to find an
en
occurrence of the target element in the sorted array. It returns the index of
the target if found, or a negative value if the target is not found.
ar
4. Output: The program prints the index of the first occurrence, or notifies the user if
A
Input/Output Example:
• Input:
• Output:
ni
o Enter the element to find the first occurrence: 7
• Output:
Pa
o Element 7 not found in the array.
Edge Cases:
ra
1. Element Not Found: If binarySearch returns a negative value, the element is not
found in the array.
d
2. Single Element Array: If the array has only one element, the search will either find
en
3. All Elements the Same: If all elements in the array are the same as the target, the
algorithm will return the first index.
ar
Time Complexity:
m
the target, so the total complexity in the worst case is O(log n + k).
Space Complexity:
• The space complexity is O(1) because no extra space is used beyond the input array
and a few variables.
24. Question: How do you sort an array in ascending
order using built-in functions in Java?
Key Concept:
To sort an array in ascending order in Java, you can use the Arrays.sort() method from the
java.util.Arrays class. This method efficiently sorts the array using the Timsort algorithm,
which has a time complexity of O(n log n) in the worst case.
ni
Approach:
Pa
2. Use Arrays.sort() to sort the array in ascending order.
package array;
d
import java.util.Arrays;
en
import java.util.Scanner;
// Step 2: Prompt the user to enter the number of elements in the array
ni
// Step 5: Sort the array in ascending order using Arrays.sort()
Pa
Arrays.sort(arr);
scanner.close();
}
m
}
A
Explanation of Steps:
1. Input Handling: The program takes input for the size and elements of the array from
the user.
3. Output: The program prints the sorted array after applying the Arrays.sort() method.
Input/Output Example:
• Input:
ni
o Enter 5 elements: 50 20 40 10 30
• Output:
Pa
o The array sorted in ascending order is: 10 20 30 40 50
Edge Cases: ra
1. Empty Array: If the array has zero elements, the program will print nothing as there
are no elements to sort.
d
2. Single Element Array: If the array has only one element, it will remain unchanged
after sorting.
en
3. Array Already Sorted: If the array is already sorted, the method will recognize that no
changes are needed.
ar
Time Complexity:
• The time complexity of Arrays.sort() is O(n log n), where n is the number of elements
m
in the array. This is because the Arrays.sort() method uses the Timsort algorithm,
which is highly efficient for real-world data.
A
Space Complexity:
• The space complexity is O(n) due to the use of temporary arrays in the internal
Timsort implementation for merging sorted runs.
25. Question: How do you sort an array in descending
order using built-in functions in Java?
Key Concept:
To sort an array in descending order, you can use the Arrays.sort() method in combination
with Collections.reverseOrder(). However, Collections.reverseOrder() works only with non-
primitive arrays (like Integer[], not int[]). Therefore, you must first convert the array to an
Integer[] if you're working with primitive int arrays.
ni
Approach:
Pa
1. Convert the array from int[] to Integer[] (if necessary).
package array;
import java.util.Arrays;
ar
import java.util.Collections;
m
import java.util.Scanner;
// Step 2: Prompt the user to enter the number of elements in the array
System.out.println("Enter the number of elements you want to store in the array:
");
ni
System.out.println("Enter " + n + " elements:");
Pa
arr[i] = scanner.nextInt(); // Receive input and store in the array
}
ra
// Step 5: Sort the array in descending order using Arrays.sort() with
Collections.reverseOrder()
d
Arrays.sort(arr, Collections.reverseOrder());
en
}
A
scanner.close();
}
Explanation of Steps:
1. Input Handling: The program takes input for the size and elements of the array.
ni
3. Output: The program prints the sorted array after sorting it in descending order.
Pa
Input/Output Example:
• Input:
Edge Cases:
ar
1. Empty Array: If the array has zero elements, nothing will be printed, as there are no
elements to sort.
m
2. Single Element Array: If the array has only one element, it will remain unchanged
after sorting.
A
3. Array Already Sorted in Descending Order: If the array is already sorted in descending
order, the method will recognize that no changes are needed.
Time Complexity:
• The space complexity is O(n) due to the use of temporary arrays in the internal
sorting process of Arrays.sort() and the additional non-primitive array required.
ni
2. Sort the array in ascending order using Arrays.sort() and then reverse it manually if
you wish to avoid using Collections.reverseOrder().
Pa
26. Question: How do you join two arrays in Java? Provide
all possible solutions.
ra
Key Concept:
d
In Java, joining (or concatenating) two arrays can be done in multiple ways depending on
your approach. This involves combining the elements of two arrays into a single larger array.
en
2. Using System.arraycopy()
3. Using Arrays.copyOf()
A
package array;
import java.util.Scanner;
ni
int[] arr1 = {1, 2, 3};
Pa
int[] arr2 = {4, 5, 6};
// Step 3: Copy elements of the first array into the joined array
d
for (int i = 0; i < arr1.length; i++) {
en
joinedArray[i] = arr1[i];
}
ar
// Step 4: Copy elements of the second array into the joined array
joinedArray[arr1.length + i] = arr2[i];
A
System.out.println("Joined Array:");
Explanation:
• First, a new array joinedArray is created with a length equal to the sum of the two
arrays.
ni
• The elements of the first array are copied using a loop, followed by the elements of
the second array.
Pa
Output:
• Joined Array: 1 2 3 4 5 6 ra
Solution 2: Using System.arraycopy()
d
The System.arraycopy() method allows you to copy elements from one array to another
efficiently.
en
package array;
ar
import java.util.Scanner;
System.out.println("Joined Array:");
ni
System.out.print(joinedArray[i] + " ");
Pa
}
}
ra
Explanation:
d
• System.arraycopy(src, srcPos, dest, destPos, length) copies elements from src starting
at srcPos to dest starting at destPos.
en
Output:
ar
• Joined Array: 1 2 3 4 5 6
m
A
Solution 3: Using Arrays.copyOf()
Arrays.copyOf() can be used to copy an array, and you can use it twice to create a joined
array.
package array;
import java.util.Arrays;
ni
public static void main(String[] args) {
Pa
// Step 1: Create two arrays to join
System.out.println("Joined Array:");
m
}
Explanation:
Output:
• Joined Array: 1 2 3 4 5 6
ni
Solution 4: Using Streams (Java 8 and above)
Pa
If you're using Java 8 or later, you can use streams to concatenate arrays.
package array; ra
import java.util.Arrays;
import java.util.stream.IntStream;
d
public class JoinArraysUsingStreams {
en
System.out.println("Joined Array:");
Explanation:
ni
• IntStream.concat() concatenates two streams.
Pa
• toArray() converts the result back into an array.
Output:
• Joined Array: 1 2 3 4 5 6
ra
Solution 5: Using List and ArrayList (For Non-Primitive Types)
d
If you're working with non-primitive arrays (e.g., Integer[]), you can use List and ArrayList to
en
package array;
ar
import java.util.ArrayList;
m
import java.util.Arrays;
import java.util.List;
A
list.addAll(Arrays.asList(arr2));
ni
System.out.println("Joined Array:");
Pa
for (int i = 0; i < joinedArray.length; i++) {
}
ra
}
d
}
en
Explanation:
Output:
• Joined Array: 1 2 3 4 5 6
A
Summary of Solutions:
1. Manual Copying (Using Loops): Basic approach with full control over the copying
process.
4. Using Streams (Java 8 and above): A modern, clean solution using Java 8 streams.
5. Using List and ArrayList: Useful for non-primitive types like Integer[].
ni
Google Guava library?
Here are the three approaches to calculate the average:
Pa
1. Using a Simple Loop
package array;
ar
import java.util.Scanner;
ni
}
Pa
// Step 5: Calculate the sum using a simple loop
int sum = 0;
scanner.close();
}
Explanation:
Example Output:
• Input:
ni
o Enter 5 elements: 10 20 30 40 50
• Output:
Pa
o Average of the array is: 30.0
ra
Solution 2: Calculate Average Using Java 8 Streams
package array;
import java.util.Arrays;
ar
Explanation:
ni
• The average() method computes the average of the elements.
Pa
• The orElse(0) method provides a default value in case the array is empty.
Example Output:
The Google Guava library provides utility methods for various operations on collections and
arrays. You can use the Ints.asList() method to convert an array to a list and then compute
ar
<dependency>
A
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
package array;
import com.google.common.primitives.Ints;
import java.util.List;
ni
// Step 2: Convert the array to a list using Guava
Pa
List<Integer> list = Ints.asList(arr);
int sum = 0;
ra
for (int num : list) {
d
sum += num;
en
Explanation:
• The sum is calculated manually using a loop, and the average is computed by dividing
the sum by the list size.
Example Output:
Summary:
ni
Java 8 Streams Arrays.stream() + .average()
Pa
Google Guava Library Ints.asList() + manual sum
Each of these methods is efficient and suitable for different situations depending on whether
you are using plain Java, Java 8+, or libraries like Guava.
ra
28. Question: How do you shift all zero elements to the
d
right side of the array in Java?
en
Key Concept:
ar
The task is to shift all the zeros in an array to the right side while maintaining the relative
order of non-zero elements. This can be done in several ways, but the most efficient
approach is to use a two-pointer technique. You can move all non-zero elements to the front
m
Approach:
A
2. Traverse the array and whenever a non-zero element is found, place it in the next
available position in the array.
3. After all non-zero elements are shifted, fill the remaining positions with zeros.
Solution: Shift All Zeros to the Right
Explanation of Steps:
1. Input Handling: The program first takes input for the size and elements of the array.
o We use a variable index to track the position where the next non-zero
element should be placed.
ni
o As we iterate through the array, each non-zero element is placed at the
position tracked by index, and then index is incremented.
Pa
3. Fill Zeros: Once all non-zero elements are placed, the remaining positions (from index
to the end of the array) are filled with zeros.
o Enter 6 elements: 0 1 0 3 12 0
ar
• Output:
Edge Cases:
A
1. All Zeros: If the array contains only zeros, the output will be the same array.
2. No Zeros: If there are no zeros in the array, the array remains unchanged.
3. Empty Array: If the array is empty (n = 0), the program should handle this case
gracefully.
Time Complexity:
• The time complexity of this solution is O(n), where n is the number of elements in
the array. This is because we make one pass through the array to move the non-zero
elements and another pass to fill the zeros.
Space Complexity:
• The space complexity is O(1) because no additional arrays or data structures are
used, and the shifting is done in-place.
ni
Pa
29. Question: How do you check the equality of two arrays
in Java?
In Java, you can check the equality of two arrays in different ways. Equality can be checked
ra
based on whether the arrays contain the same elements in the same order, or in the case of
multi-dimensional arrays, whether the arrays are deeply equal (including any nested arrays).
d
Here are different ways to check the equality of two arrays:
en
The Arrays.equals() method is used to check whether two arrays of primitive or object types
are equal, meaning they contain the same elements in the same order.
package array;
import java.util.Arrays;
ni
// Step 3: Print the result
Pa
if (areEqual) {
} else {
ra
System.out.println("The arrays are not equal.");
d
}
en
}
ar
Explanation:
elements are equal and the arrays have the same length, it returns true; otherwise,
it returns false.
A
Example Output:
For multi-dimensional arrays, Arrays.equals() is not sufficient, as it only compares the top-
level array. To check equality for nested arrays (e.g., 2D arrays), you need to use
Arrays.deepEquals().
package array;
import java.util.Arrays;
ni
public class CheckEqualityUsingDeepEquals {
Pa
// Step 1: Define two 2D arrays
if (areEqual) {
} else {
}
Explanation:
Example Output:
ni
Solution 3: Manual Comparison Using a Loop
Pa
You can manually compare the elements of two arrays using a loop. This approach works for
both primitive and object arrays. ra
package array;
if (arr1.length != arr2.length) {
A
if (arr1[i] != arr2[i]) {
areEqual = false;
ni
// Step 4: Print the result
Pa
if (areEqual) {
} else {
ra
System.out.println("The arrays are not equal.");
d
}
en
}
ar
Explanation:
• This solution compares the length of both arrays first. If the lengths are different,
m
Example Output:
The Arrays.mismatch() method can be used to check the first index where the two arrays
differ. If it returns -1, the arrays are equal.
package array;
import java.util.Arrays;
ni
public static void main(String[] args) {
Pa
// Step 1: Define two 1D arrays
if (mismatchIndex == -1) {
ar
} else {
m
}
Explanation:
Example Output:
ni
Summary of Solutions:
Pa
Method Description
arrays, multi-dimensional arrays, or you want to find exactly where two arrays differ
ar
m
A
30. Question: How do you search for an element in an
array in Java?
You can search for an element in an array using various methods depending on whether the
array is sorted or unsorted, and the efficiency you require. The most common approaches
are:
ni
2. Binary Search: For sorted arrays, which is more efficient than linear search.
3. Using Built-in Methods: Such as Arrays.binarySearch() for sorted arrays.
Pa
Solution 1: Linear Search (For Unsorted Arrays)
In linear search, you traverse through the array element by element until you find the target
element. It works for both sorted and unsorted arrays, but it is not very efficient for large
ra
arrays.
d
package array;
en
import java.util.Scanner;
ni
System.out.println("Enter the element to search: ");
Pa
int target = scanner.nextInt();
found = true;
ar
break;
}
m
}
A
if (!found) {
Explanation:
• The program iterates through the array using a for loop. If the target element is
found, the index is printed. If the target is not found, the program prints a message
ni
saying the element is not present in the array.
Example Output:
Pa
• Input:
o Enter the number of elements: 5
o
ra
Enter 5 elements: 10 20 30 40 50
o Enter the element to search: 30
• Output: Element 30 found at index: 2
d
Solution 2: Binary Search (For Sorted Arrays)
en
In binary search, you repeatedly divide the search space in half by comparing the middle
element with the target. This method only works for sorted arrays and is much more
ar
package array;
import java.util.Scanner;
A
import java.util.Arrays;
// Step 4: Input elements into the array (assume the user enters sorted elements)
ni
System.out.println("Enter " + n + " sorted elements:");
Pa
for (int i = 0; i < n; i++) {
}
ra
// Step 5: Input the element to search for
d
System.out.println("Enter the element to search: ");
en
if (arr[mid] == target) {
found = true;
break;
}
left = mid + 1;
ni
else {
Pa
right = mid - 1;
}
ra
// Step 7: If element not found
d
if (!found) {
en
}
ar
scanner.close();
m
}
A
Explanation:
• Binary search works by checking the middle element. If the target is smaller than the
middle, the search space is reduced to the left half, and if larger, the search space is
reduced to the right half.
• This method is only applicable for sorted arrays.
Example Output:
• Input:
o Enter the number of elements: 5
o Enter 5 sorted elements: 10 20 30 40 50
o Enter the element to search: 30
• Output: Element 30 found at index: 2
ni
Java provides a built-in method Arrays.binarySearch() that can be used to perform binary
Pa
search directly on a sorted array.
package array;
import java.util.Arrays;
ra
import java.util.Scanner;
d
public class BinarySearchUsingArrays {
en
// Step 4: Input elements into the array (assume the user enters sorted elements)
ni
// Step 6: Use Arrays.binarySearch() to search for the element
Pa
int index = Arrays.binarySearch(arr, target);
if (index >= 0) {
ra
System.out.println("Element " + target + " found at index: " + index);
d
} else {
en
}
ar
scanner.close();
m
}
A
Explanation:
• Input:
o Enter the number of elements: 5
o Enter 5 sorted elements: 10 20 30 40 50
o Enter the element to search: 30
• Output: Element 30 found at index: 2
Summary:
ni
Method Use Case Time Complexity
Pa
Linear Search For unsorted arrays or small arrays O(n)
Key Concept:
To reverse an array in place (i.e., without using an additional array), you can use a two-
ni
pointer approach. One pointer starts at the beginning of the array and the other starts at
the end. You swap the elements at these two pointers and then move both pointers toward
the center until they meet or cross each other.
Pa
Approach:
1. Initialize two pointers: one at the start (i = 0) and the other at the end (j =
ra
array.length - 1).
2. Swap the elements at these two pointers.
d
3. Increment the start pointer and decrement the end pointer.
4. Repeat this process until the two pointers meet or cross each other.
en
package array;
import java.util.Scanner;
m
ni
arr[i] = scanner.nextInt(); // Input each element
Pa
}
int start = 0;
ra
int end = n - 1;
d
while (start < end) {
en
arr[start] = arr[end];
arr[end] = temp;
m
// Move pointers
A
start++;
end--;
System.out.println("Reversed array:");
for (int i = 0; i < n; i++) {
scanner.close();
ni
}
Pa
Explanation of Steps: ra
1. Input Handling: The user provides the size of the array and its elements.
2. Two-Pointer Approach:
o A start pointer is initialized at the beginning (0) and an end pointer is
d
initialized at the end (n - 1).
en
end pointer.
3. Output: After reversing, the program prints the reversed array.
m
Input/Output Example:
A
• Input:
o Enter the number of elements: 5
o Enter 5 elements: 1 2 3 4 5
• Output:
o Reversed array: 5 4 3 2 1
Edge Cases:
1. Empty Array: If the array has zero elements, the program should handle this
gracefully without performing any swaps.
2. Single Element Array: If the array has only one element, it will remain unchanged
after the reverse operation.
3. Odd/Even Length Array: The approach works for both odd and even length arrays.
For odd-length arrays, the middle element will remain in the same position.
ni
Time Complexity:
Pa
• The time complexity of this approach is O(n), where n is the number of elements in
the array. This is because we swap each element exactly once.
Space Complexity:
ra
• The space complexity is O(1), since no additional arrays or data structures are used,
and the reversal is done in place.
d
en
in an array in Java?
Key Concept:
m
To find the second largest element in an array, you can traverse the array once, keeping
A
track of both the largest and second largest elements. The idea is to compare each element
with the current largest, and if it is larger, update the second largest and largest accordingly.
Approach:
1. Initialize two variables firstLargest and secondLargest to hold the largest and second
largest values, respectively.
2. Traverse the array:
o If the current element is larger than firstLargest, update secondLargest to be
firstLargest, and update firstLargest to the current element.
o Else if the current element is smaller than firstLargest but larger than
secondLargest, update secondLargest to the current element.
3. After the loop, secondLargest will hold the second largest value in the array.
package array;
ni
import java.util.Scanner;
Pa
public class SecondLargestInArray {
} else {
ni
for (int i = 0; i < n; i++) {
Pa
if (arr[i] > firstLargest) {
secondLargest = firstLargest;
firstLargest = arr[i];
ra
} else if (arr[i] > secondLargest && arr[i] != firstLargest) {
d
secondLargest = arr[i];
en
}
ar
if (secondLargest == Integer.MIN_VALUE) {
m
} else {
Explanation of Steps:
1. Input Handling: The program takes input for the size of the array and the array
elements.
ni
2. Finding the Second Largest:
o We initialize firstLargest and secondLargest with Integer.MIN_VALUE to
Pa
ensure any element in the array can replace them.
o Traverse the array:
▪ If the current element is greater than firstLargest, update
secondLargest to the value of firstLargest, and then set firstLargest to
ra
the current element.
▪ If the current element is greater than secondLargest but less than
d
firstLargest, update secondLargest.
3. Edge Cases:
en
o If the array has fewer than two elements, the program prints an error
message.
ar
o If all elements are the same, the program will print that there is no second
largest element.
4. Output: The second largest element is printed after the traversal.
m
Input/Output Example:
A
Edge Cases:
1. All Elements Are the Same: If all elements are the same, there is no second largest
element.
ni
2. Single Element Array: If the array contains only one element, the program prints an
error message.
Pa
3. Negative Numbers: The solution works correctly for negative numbers as well.
Time Complexity: ra
• The time complexity of this approach is O(n), where n is the number of elements in
the array. This is because we only need to traverse the array once.
d
Space Complexity:
en
• The space complexity is O(1), since no extra arrays or data structures are used, and
only a few variables are used to track the largest and second largest elements.
ar
Key Concept:
A
To find the second smallest element, you can use a two-pass approach similar to finding the
second largest element. You traverse the array once to find the smallest element, then
traverse it again to find the smallest element that is greater than the first smallest.
Alternatively, you can do it in one pass by keeping track of both the smallest and second
smallest elements during a single traversal.
Approach:
1. Initialize two variables firstSmallest and secondSmallest to hold the smallest and
second smallest values, respectively.
2. Traverse the array:
o If the current element is smaller than firstSmallest, update secondSmallest to
be firstSmallest, and update firstSmallest to the current element.
o Else if the current element is greater than firstSmallest but smaller than
ni
secondSmallest, update secondSmallest.
3. After the loop, secondSmallest will hold the second smallest value in the array.
Pa
Solution: Find the Second Smallest Element in the Array
package array; ra
import java.util.Scanner;
if (n < 2) {
} else {
ni
int firstSmallest = Integer.MAX_VALUE;
Pa
int secondSmallest = Integer.MAX_VALUE;
firstSmallest = arr[i];
secondSmallest = arr[i];
}
m
}
A
if (secondSmallest == Integer.MAX_VALUE) {
} else {
scanner.close();
ni
Explanation of Steps:
Pa
1. Input Handling: The program takes input for the size of the array and its elements.
2. Finding the Second Smallest:
o We initialize firstSmallest and secondSmallest with Integer.MAX_VALUE to
ra
ensure any element in the array can replace them.
o Traverse the array:
▪ If the current element is smaller than firstSmallest, update
d
secondSmallest to the value of firstSmallest, and then set firstSmallest
en
3. Edge Cases:
o If the array has fewer than two elements, the program prints an error
m
message.
o If all elements are the same, the program will print that there is no second
A
smallest element.
4. Output: The second smallest element is printed after the traversal.
Input/Output Example:
ni
Edge Cases:
Pa
1. All Elements Are the Same: If all elements are the same, there is no second smallest
element.
2. Single Element Array: If the array contains only one element, the program prints an
ra
error message.
3. Negative Numbers: The solution works correctly for negative numbers as well.
d
Time Complexity:
en
• The time complexity of this approach is O(n), where n is the number of elements in
the array. This is because we only need to traverse the array once.
ar
Space Complexity:
m
• The space complexity is O(1), since no extra arrays or data structures are used, and
only a few variables are used to track the smallest and second smallest elements.
A
•
34. Question: How do you find all possible pairs of
elements in an array in Java?
Key Concept:
To find all pairs of elements in an array, you can use nested loops to iterate through each
element of the array and pair it with every other element. This approach ensures that every
combination of pairs is covered, without repetition (if order doesn't matter).
ni
Approach:
Pa
1. Use two loops:
o The outer loop picks one element.
o The inner loop pairs it with every other element after it.
2. Print each pair.
ra
Solution: Find All Pairs of Elepackage array;
d
import java.util.Scanner;
en
ni
for (int i = 0; i < n; i++) {
Pa
for (int j = i + 1; j < n; j++) {
}
ra
}
d
// Close the scanner
en
scanner.close();
}
ar
Explanation of Steps:
m
1. Input Handling: The program first takes the number of elements in the array and
A
• Input:
o Enter the number of elements: 4
o Enter 4 elements: 1 2 3 4
• Output:
ni
(1, 2)
(1, 3)
Pa
(1, 4)
(2, 3)
ra
(2, 4)
d
(3, 4)
en
Edge Cases:
1. Array with One Element: If the array contains only one element, no pairs can be
ar
2. Empty Array: If the array has zero elements, the program should handle this without
m
Time Complexity:
A
• The time complexity of this approach is O(n^2), where n is the number of elements
in the array. This is because the inner loop runs n - 1 times for each iteration of the
outer loop, leading to quadratic time complexity.
Space Complexity:
• The space complexity is O(1) since no additional arrays or data structures are used,
and the pairing is done in place.
•
Key Concept:
The task is to find the first element that repeats in the array. We need to identify the
element that appears more than once, and among all repeating elements, return the one
ni
that occurs first.
Approach:
Pa
1. Use a HashSet to keep track of elements that have been encountered.
o If the element is already in the set, it's the first repeating element.
d
o If it's not in the set, add it to the set.
en
3. The first element found that is already in the set is the first repeating element.
package array;
import java.util.HashSet;
m
import java.util.Scanner;
A
ni
for (int i = 0; i < n; i++) {
Pa
arr[i] = scanner.nextInt(); // Input each element
if (seenElements.contains(arr[i])) {
ar
firstRepeating = arr[i];
} else {
m
seenElements.add(arr[i]);
A
if (firstRepeating != -1) {
scanner.close();
ni
}
Pa
Explanation of Steps:
1. Input Handling: The user inputs the size of the array and its elements.
Input/Output Example:
o Enter 6 elements: 10 5 3 4 3 5
• Output:
o Enter 5 elements: 1 2 3 4 5
• Output:
Edge Cases:
1. No Repeating Elements: If no elements repeat in the array, the output will indicate
ni
that no repeating elements were found.
2. All Elements are the Same: If all elements are the same, the first element will be
Pa
identified as the repeating element.
3. Empty Array: If the array is empty, the program should handle this gracefully without
errors.
ra
Time Complexity:
• The time complexity is O(n), where n is the number of elements in the array. We
d
traverse the array once and perform constant-time HashSet operations.
en
Space Complexity:
• The space complexity is O(n), since the HashSet may store all elements in the worst
ar
case.
•
m
A
36. Question: How do you find the first occurrence and last
occurrence of an element in an array in Java?
Key Concept:
1. First Occurrence: Traverse the array from left to right and find the first index where
the element appears.
ni
2. Last Occurrence: Traverse the array from right to left and find the last index where
the element appears.
Pa
Approach:
1. First Occurrence: Traverse the array from the beginning and stop at the first
occurrence of the element.
ra
2. Last Occurrence: Traverse the array from the end and stop at the first occurrence of
the element in reverse order.
d
Solution: Find the First and Last Occurrence of an Element in an Array
en
package array;
ar
import java.util.Scanner;
ni
}
Pa
// Step 5: Input the element to search for
System.out.println("Enter the element to find its first and last occurrence: ");
if (arr[i] == target) {
m
firstOccurrence = i;
A
lastOccurrence = i;
ni
if (firstOccurrence != -1) {
Pa
System.out.println("First occurrence of element " + target + " is at index: " +
firstOccurrence);
scanner.close();
}
m
}
A
Explanation of Steps:
1. Input Handling: The program first takes the number of elements in the array and the
array elements.
2. First Occurrence:
o As soon as the element is found, the index is recorded, and the loop breaks.
3. Last Occurrence:
o Another for loop is used to traverse the array from right to left.
o As soon as the element is found, the index is recorded, and the loop breaks.
4. Output the Results: If the element is found, the first and last occurrence indices are
printed. If the element is not found, an appropriate message is displayed.
Input/Output Example:
ni
• Input:
Pa
o Enter 6 elements: 10 20 20 40 50 20
• Enter 5 elements: 10 20 30 40 50
Output:
A
Edge Cases:
1. Element Not Found: If the element is not in the array, both first and last occurrences
will be -1, and the program will print that the element is not found.
2. Array with One Element: If the array has only one element, both first and last
occurrences will be the same index (0 if the element is found).
3. All Elements Are the Same: If all elements are the same, both first and last
occurrences will be the first and last indices, respectively.
Time Complexity:
• The time complexity is O(n), where n is the number of elements in the array. We
traverse the array twice: once to find the first occurrence and once to find the last
occurrence.
Space Complexity:
ni
• The space complexity is O(1), as no additional arrays or data structures are used.
Pa
37. Question: How do you find the common elements in
multiple arrays in Java?
ra
Key Concept:
d
To find common elements in multiple arrays, you need to compare the elements across all
arrays and identify which elements appear in all of them.
en
Approach:
2. For each of the subsequent arrays, find the intersection with the elements in the set
(i.e., only retain elements that are present in all arrays).
m
3. After processing all arrays, the set will contain only the common elements.
A
package array;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class CommonElementsInArrays {
ni
if (numArrays < 2) {
Pa
System.out.println("At least two arrays are required to find common elements.");
return;
}
ra
// Step 2: Input the first array
d
System.out.println("Enter the number of elements in the first array: ");
en
int n = scanner.nextInt();
int m = scanner.nextInt();
Set<Integer> currentArray = new HashSet<>();
currentArray.add(scanner.nextInt());
ni
commonElements.retainAll(currentArray);
Pa
}
if (commonElements.isEmpty()) {
ra
System.out.println("No common elements found.");
d
} else {
en
}
ar
scanner.close();
m
}
A
Explanation of Steps:
1. Input Handling:
o The first array's elements are stored in a HashSet to track the elements that
are common.
2. Intersection with Subsequent Arrays:
o For each subsequent array, another HashSet is used to store the elements
temporarily.
o The method retainAll() is called to retain only the elements that are common
between the current HashSet and the set of common elements.
3. Output the Result: After processing all arrays, the common elements are printed. If
no common elements are found, a message is displayed.
ni
Input/Output Example:
Pa
• Input:
• Output:
m
• Output:
Edge Cases:
1. No Common Elements: If no common elements exist across all arrays, the program
ni
will correctly handle this and print a message saying no common elements were
found.
Pa
2. Arrays with One Element: If any array has only one element, that element must be
common to all arrays for it to appear in the result.
3. All Elements Are Common: If all elements of the arrays are the same, all elements
will appear in the result.
ra
Time Complexity:
d
• The time complexity is O(n * m), where n is the size of the largest array, and m is the
en
number of arrays. This is because we must traverse all arrays and perform set
operations.
ar
Space Complexity:
• The space complexity is O(n), where n is the size of the largest array, as we need to
m
Key Concept:
You can rearrange the positive and negative elements in an array such that all negative
elements come before the positive elements, while maintaining their relative order. This can
be done in O(n) time by traversing the array once and using a simple approach.
ni
Approach:
1. Two-pointer technique: You can traverse the array and, when encountering a
Pa
negative element, shift the negative elements to the left side.
2. Maintain Order: To maintain the relative order of both positive and negative
numbers, you can use an auxiliary approach like insertion sort-style shifting.
ra
Solution: Rearrange Positive and Negative Elements While Maintaining Order
d
package array;
en
import java.util.Scanner;
ni
rearrangePositiveNegative(arr, n);
Pa
// Step 6: Print the rearranged array
scanner.close();
ar
}
m
// Function to rearrange the array with negatives first and positives later
if (arr[i] < 0) {
if (i != j) {
// Swap the elements
arr[i] = arr[j];
arr[j] = temp;
ni
}
Pa
}
}
ra
Explanation of Steps:
d
1. Input Handling: The program first takes the size of the array and the array elements
as input.
en
2. Rearrange Logic:
o The program traverses the array, and whenever a negative element is found,
it swaps that element with the element at index j and increments j.
m
o This process ensures that all negative numbers are shifted to the left, while
A
3. Output: The rearranged array is printed, where all negative elements appear before
the positive elements.
Input/Output Example:
• Input:
• Output:
Re-arranged array with negative elements first and positive elements later:
-1 -3 -5 -7 2 4 6 8
Edge Cases:
ni
1. All Positive or All Negative Elements: If the array contains only positive or only
negative elements, the array remains unchanged.
Pa
2. Empty Array: If the array is empty (n = 0), the program should handle this gracefully.
3. One Element: If the array contains only one element, no rearrangement is needed.
ra
Time Complexity:
• The time complexity of this approach is O(n), where n is the number of elements in
d
the array, since we traverse the array only once.
en
Space Complexity:
• The space complexity is O(1), as no additional space is required apart from a few
variables.
ar
Another approach is to create two arrays—one for positive numbers and one for negative
numbers—and then combine them. This approach does not preserve the relative order of
the numbers.
A
package array;
ni
for (int i = 0; i < n; i++) {
Pa
if (arr[i] < 0) {
negatives[negIndex++] = arr[i];
} else {
ra
positives[posIndex++] = arr[i];
d
}
en
arr[i] = negatives[i];
m
}
A
arr[negIndex + i] = positives[i];
ni
Explanation:
Pa
• In this approach, we create two temporary arrays: one for negative numbers and one
for positive numbers.
• We copy the negative numbers back into the original array, followed by the positive
numbers.
ra
• This approach does not preserve the relative order of elements, and the space
d
complexity is O(n) due to the use of temporary arrays.
en
Key Concept:
m
You can find the second smallest element in an array in one pass (i.e., without sorting the
array) by keeping track of both the smallest and second smallest elements during a single
A
Approach:
1. Initialize two variables, firstSmallest and secondSmallest, to hold the smallest and
second smallest values.
o Else if the current element is greater than firstSmallest and smaller than
secondSmallest, update secondSmallest.
3. At the end of the traversal, secondSmallest will hold the second smallest value.
ni
package array;
import java.util.Scanner;
Pa
public class SecondSmallestElement {
} else {
ni
for (int i = 0; i < n; i++) {
Pa
if (arr[i] < firstSmallest) {
secondSmallest = firstSmallest;
firstSmallest = arr[i];
ra
} else if (arr[i] > firstSmallest && arr[i] < secondSmallest) {
d
secondSmallest = arr[i];
en
}
ar
if (secondSmallest == Integer.MAX_VALUE) {
m
} else {
Explanation of Steps:
1. Input Handling: The user provides the size of the array and its elements.
ni
o We initialize firstSmallest and secondSmallest to Integer.MAX_VALUE to
ensure any element in the array can replace them.
Pa
o Traverse the array:
3. Edge Case Handling: If all elements are the same or if there is no second smallest
element, the program will notify the user that no second smallest element exists.
ar
4. Output: The second smallest element is printed at the end of the traversal.
Input/Output Example:
m
o Enter 6 elements: 10 20 5 30 15 25
• Output:
o Enter 5 elements: 5 5 5 5 5
• Output:
Edge Cases:
1. Array with Less Than Two Elements: If the array has fewer than two elements, the
ni
program will print an error message.
2. All Elements Are the Same: If all elements are the same, the program will print that
Pa
no second smallest element exists.
Time Complexity:
ra
• The time complexity of this approach is O(n), where n is the number of elements in
the array. This is because we only need to traverse the array once.
d
en
Space Complexity:
• The space complexity is O(1), since no additional arrays or data structures are used,
ar
and only a few variables are used to track the smallest and second smallest elements.
m
Key Concept:
In this case, we'll move all the negative numbers to the left side of the array and positive
numbers to the right side.
ni
package array;
Pa
import java.util.Scanner;
}
// Step 5: Segregate the array with positive and negative numbers
segregatePositiveNegative(arr, n);
ni
System.out.print(arr[i] + " ");
Pa
// Close the scanner
scanner.close();
}
ra
// Function to segregate positive and negative numbers
d
public static void segregatePositiveNegative(int[] arr, int n) {
en
if (arr[i] < 0) {
m
if (i != j) {
A
arr[i] = arr[j];
arr[j] = temp;
Input/Output Example:
• Input:
ni
o Enter the number of elements: 8
Pa
o Enter 8 elements: -1 2 -3 4 -5 6 -7 8
• Output:
Segregated array with negative numbers on the left and positive numbers on the right:
ra
-1 -3 -5 -7 2 4 6 8
d
en
In this case, we'll move all the even numbers to the left side of the array and odd numbers to
the right side.
m
package array;
import java.util.Scanner;
ni
// Step 4: Input elements into the array
Pa
System.out.println("Enter " + n + " elements:");
segregateEvenOdd(arr, n);
System.out.println("Segregated array with even numbers on the left and odd numbers
on the right:");
m
scanner.close();
if (arr[i] % 2 == 0) {
if (i != j) {
ni
int temp = arr[i];
Pa
arr[i] = arr[j];
arr[j] = temp;
}
ra
j++; // Increment index for the next even number
d
}
en
}
ar
Input/Output Example:
m
• Input:
A
o Enter 8 elements: 1 2 3 4 5 6 7 8
• Output:
Segregated array with even numbers on the left and odd numbers on the right:
24681357
Case 3: Segregate 0s and 1s (Binary Array)
In this case, we'll segregate a binary array, where all 0s are moved to the left and all 1s are
moved to the right.
package array;
ni
import java.util.Scanner;
Pa
public static void main(String[] args) {
only): ");
// Step 4: Input elements into the binary array (only 0s and 1s)
A
ni
}
Pa
scanner.close();
}
ra
// Function to segregate 0s and 1s in a binary array
if (arr[i] == 0) {
ar
if (i != j) {
arr[i] = arr[j];
arr[j] = temp;
}
}
00001111
ni
Edge Cases for All Solutions:
Pa
1. Array with Only One Type of Element: If the array contains only one type of element
(all positives, all negatives, all evens, etc.), the array remains unchanged.
2. Empty Array: If the array is empty, the program should handle this gracefully and
ra
print nothing.
3. One Element Array: If the array contains only one element, no segregation is needed.
d
Time Complexity:
en
• The time complexity for all solutions is O(n), where n is the number of elements in
the array. This is because we only traverse the array once.
ar
Space Complexity:
• The space complexity is O(1), as no additional arrays or data structures are used
beyond a few variables.
m
A
Key Concept:
To remove consecutive duplicates from an array, you need to traverse the array and compare
each element with the previous one. If an element is the same as the previous one, you skip
it. The goal is to retain only the first occurrence of consecutive elements.
Approach:
1. Traverse the array, compare each element with the previous one.
2. Only retain elements that are different from the previous element.
3. Create a new array or modify the original array in place to store the result without
consecutive duplicates.
ni
package array;
Pa
import java.util.Scanner;
}
// Step 5: Remove consecutive duplicates
ni
}
Pa
// Close the scanner
scanner.close();
}
ra
// Function to remove consecutive duplicates
d
public static int[] removeConsecutiveDuplicates(int[] arr, int n) {
en
if (n == 0) {
temp[j++] = arr[0];
temp[j++] = arr[i];
ni
// Create the final result array of size j
Pa
System.arraycopy(temp, 0, result, 0, j);
return result;
}
ra
}
d
Explanation of Steps:
en
1. Input Handling: The user provides the size of the array and its elements.
o For every subsequent element, the program checks if it is the same as the
previous element. If it's not, the element is added to the result.
3. Return the Result: The result is returned as a new array that contains no consecutive
duplicates.
Input/Output Example:
• Input:
o Enter 10 elements: 1 1 2 2 2 3 4 4 5 5
• Output:
12345
ni
Edge Cases:
1. Empty Array: If the array is empty, the program will return an empty array.
Pa
2. Array with One Element: If the array contains only one element, no duplicates exist,
and the array remains unchanged. ra
3. All Elements Are the Same: If all elements are the same, the result will contain only
one element.
d
en
Time Complexity:
• The time complexity of this approach is O(n), where n is the number of elements in
the array. This is because we only traverse the array once.
ar
Space Complexity:
m
• The space complexity is O(n) because we use a temporary array to store the result,
and the size of this array is proportional to the input array.
A
If you don't want to use extra space and want to modify the array in place, you can use the
following approach:
package array;
import java.util.Scanner;
public class RemoveConsecutiveDuplicatesInPlace {
ni
int n = scanner.nextInt(); // Size of the array
Pa
// Step 3: Create an array of the given size
}
ar
if (n == 0) {
ni
}
Pa
int j = 0; // Index for the modified array
}
ar
return j + 1;
A
Solution:
• We use a single index j to track the position where the next unique element should
be placed.
• As we traverse the array, we compare each element with the element at index j. If
they are different, we increment j and update arr[j] to the current element.
• The function returns the new length of the array after removing consecutive
duplicates.
• Input:
ni
o
o Enter 10 elements: 1 1 2 2 2 3 4 4 5 5
Pa
• Output:
12345
d ra
en
• The time complexity is O(n), where n is the number of elements in the array.
• The space complexity is O(1) since we are modifying the array in place without using
any additional arrays.
A
42. Question: How do you count all possible pairs from an
array in Java?
Key Concept:
To count all possible pairs from an array, you can use a nested loop. Each element of the
array will be paired with every other element that comes after it in the array. If there are n
elements in the array, the total number of possible pairs can be calculated as:
ni
• Total pairs = n * (n - 1) / 2
Approach:
Pa
1. Nested Loops:
2. Count the Pairs: Each time a valid pair is found, increment the count.
d
Solution: Count All Possible Pairs in an Array
en
package array;
import java.util.Scanner;
ar
ni
// Step 5: Count and print all possible pairs
Pa
int totalPairs = countPairs(arr, n);
int pairCount = 0;
pairCount++;
}
return pairCount;
Explanation of Steps:
1. Input Handling: The program first takes the size of the array and the array elements
as input.
ni
2. Counting the Pairs:
Pa
o The inner loop generates a pair between the current element in the outer
loop and each subsequent element in the array.
ra
o For each valid pair, the pairCount is incremented.
3. Return the Count: After generating all possible pairs, the function returns the total
count of pairs.
d
4. Output: The total number of possible pairs is printed.
en
Input/Output Example:
ar
• Input:
o Enter 4 elements: 1 2 3 4
• Output:
A
Explanation of Pairs:
• (1, 2)
• (1, 3)
• (1, 4)
• (2, 3)
• (2, 4)
• (3, 4)
ni
Formula for Counting Pairs:
For an array with n elements, the number of unique pairs (without repetition) can be
Pa
calculated using the combination formula:
• Number of pairs = n * (n - 1) / 2 ra
For example, if n = 4:
• Number of pairs = 4 * (4 - 1) / 2 = 4 * 3 / 2 = 6
d
Edge Cases:
en
1. Empty Array: If the array is empty (n = 0), the number of pairs will be 0.
2. Array with One Element: If the array has only one element, no pairs can be formed,
ar
3. Array with Two Elements: The only possible pair is (arr[0], arr[1]), so the number of
m
pairs will be 1.
Time Complexity:
A
• The time complexity of this approach is O(n^2), where n is the number of elements
in the array. This is because we use a nested loop to generate all pairs.
Space Complexity:
• The space complexity is O(1), as no additional arrays or data structures are used
beyond a few variables.