Just like lists are used to organize items in the real world, arrays are used to organize data in computer memory. An Array represents a collection of similar items stored in computer memory.
What is an Array?
Arrays are the building blocks of data structures in computer science. Stacks and LinkedLists are directly derived from arrays. It is used to group similar kinds of data in a contiguous memory location in computer memory for fast access.
Each item in an array is called a data element and number of items stored in array is called its size.
Each item has a maximum of 2 neighbors other than the first and the last element which only has 1 neighbor.
Each data element is assigned an index which signifies it’s position in the array.
Index is always non negative, starts from 0 and ends at size - 1. It makes it easy to read a value from array for e.g. array[2], else we would need the traverse the whole data structure.
Arrays are stored in memory using a reference pointer, which points to the first element in the array.
Memory allocation for Arrays
To store elements in arrays, we need to first define a chunk of memory as big as the number of items, which reserves the space in memory and creates a pointer to reference the first memory location in that chunk. Then we can store all items in their respective memory locations, each item having it’s own index. This approach enables fast access to each element, all we need to do it specify what index we want to access the value of.
However this also acts as a drawback. If the reserved memory has been exahusted, we would need a define a new array with more memory and then copy all items over to the new array. This is time consuming and ineffective.
Types of Arrays
Arrays can store any type of data including primitive datatypes like int, char, float, short, long, double, byte, bool or non-primitive data type values like Java classes or pointers to other arrays.
one dimensional arrays contains primitive or non-primitive data types
two dimensional arrays contain pointers to other arrays
three dimensional arrays are used to assemble data in a cube-like structure, these are indexed by three variables.
Key Points:
2D array is an array of pointers which hold reference to other arrays, which results in a matrix/table like structure. For example, a matrix that stores student name and a pointer to all the grades in 5 say subjects.
All 2D or 3D array values have to be of the same data type.
Multi dimensional arrays are widely used in game development.
Sample Definitions (Java)
1D Array
Declaration:
Instantiation:
Assignment:
2D Array
Declaration:
Instantiation:
Assignment:
Common Mistake
One important point to note is that all arrays and (subarrays in case of 2D) must be instantiated before any value assignment or else it will throw an error:
Challenges
Challenges 1 - 10
Challenge 1 : Remove Even Integers from Array
First find the number of odd elements in the given array by iterating over it and incrementing a count variable if an element is odd.
Next, initialize an array with a length equal to the quantity of odd numbers in the array, then fill it with the odd numbers in the array.
Time Complexity: O(n)
Output
Challenge 2 : Merge Two Sorted Arrays
We start by creating a new empty array of the size equal to the sum of both sorted arrays passed as the parameters of the function. Starting off from the index 0, individually compare the elements at corresponding indices of both arrays. Place the smaller one in the resultant array, and increment the index of the array where you find the smallest. Keep repeating this till you hit the end of one array. Move the elements of the other array into the resultantArray as it is.
Time Complexity: O(n + m)
Output
Challenge 3: Find Two Numbers that Add up to “n”
Solution 1: Nested Loop
Traverse the whole array of the given size, for each element in an array and check if any of the two elements add up to the given number n. So, use a nested for-loop and iterate over the entire array for each element.
Time Complexity = O(n^2)
Output
Solution 2: Sort => 2 Indices
Solve this by first sorting the array. Then using two variables, one starting from the first index of the array and second from size−1 index of the array. If the sum of the elements on these indexes of the array is smaller than given value n then increment index from the start else decrement index from the end, until the given value n is equal to the sum. Store the elements on these indexes in result array and return it.
For Time Complexity, Algo itself takes O(n) time, Now assuming sort opration takes O(n log(n)) time, for example Quicksort
Time Complexity = O(n log(n))
Output
Solution 3: Use Hash Sets
Solve this problem by using a HashSet called set. For every element in the arr array, the difference of key & each element (n-arr[i]) is computed. If it’s not already present in the set, this value is added and index moves to the next element of the array.
Note that HashSet is a class of Set interface, therefore it does not allow duplicate values. HashSet is implemented in the backend using a Hash Table. Therefore the lookup time is constant i.e O(1)
As soon as the difference of value stored in set becomes equal to any value in the array arr, the 2 numbers adding up to n are found!
Therefore, an array of size 2 called result is created to store the pair that sums up to ‘n’. If Hash-Set contains an array element, result[] is updated, or else it is returned containing the default value.
The array is iterated over once for each element, so time complexity is O(n).
Time Complexity = O(n)
Output
Challenge 4: Array of Products of All Elements Except Itself
Solution 1: Nested Loop
Time Complexity: O(n^2)
Output
Solution 2: Sequential Loop
The algorithm for this solution is to first create a new array with products of all elements to the left of each element. Then multiply each element in that array to the product of all the elements to the right of the array by traversing it in reverse.
Time Complexity: O(n)
Output
Challenge 5 : Find Minimum Value in Array
Time Complexity: O(n)
Output
Challenge 6: First Non-Repeating Integer in an Array
Solution 1: Nested Loops
Time Complexity: O(n^2)
Output
Solution 2: Using Dictionary - HashMap
Time Complexity: O(n)
Output
Challenge 7: Find Second Maximum Value in an Array
Solution 1: Traversing Array Twice
Time Complexity: O(n)
Output
Solution 2: Traversing Array only Once
Time Complexity: O(n)
Output
Challenge 8: Right Rotate the Array by 1 index
Store the last element in a variable.
Traverse the array backwards and replace element at current index with element and (current - 1) index.
Finally replace the element at 0th index with the temp value stored before.
Copy temp array over original array and return original array
Time Complexity: O(n)
Output
Solution 2: Re-arranging in Place
Use two pointers: 1 to store interation index, 2 to store index of negative numbers being swapped
Traverse the array, if element is negative - swap with last positive element and increment the 2nd index, else move to next interation
Time Complexity: O(n)
Output
Challenge 10: Rearrange Sorted Array in Max/Min Form
Solution 1: Using 2 pointers and a switch
Since the array is sorted, smallest elements will be in the beginning and largest at the end.
Set the first pointer to start of array
Set the second pointer to last of array
Set a switch variable to false
Add the element at the first pointer to a temp list, increment the first pointer and flip the switch
In the next iteration, add the element at the second pointer, decrement thte second pointer anf flip the switch
This continues till the array is complete
Now copy the temp array (in max/min form) to the original array and return the array
Time Complexity: O(n)
Output
Solution 2: In-place Replacement
This is a unique solution in which we use multipliers to store the max min element, remainders to store the original elements an division by max element to get the output array in max/min form.
min_index = pointer at start of array
max_index = end of array
max element = element at the last index + 1
we traverse the array in order
for even index: we add (arr[max_index] % max_element) * max_element to the current element at even index, then decrement max_index
for odd index: we add (arr[min_index] % max_element) * max_element to the current element at min_index, then increment min_index
finally we get the max/min array by dividing each value by max_element
Time Complexity: O(n)
Output
project showcase + professional profile | Read the fine print. README