Top Array Interview Questions to Prepare for in 2023 - IQCode

Arrays in Programming Interviews

Arrays are a fundamental concept in programming interviews, and you will encounter them in many problems. Arrays are ubiquitous and used widely across programming languages such as C, C++, Java, Python, Perl, and Ruby, to name a few.

What is an Array in Programming?

An Array is a collection of similar data types stored in contiguous memory locations. During array declaration, you must specify the type of data along with the array name. To access any element in the array, an index number is used. For instance, to access an element "pleasant" at the 3rd index (or 4th element) in an array "arr", you can use the notation "arr[3]".

How to Declare an Array?

Array declaration in C/C++:

> DataType arrayName[size];

Array declaration in Java:

> int[] intArray;

Some characteristics of an array include being fixed in length (i.e., static), holding primitive types and object references. When an array reference is made to a non-existent element, an IndexError occurs.

From observation, we note that the first element in an array is located at the lowest address while the last element is at the highest address. Also, array indexing typically starts with 0, not 1.

If you aspire to work as a developer, it is paramount to have a solid understanding of arrays as you are likely to encounter an array-related coding challenge in the interview. In this article, we discuss comprehensive Array interview questions and answers for freshers and experienced professionals to help you ace the interview.

Here are some questions that freshers can prepare for:

Array Interview Questions for Freshers - Mention some advantages and disadvantages of arrays.

Other sections covered in this article: - Array Interview Questions for Experienced. - Array Coding Interview Questions.

You can also leverage the free mock interview feature to obtain instant feedback and recommendations.

Array vs ArrayList in Java

In Java, an array is a fixed-size data structure that stores a homogeneous collection of elements of the same data type. The size of an array is defined at the time of creation and cannot be changed once created. On the other hand, an ArrayList is a dynamic data structure that can grow and shrink in size dynamically as elements are added or removed. ArrayList is a part of Java's Collection Framework and provides more flexibility than arrays. Let's see the differences between arrays and ArrayLists:

//Declaration and initialization of an array

int[] arr = new int[5];
//Declaration and initialization of an ArrayList

ArrayList<Integer> list = new ArrayList<Integer>();
  • Memory allocation: For arrays, a continuous block of memory is allocated at the time of creation. ArrayLists, on the other hand, are backed by an Array that grows dynamically when the size of the list exceeds its capacity.
  • Data types: Arrays can store only a homogeneous collection of data elements of the same data type. ArrayLists can store any type of data element including primitives and objects.
  • Size and resizing: The size of an array cannot be changed once it is created. On the other hand, an ArrayList can grow and shrink in size dynamically as elements are added or removed.
  • Accessing elements: In arrays, elements can be accessed using indexes. ArrayLists also provide the ability to access elements using the get() method or the forEach loop.
  • Performance: In terms of performance, arrays are faster than ArrayLists because they don't have the overhead of resizing, bounds checking, and performing operations through an abstraction layer.

So, if you have a fixed-size collection of items of the same data type, then an array will be a good choice. However, if you need to store a dynamic collection of items that can grow or shrink, then ArrayList will be a better choice.

What happens if an array is not initialized?

If an array is not initialized in a programming language, it will contain default values that depend on the data type of the array. For example, if the array is of integer type, then the uninitialized values will be 0, and if it is of string type, then the uninitialized values will be null or empty string.

However, it is always a good programming practice to initialize an array before using it to avoid any potential issues or errors that may arise due to uninitialized values.

Default Value of Array in Java

In Java, when an array is initialized, its values depend on the data type of the array. The default value of the elements in an array of integers is 0, for an array of booleans is false, for an array of floating-point numbers is 0.0, and for an array of objects is null. If the array is not initialized and just declared, the reference to the array will be null.

Time Complexity of Basic Operations in an Array

In general, accessing or searching for an element in an array takes O(1) constant time complexity. However, inserting or deleting an element in an array can take up to O(n) linear time complexity in worst-case scenarios, where n is the number of elements in the array. This is because these operations may require shifting the values of other elements in the array.

Creating an Uninitialized Array in Python

Yes, in Python, you can declare an array without assigning its size. This is done by using empty brackets [] or the built-in function list(). Here's an example:


# creating an empty array using empty brackets
my_array = []

# creating an empty array using the list() function
my_array_2 = list()

# printing the arrays



Note that you can also declare an uninitialized array in other programming languages, but the syntax may be different.

Understanding the Difference between Arrays and Objects

In JavaScript, both arrays and objects are used to store data and can be accessed using their properties or keys. However, there are some differences between them:

  • Use numbered indices to access elements
  • Can only store values of a specific data type
  • Have built-in methods for manipulating data
  • Are ordered, meaning elements are stored in a specific sequence
  • Use keys to access values
  • Can store values of any data type
  • Manipulating data requires custom functions or methods
  • Are unordered, meaning the order of keys is not guaranteed

It is important to understand the differences between arrays and objects, as they are both commonly used in JavaScript and choosing the appropriate data structure can impact the performance and functionality of your code.

Where is an Array stored in JVM Memory?

In Java, an array is stored in the heap memory, which is a part of the JVM memory. When an array is created in Java, memory is allocated to it during runtime and it is stored in the heap memory.

The heap memory is a large pool of memory used by the JVM to allocate memory to objects during runtime. It is managed by the garbage collector, which automatically frees up memory that is no longer needed by the program.

Arrays can also be stored in the stack memory, but this is only possible when the array is a local variable in a method or block of code. However, storing large arrays in the stack memory can cause a stack overflow, as the stack memory is limited in size compared to the heap memory. Therefore, it is recommended to store arrays in the heap memory for better memory management.

Here's a basic example of creating an array in Java:

int[] myArray = new int[10];

In this example, an array of integers named "myArray" is created with a length of 10, and memory is allocated to it in the heap memory during runtime.

Finding the Target Element in an Array

//initialize the array with elements
let arr = [2, 4, 6, 8, 10];

//initialize the target element variable
let target = 6;

//loop through the array to find the target element
for (let i = 0; i < arr.length; i++) {
  if (arr[i] === target) {
    console.log(`Target element found at index ${i}`);

In this code, we are initializing an array with certain elements, and then we are defining a target element variable. We are then using a loop to traverse the array linearly and checking if the current element matches the target element. If we find a match, we print the index of the target element and break out of the loop.

Can a Negative Number be Used as Array Size?

In most programming languages, a negative number cannot be used as the size of an array since it would not make sense to allocate a negative amount of memory. Therefore, attempting to pass a negative number as the size of an array would likely result in a runtime error or an exception being thrown. It is important to always ensure that the size parameter for an array is a positive integer.

When will we receive an ArrayStoreException?

In Java, an ArrayStoreException is thrown at runtime when an attempt is made to store the wrong type of object into an array. This exception occurs when we try to store elements of different data types in an array.

For instance, trying to put a String in an array of integers will cause an ArrayStoreException to be thrown.

Therefore, an ArrayStoreException will be thrown when we try to store an object of an incompatible type in an array.

When will we receive an ArrayIndexOutOfBoundsException?

In Java, an ArrayIndexOutOfBoundsException is thrown when trying to access an array element using an index that is either negative or greater than or equal to the size of the array. For instance, suppose you have an array of size 5, and you try to access the element at index 5 or -1, an ArrayIndexOutOfBoundsException will be thrown.

Here is an example of code that throws an ArrayIndexOutOfBoundsException:

int[] myArray = {1, 2, 3, 4, 5};
System.out.println(myArray[5]); // this will throw an ArrayIndexOutOfBoundsException since the last index is 4.

To avoid such errors, you should always make sure that the index used to access the array is within the valid range of indices, which is from 0 to the length of the array minus 1.

Why can't we write STRARRAY.LENGTH() if we know that arrays are objects?

In JavaScript, arrays are indeed objects, but they have their own unique properties and methods. The .length property of an array represents the number of elements it contains, but it should be accessed without using parentheses. Therefore, the correct syntax to get the length of an array in JavaScript is `STRARRAY.length` instead of `STRARRAY.LENGTH()`.

Difference Between length and length() in Java

In Java, `length` is a property of an array that provides the number of elements in the array, while `length()` is a method used to get the length of a string.

The `length` property is used as follows:

int[] arr = {1, 2, 3, 4, 5};
int arrLength = arr.length;

The `length()` method is used as follows:

String str = "Hello World";
int strLength = str.length();

So, to summarize: - `length` is a property of an array - `length()` is a method used to get the length of a string.

Understanding Jagged Arrays in Java

In Java, a jagged array is a two-dimensional array in which each row can have a different number of columns. This means that the size of every row in such an array can be different.

For example, consider a jagged array that stores information about students and their test scores:

int[][] scores = new int[3][];
scores[0] = new int[] {90, 95, 80};  // Row 0 has 3 columns
scores[1] = new int[] {75, 85};      // Row 1 has 2 columns
scores[2] = new int[] {100, 98, 95, 92}; // Row 2 has 4 columns

Here, the `scores` array has three rows. The first row has three columns, the second row has two columns, and the third row has four columns. This type of array is useful when you need to store data that is not of uniform size.

To access an element in a jagged array, you would use two sets of square brackets:

scores[0][1]; // returns 95 (second element in first row)

It is important to note that a jagged array in Java is not a separate datatype. Rather, it is a concept that can be implemented using regular two-dimensional arrays by varying the size of each row.

Determining the size of an array passed to a function using the sizeof operator

Yes, the sizeof operator can be used to determine the size of an array that is passed to a function. However, it will only give the size of the pointer, not the actual size of the array. Therefore, to get the size of the array, it is necessary to divide the total size of the array by the size of a single element.

Here is an example:

void arraySize(int arr[]) {
   int size = sizeof(arr)/sizeof(arr[0]);
   printf("Size of array: %d", size);

In the above example, sizeof(arr) will return the size of the pointer, which is usually 4 or 8 bytes, depending on the system. Therefore, to get the actual size of the array, we divide the total size of the array (which is the size of the pointer multiplied by the number of elements in the array) by the size of a single element in the array (which is sizeof(arr[0])).

By doing this, we get the actual size of the array, and we can use it for further calculations in our function.

Array Interview Questions for Experienced:

Question 17: What do the terms "dimension" and "subscript" mean when discussing arrays?

Answer: In the context of arrays, a "dimension" refers to the size of an array in a particular direction. For example, a two-dimensional array has a size in both rows and columns. A "subscript" is used to access a specific element within an array by specifying the position of the element in each dimension. For instance, in a two-dimensional array, an element can be accessed using two subscripts, one for the row and one for the column.

// Example of accessing element using subscripts in a two-dimensional array in Java

int[][] myArray = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };

int element = myArray[1][2];   // Accessing element in the second row and third column

Comparing Arrays and Linked Lists

In computer science, arrays and linked lists are two important data structures used to store, access and manipulate collections of data. While both serve similar purposes, there are some key differences between the two in terms of how they store data, how they are accessed and their performance in different scenarios. Let's explore these differences.

var array = [1, 2, 3, 4, 5]; //creating an array
console.log(array); // output: [1, 2, 3, 4, 5]
console.log(array[2]); // output: 3

var linkedList = new LinkedList(); //creating a linked list

console.log(linkedList); // output: LinkedList { head: Node { value: 1, next: Node { value: 2, next: Node { value: 3, next: [Node] } } } }
console.log(; // output: Node { value: 2, next: Node { value: 3, next: Node { value: 4, next: [Node] } } }

As we can see from the code above, arrays are created using square brackets and can be accessed using their index position. Linked Lists, on the other hand, require a bit more setup and use a Node class with a reference to the next node in the list.

In terms of memory usage, arrays are generally more memory efficient than linked lists since they do not require external referencing for each element. However, in terms of performance, linked lists can be more efficient in scenarios that require frequent data insertion or deletion, since they can be easily modified by changing the reference to the next node.

It is important to choose the appropriate data structure based on the requirements of your program in order to achieve the best performance and memory usage.

Why is fetching from an array O(1) complexity?

In computer science, the time complexity of an algorithm determines the amount of time it takes to execute and complete the algorithm. An algorithm that has a time complexity of O(1) takes a constant amount of time to execute, regardless of the input size.

Fetching an element from an array by its index is considered to have a time complexity of O(1) because it requires constant time to locate and retrieve the element. This is because arrays are stored in contiguous memory locations, and the location of any element can be found using simple arithmetic based on the index and the size of each element in the array.

Therefore, whether the array has 10 elements or 10,000 elements, fetching the value at a specific index takes the same amount of time and has a time complexity of O(1).

Finding the missing integer in an array of range 1 to 100

To find the missing integer in an array of range 1 to 100, you can follow the below steps:

Step 1: Take an integer array of size 100 with all elements initialized to 0.

int integerArray[100] = {0};

Step 2: Traverse the given array and update the count of each element in the integer array.

for (int i = 0; i < n; i++) {
    integerArray[array[i] - 1]++;

Step 3: Traverse the integer array and return the index of the element that has a count of 0. Add 1 to the index to get the missing integer.

for (int i = 0; i < 100; i++) {
    if (integerArray[i] == 0) {
        return i+1;

The time complexity of this solution is O(n) and the space complexity is O(1).

How to Remove a Specific Element from an Array in JavaScript

To remove a specific element from an array in JavaScript, you can use the `splice()` method. This method changes the content of an array by removing or replacing existing elements and/or adding new elements in place.

Here's an example:

let array = [1, 2, 3, 4, 5];
let index = array.indexOf(3);
if (index !== -1) {
  array.splice(index, 1);
console.log(array); // Output: [1, 2, 4, 5]

In this example, we first declare an array of numbers, and then we find the index of the element we want to remove using the `indexOf()` method. If the `indexOf()` method returns a value that is not `-1`, which means that the element is found in the array, we use the `splice()` method to remove the element.

The `splice()` method takes two arguments: the starting index of the change, and the number of elements to remove. In this case, we start at the index of the element we want to remove, and we remove only one element.

Finally, we log the modified array to the console to confirm that the element has been removed.

How to Get the Index of an Array Element in JavaScript

To get the index of an element in a JavaScript array, you can use the `indexOf()` method. This method takes an argument of the value you want to find the index of and returns the index of the first occurrence of that value in the array. If the value is not found, it returns -1. Here's an example:

let arr = [1, 2, 3, 4, 5];
let index = arr.indexOf(3);
console.log(index); // 2

In this example, we have an array with five elements. We use the `indexOf()` method to find the index of the value "3" in the array, which is 2. We then log this index to the console.

Merging Two Sorted Arrays into One Sorted Array

This can be achieved by creating a third array which will be used to store the merged array after sorting. The steps are outlined below:

1. Initialize two pointers, one for each sorted array. 2. Compare the elements at the current position of both pointers. 3. The smaller value between them is added to the third array. Increment the pointer for the sorted array that contained the smaller value. 4. Repeat step 2 and 3 until all elements from both arrays have been added to the third array. 5. If there are any remaining elements in either of the sorted arrays, append them to the third array.

Here is the code to implement the above algorithm:

void mergeArrays(int arr1[], int arr2[], int n1, int n2, int arr3[])
    int i = 0, j = 0, k = 0;
    // Traverse both arrays simultaneously
    while (i < n1 && j < n2) {
        // Add the smaller of the two values to arr3
        if (arr1[i] < arr2[j])
            arr3[k++] = arr1[i++];
            arr3[k++] = arr2[j++];
    // Append remaining elements from arr1
    while (i < n1)
        arr3[k++] = arr1[i++];
    // Append remaining elements from arr2
    while (j < n2)
        arr3[k++] = arr2[j++];

Checking Equality of Two Arrays in JavaScript

In JavaScript, you can check whether two arrays are equal or not using the following code:

function arraysEqual(array1, array2) {

  // If the arrays are of different lengths, they are not equal
  if (array1.length !== array2.length) return false;

  // Check if each element in array1 is the same as the corresponding element in array2
  for (let i = 0; i < array1.length; i++) {
    if (array1[i] !== array2[i]) return false;

  // If we reach this point, the arrays are equal
  return true;

You can then call this function, passing in the two arrays you'd like to compare:

const arr1 = [1, 2, 3];
const arr2 = [1, 2, 3];
const arr3 = [1, 2, 4];

arraysEqual(arr1, arr2); // returns true
arraysEqual(arr1, arr3); // returns false

This function first checks if the arrays have the same length. If they do not, the function returns false since they cannot be equal. If the arrays are the same length, the function then iterates through each element, comparing them in sequence. If at any point it finds two different elements, the function immediately returns false. If it reaches the end of the loop without finding any inequality, it returns true to indicate that the two arrays are equal.

Array Interview Question: Sorting an Array of 0s and 1s

Given an array of only 0s and 1s, we can sort the array by counting the number of zeros and ones in the array and then overwriting the original array with those counts.

Here's the solution in Python:

def sort_01_array(arr):
    # count the number of zeros and ones
    count_0 = arr.count(0)
    count_1 = arr.count(1)

    # overwrite the original array with the counts
    arr[:count_0] = [0] * count_0
    arr[count_0:] = [1] * count_1
    return arr

For example, if the input array is [1, 0, 1, 0, 0, 1], the sorted output would be [0, 0, 0, 1, 1, 1].

This solution has a time complexity of O(n), where n is the length of the input array, because we only loop through the array twice to count the zeros and ones and once more to overwrite the original array.


To rotate an array in JavaScript, you can use the `Array.prototype.splice()` method along with the spread operator (`...`) to insert the elements at the start of the array to the end. Here's an example code snippet that shows how to rotate an array by a given number of positions:

function rotateArray(arr, positions) {
  arr.push(...arr.splice(0, positions));
  return arr;

// example usage
const myArray = [1, 2, 3, 4, 5];
const rotatedArray = rotateArray(myArray, 2); // [3, 4, 5, 1, 2]

In this example, the `rotateArray()` function takes two arguments: `arr` is the array to rotate, and `positions` is the number of positions to rotate the array by.

The first line of the function (`arr.push(...arr.splice(0, positions));`) removes the first `positions` elements of the array using the `splice()` method, and then uses the spread operator (`...`) to insert those elements at the end of the array using the `push()` method.

The function then returns the modified array.

Note: This solution modifies the original array, so if you want to keep the original array intact, you should create a copy of the array before passing it to the `rotateArray()` function.

Two Sum of an Array:

Given an array called 'arr' and a target number, the task is to find and return the indices of two numbers in the array that add up to the target number.

     * @param arr - array of integers
     * @param target - target sum
     * @return - array of 2 indices of numbers that add up to the target
    public int[] getTwoSumIndices(int[] arr, int target) {
        // hashmap to store the difference between target sum and the current number in the array as key, and its index as value 
        Map<Integer, Integer> map = new HashMap<>();
        // loop through array and check if the difference between the target and the current number is in the hashmap,
        // if yes, return the current index and the index of the corresponding value in the hashmap
        for (int i = 0; i < arr.length; i++) {
            if (map.containsKey(arr[i])) {
                return new int[] {map.get(arr[i]), i};
            map.put(target - arr[i], i);
        // return null if no two numbers add up to target
        return null;

Checking for Balanced Parentheses in an Expression using Constant Space

In this code, we will check if an expression has balanced parentheses or not using constant space.

class CheckParentheses {
    static boolean areParenthesesBalanced(String expr) {
        int count = 0;
        for (int i = 0; i < expr.length(); i++) {
            if (expr.charAt(i) == '(') {
            } else if (expr.charAt(i) == ')') {
            if (count < 0) {
                return false;
        return count == 0;

This code maintains a count of open parentheses encountered. Whenever a closing parenthesis is encountered, it decrements the count. If the count goes below 0, it means that a closing parenthesis was encountered before an opening parenthesis, so the expression is unbalanced. If the count is 0 at the end of the loop, it means that all parentheses were matched and the expression is balanced.

Finding the Smallest and Largest Number in a Given Array

We can find the smallest and largest number in a given array by using the following steps:

STEP 1: Declare an array of numbers.

STEP 2: Initialize two variables, max and min, to the first element of the array.

STEP 3: Iterate through the array, comparing each element to the current maximum and minimum variables.

STEP 4: If the current element is greater than the current maximum variable, set the maximum variable to the current element.

STEP 5: If the current element is less than the current minimum variable, set the minimum variable to the current element.

STEP 6: After iterating through the entire array, the max and min variables will contain the maximum and minimum values, respectively.

Here is an example code in Python:

def find_min_max(arr):
    # Initialize variables to the first element in array
    max_num = arr[0]
    min_num = arr[0]
    # Iterate over array, comparing each element to max and min
    for num in arr:
        if num > max_num:
            max_num = num
        elif num < min_num:
            min_num = num
    # Return max and min values
    return max_num, min_num

# Example usage
my_arr = [5, 3, 8, 1, 9, 2]
max_val, min_val = find_min_max(my_arr)
print("Maximum value:", max_val)
print("Minimum value:", min_val)

The output of this code will be:

    Maximum value: 9
    Minimum value: 1

Technical Interview Guides

Here are guides for technical interviews, categorized from introductory to advanced levels.

View All

Best MCQ

As part of their written examination, numerous tech companies necessitate candidates to complete multiple-choice questions (MCQs) assessing their technical aptitude.

View MCQ's
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.