arif334

Lab Solutions

Jul 23rd, 2025
276
0
29 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | Help | 0 0
  1. // LeetCode 20. Valid Parentheses [Hint: Use Stack]
  2. bool isValid(string x) { // Complexity: O(n)
  3.     stack<char> s;
  4.     for(char c: x) {
  5.         if(c == '(' or c == '{' or c == '[')
  6.             s.push(c);
  7.         else if(s.empty()) return false;
  8.         else {
  9.             char last = s.top();
  10.             s.pop();
  11.             if((last=='(' and c==')')
  12.                or (last=='{' and c=='}')
  13.                or (last=='[' and c==']'))
  14.                 ;
  15.             else return false;
  16.         }
  17.     }
  18.     return s.empty();
  19. }
  20.  
  21.  
  22. // Leetcode 1046. Last Stone Weight [Hint: Use Priority Queue]
  23. int lastStoneWeight(vector<int>& stones) { // Complexity: O(n log n)
  24.     priority_queue<int> pq(stones.begin(), stones.end());
  25.  
  26.     while(pq.size() > 1) {
  27.         int y = pq.top(); pq.pop();
  28.         int x = pq.top(); pq.pop();
  29.         if(y > x) pq.push(y - x);
  30.     }
  31.  
  32.     if(!pq.empty()) return pq.top();
  33.     return 0;
  34. }
  35.  
  36.  
  37. // LeetCode 239. Sliding Window Maximum [Hint: Use Deque]
  38. vector<int> maxSlidingWindow(vector<int>& nums, int k) { // Complexity: O(n)
  39.     deque<int> dq;
  40.     int n = nums.size();
  41.     vector<int> ans;
  42.     for(int i = 0; i < n; i++) {
  43.         if(!dq.empty() and dq.front()<=(i-k))
  44.             dq.pop_front();
  45.  
  46.         while(!dq.empty() and nums[dq.back()] < nums[i])
  47.             dq.pop_back();
  48.  
  49.         dq.push_back(i);
  50.         if(i >= k - 1) ans.push_back(nums[dq.front()]);
  51.     }
  52.  
  53.     return ans;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment