0% found this document useful (0 votes)
207 views

Java Array Interview Questions

The document contains 9 questions related to arrays in Java. The questions cover topics such as finding duplicate elements in an array, finding the second largest element in an array, finding the maximum consecutive ones in a binary array, finding all pairs of elements whose sum equals a given number, finding a continuous subarray whose sum equals a given number, finding the intersection of two arrays, counting the occurrences of each element in an array, and finding the maximum Hamming distance of a rotated array. Sample code solutions are provided for each question.

Uploaded by

Muhammad Haseeb
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
207 views

Java Array Interview Questions

The document contains 9 questions related to arrays in Java. The questions cover topics such as finding duplicate elements in an array, finding the second largest element in an array, finding the maximum consecutive ones in a binary array, finding all pairs of elements whose sum equals a given number, finding a continuous subarray whose sum equals a given number, finding the intersection of two arrays, counting the occurrences of each element in an array, and finding the maximum Hamming distance of a rotated array. Sample code solutions are provided for each question.

Uploaded by

Muhammad Haseeb
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Interview Questions in Array

Question#01:
Write a java program to find duplicate elements in an array?
import java.util.HashMap;

import java.util.Map;

public class FindDuplicates {

public static void main(String[] args) {

int[] array = { 1, 2, 3, 4, 5, 3, 6, 7, 2, 8, 9, 5, 10, 11, 12, 9 };

Map<Integer, Integer> elementCount = new HashMap<>();

// Count occurrences of each element in the array

for (int num : array) {

if (elementCount.containsKey(num)) {

int count = elementCount.get(num);

elementCount.put(num, count + 1);

} else {

elementCount.put(num, 1);

// Print duplicate elements

System.out.println("Duplicate elements in the array are:");

for (Map.Entry<Integer, Integer> entry : elementCount.entrySet()) {

if (entry.getValue() > 1) {

System.out.println(entry.getKey());
}

Qusetion#02:
Write a java program to find second largest element in an array of integers?
public class SecondLargestElement {

public static void main(String[] args) {

int[] array = { 10, 6, 8, 3, 15, 7, 9, 4, 11 };

int secondLargest = findSecondLargest(array);

System.out.println("The second largest element in the array is: " + secondLargest);

public static int findSecondLargest(int[] array) {

int largest = Integer.MIN_VALUE;

int secondLargest = Integer.MIN_VALUE;

// Find the largest and second largest elements in the array

for (int num : array) {

if (num > largest) {

secondLargest = largest;

largest = num;

} else if (num > secondLargest && num != largest) {

secondLargest = num;

}
}

return secondLargest;

Question#03:
Maximum consecutive one's (or zeros) in a binary array?

To find the maximum consecutive ones (or zeros) in a binary array, you can use a simple loop to
traverse the array and keep track of the current consecutive count and the maximum
consecutive count found so far. Here's a Java program to find the maximum consecutive ones in
a binary array:

Program:

public class MaxConsecutiveOnes {

public static void main(String[] args) {

int[] binaryArray = {1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1};

int maxConsecutiveOnes = findMaxConsecutiveOnes(binaryArray);

System.out.println("Maximum consecutive ones: " + maxConsecutiveOnes);

public static int findMaxConsecutiveOnes(int[] nums) {

int maxConsecutiveOnes = 0;

int currentConsecutiveOnes = 0;

for (int num : nums) {

if (num == 1) {
currentConsecutiveOnes++;

maxConsecutiveOnes = Math.max(maxConsecutiveOnes, currentConsecutiveOnes);

} else {

currentConsecutiveOnes = 0;

return maxConsecutiveOnes;

Similarly, you can find the maximum consecutive zeros by modifying the condition
inside the loop to check for num == 0.

For example, if you have the binary array {1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1}, the program
will output:

Maximum consecutive ones: 4

Question#04:
Write a java program to find all the pairs of elements in an integer array whose sum is equal
to given number?
import java.util.HashMap;

import java.util.Map;

public class FindPairsWithSum {

public static void main(String[] args) {

int[] array = { 2, 4, 6, 8, 10, 12, 14, 16 };


int targetSum = 20;

findPairsWithSum(array, targetSum);

public static void findPairsWithSum(int[] nums, int targetSum) {

Map<Integer, Integer> map = new HashMap<>();

for (int num : nums) {

int complement = targetSum - num;

if (map.containsKey(complement)) {

System.out.println("Pair: " + num + ", " + complement);

map.put(num, num);

For example, if you have the integer array {2, 4, 6, 8, 10, 12, 14, 16} and the target sum is 20, the
program will output:

Pair: 10, 10

Pair: 12, 8

Question#05:
Write a java program to find continuous sub array whose sum is equal to a given
number?
public class FindSubarrayWithSum {
public static void main(String[] args) {

int[] array = { 1, 4, 20, 3, 10, 5 };

int targetSum = 33;

findSubarrayWithSum(array, targetSum);

public static void findSubarrayWithSum(int[] nums, int targetSum) {

int startIndex = 0;

int currentSum = nums[0];

for (int i = 1; i <= nums.length; i++) {

while (currentSum > targetSum && startIndex < i - 1) {

currentSum -= nums[startIndex];

startIndex++;

if (currentSum == targetSum) {

System.out.println("Subarray with the sum " + targetSum + " found from index " + startIndex + "
to " + (i - 1));

return;

if (i < nums.length) {

currentSum += nums[i];

}
System.out.println("No subarray found with the sum " + targetSum);

For example, if you have the integer array {1, 4, 20, 3, 10, 5} and the target sum is 33, the
program will output:

Subarray with the sum 33 found from index 2 to 4.

Question#06:
Write a java program to find intersection between two arrays?
import java.util.HashSet;

import java.util.Set;

public class ArrayIntersection {

public static void main(String[] args) {

int[] array1 = { 1, 2, 4, 5, 7 };

int[] array2 = { 2, 5, 8, 9 };

int[] intersection = findIntersection(array1, array2);

System.out.println("Intersection of the two arrays:");

for (int num : intersection) {

System.out.print(num + " ");

public static int[] findIntersection(int[] arr1, int[] arr2) {

Set<Integer> set = new HashSet<>();


for (int num : arr1) {

set.add(num);

Set<Integer> intersectionSet = new HashSet<>();

for (int num : arr2) {

if (set.contains(num)) {

intersectionSet.add(num);

int[] intersection = new int[intersectionSet.size()];

int index = 0;

for (int num : intersectionSet) {

intersection[index++] = num;

return intersection;

Question#07:
Write a java program to find intersection between two arrays?
import java.util.HashSet;

import java.util.Set;

public class ArrayIntersection {


public static void main(String[] args) {

int[] array1 = { 1, 2, 4, 5, 7 };

int[] array2 = { 2, 5, 8, 9 };

int[] intersection = findIntersection(array1, array2);

System.out.println("Intersection of the two arrays:");

for (int num : intersection) {

System.out.print(num + " ");

public static int[] findIntersection(int[] arr1, int[] arr2) {

Set<Integer> set = new HashSet<>();

for (int num : arr1) {

set.add(num);

Set<Integer> intersectionSet = new HashSet<>();

for (int num : arr2) {

if (set.contains(num)) {

intersectionSet.add(num);

int[] intersection = new int[intersectionSet.size()];

int index = 0;

for (int num : intersectionSet) {

intersection[index++] = num;
}

return intersection;

Question#08:
Write a java program to count occurrences of each element in an array?
import java.util.HashMap;

import java.util.Map;

public class CountOccurrences {

public static void main(String[] args) {

int[] array = { 2, 4, 5, 2, 6, 4, 7, 2, 8, 4, 9, 5 };

Map<Integer, Integer> elementCount = countOccurrences(array);

System.out.println("Occurrences of each element in the array:");

for (Map.Entry<Integer, Integer> entry : elementCount.entrySet()) {

System.out.println(entry.getKey() + " occurs " + entry.getValue() + " times.");

public static Map<Integer, Integer> countOccurrences(int[] arr) {

Map<Integer, Integer> elementCount = new HashMap<>();


for (int num : arr) {

elementCount.put(num, elementCount.getOrDefault(num, 0) + 1);

return elementCount;

For example, if you have an array {2, 4, 5, 2, 6, 4, 7, 2, 8, 4, 9, 5}, the program


will output:

Occurrences of each element in the array:

2 occurs 3 times.

4 occurs 3 times.

5 occurs 2 times.

6 occurs 1 times.

7 occurs 1 times.

8 occurs 1 times.

9 occurs 1 times.

Question#09:
Find a rotation with maximum hamming distance?
public class MaxHammingDistanceRotation {

public static void main(String[] args) {

int[] array = { 2, 4, 6, 8 };

int maxHammingDistance = findMaxHammingDistanceRotation(array);

System.out.println("Maximum Hamming distance: " + maxHammingDistance);


}

public static int findMaxHammingDistanceRotation(int[] arr) {

int n = arr.length;

int maxHammingDistance = 0;

// Create a duplicate array to rotate

int[] rotatedArray = new int[n];

System.arraycopy(arr, 0, rotatedArray, 0, n);

// Check all possible rotations and calculate Hamming distance

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

int hammingDistance = 0;

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

if (arr[j] != rotatedArray[j]) {

hammingDistance++;

maxHammingDistance = Math.max(maxHammingDistance, hammingDistance);

// Rotate the array by one position

int temp = rotatedArray[0];

System.arraycopy(rotatedArray, 1, rotatedArray, 0, n - 1);

rotatedArray[n - 1] = temp;

return maxHammingDistance;

}
For example, if you have an array {2, 4, 6, 8}, the program will output:

Maximum Hamming distance: 4

In this case, the maximum Hamming distance is achieved when the array is rotated by 2
positions to become {6, 8, 2, 4}.

Question#10:
Count distinct element in every k size window?
import java.util.HashMap;

import java.util.Map;

public class CountDistinctInWindow {

public static void main(String[] args) {

int[] array = { 1, 2, 1, 3, 4, 2, 3 };

int k = 4;

countDistinctInWindow(array, k);

public static void countDistinctInWindow(int[] arr, int k) {

Map<Integer, Integer> elementCount = new HashMap<>();

// Process the first window of size k

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

elementCount.put(arr[i], elementCount.getOrDefault(arr[i], 0) + 1);

}
// Print the count of distinct elements in the first window

System.out.println("Window 0: " + elementCount.size());

// Process the remaining windows

for (int i = k; i < arr.length; i++) {

// Remove the first element of the previous window

int firstElement = arr[i - k];

if (elementCount.get(firstElement) == 1) {

elementCount.remove(firstElement);

} else {

elementCount.put(firstElement, elementCount.get(firstElement) - 1);

// Add the new element in the current window

elementCount.put(arr[i], elementCount.getOrDefault(arr[i], 0) + 1);

// Print the count of distinct elements in the current window

System.out.println("Window " + (i - k + 1) + ": " + elementCount.size());

For example, if you have an array {1, 2, 1, 3, 4, 2, 3} and k = 4, the program will
output:

Window 0: 3
Window 1: 3
Window 2: 3
Window 3: 3
Window 4: 4
Question#11:
Print duplicate characters from a string?
import java.util.HashMap;

import java.util.Map;

public class PrintDuplicateCharacters {

public static void main(String[] args) {

String inputString = "Hello, World!";

printDuplicateCharacters(inputString);

public static void printDuplicateCharacters(String str) {

Map<Character, Integer> charCount = new HashMap<>();

// Count occurrences of each character in the string

for (char ch : str.toCharArray()) {

if (Character.isLetter(ch) || Character.isDigit(ch)) { // Ignore non-alphanumeric characters

charCount.put(ch, charCount.getOrDefault(ch, 0) + 1);

// Print characters with count greater than 1 (i.e., duplicates)

System.out.println("Duplicate characters in the string:");

for (Map.Entry<Character, Integer> entry : charCount.entrySet()) {

if (entry.getValue() > 1) {
System.out.println(entry.getKey() + " - " + entry.getValue() + " occurrences");

For example, if you have the input string "Hello, World!", the program will output:

Duplicate characters in the string:

l - 3 occurrences

o - 2 occurrences

Question#12:
Check if two strings are anagrams or not?
import java.util.HashMap;

import java.util.Map;

public class AnagramChecker {

public static void main(String[] args) {

String str1 = "listen";

String str2 = "silent";

boolean areAnagrams = checkAnagrams(str1, str2);

if (areAnagrams) {
System.out.println("The two strings are anagrams.");

} else {

System.out.println("The two strings are not anagrams.");

public static boolean checkAnagrams(String str1, String str2) {

if (str1.length() != str2.length()) {

return false;

Map<Character, Integer> charCount = new HashMap<>();

// Count occurrences of characters in the first string

for (char ch : str1.toCharArray()) {

charCount.put(ch, charCount.getOrDefault(ch, 0) + 1);

// Check occurrences of characters in the second string

for (char ch : str2.toCharArray()) {

int count = charCount.getOrDefault(ch, 0);

if (count == 0) {

return false;

charCount.put(ch, count - 1);

// If all characters have been matched, the strings are anagrams

return true;
}

Question#13:
Check for balanced brackets?
import java.util.Stack;

public class BalancedBracketsChecker {

public static void main(String[] args) {

String inputString1 = "{[()]}";

String inputString2 = "{[(])}";

String inputString3 = "{{[[(())]]}}";

System.out.println(inputString1 + " is " + (isBalancedBrackets(inputString1) ? "balanced" : "not


balanced"));

System.out.println(inputString2 + " is " + (isBalancedBrackets(inputString2) ? "balanced" : "not


balanced"));

System.out.println(inputString3 + " is " + (isBalancedBrackets(inputString3) ? "balanced" : "not


balanced"));

public static boolean isBalancedBrackets(String str) {

Stack<Character> stack = new Stack<>();

for (char ch : str.toCharArray()) {

if (ch == '(' || ch == '[' || ch == '{') {

stack.push(ch);

} else if (ch == ')' || ch == ']' || ch == '}') {


if (stack.isEmpty()) {

return false; // Unbalanced closing bracket

char top = stack.pop();

if (!((ch == ')' && top == '(') || (ch == ']' && top == '[') || (ch == '}' && top == '{'))) {

return false; // Mismatched brackets

return stack.isEmpty(); // If the stack is empty, all brackets are balanced

For example, if you have the strings "{[()]}", "{[(])}", and "{{[[(())]]}}", the program will
output:

{[()]} is balanced

{[(])} is not balanced

{{[[(())]]}} is balanced

Question#14:
Count number of substrings?
To count the number of substrings in a given string, you can use the following formula:

Number of substrings = n*(n+1)/2

where "n" is the length of the string.


Here's a Java program to calculate the number of substrings in a given string:

public class CountSubstrings {

public static void main(String[] args) {

String inputString = "abcde";

int numberOfSubstrings = countSubstrings(inputString);

System.out.println("Number of substrings: " + numberOfSubstrings);

public static int countSubstrings(String str) {

int n = str.length();

return n * (n + 1) / 2;

In this program, we have a function countSubstrings that takes a string as input and
calculates the number of substrings using the formula mentioned above.

For example, if you have the string "abcde", the program will output:

Number of substrings: 15

This means there are 15 substrings in the string "abcde": "a", "b", "c", "d", "e", "ab", "bc",
"cd", "de", "abc", "bcd", "cde", "abcd", "bcde", and "abcde".

Question#15:
Check if a string is a rotated palindrome or not?
To check if a string is a rotated palindrome, we can follow these steps:
1. Concatenate the input string with itself to create a new string that contains all possible rotations of
the original string.

2. For each rotation of the original string in the new string, check if it is a palindrome.

If any of the rotations are palindromes, then the original string is a rotated palindrome. Otherwise, it is
not.

Here's a Java program to implement the above logic:

```java

public class RotatedPalindromeChecker {

public static void main(String[] args) {

String inputString = "noon";

boolean isRotatedPalindrome = isRotatedPalindrome(inputString);

if (isRotatedPalindrome) {

System.out.println("The string is a rotated palindrome.");

} else {

System.out.println("The string is not a rotated palindrome.");

public static boolean isRotatedPalindrome(String str) {

// Concatenate the input string with itself to create all possible rotations

String rotatedString = str + str;

// Check if any rotation is a palindrome


for (int i = 0; i < str.length(); i++) {

if (isPalindrome(rotatedString.substring(i, i + str.length()))) {

return true;

return false;

public static boolean isPalindrome(String str) {

int left = 0;

int right = str.length() - 1;

while (left < right) {

if (str.charAt(left) != str.charAt(right)) {

return false;

left++;

right--;

return true;

```

In this program, we have a function `isRotatedPalindrome`, which takes a string as input and checks if it
is a rotated palindrome. It concatenates the input string with itself to create all possible rotations and
then checks each rotation for palindrome property using the `isPalindrome` function.
The `isPalindrome` function checks if a given string is a palindrome. It uses two pointers (`left` and
`right`) to compare characters from the beginning and end of the string until they meet at the center.

For example, if you have the string "noon", the program will output:

To check if a string is a rotated palindrome, we can follow these steps:

1. Concatenate the input string with itself to create a new string that contains all possible rotations of
the original string.

2. For each rotation of the original string in the new string, check if it is a palindrome.

If any of the rotations are palindromes, then the original string is a rotated palindrome. Otherwise, it is
not.

Here's a Java program to implement the above logic:

```java
public class RotatedPalindromeChecker {

public static void main(String[] args) {

String inputString = "noon";

boolean isRotatedPalindrome = isRotatedPalindrome(inputString);

if (isRotatedPalindrome) {

System.out.println("The string is a rotated palindrome.");

} else {

System.out.println("The string is not a rotated palindrome.");

public static boolean isRotatedPalindrome(String str) {


// Concatenate the input string with itself to create all possible rotations

String rotatedString = str + str;

// Check if any rotation is a palindrome

for (int i = 0; i < str.length(); i++) {

if (isPalindrome(rotatedString.substring(i, i + str.length()))) {

return true;

return false;

public static boolean isPalindrome(String str) {

int left = 0;

int right = str.length() - 1;

while (left < right) {

if (str.charAt(left) != str.charAt(right)) {

return false;

left++;

right--;

return true;

```
In this program, we have a function `isRotatedPalindrome`, which takes a string as input and checks if it
is a rotated palindrome. It concatenates the input string with itself to create all possible rotations and
then checks each rotation for palindrome property using the `isPalindrome` function.

The `isPalindrome` function checks if a given string is a palindrome. It uses two pointers (`left` and
`right`) to compare characters from the beginning and end of the string until they meet at the center.

For example, if you have the string "noon", the program will output:

```
The string is a rotated palindrome.
```

Since "noon" is a palindrome and its rotations "onon" and "noon" are also palindromes, it is a rotated
palindrome.is a rotated palindrome.

```

Since "noon" is a palindrome and its rotations "onon" and "noon" are also palindromes, it is a rotated
palindrome.

Question#16:
Find all possible palindromic substring of a string?
import java.util.ArrayList;

import java.util.List;

public class PalindromicSubstrings {

public static void main(String[] args) {


String inputString = "abbaaabb";

List<String> palindromicSubstrings = findAllPalindromicSubstrings(inputString);

System.out.println("Palindromic Substrings:");

for (String substring : palindromicSubstrings) {

System.out.println(substring);

public static List<String> findAllPalindromicSubstrings(String str) {

List<String> palindromicSubstrings = new ArrayList<>();

for (int i = 0; i < str.length(); i++) {

// Check for odd-length palindromes

findPalindromes(str, i, i, palindromicSubstrings);

// Check for even-length palindromes

findPalindromes(str, i, i + 1, palindromicSubstrings);

return palindromicSubstrings;

public static void findPalindromes(String str, int left, int right, List<String> result) {

while (left >= 0 && right < str.length() && str.charAt(left) == str.charAt(right)) {

result.add(str.substring(left, right + 1));

left--;

right++;

}
}

For example, if you have the string "abbaaabb", the program will output:

Palindromic Substrings:

bb

abb

aabbaa

Question#17:
Find the longest substrings of a string containing distinct characters?
import java.util.HashMap;

import java.util.Map;
public class LongestDistinctSubstring {

public static void main(String[] args) {

String inputString = "abcaabbcd";

String longestDistinctSubstring = findLongestDistinctSubstring(inputString);

System.out.println("Longest distinct substring: " + longestDistinctSubstring);

public static String findLongestDistinctSubstring(String str) {

int n = str.length();

int maxLength = 0;

int start = 0;

int end = 0;

int maxStart = 0;

Map<Character, Integer> charIndexMap = new HashMap<>();

while (end < n) {

char ch = str.charAt(end);

if (charIndexMap.containsKey(ch) && charIndexMap.get(ch) >= start) {

// Character repeats, move the start pointer to its next position

start = charIndexMap.get(ch) + 1;

charIndexMap.put(ch, end);

int currentLength = end - start + 1;

if (currentLength > maxLength) {


maxLength = currentLength;

maxStart = start;

end++;

return str.substring(maxStart, maxStart + maxLength);

For example, if you have the input string "abcaabbcd", the program will output:

Longest distinct substring: abc

Question#18:
Determine whether a string is a palindrome or not?
public class PalindromeChecker {

public static void main(String[] args) {

String inputString1 = "level";

String inputString2 = "hello";

System.out.println(inputString1 + " is " + (isPalindrome(inputString1) ? "a palindrome" : "not a


palindrome"));

System.out.println(inputString2 + " is " + (isPalindrome(inputString2) ? "a palindrome" : "not a


palindrome"));

}
public static boolean isPalindrome(String str) {

int left = 0;

int right = str.length() - 1;

while (left < right) {

if (str.charAt(left) != str.charAt(right)) {

return false;

left++;

right--;

return true;

For example, if you have the strings "level" and "hello", the program will output:

level is a palindrome
hello is not a palindrome

Question#19:
Find first k non-repeating characters in a string in a single traversal?
import java.util.LinkedHashMap;

import java.util.Map;

public class FirstKNonRepeatingCharacters {


public static void main(String[] args) {

String inputString = "aabbcddee";

int k = 3;

String result = findFirstKNonRepeatingCharacters(inputString, k);

System.out.println("First " + k + " non-repeating characters: " + result);

public static String findFirstKNonRepeatingCharacters(String str, int k) {

Map<Character, Integer> charCountMap = new LinkedHashMap<>();

// Count the occurrences of each character in the string

for (char ch : str.toCharArray()) {

charCountMap.put(ch, charCountMap.getOrDefault(ch, 0) + 1);

// Find the first k non-repeating characters

StringBuilder result = new StringBuilder();

for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {

if (entry.getValue() == 1 && k > 0) {

result.append(entry.getKey());

k--;

return result.toString();

}
For example, if you have the input string "aabbcddee" and k = 3, the program will output:

First 3 non-repeating characters: cde

Question#20:
Check if a repeated subsequence is present in a string or not?
public class RepeatedSubsequenceChecker {

public static void main(String[] args) {

String inputString = "ABCDACBD";

boolean hasRepeatedSubsequence = checkRepeatedSubsequence(inputString);

if (hasRepeatedSubsequence) {

System.out.println("The string has a repeated subsequence.");

} else {

System.out.println("The string does not have a repeated subsequence.");

public static boolean checkRepeatedSubsequence(String str) {

int n = str.length();

boolean[][] dp = new boolean[n][n];

for (int len = 1; len < n; len++) {

for (int i = 0; i < n - len; i++) {

int j = i + len;

if (str.charAt(i) == str.charAt(j) && !dp[i][j]) {


dp[i][j] = true;

} else {

for (int k = i + 1; k < j; k++) {

if (dp[i][k] && dp[k][j]) {

return true;

return false;

For example, if you have the input string "ABCDACBD", the program will output:

The string has a repeated subsequence.

You might also like