Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Pavel Kostenko
Complexity Analysis issue

Pavel Kostenko

Dec 20, 2024

Time Complexity

  • Reversing the result list: The result list is reversed at the end to maintain the original order of the elements. This operation takes  time.

We're not reversing anything here. So this bullet point can be removed I guess?

class Solution { nextLargerElement(arr) { let stack = []; // Initialize an empty stack to store indices of elements let res = new Array(arr.length).fill(-1); // Initialize a result array with -1 values // Iterate through the input array from right to left for (let i = arr.length - 1; i >= 0; i--) { while (stack.length && stack[stack.length - 1] <= arr[i]) { // While the stack is not empty and the element at the top of the stack // is less than or equal to the current element, pop elements from the stack stack.pop(); } if (stack.length) { // If the stack is not empty after popping, it means the current element // has found its next larger element res[i] = stack[stack.length - 1]; } // Push the current element's index onto the stack stack.push(arr[i]); } return res; // Return the result array containing the next larger elements } } // Test cases let sol = new Solution(); console.log(sol.nextLargerElement([4, 5, 2, 25])); // [5, 25, 25, -1] console.log(sol.nextLargerElement([13, 7, 6, 12])); // [-1, 12, 12, -1] console.log(sol.nextLargerElement([1, 2, 3, 4, 5])); // [2, 3, 4, 5, -1]

0

0

Comments
Comments
Design Gurus
Design Gurus9 months ago

Thanks for pointing this out. This was valid only for Java. We've fixed it.

On this page