Master fundamental Java concepts with these beginner-friendly programs
Find the second largest element in an array.
Write a program to find the second largest element in an array.
[12, 35, 1, 10, 34, 1]
Second Largest: 34
public class SecondLargest {
public static void main(String[] args) {
int[] arr = {12, 35, 1, 10, 34, 1};
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int num : arr) {
if (num > first) {
second = first;
first = num;
} else if (num > second && num != first) {
second = num;
}
}
System.out.println("Second Largest: " + second);
}
}
Check if the array is sorted in ascending order.
Write a program to check if the array is sorted in ascending order.
[1, 2, 3, 4, 5]
Yes, the array is sorted.
public class CheckSortedArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
boolean isSorted = true;
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
isSorted = false;
break;
}
}
if (isSorted)
System.out.println("Yes, the array is sorted.");
else
System.out.println("No, the array is not sorted.");
}
}
Find the missing number in an array from 1 to n+1.
Find the missing number in an array of size n containing numbers from 1 to n+1.
[1, 2, 4, 5, 6]
Missing Number: 3
public class FindMissingNumber {
public static void main(String[] args) {
int[] arr = {1, 2, 4, 5, 6};
int n = arr.length + 1;
int total = n * (n + 1) / 2;
int sum = 0;
for (int num : arr) {
sum += num;
}
int missing = total - sum;
System.out.println("Missing Number: " + missing);
}
}
Remove duplicate elements from an array.
Write a program to remove duplicate elements from an array.
[1, 2, 2, 3, 4, 4, 5]
[1, 2, 3, 4, 5]
import java.util.*;
public class RemoveDuplicates {
public static void main(String[] args) {
int[] arr = {1, 2, 2, 3, 4, 4, 5};
Set<Integer> set = new LinkedHashSet<>();
for (int num : arr) {
set.add(num);
}
System.out.println(set);
}
}
Reverse the elements of an array in-place.
Write a program to reverse the elements of an array in-place.
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
import java.util.Arrays;
public class ReverseArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int start = 0, end = arr.length - 1;
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
System.out.println(Arrays.toString(arr));
}
}
Merge two sorted arrays into one sorted array.
Merge two sorted arrays into one sorted array.
[1, 3, 5], [2, 4, 6]
[1, 2, 3, 4, 5, 6]
import java.util.Arrays;
public class MergeSortedArrays {
public static void main(String[] args) {
int[] a = {1, 3, 5};
int[] b = {2, 4, 6};
int[] merged = new int[a.length + b.length];
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length) {
if (a[i] <= b[j]) {
merged[k++] = a[i++];
} else {
merged[k++] = b[j++];
}
}
while (i < a.length) {
merged[k++] = a[i++];
}
while (j < b.length) {
merged[k++] = b[j++];
}
System.out.println(Arrays.toString(merged));
}
}
Count the number of even and odd elements in an array.
Count the number of even and odd elements in an array.
[1, 2, 3, 4, 5]
Even: 2, Odd: 3
public class CountEvenOdd {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int evenCount = 0, oddCount = 0;
for (int num : arr) {
if (num % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
}
System.out.println("Even: " + evenCount + ", Odd: " + oddCount);
}
}
Find all pairs in the array whose sum equals a given number.
Find all pairs in the array whose sum equals a given number.
Array: [1, 5, 7, -1], Sum = 6
Pairs: (1, 5), (7, -1)
import java.util.HashMap;
public class PairSum {
public static void main(String[] args) {
int[] arr = {1, 5, 7, -1};
int sum = 6;
findPairs(arr, sum);
}
static void findPairs(int[] arr, int sum) {
HashMap map = new HashMap<>();
for (int num : arr) {
int complement = sum - num;
if (map.containsKey(complement)) {
int count = map.get(complement);
for (int i = 0; i < count; i++) {
System.out.println("Pair: (" + complement + ", " + num + ")");
}
}
map.put(num, map.getOrDefault(num, 0) + 1);
}
}
}
Find the element that appears more than n/2 times in the array.
Find the element that appears more than n/2 times.
[3, 3, 4, 2, 3, 3, 5, 3]
Majority Element: 3
public class MajorityElement {
public static void main(String[] args) {
int[] arr = {3, 3, 4, 2, 3, 3, 5, 3};
int majority = findMajorityElement(arr);
if (majority != -1) {
System.out.println("Majority Element: " + majority);
} else {
System.out.println("No Majority Element");
}
}
static int findMajorityElement(int[] arr) {
int count = 0, candidate = -1;
for (int num : arr) {
if (count == 0) {
candidate = num;
}
count += (num == candidate) ? 1 : -1;
}
// Verify the candidate
count = 0;
for (int num : arr) {
if (num == candidate) {
count++;
}
}
return count > arr.length / 2 ? candidate : -1;
}
}
Rotate the array to the right by k steps.
Rotate the array to the right by k steps.
Array: [1, 2, 3, 4, 5, 6, 7], k = 3
[5, 6, 7, 1, 2, 3, 4]
public class RotateArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7};
int k = 3;
rotate(arr, k);
System.out.print("Rotated Array: [");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
if (i != arr.length - 1) System.out.print(", ");
}
System.out.println("]");
}
static void rotate(int[] arr, int k) {
int n = arr.length;
k = k % n; // handle if k > n
reverse(arr, 0, n - 1);
reverse(arr, 0, k - 1);
reverse(arr, k, n - 1);
}
static void reverse(int[] arr, int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
}
Count frequency of each element in an array.
Count frequency of each element in an array.
[10, 20, 20, 10, 10, 20, 5, 20]
10: 3, 20: 4, 5: 1
import java.util.HashMap;
import java.util.Map;
public class CountFrequencies {
public static void main(String[] args) {
int[] arr = {10, 20, 20, 10, 10, 20, 5, 20};
Map frequencyMap = new HashMap<>();
for (int num : arr) {
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}
System.out.print("Frequencies: ");
for (Map.Entry entry : frequencyMap.entrySet()) {
System.out.print(entry.getKey() + ": " + entry.getValue() + ", ");
}
}
}
Find the k-th smallest element in an unsorted array.
Find the k-th smallest element in an unsorted array.
Array: [7, 10, 4, 3, 20, 15], k = 3
Kth Smallest: 7
import java.util.Arrays;
public class KthSmallestElement {
public static void main(String[] args) {
int[] arr = {7, 10, 4, 3, 20, 15};
int k = 3;
Arrays.sort(arr);
System.out.println("Kth Smallest: " + arr[k - 1]);
}
}
Find all leaders in the array (element greater than all to its right).
Find all leaders in the array (element greater than all to its right).
[16, 17, 4, 3, 5, 2]
Leaders: 17, 5, 2
import java.util.ArrayList;
import java.util.Collections;
public class FindLeaders {
public static void main(String[] args) {
int[] arr = {16, 17, 4, 3, 5, 2};
ArrayList leaders = new ArrayList<>();
int maxFromRight = arr[arr.length - 1];
leaders.add(maxFromRight);
for (int i = arr.length - 2; i >= 0; i--) {
if (arr[i] > maxFromRight) {
maxFromRight = arr[i];
leaders.add(maxFromRight);
}
}
Collections.reverse(leaders);
System.out.print("Leaders: ");
for (int leader : leaders) {
System.out.print(leader + ", ");
}
}
}
Find the first repeating element in an array.
Find the first repeating element in an array.
[1, 2, 3, 4, 5, 2, 1]
First Repeating: 2
import java.util.HashSet;
public class FirstRepeatingElement {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 2, 1};
HashSet seen = new HashSet<>();
int firstRepeating = -1;
for (int num : arr) {
if (seen.contains(num)) {
firstRepeating = num;
break;
}
seen.add(num);
}
if (firstRepeating != -1) {
System.out.println("First Repeating: " + firstRepeating);
} else {
System.out.println("No repeating elements found.");
}
}
}
Find a continuous subarray that adds to a given sum.
Find a continuous subarray that adds to a given sum.
Array: [1, 4, 20, 3, 10, 5], Sum = 33
Subarray: [20, 3, 10]
public class SubarrayWithGivenSum {
public static void main(String[] args) {
int[] arr = {1, 4, 20, 3, 10, 5};
int sum = 33;
int currentSum = arr[0], start = 0;
boolean found = false;
for (int i = 1; i <= arr.length; i++) {
// Shrink the window as long as currentSum is greater than sum and start < i-1
while (currentSum > sum && start < i - 1) {
currentSum -= arr[start];
start++;
}
// Check if currentSum equals sum
if (currentSum == sum) {
System.out.print("Subarray: [");
for (int j = start; j < i; j++) {
System.out.print(arr[j]);
if (j < i - 1) System.out.print(", ");
}
System.out.println("]");
found = true;
break;
}
// Add next element if not reached end
if (i < arr.length) {
currentSum += arr[i];
}
}
if (!found) {
System.out.println("No subarray found with given sum.");
}
}
}
Move all 0s to the end of array without changing the order of other elements.
Move all 0s to the end of array without changing the order of other elements.
[0, 1, 0, 3, 12]
[1, 3, 12, 0, 0]
public class MoveZerosToEnd {
public static void main(String[] args) {
int[] arr = {0, 1, 0, 3, 12};
int count = 0; // Count of non-zero elements
// Move all non-zero elements to the front
for (int i = 0; i < arr.length; i++) {
if (arr[i] != 0) {
arr[count++] = arr[i];
}
}
// Fill remaining positions with zero
while (count < arr.length) {
arr[count++] = 0;
}
// Print the modified array
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
if (i < arr.length - 1) System.out.print(", ");
}
System.out.println("]");
}
}
Find the union and intersection of two arrays.
Find the union and intersection of two arrays.
[1, 2, 4], [2, 4, 6]
Union: [1, 2, 4, 6] Intersection: [2, 4]
import java.util.*;
public class UnionIntersection {
public static void main(String[] args) {
int[] arr1 = {1, 2, 4};
int[] arr2 = {2, 4, 6};
Set unionSet = new LinkedHashSet<>();
Set intersectionSet = new LinkedHashSet<>();
// Add elements from first array to union set
for (int num : arr1) {
unionSet.add(num);
}
// For second array, add to union, and if present in first, add to intersection
for (int num : arr2) {
if (!unionSet.add(num)) { // add() returns false if already present
intersectionSet.add(num);
}
}
System.out.println("Union: " + unionSet);
System.out.println("Intersection: " + intersectionSet);
}
}
Find the contiguous subarray within an array with the largest product.
Find the contiguous subarray within an array with the largest product.
[2, 3, -2, 4]
Max Product: 6
public class MaxProductSubarray {
public static void main(String[] args) {
int[] arr = {2, 3, -2, 4};
int maxProduct = maxProductSubarray(arr);
System.out.println("Max Product: " + maxProduct);
}
public static int maxProductSubarray(int[] nums) {
int maxSoFar = nums[0];
int minSoFar = nums[0];
int result = nums[0];
for (int i = 1; i < nums.length; i++) {
int tempMax = maxSoFar;
maxSoFar = Math.max(Math.max(nums[i], maxSoFar * nums[i]), minSoFar * nums[i]);
minSoFar = Math.min(Math.min(nums[i], tempMax * nums[i]), minSoFar * nums[i]);
result = Math.max(result, maxSoFar);
}
return result;
}
}
Replace every element with the greatest element on its right.
Replace every element with the greatest element on its right.
[16, 17, 4, 3, 5, 2]
[17, 5, 5, 5, 2, -1]
public class ReplaceWithGreatestOnRight {
public static void main(String[] args) {
int[] arr = {16, 17, 4, 3, 5, 2};
replaceElements(arr);
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
if (i != arr.length - 1) System.out.print(", ");
}
System.out.println("]");
}
public static void replaceElements(int[] arr) {
int maxRight = -1;
for (int i = arr.length - 1; i >= 0; i--) {
int temp = arr[i];
arr[i] = maxRight;
if (temp > maxRight) {
maxRight = temp;
}
}
}
}
Find the maximum sum of a contiguous subarray.
Write a program to find the maximum sum of a contiguous subarray.
[-2, 1, -3, 4, -1, 2, 1, -5, 4]
Max Sum: 6 (Subarray: [4, -1, 2, 1])
public class KadanesAlgorithm {
public static void main(String[] args) {
int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int maxSum = Integer.MIN_VALUE;
int currentSum = 0;
int start = 0, end = 0, tempStart = 0;
for (int i = 0; i < arr.length; i++) {
currentSum += arr[i];
if (currentSum > maxSum) {
maxSum = currentSum;
start = tempStart;
end = i;
}
if (currentSum < 0) {
currentSum = 0;
tempStart = i + 1;
}
}
System.out.println("Max Sum: " + maxSum + " (Subarray: " + java.util.Arrays.toString(java.util.Arrays.copyOfRange(arr, start, end + 1)) + ")");
}
}