1. Write a program to find the maximum and minimum element in an array of integers?
public class MaxMinArray { public static void main(String[] args) { int[] arr = {5, 2, 9, 1, 7, 3}; int max = arr[0]; int min = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; } if (arr[i] < min) { min = arr[i]; } } System.out.println(“Maximum element: ” + max); System.out.println(“Minimum element: ” + min); } } |
Output :
Maximum element: 9 Minimum element: 1 |
2. Write a program to reverse an array in-place without using a secondary array?
public class ReverseArray { public static void main(String[] args) { int[] arr = {5, 2, 9, 1, 7, 3}; reverseArray(arr); System.out.print(“Reversed Array: “); for (int i : arr) { System.out.print(i + ” “); } } public static void reverseArray(int[] arr) { int start = 0; int end = arr.length – 1; while (start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end–; } } } |
Output :
Reversed Array: 3 7 1 9 2 5 |
3. Write a program to how do you rotate an array in Java?
public class RotateArray { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5, 6}; int k = 2; // Number of positions to rotate rotateRight(arr, k); System.out.print(“Rotated Array: “); for (int num : arr) { System.out.print(num + ” “); } } public static void rotateRight(int[] arr, int k) { int n = arr.length; k = k % n; reverseArray(arr, 0, n – 1); reverseArray(arr, 0, k – 1); reverseArray(arr, k, n – 1); } public static void reverseArray(int[] arr, int start, int end) { while (start < end) { // Swap arr[start] and arr[end] int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end–; } } } |
Output (for input array {1, 2, 3, 4, 5, 6} and k = 2):
Rotated Array: 5 6 1 2 3 4 |
4. Write a program to check if a given array is sorted in non-decreasing order?
public class CheckSortedArray { public static void main(String[] args) { int[] arr = {1, 2, 2, 3, 4, 5}; if (isSorted(arr)) { System.out.println(“The array is sorted in non-decreasing order.”); } else { System.out.println(“The array is not sorted in non-decreasing order.”); } } public static boolean isSorted(int[] arr) { for (int i = 1; i < arr.length; i++) { if (arr[i] < arr[i – 1]) { return false; } } return true; } } |
Output :
The array is sorted in non-decreasing order. |
5. Write a program to move all zero elements of an array to the end, without changing the relative order of non-zero elements?
public class MoveZeroesToEnd { public static void main(String[] args) { int[] arr = {0, 1, 9, 2, 0, 3, 4, 0}; moveZeroes(arr); System.out.print(“Array after moving zeroes: “); for (int num : arr) { System.out.print(num + ” “); } } public static void moveZeroes(int[] arr) { int nonZeroIndex = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] != 0) { int temp = arr[nonZeroIndex]; arr[nonZeroIndex] = arr[i]; arr[i] = temp; nonZeroIndex++; } } } } |
Output :
Array after moving zeroes: 1 9 2 3 4 0 0 0 |
6. Write a program to find the second largest element in an array?
public class SecondLargestElement { public static void main(String[] args) { int[] arr = {12, 35, 1, 10, 34, 1}; int secondLargest = findSecondLargest(arr); if (secondLargest == Integer.MIN_VALUE) { System.out.println(“There is no second largest element in the array.”); } else { System.out.println(“The second largest element is: ” + secondLargest); } } public static int findSecondLargest(int[] arr) { int largest = Integer.MIN_VALUE; int secondLargest = Integer.MIN_VALUE; for (int i = 0; i < arr.length; i++) { if (arr[i] > largest) { secondLargest = largest; largest = arr[i]; } else if (arr[i] > secondLargest && arr[i] != largest) { secondLargest = arr[i]; } } return secondLargest; } } |
Output :
The second largest element is: 34 |
7. Write a program to given an array of size n-1 containing numbers from 1 to n, write a program to find the missing number?
public class MissingNumber { public static void main(String[] args) { int[] arr = {1, 2, 3, 5}; int missingNumber = findMissingNumber(arr); System.out.println(“The missing number is: ” + missingNumber); } public static int findMissingNumber(int[] arr) { int n = arr.length + 1; int expectedSum = n * (n + 1) / 2; int actualSum = 0; for (int num : arr) { actualSum += num; } return expectedSum – actualSum; } } |
Output :
The missing number is: 4 |
8. Write a program to find the first duplicate element in an array?
import java.util.HashSet; public class FirstDuplicate { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5, 6, 2, 7}; int duplicate = findFirstDuplicate(arr); if (duplicate == -1) { System.out.println(“No duplicate elements found.”); } else { System.out.println(“The first duplicate element is: ” + duplicate); } } public static int findFirstDuplicate(int[] arr) { HashSet<Integer> seen = new HashSet<>(); for (int num : arr) { if (seen.contains(num)) { return num; } seen.add(num); } return -1; } } |
Output :
The first duplicate element is: 2 |
9. Write a program to count how many times each element appears in an array?
import java.util.HashMap; import java.util.Map; public class CountElements { public static void main(String[] args) { int[] arr = {4, 5, 6, 4, 7, 8, 5, 6, 4}; countElementOccurrences(arr); } public static void countElementOccurrences(int[] arr) { HashMap<Integer, Integer> frequencyMap = new HashMap<>(); for (int num : arr) { frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1); } System.out.println(“Element occurrences:”); for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) { System.out.println(“Element ” + entry.getKey() + ” appears ” + entry.getValue() + ” time(s).”); } } } |
Output :
Element occurrences: Element 4 appears 3 time(s). Element 5 appears 2 time(s). Element 6 appears 2 time(s). Element 7 appears 1 time(s). Element 8 appears 1 time(s). |
10. Write a program to merge two sorted arrays into a single sorted array?
import java.util.Arrays; public class MergeSortedArrays { public static void main(String[] args) { int[] arr1 = {1, 3, 5, 7}; int[] arr2 = {2, 4, 6, 8}; int[] mergedArray = mergeSortedArrays(arr1, arr2); System.out.println(“Merged sorted array: ” + Arrays.toString(mergedArray)); } public static int[] mergeSortedArrays(int[] arr1, int[] arr2) { int n1 = arr1.length; int n2 = arr2.length; int[] mergedArray = new int[n1 + n2]; int i = 0, j = 0, k = 0; while (i < n1 && j < n2) { if (arr1[i] <= arr2[j]) { mergedArray[k++] = arr1[i++]; } else { mergedArray[k++] = arr2[j++]; } } while (i < n1) { mergedArray[k++] = arr1[i++]; } while (j < n2) { mergedArray[k++] = arr2[j++]; } return mergedArray; } } |
Output :
Merged sorted array: [1, 2, 3, 4, 5, 6, 7, 8] |
11. Write a program to check if two arrays are equal (contain the same elements in the same order)?
import java.util.Arrays; public class CheckArraysEqual { public static void main(String[] args) { int[] arr1 = {1, 2, 3, 4}; int[] arr2 = {1, 2, 3, 4}; if (areArraysEqual(arr1, arr2)) { System.out.println(“The arrays are equal.”); } else { System.out.println(“The arrays are not equal.”); } } public static boolean areArraysEqual(int[] arr1, int[] arr2) { if (arr1.length != arr2.length) { return false; } for (int i = 0; i < arr1.length; i++) { if (arr1[i] != arr2[i]) { return false; } } return true; } } |
Output :
The arrays are equal. |
12. Write a program to find the common elements between two arrays?
import java.util.HashSet; public class CommonElements { public static void main(String[] args) { int[] arr1 = {1, 2, 3, 4, 5}; int[] arr2 = {3, 4, 5, 6, 7}; findCommonElements(arr1, arr2); } public static void findCommonElements(int[] arr1, int[] arr2) { HashSet<Integer> set = new HashSet<>(); for (int num : arr1) { set.add(num); } System.out.print(“Common elements: “); boolean found = false; for (int num : arr2) { if (set.contains(num)) { System.out.print(num + ” “); found = true; } } if (!found) { System.out.println(“No common elements found.”); } else { System.out.println(); } } } |
Output :
Common elements: 3 4 5 |
13. Write a program to find the sum of all elements in an array?
public class SumOfArray { public static int sumOfElements(int[] arr) { int sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } return sum; } public static void main(String[] args) { int[] array = {1, 2, 3, 4, 5}; int result = sumOfElements(array); System.out.println(“The sum of all elements in the array is: ” + result); } } |
Output :
The sum of all elements in the array is: 15 |
14. Write a program to find the product of all elements in an array?
public class ProductOfArray { public static int productOfElements(int[] arr) { int product = 1; for (int i = 0; i < arr.length; i++) { product *= arr[i]; } return product; } public static void main(String[] args) { int[] array = {1, 2, 3, 4, 5}; int result = productOfElements(array); System.out.println(“The product of all elements in the array is: ” + result); } } |
Output :
The product of all elements in the array is: 120 |
15. Write a program to find the even and odd count in an array?
public class EvenOddCount { public static void countEvenOdd(int[] arr) { int evenCount = 0; int oddCount = 0; for (int num : arr) { if (num % 2 == 0) { evenCount++; } else { oddCount++; } } System.out.println(“Even numbers count: ” + evenCount); System.out.println(“Odd numbers count: ” + oddCount); } public static void main(String[] args) { int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9}; countEvenOdd(array); } } |
Output :
Even numbers count: 4 Odd numbers count: 5 |
16. Write a program to find the Largest Product of Two Elements in an Array?
public class LargestProductOfTwo { public static int largestProduct(int[] arr) { if (arr.length < 2) { System.out.println(“Array must contain at least two elements.”); return -1; } int max1 = Integer.MIN_VALUE; int max2 = Integer.MIN_VALUE; int min1 = Integer.MAX_VALUE; int min2 = Integer.MAX_VALUE; for (int num : arr) { if (num > max1) { max2 = max1; max1 = num; } else if (num > max2) { max2 = num; } if (num < min1) { min2 = min1; min1 = num; } else if (num < min2) { min2 = num; } } return Math.max(max1 * max2, min1 * min2); } public static void main(String[] args) { int[] array = {1, -10, -3, 4, 6}; int result = largestProduct(array); System.out.println(“The largest product of two elements in the array is: ” + result); } } |
Output :
The largest product of two elements in the array is: 30 |
17. Write a program to find the element that appears once in an array?
public class ElementAppearsOnce { public static int findElementAppearsOnce(int[] arr) { int result = 0; for (int num : arr) { result ^= num; } return result; } public static void main(String[] args) { int[] array = {4, 5, 6, 4, 5, 7, 6}; int result = findElementAppearsOnce(array); System.out.println(“The element that appears once in the array is: ” + result); } } |
Output :
The element that appears once in the array is: 7 |
18. Write a program to find the union of two arrays?
import java.util.HashSet; public class UnionOfArrays { public static int[] findUnion(int[] arr1, int[] arr2) { HashSet<Integer> unionSet = new HashSet<>(); for (int num : arr1) { unionSet.add(num); } for (int num : arr2) { unionSet.add(num); } int[] result = new int[unionSet.size()]; int i = 0; for (int num : unionSet) { result[i++] = num; } return result; } public static void main(String[] args) { int[] arr1 = {1, 2, 3, 4}; int[] arr2 = {3, 4, 5, 6}; int[] union = findUnion(arr1, arr2); System.out.print(“Union of the two arrays: “); for (int num : union) { System.out.print(num + ” “); } } } |
Output :
Union of the two arrays: 1 2 3 4 5 6 |
19. Write a program to find the missing positive integer in an unsorted array?
import java.util.Arrays; public class MissingPositiveInteger { public static int findMissingPositive(int[] arr) { int n = arr.length; for (int i = 0; i < n; i++) { while (arr[i] > 0 && arr[i] <= n && arr[arr[i] – 1] != arr[i]) { // Swap arr[i] with arr[arr[i] – 1] int temp = arr[i]; arr[i] = arr[arr[i] – 1]; arr[temp – 1] = temp; } } for (int i = 0; i < n; i++) { if (arr[i] != i + 1) { return i + 1; } } return n + 1; } public static void main(String[] args) { int[] array = {3, 4, -1, 1}; int result = findMissingPositive(array); System.out.println(“The smallest missing positive integer is: ” + result); } } |
Output :
The smallest missing positive integer is: 2 |
20. Write a program to find the intersection of three sorted arrays?
import java.util.ArrayList; import java.util.List; public class IntersectionOfThreeSortedArrays { public static List<Integer> intersection(int[] arr1, int[] arr2, int[] arr3) { List<Integer> result = new ArrayList<>(); int i = 0, j = 0, k = 0; while (i < arr1.length && j < arr2.length && k < arr3.length) { if (arr1[i] == arr2[j] && arr2[j] == arr3[k]) { result.add(arr1[i]); i++; j++; k++; } else if (arr1[i] < arr2[j]) { i++; } else if (arr2[j] < arr3[k]) { j++; } else { k++; } } return result; } public static void main(String[] args) { int[] arr1 = {1, 5, 10, 20, 40}; int[] arr2 = {6, 7, 20, 80}; int[] arr3 = {3, 4, 5, 20, 80}; List<Integer> intersectionResult = intersection(arr1, arr2, arr3); System.out.println(“The intersection of the three arrays is: ” + intersectionResult); } } |
Output :
The intersection of the three arrays is: [20] |
21. Write a program to find the missing number in an array of 1 to N?
public class MissingNumber { public static int findMissingNumber(int[] arr, int N) { int expectedSum = N * (N + 1) / 2; int actualSum = 0; for (int num : arr) { actualSum += num; } return expectedSum – actualSum; } public static void main(String[] args) int[] array = {1, 2, 4, 5, 6}; int N = 6; int missingNumber = findMissingNumber(array, N); System.out.println(“The missing number is: ” + missingNumber); } } |
Output :
The missing number is: 3 |
22. Write a program to find the Common Elements in All Rows of a Matrix?
import java.util.HashSet; import java.util.Set; public class CommonElementsInMatrix { public static Set<Integer> findCommonElements(int[][] matrix) { Set<Integer> commonElements = new HashSet<>(); for (int i = 0; i < matrix[0].length; i++) { commonElements.add(matrix[0][i]); } for (int row = 1; row < matrix.length; row++) { Set<Integer> currentRowSet = new HashSet<>(); for (int col = 0; col < matrix[row].length; col++) { currentRowSet.add(matrix[row][col]); } commonElements.retainAll(currentRowSet); } return commonElements; } public static void main(String[] args) { int[][] matrix = { {1, 2, 3, 4}, {2, 3, 4, 5}, {3, 4, 6, 7} }; Set<Integer> common = findCommonElements(matrix); System.out.println(“The common elements in all rows are: ” + common); } } |
Output :
The common elements in all rows are: [3, 4] |
23. Write a program to find the element that occurs more than n/3 times?
import java.util.HashMap; import java.util.Map; public class ElementOccursMoreThanNby3 { public static void findElement(int[] arr) { int n = arr.length; int threshold = n / 3; Map<Integer, Integer> frequencyMap = new HashMap<>(); for (int num : arr) { frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1); } boolean found = false; for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) { if (entry.getValue() > threshold) { System.out.println(“Element ” + entry.getKey() + ” occurs more than n/3 times.”); found = true; } } if (!found) { System.out.println(“No element occurs more than n/3 times.”); } } public static void main(String[] args) { int[] array = {3, 3, 4, 2, 4, 4, 2, 4, 4}; findElement(array); } } |
Output :
Element 4 occurs more than n/3 times. |
24. Write a program to find the Longest Palindromic Subsequence in an Array?
public class LongestPalindromicSubsequence { public static int longestPalindromicSubsequence(int[] arr) { int n = arr.length; int[][] dp = new int[n][n]; for (int i = 0; i < n; i++) { dp[i][i] = 1; } for (int len = 2; len <= n; len++) { for (int i = 0; i < n – len + 1; i++) { int j = i + len – 1; if (arr[i] == arr[j]) { dp[i][j] = dp[i + 1][j – 1] + 2; } else { dp[i][j] = Math.max(dp[i + 1][j], dp[i][j – 1]); } } } return dp[0][n – 1]; } public static void main(String[] args) { int[] array = {1, 2, 3, 2, 1}; int result = longestPalindromicSubsequence(array); System.out.println(“The length of the longest palindromic subsequence is: ” + result); } } |
Output :
The length of the longest palindromic subsequence is: 5 |
25. Write a program to find the sum of diagonal elements in a matrix?
public class DiagonalSum { public static int sumOfDiagonals(int[][] matrix) { int n = matrix.length; int sum = 0; for (int i = 0; i < n; i++) { sum += matrix[i][i]; if (i != n – i – 1) { sum += matrix[i][n – i – 1]; } } return sum; } public static void main(String[] args) { int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int result = sumOfDiagonals(matrix); System.out.println(“The sum of diagonal elements is: ” + result); } } |
Output :
The sum of diagonal elements is: 25 |