0% found this document useful (0 votes)
173 views7 pages

Stack and Queues Strivers

Uploaded by

Thirishaa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
173 views7 pages

Stack and Queues Strivers

Uploaded by

Thirishaa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 7

20.

Valid Parentheses
Example 1:

Input: s = "()"
Output: true
Example 2:

Input: s = "()[]{}"
Output: true
Example 3:

Input: s = "(]"
Output: false

bool isValid(string s) {
stack<char>st;
for(auto i:s){
if(i=='(' || i=='{'||i=='['){
st.push(i);
}
else{
if(st.size()==0){
return false;
}
char ch=st.top();
st.pop();
if((i==')' and ch=='(') || (i=='}' and ch=='{' ) || (i==']' and
ch=='[')){
continue;
}
else{
return false;
}
}
}
return st.empty();

-----------------------------------------------------------------------------------
----------------------------------
MIN STACK
Implement the MinStack class:

MinStack() initializes the stack object.


void push(int val) pushes the element val onto the stack.
void pop() removes the element on the top of the stack.
int top() gets the top element of the stack.
int getMin() retrieves the minimum element in the stack.
You must implement a solution with O(1) time complexity for each function.

Example 1:

Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
Output
[null,null,null,null,-3,null,0,-2]

Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2

#include<algorithm>
class MinStack {
stack<pair<int,int>> st;
public:
MinStack() {

void push(int val) {


int mini;
if(st.empty()){
mini=val;
}
else{
mini=std::min(st.top().second,val);
}
st.push({val,mini});
}

void pop() {

st.pop();

int top() {
return st.top().first;

int getMin() {
return st.top().second;

}
};

-----------------------------------------------------------------------------------
-----------------------
496. Next Greater Element I
Solved
Easy
Topics
Companies
The next greater element of some element x in an array is the first greater element
that is to the right of x in the same array.

You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is
a subset of nums2.

For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and
determine the next greater element of nums2[j] in nums2. If there is no next
greater element, then the answer for this query is -1.

Return an array ans of length nums1.length such that ans[i] is the next greater
element as described above.

Example 1:

Input: nums1 = [4,1,2], nums2 = [1,3,4,2]


Output: [-1,3,-1]
Explanation: The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the
answer is -1.
- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.
- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the
answer is -1.

vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {


vector<int>vec;
for(int i=0;i<nums1.size();i++){
int nextgreater=-1;
for(int j=0;i<nums2.size();j++){
if(nums1[i]==nums2[j]){
for(int k=j+1;k<nums2.size();k++){
if(nums2[k]>nums1[i]){
nextgreater=nums2[k];
break;
}

}
break;
}}
vec.push_back(nextgreater);
}
return vec;
}

-----------------------------------------------------------------------------------
---------------------------------------
TRAPPING RAIN WATER
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array
[0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are
being trapped.

int trap(vector<int>& height) {


int a=0;
int b=height.size()-1;
int rmax=0;
int lmax=0;
int trap=0;
while(a<b){
lmax=max(lmax,height[a]);
rmax=max(rmax,height[b]);
if(lmax<rmax){
trap+=lmax-height[a];
a++;
}
else{
trap+=rmax-height[b];
b--;
}
}
return trap;
}

-----------------------------------------------------------------------------------
----------------------------------------------
REMOVE K DIGITS
Given string num representing a non-negative integer num, and an integer k, return
the smallest possible integer after removing k digits from num.

Example 1:

Input: num = "1432219", k = 3


Output: "1219"
Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which
is the smallest.

string removeKdigits(string num, int k) {


stack<char>stk;
for(char c:num){
while(!stk.empty() && k>0 && stk.top()>c){
stk.pop();
k--;
}
stk.push(c);
}
while(!stk.empty() && k>0){
stk.pop();
k--;
}
string result="";
while(!stk.empty()){
result=stk.top()+result;
stk.pop();
}
int i=0;
while(i<result.length() && result[i]=='0'){
i++;
}
if(i==result.length()){
return "0";
}
return result.substr(i);
}
-----------------------------------------------------------------------------------
---------------------------------------------
LARGEST RECTANGLE IN HISTOGRAM
Given an array of integers heights representing the histogram's bar height where
the width of each bar is 1, return the area of the largest rectangle in the
histogram.
Input: heights = [2,1,5,6,2,3]
Output: 10
Explanation: The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.

int largestRectangleArea(vector<int>& heights) {


int n = heights.size();
stack<int> s;
int maxArea = 0;
for (int i = 0; i <= n; ++i) {
while (!s.empty() && (i == n || heights[i] < heights[s.top()])) {
int h = heights[s.top()];
s.pop();
int width = s.empty() ? i : i - s.top() - 1;
maxArea = max(maxArea, h * width);
}
s.push(i);
}
return maxArea;
}

-----------------------------------------------------------------------------------
---------------------------------------------------
SLIDING WINDOW MAXIMUM

You are given an array of integers nums, there is a sliding window of size k which
is moving from the very left of the array to the very right. You can only see the k
numbers in the window. Each time the sliding window moves right by one position.
Return the max sliding window.

Example 1:

Input: nums = [1,3,-1,-3,5,3,6,7], k = 3


Output: [3,3,5,5,6,7]
Explanation:
Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7

vector<int> maxSlidingWindow(vector<int>& nums, int k) {


deque<int>window;
vector<int>vec;
for(int i=0;i<nums.size();++i){
while(!window.empty() && window.front()<=i-k){
window.pop_front();
}
while(!window.empty() && nums[i]>=nums[window.back()]){
window.pop_back();
}
window.push_back(i);
if(i>=k-1){
vec.push_back(nums[window.front()]);
}
}
return vec;
}

-----------------------------------------------------------------------------------
------------------------
The Celebrity Problem
Moderate
80/80
Average time to solve is 30m
Contributed by
189 upvotes
Asked in companies
Problem statement
There are ‘N’ people at a party. Each person has been assigned a unique id between
0 to 'N' - 1(both inclusive). A celebrity is a person who is known to everyone but
does not know anyone at the party.

Given a helper function ‘knows(A, B)’, It will returns "true" if the person having
id ‘A’ know the person having id ‘B’ in the party, "false" otherwise. Your task is
to find out the celebrity at the party. Print the id of the celebrity, if there is
no celebrity at the party then print -1.

Note:
1. The helper function ‘knows’ is already implemented for you.
2. ‘knows(A, B)’ returns "false", if A doesn't know B.
3. You should not implement helper function ‘knows’, or speculate about its
implementation.
4. You should minimize the number of calls to function ‘knows(A, B)’.
5. There are at least 2 people at the party.
6. At most one celebrity will exist.
Detailed explanation ( Input/output format, Notes, Images )
Constraints:
1 <= T <= 50
2 <= N <= 10^4

Where ‘T’ is the total number of test cases, ‘N’ is the number of people at the
party.

Time Limit: 1sec


Sample Input 1:
1
2
Call function ‘knows(0, 1)’ // returns false
Call function ‘knows(1, 0)’ // returns true
Sample Output 1:
0
Explanation For Sample Input 1:
In the first test case, there are 2 people at the party. When we call function
knows(0,1), it returns false. That means the person having id ‘0’ does not know a
person having id ‘1'. Similarly, the person having id ‘1’ knows a person having id
‘0’ as knows(1,0) returns true. Thus a person having id ‘0’ is a celebrity because
he is known to everyone at the party but doesn't know anyone.

int findCelebrity(int n) {
// Write your code here.
int a=0;
for(int i=1;i<n;++i){
if(knows(a,i)){
a=i;

}
}
for (int i = 0; i < n; ++i) {
if (i != a && (knows(a, i) || !knows(i, a))) {
return -1; // Candidate is not a celebrity
}
}
return a;
}

You might also like