Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my output coming partially incorrect in the Daily Temperature problem in Python?

I am trying to solve this following problem using two pointers
Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.

Following is my code:

class Solution(object):

    def dailyTemperatures(self, temperatures):

        l = 0
        r = 1
        res = []
        

        while r < len(temperatures):

            if temperatures[r] > temperatures[l]:
                diff = temperatures[r] - temperatures[l]
                res.append(diff)
                l += 1
                r += 1
               
            else:
                diff = temperatures[l] - temperatures[r]
                res.append(diff)
                l += 1
                r += 1
                

        return res

So for following input; temperatures = [73,74,75,71,69,72,76,73] , it should display Output: [1,1,4,2,1,1,0,0] but for my code it’s displaying output= [1, 1, 4, 2, 3, 4, 3].
Where am I going wrong in my approach?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your code calculates the difference between the temperatures, but the problem asks for the number of days to wait for a warmer temperature. So instead of calculating the temperature difference, you should calculate the index difference.

def dailyTemperatures(temperatures):
    stack = []
    res = [0] * len(temperatures)
    for i, temp in enumerate(temperatures):
        while stack and temperatures[stack[-1]] < temp:
            last_index = stack.pop()
            res[last_index] = i - last_index
        stack.append(i)
    return res

dailyTemperatures([73,74,75,71,69,72,76,73])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading