question_slug stringlengths 3 77 | title stringlengths 1 183 | slug stringlengths 12 45 | summary stringlengths 1 160 ⌀ | author stringlengths 2 30 | certification stringclasses 2
values | created_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | updated_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | hit_count int64 0 10.6M | has_video bool 2
classes | content stringlengths 4 576k | upvotes int64 0 11.5k | downvotes int64 0 358 | tags stringlengths 2 193 | comments int64 0 2.56k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sliding-window-median | Easy to understand O(nlogk) Java solution using TreeMap | easy-to-understand-onlogk-java-solution-gqgcc | TreeMap is used to implement an ordered MultiSet.\n\nIn this problem, I use two Ordered MultiSets as Heaps. One heap maintains the lowest 1/2 of the elements, a | brendon4565 | NORMAL | 2017-01-10T10:58:28.099000+00:00 | 2018-08-25T21:31:54.273252+00:00 | 18,145 | false | TreeMap is used to implement an ordered MultiSet.\n\nIn this problem, I use two Ordered MultiSets as Heaps. One heap maintains the lowest 1/2 of the elements, and the other heap maintains the higher 1/2 of elements.\n \nThis implementation is faster than the usual implementation that uses 2 PriorityQueues, because unli... | 51 | 3 | [] | 11 |
sliding-window-median | Python SortedArray (beats 100%) and 2-Heap(beats 90%) solution | python-sortedarray-beats-100-and-2-heapb-ixw1 | \n### Array based solution: \n- the window is an array maintained in sorted order\n- the mid of the array is used to calculate the median\n- every iteration, t | bharanidharan | NORMAL | 2017-07-27T05:05:16.647000+00:00 | 2018-10-26T04:05:02.096555+00:00 | 9,232 | false | \n### Array based solution: \n- the window is an array maintained in sorted order\n- the mid of the array is used to calculate the median\n- every iteration, the incoming number is added in sorted order in the array using insert - `O(log K)` ?\n- every iteration, the outgoing number is removed from the array using bis... | 48 | 4 | [] | 12 |
sliding-window-median | C++ 95 ms single multiset O(n * log n) | c-95-ms-single-multiset-on-log-n-by-votr-046r | The reason to use two heaps is to have O(1) lookup for the median. It's is O(n) if we use multiset, but what if we reuse the median pointer when we can?\nThe so | votrubac | NORMAL | 2017-01-09T06:23:09.141000+00:00 | 2017-01-09T06:23:09.141000+00:00 | 9,630 | false | The reason to use two heaps is to have O(1) lookup for the median. It's is O(n) if we use multiset, but what if we reuse the median pointer when we can?\nThe solution below still has the O(n^2) worst case run-time, and the average case run-time is O(n * log n). We can achieve O(n * log n) in the worst case if we make s... | 40 | 0 | [] | 6 |
sliding-window-median | Easiest solution using only vector | C++ | easiest-solution-using-only-vector-c-by-dv0xw | \nclass Solution {\npublic:\n vector<double> medianSlidingWindow(vector<int>& nums, int k) {\n \n vector<double> res;\n vector<long long | user7392a | NORMAL | 2020-09-28T10:02:54.867129+00:00 | 2020-09-28T10:10:26.305434+00:00 | 4,556 | false | ```\nclass Solution {\npublic:\n vector<double> medianSlidingWindow(vector<int>& nums, int k) {\n \n vector<double> res;\n vector<long long> med;\n \n for(int i= 0; i<k; i++)\n med.insert(lower_bound(med.begin(),med.end(),nums[i]),nums[i]);\n if(k%2==0)\n ... | 38 | 0 | ['C', 'C++'] | 6 |
sliding-window-median | Java | TC: O(N*logK) | SC: (K) | Optimized sliding window using TreeSet | java-tc-onlogk-sc-k-optimized-sliding-wi-5zia | In following solution we are using TreeSet. Here, the remove operation in Java is most optimized\njava\n/**\n * Using TreeSet. (Here time complexity is most opt | NarutoBaryonMode | NORMAL | 2021-10-07T07:19:41.311240+00:00 | 2021-10-07T07:52:52.440158+00:00 | 6,063 | false | **In following solution we are using TreeSet. Here, the remove operation in Java is most optimized**\n```java\n/**\n * Using TreeSet. (Here time complexity is most optimized)\n *\n * Very similar to https://leetcode.com/problems/find-median-from-data-stream/\n *\n * Time Complexity: O((N-K)*log K + N*log K) = O(N * log... | 36 | 0 | ['Array', 'Tree', 'Sliding Window', 'Heap (Priority Queue)', 'Ordered Set', 'Java'] | 7 |
sliding-window-median | Easy to understand Java solution using 2 Priority Queues | easy-to-understand-java-solution-using-2-1cu4 | \nclass Solution {\n \n public double[] medianSlidingWindow(int[] nums, int k) {\n MeanQueue queue = new MeanQueue();\n double[] result = ne | pradeepneo | NORMAL | 2018-08-10T18:40:24.192389+00:00 | 2018-08-27T06:45:04.795962+00:00 | 2,930 | false | ```\nclass Solution {\n \n public double[] medianSlidingWindow(int[] nums, int k) {\n MeanQueue queue = new MeanQueue();\n double[] result = new double[nums.length - k + 1];\n int index = 0;\n \n for(int i = 0; i < nums.length; i++){\n queue.offer(nums[i]);\n ... | 29 | 2 | [] | 3 |
sliding-window-median | [C++] SIMPLE code using Multiset, Shorter, Replicable for Interviews | c-simple-code-using-multiset-shorter-rep-pee5 | The idea can be borrowed from https://leetcode.com/problems/find-median-from-data-stream/ i.e. using a max-heap and min-heap for the left and right halves of th | penrosecat | NORMAL | 2021-07-26T22:40:11.024769+00:00 | 2021-07-26T22:40:11.024812+00:00 | 1,852 | false | The idea can be borrowed from https://leetcode.com/problems/find-median-from-data-stream/ i.e. using a max-heap and min-heap for the left and right halves of the window elements. \n\nHowever, we also want efficient insertion and deletion from the heaps, so instead of priority queue we can use set in C++ to store sorted... | 28 | 0 | ['C'] | 6 |
sliding-window-median | Java + Easy to understand + 2 Heaps | java-easy-to-understand-2-heaps-by-learn-hs29 | Inutition\nIf we can maintain 2 Heaps - maxHeap and minHeap, where maxHeap stores the smaller half values and minHeap stores the larger half values, so that any | learn4Fun | NORMAL | 2021-02-17T05:45:29.556808+00:00 | 2021-02-17T05:52:14.329127+00:00 | 3,636 | false | #### Inutition\nIf we can maintain 2 Heaps - `maxHeap` and `minHeap`, where `maxHeap` stores the smaller half values and `minHeap` stores the larger half values, so that any point of time the top most element of the 2 heaps will provide the median.\n\n#### Code\n```\nclass Solution {\n private PriorityQueue<Integer>... | 23 | 1 | ['Sliding Window', 'Java'] | 6 |
sliding-window-median | Java clean and easily readable solution with a helper class | java-clean-and-easily-readable-solution-3e5p8 | \n public double[] medianSlidingWindow(int[] nums, int k) {\n MedianQueue window = new MedianQueue();\n double[] median = new double[nums.lengt | yuxiangmusic | NORMAL | 2017-01-11T05:30:09.214000+00:00 | 2017-01-11T05:30:09.214000+00:00 | 3,755 | false | ```\n public double[] medianSlidingWindow(int[] nums, int k) {\n MedianQueue window = new MedianQueue();\n double[] median = new double[nums.length - k + 1]; \n for (int i = 0; i < nums.length; i++) {\n window.add(nums[i]);\n if (i >= k) window.remove(nums[i - k]);\n ... | 23 | 1 | [] | 4 |
sliding-window-median | Simple C++ || Two Heap || Explained || Comments | simple-c-two-heap-explained-comments-by-y1w0a | ```\nclass Solution {\npublic:\n vector medianSlidingWindow(vector& nums, int k) {\n vector medians;\n int n = nums.size();\n unordered_ | mohit_motwani | NORMAL | 2022-05-18T15:52:05.831818+00:00 | 2022-05-18T15:52:05.831862+00:00 | 4,633 | false | ```\nclass Solution {\npublic:\n vector<double> medianSlidingWindow(vector<int>& nums, int k) {\n vector<double> medians;\n int n = nums.size();\n unordered_map<int,int> mp; // for late deletion\n priority_queue<int> maxh; // max heap for lower half\n priority_queue<int, vector<int... | 21 | 0 | ['C', 'Heap (Priority Queue)', 'C++'] | 4 |
sliding-window-median | Two Heaps, Lazy removals, Python3 | two-heaps-lazy-removals-python3-by-solai-v5rb | Intuition\nWant to use somehow changed version of MedianFinder from problem 295.\n\n# Approach\nThe class maintains a balance variable, which indicates the size | solairerove | NORMAL | 2023-11-10T06:21:21.530046+00:00 | 2023-11-10T06:21:21.530079+00:00 | 2,865 | false | # Intuition\nWant to use somehow changed version of MedianFinder from problem 295.\n\n# Approach\nThe class maintains a balance variable, which indicates the size difference between the two heaps. A negative balance\nindicates that the `small` heap has more elements, while a positive balance indicates that the `large` ... | 20 | 0 | ['Heap (Priority Queue)', 'Python3'] | 1 |
sliding-window-median | Short and Clear O(nlogk) Java Solutions | short-and-clear-onlogk-java-solutions-by-s36w | Use 2 priorityQueues:\n3 steps: remove out-of-bound element, add new element and keep small.peek()<=big.peek(), and get median. \nTime: O(nk). The drawback is r | lceveryday | NORMAL | 2017-02-17T01:33:37.003000+00:00 | 2017-02-17T01:33:37.003000+00:00 | 2,299 | false | **Use 2 priorityQueues:**\n3 steps: remove out-of-bound element, add new element and keep small.peek()<=big.peek(), and get median. \nTime: O(nk). The drawback is remove function of priorityQueue takes O(k) time. \n```\npublic class Solution {\n public double[] medianSlidingWindow(int[] nums, int k) {\n doubl... | 18 | 0 | [] | 4 |
sliding-window-median | Python3 O(nlogk) heap with intuitive lazy deletion - Sliding Window Median | python3-onlogk-heap-with-intuitive-lazy-gfu18 | \nimport heapq\n\nclass Heap:\n def __init__(self, indices: List[int], nums: List[int], max=False) -> None:\n self.max = max\n self.heap = [[-n | r0bertz | NORMAL | 2020-05-08T08:56:25.209509+00:00 | 2020-05-08T09:05:58.231745+00:00 | 4,901 | false | ```\nimport heapq\n\nclass Heap:\n def __init__(self, indices: List[int], nums: List[int], max=False) -> None:\n self.max = max\n self.heap = [[-nums[i], i] if self.max else [nums[i],i] for i in indices]\n self.indices = set(indices)\n heapq.heapify(self.heap)\n \n def __len__(s... | 17 | 2 | ['Heap (Priority Queue)', 'Python', 'Python3'] | 4 |
sliding-window-median | Easy to understand C++ Solution with multiset | easy-to-understand-c-solution-with-multi-oge0 | \nmultiset <double> m;\n \n double findMedian(double remove, double add) {\n m.insert(add);\n m.erase(m.find(remove));\n int n = m.si | narendrant7 | NORMAL | 2019-07-25T05:34:13.939153+00:00 | 2019-07-25T05:34:13.939196+00:00 | 2,350 | false | ```\nmultiset <double> m;\n \n double findMedian(double remove, double add) {\n m.insert(add);\n m.erase(m.find(remove));\n int n = m.size();\n double a = *next(m.begin(), n/2 - 1);\n double b = *next(m.begin(), n/2);\n return n & 1? b : (a + b) * 0.5;\n }\n \n v... | 16 | 2 | ['C', 'C++'] | 3 |
sliding-window-median | Two heaps + sliding window approach; O( n * k ) runtime O(k) space | two-heaps-sliding-window-approach-o-n-k-he1lh | \n"""\n# BCR\nRuntime: O(n)\nSpacetime: O(1)\n\n# Brute force soultion\nCreate z subsets of nums, where z is len(nums) / k\nSort z\ncalcuate median\nRuntime: O( | agconti | NORMAL | 2019-10-23T23:36:00.810486+00:00 | 2019-10-23T23:36:00.810539+00:00 | 4,186 | false | ```\n"""\n# BCR\nRuntime: O(n)\nSpacetime: O(1)\n\n# Brute force soultion\nCreate z subsets of nums, where z is len(nums) / k\nSort z\ncalcuate median\nRuntime: O(n * k * log k) -- calling merge sort on each subset in z\nSpacetime: O(z), -- where z is len(nums) / k\n\n# Two heap apporach\ncreate a max heap and min heap... | 14 | 0 | ['Heap (Priority Queue)', 'Python', 'Python3'] | 3 |
sliding-window-median | C++ two multiset solution | c-two-multiset-solution-by-hanafubuki-86nv | Similar idea as 295. Find Median from Data Stream\nKeep a max heap and a min heap\nBut in this case, we need to keep on removing elements out of the window\nSo | hanafubuki | NORMAL | 2017-01-08T23:40:37.820000+00:00 | 2018-10-16T23:16:43.970321+00:00 | 1,293 | false | Similar idea as 295. Find Median from Data Stream\nKeep a max heap and a min heap\nBut in this case, we need to keep on removing elements out of the window\nSo use multiset insead of heap\nT = O(n*log(k)), S = O(k)\n\n```\nclass Solution {\npublic:\n vector<double> medianSlidingWindow(vector<int>& nums, int k) {\n ... | 14 | 0 | [] | 0 |
sliding-window-median | JAVA Time 100% space 100% Using Binary Search, Explained | java-time-100-space-100-using-binary-sea-w1xp | \nclass Solution {\n public double[] medianSlidingWindow(int[] nums, int k) {\n int len = nums.length, p = 0;\n double[] sol = new double[len - | adarshv19 | NORMAL | 2021-06-10T16:55:38.934062+00:00 | 2021-06-13T00:21:32.114404+00:00 | 1,883 | false | ```\nclass Solution {\n public double[] medianSlidingWindow(int[] nums, int k) {\n int len = nums.length, p = 0;\n double[] sol = new double[len - k + 1];\n boolean flag = (k % 2 == 0);\n List<Integer> list = new ArrayList<>();\n \n //Insert first k-1 elements into the Array... | 11 | 0 | ['Binary Tree', 'Java'] | 4 |
sliding-window-median | Evolve from brute force to optimal | evolve-from-brute-force-to-optimal-by-yu-uiyd | The idea is similar to 239. Sliding Window Maximum.\n1. Array O(nk) Store the window in a sorted list.\n\n\tpublic double[] medianSlidingWindow(int[] nums, int | yu6 | NORMAL | 2017-02-06T00:31:50.504000+00:00 | 2020-12-07T01:04:27.978888+00:00 | 1,903 | false | The idea is similar to [239. Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/discuss/887170/Evolve-from-brute-force-to-optimal).\n1. Array O(nk) Store the window in a sorted list.\n```\n\tpublic double[] medianSlidingWindow(int[] nums, int k) {\n int n=nums.length;\n double[]... | 11 | 3 | ['C', 'Java'] | 1 |
sliding-window-median | ✅Beginner Friendly (C++/Java/Python) Solution With Detailed Explanation✅ | beginner-friendly-cjavapython-solution-w-4yit | Intuition\nThe medianSlidingWindow function maintains a sorted window of elements using vector operations and calculates medians as the window slides through th | suyogshete04 | NORMAL | 2024-01-25T04:09:18.026173+00:00 | 2024-01-25T04:09:18.026196+00:00 | 3,220 | false | # Intuition\nThe `medianSlidingWindow` function maintains a sorted window of elements using vector operations and calculates medians as the window slides through the input array. It utilizes efficient insertions and deletions with `lower_bound` and updates the result vector with calculated medians. The final result vec... | 10 | 0 | ['Sliding Window', 'C++', 'Java', 'Python3'] | 2 |
sliding-window-median | C++ Solution using Two Heaps | Using Multi Set | c-solution-using-two-heaps-using-multi-s-p5kt | \nclass Solution {\n private:\n multiset<double>MinH, MaxH;\n vector<double> ans;\n \n public: \n void balance()\n {\n if(MaxH.siz | chirags_30 | NORMAL | 2021-08-14T09:44:00.616441+00:00 | 2021-08-14T09:44:00.616492+00:00 | 1,265 | false | ```\nclass Solution {\n private:\n multiset<double>MinH, MaxH;\n vector<double> ans;\n \n public: \n void balance()\n {\n if(MaxH.size() > MinH.size() + 1)\n {\n MinH.insert(*MaxH.rbegin());\n MaxH.erase(MaxH.find(*MaxH.rbegin()));\n }\n ... | 10 | 0 | ['C', 'Heap (Priority Queue)'] | 1 |
sliding-window-median | C# SortedSet O(n*log(k)) | c-sortedset-onlogk-by-1988hz-scgs | Referencing https://leetcode.com/problems/sliding-window-median/discuss/96346/Java-using-two-Tree-Sets-O(n-logk)\n\nThe idea is to reduct the time complexity in | 1988hz | NORMAL | 2021-01-31T14:12:24.993173+00:00 | 2021-01-31T14:13:58.474098+00:00 | 443 | false | Referencing https://leetcode.com/problems/sliding-window-median/discuss/96346/Java-using-two-Tree-Sets-O(n-logk)\n\nThe idea is to reduct the time complexity in the inner loop. C# has a few built in data structures\n* List/SortedList - The search is always O(log(k)), but insert and delete are O(k). So the total complex... | 10 | 0 | [] | 3 |
sliding-window-median | C++ Sliding Window Solution Using MultiSet (Solution Updated After Recently Added TestCase) | c-sliding-window-solution-using-multiset-9rwp | \nclass Solution {\npublic:\n vector<double> medianSlidingWindow(vector<int>& nums, int k) {\n vector<double> ans;\n multiset<double> window(be | _limitlesspragma | NORMAL | 2022-09-09T16:54:15.581269+00:00 | 2023-05-11T13:07:14.234269+00:00 | 1,476 | false | ```\nclass Solution {\npublic:\n vector<double> medianSlidingWindow(vector<int>& nums, int k) {\n vector<double> ans;\n multiset<double> window(begin(nums), begin(nums) + k);\n auto it = next(begin(window), (k - 1) / 2); //take the iterator to mid position\n \n for(int i=k; ;... | 9 | 0 | ['C++'] | 1 |
sliding-window-median | The Most Optimal T-O(NlogK), S-O(K) using 2 Heaps C++ Commented Solution | the-most-optimal-t-onlogk-s-ok-using-2-h-lk0e | \nclass Solution {\npublic:\n\t// Custom structures for max & min heaps\n struct maxstruct{\n bool operator()(pair<double,double>& a, pair<double,doub | ankurharitosh | NORMAL | 2020-08-07T10:28:27.980291+00:00 | 2020-12-31T16:04:37.584108+00:00 | 1,995 | false | ```\nclass Solution {\npublic:\n\t// Custom structures for max & min heaps\n struct maxstruct{\n bool operator()(pair<double,double>& a, pair<double,double>& b){\n return a.second<b.second;\n } \n };\n struct minstruct{\n bool operator()(pair<double,double>& a, pair<double,doub... | 9 | 1 | ['C', 'Heap (Priority Queue)', 'C++'] | 3 |
sliding-window-median | Javascript solution beats 98.81% | javascript-solution-beats-9881-by-darynk-rhcn | The idea is pretty simple. You need to keep the sorted array, adding and deleting numbers one by one. For this purpose, you can use binary insertion and binary | darynkaypbaev | NORMAL | 2020-02-25T22:00:55.012606+00:00 | 2020-02-25T22:00:55.012654+00:00 | 1,942 | false | The idea is pretty simple. You need to keep the sorted array, adding and deleting numbers one by one. For this purpose, you can use binary insertion and binary deletion.\n\n\tconst medianSlidingWindow = (nums, k) => {\n\t\tconst arr = []\n\t\tconst output = []\n\t\tconst isEven = k % 2 === 0\n\t\tconst m = k >> 1\n\n\t... | 9 | 0 | ['Binary Search', 'JavaScript'] | 3 |
sliding-window-median | Easy to understand with explanation - Python Two heaps - O(N * K) and O(K) | easy-to-understand-with-explanation-pyth-tf5n | Explanation:\nSimilar to finding median from a stream with the following changes:\n- We need to keep track of a sliding window of "k" numbers.\n- This means, in | mpatel_21 | NORMAL | 2021-01-04T20:03:55.646872+00:00 | 2021-01-04T20:23:51.558073+00:00 | 1,786 | false | # Explanation:\nSimilar to finding median from a stream with the following changes:\n- We need to keep track of a sliding window of "k" numbers.\n- This means, in each iteration, when we insert a new number in the heaps, we need to remove one number from the heaps which is going out of the sliding window.\n - After the... | 8 | 0 | ['Python', 'Python3'] | 3 |
sliding-window-median | Python 2 Heap Solution O(N*K) | python-2-heap-solution-onk-by-satwik95-yk6z | Use a deque to slide through and 2 heaps to compute the median of the stream of data. Tc = O(N*K), K because of heapify in remove(). \nFinding median of a strea | satwik95 | NORMAL | 2020-07-30T21:18:09.537793+00:00 | 2020-08-21T03:48:20.305688+00:00 | 1,595 | false | Use a deque to slide through and 2 heaps to compute the median of the stream of data. Tc = O(N*K), K because of heapify in remove(). \nFinding median of a stream: https://leetcode.com/problems/find-median-from-data-stream/discuss/74062/Short-simple-JavaC%2B%2BPython-O(log-n)-%2B-O(1)\n```\nfrom heapq import *\nfrom col... | 8 | 0 | ['Heap (Priority Queue)', 'Python3'] | 5 |
sliding-window-median | Python Hash Heap Implementation | python-hash-heap-implementation-by-hanke-6y05 | Apparently, we need a data structure which supports both Insert and Remove operation in O(log K) time and supports getMin operation in O(1) or O(log K) time.\n\ | hankerzheng | NORMAL | 2017-01-19T21:37:16.231000+00:00 | 2017-01-19T21:37:16.231000+00:00 | 4,399 | false | Apparently, we need a data structure which supports both `Insert` and `Remove` operation in `O(log K)` time and supports `getMin` operation in `O(1)` or `O(log K)` time.\n\nThe Data Structure we could choose may be Balanced BST or Hash Heap. But there is no such implemented data structure in Python. Here is my implemen... | 8 | 1 | [] | 4 |
sliding-window-median | C++ Solution O(n*k) | c-solution-onk-by-kevin36-3o9g | The idea is to maintain a BST of the window and just search for the k/2 largest element and k/2 smallest element then the average of these two is the median of | kevin36 | NORMAL | 2017-01-08T05:15:32.283000+00:00 | 2017-01-08T05:15:32.283000+00:00 | 2,320 | false | The idea is to maintain a BST of the window and just search for the k/2 largest element and k/2 smallest element then the average of these two is the median of the window.\n\n Now if the STL's multiset BST maintained how many element were in each subtree finding each median would take O(log k) time but since it doe... | 7 | 2 | [] | 1 |
sliding-window-median | Java, Two Heaps and HashMap for lazy removes | java-two-heaps-and-hashmap-for-lazy-remo-bim2 | Intuition\nThe main tricky point in this problem is to remove an elememnt from PriorityQueue. Regular method remove(i) takes O(n) and such solution fails by LTE | Vladislav-Sidorovich | NORMAL | 2023-07-29T16:40:43.985614+00:00 | 2023-07-29T16:41:25.995408+00:00 | 1,123 | false | # Intuition\nThe main tricky point in this problem is to remove an elememnt from `PriorityQueue`. Regular method `remove(i)` takes `O(n)` and such solution fails by LTE.\nAll the rest is similart to https://leetcode.com/problems/find-median-from-data-stream/ \n\n# Approach\nLet\'s keep removed items in `HashMap` and re... | 6 | 0 | ['Hash Table', 'Sliding Window', 'Heap (Priority Queue)', 'Java'] | 1 |
sliding-window-median | [Java] Optimal Sliding Window using two PriorityQueues | java-optimal-sliding-window-using-two-pr-pac0 | \nclass Solution {\n public double[] medianSlidingWindow(int[] nums, int k) {\n \n double[] result = new double[nums.length - k + 1];\n | nagato19 | NORMAL | 2022-08-22T15:09:48.093598+00:00 | 2022-08-22T15:09:48.093630+00:00 | 2,014 | false | ```\nclass Solution {\n public double[] medianSlidingWindow(int[] nums, int k) {\n \n double[] result = new double[nums.length - k + 1];\n int p = 0;\n PriorityQueue<Integer> max = new PriorityQueue<>(Collections.reverseOrder());\n PriorityQueue<Integer> min = new PriorityQueue<>()... | 6 | 0 | ['Sliding Window', 'Heap (Priority Queue)', 'Java'] | 1 |
sliding-window-median | Java max + min heaps cleaned up version | java-max-min-heaps-cleaned-up-version-by-fm5k | \tPriorityQueue max = new PriorityQueue<>(Collections.reverseOrder());\n PriorityQueue min = new PriorityQueue<>();\n\n public double[] medianSlidingWindo | didado | NORMAL | 2021-01-24T02:49:38.641453+00:00 | 2021-01-24T02:50:29.361035+00:00 | 447 | false | \tPriorityQueue<Integer> max = new PriorityQueue<>(Collections.reverseOrder());\n PriorityQueue<Integer> min = new PriorityQueue<>();\n\n public double[] medianSlidingWindow(int[] nums, int k) {\n double[] res = new double[nums.length - k + 1];\n\n for (int i = 0; i < nums.length; i++) {\n ... | 6 | 0 | ['Java'] | 1 |
sliding-window-median | Using ArrayList in Java, faster than 99% of the codes | using-arraylist-in-java-faster-than-99-o-p7k4 | \npublic double[] medianSlidingWindow(int[] nums, int k) {\n double[] res=new double[nums.length-k+1];\n List<Integer> list = new ArrayList<Intege | hitesh_bhalotia | NORMAL | 2020-07-28T12:03:00.426619+00:00 | 2020-07-28T12:04:26.621612+00:00 | 732 | false | ```\npublic double[] medianSlidingWindow(int[] nums, int k) {\n double[] res=new double[nums.length-k+1];\n List<Integer> list = new ArrayList<Integer>();\n for(int i=0;i<k;i++){ // used to get the first window only\n list.add(nums[i]);\n }\n Collections.sort(list);\n ... | 6 | 0 | ['Array', 'Binary Tree', 'Java'] | 1 |
sliding-window-median | JavaScript solution | Binary search [81%, 100%] | javascript-solution-binary-search-81-100-froe | Idea behind this solution is to use binary search to insert right number and remove left number when moving the sliding window to the right.\n\nRuntime: 108 ms, | i-love-typescript | NORMAL | 2020-04-25T23:14:37.815840+00:00 | 2020-04-26T15:12:05.539278+00:00 | 964 | false | Idea behind this solution is to use binary search to insert right number and remove left number when moving the sliding window to the right.\n\nRuntime: 108 ms, faster than 81.03% of JavaScript online submissions for Sliding Window Median.\nMemory Usage: 40 MB, less than 100.00% of JavaScript online submissions for Sli... | 6 | 0 | ['JavaScript'] | 0 |
sliding-window-median | Python SortedList solution | python-sortedlist-solution-by-drfirestre-rhg6 | Just to remind we have quite a standard sortedcontainers library to deal with such problems very easily in O(n log k) in contrast to practically fast but arguab | drfirestream | NORMAL | 2020-01-09T09:38:50.218704+00:00 | 2020-01-09T09:38:50.218750+00:00 | 1,170 | false | Just to remind we have quite a standard sortedcontainers library to deal with such problems very easily in O(n log k) in contrast to practically fast but arguable from algorithmic point of view O(n k) solution that uses insort from bisect library\n\n```\nfrom sortedcontainers import SortedList\nclass Solution:\n def... | 6 | 0 | ['Python', 'Python3'] | 2 |
sliding-window-median | Python O(NlogN) using heap | python-onlogn-using-heap-by-danny7226-ydwo | python heap solution with run time O(NlogN)\n\n\n def medianSlidingWindow(self, nums, k):\n low, high = [], [] # heap\n for i in range(k):\n | danny7226 | NORMAL | 2019-07-12T08:32:44.828545+00:00 | 2019-07-12T08:33:25.284733+00:00 | 1,809 | false | python heap solution with run time O(NlogN)\n\n```\n def medianSlidingWindow(self, nums, k):\n low, high = [], [] # heap\n for i in range(k):\n heapq.heappush(high, (nums[i], i)) # high is a min-heap\n for _ in range(k>>1):\n self.convert(high, low)\n ans = [high[0][... | 6 | 0 | ['Heap (Priority Queue)', 'Python'] | 4 |
sliding-window-median | Simple Solution with Diagrams in Video - JavaScript, C++, Java, Python | simple-solution-with-diagrams-in-video-j-vriw | Video\nPlease upvote here so others save time too!\n\nLike the video on YouTube if you found it useful\n\nClick here to subscribe on YouTube:\nhttps://www.youtu | danieloi | NORMAL | 2024-11-26T14:19:20.558032+00:00 | 2024-11-26T14:19:20.558074+00:00 | 1,897 | false | # Video\nPlease upvote here so others save time too!\n\nLike the video on YouTube if you found it useful\n\nClick here to subscribe on YouTube:\nhttps://www.youtube.com/@mayowadan?sub_confirmation=1\n\nThanks!\n\nhttps://youtu.be/QL6eAE_WopE?si=RKW9MF_rI_EuMdGD\n\n```Javascript []\n/**\n * @param {number[]} nums\n * @p... | 5 | 0 | ['Python', 'C++', 'Java', 'Python3', 'JavaScript'] | 0 |
sliding-window-median | Python | Easy | Heap | Sliding Window Median | python-easy-heap-sliding-window-median-b-xzdk | \nsee the Successfully Accepted Submission\nPython\nfrom sortedcontainers import SortedList # Import the SortedList class from the sortedcontainers module\n\nc | Khosiyat | NORMAL | 2023-10-12T14:24:05.784403+00:00 | 2023-10-12T14:24:05.784428+00:00 | 643 | false | \n[see the Successfully Accepted Submission](https://leetcode.com/submissions/detail/1069477256/)\n```Python\nfrom sortedcontainers import SortedList # Import the SortedList class from the sortedcontainers module\n\nclass Solution:\n def medianSlidingWindow(self, nums, k):\n window = SortedList(nums[:k]) # ... | 5 | 0 | ['Heap (Priority Queue)', 'Python'] | 1 |
sliding-window-median | [Python3] SortedList | python3-sortedlist-by-ye15-7c98 | \n\nfrom sortedcontainers import SortedList\n\nclass Solution:\n def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:\n ans = []\n | ye15 | NORMAL | 2021-06-18T00:41:04.556518+00:00 | 2021-06-18T00:41:04.556549+00:00 | 286 | false | \n```\nfrom sortedcontainers import SortedList\n\nclass Solution:\n def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:\n ans = []\n sl = SortedList()\n for i, x in enumerate(nums): \n sl.add(x)\n if i >= k: sl.remove(nums[i-k])\n if i+1 >= k: ... | 5 | 1 | ['Python3'] | 2 |
sliding-window-median | JAVA || Clean & Concise & Optimal Code || Binary Search or Two Heaps Data Structure | java-clean-concise-optimal-code-binary-s-dv0t | Solution 1: Binary Search Algorithm\n\n\nclass Solution {\n \n public void addElement (List<Integer> list, int num) {\n \n int index = Colle | anii_agrawal | NORMAL | 2021-05-04T19:31:50.619839+00:00 | 2021-05-04T19:31:50.619881+00:00 | 910 | false | # Solution 1: Binary Search Algorithm\n\n```\nclass Solution {\n \n public void addElement (List<Integer> list, int num) {\n \n int index = Collections.binarySearch (list, num);\n index = index < 0 ? Math.abs (index) - 1 : index;\n list.add (index, num);\n }\n \n public void r... | 5 | 1 | ['Heap (Priority Queue)', 'Binary Tree', 'Java'] | 2 |
sliding-window-median | My concise version with two TreeSet (JAVA) | my-concise-version-with-two-treeset-java-jj74 | This quesiton is very similar to LC295 Find Median from Data Stream. We use two PriorityQueue in that question. However, the remove(Object) is O(n) for Priority | deepli | NORMAL | 2020-08-13T05:56:59.760252+00:00 | 2020-08-13T05:57:29.271948+00:00 | 171 | false | This quesiton is very similar to LC295 Find Median from Data Stream. We use two PriorityQueue in that question. However, the remove(Object) is O(n) for PriorityQueue. We want O(logn), so we use TreeSet. To handle the duplicate case, we store the index instead of the array value in the TreeSet.\n```\npublic double[] med... | 5 | 0 | [] | 1 |
sliding-window-median | [Rust] Just write a avl tree library | rust-just-write-a-avl-tree-library-by-ye-0ock | since rust doesn\'t have multiset like C++, I created it myself. The code is long, but works :) and beats 100% time and memory.\n\n\n#![allow(dead_code)]\n\n#[d | yeetcoder4736 | NORMAL | 2020-07-15T17:17:09.038251+00:00 | 2020-07-15T17:17:09.038311+00:00 | 321 | false | since rust doesn\'t have multiset like C++, I created it myself. The code is long, but works :) and beats 100% time and memory.\n\n```\n#![allow(dead_code)]\n\n#[derive(Debug)]\nstruct MultiSetNode<T> {\n /// The value being stored.\n value: T,\n /// The number of times this value is stored.\n count: usize,... | 5 | 0 | ['Rust'] | 1 |
sliding-window-median | Swift 100/100 using binary search | swift-100100-using-binary-search-by-mode-qthj | \nclass Solution {\n \n func getMedian(_ arr: inout [Int]) -> Double {\n if arr.count % 2 != 0 {\n return Double(arr[arr.count / 2])\n | moderator1 | NORMAL | 2020-03-08T12:28:03.342383+00:00 | 2020-03-08T12:28:03.342420+00:00 | 264 | false | ```\nclass Solution {\n \n func getMedian(_ arr: inout [Int]) -> Double {\n if arr.count % 2 != 0 {\n return Double(arr[arr.count / 2])\n } else {\n return Double((Double(arr[arr.count/2]) + Double(arr[arr.count/2 - 1])) / 2.0)\n }\n }\n \n\t\n func binaryRemove... | 5 | 0 | [] | 1 |
sliding-window-median | C# SortedList | c-sortedlist-by-user638-m14p | C# SortedList\n\npublic class Solution\n{\n public double[] MedianSlidingWindow(int[] nums, int k)\n {\n var res = new List<double>();\n var | user638 | NORMAL | 2020-02-11T06:54:05.744341+00:00 | 2020-02-11T06:54:05.744388+00:00 | 437 | false | C# SortedList\n```\npublic class Solution\n{\n public double[] MedianSlidingWindow(int[] nums, int k)\n {\n var res = new List<double>();\n var sl = new SortedList<long, int>();\n for (var i = 0; i < nums.Length; i++)\n {\n sl.Add(GetId(i, nums), nums[i]);\n if (s... | 5 | 0 | [] | 2 |
sliding-window-median | JavaScript 2 Heaps & Binary Search [2 approaches] | javascript-2-heaps-binary-search-2-appro-6xjt | 2 Heaps\nSlower than below but better at scale\njavascript\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number[]}\n */\nvar medianSlidingW | stevenkinouye | NORMAL | 2020-01-13T04:18:42.100601+00:00 | 2020-01-15T03:49:40.713773+00:00 | 1,239 | false | # 2 Heaps\nSlower than below but better at scale\n```javascript\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number[]}\n */\nvar medianSlidingWindow = function(nums, k) {\n const window = new Window();\n for (let i = 0; i < k - 1; i++) window.add(nums[i]);\n let res = [];\n for (let i = k - 1;... | 5 | 0 | ['Binary Search', 'Heap (Priority Queue)', 'JavaScript'] | 7 |
sliding-window-median | Java solution using 2 heap simplify. | java-solution-using-2-heap-simplify-by-k-p96j | \nclass Solution {\n PriorityQueue<Integer> maxHeap; // 1st part\n PriorityQueue<Integer> minHeap; // 2nd part\n \n public Solution() {\n // | kode_4_living | NORMAL | 2020-01-03T05:30:36.616957+00:00 | 2020-01-03T05:34:31.132237+00:00 | 682 | false | ```\nclass Solution {\n PriorityQueue<Integer> maxHeap; // 1st part\n PriorityQueue<Integer> minHeap; // 2nd part\n \n public Solution() {\n // use Collections.reverseOrder() as comparator as this will work when input number as max integer, can\'t use (a,b)->b-a\n maxHeap = new PriorityQueue<>... | 5 | 0 | ['Heap (Priority Queue)', 'Java'] | 1 |
sliding-window-median | Easy to understand Python solution O(nk) | easy-to-understand-python-solution-onk-b-sdqj | \n\nclass Solution(object):\n def medianSlidingWindow(self, nums, k):\n """\n :type nums: List[int]\n :type k: int\n :rtype: List | hkhushk3 | NORMAL | 2017-10-03T06:13:38.543000+00:00 | 2018-08-09T19:53:44.276377+00:00 | 968 | false | \n```\nclass Solution(object):\n def medianSlidingWindow(self, nums, k):\n """\n :type nums: List[int]\n :type k: int\n :rtype: List[float]\n """\n medians = []\n sortedwindow = sorted(nums[ : k])\n medians.append((sortedwindow[k/2] + sortedwindow[k/2 - (k%2 ==... | 5 | 0 | [] | 0 |
sliding-window-median | Utilize to heaps to find median, and hashmap for counts when updating window | utilize-to-heaps-to-find-median-and-hash-r866 | Intuition\n Describe your first thoughts on how to solve this problem. \nThis problem is similar to the "Find Median from data stream" problem, but the main dif | yqd5143 | NORMAL | 2024-10-22T21:41:56.572826+00:00 | 2024-10-22T21:41:56.572842+00:00 | 496 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem is similar to the "Find Median from data stream" problem, but the main difference is that we are looking to find the median for all possible window of an arbitrary size k <= n which is the size of our nums list. \n\nTo find t... | 4 | 0 | ['Hash Table', 'Sliding Window', 'Heap (Priority Queue)', 'Python3'] | 0 |
sliding-window-median | simple and easy solution using PBDS 😍❤️🔥 | simple-and-easy-solution-using-pbds-by-s-4vsh | if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n# Code\n\n#include<ext/pb_ds/assoc_container.hpp>\n#include<ext/pb_ds/tree_policy.hpp>\nusing namespace __ | shishirRsiam | NORMAL | 2024-05-25T13:26:20.914625+00:00 | 2024-05-25T13:26:20.914655+00:00 | 1,078 | false | # if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n# Code\n```\n#include<ext/pb_ds/assoc_container.hpp>\n#include<ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\n\ntemplate <typename T> using pbds = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\n\nclass Solution {\npublic:\n... | 4 | 0 | ['Array', 'Hash Table', 'Sliding Window', 'C++'] | 3 |
sliding-window-median | Multiset and advance() - O(nlog(k)) | multiset-and-advance-onlogk-by-ritvic-ag-cqwy | Code\n\nclass Solution {\npublic:\n vector<double> medianSlidingWindow(vector<int>& nums, int k) {\n multiset<long> s; // create a multiset to store the e | ritvic-agg | NORMAL | 2022-12-31T07:22:22.709330+00:00 | 2023-01-03T14:25:53.321312+00:00 | 1,294 | false | # Code\n```\nclass Solution {\npublic:\n vector<double> medianSlidingWindow(vector<int>& nums, int k) {\n multiset<long> s; // create a multiset to store the elements of the window\n vector<double> v; // create a vector to store the median values\n // insert the first k-1 elements into the multiset\n ... | 4 | 0 | ['C++'] | 3 |
sliding-window-median | Using multiset beats 90% C++ | using-multiset-beats-90-c-by-idvjojo123-9z59 | \nclass Solution {\npublic:\n int b;\n double picaro;\n multiset<long long > halfmin,halfmax;\n vector<double> ans;\n void huy(int v)\n {\n | idvjojo123 | NORMAL | 2022-12-29T15:21:40.539936+00:00 | 2022-12-29T15:21:40.539965+00:00 | 1,090 | false | ```\nclass Solution {\npublic:\n int b;\n double picaro;\n multiset<long long > halfmin,halfmax;\n vector<double> ans;\n void huy(int v)\n {\n b=0;\n if(halfmin.size()==halfmax.size())\n {\n b=1;\n if(v>*halfmax.begin()) halfmax.insert(v);\n else... | 4 | 0 | ['C'] | 0 |
sliding-window-median | [C++] 2 solutions: Binary Search | Height Balanced Tree + Pointer movement [Detailed Explanation] | c-2-solutions-binary-search-height-balan-bnef | \n/*\n https://leetcode.com/problems/sliding-window-median/\n \n 1. SOLUTION 1: Binary Search\n \n The core idea is we maintain a sorted window o | cryptx_ | NORMAL | 2022-07-25T10:31:52.388178+00:00 | 2022-07-25T10:31:52.388249+00:00 | 675 | false | ```\n/*\n https://leetcode.com/problems/sliding-window-median/\n \n 1. SOLUTION 1: Binary Search\n \n The core idea is we maintain a sorted window of elements. Initially we make the 1st window and sort all its elements.\n Then from there onwards any insertion or deletion is done by first finding the a... | 4 | 0 | ['Binary Search', 'Tree', 'C', 'C++'] | 0 |
sliding-window-median | Java Solution using 2 Priority Queues | Median Priority Queue | Easy to Understand | java-solution-using-2-priority-queues-me-o83s | Please upvote, if you find it useful :)\n\n\nclass Solution {\n \n public PriorityQueue<Integer> left = new PriorityQueue<>(Collections.reverseOrder());\n | kxbro | NORMAL | 2022-06-08T14:38:48.516371+00:00 | 2022-06-08T14:43:37.984212+00:00 | 1,394 | false | Please upvote, if you find it useful :)\n\n```\nclass Solution {\n \n public PriorityQueue<Integer> left = new PriorityQueue<>(Collections.reverseOrder());\n public PriorityQueue<Integer> right = new PriorityQueue<>();\n \n public double[] medianSlidingWindow(int[] nums, int k) {\n for(int i=0; i<... | 4 | 0 | ['Java'] | 3 |
sliding-window-median | C++ || Simplest Code to Understand || Explained || Priority Queue | c-simplest-code-to-understand-explained-hy9do | Please do upvote if you liked my code ;)\n\n\nclass Solution {\npublic:\n multiset<double> minH;\n multiset<double, greater<double>> maxH;\n \n void | markrash4 | NORMAL | 2022-05-15T18:50:19.159319+00:00 | 2022-05-15T18:50:19.159360+00:00 | 433 | false | **Please do upvote if you liked my code ;)**\n\n```\nclass Solution {\npublic:\n multiset<double> minH;\n multiset<double, greater<double>> maxH;\n \n void balanceHeaps()\n {\n if(maxH.size() > minH.size())\n {\n minH.insert(*maxH.begin()); \n maxH.erase(maxH.begin())... | 4 | 0 | ['C', 'Heap (Priority Queue)', 'C++'] | 0 |
sliding-window-median | Multiset Solution | Simple & Short | Easy to Understand | multiset-solution-simple-short-easy-to-u-me71 | Idea?\n Maintain two multisets for each k size subarray.\n First multiset will store the first (k+1)/2 integers while second multiset will store k/2 elements.\n | sunny_38 | NORMAL | 2022-03-10T13:28:21.534311+00:00 | 2022-03-10T13:28:41.123445+00:00 | 142 | false | **Idea?**\n* Maintain **two multisets** for each k size subarray.\n* First multiset will store the first **(k+1)/2** integers while second multiset will store **k/2** elements.\n* Note that first multiset stores element in non-increasing order while second multiset will store the elements in non-decreasing order.\n* Wh... | 4 | 0 | [] | 0 |
sliding-window-median | C++ | 2 heaps | O(nlogn) | c-2-heaps-onlogn-by-tanyarajhans7-2gg3 | \nclass Solution {\npublic:\n vector<double> ans;\n unordered_map<int, int> m; //to store the elements to be discarded\n priority_queue<int> maxh; //ma | tanyarajhans7 | NORMAL | 2022-03-07T07:59:35.005331+00:00 | 2022-03-07T07:59:35.005363+00:00 | 674 | false | ```\nclass Solution {\npublic:\n vector<double> ans;\n unordered_map<int, int> m; //to store the elements to be discarded\n priority_queue<int> maxh; //max heap for lower half \n priority_queue<int, vector<int>, greater<int>> minh; //min heap for upper half \n \n vector<double> medianSlidingWindow(vec... | 4 | 1 | ['Heap (Priority Queue)'] | 1 |
sliding-window-median | Python simple solution using SortedList | python-simple-solution-using-sortedlist-2qvdh | Adding and removing from sortedList is O(logk) operation. \n\nSo time complexity is O(n* logk) and Space is O(k) for sortedList \n\nfrom sortedcontainers import | ikna | NORMAL | 2021-11-08T07:06:16.713073+00:00 | 2021-11-08T07:06:28.666736+00:00 | 424 | false | Adding and removing from sortedList is O(logk) operation. \n\nSo time complexity is O(n* logk) and Space is O(k) for sortedList \n```\nfrom sortedcontainers import SortedList\nclass Solution:\n def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:\n res = []\n sl = SortedList()\n ... | 4 | 0 | ['Python'] | 1 |
sliding-window-median | Short Python solution, O(n log k) | short-python-solution-on-log-k-by-404akh-g0fw | \nfrom sortedcontainers import SortedList\n\nclass Solution:\n def medianSlidingWindow(self, nums, k):\n sl = SortedList(nums[:k - 1])\n wd = [ | 404akhan | NORMAL | 2021-09-22T12:02:28.344123+00:00 | 2021-09-22T12:02:28.344218+00:00 | 492 | false | ```\nfrom sortedcontainers import SortedList\n\nclass Solution:\n def medianSlidingWindow(self, nums, k):\n sl = SortedList(nums[:k - 1])\n wd = []\n\n for i in range(k - 1, len(nums)):\n sl.add(nums[i])\n wd.append((sl[(k - 1) // 2] + sl[k // 2]) / 2)\n sl.remov... | 4 | 0 | [] | 1 |
sliding-window-median | C++ | Simple Approach | Sorted Vector - O(N*K) | Beats 99.52% on memory use | c-simple-approach-sorted-vector-onk-beat-ay9r | We define a custom class sorted_vector with only 3 operations\n1. add element by value\n2. remove element by value\n3. get median\n\nWe only keep K elements of | pratham1002 | NORMAL | 2021-08-02T10:51:44.827042+00:00 | 2021-08-13T20:06:18.158160+00:00 | 853 | false | We define a custom class `sorted_vector` with only 3 operations\n1. add element by value\n2. remove element by value\n3. get median\n\nWe only keep K elements of the sliding window in the `sorted_vector` .\n\nTrust me, this is the simplest approach to this question.\n\nFor those of you who aren\'t familiar with `std::l... | 4 | 0 | ['Array', 'Sorting', 'C++'] | 3 |
sliding-window-median | c++ solution (two multiset) | c-solution-two-multiset-by-dilipsuthar60-78ax | \nclass Solution {\npublic:\n multiset<int,greater<int>>left;\n multiset<int>right;\n void balance()\n {\n if(left.size()-right.size()==2)\ | dilipsuthar17 | NORMAL | 2021-06-25T08:20:40.302323+00:00 | 2021-06-25T08:20:40.302359+00:00 | 412 | false | ```\nclass Solution {\npublic:\n multiset<int,greater<int>>left;\n multiset<int>right;\n void balance()\n {\n if(left.size()-right.size()==2)\n {\n int val=*left.begin();\n left.erase(left.begin());\n right.insert(val);\n }\n else if(right.size(... | 4 | 0 | ['C', 'C++'] | 0 |
sliding-window-median | O(nlogk) c++ using ordered multiset (policy based data structure) | onlogk-c-using-ordered-multiset-policy-b-limo | \n#include <ext/pb_ds/assoc_container.hpp> \nusing namespace __gnu_pbds; \ntypedef tree<int, null_type, \n less_equal<int>, rb_tree_tag, \n | devanshuraj226 | NORMAL | 2020-12-23T14:18:40.575984+00:00 | 2020-12-23T14:18:40.576025+00:00 | 1,350 | false | ```\n#include <ext/pb_ds/assoc_container.hpp> \nusing namespace __gnu_pbds; \ntypedef tree<int, null_type, \n less_equal<int>, rb_tree_tag, \n tree_order_statistics_node_update> \n ordered_set; \nclass Solution {\npublic:\n vector<double> medianSlidingWindow(vector<int>& arr, int k) {\n ... | 4 | 0 | [] | 0 |
sliding-window-median | [C++] using multiset beats 98% | c-using-multiset-beats-98-by-suhailakhta-vlsn | c++\n#define ll long long\nclass Solution {\npublic:\n vector<double> medianSlidingWindow(vector<int>& a, int k) {\n int n=a.size();\n multiset | suhailakhtar039 | NORMAL | 2020-09-28T18:41:14.582312+00:00 | 2020-09-28T18:41:14.582356+00:00 | 734 | false | ```c++\n#define ll long long\nclass Solution {\npublic:\n vector<double> medianSlidingWindow(vector<int>& a, int k) {\n int n=a.size();\n multiset<ll> m;\n for(ll i=0;i<k;i++)m.insert(a[i]);\n auto it=m.begin();\n for(ll i=0;i<k/2;i++)\n it++;\n ll med=*it;\n ... | 4 | 1 | ['C', 'C++'] | 0 |
sliding-window-median | python on * k two heap solution | python-on-k-two-heap-solution-by-yingziq-nhes | this idea is from https://leetcode.com/problems/sliding-window-median/discuss/412047/Two-heaps-%2B-sliding-window-approach-O(-n-*-k-)-runtime-O(k)-space\nthanks | yingziqing123 | NORMAL | 2020-04-15T23:27:18.562096+00:00 | 2020-04-15T23:27:18.562130+00:00 | 661 | false | this idea is from https://leetcode.com/problems/sliding-window-median/discuss/412047/Two-heaps-%2B-sliding-window-approach-O(-n-*-k-)-runtime-O(k)-space\nthanks @agconti\n```\nfrom heapq import * \nimport heapq\n\nclass Solution:\n def medianSlidingWindow(self, nums, k: int) :\n \'\'\'\n the concept/id... | 4 | 0 | ['Python3'] | 0 |
sliding-window-median | too long java code, AVL tree. 99% speed and 80% memory. Balanced and Unbalanced BSTs. | too-long-java-code-avl-tree-99-speed-and-gbr7 | Hi, I tried to solve with AVL tree in java. Really good thing would be to use MultiSet but since java doesn\'t have it one built in, I tried to write own. Code | rostau3 | NORMAL | 2019-05-17T21:33:54.219408+00:00 | 2019-05-17T21:48:37.403277+00:00 | 305 | false | Hi, I tried to solve with AVL tree in java. Really good thing would be to use MultiSet but since java doesn\'t have it one built in, I tried to write own. Code became long.\nTime complexity: O(n log(k))\nSpace coplexity: O(n) \n where n is size of array and k is the size of window.\n\n```\nclass Solution {\n public... | 4 | 0 | [] | 0 |
sliding-window-median | O(nlogk) Python solution using Binary Search Tree | onlogk-python-solution-using-binary-sear-ched | My solution is to store the K elements in the current window in a BST. The BST node has other two attributes: dup store the number of duplicates, left_count sto | hx364 | NORMAL | 2017-01-16T03:34:56.623000+00:00 | 2017-01-16T03:34:56.623000+00:00 | 563 | false | My solution is to store the K elements in the current window in a BST. The BST node has other two attributes: ```dup``` store the number of duplicates, ```left_count``` store the number of elements in the current node's left tree.\n\nThree methods of the BST class are implemented. ```insert``` inserts a new value to th... | 4 | 0 | [] | 0 |
sliding-window-median | C# BinarySearch solution | c-binarysearch-solution-by-liberwang-v8hu | \npublic double[] MedianSlidingWindow(int[] nums, int k) {\n List<double> llist = new List<double>();\n\n if (nums != null && nums.Length > 0 && k > 0) {\ | liberwang | NORMAL | 2017-01-18T20:48:23.207000+00:00 | 2017-01-18T20:48:23.207000+00:00 | 553 | false | ```\npublic double[] MedianSlidingWindow(int[] nums, int k) {\n List<double> llist = new List<double>();\n\n if (nums != null && nums.Length > 0 && k > 0) {\n int liPos1 = (k >> 1);\n int liPos2 = liPos1 + (k & 1) - 1;\n\n List<double> llistSlid = new List<double>();\n \n for( i... | 4 | 0 | [] | 2 |
sliding-window-median | Sliding Window Median Using Balanced Multisets | sliding-window-median-using-balanced-mul-dhdm | IntuitionThe problem requires computing the median of every sliding window of size k in an array. Since the median is the middle element in a sorted window, an | sirravirathore | NORMAL | 2025-03-30T19:46:38.290929+00:00 | 2025-03-30T19:46:38.290929+00:00 | 371 | false | # Intuition
The problem requires computing the median of every sliding window of size `k` in an array. Since the median is the middle element in a sorted window, an efficient way to maintain a dynamically changing sorted window is needed.
# Approach
1. **Use two multisets** (`left` and `right`) to maintain a balanced ... | 3 | 0 | ['Array', 'Sliding Window', 'Ordered Set', 'C++'] | 0 |
sliding-window-median | easy readable few lines of code with clear explanation using in line comment ACCEPTED!!!!!!! | easy-readable-few-lines-of-code-with-cle-jjky | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | ResilientWarrior | NORMAL | 2023-10-20T20:14:57.486452+00:00 | 2023-10-20T20:14:57.486493+00:00 | 301 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 3 | 0 | ['Array', 'Sliding Window', 'Python', 'C++', 'Java', 'Python3'] | 0 |
sliding-window-median | ordered_multimap, Policy Based Data Structure in C++ | ordered_multimap-policy-based-data-struc-6g3w | Intuition\nUsing policy based data strucuture, ordered_multimap\n\n# Code\n\n#include <bits/stdc++.h>\n\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext | theroyakash | NORMAL | 2023-10-02T17:23:33.631477+00:00 | 2023-10-02T17:23:33.631500+00:00 | 794 | false | # Intuition\nUsing policy based data strucuture, `ordered_multimap`\n\n# Code\n```\n#include <bits/stdc++.h>\n\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace __gnu_pbds;\n\ntypedef tree<pair<double, int>, null_type, less<pair<double, int>>, rb_tree_tag, tree_order_sta... | 3 | 0 | ['Ordered Map', 'C++'] | 0 |
sliding-window-median | C++ code with explanation | c-code-with-explanation-by-vi_05-ypkw | Complexity\n- Time complexity: O(nlogn)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n\n | Vi_05 | NORMAL | 2023-06-06T08:52:08.880031+00:00 | 2023-06-06T08:52:08.880068+00:00 | 1,097 | false | # Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<double> medianSlidingWindow(vector<int>& nums, int k) {\n //vector to store me... | 3 | 0 | ['Sliding Window', 'Heap (Priority Queue)', 'C++'] | 0 |
sliding-window-median | Sliding Window Median (C#) | sliding-window-median-c-by-framebymahmud-kf4l | Intuition:\nThe problem asks for the median of each sliding window of size k in an input array. One approach to solving this problem is to maintain a sorted lis | framebymahmud | NORMAL | 2023-05-12T11:13:22.860325+00:00 | 2023-05-12T11:13:22.860361+00:00 | 351 | false | Intuition:\nThe problem asks for the median of each sliding window of size k in an input array. One approach to solving this problem is to maintain a sorted list of the elements in the current window, and compute the median from this list. To slide the window, we remove the leftmost element and insert the rightmost ele... | 3 | 0 | ['C#'] | 4 |
sliding-window-median | 480: Solution with step by step explanation | 480-solution-with-step-by-step-explanati-vemk | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. Check if the list is empty or the window size is greater than the list | Marlen09 | NORMAL | 2023-03-10T18:17:34.513444+00:00 | 2023-03-10T18:17:34.513478+00:00 | 2,282 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Check if the list is empty or the window size is greater than the list length. If either of these conditions is true, return an empty list.\n\n2. Create a helper function to calculate the median of a given subarray. If th... | 3 | 0 | ['Array', 'Hash Table', 'Sliding Window', 'Python', 'Python3'] | 3 |
sliding-window-median | Easy understandable implementation in c++ (ordered_set). | easy-understandable-implementation-in-c-0vwgi | Intuition\n Describe your first thoughts on how to solve this problem. \nJust think about the advance data structure ordered set .\n\n# Approach\n Describe your | ups1610 | NORMAL | 2022-11-28T15:11:07.752666+00:00 | 2022-11-28T15:11:07.752714+00:00 | 1,367 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nJust think about the advance data structure ordered set .\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nStore each k window elements in ordered set \nfind the median \nstore each k window median in an array\n# Co... | 3 | 0 | ['C++'] | 1 |
sliding-window-median | ✅Python short and very easy to understand | python-short-and-very-easy-to-understand-hv5a | ```\ndef medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:\n res = []\n for i in range(len(nums)-k+1):\n temp = sorted | SteveDes | NORMAL | 2022-08-03T23:23:08.655766+00:00 | 2022-08-03T23:23:08.655794+00:00 | 580 | false | ```\ndef medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:\n res = []\n for i in range(len(nums)-k+1):\n temp = sorted(nums[i:i+k])\n \n if k % 2 != 0:\n res.append(temp[k//2])\n else:\n avg = (temp[k//2] + temp[k//2-1... | 3 | 0 | ['Python'] | 0 |
sliding-window-median | Simple C++ Code || 2 multiset | simple-c-code-2-multiset-by-prosenjitkun-8x1y | Reference was taken from youtube channel.\n# If you like the implementation then Please help me by increasing my reputation. By clicking the up arrow on the lef | _pros_ | NORMAL | 2022-06-16T03:26:48.829049+00:00 | 2022-06-16T03:26:48.829087+00:00 | 145 | false | # Reference was taken from youtube channel.\n# **If you like the implementation then Please help me by increasing my reputation. By clicking the up arrow on the left of my image.**\n\n```\nclass Solution {\npublic:\n vector<double> medianSlidingWindow(vector<int>& nums, int k) {\n multiset<double> asc;\n ... | 3 | 0 | [] | 0 |
sliding-window-median | Python - Easy to understand using 2 heap | python-easy-to-understand-using-2-heap-b-0xhn | \nimport heapq\n\nclass Solution:\n def getMedian(self, maxHeap: List[int], minHeap: List[int]) -> float:\n # minHeap stores larger half and maxHeap s | abrarjahin | NORMAL | 2022-05-24T11:19:44.248335+00:00 | 2022-05-24T11:19:44.248372+00:00 | 1,644 | false | ```\nimport heapq\n\nclass Solution:\n def getMedian(self, maxHeap: List[int], minHeap: List[int]) -> float:\n # minHeap stores larger half and maxHeap stores small half elements\n # So data is like -> [maxHeap] + [minHeap]\n # if total no of element is odd, then maxHeap contains more elements t... | 3 | 0 | ['Heap (Priority Queue)', 'Python', 'Python3'] | 1 |
sliding-window-median | O(n log k) | C++ | Straight Forward | Using two sets as heaps | on-log-k-c-straight-forward-using-two-se-chpz | The question is similar to find median in a stream https://leetcode.com/problems/find-median-from-data-stream/.\nI\'d suggest you to go through the above proble | onemol | NORMAL | 2022-03-12T10:56:34.816708+00:00 | 2022-03-12T10:56:34.816733+00:00 | 187 | false | The question is similar to find median in a stream https://leetcode.com/problems/find-median-from-data-stream/.\nI\'d suggest you to go through the above problem before proceeding with this one\n\nThere are two things to keep in mind: \n1. Create balanced heaps for current window. \n2. Discard elements that are out of ... | 3 | 0 | ['Heap (Priority Queue)', 'Ordered Set'] | 2 |
sliding-window-median | C# solution PriorityQueue || Similar solution for leet code 295 and leet code 480 | c-solution-priorityqueue-similar-solutio-6kjy | Lets first understand the solution of problem #295 - Median of data streams\n\n1. Partition streaming numbers into 2 halves\n2. maxHeap - for all smaller number | adparoha | NORMAL | 2022-02-13T00:02:11.592954+00:00 | 2022-02-13T00:04:09.673779+00:00 | 186 | false | Lets first understand the solution of problem #295 - Median of data streams\n\n1. Partition streaming numbers into 2 halves\n2. maxHeap - for all smaller numbers\n3. minHeap - for all larger numbers\n4. Balance heap - whenever difference of both heap size > 1\n5. Find Median - for odd numbers - maxHeap peek is median, ... | 3 | 0 | ['Heap (Priority Queue)'] | 0 |
sliding-window-median | JAVA simple solution using min-heap and max-heap | java-simple-solution-using-min-heap-and-2p2pf | Slide through each of the window of size K and calculate median of each window.\nTime Complexity : O(nlogn)\nSpace Complexity: O(n)\n\n\nclass Solution {\n \ | mitesh_pv | NORMAL | 2022-01-15T06:41:13.861821+00:00 | 2022-01-15T06:47:03.999891+00:00 | 937 | false | Slide through each of the window of size K and calculate median of each window.\nTime Complexity : **O(nlogn)**\nSpace Complexity: **O(n)**\n\n```\nclass Solution {\n \n PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());\n PriorityQueue<Integer> minHeap = new PriorityQueue<>();\n... | 3 | 0 | ['Heap (Priority Queue)', 'Java'] | 1 |
sliding-window-median | C++ solution using GNU-PBDS | c-solution-using-gnu-pbds-by-mihir_devil-03dh | \n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\n#define ordered_set tree<pair<int,int>,null_type, | mihir_devil | NORMAL | 2021-07-05T23:00:58.520442+00:00 | 2021-07-05T23:00:58.520474+00:00 | 303 | false | ```\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\n#define ordered_set tree<pair<int,int>,null_type,less<pair<int,int>>,rb_tree_tag,tree_order_statistics_node_update>\nclass Solution {\npublic:\n vector<double> medianSlidingWindow(vector<int>& a, int k) ... | 3 | 0 | [] | 0 |
sliding-window-median | Multiset C++ Solution | multiset-c-solution-by-voquocthang99-2kr5 | ```\nclass Solution {\npublic:\n void Balance(multiset & left, multiset & right) {\n int n = left.size();\n int m = right.size();\n if ( | voquocthang99 | NORMAL | 2021-05-10T07:06:23.714986+00:00 | 2021-05-10T07:06:23.715049+00:00 | 381 | false | ```\nclass Solution {\npublic:\n void Balance(multiset<int> & left, multiset<int> & right) {\n int n = left.size();\n int m = right.size();\n if (n == m || n+1 == m) return;\n if (n > m) {\n auto it = left.end();\n it--;\n right.emplace(*it);\n ... | 3 | 0 | [] | 3 |
sliding-window-median | Java Solution - TreeSet - O(n*logk) | java-solution-treeset-onlogk-by-mycafeba-0fne | \nclass Solution {\n public double[] medianSlidingWindow(int[] nums, int k) {\n Comparator<Integer> comparator = (a, b) -> nums[a] != nums[b] ? Intege | mycafebabe | NORMAL | 2021-05-07T06:15:02.257694+00:00 | 2021-05-07T06:15:02.257736+00:00 | 239 | false | ```\nclass Solution {\n public double[] medianSlidingWindow(int[] nums, int k) {\n Comparator<Integer> comparator = (a, b) -> nums[a] != nums[b] ? Integer.compare(nums[a], nums[b]) : a - b;\n TreeSet<Integer> left = new TreeSet<>(comparator);\n TreeSet<Integer> right = new TreeSet<>(comparator);... | 3 | 1 | [] | 0 |
sliding-window-median | TypeScript O(nk + klogk) solution. No heap | typescript-onk-klogk-solution-no-heap-by-f9lf | You can\'t write a heap data structure during the interview if you use JS/TS\nSort the first window using O(klogk). Then use O(k) to keep the window sorted when | pike96 | NORMAL | 2021-04-27T05:50:35.623695+00:00 | 2021-04-27T05:50:35.623742+00:00 | 167 | false | You can\'t write a heap data structure during the interview if you use JS/TS\nSort the first window using O(klogk). Then use O(k) to keep the window sorted when adding & removing elements\n\nIt\'s actually O(nk + klogk)\n\n```\nfunction medianSlidingWindow(nums: number[], k: number): number[] {\n const medians: numb... | 3 | 0 | ['TypeScript'] | 0 |
sliding-window-median | Python bisect solution, easy to understand, faster than 99.83% | python-bisect-solution-easy-to-understan-hnhf | \nimport bisect\n\nclass Solution:\n\tdef median(self, nums: List[int]) -> float:\n\t\tmid = len(nums) // 2\n\t\tif len(nums) % 2:\n\t\t\treturn nums[mid]\n\t\t | tumepjlah | NORMAL | 2021-02-12T08:44:45.133501+00:00 | 2021-02-14T09:26:34.924905+00:00 | 715 | false | ```\nimport bisect\n\nclass Solution:\n\tdef median(self, nums: List[int]) -> float:\n\t\tmid = len(nums) // 2\n\t\tif len(nums) % 2:\n\t\t\treturn nums[mid]\n\t\treturn (nums[mid-1] + nums[mid])/2\n \n\tdef medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:\n\t\tif not nums:\n\t\t\treturn []\n\n\t\t... | 3 | 0 | ['Python', 'Python3'] | 2 |
sliding-window-median | Sliding Window Easy to understand cpp solution | sliding-window-easy-to-understand-cpp-so-k124 | \nclass Solution {\npublic:\n int getIndex(vector<int>& window,int element){ //binary search\n int first = 0;\n int last = window.size()-1;\n | hd_16 | NORMAL | 2020-10-02T12:59:51.555030+00:00 | 2020-10-02T12:59:51.555062+00:00 | 198 | false | ```\nclass Solution {\npublic:\n int getIndex(vector<int>& window,int element){ //binary search\n int first = 0;\n int last = window.size()-1;\n while(first<=last){\n int mid = (first+last)/2;\n if(window[mid] == element)\n return mid;\n if(window[... | 3 | 0 | [] | 0 |
sliding-window-median | C++ using multiset | c-using-multiset-by-degalasivasairam-ni8l | //next(it,n) returns the iterator at the next address of the given n from it\n\n vector<double> medianSlidingWindow(vector<int>& nums, int k) {\n vector<doub | DegalaSivaSaiRam | NORMAL | 2020-06-10T16:56:16.037077+00:00 | 2020-06-10T16:56:16.037122+00:00 | 366 | false | //next(it,n) returns the iterator at the next address of the given n from it\n```\n vector<double> medianSlidingWindow(vector<int>& nums, int k) {\n vector<double> ans;\n if (k == 0) return ans;\n multiset<int>s(nums.begin(), nums.begin() + k);\n auto mid = next(s.begin(), (k - 1) / 2);\n if(k%2!=0)\n ... | 3 | 0 | [] | 1 |
sliding-window-median | Simple Javascript solution with sliding window | simple-javascript-solution-with-sliding-radyj | \nvar medianSlidingWindow = function(nums, k) {\n if (!nums.length) {\n return [];\n }\n\n // find the median of the first window\n const fir | bozilhan | NORMAL | 2020-03-01T15:38:11.208671+00:00 | 2020-03-01T15:38:11.208719+00:00 | 861 | false | ```\nvar medianSlidingWindow = function(nums, k) {\n if (!nums.length) {\n return [];\n }\n\n // find the median of the first window\n const firstSlided = nums.slice(0, k);\n\n let medians = [findMedian(firstSlided)];\n\n for (let i = k; i < nums.length; i++) {\n const slidedArr = nums.s... | 3 | 0 | [] | 1 |
sliding-window-median | Short and Simple Java Solution | short-and-simple-java-solution-by-zlareb-6age | \nclass Solution {\n public double[] medianSlidingWindow(int[] nums, int k) {\n double[] res=new double[nums.length-k+1];\n if(nums==null || nu | zlareb1 | NORMAL | 2019-08-08T16:39:00.809261+00:00 | 2019-08-08T16:39:00.809294+00:00 | 284 | false | ```\nclass Solution {\n public double[] medianSlidingWindow(int[] nums, int k) {\n double[] res=new double[nums.length-k+1];\n if(nums==null || nums.length==0 || k<=0) return res;\n PriorityQueue<Integer> left=new PriorityQueue<>(Collections.reverseOrder());\n PriorityQueue<Integer> right... | 3 | 0 | [] | 1 |
sliding-window-median | Design and implement the interface of Hash Heap in Java | design-and-implement-the-interface-of-ha-m4od | \nclass Solution {\n\n public double[] medianSlidingWindow(int[] nums, int k) {\n \n // maxHeap maitians the half small part\n // maitai | wirybeaver | NORMAL | 2019-03-20T22:04:06.183363+00:00 | 2019-03-20T22:04:06.183406+00:00 | 2,643 | false | ```\nclass Solution {\n\n public double[] medianSlidingWindow(int[] nums, int k) {\n \n // maxHeap maitians the half small part\n // maitain the propetry (*): maxHeap.size() - minHeap.size() = 0 or 1 \n if(nums.length==0 || k<=0){\n return new double[nums.length];\n }\n ... | 3 | 0 | [] | 3 |
alternating-groups-ii | ✔️ Sliding Window | Python | C++ | Java | JS | C# | Go | Swift | Rust | sliding-window-python-by-otabek_kholmirz-7pg5 | IntuitionThe problem requires finding alternating groups of length k. A key observation is that we can extend the array to simulate a cyclic sequence, ensuring | otabek_kholmirzaev | NORMAL | 2025-03-09T00:30:37.552522+00:00 | 2025-03-09T02:25:13.151386+00:00 | 27,130 | false | # Intuition
The problem requires finding alternating groups of length `k`. A key observation is that we can extend the array to simulate a cyclic sequence, ensuring we check all possible groups without worrying about wrapping around.
# Approach
1. Extend the array
- We append the first `(k-1)` elements to the end ... | 164 | 3 | ['Swift', 'Sliding Window', 'Python', 'C++', 'Java', 'Go', 'Python3', 'Rust', 'JavaScript', 'C#'] | 10 |
alternating-groups-ii | Solution By Dare2Solve | Detailed Explanation | Clean Code | solution-by-dare2solve-detailed-explanat-bpvk | Explanation []\nauthorslog.vercel.app/blog/CB5AJHUJFs\n\n\n# Code\n\ncpp []\nclass Solution {\npublic:\n int numberOfAlternatingGroups(vector<int>& colors, i | Dare2Solve | NORMAL | 2024-07-06T16:04:36.436116+00:00 | 2024-07-06T16:07:47.725876+00:00 | 4,837 | false | ```Explanation []\nauthorslog.vercel.app/blog/CB5AJHUJFs\n```\n\n# Code\n\n```cpp []\nclass Solution {\npublic:\n int numberOfAlternatingGroups(vector<int>& colors, int k) {\n for (int i = 0; i < k - 1; ++i) colors.push_back(colors[i]);\n int res = 0;\n int cnt = 1;\n for (int i = 1; i < ... | 58 | 5 | ['Python', 'C++', 'Java', 'Python3', 'JavaScript'] | 20 |
alternating-groups-ii | n + k - 2 | n-k-2-by-votrubac-msly | We count alternating elements for i up to n + k - 2. \n\nIf two neighbours have the same color, we reset the count to 1.\n\nWhen the count reaches or exceeds k, | votrubac | NORMAL | 2024-07-06T16:01:26.668469+00:00 | 2024-07-06T16:56:54.586888+00:00 | 2,220 | false | We count alternating elements for `i` up to `n + k - 2`. \n\nIf two neighbours have the same color, we reset the count to 1.\n\nWhen the count reaches or exceeds `k`, we found an alternating group.\n\n**C++**\n```cpp\nint numberOfAlternatingGroups(vector<int>& colors, int k) {\n int n = colors.size(), res = 0, cnt =... | 43 | 6 | [] | 6 |
alternating-groups-ii | 1 pass||36ms Beats 100% | 1-pass39ms-beats-100-by-anwendeng-72uk | IntuitionAgain sliding window
1 pass can solve it.
C++, Python & C are made.Approach
let n=|color|, sz=n+k-1
Initialize ans=0, alt=1, prev=color[0] where ans is | anwendeng | NORMAL | 2025-03-09T00:20:24.107416+00:00 | 2025-03-09T04:06:10.104715+00:00 | 3,784 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Again sliding window
1 pass can solve it.
C++, Python & C are made.
# Approach
<!-- Describe your approach to solving the problem. -->
1. let `n=|color|, sz=n+k-1`
2. Initialize `ans=0, alt=1, prev=color[0]` where `ans` is the answer to re... | 31 | 0 | ['C', 'Sliding Window', 'C++', 'Python3'] | 5 |
alternating-groups-ii | ✅ Sliding Window - Cyclic Comparison 🔥| Visualization ✨| Math | Python | Java | C++ | C ✨ | sliding-window-cyclic-comparison-visuali-ux6m | Approach
Complexity
Time complexity: O(n+k)
Space complexity: O(1)
Code | Raw_Ice | NORMAL | 2025-03-09T02:15:07.784344+00:00 | 2025-03-09T02:26:02.177822+00:00 | 6,034 | false | # Approach


# Complexity
- Time complexity: $$O(n+k)$$
- Space complexity: $$O(1)$$
... | 24 | 0 | ['Array', 'Math', 'Dynamic Programming', 'C', 'Counting', 'Python', 'C++', 'Java', 'Python3'] | 5 |
alternating-groups-ii | EASY O(N) || Sliding Window | easy-on-sliding-window-by-mohit_kukreja-fib3 | Intuition\nUse simple sliding window technique.\n\nCount bad pairs in a window. \nWhen the window size reaches k check if there is any bad pair or not. \nNow sh | Mohit_kukreja | NORMAL | 2024-07-06T16:12:19.187573+00:00 | 2024-07-07T05:43:44.748342+00:00 | 2,105 | false | # Intuition\nUse simple **sliding window** technique.\n\n*Count bad pairs* in a window. \nWhen the window size reaches k check if there is any bad pair or not. \nNow shift the window and remember to adjust the bad pairs.\n\n# Complexity\n- Time complexity: O(n) Just a simple traversal\n\n- Space complexity: O(1)\n\n# C... | 24 | 4 | ['Sliding Window', 'C++'] | 5 |
alternating-groups-ii | 🔥BEATS 💯 % 🎯 |✨SUPER EASY BEGINNERS 👏| JAVA | C | C++ | PYTHON| JAVASCRIPT | DART | beats-super-easy-beginners-java-c-c-pyth-t7i0 | IntuitionThe problem requires us to determine the number of valid alternating groups of size k in a circular array. A valid alternating group means that no two | CodeWithSparsh | NORMAL | 2025-03-09T06:45:42.742940+00:00 | 2025-03-09T07:11:57.842520+00:00 | 2,156 | false | 
-----

------
## **Intuition**
The problem requires us to determine the number of ... | 21 | 0 | ['Array', 'C', 'Sliding Window', 'Python', 'C++', 'Java', 'Python3', 'JavaScript', 'Dart', 'Python ML'] | 2 |
alternating-groups-ii | Iterate with alternate check | iterate-with-alternate-check-by-kreakemp-mfgv | \n\n# Approach 1: (two pass)\n- Simply count the alternate contiguous items length\n- As soon as the count more equal to k, increase ans by one as we found one | kreakEmp | NORMAL | 2024-07-06T16:01:36.342732+00:00 | 2024-07-06T16:21:41.330453+00:00 | 2,825 | false | \n\n# Approach 1: (two pass)\n- Simply count the alternate contiguous items length\n- As soon as the count more equal to k, increase ans by one as we found one group\n- Once we reach end, continue counting from begin again up to k-1 items due to circular nature.\n\n\n```\nint numberOfAlternatingGroups(vector<int>& colo... | 17 | 5 | ['C++'] | 6 |
alternating-groups-ii | [Java/Python 3] Sliding window 1 pass O(n) codes w/ brief explanation and analysis. | javapython-3-sliding-window-1-pass-on-co-2c0r | Note: Sliding window lower boundary lo is exclusive, and upper boundary hi is inclusive. That is, (lo, hi] is the sliding window range.
Append first k - 1 items | rock | NORMAL | 2024-07-06T16:04:18.175482+00:00 | 2025-03-09T11:35:24.610121+00:00 | 1,579 | false | **Note:** Sliding window lower boundary `lo` is exclusive, and upper boundary `hi` is inclusive. That is, `(lo, hi]` is the sliding window range.
1. Append first `k - 1` items to the end of the input `colors` so that we will NOT omit those groups including first and last items;
2. Traverse the modified array in 1, and... | 15 | 0 | ['Sliding Window', 'Java', 'Python3'] | 6 |
alternating-groups-ii | Python 3 || 7 lines, iterate and count || T/S: 97% / 98% | python-3-8-lines-iterate-and-count-ts-97-1gdp | Here's the plan:
We extend colors by the initial k - 1 elements of 'colors` in order to eschew all the modular arithmetic.
We iterate through colors by pairs, c | Spaulding_ | NORMAL | 2024-07-06T19:05:01.425827+00:00 | 2025-03-09T03:07:04.399122+00:00 | 165 | false | Here's the plan:
1. We extend `colors` by the initial *k* - 1 elements of 'colors` in order to eschew all the modular arithmetic.
2. We iterate through `colors` by pairs, checking whether the colors are equal.
3. If equal, we know the current subarray is not alternating. We end the current subarray by incrementing `ans... | 12 | 0 | ['Python', 'Python3'] | 1 |
alternating-groups-ii | Beats 100% ✅ || Short code with Detailed explanation 🔥 || Very Easy to understand for beginners 💯 | beats-100-short-code-with-detailed-expla-40l1 | Intuition\nTo solve this problem, we need to count the number of alternating groups of length \uD835\uDC58 in a circular array of tiles. An alternating group is | soukarja | NORMAL | 2024-07-06T16:01:23.087498+00:00 | 2024-07-06T16:01:23.087533+00:00 | 1,234 | false | # Intuition\nTo solve this problem, we need to count the number of alternating groups of length `\uD835\uDC58` in a circular array of tiles. An alternating group is a sequence of tiles where each tile has a different color than its adjacent tiles. Since the array is circular, the last tile is considered adjacent to the... | 11 | 0 | ['C++', 'Java', 'Python3'] | 5 |
alternating-groups-ii | JAVA (5ms) Simplest Solution | java-5ms-simplest-solution-by-devansh_ya-x5tr | IntuitionWe need to find alternating groups of length k in a circular array. Instead of checking every possible group from scratch, we can efficiently track the | Devansh_Yadav_11 | NORMAL | 2025-03-09T07:05:05.694945+00:00 | 2025-03-09T07:05:05.694945+00:00 | 569 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
We need to find alternating groups of length k in a circular array. Instead of checking every possible group from scratch, we can efficiently track the length of alternating sequences as we traverse the array.
# Approach
<!-- Describe your... | 7 | 0 | ['Java'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.