You must thoroughly prepare these Array interview questions if you appear for a developer position interview shortly. In this article, we'll cover a thorough list of Array interview questions and answers to guide you to nail the interview.
Here are some crucial Array Interview Questions that" ll boost your confidence.
We'll traverse some of the Array Interview Questions individually for the given three categories :
Array Interview Questions for Freshers
Array Interview Questions for Experienced
Array Coding Interview Questions
Array Interview Questions for Freshers
Here, we will be discussing on beginner level array interview questions.
1. What is an Array in Programming?
An array is a collection of similar data types kept in contiguous memory locations. You must include the array name and the kind of data when declaring an array. By using their index, you can get to various array elements. For instance, you can type arr[4] to access the element at position 4 (the array's fifth element).
2. How do you declare an Array?
In C/C++, DataType ArrayName [size]; and in Java, DataType var-name[] OR type[] var-name;
3. Mention some advantages and disadvantages of Arrays.
Advantages: Arrays represent multiple data items of the same type using a single name. We can quickly retrieve any element using the index in O(1) time. Disadvantages: You must decide in advance how many elements your array will hold because it is impossible to change its size once created. You must move the other elements to fill in or close gaps, which requires worst-case O(n) time.
4. What will happen if an array is not initialised?
In accordance with the data type, the array will accept default values.
5. Is it possible to declare an array without specifying its size?
No, we must specify a size before declaring an array. An error will be generated at compile time if an array is declared without a size.
6. Can you pass a negative integer as an array size?
No, you cannot pass a negative value as the array size. The NegativeArraySizeException will be thrown at runtime if you supply a negative number in the Array size parameter.
7. What is the default value of Array in Java?
Array in Javawill assign default values if we don't define them ourselves. These default values are 0 for byte, short, int, and long has 0 for float and double it is 0.0, false for boolean, and null for objects.
8. How to find the largest element in an unsorted array?
Create a variable and initialise it with the value INT_MIN. Traverse over the array and keep track. If the current element is greater than the variable, update it. Finally, return the element stored in the variable.
int largestElement(int [] arr)
{
int maxi = INT_MIN;
int size= arr.length();
for( int i = 0 ; i < size; i++){
if( arr[i] > maxi)
{
maxi = arr[i];
}
}
return maxi;
9. When will we get an ArrayStoreException?
Runtime exceptions include ArrayStoreException. For instance, if you declare a String Array and then attempt to put integer elements into the array, you will see this exception during runtime.
10. How to linearly search an element in an array?
We will traverse the array and match each element with the element that needs to be searched. If the match is found, display “Target Found”; otherwise, continue the search. Even if the last element of the array does not match, the linear search will be terminated and display “NULL”.
Array Interview Questions for Experienced
11. Difference between Array and Object.
Parameters
Array
Object
Definition
A collection of elements of the same type.
An instance of a class that can hold multiple properties and methods.
Data Type
Arrays are homogeneous; they store elements of the same data type.
Objects are heterogeneous; they can store different types of data and behavior.
Size
Fixed size, defined at the time of creation.
Dynamic size; it can grow or shrink based on the class design.
Memory Allocation
Allocates memory contiguously for all elements.
Allocates memory for each property or method based on the class structure.
Access Method
Accessed using index values.
Accessed using dot notation (e.g., object.property).
Storage
Stores only data.
Can store both data (variables) and behavior (methods).
Flexibility
Limited to a fixed size and type.
More flexible, allowing the use of various methods and properties.
Type of Collection
Primarily used for homogeneous data collection.
Used to represent real-world entities with both state (attributes) and behavior (methods).
12. How to get the index of an array element?
An element's index can be found using a linear or binary search until it locates the match of the desired element, a linear search function loops through every element in an array. It returns the index once it locates the matching element. Consequently, the linear search's temporal complexity is O(n). Both a sorted and an unsorted array can use linear search.
Using a binary search, which divides the array in half until the interval mid matches the required element and provides the index, you can find the element's index if the array is sorted.
mid = low + (high - low)/2;
Consequently, the binary search's temporal complexity is O(log n).
13. What is a Jagged Array in Java?
A jagged array is an array whose elements are arrays, maybe of different sizes. A jagged array is also called an “array of arrays”.
For example :
int [][] jaggedArray = new int [2][ ];
Initialise the elements like this :
jaggedArray[0] = new int [3];
jaggedArray[1] = new int [5];
14. Where in the JVM memory is an Array kept?
JVM has five memory locations, and these memory locations are :
Heap
Stack
PC registers
Execution Engine and
Native method stacks.
In Java, an array is an object. As a result, the Java Virtual Machine stores an array in heap memory. Arrays are reference types, so these are stored in heap areas.
15. How to sort an array of 0 and 1?
Maintain two indexes (i,j), and set the first index to 0 and the second to n-1, respectively. Continue using the technique below till left < right. Continue increasing the left index while there are 0s at it or decreasing the right index while there are 1s at it.
Exchange arr[left] and arr[right] whenever left < right.
You can also use a two-pointers approach. Initialise two variables pointing to the array's first and last element, respectively. Start swapping arr[i] and arr[j] and keep j fixed and incrementing i moving towards j. Repeat till i is not equal to j.
Another method is to store the last element of the array in a variable, and then shift all elements to one position ahead. Replace the first element of the array with the variable you declared.
17. How to move all zeros to the end of the array?
You can use a two-pointer approach. Traverse the array from the first occurrence index of 0. Initialize two variables (i,j). If the element at j index is 0 and element at i index is not 0, swap elements at index i,j. If the element at j index is not 0, then only increment j.
int moveZeroes( int arr[], int n ){
int j=0;
for( int i=0; i<n; i++ ){
if( arr[i]!=0 && arr[j]==0 ){
swap( arr[i] , arr[j] );
}
if( arr[j]!=0 )
j++;
}
}
18. Which is the fastest array sorting algorithm?
Quick-sort is considered the “fastest” sorting algorithm. The time complexity is O(nlog n) in the best case and O(n^2) in the worst case. In quick-sort, we choose a “pivot” and rearrange the array such that all the elements less than pivot are to its left and the elements greater than the pivot are to its right.
19. What are the features of an ArrayList ?
ArrayList is not a fixed data structure; accordingly, there’s no need to mention the size of the ArrayList. ArrayList can be seen as a vector in C++. ArrayList requires more memory to store the elements. Operations such as indexOf() and remove() can be performed on ArrayList.
Declaring the ArrayList with initial size n :
ArrayList<Integer> arrli = new ArrayList<Integer>(n);
20. How to retrieve the class name of an array?
You can use various ways to retrieve the class name of an array. getSimpleName(), getName(), getTypeName() and getCanonicalName() are the methods.
Here, we will be discussing programming array interview questions.
21. How to check the equality of two arrays?
You will be given two arrays, and your task will be to determine whether or not they are equal.
It would help if you first verified the lengths of the two provided arrays. The matching elements of both arrays are compared when their lengths are equal. The two arrays will be regarded as equal if each pair of elements in every correspondence is equal. This approach is not advised to check the equality of two arrays if they are large because it will take a lot of time. You can also use the equals() method in the Arrays class. However, this way will be helpful if the interviewer asks you to compare two arrays without utilizing built-in functions.
Here’s the pseudo code to approach this problem :
bool equality( int arr1[], int arr2[] ){
if( arr1.length()!= arr2.length() )
return false;
sort(arr1); sort(arr2); //sort both arrays
for( int i=0; i< arr1.length(); i++ )
if( arr1[i] != arr2[i] )
return false;
return true; //if all the elements are same
}
22. How to remove a particular element from an array?
Because arrays are fixed sets and their size cannot change, you cannot directly delete elements from the original array. As a result, the interviewer is asking you to propose an alternative solution and handle the problem that the question raises. Making a new array would be the best approach to removing an element. You could duplicate the elements from the first array and only include the element you want to leave out in this array.
Another strategy is to find the target element in the array and then move all the items on the right side back into one position.
Note that we"'ll be only dealing with positive arrays.
Here’s the pseudo code to solve this problem :
int main(){
int key,index = -1;
cin>>key;
for( int i=0; i< n; i++ ){
if( arr[i] == key )
{
index = i;
}
if(index != -1){
for(int i=index; i<n-1 ;i++)
arr[i]= arr[i+1];
for(int i=0; i<n-1;i++)
cout<<arr[i]<<” “;
break;
}
}
if( index == -1 )
cout<<”Element not found”;
}
23. How to find the missing integer in an array of range 1 to 100?
This question is frequently asked during interviews to gauge your understanding of the array manipulation and troubleshooting techniques that programmers may utilise. This question also showcases your problem-solving ability because the solution may depend on the particular items or array structure. Providing solutions for every scenario might impress the interviewer in addition to demonstrating your adaptability and breadth of expertise.
The sum of the series can be computed by applying the following function: n (n + 1) / 2
This function will work if the array has no duplicates or if more than one integer is missing. If an array has duplicate elements, you can sort the array to see if any elements are equal.
24. Compare Arrays with Linked Lists.
Parameters
Array
Linked List
Structure
Fixed-size, contiguous block of memory.
A collection of nodes where each node contains data and a reference to the next node.
Memory Allocation
Allocates memory contiguously.
Memory is dynamically allocated for each node.
Size
Fixed size, defined at creation.
Dynamic size, can grow or shrink during runtime.
Access Time
Direct access to elements using indices (O(1)).
Sequential access, requires traversal (O(n)).
Insertion/Deletion
Inserting or deleting elements is inefficient (O(n)) due to shifting.
Insertion and deletion are efficient (O(1)) if the position is known.
Memory Efficiency
Can waste memory if the array is larger than needed.
More memory efficient as memory is allocated dynamically.
Cache Locality
Better cache locality due to contiguous memory allocation.
Poorer cache locality as nodes are scattered in memory.
Traversal
Can be traversed using simple indexing.
Requires traversal node by node from the head.
Implementation Complexity
Simple to implement and use.
More complex due to handling pointers for each node.
25. Which algorithm is used to find the largest subarray sum from a given array of integers ?
You can use Kadane’s Algorithmto find the largest sub-array sum. This algorithm is used to solve the issue in linear time.
Initialise: curr_max=0; global_max= INT_MIN;
While traversing through the array :
curr_max = curr_max+arr[i]
Whenever we will get a positive sub-array sum, compare it with the global_max and update the global_max variable if the curr_max is greater than it. If the sub-array sum is negative, we must reset the curr_max to zero because we will never take that element for the next sub-arrays. Finally, return the global_max.
Here’s the code to implement Kadane’s algorithm:
long long Kadanes(int arr[], int n)
{
long long curr_max=0; long long global_max= 0;
for( int i=0 ;i<n ;i++ ){
curr_max+=arr[i];
if( global_max < curr_max)
global_max = curr_max;
if(curr_max < 0)
curr_max=0;
}
return global_max;
}
26. How do you perform binary search in a given array?
The binary search technique works efficiently on sorted arrays and follows the divide-and-conquer approach. Calculate the mid of the array -
mid = beg + (end-beg)/2;
The array is divided into halves, and the element is compared with the middle element of the array. If the match is found, return the middle element's location. Here’s the code to implement binary search :
int binarySearch( int arr[], int num ){
int beg = 0;
int end = size-1;
while( beg <= end ){
mid = beg + (end-beg)/2;
if( arr[mid] == num ){
return mid+1;
}
else if( arr[mid] > num ){
end =mid-1;
}
else if( arr[mid] < num ){
beg = mid+1;
}
}
return -1; //if the element does not exist
}
The time complexity in the worst case is O(logn).
27. How to convert a byte array to a string in Java?
The process of converting a byte array to a String is called decoding. You can use the String class constructor with byte[] as the constructor argument.
This problem can also be solved by providing “UTF-8” as character encoding. Java provides another overloaded constructor in the String class, which accepts character encoding.
28. How do you find a triplet with the given sum in an array?
Firstly sort the given array. Now traverse the array and fix the first element of the possible triplet arr[i]. Use two pointer technique, and initialise two pointers (x,y), one at i+1 and the other at n-1, respectively. Look at the target sum.
If the sum exceeds the required sum, increment the x pointer.
Else, if the sum is greater, decrement y pointer.
Otherwise, if the sum of elements at two pointers equals the target sum, then return the triplet and break.
29. How will you efficiently calculate the frequency of all the elements in a limited range array?
Create a count array equal to the size of the given array to store the count of all array elements. Traverse through the array and update the frequency of each element in the count array. Now iterate the array to print frequencies.
You can also traverse the given array and, for each different element of the array, store its frequency in a HashMap.
30. How to find a pair with a given sum in an array?
You can use Two pointer techniques to approach this problem.
Firstly sort the array. Now take two pointers (i,j) which mark the array's beginning and end respectively. Traverse the array if the sum is greater than the sum of those elements at index i and j decrement the j pointer. If the sum exceeds the target value, increment the i pointer.
Here’s the pseudo code :
void findPairSum( int arr[], int n, int targetSum ){
sort( arr, arr+n);
int i=0; int j= n-1;
while(i<j){
if( arr[i]+arr[j] == targetSum ){
cout<<arr[i]<<” ”<<arr[j]<<endl;
return;
}
else if( arr[i]+arr[j] < targetSum )
i++;
else
j--;
}
cout<<"Given sum is not found";
}
You can also use Binary search methods. Then traverse the array elements and perform a binary search for (target-a[i]) for the remaining part.
In this article, we have extensively discussed Array Interview Questions.
We also have courses and articles on well-liked interview questions like these Array Interview Questions, which will assist you in clearing the interview round. Just keep practicing more and more questions.
Also, do refer to Array Interview Questions related articles: