Hello there! In this unit, we're offering an engaging coding lesson that highlights the performance efficiencies offered by the utilization of Map
in JavaScript. We'll address a list-based problem that requires us to make an optimal choice to minimize the size of our list. Excited? So am I! Let's get started.
In this unit's task, we'll manipulate a list of integers. You are required to construct a JavaScript function titled minimalMaxBlock()
. This function should accept an array as an input and compute an intriguing property related to contiguous blocks within the array.
More specifically, you must select a particular integer, k
, from the array. Once you've selected k
, the function should remove all occurrences of k
from the array, thereby splitting it into several contiguous blocks or remaining sub-arrays. A unique feature of k
is that it is chosen such that the maximum length among these blocks is minimized.
For instance, consider the list [1, 2, 2, 3, 1, 4, 4, 4, 1, 2, 5]
. If we eliminate all instances of 2 (our k
), the remaining blocks would be [1]
, [3, 1, 4, 4, 4, 1]
, [5]
, with the longest containing 6 elements. Now, if we instead remove all instances of 1, the new remaining blocks would be [2, 2, 3]
, [4, 4, 4]
, [2, 5]
, the longest of which contains 3 elements. As such, the function should return 1 in this case, as it leads to a minimally maximal block length.
An initial way to approach this problem can be through a brute force method. Each possible value in the array could be tested in turn by removing it from the array and then checking the resulting sub-array sizes. This approach entails iteratively stepping through the array for each possible value in the array.
JavaScript1function minimalMaxBlockBruteforce(array) { 2 let minMaxBlockSize = Number.MAX_VALUE; // Largest positive number in JavaScript, approximately 1.79E+308 3 let minNum = -1; 4 5 const uniqueElements = new Set(array); 6 7 uniqueElements.forEach(num => { // Avoid duplicates. 8 const indices = []; 9 for (let i = 0; i < array.length; ++i) { 10 if (array[i] === num) { 11 indices.push(i); 12 } 13 } 14 indices.unshift(-1); // Insert -1 at first index 15 indices.push(array.length); 16 17 let maxBlockSize = 0; 18 for (let i = 1; i < indices.length; ++i) { 19 maxBlockSize = Math.max(maxBlockSize, indices[i] - indices[i - 1] - 1); 20 } 21 22 if (maxBlockSize < minMaxBlockSize) { 23 minMaxBlockSize = maxBlockSize; 24 minNum = num; 25 } 26 }); 27 28 return minNum; 29}
This method has a time complexity of O(n^2)
, as it involves two nested loops: the outer loop cycling through each potential k
value and the inner loop sweeping through the array for each of these k
values.
However, this approach becomes increasingly inefficient as the size n
of the array grows, due to its quadratic time complexity. For larger arrays or multiple invocations, the computation time can noticeably increase, demonstrating the need for a more efficient solution.
To find the number that, when removed from the array, would split the array into several contiguous blocks such that the length of the longest block is minimized, we need to track every position of the same elements, the block size when removing each of the encountered elements, and store the maximum of these blocks.
But, in this case, we don't need to store all positions. We only need the last occurrence position since the blocks we are interested in are between two adjacent same elements, the beginning of the array, and the first occurrence of an element, and between the last occurrence of an element and the end of the array. For the first two cases, we will keep the maximum block size for each element and update it whenever we get a bigger one, and for the last case, we will process it separately after the array traversal.
To do this, we need to:
-
Initialize two
Map
s. ThelastOccurrence
map will store the last occurrence index of each number, whilemaxBlockSizes
will map each number to the maximum size of the blocks formed when the number is removed. -
Traverse the array from left to right, and for each number:
- If it's the first time we encounter the number, we regard the block from the start of the array up to its current position as a block formed when this number is removed, and store the size of this block in
maxBlockSizes
for this number. - If the number has appeared before, we calculate the size of the block it forms (excluding the number itself) by subtracting the last occurrence index from the current index and subtracting 1. If the size is larger than the current maximum stored in
maxBlockSizes
for this number, we update it. - Store the current index as the last occurrence of the number.
- If it's the first time we encounter the number, we regard the block from the start of the array up to its current position as a block formed when this number is removed, and store the size of this block in
-
After finishing the array traversal, we need to calculate the size of the "tail block" (i.e., the block between the last occurrence of a number and the end of the array) for each number, and update its maximum block size in
maxBlockSizes
if necessary. -
Find the number that gives the smallest maximum block size and return it as the result.
First, we initialize two Maps
. The lastOccurrence
map stores the last occurrence index of each number, while maxBlockSizes
maps each number to the maximum size of the blocks formed when the number is removed.
JavaScript1function minimalMaxBlock(array) { 2 const lastOccurrence = new Map(); 3 const maxBlockSizes = new Map();
Next, we iterate over the array. For each number:
- If it's the first time the number is encountered, we regard the block from the start of the array up to its current position as a block formed when this number is removed, and store the size of this block in
maxBlockSizes
for this number. - If it has appeared before, we calculate the size of the block it forms by subtracting the last occurrence index from the current index, and subtracting 1 (since block length doesn't include the number itself). We update
maxBlockSizes
for this number if necessary. - Store the current index as the last occurrence of this number.
JavaScript1 for (let i = 0; i < array.length; ++i) { 2 const num = array[i]; 3 if (!lastOccurrence.has(num)) { 4 maxBlockSizes.set(num, i); 5 } else { 6 const blockSize = i - lastOccurrence.get(num) - 1; 7 maxBlockSizes.set(num, Math.max(maxBlockSizes.get(num), blockSize)); 8 } 9 lastOccurrence.set(num, i); 10 }
Tail blocks are defined as blocks formed from the last occurrence of a number to the end of the array. For each number, we calculate the size of its tail block and update maxBlockSizes
if necessary.
JavaScript1 lastOccurrence.forEach((pos, num) => { 2 const blockSize = array.length - pos - 1; 3 maxBlockSizes.set(num, Math.max(maxBlockSizes.get(num), blockSize)); 4 });
Finally, we find the number associated with the smallest maximum block size in maxBlockSizes
, and return it.
JavaScript1 let minNum = -1; 2 let minBlockSize = Number.MAX_VALUE; 3 maxBlockSizes.forEach((blockSize, num) => { 4 if (blockSize < minBlockSize) { 5 minBlockSize = blockSize; 6 minNum = num; 7 } 8 }); 9 10 return minNum; 11}
The final implementation of our function leverages the efficiency of Map
in JavaScript to track the necessary information during a single traversal of the array. This optimized approach ensures that we determine the minimal maximal block size with greater computational efficiency. Below is the complete code for our minimalMaxBlock
function using the described optimization techniques.
JavaScript1function minimalMaxBlock(array) { 2 const lastOccurrence = new Map(); 3 const maxBlockSizes = new Map(); 4 5 for (let i = 0; i < array.length; ++i) { 6 const num = array[i]; 7 if (!lastOccurrence.has(num)) { 8 maxBlockSizes.set(num, i); 9 } else { 10 const blockSize = i - lastOccurrence.get(num) - 1; 11 maxBlockSizes.set(num, Math.max(maxBlockSizes.get(num), blockSize)); 12 } 13 lastOccurrence.set(num, i); 14 } 15 16 lastOccurrence.forEach((pos, num) => { 17 const blockSize = array.length - pos - 1; 18 maxBlockSizes.set(num, Math.max(maxBlockSizes.get(num), blockSize)); 19 }); 20 21 let minNum = -1; 22 let minBlockSize = Number.MAX_VALUE; 23 maxBlockSizes.forEach((blockSize, num) => { 24 if (blockSize < minBlockSize) { 25 minBlockSize = blockSize; 26 minNum = num; 27 } 28 }); 29 30 return minNum; 31}
Now that we have gone over the steps of the optimized Map
solution, let's understand why the proposed method is superior in terms of time and space complexity when compared to the brute force approach.
-
Time Complexity: The
Map
solution only requires a single traversal of the array. This results in a linear time complexity,O(n)
, wheren
is the number of elements in the array. This is significantly more efficient than theO(n^2)
complexity of the brute force approach, which needs to traverse the list for every distinct number. -
Space Complexity: The brute-force approach maintains a set of unique elements and an indices list for each element. Although the indices list can have up to
n
elements across some particular element, the total space required for all indices combined is stilln
, leading to an overall space complexity ofO(n)
. Similarly, theMap
solution maintains two maps for storing the last occurrence and maximum block size for each number. In a worst-case scenario, every element in the array is unique, leading to anO(n)
space complexity, wheren
is the number of elements in the array.
Excellent work! The lesson of this unit was quite comprehensive — we revisited the concept of Map
, learned how they enhance the performance of code, and even constructed a function to locate a specific number in an array that minimizes the maximum chunk size upon removal.
Now that we've mastered the basics, the logical next step is to apply your newfound knowledge. In the upcoming practice session, a variety of intriguing challenges await that delve further into Map
, array manipulation, and innovative optimizations. So brace yourself, and let's dive in!