Accreditation Bodies
Accreditation Bodies
Accreditation Bodies
Supercharge your career with our Multi-Cloud Engineer Bootcamp
KNOW MOREArray interview questions are crucial for coding interviews. No matter for which role you are preparing either SDE or for a simple role of Web Developer, arrays are very essential and an important way to judge one's capabilities. Arrays are the collection of elements of the same data type stored at contiguous memory locations. Below is the list of top, expert-curated lists of Array interview questions and answers/ and array coding interview questions which will help you competently crack interviews. This article mainly contains array programming questions in C, array coding interview and many more interview questions based on logic and coding in different programming languages like Python, JavaScript, Java, C++ and PHP so that you are good to go for any interview process.
Filter By
Clear all
This is a frequently asked question in Array interview questions.
An array is a type of data structure that we use to store data in contiguous memory locations. But this data should be of the same data type as the one used for array declaration.
The advantage of having a contiguous memory is that we can easily find the location of any element in the array by just finding its index value. For example, if we want to access an element present at the 3rd index(4th element) in an array arr, then we can write arr[3]. This is generally because when it comes to arrays, we mostly follow 0-based indexing and not 1-based indexing.
While this is good and all, an array cannot be resized once declared. This may sometimes lead to memory leaks which are not good for any programmer.
Expect to come across this popular question in Programming questions on Arrays.
The main difference between them is that array is static, meaning we have to specify the size of the array along with its data type to initialize an array which can sometimes become the reason for memory leaks. While in the case of ArrayList, no such memory leaks happen as it is dynamic, meaning it can adjust its size according to the input given.
This is because, in the case of an ArrayList, as soon as an element is added, JVM checks whether it has enough space or not by calling the ensureCapacity() method. If the space exists, the element gets added to the ArrayList, else the ArrayList gets resized.
In the resizing process, an array of a larger size is created, the old array is copied to the new array using the Arrays.copyOf method, and the new array is then assigned to the existing array.
Let us understand some more differences in a tabular format:
Array | ArrayList | |
---|---|---|
Definition | An Array is a collection of similar data types stored in contiguous memory locations. | An ArrayList is a class of Java Collections framework which contains popular classes like Vector, HashMap, etc. |
Performance | It is fast as compared to ArrayList. | Its resizing ability slows it down. |
Type of Data Structure stored | It can store both objects and primitive data type like int, long, float, etc. | It cannot store primitive data type and automatically converts primitive data types into objects. |
Type - Safety | It is not type safe as we cannot save generics along with the array thus making the array convertible in nature. | ArrayList, on the other hand, can store generics. Hence is not convertible and thus is type-safe. |
In Java, when we initialize an array with the new keyword, the size argument is of the type int and a 32-bit Java int can go up to 2,147,483,647 elements which can be considered as the theoretical max limit of an array when it is initialized with an int data type.
However, in reality, the virtual machines of different operating systems may not allocate every bit of it to the array elements. Thus, the maximum number of elements a Java array can hold is typically a little less than the upper limit of a Java int.
In the above example, we tried to test out this theoretical max limit of an array but what we received was an OutOfMemory exception. This is because this is not the actual max limit of an array. Moreover, it totally depends upon the type of OS we are using.
Commonly we use the terms ‘size’ when we want to know how many elements an array can hold, on the contrary in java we do not have a size() method nor do we have a length() method in java. What we do have is the length property which we use to find out the length of the array or the number of elements it holds.
To confuse the matters even more, Java Collection class that implements a list interface does have a size() method. Collection classes like Vector, ArrayList, and Stacks have a size method that is used to calculate the number of elements present in them.
A must-know for anyone heading into an Array interview, this question is frequently asked in Array interview questions.
Advantages
Disadvantages
Arrays | Dictionary |
---|---|
It is a collection of the same data types. | It is a collection of data values. |
Look up time in case of arrays is O(n). | Look up time in case of Dictionary is O(1). |
It is compulsory that the elements will be stored in contiguous memory locations. | It is not compulsory that the elements will be stored in contiguous memory locations. |
In case of arrays, we can duplicate elements and store them . | In case of Dictionary, we cannot duplicate elements as they are not allowed in it. |
Items are not represented as key and value pairs. | Items are represented as key and value pairs. |
Values can be accessed randomly with the help of its index. | Well, there are quite a few ways to get a random value from a dictionary but the thing common in each one of them is the use of key. |
It's no surprise that this one pops up often in Programming questions on Arrays.
Passing an array as a parameter in C and C++ will not give us the correct answer, as in C and C++, array parameters are treated as pointers. Although sizeof() can tell you the size of the pointer and the size of the type it points to, it cannot tell you how many bytes are occupied by the entire array.
Let us understand this with the help of an example:
#include <stdio.h> void fun(int arr[]) { int i; // sizeof should not be used here to get number // of elements in array int arr_size = sizeof(arr) / sizeof(arr[0]); for (i = 0; i < arr_size; i++) { arr[i] = i; } // executed two times only } // Driver Code int main() { int i; int arr[4] = { 0, 0, 0, 0 }; fun(arr); // use of sizeof is fine here for (i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) printf("%d", arr[i]); getchar(); return 0; }
The above code will run without any run-time or compile-time errors, but it will return an incorrect result because the function fun() receives an array parameter 'arr[]' and attempts to find the number of elements in arr[] using the sizeof operator.
Array parameters are treated as pointers in C. As a result, the expression sizeof(arr)/sizeof(arr[0]) becomes sizeof(int *)/sizeof(int), yielding 2 (size of int* is 8 bytes because it is a pointer, and a pointer occupies 8 bytes of memory, and int is 4) and the for loop inside fun() is executed only twice, regardless of the size of the array. In such cases, sizeof should not be used to obtain the number of elements.
Dynamic Arrays or Vectors in C/C++ or ArrayList in Java are nothing more than an array that can resize itself according to the number of elements present in the array.
A basic array is also known as a fixed array as we have to specify the number of elements that the array will hold at the time of initialization of the array which then cannot be resized as the number of inputs increases in the array.
But in the case of dynamic, the size of the array usually gets doubled automatically (depending upon the programming we are writing code in).
A jagged Array is also called an Array of Arrays, irregular Array, Ragged Array, etc as it is a multidimensional array that has member arrays of different sizes. Like in a 2D array, the first array contains three elements, and the second array consists of four elements.
Below is an implementation of the Jagged Arrays:
class Main { public static void main(String[] args) { int[][] Array = new int[2][]; Array[0] = new int[3]; Array[1] = new int[4]; int counter = 0; for(int row=0; row <Array.length; row++){ for(int col=0; col < Array[row].length; col++){ Array[row][col] = counter++; } } for(int row=0; row < Array.length; row++){ System.out.println(); for(int col=0; col < Array[row].length; col++){ System.out.print(Array[row][col] + " "); } } } }
Output
This is one of the most asked programming questions on arrays. We will be answering this question on the basis of JavaScript programming language. There are five methods using which we can very easily find any element in an array in JavaScript. They are:
1. Array.find()
This method is used to find the element in the array that specifically satisfies the testing function or the test criteria. The first element that satisfies this criteria will be returned as the result of the callback function.
If there is no such element in the array, undefined will be returned.
It can also be used to find an element in an array of objects. See the below code:
2. Array.findIndex()
It is quite similar to the find() method. The only difference is, it will return the index of the first element that satisfies the condition of the callback function and if by any chance no element satisfies the given condition, it will return -1.
3. Array.indexOf() method
It is quite similar to findIndex() method as it will also return the index of the element which will satisfy the condition of the callback function. The only difference is that this method uses strict equality to compare the specified search element to array items. So, if you were looking for the index at which the value 5 is, but you submitted '5' to this function, the element will not be discovered and the method would return -1.
We can also provide a second argument which is optional by all means but gives us the power of telling the compiler to begin its search from the specified index as shown in the above image.
There is one more method - the lastIndexOf() method. This method works the same way as the indexOf() method works, but this method returns only the last element of the array which satisfies the condition.
4. Array.includes() method
The fourth method on our list is the includes() method. Like the other methods it is also used to tell whether a specific element is present in the array or not, but this method returns a boolean value - true if the value is present and false if it doesn’t.
This method just like the indexOf() method uses strict comparison before returning the boolean as the answer. And it also supports NaN comparisons.
5. Array.some() method
This method is quite different from the above 4. It checks whether the array contains at least one element that satisfies the condition. If it does, the method returns true else false.
Arrays are the simplest type of data structure that can store multiple elements of the same data type in contiguous memory locations. But it doesn’t stop here, it has many applications not only in the world of programming but in real life as well.
The basic use of arrays that we can think of is our contacts which are stored in our mobile phones. An array is used to keep track of all the phone contacts in our phone.
Other real-time applications of arrays include:
A common question in Array interview questions, don't miss this one.
It is one of the popular questions asked in array program interviews for java. Given an array, our task is to print the same array in reverse order. Let us understand this with the help of a diagram and example.
Example
arr[] = {1, 2, 3, 4, 5, 6, 7}; //original array arr[] = {7, 6, 5, 4, 3, 2, 1}; //reversed array
Let us see how this problem is solved in the most effective way.
Iterative Approach
import java.util.*; class Main { public static void main(String[] args) { int arr[] = {1, 2, 3, 4, 5, 6, 7}; int n = arr.length; int start = 0; int end = n-1; while (start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } System.out.println(Arrays.toString(arr)); } }
Output
[7, 6, 5, 4, 3, 2, 1] Time Complexity - O(n) Space Complexity - O(1)
This is yet another example of what type of questions are asked in array program in java for interviews. Given a sorted array arr[] and a number x, write a function that counts the occurrences of x in arr[]. Expected time complexity is O(Logn).
Example
Input: arr[] = {1, 1, 2, 2, 2, 2, 3,}, x = 3
Output: 1
Approach
We can do this in two ways - using linear search and using binary search. The method in which we find the occurrence of x using linear search has a time complexity of O(n), but if we use binary search we can reduce the time complexity to O(log n) which we were told in the question.
class Main { // A recursive binary search function. It returns location // of x in given array arr[l..r] is present, otherwise -1 static int binarySearch(int arr[], int l, int r, int x) { if (r < l) return -1; int mid = l + (r - l) / 2; // If the element is present at the middle itself if (arr[mid] == x) return mid; // If element is smaller than mid, then it can only be // present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); // Else the element can only be present in right subarray return binarySearch(arr, mid + 1, r, x); } // Returns number of times x occurs in arr[0..n-1] static int countOccurrences(int arr[], int n, int x) { int ind = binarySearch(arr, 0, n - 1, x); // If element is not present if (ind == -1) return 0; // Count elements on the left side. int count = 1; int left = ind - 1; while (left >= 0 && arr[left] == x) { count++; left--; } // Count elements on the right side. int right = ind + 1; while (right < n && arr[right] == x) { count++; right++; } return count; } // Driver code public static void main(String[] args) { int arr[] = {1, 2, 2, 2, 2, 3, 4, 7, 8, 8}; int n = arr.length; int x = 2; System.out.print(countOccurrences(arr, n, x)); } }
Output
4 Time Complexity: O(log n) Space Complexity: O(1)
Given two arrays find the union and intersection in linear time complexity.
Example
Input: arr1[] = {2, 4, 6, 8, 7}; arr2[] = {1, 3, 5, 2, 8);
Output:
Union: {1, 2, 3, 4, 5, 6, 7, 8} Intersection: {2, 8}
Approach
For finding the union of the array
For finding the insertion of array
import java.io.*; import java.util.*; class Main { /* Function prints union of arr1[] and arr2[] m is the number of elements in arr1[] n is the number of elements in arr2[] */ static int printUnion(int arr1[], int arr2[], int m, int n) { int i = 0, j = 0; int z = 9; int arr[] = new int[n]; while (i < m && j < n) { if (arr1[i] < arr2[j]) System.out.print(arr1[i++] + " "); else if (arr2[j] < arr1[i]) System.out.print(arr2[j++] + " "); else { System.out.print(arr2[j++] + " "); i++; } } /* Print remaining elements of the larger array */ while (i < m) System.out.print(arr1[i++] + " "); while (j < n) System.out.print(arr2[j++] + " "); return 0; } static void printInsertion(int A[], int B[], int n, int m) { int i=0,j=0,z=0; ArrayList<Integer> arr = new ArrayList<Integer>(); while(i < n && j < m){ if(A[i]==B[j]){ arr.add(A[i]); i++;j++; } else if(A[i]<B[j]) i++; else j++; } int array[] = new int[arr.size()]; for(i = 0;i<arr.size();i++){ array[i] = arr.get(i); } System.out.println(); System.out.println("Intersection points are " + Arrays.toString(array)); } public static void main(String args[]) { int arr1[] = { 1, 2, 4, 5, 6 }; int arr2[] = { 2, 3, 5, 7 }; int m = arr1.length; int n = arr2.length; printUnion(arr1, arr2, m, n); printInsertion(arr1, arr2, n, m); } }
Output
Union of the array - {1, 2, 3, 4, 5, 6, 7} Intersection of the array - {2, 5} Time Complexity : O(m+n) Space Complexity: O(1)
Before answering this question, let us understand the difference between a data type and a data structure:
A. Data Type
A type of value that is stored in a variable is called a data type. There are a two types of data types - primitive and non-primitive. Below diagram will show you different types of primitive and non-primitive data types.
B. Data Structure
It is a way of storing, organizing, and arranging data on a computer so that it can be updated efficiently. There are different types of basic and advanced data structures in almost all programming languages. Some of them are listed below:
Now according to the definition of Arrays, arrays are a collection of elements of the same data type stored at contiguous memory locations. We can clearly state that Array is a type of Data Structure and not a Data Type. This is because it can store, access, delete and update the existing values and we can add new values into it.
There are two ways of initializing an array:
But if for some reason we don't initialize the array in both scenarios, the array will be initialized with some random values, and at each memory location as in the array, elements are stored in contiguous order. These random values can again be categorized into two categories - Default values and Garbage values.
In the case of Java Programming Language, if the elements of the array which has already been declared are not set to their specific values, they will be initialized as the default values of the Data Type that was used for Array Declaration.
In the case of JavaScript, this default value is undefined. While in the case of C++, these random values will be the garbage values that the compiler has initialized the array with, and it's not a good thing for a programmer to rely on. While he can do so in the case of Java.
C++
JS
One of the most frequently posed Array coding questions, be ready for it.
The question is that you are given an array of size ‘n’ and a target value. You have to find the index at which this target value is and also tell its time complexity.
Approach
We will run a loop through the input array and check whether the given target value is present or not. If it’s present, we will return its index value, and if it's not, we will return -1.
We can also use Binary Search Algorithm, but we can only use it if the given array is sorted. And we just cannot sort our array as it will increase the time complexity to O(n log n).
Approach
import java.io.*; import java.util.*; class Main { static void binarySearch(int v[], int x) { int lo = 0, hi = v.length - 1; while (hi - lo > 1) { int mid = (hi + lo) / 2; if (v[mid] < x) { lo = mid + 1; } else { hi = mid; } } if (v[lo] == x) { System.out.println("Found At Index " + lo ); } else if (v[hi] == x) { System.out.println("Found At Index " + hi ); } else { System.out.println("Not Found" ); } } public static void main (String[] args) { int v[]= {1, 3, 4, 5, 6}; int x = 1; binarySearch(v, x); x = 6; binarySearch(v, x); x = 10; binarySearch(v, x); } }
Output
In Java, we have something known as JVM - Java Virtual Machine. It is mainly a part of JRE - Java Runtime Environment and acts as a run-time engine to run Java applications. JVM is the one that actually calls the main method present in a java code.
Now to answer the question as to why arrays are stored in the heap part of the JVM and not in any other part, we first have to understand that in Java reference types are stored in the Heap area. As arrays are also referenced types, (they can be created using the “new” keyword) they are also stored in the Heap area.
Let us understand this concept with the help of an example:
int myArray[]; //array declaration myArray = new int[4];//memory allocation using the new keyword myArray[0] = 25;//allocating memory myArray[1] = 32;//allocating memory myArray[2] = 56;//allocating memory myArray[3] = 93;//allocating memory
The int myArray[] is just a reference to the array of four integers. While to allocate the memory to an array, we have to use the new keyword. See the diagram below to get a better understanding of the concept.
The above statement is true. This is because in Java language we are free to use as many array-specific syntaxes as we want for both initializing (putting explicit values into an array) and constructing (creating the array object itself) in a single line.
Let us see how the above statement is true. We have initialized a variable y as 56 and it is inside an array of length 5. Now the compiler will replace the value of the y variable with its value as we print the array. See the image below.
But what if we try to initialize the variable after initializing the same array. We will get an error. This is because we have initialized the y variable after using it in the array which becomes the root cause of the error as y is an unknown variable for him.
A staple in Array interview questions, be prepared to answer this one.
There are various reasons to choose a Linkedlist over an Array. Some of them have been listed below:
In the case of a Linked list, we can add any element in the middle at any index without replacing any element from the original list, which we, of course, can’t do in both static and dynamic arrays.
A Sparse Array is the type of array in which most of the elements have either zero or null values. These types of arrays do not have contiguous indexes and are used over basic arrays. There are less non zero elements in comparison to the elements with zero value.
This is because this way, we only need to store non zero elements which are less in number saving a lot of memory and time which again in the world of DSA are very essential parameters.
They are normally seen and used in the Sparse Matrix in which most of the elements are equal to zero and no null values are there. Let us see some examples to understand.
Example
This is a frequently asked question in Programming questions on Arrays.
Before answering this question, let's first understand the concept of both arrays and pointers in C.
A. Arrays in C
Array will not be changed, no matter in which language they are defined in. They are collections of elements of the same data type stored in contiguous memory locations.
B. Pointers in C
In C, pointers are used to hold the address of variables or memory locations. These variables can be of any data type, such as int, char, function, array, or any other pointer. The pointer of type void is known as a Void pointer or a Generic pointer. A void pointer can hold the location of any type of variable.
Difference between Arrays and Pointers
Type | Arrays | Pointers |
---|---|---|
Definition | Collection of elements of the same data types. | Variable that stores address |
Storing Elements | Can store elements at contiguous memory locations. | Can store address one at a time. |
sizeOf Operator | When used with arrays, gives total number of bytes used by the elements. | When used with pointer, gives only the size of the pointer. |
Nature | Arrays are static in nature - cannot be resized. | Pointers are dynamic in nature - can be resized. |
Memory Elements | An array will allocate the memory correctly according to its scope. Thus will free the extra memory automatically as soon as the variable goes out of the scope. | But in case of pointers, memory leaks happens as they are unable to free memory automatically. |
Syntax | Data_Type Array_Name [size]; | Data_Type * Pointer_Name; |
No, it is not possible to initialize an array of negative size. This is because ‘as per the convention of array declaration, it is mandatory that each time an array is evaluated it shall have a size greater than 0. Declaring array size negative breaks this “shall” condition.’ That is why this action gives an error of NegativeArraySizeException at run-time in Java while other programming languages handle the declaration of Array size with a negative value. Let's see some of them.
Python
C++
Java
Expect to come across this popular question in Array interview questions.
We have two sorted arrays, A and B, the task is to merge both arrays in such a way that the third array is also sorted.
Examples
Input: arr1[] = { 1, 3, 4, 5}, arr2[] = {2, 4, 6, 8}
Output: arr3[] = {1, 2, 3, 4, 4, 5, 6, 8}
There are many ways of doing it, but here we will be discussing the most efficient way by using merge sort.
Using Merge Sort Algorithm
class Main{ public static int[] mergeArrays(int[] A, int[] B, int m,int n){ int i = 0, j = 0, k = 0; int[] C = new int[m+n]; // Traverse both array while (i<m && j <n){ // Check if current element of first // array is smaller than current element // of second array. If yes, store first // array element and increment first array // index. Otherwise do same with second array if (A[i] < B[j]) C[k++] = A[i++]; else C[k++] = B[j++]; } // Store remaining elements of first array while (i < m) C[k++] = A[i++]; // Store remaining elements of second array while (j < n) C[k++] = B[j++]; return C; } public static void main (String[] args){ int[] A = {1, 3, 5, 7}; int m = A.length; int[] B = {2, 4, 6, 8}; int n = B.length; int[] nums = mergeArrays(A, B, m, n); System.out.println("Array after merging"); for (int i=0; i < m+n; i++) System.out.print(nums[i] + " "); } }
Output
Array after merging - 1, 2, 3, 4, 5, 6, 7, 8 Time Complexity - O(n+m) Space Complexity - O(n+m)
In data structures there is something known as Hashed Array Tree which is also a type of dynamic array but it stores data in a separate memory fragment called leaves unlike dynamic arrays which stores data in the heap part of the JVM that too in contiguous order.
Its basic objective is to eliminate element duplication caused by automatic array resizing operations and to enhance memory usage patterns. In contrast to dynamic arrays, which are based on geometric expansion, HAT wastes rootlinear - O(√n) space.
We know that an array is a collection of elements of the same data type stored in contiguous memory locations and are of fixed size and cannot be resized until declared otherwise.
Now the error ArrayStoreException is thrown by the compiler when we try to add an element of an incompatible data type. While the other error ArrayOutOfBounds is thrown by the compiler when we are either accessing an element with -ve index value or illegal index. Let's understand these errors with the help of an example.
A must-know for anyone heading into an Array interview, this question is frequently asked in Array questions in Java.
We have been given an array and told to write a program to cyclic rotate this array by one - here, cyclic means in the clockwise direction.
Examples:
Input: arr[] = {1, 2, 3, 4, 5}
Output: arr[] = {5, 1, 2, 3, 4}
Approach: Using the k variable
In this approach, we will define a new variable, say k. Store the last element into k and shift the rest towards the end of the array. When all the elements have been shifted to the end, paste the k elements, which was also the last element of the array, and here is our chad and tare for us.
import java.util.Arrays; public class Main { public static void main(String args[]) { int[] a = {1, 2, 3, 4, 5}; int k = a[a.length-1]; for (int i = a.length-1; i > 0; i--) a[i] = a[i-1]; a[0] = k; System.out.print(Arrays.toString(a)); } }
Output -
{5, 1, 2, 3, 4} Time Complexity: O(n) Space Complexity: O(1)
HashSet class implements Set Interface and is backed up by a Hash Table to arrange and store elements in it. The working of a Hash table is little different than other methods of storing elements, in its elements are not stored in the same way they are given to a hashset.
It uses a unique concept of hash code to sort and store data making it easier to perform operations like add, remove, contains, and size assuming the hash function disperses the elements properly among the buckets, and the time complexity taken by the Hash et to perform all of these is O(1).
There are two ways in which we can convert a HashSet into an array:
Method 1: Traversing Hashset and adding every element to the array
We can traverse the HashSet using the forEach loop and add each element into the array one at a time.
import java.io.*; import java.util.*; class Main { public static void main(String[] args) { HashSet<String> set = new HashSet<String>(); set.add("1"); set.add("13"); set.add("27"); set.add("87"); set.add("19"); System.out.println("Hash Set Contains :" + set); String arr[] = new String[set.size()]; int i=0; // iterating over the hashset for(String ele:set){ arr[i++] = ele; } System.out.println("Array. contains : "+ Arrays.toString(arr)); } }
Output
Hash Set Contains :[1, 13, 27, 19, 87]
Array. contains : [1, 13, 27, 19, 87]
Method 2 : Convert the complete HashSet into an array using the toArray() method.
The toArray() method of ArrayList is used to return an array containing all the elements in ArrayList in the correct order.
Syntax:
public Object[] toArray() or public <T> T[] toArray(T[] a)
import java.io.*; import java.util.*; class Main { public static void main(String[] args) { HashSet<String> set = new HashSet<String>(); set.add("1"); set.add("13"); set.add("27"); set.add("87"); set.add("19"); System.out.println("Hash Set Contains :" + set); String arr[] = new String[set.size()]; // toArray() method converts the set to array set.toArray(arr); System.out.println("Array Contains : "+ Arrays.toString(arr)); } }
Output
Hash Set Contains :[1, 13, 27, 19, 87] Array Contains : [1, 13, 27, 19, 87]
We were given an array containing both positive and negative numbers. Our task is to rearrange the array elements so that positive and negative numbers are alternately placed. The sum of positive and negative numbers does not have to be equal.
If there are more positive numbers, they are displayed at the bottom of the array. If there are any more negative numbers, they are also added to the end of the array.
Example
Input : arr[] = [-1, 2, -3, 4, 5, 6, -7, 8, 9];
Output : arr[] = [9, -7, 8, -3, 5, -1, 2, 4, 6];
import java.io.*; class Main { // The main function that rearranges elements of given // array. It puts positive elements at even indexes (0, // 2, ..) and negative numbers at odd indexes (1, 3, ..). static void rearrange(int arr[], int n) { // The following few lines are similar to partition // process of QuickSort. The idea is to consider 0 // as pivot and divide the array around it. int i = -1, temp = 0; for (int j = 0; j < n; j++) { if (arr[j] < 0) { i++; temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // Now all positive numbers are at end and negative numbers at // the beginning of array. Initialize indexes for starting point // of positive and negative numbers to be swapped int pos = i+1, neg = 0; // Increment the negative index by 2 and positive index by 1, i.e., // swap every alternate negative number with next positive number while (pos < n && neg < pos && arr[neg] < 0) { temp = arr[neg]; arr[neg] = arr[pos]; arr[pos] = temp; pos++; neg += 2; } } // A utility function to print an array static void printArray(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); } /*Driver function to check for above functions*/ public static void main (String[] args) { int arr[] = {-1, 2, -3, 4, 5, 6, -7, 8, 9}; int n = arr.length; rearrange(arr,n); System.out.println("Array after rearranging: "); printArray(arr,n); } }
Output
Array after rearranging: 4 -3 5 -1 6 -7 2 8 9 Time Complexity: O(n) Space Complexity: O(1)
Consecutive numbers are those numbers that follow each other in order and have a difference of 1 between them. Like 1,2,3,4,5 is a set of consecutive numbers.
According to the problem, we have to find whether the elements of the given array are consecutive or not. And to do that we will be using two methods - sorting and XOR.
Method 1 - Sorting
Approach
Just sort the given array and fins whether the elements of the given array are consecutive or not.
import java.util.*; class Main { public static void main(String[] args) { int arr[] = {5, 4, 3, 1, 6, 2}; int n = arr.length; Arrays.sort(arr); // checking the adjacent elements for(int i=1;i<n;i++) { if(arr[i]!=arr[i-1]+1) { System.out.println("Elements are not Consecutive"); } } System.out.println("Elements are Consecutive"); } }
Output
Elements are Consecutive Time Complexity - O(n log n) Space Complexity - O(1)
Method 2 - Using XOR Property
Approach
import java.util.*; class Main { public static void main(String[] args) { int arr[] = {5, 4, 3, 1, 6, 2}; int n = arr.length; int min_ele = Arrays.stream(arr).min().getAsInt(); int num = 0; for(int i=0; i<n; i++){ num = num ^ min_ele ^ arr[i]; min_ele += 1; } if(num == 0) { System.out.println("Array is consecutive"); }else { System.out.println("Array is not Consecutive"); } } }
Output
Array is Consecutive Time Complexity - O(n) Space Complexity - O(1)
According to Geeks for Geeks, the reduce() method reduces the array to a single value. and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator.
Syntax
array.reduce( function(total, currentValue, currentIndex, arr), initialValue )
Where -
Total and current value are required parameters while the other three are optional parameters.
Coming back to the question, we have to double the value of the elements of the array like
Input arr[] = {1, 2, 3, 4, 5}
Output arr[] = {2, 4, 6, 8, 10}
var arr = [1, 2, 3, 4, 5]; var doubled = arr.reduce(function (memo, val) { memo.push(val * 2); return memo; }, []); console.log(doubled);
Output
[ 2, 4, 6, 8, 10 ]
In the above code, we have defined and used two variables - memo and val which are representing the total and currentValue parameter of the reduce() method.
The initial value of the memo variable will be 0 and that of val will be 1 which when multiplied by 2 will become 2 which will become the current value of memo which then gets returned to the function. Same process continues until we have reached the end of the array,
This question is a regular feature in Array interview questions, be ready to tackle it.
According to MDN docs, the map() method creates a new array populated with the results of calling a provided function on every element in the calling array. Simply said, this method allows us to iterate over an array and modify its elements using a callback function. The callback function will then be executed on each of the array's elements.
It is basically a replacement for loop and was introduced with other ES6 variables and methods. Instead of manually iterating over the array using a for loop, you can simply use the built-in Array.map() method.
Let us understand the map method with the help of an example program. We are given an array of size 5 and we are told to print the same array but this time by multiplying each element by 3.
Suppose your input array is {1, 2, 3, 4, 5}, then the output should be {3, 6, 9, 12, 15}.
var arr = [1, 2, 3, 4, 5]; for (let i = 0; i < arr.length; i++){ arr[i] = arr[i] * 3; } console.log("Using for loop " + arr); var arr1 = [1, 2, 3, 4, 5]; arr1.map((val) => { return arr1 * 3; }) console.log("Using map function " + arr1);
Output
Using for loop3,6,9,12,15
Using map function1,2,3,4,5
We can clearly see that map() function works the same way as the for loop.
This is a frequently asked question in Java Array interview questions.
According to MDN docs, the destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
Consider me choosing a shirt from my favorite assortment of stunning yet casual shirts. I will first search through the collection of shirts and unpack everything to get a better idea of what’s in store, which will aid me in making better decisions.
Destructuring is the same as unpacking the elements of an object or array. Destructuring gives us the ability to manipulate and switch out elements after they have been unpacked, depending on the operation we want to carry out.
Destructuring array elements in JavaScript is quite easy, we just have to use the bracket([]) notation to define destructuring.
const colorArr = ["red", "yellow", "blue", "green", "white", "black"]; const [first, second] = colorArr; console.log(first, second); // red, yellow
We can also use destructuring to store variable names which will be assigned to the name of the array storing the element.
const [var1, var2, ...] = arrayName;
There are endless possibilities when it comes to destructuring array elements. Like the one shown below:
var thing = ["Table", "Chair", "Fan"]; var [a, b, c] = thing; console.log(a); // Output: Table console.log(b); //Output: Chair console.log(c); //Output: Fan
Here we have mapped each variable on the array literal on the left-hand side to the same element at the same index in the array.
Thus we can say that destructuring has made extracting data from an array very simple and readable.
There are four ways in which we can empty an array:
Suppose we have the following array, and my task is to remove all its elements;
Let us see the different methods of emptying the array in action;
Equate the array to an empty array
Yes, this is one of the methods of turning an array of any numeric length to empty. This is by far the most easiest way to empty a array.
This array a previously had elements in it and was of length 5. But now its length has become zero as we can see in the above image. It works perfectly if we do not have any references to the original array.
In the above code, the variable b has stored the values of a in it or we can say has taken a reference of a, and then the variable a is assigned to an empty array. But its reference still persists.
Make its length 0
Another way to make an array empty is to set its length to zero.
Using the splice() method
This method of java script is used to modify the existing array by either removing or adding new elements in the array.
Syntax
array.splice(index, howmany, item1, ....., itemX)
Where -
Using pop() method
This method will remove every element one by one from the end of the array until the array is empty.
It's no surprise that this one pops up often in Array programming questions in Java.
The missing integer can be found using a very simple math formula - S = [n(n+1)]/2. Adding all the numbers given in the array and subtracting them from S will give us our answer or the missing number.
But this formula will not work if the array contains duplicates or is missing more than one number. If the array contains duplicates, sort the array and find and remove the duplicate element from the array and then use the above formula to find the missing number.
A common question in Array related interview questions, don't miss this one.
First of all, we won’t use the ‘==’ operator here, as it will not give the desired result, and it will compare them as objects.
The best way to check whether the two arrays are the same or not is first to compare their lengths, if they are the same, then we can proceed, but if not, return arrays' arrays are not the same.
Then sort both the arrays in ascending order and, using a loop compare each index value using the == operator - through this we can ensure that only the values are compared and not the whole array.
import java.io.*; import java.util.*; class Main { public static void main(String[] args) { int arr1[] = {1, 2, 4, 5, 3}; int arr2[] = {3, 4, 2, 1, 5}; int N = arr1.length; int M = arr2.length; if (N != M) System.out.println("Arrays are not equal"); Arrays.sort(arr1); Arrays.sort(arr2); for (int i = 0; i < N; i++) if (arr1[i] != arr2[i]) System.out.println("Arrays are not equal"); System.out.println("Arrays are equal"); } }
Output
There are other ways of checking whether the two arrays are the same or not - Using the Arrays.equals() method and Arrays.deepEquals() method.
A dynamic array is an array of variable size which will automatically expand its size when we try to insert a new element in it and there is no room for it. At this stage a new array is created with a new address and reference of double the size than the previous one so that the old elements as well the new elements can be appended. See the figure below.
In Java, Array works as a dynamic array while in C/C++ we have vectors showing us the same characteristics as of a dynamic array.
Implementation of Dynamic Array
In dynamic arrays elements are stored contiguously in the same manner from start to end but if after all the elements are appended and some space is left, that space is called reserved space.
We can add until that reserved space is consumed, but once it gets completely full then only a new array of double the size is created, and the same process continues ,of copying and inserting old and new elements in that new array and waiting until the reserved space gets filled. Or another way to add an element is that first, create a function that creates a new array of double size, copies all the elements from the old array, and returns the new array.
The table given below gives us a brief idea as to how much growth we can expect from different programming to show us when it comes to dynamic arrays:
Programming Language | Growth Rate |
---|---|
Java | 1.5 |
Python | ~1.125 |
C++ | 1.5 |
Go | 1.5 - 2 |
Yes, we can make both primitive data types and reference types volatile, but we can only make the variable pointing towards the array volatile and the whole array.
To understand this concept, first we have to understand that the concept of making an array volatile is simply taken to protect the elements of the array from multiple threads which can modify the data of the array, and that this is only possible with the help of volatile keywords.
The volatile keyword can be applied to both primitive data types and objects. It never caches the variable's value and always reads it from main memory. Although it cannot be used with classes or methods, it is perfectly fine with static variables. It stops the compiler from reordering code while ensuring visibility and ordering.
Associative Array | Indexed Array |
---|---|
Stored in the form of key and value pairs in either numeric or string format | Stored in the form of key and value pairs where each key each associated with itrs own specific value |
They have strings as their keys | They have integers as their keys which starts from 0 |
They are known as maps | They are not maps |
They behave like two column table | They behave like a single column table |
There are three ways of retrieving a class name of the array from the object:
Using the get*Name() Methods.
The simplest way to retrieve the class name of an array is to use the getClass() and getName() methods. The getClass() returns the runtime class of the array while the getName() method returns the name of the class/array class. There are many ways of calling them like getSimpleName() or getCanonicalName() which as the name suggests will return the simple and conical name of the underlying class.
Using the Class.getEnclosingClass() Method
This method is only used when we want to return an anonymous inner class that is an immediate enclosing class of an underlying class.
Using the Stack Trace Method
The first element which has been returned by the stack trace which acts just like a call stack contains the stack frame of the current method used for debugging and contains the information of the class
This method is not safe as some machines may omit some vital information from the stack frames while giving us a stack frame with incomplete information.
One of the most frequently posed Array interview questions, be ready for it.
An object is a thing that has characteristics (called properties), whereas an array is a list of data that is stored in a single variable. We can access, alter, and delete items from objects using brackets and dots, while we can access and modify items in arrays using a variety of built-in methods and zero-based indexing. Using various loops (e.g., for, for...in, for...of, forEach()), we can iterate over object properties and array items.
On the heap memory, all Java objects are dynamically allocated. Unlike in C++, where objects can be allocated on the Heap or the Stack. When we use the new() method in C++, the object is allocated on the heap unless it is global or static, in which case it is allocated on Stack.
Dimension of an array is the number of indices or subscripts that you need to specify an individual element of an array while subscripts are a means of displaying or defining the value of a particular element in an array.
A subscript is a number while a dimension is a description of the range of the number of keys. And you only need one subscript for the dimension of the array.
This is a frequently asked question in Array coding questions.
We know that arrays are the simplest form of data structures that can store multiple values at the same time, but they should be of the same data type and stored at contiguous memory locations. These values can be accessed and modified using their index or keys, which again is in the form of a number starting from 0.
These contiguous memory locations are the spaces created by the new() keyword on either the heap or stack memory, and the address of the element is calculated mathematically during run-time using the formula given below:
element address = (base address) + (element index * size of a single element)
Where?
The below table shows memory taken by different data types for Java and C++ programming languages:
Data Type | Java | C++ |
---|---|---|
byte | 1 byte | - |
char | 2 bytes | 1 byte |
short | 2 bytes | 2 bytes |
int | 4 bytes | 2 bytes |
Short int | - | 2 bytes |
Long int | - | 4 bytes |
long | 8 bytes | - |
float | 4 bytes | 4 bytes |
double | 8 bytes | 8 bytes |
Long double | - | 10 bytes |
boolean | 1 byte | 1 byte |
Array remains the same no matter the programming language. The difference comes in the methods we use to perform certain operations like removing a certain element from the array.
In JavaScript we have four different methods which can very easily do this task for us without us traversing through each element of the array. Those four methods are:
pop() Method - This method is used to remove elements from the end of the array and returns the removed array.
function func() { var arr = ["shift", "splice", "filter", "pop"]; // Popping the last element from the array var remove = arr.pop(); console.log("Removed element: " + remove ); console.log("Remaining elements: " + arr); } func();
Output
Removed element: pop
Remaining elements: shift,splice,filter
shift() Method - This method is used to removes the first element of the array.
function func() { var arr = ["shift", "splice", "filter", "pop"]; // Popping the last element from the array var remove = arr.shift(); console.log("Removed element: " + remove ); console.log("Remaining elements: " + arr); } func();
Output
Removed element: shift
Remaining elements: splice,filter,pop
splice() Method - This method is little different from the other two. With this method we can even add an element at any position of the array either using its index or the value which we want to add. For this question our main focus will be on how to remove an element from an array. See the following to understand this method clearly.
//Use the indexing of the splice method to remove elements from a JavaScript array. function func() { var arr = ["shift", "splice", "filter", "pop"]; var spliced = arr.splice(1, 1); console.log("Use the indexing of the splice method to remove elements from a JavaScript array. ") console.log("Removed element: " + spliced); console.log("Remaining elements: " + arr); console.log("\n"); } func(); //Using the value of the splice method to remove elements from a JavaScript array. function func1() { var arr1 = ["shift", "splice", "filter", "pop"]; for (var i = 0; i < arr1.length; i++) { if (arr1[i] === "splice") { var spliced = arr1.splice(i, 1); console.log("Using the value of the splice method to remove elements from a JavaScript array. ") console.log("Removed element: " + spliced); console.log("Remaining elements: " + arr1); } } } func1();
Output
Use the indexing of the splice method to remove elements from a JavaScript array.
Removed element: splice
Remaining elements: shift,filter,pop
Using the value of the splice method to remove elements from a JavaScript array.
Removed element: splice
Remaining elements: shift,filter,pop
filter() Method - This method is used to create a new array of those elements which satisfies the given condition.
function isPositive( value ) { return value > 0; } function func() { var filtered = [101, 98, 12, -1, 848].filter( isPositive ); console.log("Positive elements in array: " + filtered); } func();
Output
Positive elements in array: 101,98,12,848
Expect to come across this popular question in Array questions in Java.
While there is not much difference between these methods of array declaration, and both of them are accepted when it comes to array declaration in Java. The difference comes when we have to declare multiple array in a single line.
Note that the word declare is used and not initialized, as when we try to do that, we will receive an error by the compiler that both arrays are not initialized. See the below diagram for more clarity:
Also, we can declare first and then initialize;
In the end, there is no difference between int[] a and int[] a, where a is the array that is being declared. But int[] a is preferred more in java for array declaration and initialization, and the other method was included to help the traditional C/C++ developer get used to this language.
A must-know for anyone heading into an Array interview, this question is frequently asked in Array questions in Java.
We have been given an array and our task is to find the missing number and the duplicate number in that array and print them.
Example
Input: arr[] = {3, 1, 3}
Output: Missing = 2, Repeating = 3
Explanation: In the array, 2 is missing and 3 occurs twice
Approach
The approach in this method is simple yet effective. We traverse the array and while traversing, we use the absolute value of every element as an index, making the value at this index as negative to mark it as visited. If something has already been marked negative, then this is the repeating element. For finding the missing value, we traverse the array again and look for a positive value.
import java.io.*; import java.util.*; class Main { public static void main(String[] args) { int [] arr = {1, 2, 5, 4, 2}; int n = arr.length; // initializing temp array int [] temp = new int [n]; int miss = 0, repeat = 0; // setting temp array values for (int i = 0; i < n; ++i) { if(temp[arr[i]-1] == 0) temp[arr[i]-1] = 1; if(temp[arr[i]-1] == 1) repeat = arr[i]; } for (int i = 0; i < n; ++i) { if(temp[i] == 0) miss = i+1; } System.out.println("Missing: "+miss+" Repeating: "+repeat); } }
A common question in Array interview questions, don't miss this one.
Example
Input: list = [10, 20, 30, 20, 20, 30, 40, 50, -20, 60, 60, -20, -20]
Output: output_list = [20, 30, -20, 60]
lis = [10, 20, 30, 20, 20, 30, 40, 50, -20, 60, 60, -20, -20] uniqueList = [] duplicateList = [] for i in lis: if i not in uniqueList: uniqueList.append(i) elif i not in duplicateList: duplicateList.append(i) print(duplicateList)
Output
[20, 30, 60, -20]
One of the most frequently posed Array interview questions in Java, be ready for it.
Examples
Array : [5, 2, 3, 4, 1, 6, 7]
Sum= 7
Possible pairs: [5, 2], [3, 4], [1, 6]
Approach
def find(array, len, summ): print("Pairs whose sum is : ", summ) for i in range(len): for j in range(i, len): if (array[i] + array[j]) == summ: print(array[i], array[j]) array = [5, 2, 3, 4, 1, 6, 7] # Take sum as input from user summ = 7 # print array print("Arra = ", array) # call function find find(array, len(array), summ)
Output
Array = [5, 2, 3, 4, 1, 6, 7]
Pairs whose sum is: 7 -> 5 2, 3 4, 1 6
Examples
Input: arr[] = {1, 2, 3, 4, 5}
Output: Maximum is: 5; Minimum is: 1
Explanation: The maximum of the array is 5 and the minimum of the array is 1.
Approach - Using Greedy Algorithm
def findMinMax(arr, n): mini = arr[0] maxi = arr[0] for i in range(0, n): if (arr[i] < mini): mini = arr[i] elif (arr[i] > maxi): maxi = arr[i] return [mini, maxi] if __name__ == "__main__": arr = [1, 2, 3, 4, 5] N = len(arr) # Function Call ans = findMinMax(arr, N) print(f"Maximum is: {ans[1]}") print(f"Minimum is: {ans[0]}")
Output
Maximum is: 5
Minimum is: 1
Time Complexity: O(N)
Space Complexity: O(1)
A staple in Array interview questions, be prepared to answer this one.
Well, there are different ways of adding an element at the end of an array in python.
Adding elements at the end of the array using array module.
append() Method
fruit_list = ["Apple", "Banana"] print(f'Current Fruits List {fruit_list}') append_fruit = "Mango" fruit_list.append(append_fruit) print(f'Appended Fruits List {fruit_list}')
Output
Current Fruits List ['Apple', 'Banana']
Updated Fruits List ['Apple', 'Banana', 'Mango']
insert() Method
num_list = [1, 2, 3, 4, 5] print(f'Current Numbers List {num_list}') num = 10 index = 4 num_list.insert(index, num) print(f'Updated Numbers List {num_list}')
Output
Current Numbers List [1, 2, 3, 4, 5]
Updated Numbers List [1, 2, 3, 4, 10, 5]
extend() Method
extend_list = [] extend_list.extend([1, 2]) # extending list elements print(extend_list) extend_list.extend((3, 4)) # extending tuple elements print(extend_list) extend_list.extend("ABC") # extending string elements print(extend_list)
Output
[1, 2]
[1, 2, 3, 4]
[1, 2, 3, 4, 'A', 'B', 'C']
An input array has been given to us. Our task is to find the number of elements that have the most frequency. If there are more than one such element, print them in the form of an array.
Example
Input : arr[] = {1, 3, 2, 1, 4, 1}
Output : 1
Explanation: 1 appears three times in the array which is maximum frequency.
There are 3 ways of solving this problem:
Double Loop Approach - the outer loop is used to collect individual elements while the inner loop is used to calculate the frequency of the picked element and compares it with the maximum so far.
Time Complexity - O(n2)
Space Complexity - O(1)
Sorting Approach - This is one of the basic approaches that first comes to mind but is again a better approach compared to the double loop system. In this we first sort the array and then find the frequency of each element by doing a linear search.
Time Complexity - O(n log n)
Space Complexity - O(1)
Using Hashing Algorithm - Create a hashtable and store elements with their frequency count as key and value pairs, and then traverse the array to find the maximum frequency.
import math as mt def mostFrequent(arr, n): # Insert all elements in Hash. Hash = dict() for i in range(n): if arr[i] in Hash.keys(): Hash[arr[i]] += 1 else: Hash[arr[i]] = 1 # find the max frequency max_value = 0 res = -1 for i in Hash: if (max_value < Hash[i]): res = i max_value = Hash[i] return res # Driver Code arr = [1, 3, 2, 1, 4, 1] n = len(arr) print(mostFrequent(arr, n))
Output
The element that has the most frequency is 1.
Time Complexity - O(n)
Space Complexity - O(n)
Note- There is another way of solving it which is more efficient than the one above not in terms of time as we do need to traverse the array once to calculate the frequency of each element, but in terms of space. The name of that method is Moore’s voting Algorithm.
Expect to come across this popular question in Array interview questions.
There are a total of eight methods through which we can sort an array. They are:
asort() - this function is used to sort associative arrays in ascending order according to their value.
<?php $age = array("john"=>"35", "smith"=>"37", "Joe"=>"43"); asort($age); print_r($age); ?>
Output
Array ( [john] => 35 [smith] => 37 [Joe] => 43 )
arsort() - this method is the reverse of asort() method. In this we sort the associative array in descending order.
<?php $age = array("john"=>"35", "smith"=>"37", "Joe"=>"43"); asort($age); print_r($age); ?>
Output
Array ( [Joe] => 43 [smith] => 37 [john] => 35 )
ksort() - sort() function was used to sort the associative array into ascending order of the value. This method is used to sort the associative array in the order of keys.
<?php $age = array("john"=>"35", "smith"=>"37", "Joe"=>"43"); asort($age); print_r($age); ?>
Output
Array ( [Joe] => 43 [john] => 35 [smith] => 37 )
krsort() - Opposite of ksort(). Sorts the associative array in descending according to their keys.
<?php $age = array("john"=>"35", "smith"=>"37", "Joe"=>"43"); asort($age); print_r($age); ?>
Output
Array ( [smith] => 37 [john] => 35 [Joe] => 43 )
sort() - Sorts the array in ascending order
<?php $cars = array("Swift", "Honda City", "Elentra"); sort($cars); print_r($cars); ?>
Output
Array ( [0] => Elentra [1] => Honda City [2] => Swift )
rsort() - Sorts the array in descending order
<?php $cars = array("Swift", "Honda City", "Elentra"); sort($cars); print_r($cars); ?>
Output
Array ( [0] => Swift [1] => Honda City [2] => Elentra )
There are three types of arrays – Indexed array, Associative Array, Multidimensional Array.
Indexed Array
A type of array in which we can store anything but each element has its own index and that will be a numeric value starting from 0. These arrays can be created in two different ways -
1st way:
$season=array("summer","winter","spring","autumn");
2nd way:
$season[0]="summer"; $season[1]="winter"; $season[2]="spring"; $season[3]="autumn";
Associative Array
This type of array is also quite similar to Index Array but in this the unique key is in the form of a string and not a number. There are again two ways of doing it.
1st way:
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
$salary["Sonoo"]="350000"; $salary["John"]="450000"; $salary["Kartik"]="200000";
Multidimensional Array
Multi-dimensional arrays are such arrays that store another array at each index instead of a single element. In other words. Simply said, very element in this array can be an array and they can also hold other sub-arrays within. Arrays or sub-arrays in multidimensional arrays can be accessed using multiple dimensions.
To sort an array without using any in-built function, we have to use a double loop system in which the outer loop will read the value inside the inner lop we will compare the value with the help of a temp variable as shown which has been initialized as 0.
<?php $array = array(1, 6, 23, 10, 3, 2, 15,7); $total = count($array); for ($i=0; $i < $total; $i++) { for ($j=$i+1; $j < $total; $j++) { if($array[$i] > $array[$j]) { $temp = $array[$i]; $array[$i] = $array[$j]; $array[$j] = $temp; } } } echo '<pre>'; echo "Ascending Sorted Array is: "; print_r($array); ?>
Output
( [0] => 1 [1] => 2 [2] => 3 [3] => 6 [4] => 7 [5] => 10 [6] => 15 [7] => 23 )
<?php $array = array(2,7,10,25,35,65,80); $count = count($array); $min = $array[0]; for ($i=0; $i < $count; $i++) { if($array[$i] < $min) { $min = $array[$i]; } } echo "minmum value $min"; ?>
Output
2 Program to find the maximum number <?php $array = array(2,7,10,25,35,65,80); $count = count($array); $max = $array[0]; for ($i=0; $i < $count; $i++) { if($array[$i] > $max) { $max = $array[$i]; } } echo "maximum value $max"; ?> Output 80
This is a frequently asked question in Array interview questions.
An array is a type of data structure that we use to store data in contiguous memory locations. But this data should be of the same data type as the one used for array declaration.
The advantage of having a contiguous memory is that we can easily find the location of any element in the array by just finding its index value. For example, if we want to access an element present at the 3rd index(4th element) in an array arr, then we can write arr[3]. This is generally because when it comes to arrays, we mostly follow 0-based indexing and not 1-based indexing.
While this is good and all, an array cannot be resized once declared. This may sometimes lead to memory leaks which are not good for any programmer.
Expect to come across this popular question in Programming questions on Arrays.
The main difference between them is that array is static, meaning we have to specify the size of the array along with its data type to initialize an array which can sometimes become the reason for memory leaks. While in the case of ArrayList, no such memory leaks happen as it is dynamic, meaning it can adjust its size according to the input given.
This is because, in the case of an ArrayList, as soon as an element is added, JVM checks whether it has enough space or not by calling the ensureCapacity() method. If the space exists, the element gets added to the ArrayList, else the ArrayList gets resized.
In the resizing process, an array of a larger size is created, the old array is copied to the new array using the Arrays.copyOf method, and the new array is then assigned to the existing array.
Let us understand some more differences in a tabular format:
Array | ArrayList | |
---|---|---|
Definition | An Array is a collection of similar data types stored in contiguous memory locations. | An ArrayList is a class of Java Collections framework which contains popular classes like Vector, HashMap, etc. |
Performance | It is fast as compared to ArrayList. | Its resizing ability slows it down. |
Type of Data Structure stored | It can store both objects and primitive data type like int, long, float, etc. | It cannot store primitive data type and automatically converts primitive data types into objects. |
Type - Safety | It is not type safe as we cannot save generics along with the array thus making the array convertible in nature. | ArrayList, on the other hand, can store generics. Hence is not convertible and thus is type-safe. |
In Java, when we initialize an array with the new keyword, the size argument is of the type int and a 32-bit Java int can go up to 2,147,483,647 elements which can be considered as the theoretical max limit of an array when it is initialized with an int data type.
However, in reality, the virtual machines of different operating systems may not allocate every bit of it to the array elements. Thus, the maximum number of elements a Java array can hold is typically a little less than the upper limit of a Java int.
In the above example, we tried to test out this theoretical max limit of an array but what we received was an OutOfMemory exception. This is because this is not the actual max limit of an array. Moreover, it totally depends upon the type of OS we are using.
Commonly we use the terms ‘size’ when we want to know how many elements an array can hold, on the contrary in java we do not have a size() method nor do we have a length() method in java. What we do have is the length property which we use to find out the length of the array or the number of elements it holds.
To confuse the matters even more, Java Collection class that implements a list interface does have a size() method. Collection classes like Vector, ArrayList, and Stacks have a size method that is used to calculate the number of elements present in them.
A must-know for anyone heading into an Array interview, this question is frequently asked in Array interview questions.
Advantages
Disadvantages
Arrays | Dictionary |
---|---|
It is a collection of the same data types. | It is a collection of data values. |
Look up time in case of arrays is O(n). | Look up time in case of Dictionary is O(1). |
It is compulsory that the elements will be stored in contiguous memory locations. | It is not compulsory that the elements will be stored in contiguous memory locations. |
In case of arrays, we can duplicate elements and store them . | In case of Dictionary, we cannot duplicate elements as they are not allowed in it. |
Items are not represented as key and value pairs. | Items are represented as key and value pairs. |
Values can be accessed randomly with the help of its index. | Well, there are quite a few ways to get a random value from a dictionary but the thing common in each one of them is the use of key. |
It's no surprise that this one pops up often in Programming questions on Arrays.
Passing an array as a parameter in C and C++ will not give us the correct answer, as in C and C++, array parameters are treated as pointers. Although sizeof() can tell you the size of the pointer and the size of the type it points to, it cannot tell you how many bytes are occupied by the entire array.
Let us understand this with the help of an example:
#include <stdio.h> void fun(int arr[]) { int i; // sizeof should not be used here to get number // of elements in array int arr_size = sizeof(arr) / sizeof(arr[0]); for (i = 0; i < arr_size; i++) { arr[i] = i; } // executed two times only } // Driver Code int main() { int i; int arr[4] = { 0, 0, 0, 0 }; fun(arr); // use of sizeof is fine here for (i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) printf("%d", arr[i]); getchar(); return 0; }
The above code will run without any run-time or compile-time errors, but it will return an incorrect result because the function fun() receives an array parameter 'arr[]' and attempts to find the number of elements in arr[] using the sizeof operator.
Array parameters are treated as pointers in C. As a result, the expression sizeof(arr)/sizeof(arr[0]) becomes sizeof(int *)/sizeof(int), yielding 2 (size of int* is 8 bytes because it is a pointer, and a pointer occupies 8 bytes of memory, and int is 4) and the for loop inside fun() is executed only twice, regardless of the size of the array. In such cases, sizeof should not be used to obtain the number of elements.
Dynamic Arrays or Vectors in C/C++ or ArrayList in Java are nothing more than an array that can resize itself according to the number of elements present in the array.
A basic array is also known as a fixed array as we have to specify the number of elements that the array will hold at the time of initialization of the array which then cannot be resized as the number of inputs increases in the array.
But in the case of dynamic, the size of the array usually gets doubled automatically (depending upon the programming we are writing code in).
A jagged Array is also called an Array of Arrays, irregular Array, Ragged Array, etc as it is a multidimensional array that has member arrays of different sizes. Like in a 2D array, the first array contains three elements, and the second array consists of four elements.
Below is an implementation of the Jagged Arrays:
class Main { public static void main(String[] args) { int[][] Array = new int[2][]; Array[0] = new int[3]; Array[1] = new int[4]; int counter = 0; for(int row=0; row <Array.length; row++){ for(int col=0; col < Array[row].length; col++){ Array[row][col] = counter++; } } for(int row=0; row < Array.length; row++){ System.out.println(); for(int col=0; col < Array[row].length; col++){ System.out.print(Array[row][col] + " "); } } } }
Output
This is one of the most asked programming questions on arrays. We will be answering this question on the basis of JavaScript programming language. There are five methods using which we can very easily find any element in an array in JavaScript. They are:
1. Array.find()
This method is used to find the element in the array that specifically satisfies the testing function or the test criteria. The first element that satisfies this criteria will be returned as the result of the callback function.
If there is no such element in the array, undefined will be returned.
It can also be used to find an element in an array of objects. See the below code:
2. Array.findIndex()
It is quite similar to the find() method. The only difference is, it will return the index of the first element that satisfies the condition of the callback function and if by any chance no element satisfies the given condition, it will return -1.
3. Array.indexOf() method
It is quite similar to findIndex() method as it will also return the index of the element which will satisfy the condition of the callback function. The only difference is that this method uses strict equality to compare the specified search element to array items. So, if you were looking for the index at which the value 5 is, but you submitted '5' to this function, the element will not be discovered and the method would return -1.
We can also provide a second argument which is optional by all means but gives us the power of telling the compiler to begin its search from the specified index as shown in the above image.
There is one more method - the lastIndexOf() method. This method works the same way as the indexOf() method works, but this method returns only the last element of the array which satisfies the condition.
4. Array.includes() method
The fourth method on our list is the includes() method. Like the other methods it is also used to tell whether a specific element is present in the array or not, but this method returns a boolean value - true if the value is present and false if it doesn’t.
This method just like the indexOf() method uses strict comparison before returning the boolean as the answer. And it also supports NaN comparisons.
5. Array.some() method
This method is quite different from the above 4. It checks whether the array contains at least one element that satisfies the condition. If it does, the method returns true else false.
Arrays are the simplest type of data structure that can store multiple elements of the same data type in contiguous memory locations. But it doesn’t stop here, it has many applications not only in the world of programming but in real life as well.
The basic use of arrays that we can think of is our contacts which are stored in our mobile phones. An array is used to keep track of all the phone contacts in our phone.
Other real-time applications of arrays include:
A common question in Array interview questions, don't miss this one.
It is one of the popular questions asked in array program interviews for java. Given an array, our task is to print the same array in reverse order. Let us understand this with the help of a diagram and example.
Example
arr[] = {1, 2, 3, 4, 5, 6, 7}; //original array arr[] = {7, 6, 5, 4, 3, 2, 1}; //reversed array
Let us see how this problem is solved in the most effective way.
Iterative Approach
import java.util.*; class Main { public static void main(String[] args) { int arr[] = {1, 2, 3, 4, 5, 6, 7}; int n = arr.length; int start = 0; int end = n-1; while (start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } System.out.println(Arrays.toString(arr)); } }
Output
[7, 6, 5, 4, 3, 2, 1] Time Complexity - O(n) Space Complexity - O(1)
This is yet another example of what type of questions are asked in array program in java for interviews. Given a sorted array arr[] and a number x, write a function that counts the occurrences of x in arr[]. Expected time complexity is O(Logn).
Example
Input: arr[] = {1, 1, 2, 2, 2, 2, 3,}, x = 3
Output: 1
Approach
We can do this in two ways - using linear search and using binary search. The method in which we find the occurrence of x using linear search has a time complexity of O(n), but if we use binary search we can reduce the time complexity to O(log n) which we were told in the question.
class Main { // A recursive binary search function. It returns location // of x in given array arr[l..r] is present, otherwise -1 static int binarySearch(int arr[], int l, int r, int x) { if (r < l) return -1; int mid = l + (r - l) / 2; // If the element is present at the middle itself if (arr[mid] == x) return mid; // If element is smaller than mid, then it can only be // present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); // Else the element can only be present in right subarray return binarySearch(arr, mid + 1, r, x); } // Returns number of times x occurs in arr[0..n-1] static int countOccurrences(int arr[], int n, int x) { int ind = binarySearch(arr, 0, n - 1, x); // If element is not present if (ind == -1) return 0; // Count elements on the left side. int count = 1; int left = ind - 1; while (left >= 0 && arr[left] == x) { count++; left--; } // Count elements on the right side. int right = ind + 1; while (right < n && arr[right] == x) { count++; right++; } return count; } // Driver code public static void main(String[] args) { int arr[] = {1, 2, 2, 2, 2, 3, 4, 7, 8, 8}; int n = arr.length; int x = 2; System.out.print(countOccurrences(arr, n, x)); } }
Output
4 Time Complexity: O(log n) Space Complexity: O(1)
Given two arrays find the union and intersection in linear time complexity.
Example
Input: arr1[] = {2, 4, 6, 8, 7}; arr2[] = {1, 3, 5, 2, 8);
Output:
Union: {1, 2, 3, 4, 5, 6, 7, 8} Intersection: {2, 8}
Approach
For finding the union of the array
For finding the insertion of array
import java.io.*; import java.util.*; class Main { /* Function prints union of arr1[] and arr2[] m is the number of elements in arr1[] n is the number of elements in arr2[] */ static int printUnion(int arr1[], int arr2[], int m, int n) { int i = 0, j = 0; int z = 9; int arr[] = new int[n]; while (i < m && j < n) { if (arr1[i] < arr2[j]) System.out.print(arr1[i++] + " "); else if (arr2[j] < arr1[i]) System.out.print(arr2[j++] + " "); else { System.out.print(arr2[j++] + " "); i++; } } /* Print remaining elements of the larger array */ while (i < m) System.out.print(arr1[i++] + " "); while (j < n) System.out.print(arr2[j++] + " "); return 0; } static void printInsertion(int A[], int B[], int n, int m) { int i=0,j=0,z=0; ArrayList<Integer> arr = new ArrayList<Integer>(); while(i < n && j < m){ if(A[i]==B[j]){ arr.add(A[i]); i++;j++; } else if(A[i]<B[j]) i++; else j++; } int array[] = new int[arr.size()]; for(i = 0;i<arr.size();i++){ array[i] = arr.get(i); } System.out.println(); System.out.println("Intersection points are " + Arrays.toString(array)); } public static void main(String args[]) { int arr1[] = { 1, 2, 4, 5, 6 }; int arr2[] = { 2, 3, 5, 7 }; int m = arr1.length; int n = arr2.length; printUnion(arr1, arr2, m, n); printInsertion(arr1, arr2, n, m); } }
Output
Union of the array - {1, 2, 3, 4, 5, 6, 7} Intersection of the array - {2, 5} Time Complexity : O(m+n) Space Complexity: O(1)
Before answering this question, let us understand the difference between a data type and a data structure:
A. Data Type
A type of value that is stored in a variable is called a data type. There are a two types of data types - primitive and non-primitive. Below diagram will show you different types of primitive and non-primitive data types.
B. Data Structure
It is a way of storing, organizing, and arranging data on a computer so that it can be updated efficiently. There are different types of basic and advanced data structures in almost all programming languages. Some of them are listed below:
Now according to the definition of Arrays, arrays are a collection of elements of the same data type stored at contiguous memory locations. We can clearly state that Array is a type of Data Structure and not a Data Type. This is because it can store, access, delete and update the existing values and we can add new values into it.
There are two ways of initializing an array:
But if for some reason we don't initialize the array in both scenarios, the array will be initialized with some random values, and at each memory location as in the array, elements are stored in contiguous order. These random values can again be categorized into two categories - Default values and Garbage values.
In the case of Java Programming Language, if the elements of the array which has already been declared are not set to their specific values, they will be initialized as the default values of the Data Type that was used for Array Declaration.
In the case of JavaScript, this default value is undefined. While in the case of C++, these random values will be the garbage values that the compiler has initialized the array with, and it's not a good thing for a programmer to rely on. While he can do so in the case of Java.
C++
JS
One of the most frequently posed Array coding questions, be ready for it.
The question is that you are given an array of size ‘n’ and a target value. You have to find the index at which this target value is and also tell its time complexity.
Approach
We will run a loop through the input array and check whether the given target value is present or not. If it’s present, we will return its index value, and if it's not, we will return -1.
We can also use Binary Search Algorithm, but we can only use it if the given array is sorted. And we just cannot sort our array as it will increase the time complexity to O(n log n).
Approach
import java.io.*; import java.util.*; class Main { static void binarySearch(int v[], int x) { int lo = 0, hi = v.length - 1; while (hi - lo > 1) { int mid = (hi + lo) / 2; if (v[mid] < x) { lo = mid + 1; } else { hi = mid; } } if (v[lo] == x) { System.out.println("Found At Index " + lo ); } else if (v[hi] == x) { System.out.println("Found At Index " + hi ); } else { System.out.println("Not Found" ); } } public static void main (String[] args) { int v[]= {1, 3, 4, 5, 6}; int x = 1; binarySearch(v, x); x = 6; binarySearch(v, x); x = 10; binarySearch(v, x); } }
Output
In Java, we have something known as JVM - Java Virtual Machine. It is mainly a part of JRE - Java Runtime Environment and acts as a run-time engine to run Java applications. JVM is the one that actually calls the main method present in a java code.
Now to answer the question as to why arrays are stored in the heap part of the JVM and not in any other part, we first have to understand that in Java reference types are stored in the Heap area. As arrays are also referenced types, (they can be created using the “new” keyword) they are also stored in the Heap area.
Let us understand this concept with the help of an example:
int myArray[]; //array declaration myArray = new int[4];//memory allocation using the new keyword myArray[0] = 25;//allocating memory myArray[1] = 32;//allocating memory myArray[2] = 56;//allocating memory myArray[3] = 93;//allocating memory
The int myArray[] is just a reference to the array of four integers. While to allocate the memory to an array, we have to use the new keyword. See the diagram below to get a better understanding of the concept.
The above statement is true. This is because in Java language we are free to use as many array-specific syntaxes as we want for both initializing (putting explicit values into an array) and constructing (creating the array object itself) in a single line.
Let us see how the above statement is true. We have initialized a variable y as 56 and it is inside an array of length 5. Now the compiler will replace the value of the y variable with its value as we print the array. See the image below.
But what if we try to initialize the variable after initializing the same array. We will get an error. This is because we have initialized the y variable after using it in the array which becomes the root cause of the error as y is an unknown variable for him.