I was attempting the Leetcode Problem 239(Sliding Window Maximum).
Consider the two implementations, Sol1 and Sol2.
Sol1:
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
deque<int> dq;
vector<int> ans;
for (int i=0; i<nums.size(); i++) {
if (!dq.empty() && dq.back() == i-k) dq.pop_back();
while (!dq.empty() && nums[dq.front()] < nums[i]) dq.pop_front();
dq.push_front(i);
if (i>=k-1) ans.push_back(nums[dq.back()]);
}
return ans;
}
};
Sol2:
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
deque<int> dq;
vector<int> ans;
for (int i=0; i<nums.size(); i++) {
if (!dq.empty() && dq.front() == i-k) dq.pop_front();
while (!dq.empty() && nums[dq.back()] < nums[i]) dq.pop_back();
dq.push_back(i);
if (i>=k-1) ans.push_back(nums[dq.front()]);
}
return ans;
}
};
Sol2 differs from Sol1 in these ways:
- The
back()
method of the deque has been changed tofront()
and vice versa. - The
push_front()
method of the deque has been changed topush_back()
and vice versa. - The
pop_front()
method of the deque has been changed topop_back()
and vice versa. Logically, these two implementations are similar.
According to the C++ deque implementation,
The complexity (efficiency) of common operations on deques is as follows:
- Random access - constant O(1)
- Insertion or removal of elements at the end or beginning - constant O(1)
- Insertion or removal of elements - linear O(n)
But I observed a significant difference in the time and memory consumed by these implementations. I tried to check with few compilers, the differences are still there.
The results and the entire code used for testing can be found in this gist. Why is there a difference between the 2 implementations (Sol1 and Sol2)? There is also a difference when we use different compilers. I am not able to figure this out. Any help is appreciated.