A.1.1: Arrays

Learning Objectives

  1. Understand common array functions and their use cases

  2. Get familiar with solving algorithm problems with arrays

Common array functions

Assume we start with the following example array arr. Scroll right in the table below to see explanations.

const arr = [2, 1, 3];
FunctionResulting value of `arr`Return valueExplanation

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]

[]

Adding and removing elements from the middle of an array requires shifting every following element by a constant number of indexes

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.

Exercises

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.

Pre-Class

  1. Running Sum of 1D Array (LeetCode)

  2. Richest Customer Wealth (LeetCode)

Part 1

  1. Valid Mountain Array (LeetCode)

  2. Sherlock and Array (HackerRank)

  3. Jewels and Stones (LeetCode)

  4. Missing Numbers (HackerRank)

  5. Sparse Arrays (HackerRank)

Part 2

  1. Count Items Matching a Rule (LeetCode)

  2. Kids with the Greatest Number of Candies (LeetCode)

  3. Left Rotation (HackerRank)

  4. Number of Good Pairs (LeetCode)

Part 3

  1. Sort Array by Parity (LeetCode)

  2. Shuffle the Array (LeetCode)

  3. String Matching in an Array (LeetCode)

    1. Hint: You may find the array sort method helpful to sort input array by word length

    2. Hint: You may find nested for loops helpful where the indexes follow the pattern in the below code sample

  4. Ice Cream Parlor (HackerRank)

Code sample for String Matching in an Array:

for (let i = 0; i <= arr; i += 1) {
  for (let j = i+1; j <= arr; j += 1) {
    // Compare arr[i] and arr[j] without duplicate checks
  }
}

More Comfortable

  1. Squares of a Sorted Array (LeetCode)

  2. Sort Array by Parity II (LeetCode)

  3. Relative Sort Array (LeetCode)

Last updated