Arrays are one of the first things you learn in Java, they make it easy to store, organize, and work with groups of data. Whether it is a single list of numbers or a multi-layered grid, arrays are everywhere in real-world Java applications. If you are preparing for Software Engineering interviews, you cannot skip arrays. To help you out, we have put together 50 important interview questions on Java Arrays, Multidimensional Arrays, and Array Copying. Each question comes with simple explanations and code examples so you can learn by doing. By the end of this blog, you will have a stronger grasp of arrays and the confidence to tackle interview questions with ease. Let’s get started!
Table of Contents:
Array Interview Questions in Java for Freshers
1. What is an array in Java?
Answer: An array in Java is a container object that holds a fixed number of elements of a single type. The size of an array is determined at the time of creation and cannot be changed later. Example:
class Sol {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[0]); // Output: 1
}
}
2. What is the default value of an array in Java?
Answer: The default value of Numeric arrays is 0. The default value of Boolean arrays is false. The default value of Object arrays is null.
class Sol {
public static void main(String[] args) {
int[] arr = new int[3]; // numeric array, default values = 0
boolean[] flags = new boolean[3]; // boolean array, default values = false
String[] names = new String[3]; // object array, default values = null
// Print default values
System.out.println(arr[0]); // Output: 0
System.out.println(flags[0]); // Output: false
System.out.println(names[0]); // Output: null
}
}
3. How do you declare and initialize an array in Java?
Answer: You can declare and initialize arrays in different ways:
// Declare and initialize together
int[] arr = {1, 2, 3, 4, 5};
// Declare first, initialize later
int[] arr2 = new int[5];
arr2[0] = 10;
arr2[1] = 20;
4. What are the advantages of using arrays in Java?
Answer: Arrays are the most preferred data structure in Java, Python and even in C and C++ and here’s a list of benefits why:
-
- Arrays allow you to store a collection of elements of the same data type in a single structure, making it easier to manage related data.
- Each element in an array is accessed by its index. Java arrays use zero-based indexing, making it quick and easy to access any element by its position.
- Storing data in an array can save memory and prevent the need for creating individual variables for each element. This leads to cleaner and more manageable code, especially for large collections of data.
- Arrays are perfect for iterating through collections of data using loops (like for loops), making batch operations (e.g., summing all elements or applying a transformation) straightforward.
- Arrays have a fixed size, which means their length is determined when they’re created. While this can be limiting (compared to collections like ArrayList), it also ensures that the memory is allocated once and prevents resizing overhead.
5. What are the disadvantages of arrays in Java?
Answer: No doubt arrays are powerful, but still they do have some limitations that developers should be aware of:
-
- Once an array is created, its size cannot be changed. If you need to add more elements, you must create a new array and copy the existing data.
- Arrays can only hold elements of the same type, so you cannot mix integers, strings, or objects in the same array.
- Arrays do not provide direct methods for operations like insertion, deletion, or searching. These tasks need to be implemented manually.
- For more advanced operations and dynamic resizing, Java Collections such as ArrayList or HashMap are usually more suitable.
6. What are the different types of arrays?
Answer: In Java, arrays can be broadly classified into the following types:

-
- Single-Dimensional Array (1D Array) It is the most simplest form of an array, which stores elements in a linear structure. Example: int[] arr = {10, 20, 30, 40};
Array of arrays (rectangular structure) is a commonly used for matrices or tables in Java.
a) Two-Dimensional Array (2D)
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
Java allows arrays that operate in 2 dimension X and Y.
b) Three-Dimensional Array (3D)
int[][][] cube = new int[3][3][3];
c) n-Dimensional Arrays
Java allows arrays with more than 3 dimensions, though they’re rare in practice.
-
- Jagged Array (Ragged Array)
It is a special kind of 2D array in which rows can have different lengths. Example:
int[][] jagged = new int[2][];
jagged[0] = new int[3]; // row 0 has 3 elements
jagged[1] = new int[5]; // row 1 has 5 elements
7. What is ArrayStoreException in Java? When does it occur?
Answer: ArrayStoreException is a runtime exception in Java that occurs when you try to store an element of an incompatible type into an array. Even though arrays in Java are covariant (meaning String[] can be assigned to Object[]), the JVM still checks the actual type at runtime. If you try to insert a wrong type, it will throw an ArrayStoreException. Example:
public class MainClass {
public static void main(String[] args) {
Object[] stringArray = new String[5];
// Allowed: String[] is upcasted to Object[]
stringArray[0] = "Hello"; // Works fine
stringArray[1] = "Java"; // Works fine
// Problem:
stringArray[2] = 100; // Compiles fine, but throws ArrayStoreException at runtime
}
}
Why this happens? At compile time, the compiler sees Object[], so it allows 100 (an Integer). At runtime, the JVM sees that the actual array is of type String[], and inserting an Integer violates type safety so, it throws java.lang.ArrayStoreException. Interview Tip: This is a classic case that demonstrates the difference between compile-time type checking and runtime type checking in Java.
8. Can we pass a negative number as an array size in Java?
Answer: No, we cannot. If you try to create an array with a negative size, the compiler will not complain, but at runtime Java will throw a NegativeArraySizeException. This happens because array size must always be a non-negative integer. Example:
public class MainClass {
public static void main(String[] args) {
int[] array = new int[-5];
// No compile-time error
// Runtime: java.lang.NegativeArraySizeException
}
}
Key points to remember with array size in java:
-
- Array size in Java must be 0 or positive.
- A size of 0 creates an empty array (valid).
- A negative size causes NegativeArraySizeException at runtime.
9. What is the difference between int[] a and int a[] in Java?
Answer: There is no difference between the two. Both are valid ways to declare an integer array in Java.
int[] a; // preferred Java style
int a[]; // valid but C/C++ style
The only difference is readability: int[] a; makes it clear that the type is “array of int”. int a[]; can confuse when declaring multiple variables.
10. Differentiate between Array and ArrayList in Java
Answer: Both Array and ArrayList are used to store collections of elements, but they differ in terms of size, flexibility, and usage.
Array |
ArrayList |
Arrays have a fixed size. Once created, the size cannot be changed. |
ArrayList is dynamic. Its size grows or shrinks as you add or remove elements. |
Can store both primitive types (int, char, etc.) and reference types (objects). |
Can store only objects (reference types). For primitives, wrapper classes like Integer, Double, etc. must be used. |
Syntax: int[] arr = new int[5]; |
Syntax: ArrayList<Integer> list = new ArrayList<>(); |
Performance is faster because arrays are simple and memory-efficient. |
Slightly slower due to dynamic resizing and extra features. |
Does not have built-in methods for insertion, deletion, or searching. |
Provides many built-in methods like add() , remove() , contains() , etc. |
Array Interview Questions in Java for Intermediates
11. What is the time complexity for accessing an element in an array?
Answer: Accessing any element in an array takes O(1) constant time, because arrays use index-based addressing. This means the memory address of any element can be calculated directly using its index, without looping through other elements. Example:
int[] arr = {10, 20, 30, 40};
System.out.println(arr[2]); // Accessing 3rd element -> O(1)
12. How do you check the equality of two arrays in Java?
Answer: To check the equality of two arrays in java you should:
-
- Use Arrays.equals() for one-dimensional arrays.
- Use Arrays.deepEquals() for multi-dimensional arrays.
import java.util.Arrays;
class Demo {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
System.out.println(Arrays.equals(arr1, arr2)); // true
int[][] m1 = {{1, 2}, {3, 4}};
int[][] m2 = {{1, 2}, {3, 4}};
System.out.println(Arrays.deepEquals(m1, m2)); // true
}
}
13. Can an array be resized at runtime?
Answer: No, arrays in Java cannot be resized once created. Their size is fixed at the time of initialization. If you need a dynamic, resizable structure, you should use ArrayList or other Collection Framework classes. Example:
int[] arr = new int[5]; // fixed size
// To "resize", you need to create a new array
int[] newArr = new int[10];
System.arraycopy(arr, 0, newArr, 0, arr.length);
Interview Tip: This limitation is one of the main reasons why ArrayList is often preferred over arrays in real-world projects.
14. What is ArrayIndexOutOfBoundsException in Java and when does it occur?
Answer: ArrayIndexOutOfBoundsException is a runtime exception in Java that occurs when you try to access an array with an invalid index, either a negative index or an index greater than or equal to the array size.
15. What is the difference between shallow copy and deep copy in arrays?
Answer: Shallow copy: Copies only the references, not the actual objects. Changes in one array affect the other. Deep copy: Copies the actual data, so the arrays are completely independent.
16. How do you find duplicate elements in an array in Java?
Answer: There are two common ways to find duplicates in an array:
-Brute Force Method:
-
- Compare each element with every other element.
- Easy to implement but very slow for large arrays.
- Not recommended in real-time applications.
-Using HashSet:
-
- A HashSet only stores unique elements.
- If add() returns false, it means the element is a duplicate.
17. How do you find the second-largest element in an array of integers in Java?
Answer: This is a commonly asked Java interview question for freshers to test logical thinking and understanding of core concepts. The usual expectation is to find the second largest element without using sorting methods or collection classes. The solution should be achieved by iterating through the array only once, while also handling cases where duplicate values exist.
18. How do you find all pairs of elements in an array whose sum is equal to a given number?
Answer: In this problem, you are given an array of integers and a target number. The task is to identify all pairs of elements from the array whose sum is equal to the given number. For example, if the array is {4, 5, 7, 11, 9, 13, 8, 12} and the target number is 20, then the valid pairs are (9, 11), (7, 13), and (8, 12) since each of these pairs adds up to 20.
19. How do you separate zeroes from non-zeroes in an integer array?
Answer: In this problem, you are given an integer array and need to separate all zero elements from the non-zero elements. The zeroes can either be moved to the end of the array or shifted to the beginning. For example, if the given array is {14, 0, 5, 2, 0, 3, 0}, then moving zeroes to the end will result in {14, 5, 2, 3, 0, 0, 0}, while bringing them to the front will result in {0, 0, 0, 14, 5, 2, 3}.
20. How do you find a continuous subarray whose sum is equal to a given number?
Answer: In this problem, you are given an integer array along with a target number, and the task is to find a continuous subarray whose elements add up exactly to the given number. For example, if the array is {12, 5, 31, 9, 21, 8} and the target number is 45, then the subarray {5, 31, 9} is the required solution since its elements sum up to 45.
Array Interview Questions in Java for Advanced
21. What is a multidimensional array in Java?
Answer: A multidimensional array is essentially an array of arrays. It’s commonly used to represent matrices, grids, or tables. In Java, a two-dimensional array is an array where each element itself is a one-dimensional array. You can declare it using multiple square brackets (e.g., int[][]). The sizes can be uniform (rectangular) or jagged (uneven rows).
public class MultidimensionalArray {
public static void main(String[] args) {
int[][] matrix = {{1, 2}, {3, 4}, {5, 6}};
System.out.println("Element at [1][0]: " + matrix[1][0]); //Element at [1][0]: 3
System.out.println("Rows: " + matrix.length); //Rows: 3
System.out.println("Columns in first row: " + matrix[0].length); //Columns in first row: 2
}
}
22. How do you initialize a multidimensional array in Java?
Answer: In Java, a multidimensional array can be initialized in two main ways:
-
-
- Using nested initializers: A concise way to directly assign values.
- Using manual allocation: You define the dimensions first and then assign values element by element.
Any elements not explicitly initialized will take their default values (e.g., 0 for numbers, false for booleans, null for objects).
23. How do you use System.arraycopy() in Java?
Answer: The System.arraycopy() method is a built-in way to quickly copy elements from one array to another. It is faster than manually looping through elements because it is implemented natively.
Syntax:
System.arraycopy(sourceArray, sourcePosition, destinationArray, destinationPosition, length);
sourceArray → the array you are copying from
sourcePosition → starting index in the source array
destinationArray → the array you are copying to
destinationPosition → starting index in the destination array
length → number of elements to copy
Example:
int[] src = {1, 2, 3, 4, 5};
int[] dest = new int[5];
// Copy elements from src to dest
System.arraycopy(src, 0, dest, 0, src.length);
System.out.println(Arrays.toString(dest));
// Output: [1, 2, 3, 4, 5]
24. How do you reverse an array in Java?
Answer: You can reverse an array by swapping elements from both ends until the middle.
import java.util.Arrays;
public class ReverseArray
{
public static void main(String[] args)
{
int[] arr = {1, 2, 3, 4, 5}; int n = arr.length; for (int i = 0; i < n / 2; i++)
{
int temp = arr[i]; arr[i] = arr[n - i - 1]; arr[n - i - 1] = temp;
}
System.out.println(Arrays.toString(arr)); // Output: [5, 4, 3, 2, 1]
}
}
25. How can you find the majority element in an array?
Answer: A majority element is one that appears more than n/2 times in an array of size n. Candidates are expected to solve this using efficient techniques such as the Boyer-Moore voting algorithm or HashMap, avoiding brute-force counting for large arrays.
import java.util.HashMap;
public class MajorityElement {
public static void main(String[] args) {
int[] arr = {2, 2, 1, 1, 2, 2, 3};
HashMap<Integer, Integer> countMap = new HashMap<>();
int n = arr.length;
int majority = -1;
for (int num : arr) {
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
if (countMap.get(num) > n / 2) {
majority = num;
break;
}
}
if (majority != -1) {
System.out.println("Majority element: " + majority);
} else {
System.out.println("No majority element found");
}
}
}
26. How do you initialize a multidimensional array in Java?
Answer: In Java, a multidimensional array can be initialized in two main ways:
-
- Using nested initializers – A concise way to directly assign values.
- Using manual allocation – You define the dimensions first and then assign values element by element.
Any elements not explicitly initialized will take their default values (e.g., 0 for numbers, false for booleans, null for objects).
public class MultiArrayInit {
public static void main(String[] args) {
// Initialization with values
int[][] grid = {{1, 2, 3}, {4, 5, 6}};
// Manual allocation
int[][] table = new int[2][2];
table[0][0] = 10;
table[1][1] = 20;
System.out.println("Grid[0][1]: " + grid[0][1]); // Output: 2
System.out.println("Table[1][1]: " + table[1][1]); // Output: 20
}
}
Try it yourself to know the output of this code!
27. What is a jagged array, and how is it created?
Answer: A jagged array in Java is a type of multidimensional array in which the sub-arrays can have different lengths. Unlike regular two-dimensional arrays that form a rectangular structure, jagged arrays allow each row to hold a different number of elements.
This makes them especially useful when working with irregular data structures, such as storing marks of students where each student may have taken a different number of subjects. To create a jagged array, you first declare the outer array with a fixed number of rows, but without specifying the size of the columns.
Later, you assign each row its own array of any length. For example, in the code below, the first row holds two elements, the second row holds three, and the third row holds only one.
public class JaggedArray {
public static void main(String[] args) {
int[][] jagged = new int[3][];
jagged[0] = new int[] {1, 2};
jagged[1] = new int[] {3, 4, 5};
jagged[2] = new int[] {6};
System.out.println("Jagged[1][2]: " + jagged[1][2]); // Output: 5
System.out.println("Length of row 2: " + jagged[2].length); // Output: 1
}
}
When using jagged arrays, the outer dimension (number of rows) must always be specified at the time of creation, but the inner arrays can be assigned dynamically with different lengths.
This gives you flexibility in memory usage since you don’t need to allocate unnecessary space for unused elements, unlike rectangular arrays where every row must have the same length.
Try running it in Intellipaat’s Online Java Compiler!
28. How can you pass a multidimensional array to a method?
Answer: In Java, you can pass a multidimensional array to a method in the same way as a one-dimensional array, by reference. This means the method does not receive a copy of the array; instead, it works with the actual reference, so any changes made inside the method are reflected in the original array.
The method signature simply uses multiple brackets to represent dimensions (for example, int[][] for a two-dimensional array). If the array is jagged, extra care must be taken to handle rows of varying lengths to avoid runtime errors.
public class PassMultiArray {
public static void modifyMatrix(int[][] matrix) {
matrix[0][0] = 999; // Changes the original array
}
public static void main(String[] args) {
int[][] data = {{1, 2}, {3, 4}};
System.out.println("Before: " + data[0][0]); // Output: 1
modifyMatrix(data);
System.out.println("After: " + data[0][0]); // Output: 999
}
}
29. How can you pass a multidimensional array to a method in Java?
Answer: In Java, multidimensional arrays are passed by reference, just like one-dimensional arrays. The method receives a reference to the same array, so any changes made inside the method will reflect in the original. The method signature uses multiple brackets (e.g., int[][]).
public class PassMultiArray {
public static void modifyMatrix(int[][] matrix) {
matrix[0][0] = 999; // modifies original
}
public static void main(String[] args) {
int[][] data = {{1, 2}, {3, 4}};
System.out.println("Before: " + data[0][0]);
modifyMatrix(data);
System.out.println("After: " + data[0][0]);
}
}
Try running it yourself to know the answer!
30. What are the default values in a multidimensional array in Java?
Answer: In Java, all array elements are automatically initialized to default values based on their type. For Numeric types (int, double, etc.) it is 0. For Boolean it is false. For Reference types (e.g., String) it is null. For example, in an int[][], every element defaults to 0 unless explicitly set.
Example:
public class MultiArrayDefaults {
public static void main(String[] args) {
int[][] array = new int[2][3];
System.out.println("Default value at [0][0]: " + array[0][0]);
System.out.println("Default value at [1][2]: " + array[1][2]);
}
}
31. What is the role of the clone() method in array copying in Java?
Answer: The clone() method creates a shallow copy of an array. For primitive arrays, this behaves like a deep copy since primitive values are duplicated. For object arrays, only the references are copied, so both arrays still point to the same objects. In such cases, extra steps are needed for a true deep copy. Example:
public class ArrayClone {
public static void main(String[] args) {
int[] original = {1, 2, 3};
int[] cloned = original.clone();
cloned[0] = 10;
System.out.println("Original[0]: " + original[0]); // 1
System.out.println("Cloned[0]: " + cloned[0]); // 10
}
}
32. What are the performance considerations when copying large arrays in Java?
Answer: Copying large arrays can be costly in terms of both time and memory. System.arraycopy() is the fastest option because it uses native, low-level optimizations. Arrays.copyOf() and Arrays.copyOfRange() are easier to use but slightly slower since they wrap System.arraycopy(). Manual loops are the least efficient for very large arrays. For multidimensional arrays, deep copies add extra overhead, so they should only be used when independent copies are truly needed.
Example:
public class LargeArrayCopy {
public static void main(String[] args) {
int[] largeArray = new int[1000];
for (int i = 0; i < largeArray.length; i++) {
largeArray[i] = i;
}
int[] copy = new int[largeArray.length];
System.arraycopy(largeArray, 0, copy, 0, largeArray.length);
System.out.println("Copied element 999: " + copy[999]);
}
}
33. Why is the complexity of fetching an element from an array O(1)?
Answer: In an array, elements are stored in contiguous memory locations. If you know the base address (a[0]), the address of the i-th element can be directly calculated using: address(a[i]) = address(a[0]) + i * size_of_element Since this calculation takes the same amount of time regardless of the array size, the time complexity of fetching any element is O(1) (constant time).
34. What do you mean by the terms “Dimension” and “Subscript” in arrays?
Answer: Dimension refers to the number of indices needed to identify an element in the array. A 1D array needs one index, a 2D array needs two, and so on. Subscript is the actual index value used to access an element within that dimension.
For example:
int arr[10][5];
This is a 2-dimensional array. The first dimension has size 10 (valid subscripts: 0–9). The second dimension has size 5 (valid subscripts: 0–4). To access any element, you need two subscripts, e.g., arr[2][3].
35. Find the number of ways to represent N as a sum of two cubes
You are given a positive integer N. Find the number of ordered pairs (A, B) such that: N = A³ + B³ A ≥ 1 B ≥ 0 (A, B) and (B, A) are considered different if A ≠ B Constraints: 1 ≤ T ≤ 10³ 1 ≤ N ≤ 10⁸ Time Limit: 1 sec
Example 1
Input: 1 9
Output: 2
Explanation: There are two valid pairs: (1, 2) → 1³ + 2³ = 9 (2, 1) → 2³ + 1³ = 9 Approach: Iterate A from 1 to cuberoot(N). For each A, calculate B³ = N – A³. If B³ is a perfect cube and B ≥ 0, count (A, B) as a solution.
Solution:
import java.util.Scanner;
public class SumOfCubes {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt(); // number of test cases
while (T-- > 0) {
int N = sc.nextInt();
int count = 0;
int limit = (int) Math.cbrt(N); // max value for A
for (int A = 1; A <= limit; A++) {
int aCube = A * A * A;
int remaining = N - aCube;
if (remaining < 0) continue;
int B = (int) Math.round(Math.cbrt(remaining));
if (B >= 0 && B * B * B == remaining) {
count++;
}
}
System.out.println(count);
}
sc.close();
}
}
36. Maximize the overall focus level in a Chess Tournament
Problem: You are given N rooms at distinct positions in a hotel and C chess players who need to stay in these rooms. Each player must be assigned one room. A player’s focus level = minimum distance to another player’s room. The tournament’s overall focus = minimum focus level across all players. Your task: Assign rooms such that the overall focus is maximized.
Constraints 1 ≤ T ≤ 10 (number of test cases) 2 ≤ C ≤ N ≤ 10^5 1 ≤ position[i] ≤ 10^9
Approach Recap
-
-
- Sort room positions.
- Use binary search on the minimum possible distance (low = 1, high = maxRoom – minRoom).
- Check feasibility: greedily place players in the earliest possible room that is at least dist away from the last placed player.
Java Code:
import java.util.*;
public class ChessTournament {
// Function to check if players can be placed with at least 'dist' apart
public static boolean canPlace(int[] rooms, int players, int dist) {
int count = 1; // place first player
int lastPos = rooms[0];
for (int i = 1; i < rooms.length; i++) {
if (rooms[i] - lastPos >= dist) {
count++;
lastPos = rooms[i];
if (count == players) return true;
}
}
return false;
}
// Binary search to find maximum minimum distance
public static int maxFocus(int[] rooms, int players) {
Arrays.sort(rooms);
int low = 1;
int high = rooms[rooms.length - 1] - rooms[0];
int ans = 0;
while (low <= high) {
int mid = (low + high) / 2;
if (canPlace(rooms, players, mid)) {
ans = mid;
low = mid + 1; // try for bigger distance
} else {
high = mid - 1; // reduce distance
}
}
return ans;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while (T-- > 0) {
int N = sc.nextInt();
int C = sc.nextInt();
int[] rooms = new int[N];
for (int i = 0; i < N; i++) {
rooms[i] = sc.nextInt();
}
System.out.println(maxFocus(rooms, C));
}
sc.close();
}
}
Sample Input: 2 5 3 1 2 3 4 6 4 2 5 4 2 1 Sample Output: 2 4 Time Complexity: O(N log(maxDistance)) Space Complexity: O(1) (excluding input storage)
37. How to sort an array in wave form?
Problem Statement:
You are given an unsorted array ARR of size N. Rearrange it into a wave array such that:
ARR[0] >= ARR[1]
ARR[1] <= ARR[2]
ARR[2] >= ARR[3]
ARR[3] <= ARR[4]
… and so on.
If multiple wave arrays are possible, return any one valid arrangement.
1 <= N <= 10^4
-10^9 <= ARR[i] <= 10^9
Time limit: 1 sec
Input Format:
The first line contains T, the number of test cases.
For each test case:
The first line contains N, the size of the array.
The second line contains N space-separated integers representing the array elements.
Output Format:
For each test case, print a single line containing the rearranged wave array.
Example 1:
Input: 1 5 2 3 1 4 2
Output: 2 1 3 2 4
Follow-up: Try to solve this problem in linear time complexity, i.e., without sorting.
Answer: Approach- Traverse the array at odd indices (i = 1, 3, 5 …). At each odd index i: If ARR[i] > ARR[i-1], swap them. If i + 1 < N and ARR[i] > ARR[i+1], swap them. This ensures the wave property for the entire array in O(N) time.
Java Code:
import java.util.*;
public class WaveArray {
public static void waveSort(int[] arr, int n) {
for (int i = 1; i < n; i += 2) {
if (arr[i] > arr[i - 1]) {
swap(arr, i, i - 1);
}
if (i + 1 < n && arr[i] > arr[i + 1]) {
swap(arr, i, i + 1);
}
}
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while (T-- > 0) {
int N = sc.nextInt();
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = sc.nextInt();
}
waveSort(arr, N);
for (int val : arr) {
System.out.print(val + " ");
}
System.out.println();
}
sc.close();
}
}
Time Complexity: O(N)
Space Complexity: O(1)
38. Maximum Profit from Stock Prices
Problem Statement:
You are given an array prices of size N where each element represents the price of a stock at a particular minute (index represents the minute).
Your task is to find and return the maximum profit you can make by buying and selling the stock only once.
Rules:
You cannot sell a stock before buying it.
You can buy and sell only once.
Constraints:
1 <= T <= 10 (number of test cases)
2 <= N <= 10^4
1 <= prices[i] <= 10^9
Time Limit: 1 second
Input Format:
First line contains T, the number of test cases.
For each test case:
First line contains N, the size of the array.
Second line contains N space-separated integers, representing the stock prices.
Output Format:
For each test case, print the maximum profit achievable.
Example Input:
2
4
1 2 3 4
4
2 2 2 2
Example Output:
3
0
Explanation:
Test case 1: Buy at minute 0 (price 1) and sell at minute 3 (price 4) → profit = 3. Test case 2: No profit possible as prices are constant → profit = 0.
Answer: We can solve this problem in O(N) time with a single pass:
Initialize two variables: minPrice = prices[0] (minimum price seen so far) maxProfit = 0
Traverse the array from left to right: Update minPrice if the current price is lower. Calculate potential profit = currentPrice – minPrice. Update maxProfit if the potential profit is higher. Return maxProfit after the traversal.
Java Code:
import java.util.*;
public class MaxProfitStock {
public static int maximumProfit(int[] prices) {
int minPrice = prices[0];
int maxProfit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] < minPrice) {
minPrice = prices[i]; // update minimum price
}
maxProfit = Math.max(maxProfit, prices[i] - minPrice); // update maximum profit
}
return maxProfit;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while (T-- > 0) {
int N = sc.nextInt();
int[] prices = new int[N];
for (int i = 0; i < N; i++) {
prices[i] = sc.nextInt();
}
System.out.println(maximumProfit(prices));
}
sc.close();
}
}
Time Complexity: O(N) → single pass through the array.
Space Complexity: O(1) → only two extra variables used.
39. First Missing Positive Integer
Problem: Given an unsorted integer array nums, find the smallest missing positive integer.
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
Time complexity: O(N)
Space complexity: O(1)
Input Format: An integer array nums.
Output Format: Return the first missing positive integer.
Example:
Input: [3, 4, -1, 1]
Output: 2
Input: [1, 2, 0]
Output: 3
Technique Used: Cyclic Sort
Java Code:
public class FirstMissingPositive {
public static int firstMissingPositive(int[] nums) {
int n = nums.length;
for (int i = 0; i < n; i++) {
while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) {
// Swap nums[i] with nums[nums[i]-1]
int temp = nums[i];
nums[i] = nums[temp - 1];
nums[temp - 1] = temp;
}
}
for (int i = 0; i < n; i++) {
if (nums[i] != i + 1) {
return i + 1;
}
}
return n + 1;
}
public static void main(String[] args) {
int[] nums = {3, 4, -1, 1};
System.out.println(firstMissingPositive(nums)); // Output: 2
}
}
Time Complexity: O(N)
Space Complexity: O(1)
40. Sort an Array of 0s, 1s, and 2s (Dutch National Flag Problem)
Problem: Given an array containing only 0s, 1s, and 2s, sort the array in-place so that all 0s come first, followed by 1s and then 2s.
Constraints:
1 <= N <= 10^5
Time complexity: O(N)
Space complexity: O(1)
Input Format: An integer array containing only 0, 1, and 2.
Output Format: The same array sorted in ascending order.
Example:
Input: [2, 0, 2, 1, 1, 0]
Output: [0, 0, 1, 1, 2, 2]
Technique Used: Dutch National Flag Algorithm / Two-pointer Approach Java Code:
public class DutchNationalFlag {
public static void sortColors(int[] nums) {
int low = 0, mid = 0, high = nums.length - 1;
while (mid <= high) {
if (nums[mid] == 0) {
int temp = nums[low];
nums[low] = nums[mid];
nums[mid] = temp;
low++;
mid++;
} else if (nums[mid] == 1) {
mid++;
} else { // nums[mid] == 2
int temp = nums[mid];
nums[mid] = nums[high];
nums[high] = temp;
high--;
}
}
}
public static void main(String[] args) {
int[] nums = {2, 0, 2, 1, 1, 0};
sortColors(nums);
System.out.println(Arrays.toString(nums)); // Output: [0, 0, 1, 1, 2, 2]
}
}
Time Complexity: O(N)
Space Complexity: O(1)
Array Coding Interview Questions
41. How to remove duplicates from a sorted array?
Problem: Given a sorted array, you can remove the duplicates in place by using the following method.
import java.util.Arrays;
class Sol {
public int removeDuplicates(int[] nums) {
if (nums.length == 0) return 0; // edge case: empty array
int k = 0; // pointer for unique elements
for (int i = 1; i < nums.length; i++) {
if (nums[k] != nums[i]) {
nums[k + 1] = nums[i];
k++;
}
}
return k + 1; // number of unique elements
}
public static void main(String[] args) {
Sol s = new Sol();
int[] nums = {0,0,1,1,1,2,2,3,3,4};
int k = s.removeDuplicates(nums);
// Print the first k elements (unique part of array)
System.out.println("k = " + k);
System.out.println(Arrays.toString(Arrays.copyOfRange(nums, 0, k)));
}
}
Tip: Use two pointers method to overwrite the duplicates.
42. How to merge two sorted arrays?
Problem: Given two sorted arrays, you can easily merge them into a single sorted array like as follows:
import java.util.Arrays;
class Sol {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int i = m - 1; // last index of valid nums1
int j = n - 1; // last index of nums2
int k = m + n - 1; // last index of nums1 (full size)
while (i >= 0 && j >= 0) {
if (nums1[i] > nums2[j]) {
nums1[k] = nums1[i];
i--;
} else {
nums1[k] = nums2[j];
j--;
}
k--;
}
// If nums2 still has elements left
while (j >= 0) {
nums1[k] = nums2[j];
j--;
k--;
}
}
public static void main(String[] args) {
Sol s = new Sol();
int[] nums1 = {1, 2, 3, 0, 0, 0};
int[] nums2 = {2, 5, 6};
int m = 3, n = 3;
s.merge(nums1, m, nums2, n);
System.out.println(Arrays.toString(nums1));
// Expected output: [1, 2, 2, 3, 5, 6]
}
}
43. How to rotate an array?
Problem: Rotate an array to the right by k steps like as follows:
class Sol {
public void rotate(int[] nums, int k) {
int n = nums.length;
if (n == 0) return;
k = k % n;
reverse(nums, 0, n - k - 1);
reverse(nums, n - k, n - 1);
reverse(nums, 0, n - 1);
}
public static void reverse(int nums[], int start, int end) {
while (start <= end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
public static void main(String[] args) {
Sol obj = new Sol();
int[] arr = {1, 2, 3, 4, 5, 6, 7};
int k = 3;
obj.rotate(arr, k);
// Print rotated array
for (int num : arr) {
System.out.print(num + " ");
}
}
}
44. How to find the missing number?
Problem: Given an array containing n-1 numbers ranging from 1 to n, find the missing number.
class Sol {
public int missingNumber(int[] nums) {
int res = nums.length;
for (int i = 0; i < nums.length; i++) {
res += i - nums[i];
}
return res;
}
public static void main(String[] args) {
Sol obj = new Sol();
int[] arr = {3, 0, 1}; // numbers from 0 to 3, missing = 2
System.out.println("Missing number: " + obj.missingNumber(arr));
}
}
45. How to find the duplicate number in the array?
Problem: Given an array containing n+1 numbers ranging from 1 to n, find the duplicate.
import java.util.Arrays;
class Sol {
public int findDuplicate(int[] nums) {
int n = nums.length;
Arrays.sort(nums); // sort first
for (int i = 0; i < n - 1; i++) { // go until n-2
if (nums[i] == nums[i + 1]) {
return nums[i];
}
}
return -1; // no duplicate found
}
public static void main(String[] args) {
Sol obj = new Sol();
int[] arr = {3, 1, 3, 4, 2}; // duplicate is 3
System.out.println("Duplicate number: " + obj.findDuplicate(arr));
}
}
46. How to find the length of the longest Increasing subsequence?
Problem: Find the length of the longest increasing subsequence in an array.
import java.util.*;
class Sol {
public int lengthOfLIS(int[] nums) {
int n = nums.length;
if (n == 0) return 0;
int[] dp = new int[n];
Arrays.fill(dp, 1); // each element is LIS of length 1
int maxLen = 1;
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
maxLen = Math.max(maxLen, dp[i]);
}
return maxLen;
}
public static void main(String[] args) {
Sol obj = new Sol();
int[] arr = {10, 9, 2, 5, 3, 7, 101, 18};
System.out.println("Length of LIS: " + obj.lengthOfLIS(arr));
}
}
47. How can you find the intersection of two arrays in Java?
Answer: This is a commonly asked question in Java interviews for both freshers and professionals. There are multiple ways to find the common elements between two arrays.
Using Iterative Method: Compare each element of one array with elements of the other array. If a match is found, add it to a HashSet. This approach also works when arrays contain duplicate elements.
Using retainAll() Method: Convert both arrays into HashSet objects and then call the retainAll() method. This retains only the common elements between the two sets.
Example:
import java.util.*;
class Demo {
public static void main(String[] args) {
Integer[] arr1 = {1, 2, 3, 4, 5};
Integer[] arr2 = {3, 4, 5, 6, 7};
// Method 1: Iterative
HashSet<Integer> set = new HashSet<>();
for (int i : arr1) {
for (int j : arr2) {
if (i == j) {
set.add(i);
}
}
}
System.out.println("Intersection using iteration: " + set);
// Method 2: retainAll()
HashSet<Integer> set1 = new HashSet<>(Arrays.asList(arr1));
HashSet<Integer> set2 = new HashSet<>(Arrays.asList(arr2));
set1.retainAll(set2);
System.out.println("Intersection using retainAll(): " + set1);
}
}
Output: Intersection using iteration: [3, 4, 5] Intersection using retainAll(): [3, 4, 5]
48. How can you copy an array using a loop in Java?
Answer: To copy an array using a loop, you first create a new array of the same size (or desired size) and then manually copy each element using its index. This approach is simple and allows flexibility, such as making partial copies or transforming elements during the copy.
Example:
public class ManualCopy {
public static void main(String[] args) {
int[] source = {1, 2, 3, 4};
int[] destination = new int[source.length];
for (int i = 0; i < source.length; i++) {
destination[i] = source[i];
}
System.out.println("Copied element: " + destination[2]); //Copied element: 3
}
}
49. How does the Arrays.copyOf() method work in Java?
Answer: Arrays.copyOf() creates a new array of the size you specify and copies elements from the original into it.
-
-
- If the new size is smaller, the array gets truncated.
- If it’s bigger, the extra slots are filled with default values (0, false, or null).
- It’s a quick way to resize or duplicate an array without writing a manual loop.
Example:
import java.util.Arrays;
public class ArraysCopyOf {
public static void main(String[] args) {
int[] original = {1, 2, 3};
int[] copied = Arrays.copyOf(original, 5);
System.out.println("Length: " + copied.length); // 5
System.out.println("Last element: " + copied[4]); // 0
}
}
50. How can you copy a multidimensional array in Java?
Answer: When you use clone() or Arrays.copyOf() on a multidimensional array, you only get a shallow copy, the outer array is new, but the inner arrays are still references to the originals. To make a deep copy, you need to explicitly copy each sub-array (or do it recursively for higher dimensions). This way, changes in the copy don’t affect the original.
Example:
public class DeepCopyMultiArray {
public static void main(String[] args) {
int[][] source = {{1, 2}, {3, 4}};
int[][] deepCopy = new int[source.length][];
for (int i = 0; i < source.length; i++) {
deepCopy[i] = source[i].clone(); // copy each row
}
deepCopy[0][0] = 99;
System.out.println("Source[0][0]: " + source[0][0]); //1
System.out.println("Copy[0][0]: " + deepCopy[0][0]); //99
}
}