Java Array Coding Problems
Click on any problem to view its solution
Basic Problems
1. Find Largest and Smallest Element in an Array
Given an array, find the maximum and minimum elements.
Example: [10, 5, 20, 8] → Max = 20, Min = 5
public class MinMaxInArray {
public static void findMinMax(int[] arr) {
if (arr == null || arr.length == 0) {
System.out.println("Array is empty");
return;
}
int min = arr[0];
int max = arr[0];
for (int num : arr) {
if (num < min) min = num;
if (num > max) max = num;
}
System.out.println("Max = " + max + ", Min = " + min);
}
public static void main(String[] args) {
int[] arr = {10, 5, 20, 8};
findMinMax(arr); // Output: Max = 20, Min = 5
}
}
2. Reverse an Array
Reverse the elements of an array in place.
Example: [1, 2, 3, 4, 5] → [5, 4, 3, 2, 1]
public class ReverseArray {
public static void reverse(int[] arr) {
int start = 0;
int end = arr.length - 1;
while (start < end) {
// Swap elements
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
reverse(arr);
System.out.println(Arrays.toString(arr)); // Output: [5, 4, 3, 2, 1]
}
}
3. Find Second Largest Number in an Array
Find the second largest element in an array.
Example: [10, 20, 5, 40] → 20
public class SecondLargest {
public static int findSecondLargest(int[] arr) {
if (arr == null || arr.length < 2) {
throw new IllegalArgumentException("Array should have at least two elements");
}
int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
for (int num : arr) {
if (num > first) {
second = first;
first = num;
} else if (num > second && num != first) {
second = num;
}
}
return second;
}
public static void main(String[] args) {
int[] arr = {10, 20, 5, 40};
System.out.println(findSecondLargest(arr)); // Output: 20
}
}
4. Check if an Array is Sorted
Determine if an array is sorted in ascending order.
Example: [1, 2, 3, 4] → true, [3, 1, 2] → false
public class CheckSortedArray {
public static boolean isSorted(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4};
int[] arr2 = {3, 1, 2};
System.out.println(isSorted(arr1)); // Output: true
System.out.println(isSorted(arr2)); // Output: false
}
}
Intermediate Problems
5. Remove Duplicates from Sorted Array
Remove duplicates from a sorted array in place.
Example: [1, 1, 2, 2, 3] → [1, 2, 3]
public class RemoveDuplicates {
public static int removeDuplicates(int[] arr) {
if (arr.length == 0) return 0;
int uniqueIndex = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[uniqueIndex]) {
uniqueIndex++;
arr[uniqueIndex] = arr[i];
}
}
return uniqueIndex + 1;
}
public static void main(String[] args) {
int[] arr = {1, 1, 2, 2, 3};
int newLength = removeDuplicates(arr);
for (int i = 0; i < newLength; i++) {
System.out.print(arr[i] + " "); // Output: 1 2 3
}
}
}
6. Move All Zeros to End of Array
Move all zeros to the end while maintaining the order of other elements.
Example: [0, 1, 0, 3, 12] → [1, 3, 12, 0, 0]
public class MoveZeros {
public static void moveZeros(int[] arr) {
int nonZeroIndex = 0;
// Move all non-zero elements to the front
for (int num : arr) {
if (num != 0) {
arr[nonZeroIndex++] = num;
}
}
// Fill remaining positions with zeros
while (nonZeroIndex < arr.length) {
arr[nonZeroIndex++] = 0;
}
}
public static void main(String[] args) {
int[] arr = {0, 1, 0, 3, 12};
moveZeros(arr);
System.out.println(Arrays.toString(arr)); // Output: [1, 3, 12, 0, 0]
}
}
7. Find the Missing Number in an Array (1 to N)
Find the missing number in an array containing numbers from 1 to N with one missing.
Example: [1, 2, 4, 5] → 3
public class MissingNumber {
public static int findMissing(int[] arr) {
int n = arr.length + 1; // Since one number is missing
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[] arr = {1, 2, 4, 5};
System.out.println(findMissing(arr)); // Output: 3
}
}
8. Find the Intersection of Two Arrays
Find common elements between two arrays.
Example: [1, 2, 3, 4] & [3, 4, 5, 6] → [3, 4]
import java.util.ArrayList;
import java.util.HashSet;
public class ArrayIntersection {
public static ArrayList findIntersection(int[] arr1, int[] arr2) {
HashSet set = new HashSet<>();
ArrayList result = new ArrayList<>();
// Add all elements of first array to set
for (int num : arr1) {
set.add(num);
}
// Check elements of second array
for (int num : arr2) {
if (set.contains(num)) {
result.add(num);
set.remove(num); // To avoid duplicates
}
}
return result;
}
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4};
int[] arr2 = {3, 4, 5, 6};
System.out.println(findIntersection(arr1, arr2)); // Output: [3, 4]
}
}
Advanced Problems
9. Maximum Subarray Sum (Kadane's Algorithm)
Find the contiguous subarray with the largest sum.
Example: [−2,1,−3,4,−1,2,1,−5,4] → Maximum sum is 6 ([4,−1,2,1])
public class MaxSubarray {
public static int maxSubArray(int[] arr) {
int maxSoFar = arr[0];
int maxEndingHere = arr[0];
for (int i = 1; i < arr.length; i++) {
maxEndingHere = Math.max(arr[i], maxEndingHere + arr[i]);
maxSoFar = Math.max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}
public static void main(String[] args) {
int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
System.out.println(maxSubArray(arr)); // Output: 6
}
}
10. Find Pair with Given Sum
Find a pair of numbers in an array that adds up to a given target.
Example: [1, 4, 6, 8], Target = 10 → (4,6)
import java.util.HashSet;
public class PairSum {
public static void findPair(int[] arr, int target) {
HashSet set = new HashSet<>();
for (int num : arr) {
int complement = target - num;
if (set.contains(complement)) {
System.out.println("Pair found: (" + complement + ", " + num + ")");
return;
}
set.add(num);
}
System.out.println("No pair found");
}
public static void main(String[] args) {
int[] arr = {1, 4, 6, 8};
findPair(arr, 10); // Output: Pair found: (4, 6)
}
}
11. Sort Array of 0s, 1s, and 2s (Dutch National Flag)
Sort an array containing only 0s, 1s, and 2s in O(n) time.
Example: [0, 1, 2, 1, 2, 0, 1] → [0, 0, 1, 1, 1, 2, 2]
public class Sort012 {
public static void sort(int[] arr) {
int low = 0, mid = 0, high = arr.length - 1;
while (mid <= high) {
switch (arr[mid]) {
case 0:
// Swap with low
int temp = arr[low];
arr[low] = arr[mid];
arr[mid] = temp;
low++;
mid++;
break;
case 1:
mid++;
break;
case 2:
// Swap with high
temp = arr[mid];
arr[mid] = arr[high];
arr[high] = temp;
high--;
break;
}
}
}
public static void main(String[] args) {
int[] arr = {0, 1, 2, 1, 2, 0, 1};
sort(arr);
System.out.println(Arrays.toString(arr)); // Output: [0, 0, 1, 1, 1, 2, 2]
}
}
12. Find Majority Element in an Array
Find an element that appears more than n/2 times in an array.
Example: [2, 2, 1, 1, 1, 2, 2] → 2
public class MajorityElement {
public static int findMajority(int[] arr) {
int candidate = arr[0];
int count = 1;
// Find potential candidate
for (int i = 1; i < arr.length; i++) {
if (count == 0) {
candidate = arr[i];
count = 1;
} else if (arr[i] == candidate) {
count++;
} else {
count--;
}
}
// Verify candidate
count = 0;
for (int num : arr) {
if (num == candidate) count++;
}
return (count > arr.length / 2) ? candidate : -1;
}
public static void main(String[] args) {
int[] arr = {2, 2, 1, 1, 1, 2, 2};
System.out.println(findMajority(arr)); // Output: 2
}
}
Tricky Puzzle-Based Problems
13. First Non-Repeating Element in an Array
Find the first element that doesn't repeat in the array.
Example: [4, 5, 1, 2, 0, 4] → 5
import java.util.LinkedHashMap;
import java.util.Map;
public class FirstNonRepeating {
public static int findFirstNonRepeating(int[] arr) {
LinkedHashMap countMap = new LinkedHashMap<>();
// Count occurrences
for (int num : arr) {
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
}
// Find first with count 1
for (Map.Entry entry : countMap.entrySet()) {
if (entry.getValue() == 1) {
return entry.getKey();
}
}
return -1; // if none found
}
public static void main(String[] args) {
int[] arr = {4, 5, 1, 2, 0, 4};
System.out.println(findFirstNonRepeating(arr)); // Output: 5
}
}
14. Maximum Product of Two Integers
Find the maximum product of any two integers in an array.
Example: [3, 5, -2, 8, 7] → 56 (8 × 7)
public class MaxProduct {
public static int maxProduct(int[] arr) {
if (arr.length < 2) return -1;
int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE;
int min1 = Integer.MAX_VALUE, 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[] arr = {3, 5, -2, 8, 7};
System.out.println(maxProduct(arr)); // Output: 56
}
}
15. Longest Consecutive Sequence in an Array
Find the length of the longest consecutive elements sequence.
Example: [100, 4, 200, 1, 3, 2] → 4 (Sequence: [1, 2, 3, 4])
import java.util.HashSet;
public class LongestConsecutive {
public static int longestConsecutive(int[] arr) {
HashSet set = new HashSet<>();
for (int num : arr) {
set.add(num);
}
int longestStreak = 0;
for (int num : set) {
if (!set.contains(num - 1)) { // Only check for the smallest element in streak
int currentNum = num;
int currentStreak = 1;
while (set.contains(currentNum + 1)) {
currentNum++;
currentStreak++;
}
longestStreak = Math.max(longestStreak, currentStreak);
}
}
return longestStreak;
}
public static void main(String[] args) {
int[] arr = {100, 4, 200, 1, 3, 2};
System.out.println(longestConsecutive(arr)); // Output: 4
}
}
16. Triplets that Sum to Zero (3-Sum Problem)
Find all unique triplets in the array which gives the sum of zero.
Example: [-1, 0, 1, 2, -1, -4] → [[-1, -1, 2], [-1, 0, 1]]
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ThreeSum {
public static List> threeSum(int[] arr) {
Arrays.sort(arr);
List> result = new ArrayList<>();
for (int i = 0; i < arr.length - 2; i++) {
if (i > 0 && arr[i] == arr[i - 1]) continue; // Skip duplicates
int left = i + 1;
int right = arr.length - 1;
while (left < right) {
int sum = arr[i] + arr[left] + arr[right];
if (sum == 0) {
result.add(Arrays.asList(arr[i], arr[left], arr[right]));
// Skip duplicates
while (left < right && arr[left] == arr[left + 1]) left++;
while (left < right && arr[right] == arr[right - 1]) right--;
left++;
right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return result;
}
public static void main(String[] args) {
int[] arr = {-1, 0, 1, 2, -1, -4};
System.out.println(threeSum(arr)); // Output: [[-1, -1, 2], [-1, 0, 1]]
}
}
17. Median of Two Sorted Arrays
Find the median of two sorted arrays without merging them.
Example: [1, 3] and [2] → 2.0, [1, 2] and [3, 4] → 2.5
public class MedianOfTwoArrays {
public static double findMedian(int[] nums1, int[] nums2) {
if (nums1.length > nums2.length) {
return findMedian(nums2, nums1);
}
int x = nums1.length;
int y = nums2.length;
int low = 0, high = x;
while (low <= high) {
int partitionX = (low + high) / 2;
int partitionY = (x + y + 1) / 2 - partitionX;
int maxLeftX = (partitionX == 0) ? Integer.MIN_VALUE : nums1[partitionX - 1];
int minRightX = (partitionX == x) ? Integer.MAX_VALUE : nums1[partitionX];
int maxLeftY = (partitionY == 0) ? Integer.MIN_VALUE : nums2[partitionY - 1];
int minRightY = (partitionY == y) ? Integer.MAX_VALUE : nums2[partitionY];
if (maxLeftX <= minRightY && maxLeftY <= minRightX) {
if ((x + y) % 2 == 0) {
return (Math.max(maxLeftX, maxLeftY) + Math.min(minRightX, minRightY)) / 2.0;
} else {
return Math.max(maxLeftX, maxLeftY);
}
} else if (maxLeftX > minRightY) {
high = partitionX - 1;
} else {
low = partitionX + 1;
}
}
throw new IllegalArgumentException("Input arrays are not sorted");
}
public static void main(String[] args) {
int[] arr1 = {1, 3};
int[] arr2 = {2};
System.out.println(findMedian(arr1, arr2)); // Output: 2.0
int[] arr3 = {1, 2};
int[] arr4 = {3, 4};
System.out.println(findMedian(arr3, arr4)); // Output: 2.5
}
}