Java Interview Coding problems and solutions - Array


Top 10 java array based coding problems


Array Sorting techniques

In this kind of interview question, we are asked to sort an unsorted array either in ascending or descending order. In some cases, we may be asked not to use any java library to sort an array also we may be used to sort an array using a sorting algorithm on java.

Ascending order

First, let's sort the array in ascending order (low to high). In the below program, we have a number array and iterate each array element, and compare it with the next array element.

if num[i] is larger or equal to num[j] then swap the values using the third temp variable. Repeat the steps till the last elements.


import java.util.Arrays;

public class ArraySort {

	public static void main(String[] args) {
		Integer[] num = { 2, 5, 6, 3, 7, 9, 4, 1, 8 };
		sortInAscendingOrder(num);
	}

	private static void sortInAscendingOrder(Integer[] num) {

		int size = num.length;
		for (int i = 0; i<size; i++) {
			for (int j = i + 1; j<size; j++) {
				if (num[i] >= num[j]) {
					int temp = num[i];
					num[i] = num[j];
					num[j] = temp;
				}
			}
		}
		System.out.println(Arrays.toString(num));
	}
}

Arrays.toString method is used to print our array elements in a formatted manner.

Descending order

Now we are going to sort the array in descending order (high to low). Here we follow the same steps as we did for ascending sorting but only the condition is different.

If arr[i] is lesser than or equal to arr[j], swap the values using the third variable.


import java.util.Arrays;

public class ArraySort {

	public static void main(String[] args) {
		Integer[] num = { 2, 5, 6, 3, 7, 9, 4, 1, 8 };
		sortInDeascendingOrder(num);
	}

	private static void sortInDeascendingOrder(Integer[] num) {

		int size = num.length;
		for (int i = 0; i<size; i++) {
			for (int j = i + 1; j<size; j++) {
				if (num[i]<= num[j]) {
					int temp = num[i];
					num[i] = num[j];
					num[j] = temp;
				}
			}
		}
		System.out.println(Arrays.toString(num));
	}
}

Using Build-in methods

Java has built-in methods to sort arrays in ascending order.

Using the Arrays.sort method to sort the array where Arrays is a pre-defined class in Java to support array operations.


private static void usingArraysLibray(Integer[] num) {
	Arrays.sort(num);
	System.out.println(Arrays.toString(num));
}

Using the Collections.sort method to sort the array, we will convert our array into a list collection by using the Arrays.asList method and sort them.


private static void usingCollections(Integer[] num) {
	Collections.sort(Arrays.asList(num));
	System.out.println(Arrays.toString(num));
}

Write a program to reverse the array

Given an array, we need to reverse it. This problem can be solved using the transverse way and library method

Using transversal

In the below code, we use a temp array to store the reversed array.

First, we have created a temp array with size and calculated the last index of the array stored in the lastIndex variable.

Iterate from the first element and store in a temp array, each time decrementing the lastIndex value by 1.

import java.util.Arrays;

public class ArrayReverse {

	public static void main(String[] args) {
		Integer[] num = { 2, 5, 6, 3, 7, 9, 4, 1 };
		usingTempArray(num);
	}

	private static void usingTempArray(Integer num[]) {
		int[] tempNum = new int[num.length];
		int lastIndex = num.length - 1;

		for (int n: num) {
			tempNum[lastIndex] = n;
			lastIndex--;
		}
		System.out.println(Arrays.toString(tempNum));
	}
}

Using the Collection method

Collections class has a built-in method to reverse collections, using that we can reverse our array.

Convert array to list using Arrays.asList method and pass it to Collections.reverse method


private static void usingCollectionReverse(Integer[] num) {
	List<Integer> list = Arrays.asList(num);
	Collections.reverse(list);
	System.out.println(list);
}

Reverse String

If we are asked to reverse a string or character array, we can follow the below code.

First, we are passing a string with a character array as an argument to StringBuilder.

StringBuilder has a built-in reverse method that reverses the value. Now our StringBuilder values got reversed so converting back to a string using the toString method.

The toCharArray method returns the string value as a character array.


private static void reverse() {
	char letters[] = {'b', 'c', 'd', 'a'};
	StringBuilder str = new StringBuilder(new String(letters));
	letters = str.reverse().toString().toCharArray();
	System.out.println(Arrays.toString(letters));
}

Java interview questions based on string to see more java string questions and solutions and see codingBat problem which helps in improving logical thinking and problem-solving.Coding Bat String Problems and Solutions and Coding Bat Advanced String Problems and Solutions

Print the minimum and maximum values in the array without using the library.

Here we are asked to find the small and large values present in an array. The array can be either sorted or unsorted. Let's see the traverse way to solve the problem.

We create two variables named small and large both having the initial value of num[0];

Now iterating each element (using foreach) in the array we check the below conditions.

  • Compare small with n (array element) if n is smaller or equal to small then assign the value of n to small.
  • Compare the large with n (array element) if n is larger or equal to large then assign the value of n to large.

Repeat the steps till the end of the array.


import java.util.Arrays;

public class LargestAndSmallest {

  public static void main(String[] args) {
    int num[] = new int[] {2, 5, 6, 3, 7, 9, 4, 1};

    usingTraverse(num);
  }

  private static void usingTraverse(int num[]) {
    int small, large;

    small = large = num[0];

    for (int n: num) {
      if (n<small) {
        small = n;
      } else if (n > large) {
        large = n;
      }
    }

    System.out.println("Smallest " + small);
    System.out.println("Largest " + large);
  }
}

Using the Sort method

The next way to solve the problem is to sort the array in ascending order (low to high) so that elements are in the sorted order. The element present in num[0] first index is the smallest and element in num[array size -1] the last index is the largest.

We can use any sorting method used above or Arrays.sort to sort the array in ascending order.


private static void usingSort(int num[]) {
  Arrays.sort(num);
  System.out.println("Smallest " + num[0]);
  System.out.println("Largest " + num[num.length - 1]);
}

Find duplicates in an array

The task is to find duplicates in an array. For example [4, 3, 2, 7, 8, 2, 3, 1] contains 2 and 3 as duplicates because both are present twice in the array. This is because an element can be repeated multiple times in an array.

In the below code we have created two sets, one to store array elements without any duplicates and the second set is used to store duplicate elements.

The reason we are a Java set is it does not allow or store duplicate content. All values stored in set will be distinct, so even if the array contains the same element multiple times the set will have only one element in it.


import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class DuplicateInArray {

  public static void main(String[] args) {
    Integer[] num = { 4, 3, 2, 7, 8, 2, 3, 1 };

    Set<Integer> set1 = new HashSet<>();
    Set<Integer> set2 = new HashSet<>();

    for (Integer i: num) {
      if (set1.contains(i)) {
        set2.add(i);
      } else {
        set1.add(i);
      }
    }

    System.out.println("Array without Duplicate " + set1);
    System.out.println("duplicate elements " + set2);

  }
}

Determine what the missing number is in the integer array of 1 to 100 in Java.

We are given an array containing elements from 1 to 100. One number is missing in the range so our task is to find the missing number in the list.

A simple and easy way to find the missing number is to use the summation formula where the sum of numbers from 1 to n can be calculated by this (n*(n+1)/2) formula where n is the size of the array.

Subtract the sum of array elements from the value obtained using the above formula.

  • First, using the summation formula find the sum of n using (n*(n+1)/2).
  • Iterate array elements and calculate the sum += array[I].
  • Subtract the sum of n - sum of elements.
  • Print it.


public class MissingNumberInArray {

  public static void main(String[] args) {
    Integer[] num = { 2, 5, 6, 3, 7, 9, 4, 1 };

    int n = num.length;
    int sumUsingFormula = ((n + 1) * (n + 2)) / 2;
    int sumofArray = 0;

    for (Integer element: num) {
      sumofArray += element;
    }

    int missingNumber = sumUsingFormula - sumofArray;

    System.out.println("Missing number is " + missingNumber);

  }
}


2D array based problems

Program to add two matrices.

The task is to add two matrices and print the result.

A matrix is a 2D array that has rows and columns where each row contains elements.

Top 10 java 2d array based coding problems


Let A =[aij] and B =[bij] be row × column matrices. The addition of A and B, denoted by A + B, is the row × column matrix that has a[i][j] + b[i][j] elements.



public class MatrixOperation {

	public static void main(String[] args) {

		int[][] arr1 = { { 4, 8 }, { 3, 7 } };

		int[][] arr2 = { { 1, 0 }, { 5, 2 } };

		addition(arr1, arr2);

		int a[][] = { { 1, 3, 4 }, { 2, 4, 3 }, { 3, 4, 5 } };
		int b[][] = { { 1, 3, 4 }, { 2, 4, 3 }, { 1, 2, 4 } };

		addition(a, b);

	}

	private static void addition(int[][] arr1, int[][] arr2) {

		// both array must have same number of row and columns
		if ((arr1.length == arr2.length) && (arr1[0].length == arr2[0].length)) {

			int row = arr1.length;
			int column = arr1[0].length;
			int[][] added = new int[row][column];

			for (int i = 0; i < row; i++) {

				for (int j = 0; j < column; j++) {

					added[i][j] = arr1[i][j] + arr2[i][j];

				}
			}
			toString(added);
		} else {
			System.out.println("Matrix addition is not possible");
		}
	}

	private static void toString(int[][] array) {
		for (int i = 0; i < array.length; ++i) {
			for (int j = 0; j < array[i].length; ++j) {
				System.out.print(array[i][j] + " ");
			}
			System.out.println();
		}
	}
}

In order to find matrix addition or subtraction of two matrices, both must have the same row and column size otherwise we cannot perform matrix addition or subtraction.

Program to subtract two matrices

The task is to subtract two matrices and print the result.

Let A =[aij] and B =[bij] be row × column matrices. The subtraction of A and B, denoted by A - B, is the row × column matrix that has a[i][j] - b[i][j] elements.


public class MatrixOperation {

	public static void main(String[] args) {

		int[][] arr1 = { { 4, 8 }, { 3, 7 } };

		int[][] arr2 = { { 1, 0 }, { 5, 2 } };

		subtraction(arr1, arr2);

	}

	private static void subtraction(int[][] arr1, int[][] arr2) {

		// both array must have same number of row and columns
		if ((arr1.length == arr2.length) && (arr1[0].length == arr2[0].length)) {

			int row = arr1.length;
			int column = arr1[0].length;
			int[][] result = new int[row][column];

			for (int i = 0; i < row; i++) {

				for (int j = 0; j < column; j++) {

					result[i][j] = arr1[i][j] - arr2[i][j];

				}
			}
			toString(result);
		} else {
			System.out.println("Matrix subtraction is not possible");
		}
	}

	private static void toString(int[][] array) {
		for (int i = 0; i < array.length; ++i) {
			for (int j = 0; j < array[i].length; ++j) {
				System.out.print(array[i][j] + " ");
			}
			System.out.println();
		}
	}
}
For more practice try to solve out below problems. 

Coding Bat Array Problems and Solutions

Post a Comment

Previous Post Next Post

Recent Posts

Facebook