Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions DailyTemperatures.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package Stack1;

public class DailyTemperatures {
//TC : o(2n) - o(n) to read each temperature and push to stack and o(n) to resolve each from stack. So o(2n)
//SC : o(n) no. of elements in array
//Approach : Brute force way is to nested iterations to check next largest element which o(n^2) time
// Optimized : push each index to stack and check if arr[i] is greater than top of stack. If it is then calculate value at that index(i-index)
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
//null case
int[] result = new int[temperatures.length];
if(temperatures == null || temperatures.length == 0) return result;

Stack<Integer> st = new Stack<>();

for(int i=0; i<temperatures.length; i++){
while(!st.isEmpty() && temperatures[i] > temperatures[st.peek()]){
int index = st.pop();
result[index] = i - index;
}
st.push(i);
}
return result;
}
}
}
24 changes: 24 additions & 0 deletions NextGreaterElement2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package Stack1;

public class NextGreaterElement2 {
//TC : o(4n)
//SC : o(n)
//Approach : fill result array with -1's. push each index into stack and check nums[i] > stack.peek() then add value of that index to res array. array can be iterated twice as it's circular
class Solution {
public int[] nextGreaterElements(int[] nums) {
int[] res = new int[nums.length];
if(nums == null || nums.length == 0) return res;
Stack<Integer> st = new Stack<>();
Arrays.fill(res,-1);
int n = nums.length;
for(int i=0; i<2*n; i++){
while(!st.isEmpty() && nums[i%n] > nums[st.peek()]){
int index = st.pop();
res[index] = nums[i%n];
}
if(i<n) st.push(i);
}
return res;
}
}
}