Skip to content

Commit

Permalink
Merge pull request #31 from aviraltandon21/master
Browse files Browse the repository at this point in the history
Peak element in array
  • Loading branch information
keshavagarwal17 authored Oct 1, 2021
2 parents 51482db + 900a800 commit 87e849e
Show file tree
Hide file tree
Showing 2 changed files with 112 additions and 0 deletions.
70 changes: 70 additions & 0 deletions Parenthesis-Checker.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
#include<bits/stdc++.h>
#include <iostream>

using namespace std;

// Given an expression string x. Examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp.
// For example, the function should return 'true' for exp = “[()]{}{[()()]()}” and 'false' for exp = “[(])”.
bool ispar(string expr)
{

stack<char> s;
char x;

for (int i = 0; i < expr.length(); i++)
{
if (expr[i] == '(' || expr[i] == '['
|| expr[i] == '{')
{
s.push(expr[i]);
continue;
}

if (s.empty())
return false;

switch (expr[i]) {
case ')':

x = s.top();
s.pop();
if (x == '{' || x == '[')
return false;
break;

case '}':

x = s.top();
s.pop();
if (x == '(' || x == '[')
return false;
break;

case ']':
x = s.top();
s.pop();
if (x == '(' || x == '{')
return false;
break;
}
}


return (s.empty());

}



int main()
{
string s;
cin>>s;

if(ispar(s))
cout<<"Balanced"<<endl;
else
cout<<"Not Balanced"<<endl;

return 0;
}
42 changes: 42 additions & 0 deletions Peak_element.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#include<bits/stdc++.h>
#include <iostream>

using namespace std;

// A peak element in an array is the one that is not smaller than its neighbours.
// Given an array arr[] of size N, find the index of any one of its peak elements.

int findPeakUtil(int arr[], int low, int high, int n)
{
int mid = low + (high - low) / 2;

if ((mid == 0 || arr[mid - 1] <= arr[mid]) && (mid == n - 1 || arr[mid + 1] <= arr[mid]))
return mid;

else if (mid > 0 && arr[mid - 1] > arr[mid])
return findPeakUtil(arr, low, (mid - 1), n);

else
return findPeakUtil(arr, (mid + 1), high, n);
}


int peakElement(int arr[], int n)
{
return findPeakUtil(arr, 0, n - 1, n);

}


int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];

cout<<peakElement(arr,n);

return 0;
}

0 comments on commit 87e849e

Please sign in to comment.