Isalfa (X) To Check Whether Character X Is An Alphabet or Not Isdigit (X) To Check Whether Character X Is A Digit or Not
Isalfa (X) To Check Whether Character X Is An Alphabet or Not Isdigit (X) To Check Whether Character X Is A Digit or Not
https://www.geeksforgeeks.org/reversing-a-queue-using-another-queue/?ref=rp
https://www.geeksforgeeks.org/reversing-first-k-elements-queue/?ref=rp
https://www.geeksforgeeks.org/stack-data-structure/
void reverse2(string& str)
{
int i;
int n = str.length();
for (i = 0; i < n / 2; i++)
{
swap(str[i], str[n - i - 1]);
}
}
2) Auxiliary Space : O(1)
void reverse3(string& str)
{
int i,j;
int n = str.length();
for (i = 0,j = n-1 ; i < j; i++,j--)
{
swap(str[i], str[j]);
}
}
1) Time complexity : O(n)
2) Auxiliary Space : O(1)
if (i == n / 2)
return;
swap(str[i], str[n - i - 1]);
reverse4(str, i + 1);
}
Time complexity : O(n)
Auxiliary Space : O(n)
https://www.geeksforgeeks.org/reverse-the-sentence-using-stack/
1) exp = “[()]{}{[()()]()}”
Balanced
2) exp = “[(])”
Not Balanced
Ex1) Algorithm
3) Note :-
In the examples String exp is shown as a String of paranthesis
However actually the String exp is an algebraic expression consisting of paranthesis.
exp[i] = Current Character
// function to check if brackets are balanced // If current
bool areBracketsBalanced(string expr)
{ // Pop one ch
int i;
stack<char> stk; // x = Essent
char x;
// If x match
// Traversing the Expression correspondin
for (i=0;i<expr.length();i++)
{ // Then Fine
// If the current character exp[i] is a opening bracket switch (expr[i]
// Push it into the stack {
if ( expr[i] == '(' || expr[i] == '[' || expr[i] == '{' ) case ')':
{ x = stk
x = expr[i]; stk.pop
// Push the element in the stack if (x =
stk.push(x); ret
continue; break;
}
case '}':
// IF current current character exp[i] is not opening brack x = stk
et, stk.pop
// Then it must be closing. if (x =
// So stack cant be empty at this point. ret
if (stk.empty()) break;
return false;
case ']':
// Driver code x = stk
int main() stk.pop
{ if (x =
string expr = "{()}[]"; ret
break;
// Function call }
if (areBracketsBalanced(expr)) }
cout << "Balanced";
else // Check Empty Sta
cout << "Not Balanced"; return (stk.empty()
return 0; }
}
https://www.techiedelight.com/find-elements-array-greater-than-elements-right/
Ex1) Program 1
Using the Stack DS.
1) For each element x in the given array arr
We pop out all the elements of the stack which are <= x
Then we insert that element x in the stack
3) Trick :-
Going (left right) in an array Going (bottom top) in the Stack.
Hence elements right of x Elements above x in the Stack.
// Function to print all elements x of an arr[]
// s.t all elements present to the right of a is greater than x
void find1(int arr[], int n)
{
stack<int> stk;
cout<<"\nThe elements in an array which is greater than all elements to their right is : ";
// do for each element
for (int i = 0; i < n; i++)
{
// remove all the elements that are less than the current element
while ((!stk.empty()) && (stk.top() < arr[i]))
{
stk.pop();
}
// push current element into the stack
stk.push(arr[i]);
}
// Print all elements in stack one by one
while (!stk.empty())
{
cout << stk.top() << ",";
stk.pop();
}
}
5) Auxillary Space:-O(n)
bcoz a stack is used
void find3(int arr[], int n)
{
int max_so_far = INT_MIN;
cout<<"\nThe elements in an array which is greater than all elements to their right is : ";
// traverse the array from right to left
for (int i = n - 1; i >= 0; i--)
{
// if current element is greater than maximum so far, print it and update max_so_far
if (arr[i] > max_so_far)
{
max_so_far = arr[i];
printf("%d,", arr[i]);
}
}
}
https://www.techiedelight.com/next-greater-element/
Q) Find the next greater element for every array element
Given an integer array, find the next greater element for every array element.
The next greater element of a number x The first greater number to the right of x in the
1) In other words,
for each element A[i] in the array,
find an element A[j] such that j > i and A[j] > A[i]
and the value of j should be as minimum as possible.
2) If the NGE doesn’t exist in the array for any element, consider it -1.
NGE of last element is always -1.
4) After steps 2,3 are complete…..if stack is not empty…That means those elements which are in
have no NGE
5) So pop out all the elements one by one from the stack and print their NGE as -1
1) Time Complexity:- O(n)….Worst case occurs when all elements are sorted in decreasing order
2) Auxillary Complexity :- O(n)….Additional stack is used
1)
1) Time Complexity :- O(n 2 )… Worst case occurs when all element are sorted in decreasing
order
2) Auxillary Space :- O(1)….No extra space is used
https://www.geeksforgeeks.org/stack-set-4-evaluation-postfix-expression/
Ex1) Logic
1) Scan the given expression from leftright and process them as mentioned in Steps 2,3
4) So like this when all the characters in the expression are finished processing
We are left with only one element in the stack
i.e the postfix value of the given expression
int postfix1(string exp)
{
stack<int> stk;
int i;
for(i=0;i<exp.length();i++)
{
// If current_character is an operand
// Then push it into the stack
if( (exp[i]>='0') && (exp[i]<='9'))
{
stk.push(exp[i]-'0');
}
// If current_character is an operator
// pop out 2 elements from the stack (say x,y)
// Compute the 2 popped out elements using the current_character_operator
// Then Push the result back into the stack
else
{
int x = stk.top();
stk.pop();
int y = stk.top();
stk.pop();
if(exp[i]=='+')
stk.push(y+x);
if(exp[i]=='-')
stk.push(y-x);
if(exp[i]=='*')
stk.push(y*x);
if(exp[i]=='/')
stk.push(y/x);
}
}
// At this point the stack is left with only one element
// i.e the postfix value of the given expression
return stk.top();
}
// Driver code
int main()
{
string exp1 = "231*+9-";
int answer1 = postfix1(exp1);
cout<<"The Postfix Form = "<<exp1<<endl;
cout<<"The Postfix value = "<<answer1<<endl;
}
Output :-
The Postfix Form = 231*+9-
The Postfix value = -4
1) Prefix expression = + - 9 2 7 * 8 / 4 12
Scan the prefix expression from R L
4 12,4
stk.push(4);
/ 3
int x = stk.pop() x = 4
int y = stk.pop() y = 12
y / x = 3
stk.push(y/x) = stk.push(3)
8 3,8
stk.push(8);
* 24
int x = stk.pop() x = 8
int y = stk.pop() y = 3
y * x = 24
stk.push(y*x) = stk.push(24)
7 24,7
stk.push(7);
2 24,7,2
stk.push(2);
- 24,5
int x = stk.pop() x = 2
int y = stk.pop() y = 7
y - x = 5
stk.push(y-x) = stk.push(5)
+ 29
int x = stk.pop() x = 5
int y = stk.pop() y = 24
y + x = 29
stk.push(y+x) = stk.push(29)
Final Answer 29
1) Postfix expression = 9 3 4 * 8 + 4 / –
Scan the postfix expression from L R.
3 9,3
stk.push(3);
4 9,3,4
stk.push(4);
* 9,12
int x = stk.pop() x = 4
int y = stk.pop() y = 3
y * x = 12
stk.push(y*x) = stk.push(12)
8 9,12,8
stk.push(8);
+ 9,20
int x = stk.pop() x = 8
int y = stk.pop() y = 12
y + x = 20
stk.push(y+x) = stk.push(20)
4 9,20,4
stk.push(4);
/ 9,5
int x = stk.pop() x = 4
int y = stk.pop() y = 20
y / x = 5
stk.push(y-x) = stk.push(5)
- 4
int x = stk.pop() x = 5
int y = stk.pop() y = 9
y - x = 4
stk.push(y-x) = stk.push(4)
Final Answer 4
Note :-
1 <= No. of elements in Operand Stack <= 3.
The maximum no. of elements present at any time of operand stack = 3.
https://www.techiedelight.com/merging-overlapping-intervals/
Ex1) Process
1) The idea is to sort the intervals in increasing order of their starting time.
Then create an empty stack
4) At the end
Stack is left with non-overlapping intervals
Simply print them
#include <iostream> // Function to Merge Non Ov
#include <stack> void mergeIntervals(vector<I
#include <vector> {
#include <algorithm> // Sort Intervals in in
using namespace std; ime.
sort(intervals.begin(),
struct Interval stack<Interval> stk;
{
int start,end; // Do it for each Inter
}; for(const Interval &curr
{
// Sort Intervals based on their starting time in asc order // If Stack is emp
bool sortByStartingTime(const Interval &a, const Interval &b) // Then insert cur
{ if( stk.empty() )
return (a.start < b.start); stk.push(curr);
}
Interval top = stk.t
int main()
{ // If the 2 Interv
vector<Interval> intervals = { { 1, 5 }, { 2, 3 }, { 4, 6 }, // Then insert cur
{ 7, 8 }, { 8, 10 }, {12, 15} if(curr.start > stk.
}; stk.push(curr);
mergeIntervals(intervals); // If the 2 Interv
// AND curr.end >
return 0; // Then top.end =
} if(curr.end > stk.to
stk.top().end =
Output :-
The Non-Overlapping Intervals are =
}
{12,15}
{7,10} // After completing the
{1,6} // The Stack stk contai
// Hence now just print
cout<<"\nThe Non-Overlap
while(!stk.empty())
{
Interval x = stk.top
stk.pop();
printf("\n{%d,%d}",
}
}
Ex1) Idea
2) How to do it
Pop all items from the stack stk one by one and hold them in the call stack.
Then as the recursion unfolds Then insert each of those popped values from Call Stack
i.e Sorted Insert each of those popped values from Call Stack back into the Input Stack.
#include <iostream> // Insert the given key into the sorted
#include <stack> while maintaining its sorted order.
#include <vector>
using namespace std; // This is similar to the recursive ins
void sortedInsert(stack<int> &stk, int k
{
int main() // Insert the key into the stack.
{ // Only if it satisfies this Base
vector<int> list = { 5, -2, 9, -7, 3 }; if( (stk.empty()) || (key > stk.top(
{
stack<int> stk; stk.push(key);
for (int x : list) { return;
stk.push(x); }
}
// Pop all items from the stack
cout<<"\n\nStack stk before sorting : "; and hold them in the call stack
printStack(stk); int x = stk.top();
stk.pop();
// Sorting the Stack stk. sortedInsert(stk, key);
sortStack(stk);
// After the recursion unfolds
cout <<"\n\nStack stk after sorting: "; // Then push each item into stk fr
printStack(stk); stk.push(x);
}
return 0;
} void sortStack(stack<int> &stk)
{
Output :- if(stk.empty())
Stack stk before sorting : return;
3
-7 int x = stk.top();
9 stk.pop();
-2 sortStack(stk);
5
// After the recursion unfolds
// Then sortedInsert each item x
Stack stk after sorting: into stk from the call stack
9 sortedInsert(stk, x);
5
3
-2
// Print the contents of the Stack stk.
-7
void printStack(stack<int> stk)
{
while (!stk.empty())
{
int x = stk.top();
stk.pop();
printf("\n%d",x);
}
cout << endl;
}
https://www.geeksforgeeks.org/stack-set-2-infix-to-postfix/?ref=rp
https://www.geeksforgeeks.org/convert-infix-prefix-notation/?ref=rp
https://www.geeksforgeeks.org/infix-to-prefix-conversion-using-two-stacks/?ref=rp
Procedure:-
7) Perform Steps 2-6 till the entire infix expression has been scanned
8) Now after step 7….There is some content in the output….and some content in the Stack
Now pop out elements one by one from the Stack until the Stack is empty
And keep on adding the popped elements of the Stack to the output
9) Hence Finally
The Stack is empty
Output contains the Postfix Expression
Procedure:-
1) Suppose infix_expression = A+B*C
Formula :-
1) prefix_expression = reverse( infix_to_postfix(reversed_infix_expression) )
https://www.techiedelight.com/implement-a-queue-using-stack-data-structure/
https://www.geeksforgeeks.org/reversing-first-k-elements-queue/
Q) Reverse the first k elements of the queue
Q) Reversing String in C++(Using Stacks,loops)
Q) Some Basics
1) A Stack is a Linear DS
Which follows LIFO priciple (Last in First Out)(Last element inserted is the first element r
Or the FILO principle (First in Last Out) (First element inserted is the last element remove
2) In computers memory :-
Stack implemented by Queue/Linked Lists.
Auxillary Space taken by Stack = O(n).
1) Unlike Linked Lists,1D arrays and other linear data structures which are traversed in linear ord
Process :-
3) After Step 2….stack 2 will contain elements from bottom to top in reverse post_order
4) So now just pop elements from stack 2 and print them…i.e print contents of stack 2 from top to
bottom
Q) What is a Queue
3) Note :-
The process of inserting an element x in the queue = enqueue(x).
The process of deleting an element from the queue = dequeue
1) If front = rear = -1
Then LinearQ is empty
2) If front = rear
If both front,rear point to the same location.
Then the LinearQ has only 1 element.
3) If rear = max_size – 1
Then LinearQ is full
public:
// Constructor to initialize the Q
LinearQ(int s)
{
front = rear = -1;
max_size = s;
arr = new int[s];
curr_size = 0;
}
// Destructor to de-allocate(free)memory allocated to circularQ
~LinearQ()
{
delete[] arr;
}
bool isFull();
bool isEmpty();
int count();
int get_front();
void insert(int x);
void deletion();
void display();
};
Ex3)