Array Program That Can Be Ask in Interview On Java
Array Program That Can Be Ask in Interview On Java
● Explanation: We iterate through the array, keeping track of the largest and
secondLargest elements found so far. We update them accordingly. We also handle edge
cases where all elements might be the same.
2. Check if an Array is Sorted:
● Question: Write a Java program to check if a given array of integers is sorted in
ascending order.
● Answer (Java):
class Solution {
public boolean isSorted(int[] nums) {
if (nums == null || nums.length <= 1) {
return true;
}
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] > nums[i + 1]) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] arr1 = {1, 2, 3, 4, 5};
System.out.println("[1, 2, 3, 4, 5] is sorted: " +
sol.isSorted(arr1)); // Output: true
int[] arr2 = {5, 2, 8, 1, 9};
System.out.println("[5, 2, 8, 1, 9] is sorted: " +
sol.isSorted(arr2)); // Output: false
}
}
● Explanation: We iterate through the array and check if each element is less than or equal
to the next element. If we find any element that is greater than the next, the array is not
sorted.
3. Reverse an Array:
● Question: Write a Java program to reverse a given array of integers in place.
● Answer (Java):
class Solution {
public void reverseArray(int[] nums) {
if (nums == null || nums.length <= 1) {
return;
}
int left = 0;
int right = nums.length - 1;
while (left < right) {
// Swap nums[left] and nums[right]
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] arr = {1, 2, 3, 4, 5};
sol.reverseArray(arr);
System.out.print("Reversed array: ");
for (int num : arr) {
System.out.print(num + " "); // Output: 5 4 3 2 1
}
System.out.println();
}
}
● Explanation: We use two pointers, left starting at the beginning and right starting at the
end. We swap the elements at these pointers and move the pointers towards the center
until they meet or cross.
4. Find the Missing Number in an Array:
● Question: Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the
one number that is missing from the array.
● Answer (Java - using sum):
class Solution {
public int findMissingNumber(int[] nums) {
int n = nums.length;
int expectedSum = n * (n + 1) / 2;
int actualSum = 0;
for (int num : nums) {
actualSum += num;
}
return expectedSum - actualSum;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] arr = {3, 0, 1};
System.out.println("Missing number in [3, 0, 1]: " +
sol.findMissingNumber(arr)); // Output: 2
int[] arr2 = {0, 1};
System.out.println("Missing number in [0, 1]: " +
sol.findMissingNumber(arr2)); // Output: 2
}
}
● Explanation: The sum of numbers from 0 to n is n(n+1)/2. We calculate the actual sum of
the elements in the array and the difference is the missing number.
● Answer (Java - using XOR):
class Solution {
public int findMissingNumberXOR(int[] nums) {
int n = nums.length;
int xorSum = 0;
for (int i = 0; i <= n; i++) {
xorSum ^= i;
}
for (int num : nums) {
xorSum ^= num;
}
return xorSum;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] arr = {3, 0, 1};
System.out.println("Missing number (XOR) in [3, 0, 1]: " +
sol.findMissingNumberXOR(arr)); // Output: 2
}
}
● Explanation: The XOR of a number with itself is 0. We XOR all the numbers from 0 to n
and then XOR all the numbers in the array. The remaining value is the missing number.
5. Remove Duplicates from a Sorted Array:
● Question: Given a sorted array of integers, remove the duplicates in-place such that
each unique element appears only once. The relative order of elements should be kept
the same. Return the new length of the array.
● Answer (Java):
class Solution {
public int removeDuplicates(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int i = 0; // Pointer for the next unique element
for (int j = 1; j < nums.length; j++) {
if (nums[j] != nums[i]) {
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] arr = {1, 1, 2, 2, 3, 4, 4};
int newLength = sol.removeDuplicates(arr);
System.out.print("Array after removing duplicates: ");
for (int k = 0; k < newLength; k++) {
System.out.print(arr[k] + " "); // Output: 1 2 3 4
}
System.out.println("\nNew length: " + newLength); //
Output: 4
}
}
● Explanation: We use two pointers, i to track the position for the next unique element and
j to iterate through the array. If nums[j] is different from nums[i], we increment i and update
nums[i] with nums[j].
6. Move All Zeros to the End of an Array:
● Question: Write a Java program to move all the zeros to the end of a given array while
maintaining the relative order of the non-zero elements.
● Answer (Java):
class Solution {
public void moveZeroes(int[] nums) {
if (nums == null || nums.length <= 1) {
return;
}
int nonZeroIndex = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
// Swap nums[i] with nums[nonZeroIndex]
int temp = nums[nonZeroIndex];
nums[nonZeroIndex] = nums[i];
nums[i] = temp;
nonZeroIndex++;
}
}
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] arr = {0, 1, 0, 3, 12};
sol.moveZeroes(arr);
System.out.print("Array after moving zeroes: ");
for (int num : arr) {
System.out.print(num + " "); // Output: 1 3 12 0 0
}
System.out.println();
}
}
● Explanation: We use a pointer nonZeroIndex to keep track of the position where the next
non-zero element should be placed. We iterate through the array, and if we encounter a
non-zero element, we swap it with the element at nonZeroIndex and increment
nonZeroIndex.
7. Find Pairs with a Given Sum:
● Question: Write a Java program to find all pairs of numbers in a given array whose sum
is equal to a target number.
● Answer (Java - using HashSet for unsorted array):
import java.util.HashSet;
import java.util.Set;
class Solution {
public void findPairsWithSum(int[] nums, int target) {
if (nums == null || nums.length < 2) {
return;
}
Set<Integer> seen = new HashSet<>();
System.out.println("Pairs with sum " + target + ":");
for (int num : nums) {
int complement = target - num;
if (seen.contains(complement)) {
System.out.println("(" + complement + ", " + num +
")");
}
seen.add(num);
}
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] arr = {1, 5, 7, 2, 9, 4};
int targetSum = 6;
sol.findPairsWithSum(arr, targetSum);
// Output:
// Pairs with sum 6:
// (5, 1)
// (4, 2)
}
}
● Explanation: We iterate through the array. For each number, we calculate its complement
needed to reach the target sum. We use a HashSet to keep track of the numbers we've
seen so far. If the complement is in the seen set, we've found a pair.
● Answer (Java - using two pointers for sorted array):
import java.util.Arrays;
class Solution {
public void findPairsWithSumSorted(int[] nums, int target) {
if (nums == null || nums.length < 2) {
return;
}
Arrays.sort(nums);
int left = 0;
int right = nums.length - 1;
System.out.println("Pairs with sum " + target + " (sorted
array):");
while (left < right) {
int currentSum = nums[left] + nums[right];
if (currentSum == target) {
System.out.println("(" + nums[left] + ", " +
nums[right] + ")");
left++;
right--;
} else if (currentSum < target) {
left++;
} else {
right--;
}
}
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] arr = {1, 2, 4, 5, 7, 9};
int targetSum = 6;
sol.findPairsWithSumSorted(arr, targetSum);
// Output:
// Pairs with sum 6 (sorted array):
// (1, 5)
// (2, 4)
}
}
● Explanation: If the array is sorted, we can use the two-pointer approach. We initialize left
at the beginning and right at the end. We adjust the pointers based on whether the current
sum is less than, equal to, or greater than the target.
These are some fundamental array-based questions in Java interviews. Be prepared to discuss
the time and space complexity of your solutions.
Do you have any specific types of array problems you'd like more examples of?