A.1.1: Arrays
Last updated
Last updated
Understand common array functions and their use cases
Get familiar with solving algorithm problems with arrays
Assume we start with the following example array arr
. Scroll right in the table below to see explanations.
Function | Resulting value of `arr` | Return value | Explanation |
---|---|---|---|
After attempting each problem, find solutions in the Leaderboard tab (HackerRank, may be on left side of page) or Solution or Discuss tabs (LeetCode) on that problem's page. If you get stuck for more than 15 minutes, review and understand the solutions and move on. Come back and re-attempt the problem after a few days.
Valid Mountain Array (LeetCode)
Sherlock and Array (HackerRank)
Jewels and Stones (LeetCode)
Missing Numbers (HackerRank)
Sparse Arrays (HackerRank)
Count Items Matching a Rule (LeetCode)
Kids with the Greatest Number of Candies (LeetCode)
Left Rotation (HackerRank)
Number of Good Pairs (LeetCode)
Sort Array by Parity (LeetCode)
Shuffle the Array (LeetCode)
String Matching in an Array (LeetCode)
Hint: You may find the array sort
method helpful to sort input array by word length
Hint: You may find nested for loops helpful where the indexes follow the pattern in the below code sample
Ice Cream Parlor (HackerRank)
Code sample for String Matching in an Array:
arr[1]
[2,1,3]
1
We can access value at specific index in array in a single operation
arr.push(4)
[2,1,3,4]
4
We can append to end of array in single operation
arr.length
[2,1,3]
3
JS Array data structure stores up-to-date length that we can retrieve in constant time
Math.max(...arr)
[2,1,3]
3
Get max element of unsorted array requires iterating over every element in array
arr.shift()
[1, 3]
2
Removing element from start of array requires shifting every element to the left by 1 index
arr.unshift(4)
[4,2,1,3]
4
Adding element to start of array requires shifting every element to the right by 1 index
arr.splice(1, 0, 4)
[2,4,1,3]
[2, 4, 4, 1, 3]
Adding and removing elements from the middle of an array requires shifting every following element by a constant number of indexes. The splice command starts at index 1, will not remove any items but insert the value 4
arr.sort()
[1,2,3]
[1,2,3]
The fastest sorting algorithms run in O(nlogn)
time, different JS runtimes implement different sorting algorithms that all have similar runtimes.