Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
2.
Array Interview Questions for Freshers
2.1.
1. What is an Array in Programming?
2.2.
2. How do you declare an Array?
2.3.
3. Mention some advantages and disadvantages of Arrays.
2.4.
4. What will happen if an array is not initialised?
2.5.
5. Is it possible to declare an array without specifying its size?
2.6.
6. Can you pass a negative integer as an array size?
2.7.
7. What is the default value of Array in Java?
2.8.
8. How to find the largest element in an unsorted array?
2.9.
9. When will we get an ArrayStoreException?
2.10.
10. How to linearly search an element in an array?
3.
Array Interview Questions for Experienced
3.1.
11. Difference between Array and Object.
3.2.
12. How to get the index of an array element?
3.3.
13. What is a Jagged Array in Java?
3.4.
14. Where in the JVM memory is an Array kept?
3.5.
15. How to sort an array of 0 and 1?
3.6.
16. How to cyclically rotate an array by one?
3.7.
17. How to move all zeros to the end of the array?
3.8.
18. Which is the fastest array sorting algorithm?
3.9.
19. What are the features of an ArrayList ?
3.10.
20. How to retrieve the class name of an array?
4.
Array Coding Problems Interview Questions
4.1.
21. How to check the equality of two arrays?
4.2.
22. How to remove a particular element from an array?
4.3.
23. How to find the missing integer in an array of range 1 to 100?
4.4.
24. Compare Arrays with Linked Lists.
4.5.
25. Which algorithm is used to find the largest subarray sum from a given array of integers ?
4.6.
26. How do you perform binary search in a given array?
4.7.
27. How to convert a byte array to a string in Java?
4.8.
28. How do you find a triplet with the given sum in an array?
4.9.
29. How will you efficiently calculate the frequency of all the elements in a limited range array?
4.10.
30. How to find a pair with a given sum in an array?
5.
Conclusion
Last Updated: May 25, 2024
Easy

Array Interview Questions

Author Aayushee
1 upvote

Introduction 

The array is an essential topic for programming interviews. As you learn to code, you'll find that arrays are used in many issues. Because arrays are so typical, you will find them used in any programming language you select, including C, C++, Java, Python, Perl, and Ruby.

Array Interview Questions

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.

Also read, BPO interview questions

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 Java will 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”.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Array Interview Questions for Experienced

11. Difference between Array and Object.

An array creates a data collection and keeps it in a single variable, whereas an object represents a thing with characteristics (referred to as a property). Using brackets and dots, we can access, modify, and delete items from objects. In contrast, we can access and modify items in arrays using    several built-in methods and zero-based indexing. Using many alternative loops (such as for, for...in, for...of, and forEach()), we can traverse over object attributes and array entries.

Every Java object is allocated dynamically on the heap, unlike C++, which allows for the memory allocation of objects on either a heap or a stack. The object is allocated on the heap when the new() method in C++ is used and on the stack if the object is not global or static.
 

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.

void sort(int arr[], int n)
{
	int i=0; int j=n-1;
	while(i<j)
	{
		while( arr[i]==0 )
		{
			i++;
		}
		while( arr[j]==1 )
		{
			j--;
		}
		if( i<j)
		{
			int temp = arr[i];     //swapping
			arr[i] = arr[j];
			arr[j] = temp;
		}
 	}
}

 

16. How to cyclically rotate an array by one?

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.

To know more about jQuery interview questions  click here.

 

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. 

Must Read: Ab Initio Interview Questions And Operating System Interview Questions

Array Coding Problems 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”;
}


Also read, Spring boot interview questions


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.

  • Size: Since data may only be stored in contiguous memory blocks in an array, the size of an array cannot be changed at runtime. However, a linked list's node structure allows for easy size modification because each node points to the one after it, allowing for data at dispersed (non-contiguous) locations.
     
  • Memory allocation: Linked lists have runtime memory allocation, whereas arrays have compile-time memory allocation. However, memory is also allocated during runtime by a dynamically allocated array.
     
  • Memory efficiency: Due to its node structure, the linked list requires more memory for a given amount of entries because each node also keeps a reference to the node after it. In contrast, linked lists may utilise less memory overall than arrays if the size of the data pieces varies widely or if there needs to be more clarity about their size.
     
  • Execution time: Unlike elements in an array, which may be accessed using their index, all previous elements in a linked list must be traversed before reaching any entry. Because of this, some actions, like changing an element, are quicker in arrays, while others, like adding an element, are quicker in linked lists.

 

Must Read Difference between ArrayList and LinkedList

 

25. Which algorithm is used to find the largest subarray sum from a given array of integers ?

You can use Kadane’s Algorithm to 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.

  1. If the sum exceeds the required sum, increment the x pointer.
  2. Else, if the sum is greater, decrement y pointer.
  3. 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.

Must Read Array of Objects in Java

Conclusion

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:

Recommended problems -

 

Best wishes for your interview!

Refer to our guided paths on Code360 to learn more about DSA, Competitive Programming, JavaScript, System Design, etc.

Enrol in our courses and refer to the mock test and problems available.

Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow.

Happy Coding!

Previous article
LINQ Interview Questions
Next article
Database Testing Interview Questions
Live masterclass