Skip to content

Commit

Permalink
Solutions for 2 questions on leetcode
Browse files Browse the repository at this point in the history
The Questions are :
1st -> Largest Rectangle in Histogram
https://leetcode.com/problems/largest-rectangle-in-histogram/

2nd -> Valid Parenthesis
https://leetcode.com/problems/valid-parentheses/
  • Loading branch information
Saarcasmic authored Oct 4, 2022
1 parent 44855cf commit 20d227f
Show file tree
Hide file tree
Showing 2 changed files with 104 additions and 0 deletions.
62 changes: 62 additions & 0 deletions LeetCode Solutions/LargestRectangleInHistogram.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
class Solution {
private:
vector<int> nextSmallerElement(vector<int> arr, int n) {
stack<int> s;
s.push(-1);
vector<int> ans(n);

for(int i=n-1; i>=0 ; i--) {
int curr = arr[i];
while(s.top() != -1 && arr[s.top()] >= curr)
{
s.pop();
}
//ans is stack ka top
ans[i] = s.top();
s.push(i);
}
return ans;
}

vector<int> prevSmallerElement(vector<int> arr, int n) {
stack<int> s;
s.push(-1);
vector<int> ans(n);

for(int i=0; i<n; i++) {
int curr = arr[i];
while(s.top() != -1 && arr[s.top()] >= curr)
{
s.pop();
}
//ans is stack ka top
ans[i] = s.top();
s.push(i);
}
return ans;
}

public:
int largestRectangleArea(vector<int>& heights) {
int n= heights.size();

vector<int> next(n);
next = nextSmallerElement(heights, n);

vector<int> prev(n);
prev = prevSmallerElement(heights, n);

int area = INT_MIN;
for(int i=0; i<n; i++) {
int l = heights[i];

if(next[i] == -1) {
next[i] = n;
}
int b = next[i] - prev[i] - 1;
int newArea = l*b;
area = max(area, newArea);
}
return area;
}
};
42 changes: 42 additions & 0 deletions LeetCode Solutions/ValidParenthesis.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
class Solution {
public:
bool isValid(string expression) {
stack<char> s;
for(int i=0; i<expression.length(); i++) {

char ch = expression[i];

//if opening bracket, stack push
//if close bracket, stacktop check and pop

if(ch == '(' || ch == '{' || ch == '['){
s.push(ch);
}
else
{
//for closing bracket
if(!s.empty()) {
char top = s.top();
if( (ch == ')' && top == '(') ||
( ch == '}' && top == '{') ||
(ch == ']' && top == '[') ) {
s.pop();
}
else
{
return false;
}
}
else
{
return false;
}
}
}

if(s.empty())
return true;
else
return false;
}
};

0 comments on commit 20d227f

Please sign in to comment.