-2

Why is the code, below, throwing a TLE? Even the time complexity is O(n) it is throwing TLE QUESTION:https://leetcode.com/problems/sliding-window-maximum/ You can take this website as your reference: https://www.geeksforgeeks.org/sliding-window-maximum-maximum-of-all-subarrays-of-size-k/

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        PriorityQueue<Integer> ans = new PriorityQueue<>(Collections.reverseOrder());
        ArrayList<Integer> res = new ArrayList<>();
        int i = 0, n = nums.length;
        int a[] = new int[n - k + 1];
        int j = 0, index = 0;
        while (j < n) {
            ans.add(nums[j]);
            if (j - i + 1 == k) {
                a[index++] = ans.peek();
                System.out.print(nums[i] + " ");
                ans.remove(nums[i]);
                i++;
            }
            j++;
        }
        System.out.println();
        return a;
    }
}
OscarRyz
  • 196,001
  • 113
  • 385
  • 569

1 Answers1

0

Assuming "TLE" stands for "Time Limit Exceeded" which is not something the code "throws", it means you exceeded the maximum limit you have for the problem -_-

You might be thinking the complexity is O(n) but as @unmitigated mentions, this is actually O(n^2) so, the answer to your question is: "because it takes very long time to compute"

The Java API says the following about the time complexity:

Implementation note: this implementation provides O(log(n)) time for the enqueing and dequeing methods (offer, poll, remove() and add); linear time for the remove(Object) and contains(Object) methods; and constant time for the retrieval methods (peek, element, and size).

OscarRyz
  • 196,001
  • 113
  • 385
  • 569
  • Ho sir is it running O(n*n) times but i have checked it twice sir i thought its O(n) bcs the window is getting slided according to j so i thought its running for O(n) times – tejartr445 Oct 04 '22 at 14:04