Java Array Interview Questions
Java Array Interview Questions
Java Array Interview Questions
Question#01:
Write a java program to find duplicate elements in an array?
import java.util.HashMap;
import java.util.Map;
if (elementCount.containsKey(num)) {
} else {
elementCount.put(num, 1);
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 {
secondLargest = largest;
largest = num;
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:
int maxConsecutiveOnes = 0;
int currentConsecutiveOnes = 0;
if (num == 1) {
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:
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;
findPairsWithSum(array, targetSum);
if (map.containsKey(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) {
findSubarrayWithSum(array, targetSum);
int startIndex = 0;
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:
Question#06:
Write a java program to find intersection between two arrays?
import java.util.HashSet;
import java.util.Set;
int[] array1 = { 1, 2, 4, 5, 7 };
int[] array2 = { 2, 5, 8, 9 };
set.add(num);
if (set.contains(num)) {
intersectionSet.add(num);
int index = 0;
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;
int[] array1 = { 1, 2, 4, 5, 7 };
int[] array2 = { 2, 5, 8, 9 };
set.add(num);
if (set.contains(num)) {
intersectionSet.add(num);
int index = 0;
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;
int[] array = { 2, 4, 5, 2, 6, 4, 7, 2, 8, 4, 9, 5 };
return elementCount;
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 {
int[] array = { 2, 4, 6, 8 };
int n = arr.length;
int maxHammingDistance = 0;
int hammingDistance = 0;
if (arr[j] != rotatedArray[j]) {
hammingDistance++;
rotatedArray[n - 1] = temp;
return maxHammingDistance;
}
For example, if you have an array {2, 4, 6, 8}, the program will output:
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;
int[] array = { 1, 2, 1, 3, 4, 2, 3 };
int k = 4;
countDistinctInWindow(array, k);
}
// Print the count of distinct elements in the first window
if (elementCount.get(firstElement) == 1) {
elementCount.remove(firstElement);
} else {
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;
printDuplicateCharacters(inputString);
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:
l - 3 occurrences
o - 2 occurrences
Question#12:
Check if two strings are anagrams or not?
import java.util.HashMap;
import java.util.Map;
if (areAnagrams) {
System.out.println("The two strings are anagrams.");
} else {
if (str1.length() != str2.length()) {
return false;
if (count == 0) {
return false;
return true;
}
Question#13:
Check for balanced brackets?
import java.util.Stack;
stack.push(ch);
if (!((ch == ')' && top == '(') || (ch == ']' && top == '[') || (ch == '}' && top == '{'))) {
For example, if you have the strings "{[()]}", "{[(])}", and "{{[[(())]]}}", the program will
output:
{[()]} is 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:
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.
```java
if (isRotatedPalindrome) {
} else {
// Concatenate the input string with itself to create all possible rotations
if (isPalindrome(rotatedString.substring(i, i + str.length()))) {
return true;
return false;
int left = 0;
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:
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.
```java
public class RotatedPalindromeChecker {
if (isRotatedPalindrome) {
} else {
if (isPalindrome(rotatedString.substring(i, i + str.length()))) {
return true;
return false;
int left = 0;
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;
System.out.println("Palindromic Substrings:");
System.out.println(substring);
findPalindromes(str, i, i, palindromicSubstrings);
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)) {
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 {
int n = str.length();
int maxLength = 0;
int start = 0;
int end = 0;
int maxStart = 0;
char ch = str.charAt(end);
start = charIndexMap.get(ch) + 1;
charIndexMap.put(ch, end);
maxStart = start;
end++;
For example, if you have the input string "abcaabbcd", the program will output:
Question#18:
Determine whether a string is a palindrome or not?
public class PalindromeChecker {
}
public static boolean isPalindrome(String str) {
int left = 0;
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;
int k = 3;
result.append(entry.getKey());
k--;
return result.toString();
}
For example, if you have the input string "aabbcddee" and k = 3, the program will output:
Question#20:
Check if a repeated subsequence is present in a string or not?
public class RepeatedSubsequenceChecker {
if (hasRepeatedSubsequence) {
} else {
int n = str.length();
int j = i + len;
} else {
return true;
return false;
For example, if you have the input string "ABCDACBD", the program will output: