Arrays Flashcards
Time complexity to access an element in array?
O(1)
Time complexity to search in array/list?
O(n)
Time complexity of search in a sorted array?
O(log(n))
Time complexity to Insert an item in array/list?
O(n) - Insertion, in the middle of an array, would require shifting all the subsequent elements to the right by one and that takes O(n)
Time complexity to insert an element at the end of an array/list?
O(1)
Time complexity to remove an element from the middle of an array/list?
O(n) - Removal would require shifting all the subsequent elements to the left by one and that takes O(n)
Time complexity to remove an element from the end of an array/list?
O(1) - Special case of removal where no other element needs to be shifted.
Advantages of Arrays
- Storing multiply elements of the same kind w/ one single variable name
- Accessing elements if fast if you have the index
- Arrays are better at processing many values easily and quickly
- Sorting and searching the values is easier in arrays
Disadvantages of Arrays
- Addition/removal of elements to/from the middle of the array is slow because the remaining elements need to be shifted to accomodate new/missing elements (An exception to this is if the position to be inserted/removed is at the end of the array.)
- Depending on the language, arrays are fixed in size. it cannot alter its size after initialization. If an insertion causes the total number of elements to exceed the size, a new array has to be allocated and the existing elements have to be copied over. The act of creating a new array and transferring elements over takes O(n) time.
What is a Subarray?
A range of contiguous values within an array.
Example: given an array [2, 3, 6, 1, 5, 4], [3, 6, 1] is a subarray while [3, 1, 5] is not a subarray.
What is a Subsequence?
A sequence that can be derived from the given sequence by deleting some or no elements without changing the order of the remaining elements.
Example: given an array [2, 3, 6, 1, 5, 4], [3, 1, 5] is a subsequence but [3, 5, 1] is not a subsequence.
What is an Array?
Arrays hold values of the same type at contiguous memory locations. In an array, we’re usually concerned about two things - the position/index of an element and the element itself