Is it possible to use a hash map to monitor progress while looping through this array in JavaScript?

I've been exploring some algorithmic problems and I'm puzzled about the most efficient way to solve this particular question. While nested for loops are an option, they don't seem like the optimal choice. I'm considering using a hash map to keep track of the temperature and the index associated with it.

Imagine you have a list of daily temperatures. Your task is to create a new list that indicates, for each day in the input, how many days you would need to wait until a warmer temperature occurs. If there's no future day with a higher temperature, mark 0 instead. For instance, if the input list is temperatures = [73, 74, 75, 71, 69, 72, 76, 73], then your output should look like this: [1, 1, 4, 2, 1, 1, 0, 0].

Answer №1

There are a variety of techniques that can be employed for this particular problem. While @PlatypusMaximus suggests an approach that works when iterating from the end, you can also tackle it by moving forward through the array, which may offer a clearer understanding:

  1. As you traverse the array, maintain a list of indexes where the 'closest following warmer day' has not yet been determined. This list starts off empty.

  2. For each element, eliminate any indexes from the list with lower temperatures and assign their 'closest following warmer day' to the current index.

  3. By the time you reach the end, any remaining indexes in the list do not have a 'closest following warmer day' and are assigned 0s.

The key part is: Each time you add an element to the list, all previous elements are either equal or higher in temperature. Consequently, the index list stays sorted in decreasing order of temperature. In step (2), this means that only the elements at the tail end of the list (possibly implemented as a stack) need consideration rather than searching through the entire list, resulting in an efficient O(N) time complexity for the process.

Answer №2

One approach is to fill the result array with zeroes and then iterate through the given values by utilizing an object to store key-value pairs of indices and temperatures.

If a value is encountered that is higher than the current temperature in the temporary object, the difference between the indices is calculated and assigned at the corresponding index while removing the key from the object.

The temperatures are assigned as keys in the object along with their respective indices.

var data = [73, 74, 75, 71, 69, 72, 76, 73],
    //     [ 1,  1,  4,  2,  1,  1,  0,  0]
    result = Array.from(data, _ => 0);

data.reduce((tempObj, tempVal, index) => 
    tempObj.filter(([storedTemp, storedIndex]) => {
        if (storedTemp >= tempVal) return true;
        result[storedIndex] = index - storedIndex;
    }).concat([[tempVal, index]]),
    []
);

console.log(result);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How a JavaScript function handles the scope of a for loop index

Here's some Javascript code I'm working with: func1() { for(i = 2; i < 5; i ++) { console.log(i); func2(i); } } func2(x) { for(i = 100; i < 200; i ++) { do something } } I've noticed that when runni ...

What techniques can I implement to optimize the speed of this feature in JavaScript?

I have developed a feature that highlights any text within a <p> tag in red based on a user-specified keyword. The current implementation works well, but it is slow when dealing with over 1000 lines of <p>. Is there a faster way to achieve this ...

Javascript/AJAX functions properly on the homepage, but encounters issues on other pages

For a client, I have recently created 4 websites using Wordpress. Each site includes a sidebar with a script that utilizes the Google Maps API to estimate taxi fares. Strangely, the script works perfectly on the home page of each site, but fails to funct ...

Converting a numerical value starting with zero into a string while retaining the leading zero

I am facing an issue with my JavaScript code that retrieves GPS location from a browser. Due to the limitation of writing coordinates to an SQL database directly from JavaScript, I have resorted to sending it via PHP by utilizing the controller "site" and ...

Issues with slow scrolling and sticky sidebar on websites with infinite scrolling feature

My webpage has a sidebar that is supposed to scroll down with the page. However, I am experiencing some lagging issues where the sidebar appears a few seconds after scrolling. Additionally, the sidebar keeps moving downwards, making the page longer and cau ...

Placing a hyperlink within template strings

Currently, I am working on implementing a stylish email template for when a user registers with their email. To achieve this, I am utilizing Express and Node Mailer. Initially, my code appeared as follows: "Hello, " + user.username + ",&bs ...

Dialog in Angular Material refuses to close even after calling the dialog.close() function

I've been struggling with this issue for a while, hoping someone can assist. In my Angular project, I have a login component with a dialog that opens a new popup window. Upon successful login, this window closes and triggers the following function: l ...

Form submission causing page to reload, getElementById function fails to return value, rendering form ineffective

The objective of this code snippet is to extract data from a form using IDs and store it in an array object named studRec. The entire process is intended to be carried out on the client-side in order to preserve the data for future use in other functions. ...

Retrieve the properties of an object

I have a JavaScript program where I retrieve values from a JSON file and store them in an array. However, when I attempt to access the elements of this array, it returns nothing. Below is the function that pushes temperatures: temperatures = [] get_info ...

Enable Parse5's case sensitivity

Recently, I've attempted to parse Angular Templates into AST using the powerful parse5 library. It seemed like the perfect solution, until I encountered an issue - while parsing HTML, it appears that the library transforms everything to lowercase. Fo ...

Problem Installing Express Sharp using Docker

When deploying via Docker, I encountered an error with sharp, even though it works fine on my workspace. I followed all the steps but still faced issues. Error: 'linux-x64' binaries cannot be used on the 'linuxmusl-x64' platform. P ...

Attempting to program a bot to navigate in a random pattern across a two-dimensional xz plane using Threejs

My journey began with the code below, which initiates a block moving in a straight line: const bot_geometry = new THREE.BoxGeometry(1,1,1); const bot_material = new THREE.MeshBasicMaterial( {color: 0x7777ff, wireframe: false} ); const bot = new THREE.Me ...

Is there a way to streamline the process of connecting multiple ajax requests automatically?

After reviewing the lower portion of my function, I realized that I need to repeat info(url_part1 + next + url_part2, function(next) { multiple times. Is there a more efficient way to accomplish this task, perhaps utilizing some type of loop? I have been b ...

The accordion feature fails to function properly when incorporated into an ajax response

When I click a button, an Ajax response is loaded. The response is successfully appended where it should be, but the issue arises with the accordion not working for the response part. Below is the structure of my response: <div class="articles-content ...

Using the https module in Node.js to transfer a file to a PHP server

What is the best method to send an HTTP post request that includes a jpg file to a php server using the node https module? I attempted to use the request module, but it is unreliable (timing out most of the time) and already deprecated. Here is the functi ...

The audio.play() HTML element fails to function in Chrome, preventing the audio from playing

I'm experiencing an issue with playing audio in Chrome when the audio.src is not called before the play call, but Firefox seems to handle it fine. Does anyone have any suggestions? You can check out the fiddle link below - http://jsfiddle.net/vn215r2 ...

Guide on displaying the AJAX response in CakePHP 3.1

I'm working with a table that contains checkboxes. After selecting them, I want to calculate the sum of values from the table in a modal before confirming the form submission. Can someone guide me on how to render the AJAX response from the controller ...

Errors that occur during Javascript runtime in the Express framework

I'm currently working on an Express app with several routes. One of them looks like this: router.post('/upload', (req, res) => { let audioFile = req.files.audioFile; const file = __dirname + '/../' + req.body.uploadLocation ...

What is the best choice for UI design framework when creating an ERP web application?

I am in the process of creating a web-based ERP application using Angular Material. However, I've noticed that each input element takes up a significant amount of vertical space on the page. This means if I have 15 input elements, I have to scroll dow ...

show information from json onto an html page with the help of jquery

I'm looking to showcase buttons from a JSON file within a simple block. Here's the JSON data for movies: { "movies": [ { "title": "Mena", "movieid": "1", ...