text:
#include<bits/stdc++.h>
#include<math.h>
#include<string.h>
#include<cstring>
#include<string>
#include<vector>
#include<stdlib.h>
#include <ext/pb_ds/exception.hpp>
#include <ext/pb_ds/detail/type_utils.hpp>
#include <ext/pb_ds/detail/hash_fn/mask_based_range_hashing.hpp>
#include <ext/pb_ds/detail/hash_fn/mod_based_range_hashing.hpp>
#include <ext/pb_ds/tree_policy.hpp> // Including tree_order_statistics_node_update
#define MOD 1000000007
#define INF 1e18
#define ff first
#define ss second
#define PI 3.141592653589793238462
#define set_bits __builtin_popcountll
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define small 0
#define MAXSIZE 100000
const int N = 200005;
#define endl "\n"
using namespace std;
using namespace __gnu_pbds;
#define debug(x) cout << #x << " " << x << endl;
#define debug1(x) cout << #x << " " << x << " ";
#define debug2(x) cout<<"["<<#x<<" = "<<x<<"]\n";
typedef long long int ll;
typedef long double lld;
#define timeset ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL)
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);

/*#define debug(x);
printf(x);*/

void init()
{
#ifndef ONLINE_JUDGE
freopen("input1.txt" , "r"  ,stdin);
freopen("output1.txt" , "w" ,stdout);
#endif
}

// typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; // find_by_order, order_of_key

const int MAXN = (int)((1e8) + 100);
ll expo(ll a, ll b, ll mod) {ll res = 1; while (b > 0) {if (b & 1)res = (res * a) % mod; a = (a * a) % mod; b = b >> 1;} return res;}
int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a);}
int max(int a, int b) {if (a > b) return a; else return b;}
int min(int a, int b) {if (a < b) return a; else return b;}
vector<ll> sieve(int n) {int*arr = new int[n + 1](); vector<ll> vect; for (int i = 2; i <= n; i++)if (arr[i] == 0) {vect.push_back(i); for (int j = 2 * i; j <= n; j += i)arr[j] = 1;} return vect;}

void precision(int a)
{
cout << setprecision(a) << fixed;
}

// {
//  reference
//  cout << "0th element: " << *A.find_by_order(0) << endl;
//  cout << "No. of elems smaller than 6: " << A.order_of_key(6) << endl; // 2
//  cout << "Lower Bound of 6: " << *A.lower_bound(6) << endl;
//  cout << "Upper Bound of 6: " << *A.upper_bound(6) << endl;
// }

//** pritishcf307 **//
//**------------------------------------------------------------------------------------------------------**//
ll index=0;
ll valod=0;
vector<ll> construct(vector<ll> v1,vector<ll> v2){
 ll n1=sz(v1);
 ll n2=sz(v2);
vector<ll> dp(n2+1),helper(n2+1);
 for(ll i=1;i<=n1;i++){
  ll current=0;
  for(ll j=1;j<=n2;j++){
    if(v1[i]==v2[j]){
      dp[j]=dp[current]+1;
      helper[j]=current;
    }
   else if(v2[j]<v1[i] && dp[j]>dp[current]){
        current=j;
    }
  }
 }
 ll val2=0;
 for(ll i=1;i<=n2;i++){
  if(dp[i] > dp[val2]){
    val2=i;
    index=i;
  }
 }
 valod=dp[val2];
 vector<ll> ans;
 while(val2){
  ans.push_back(v2[val2]);
  val2=helper[val2];
 }
 return ans;
}
vector<ll> lcs(vector<ll> v1,vector<ll> v2){
  vector<ll> helper;
  ll n1=sz(v1);
  ll n2=sz(v2);
  ll dp[n1][n2];
  for(ll i=0;i<n1;i++){
    for(ll j=0;j<n2;j++){
      if(i==0 || j==0){
        dp[i][j]=0;
      }
    }
  }
  for(ll i=1;i<n1;i++){
    for(ll j=1;j<n2;j++){
      if(v1[i-1]==v2[j-1]){
        dp[i][j]=dp[i-1][j-1]+1;
      }
      else{
        dp[i][j]=max((dp[i-1][j]),dp[i][j-1]);
      }
    }
  }

  ll p1=n1;
  ll p2=n2;
  while(p1 > 0 && p2 > 0){
    if(v1[p1-1]==v2[p2-1]){
      helper.push_back(v1[p1-1]);
      p1--;
      p2--;
    }
    else{
      if(dp[p1-1][p2] > dp[p1][p2-1]){
        p1--;
      }
      else{
        p2--;
      }
    }
  }
  reverse(all(helper));
  return helper;
}
vector<ll> lis(vector<ll> v){
  set<ll> s;
  for(auto i:v){
    s.insert(i);
  }
  vector<ll> helper;
  for(auto i:s){
    helper.push_back(i);
  }
  vector<ll> helper1=lcs(v,helper);
  return helper1;
}
vector<ll> common(vector<ll> v1,vector<ll> v2){
  vector<ll> helperl;
  set<ll> s1;
  for(auto i:v1){
    s1.insert(i);
  }
  for(auto i:v2){
    if(s1.count(i)){
      helperl.push_back(i);
    }
  }
  return helperl;
}
void solve(){
  ll n1;
  cin >> n1;
  vector<ll> v1(n1+1);
  for(ll i=0;i<n1;i++){
    cin >> v1[i+1];
  }
  ll n2;
  cin >> n2;
  vector<ll> v2(n2+1);
  for(ll i=0;i<n2;i++){
    cin >> v2[i+1];
  }
  vector<ll> ans3=construct(v1,v2);
  if(ans3.size() > 0){
    ll val1=*max_element(all(ans3));
  }
  vector<ll> ans1=common(v1,v2);
  vector<ll> ans2=common(v2,v1);
  vector<ll> ans4=lis(ans1);
  vector<ll> ans5=lis(ans2);
  cout << valod << endl;
  reverse(all(ans3));
  for(auto i:ans3){
    cout << i << " ";
  }
}

int main(){
init();
IOS;
ll t=1;
// cin >> t;
while(t--){
solve();
}
return 0;
}


text:
#include<bits/stdc++.h>
using namespace std;
#define deb(x) cout<<#x<<'='<<x<<endl;
#define fastio() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define ll long long
int binary_expo(int a,int b);
int dp[1001][1001];
int mod=1e9+7;
void solve()
{
    int n;
    cin>>n;
    string s[n+1];
    for(int i=0;i<n;i++)
    {
      cin>>s[i];
    }

     dp[0][0]=1;
    for(int i=0;i<n;i++)
    {
      for(int j=0;j<n;j++)
      {
         if(i) dp[i][j]+=dp[i-1][j];
         if(j) dp[i][j]+=dp[i][j-1];
         if(s[i][j]=='*')
         {
           dp[i][j]=0;
         }
         dp[i][j]=dp[i][j]%mod;

      }
    }
    cout<<dp[n-1][n-1]<<endl;

}

int main()
{

fastio();
/* #ifndef ONLINE_JUDGE
freopen(     ,  ,stdin);
freopen(     ,   ,stdout);
#endif */

solve();
return 0;

}

 int binary_expo(int a,int b)
{
     int result=1;
   while(b>0){
     if(b%2!=0){   result=result*a;  }
        a=a*a;
         b=b/2;
          }
return result;
}

file_name: Merge Sorted Array.cpp

mime_type: text/x-c++


text:
class Solution {
public:
    vector<vector<int>> generate(int numRows)
    {
        vector<vector<int>> triangle(numRows);
        triangle[0].push_back(1);

        for(int i=1; i< numRows; i++){
            triangle[i].push_back(1);
            for( int j = 1; j < i; j++){
                triangle[i].push_back(triangle[i-1][j-1]+triangle[i-1][j]);
            }
            triangle[i].push_back(1);
        }
        return triangle;
    }
};


text:
#include <bits/stdc++.h>

using namespace std;

int maximumProfit(vector<int> &Arr){

	int maxProfit = 0;
	int mini = Arr[0];

	for(int i=1;i<Arr.size();i++){
        int curProfit = Arr[i] - mini;
        maxProfit = max(maxProfit,curProfit);
        mini = min(mini,Arr[i]);
        }
	return maxProfit;
}
//Time complexity - O(n)
//Space complexity- O(1)
int main() {
  int n;
  cin>>n;
  int a;
  vector<int>v;
 for(int i=0;i<n;i++){
    cin>>a;
    v.push_back(a);
 }
  cout<<"The maximum profit by selling the stock is "<<maximumProfit(v);
}


text:
#include <iostream>
using namespace std;

int main()
{
    int n,sum;

    cin>>n>>sum;
    int arr[n];
    bool t[n+1][sum+1];
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    for (int i=0;i<n+1;i++)
    {
        for(int j=0;j<sum+1;j++)
        {
            if(i==0)
            t[i][j]=false;
            if(j==0)
            t[i][j]=true;
        }
    }
    for (int i=1;i<n+1;i++)
    {
        for(int j=1;j<sum+1;j++)
        {
            if(arr[i-1]<=j)
            t[i][j]=t[i-1][j-arr[i-1]]||t[i-1][j];
            else
            t[i][j]=t[i-1][j];
        }
    }
    if(t[n][sum])
     cout<<"yes";
     else
     cout<<"no";
}


text:
#include <iostream>
#include <limits.h>

using namespace std;

void matrix_chain_order(int* order, int **min_scalar_mults, int **optimal_split_pos, int n)
{
    for (int i = 1; i <= n; i++)
    {
        min_scalar_mults[i][i] = 0;
    }

    for (int length = 2; length <= n; length++)
    {
        int i, j;
        for (i = 1; i <= (n - length + 1); i++)
        {
            j = (i + length - 1);
            min_scalar_mults[i][j] = INT_MAX;
            int k, scalar_mults;
            for (k = i; k < j; k++)
            {
                scalar_mults = min_scalar_mults[i][k] + min_scalar_mults[k + 1][j] + (order[i-1] * order[k] * order[j]);
                if (scalar_mults < min_scalar_mults[i][j])
                {
                    min_scalar_mults[i][j] = scalar_mults;
                    optimal_split_pos[i][j] = k;
                }
            }
        }
    }
}

void print_optimal_parens(int** optimal_split_pos, int start, int end)
{
    if (start == end)
        cout << "A" << start << " ";

    else {
        cout << "(";
        print_optimal_parens(optimal_split_pos, start, optimal_split_pos[start][end]);
        print_optimal_parens(optimal_split_pos, optimal_split_pos[start][end] + 1, end);
        cout << ")";
    }
}

int main()
{
    int n;
    cout << "Enter the number of matrices in the chain: <A, B, C, ..., > ";
    cin >> n;

    // matrices are A1, A2, A3 ..., An

    int* order = new int[n + 1];
    cout << "Enter the order of matrices: <p0, p1, ... ,pn> ";
    for (int i = 0; i <= n; i++)
    {
        cin >> order[i];
    }

    // A1(p0 x p1), A2(p1 x p2), ..., An(p(n-1) x pn)

    // min_scalar_mults[i][j] stores minimum number of scalar multiplications required to multiply matrices Ai to Aj
    int** min_scalar_mults = new int*[n+1];
    for (int i=0; i<=n; i++) {
        *(min_scalar_mults + i) = new int[n+1];
    }

    // optimal_split_pos[i][j] stores optimal splitting position required to multiply matrices Ai to Aj
    int** optimal_split_pos = new int*[n+1];
    for (int i=0; i<=n; i++) {
        *(optimal_split_pos + i) = new int[n+1];
    }

    matrix_chain_order(order, min_scalar_mults, optimal_split_pos, n);

    cout << "\nThe minimum number of scalar multiplications required to multiply the matrices are: " << min_scalar_mults[1][n];

    cout << "\nThe optimal way to multiply the matrices is: ";

    print_optimal_parens(optimal_split_pos, 1, n);

    return 0;
}


text:
import React, { useState } from "react";

const App = () => {
  const [bmi, setBmi] = useState();
  const [info, setInfo] = useState();
  const [height, setHeight] = useState();
  const [weight, setWeight] = useState();
  const handleBmi = () => {
    let val = (
      [Number(weight) / Number(height) / Number(height)] * 10000
    ).toFixed(1);
    setBmi(val);
    if (val < 18.5) {
      setInfo("Under Weight");
    } else if (val > 18.5 && val <= 24.9) {
      setInfo("Healthy");
    } else if (val > 24.9 && val < 30) {
      setInfo("Overweight");
    } else {
      setInfo("Obese");
    }
  };
  return (

BMI Calculator

      <input
        type="text"
        onChange={(e) => setHeight(e.target.value)}
        placeholder="height in cm"
      />
      <input
        type="text"
        onChange={(e) => setWeight(e.target.value)}
        placeholder="Weight in kg"
      />
      <button onClick={handleBmi}>Calculate</button>

{bmi}

{info}

  );
};

export default App;


text:
// function to check palindrome
function checkPalindrome(str) {

    // applying split, revere and join
    const reversedString = str.split('').reverse().join('');
    if(str === reversedString)
          return true;
    else
          return false;
}


text:
 Calculate Age from Date of Birth

 Enter Date of Birth: <input type=date id = DOB>

<button type="submit" onclick = "ageCalculator()"> Calculate age </button>


text:
const { default: ms } = require('ms-prettify');

/**
 *
 * @param {String} time time for which timer have to wait
 * @param {*} callback
 * @param  {...any} args
 * @returns
 */
function timer(time, callback, ...args) {
    return new Promise((resolve, reject) => {
        time = ms(time);

        if (typeof (time) !== 'number' || time < 1) return reject("Invalid Time Was provided");

        setTimeout(() => {
            if (typeof callback === "function") callback(...args);

            resolve(true)
        }, time);
    })
}

timer("10s", () => console.timeEnd("1"));

timer("10 hours", (x) => console.log("Why are you still " + x), "here?");


text:
#include<bits/stdc++.h>
using namespace std;
int main(){
  int t;
  cin>>t;
  while(t--){
    long long n;
    cin>>n;
    if(n&(n-1)){
      cout<<"YES"<<endl;
    }
    else{
      cout<<"NO"<<endl;
    }
  }
}


text:
/******
  Trailing zeroes in factorial
  For an integer N find the number of trailing zeroes in N!.

  Example 1:

  Input:
  N = 6
  Output:
  0
  Explanation:
  5! = 120 so the number of trailing zero is 1.
  Example 2:

  Input:
  N = 5
  Output:
  2
  Explanation:
  4! = 24 so the number of trailing zero is 0.
  Your Task:
  You don't need to read input or print anything. Your task is to complete the function trailingZeroes() which take an integer N as an input parameter and returns the count of trailing zeroes in the N!.

  Expected Time Complexity: O(logN)
  Expected Auxiliary Space: O(1)

  Constraints:
  1 <= N <= 109
****/
//User function Template for C++

// Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// Driver Code Ends

class Solution
{
public:
    int trailingZeroes(int N)
    {
        // Write Your Code here
        int m=0;
        while(N>0){
        m= m+N/5;
        N=N/5;}
        return m;
    }

    int trailingZeroes2(int N)
    {
        // Write Your Code here
        int ans = 0;
        while(N/5)
        {
            ans+=N/5;
            N/=5;
        }
        return ans;
    }
};

// Driver Code Starts.
int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        int N;
        cin >> N;
        Solution ob;
        int ans  = ob.trailingZeroes(N);
        cout<<ans<<endl;
    }
    return 0;
}
//Driver Code Starts.


text:
#include<bits/stdc++.h>
using namespace std;

typedef long long int ll;

//lcm(a,b)=a*b/hcf(a,b)

// Method to calculate HCF of two numbers
ll hcf(ll a, ll b)
{
    if(b==0)
        return a;
    return hcf(b,a%b);
}
//Method to calculate LCM of numbers from array
ll lcm(ll arr[],int n)
{
    ll ans=arr[0];
    for(int i=1;i<n;i++)
    {
        ans=((arr[i]*ans)/(hcf(arr[i],ans)));
    }
    return ans;
}

int main()
{
    ll arr[]={21223232323,72322323,3,1239,4};
    cout<<lcm(arr,5)<<endl;
    cout<<hcf(12,24);

}


text:
public class fib {
    public static void main(String[] args) {
        int n = 10;
        for(int i = 1; i <= n; i++){
            System.out.println(fibonacci(i) + " ");
        }

    }
    public static int fibonacci(int n){
        if (n <= 1)
            return n;
        return fibonacci(n-1) + fibonacci(n-2);
    }
}


text:
/**
4. Number of paths
The problem is to count all the possible paths from top left to bottom right of a MxN matrix with the constraints that from each cell you can either move to right or down.

Example 1:

Input:
M = 3 and N = 3
Output: 6
Explanation:
Let the given input 3*3 matrix is filled
as such:
A B C
D E F
G H I
The possible paths which exists to reach
'I' from 'A' following above conditions
are as follows:ABCFI, ABEHI, ADGHI, ADEFI,
ADEHI, ABEFI

Example 2:

Input:
M = 2 and N = 8
Output: 8

Your Task:
You don't need to read input or print anything. Your task is to complete the function numberOfPaths() which takes the integer M and integer N as input parameters and returns the number of paths..

Expected Time Complexity: O(m + n - 1))
Expected Auxiliary Space: O(1)

Constraints:
1 ≤ M, N ≤ 10
**/
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;

 // } Driver Code Ends
long long  numberOfPaths(int m, int n)
{
    // Code Here
    if (m == 1 || n == 1)
        return 1;

    return numberOfPaths(m - 1, n) + numberOfPaths(m, n - 1);
}
// { Driver Code Starts.

int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		int n,m;
		cin>>m>>n;
	    cout << numberOfPaths(m, n)<<endl;
	}
    return 0;
}  // } Driver Code Ends


text:
#include <iostream>
#include <cmath>
#define G 6371000
#define PI 3.14159265
using namespace std;

enum{altitude = 0, latitude, longitude};

double Haversine(double *p1, double *p2){
    double D;
    //convert latitude and longitude info in degree to radian
    p1[latitude] = p1[latitude]*PI/180;
    p1[longitude] = p1[longitude]*PI/180;
    p2[latitude] = p2[latitude]*PI/180;
    p2[longitude] = p2[longitude]*PI/180;

    //haversine formula to find shortest plane distance between 2 places
    D = G * acos((sin(p1[latitude])*sin(p2[latitude]))+(cos(p1[latitude])*cos(p2[latitude])*cos(p1[longitude]-p2[longitude])));
    D = abs(D);

    return D;
}

//get height difference between 2 position
double Get_heightdistance(double *p1, double *p2){
    double H;
    H = abs(p1[altitude] - p2[altitude]);

    return H;
}

//get distance using basic pythagoras theorem
//   |\
//   | \
//  H|  \ d(distance)
//   |   \
//   |____\
//      D(haversine)
double Get_distance(double *p1, double *p2){
    double distance, D, H;

    D = Haversine(p1, p2);
    H = Get_heightdistance(p1, p2);
    distance = sqrt(pow(D, 2)+pow(H, 2));

    return distance;
}

int main(){
    double *ptr1, *ptr2;
    double p1[3], p2[3];
    ptr1 = p1;
    ptr2 = p2;

    cout << "p1 [alt(meter); lat; long]: ";
    cin >> p1[altitude] >> p1[latitude] >> p1[longitude];
    cout << "p2 [alt(meter); lat; long]: ";
    cin >> p2[altitude] >> p2[latitude] >> p2[longitude];

    double distance;
    distance = Get_distance(ptr1, ptr2);

    cout << "\nDistance: " << distance << " m"<< endl;

    return 0;
}


text:
#include<iostream>
using namespace std;
int main ()
{
    int num , fact = 1;
    cin>>num;

    // Factorial of negative number doesn't exist
    // Read more here - https://www.quora.com/Is-the-factorial-of-a-negative-number-possible
    if(num < 0)
        cout << "Not Possible";
    else
    {
        for(int i = 1; i <= num; i++)
            fact = fact * i;
    }

    cout << "Fact " << num << ": " << fact;
}
// Time complexity: O(N)
// Space complexity: O(1)


text:
// generate all different strings that can be created using its characters.

#ifndef ONLINE_JUDGE
#include "debug.hpp"
#else
#define debug(...)
#endif
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ve vector<int>
#define vell vector<ll>
#define vpp vector<pair<int, int>>
#define ump unordered_map<int, int>
#define rep1(i, a, b) for (int i = a; i < (b); i++)
#define rep(i, n) for (int i = 0; i < (n); i++)
#define FORd(i, a, b) for (int i = (b)-1; i >= a; i--)
#define F0Rd(i, n) for (int i = (n)-1; i >= 0; i--)
#define trav(a, x) for (auto &a : x)
#define asort(a) sort(a, a + n)
#define all(x) (x).begin(), (x).end()
#define uniq(v) v.erase(unique(all(v)), (v).end())
#define vmax(v) *max_element(v.begin(), v.end());
#define vmin(v) *min_element(v.begin(), v.end());
const ll INF = 1e18 + 10;
const int mod = 1e9 + 7; // 998244353;

set<string> perms;

void permutations(string prefix, string suffix)
{
    if (suffix.length() == 0)
    {
        perms.insert(prefix);
        return;
    }
    for (int i = 0; i < suffix.length(); i++)
    {
        permutations(prefix + suffix[i], suffix.substr(0, i) + suffix.substr(i + 1));
    }
}

int main()
{

    (ios_base::sync_with_stdio(false), cin.tie(NULL));
    string s;
    cin >> s;
    permutations("", s);
    cout << perms.size() << endl;
    for (auto ele : perms)
    {
        cout << ele << endl;
    }
    return 0;
}


text:
#include <iostream>
using namespace std;

/*
    Program to find nth Catalan number
    Constraints 1<=n<=19

*/
long catalan(int n)
{
    long ar[n + 1];

    ar[0] = 1;
    ar[1] = 1;

    for (int i = 2; i <= n; i++) {
        ar[i] = 0;
        for (int j = 0; j < i; j++)
            ar[i] += ar[j] * ar[i - j - 1];
    }

    return ar[n];
}

int main()
{
    int n;
    cout<<"Enter the number ";
    cin>>n;
    cout<<"\n"<<n<<"th Catalan number is:"<<catalan(n)<<"\n";
    return 0;
}


text:
/**
3.Final Destination
Consider a 2d plane and a Robot which is located at (0,0) who can move only one unit step at a time in any direction i.e. if its initial position is (x,y), he can go to positions (x + 1, y), (x - 1, y), (x, y + 1) or (x, y - 1). Now Given three integers a,b (denoting the final position where the robot has to reach), and x. Find out if the Robot can reach the final position in exactly x steps.

Example 1:

Input:
a = 5, b = 5, x = 11
Output:
0
Explanation:
No matter how the Robot moves,
the Robot won't be able to reach
point (5,5) in exactly 11 moves.
Example 2:

Input:
a = 10, b = 15, x = 25
Output:
1
Explanation:
The Robot can move 10 times towards
positive x-axis and then 15 times
towards positive y-axis to reach (10,15).

Your Task:
You don't need to read input or print anything. Your task is to complete the function canReach() which takes 3 Integers a,b and x as input and returns the answer.

Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)

Constraints:
-109 <= a,b <= 109
1 <= x <= 2*109

**/

// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;

 // } Driver Code Ends
class Solution {
  public:
    int canReach(long long a, long long b, long long x) {
        // code here
        a= abs(a);
        b= abs(b);
        long long c= a+b;

        if(a==0 && b==0 && x%2!=0){ return 0;}
        if(c>x){ return 0;}
        if(c==x){ return 1;}
        if(c<x){ return (((x-c)%2)?0:1);}
        }
    };

// { Driver Code Starts.
int main() {
    int t;
    cin >> t;
    while (t--) {
        long long a,b,x;

        cin>>a>>b>>x;

        Solution ob;
        cout << ob.canReach(a,b,x) << endl;
    }
    return 0;
}  // } Driver Code Ends


text:
// C++ program for Lucky Numbers

#include <bits/stdc++.h>
using namespace std;

/* Returns 1 if n is a lucky no.
otherwise returns 0*/
bool isLucky(int n)
{
    static int counter = 2;

    if (counter > n)
        return 1;
    if (n % counter == 0)
        return 0;

    /*calculate next position of input no.
      Variable "next_position" is just for
    readability of the program we can
    remove it and update in "n" only */
    int next_position = n - (n / counter);

    counter++;
    return isLucky(next_position);
}

// Driver Code
int main()
{
    int x = 5;

    // Function call
    if (isLucky(x))
        cout << x << " is a lucky no.";
    else
        cout << x << " is not a lucky no.";
}


text:
#include<bits/stdc++.h>
using namespace std;

int sum(int n){
    if(n==1){
        return 1;
    }
    if(n==2){
        return 2;
    }
    else{
        return sum(n-1)+sum(n-2)+1;
    }
}
int main(){
    int n;
    cin>>n;
cout<<sum(n)<<endl;
}


text:
public class GCD {

    public static void main(String[] args) {

    int n1 = 50;
    int n2 = 25;

    int gcd = gcd (n1, n2);

    System.out.printf ("G.C.D of %d and %d is %d.", n1, n2, gcd);
    }

    public static int gcd (int n1, int n2){
        if (n2 == 0)

            return n1;

        else

            return gcd (n2, n1 % n2);

    }

}


text:
import java.util.*;

public class Bubblesort {
        static void bubbleSort(int[] arr) {
                int n = arr.length;
                int temp = 0;
                for (int i = 0; i < n; i++) {
                        for (int j = 1; j < (n - i); j++) {
                                if (arr[j - 1] > arr[j]) {

                                        temp = arr[j - 1];
                                        arr[j - 1] = arr[j];
                                        arr[j] = temp;
                                }

                        }
                }

        }

        public static void main(String[] args) {
                Scanner sc = new Scanner(System.in);
                int x = sc.nextInt();
                int arr[] = new int[x];
                for (int i = 0; i < x; i++) {
                        arr[i] = sc.nextInt();
                }
                bubbleSort(arr);

                System.out.println("Array after Bubble Sort");
                Arrays.stream(arr).forEach(System.out::println);
                sc.close();
        }
}


text:
import java.util.*;

class Volume {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        float l, b, h, r, volume=0, cont;

        while (true) {
            System.out.println("\n\nTo find the volume of figure:\nPress '1' for CUBE\nPress '2' for CUBOID\nPress '3' for SPHERE\nPress '4' for CYLINDER\nPress '5' for CONE\n");
            int ch = sc.nextInt();

            switch (ch) {
                case 1: System.out.print("Enter the value of side (l): ");
                        l = sc.nextFloat();

                        volume= l*l*l;

                        System.out.println("The volume of the cube is: "+volume);
                        break;

                case 2: System.out.print("Enter the value of length of cuboid (l): ");
                        l = sc.nextFloat();

                        System.out.print("Enter the value of breadth of cuboid (b): ");
                        b = sc.nextFloat();

                        System.out.print("Enter the value of height of cuboid (h): ");
                        h = sc.nextFloat();

                        volume = l*b*h;

                        System.out.println("The volume of the cuboid is: "+volume);
                        break;

                case 3: System.out.print("Enter the value of radius of sphere (r): ");
                        r = sc.nextFloat();

                        volume= (4*22*r*r*r)/(21);

                        System.out.println("The volume of the sphere is: "+volume);
                        break;

                case 4: System.out.print("Enter the value of radius of cylinder (r): ");
                        r = sc.nextFloat();

                        System.out.print("Enter the value of height of cylinder (h): ");
                        h = sc.nextFloat();

                        volume= (22*r*r*h)/7;

                        System.out.println("The volume of the cylinder is: "+volume);
                        break;

                case 5: System.out.print("Enter the value of radius of cone (r): ");
                        r = sc.nextFloat();

                        System.out.print("Enter the value of height of cone (h): ");
                        h = sc.nextFloat();

                        volume= (22*r*r*h)/21;

                        System.out.println("The volume of the cone is: "+volume);
                        break;

                default:System.out.println("Invalid input\n");
            }
            System.out.print("\nDo you wish to continue \nPress 1 for YES \nPress 0 for NO : ");
            cont = sc.nextInt();

            if (cont == 0) {
                break;
            }
        }
    }
}


text:
import java.util.Scanner;
public class MatrixMultiplication
{
int m,n,p,q,i,j,k=0;
int a[][] = new int [10][10];
int b[][] = new int [10][10];
int c[][] = new int [10][10];
Scanner sc = new Scanner (System.in);
void Input ()
{
System.out.println ("Enter no. of Rows & Columns of 1st Matrix");
m = sc.nextInt();
n = sc.nextInt();
System.out.println ("Enter no. of Rows & Columns of 2nd Matrix");
p = sc.nextInt();
q = sc.nextInt();
if (n != p)
{
System.out.println("Matrix Multiplication is not possible");
System.exit(0);
}
else
{
System.out.println("Enter elements of 1st Matrix");
for (i=0;i<m;i++)
for (j=0;j<n;j++)
a[i][j] = sc.nextInt();
System.out.println("Enter elements of 2nd Matrix");
for (i=0;i<p;i++)
for (j=0;j<q;j++)
b[i][j] = sc.nextInt();
}
}
void Calculate ()
{
for (i=0;i<m;i++)
 for (j=0;j<q;j++)
 {
 c[i][j] = 0;
 for (k=0;k<n;k++)
 c[i][j] = c[i][j] +a[i][k]*b[k][j];
 }
}
void Result ()
{
System.out.println ("Product is");
for (int i=0;i<m;i++)
{
for ( int j=0;j<q;j++)
{
System.out.print (c[i][j]+"\t");
}
System.out.print ("\n");
}
}
}
class MulRun
{
public static void main (String args [])
{
MatrixMultiplication mu = new MatrixMultiplication ();
mu.Input();
mu.Calculate();
mu.Result();
}
}


text:
class BubbleSort {
    void bubbleSort(int arr[])
    {
        int n = arr.length;
        for (int i = 0; i < n - 1; i++)
            for (int j = 0; j < n - i - 1; j++)
                if (arr[j] > arr[j + 1]) {
                    // swap arr[j+1] and arr[j]
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
    }

    /* Prints the array */
    void printArray(int arr[])
    {
        int n = arr.length;
        for (int i = 0; i < n; ++i)
            System.out.print(arr[i] + " ");
        System.out.println();
    }

    // Driver method to test above
    public static void main(String args[])
    {
        BubbleSort ob = new BubbleSort();
        int arr[] = { 64, 34, 25, 12, 22, 11, 90 };
        ob.bubbleSort(arr);
        System.out.println("Sorted array");
        ob.printArray(arr);
    }
}


text:
//Github Username: Udyansingh

import java.util.Arrays;
import java.util.Scanner;

public class QuickSort {

    public static int partition(int[] arr, int si, int ei) {
        int pid, piv = arr[si], count = 0, i = si;
        for (i = si + 1; i <= ei; i++) {
            if (arr[i] <= piv) {
                count++;
            }
        }
        pid = count + si;
        arr[si] = (arr[pid] + arr[si]) - (arr[pid] = arr[si]);
        while (si < pid && ei > pid) {
            if (arr[si] < piv) {
                si++;
            } else if (arr[ei] > piv) {
                ei--;
            } else {
                arr[si] = (arr[ei] + arr[si]) - (arr[ei--] = arr[si++]);
            }
        }
        return pid;
    }

    public static void quickSort(int[] arr, int si, int ei) {
        if (si < ei) {
            int p = partition(arr, si, ei);
            quickSort(arr, si, p - 1);
            quickSort(arr, p + 1, ei);
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in).useDelimiter(",");
        System.out.println("Hint: Enter Array -> 1,2,3,4,5,6 ");
        System.out.print("Enter Array -> ");
        String input = sc.nextLine();
        String[] split = input.split(",");
        int[] arr = new int[split.length];
        for (int i = 0; i < split.length; i++) {
            arr[i] = Integer.parseInt(split[i]);
        }
        quickSort(arr, 0, arr.length - 1);
        System.out.println("Sorted Array -> " + Arrays.toString(arr));
        sc.close();
    }
}


text:
import java.util.Scanner;
class LinearSearch
{
   public static void main(String args[])
   {
      int counter, num, item, array[];
      //To capture user input
      Scanner input = new Scanner(System.in);
      System.out.println("Enter number of elements:");
      num = input.nextInt();
      //Creating array to store the all the numbers
      array = new int[num];
      System.out.println("Enter " + num + " integers");
      //Loop to store each numbers in array
      for (counter = 0; counter < num; counter++)
        array[counter] = input.nextInt();

      System.out.println("Enter the search value:");
      item = input.nextInt();

      for (counter = 0; counter < num; counter++)
      {
         if (array[counter] == item)
         {
           System.out.println(item+" is present at location "+(counter+1));
           /*Item is found so to stop the search and to come out of the
            * loop use break statement.*/
           break;
         }
      }
      if (counter == num)
        System.out.println(item + " doesn't exist in array.");
   }
}


text:
import java.util.Arrays;

public class InsertionSort {
  public static void main(String[] args) {

    System.out.println(Arrays.toString(new int[] { 8, 4, 2, 1, 6 }));

  }

  static int[] insertionSort(int[] array) {
    for (int i = 1; i < array.length; i++) {
      int current = array[i];
      int j = i - 1;
      while (j >= 0 && array[j] > current) {
        array[j + 1] = array[j];
        j--;
      }
      array[j + 1] = current;
    }
    return array;
  }

}


text:
public class Selection_sort {
    public static void main(String[] args) {
        int []a={4,1,7,9,456,864,3};
        for(int i=0;i<a.length-1;i++){
            int min=i;
            for (int j=i+1;j<a.length;j++){
                if(a[min]>a[j]){
                   min=j;
                }
            }
            int t=a[i];
            a[i]=a[min];
            a[min]=t;
        }
        for (int i:a){
            System.out.print(i+" ");
        }
    }
}


text:
// Java program to count frequencies of
// characters in string using Hashmap

class OccurenceOfCharInString {
	static void characterCount(String inputString)
	{
		// Creating a HashMap containing char
		// as a key and occurrences as a value
		HashMap<Character, Integer> charCountMap
			= new HashMap<Character, Integer>();

		// Converting given string to char array

		char[] strArray = inputString.toCharArray();

		// checking each char of strArray
		for (char c : strArray) {
			if (charCountMap.containsKey(c)) {

				// If char is present in charCountMap,
				// incrementing it's count by 1
				charCountMap.put(c, charCountMap.get(c) + 1);
			}
			else {

				// If char is not present in charCountMap,
				// putting this char to charCountMap with 1 as it's value
				charCountMap.put(c, 1);
			}
		}

		// Printing the charCountMap
		for (Map.Entry entry : charCountMap.entrySet()) {
			System.out.println(entry.getKey() + " " + entry.getValue());
		}
	}

	// Driver Code
	public static void main(String[] args)
	{
		String str = "Ajit";
		characterCount(str);
	}
}


text:
import java.util.Scanner;
public class Fibonacci
{
    public static void main(String[] args)
    {
        int n, a = 0, b = 0, c = 1;
        Scanner s = new Scanner(System.in);
        System.out.print("Enter value of n:");
        n = s.nextInt();
        System.out.print("Fibonacci Series:");
        for(int i = 1; i <= n; i++)
        {
            a = b;
            b = c;
            c = a + b;
            System.out.print(a+" ");
        }
    }
}


text:
/**
 * Google Online Coding Challenge: Counting paths
 * You are given a matrix A having N rows and M columns. The rows are numbered 1 to N from top to bottom and columns are
 * numbered 1 to M from left to right. You are allowed to move right and down only, i.e., if you are at cell (i,j), then
 * you can move to (i+1, j) and (i, j+1). You are not allowed to move outside the matrix.
 * Your task is to find the number of good paths starting from (1, 1) and ending at (N, M).
 * Good Path: If the sum of all elements that lie in the path is divisible by K, then the path is considered as good.
 *
 * @author: ShubhanshuJha
 *
**/

import java.io.*;
import java.util.Set;
import java.util.HashSet;
import java.util.Scanner;

public class CountingTheNumberOfPathsToReachFrom1ToN {
	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		Scanner sc = new Scanner(System.in);

		int testCase = Integer.parseInt(br.readLine());
		while(testCase-- > 0){
			long n = Long.parseLong(br.readLine());
			long m = Long.parseLong(br.readLine());
			long a[][] = new long[(int)n][(int)m];
			for (int i = 0; i < (int)n; i++) {
				for (int j = 0; j < (int)m; j++) {
					a[i][j] = sc.nextLong();
				}
			}
			long k = Long.parseLong(br.readLine());
			printMat(a);
			long res = paths(a, n, m);
			System.out.println(res);
		}
	}
	static void printMat(long[][] m){
		for (int i = 0; i < m.length; i++) {
			for (int j = 0; j < m[0].length; j++) {
				System.out.print(m[i][j]+" ");
			}
			System.out.println();
		}
	}
	private static long paths(long a[][], long N, long M){
		if (a[(int)N][(int)M] == 1 || a[(int)N][(int)M] == 1) {
			return 1;
		}
		return paths(a, N, M-1) + paths(a, M, N-1);
	}
}


text:
public class MergeSort {
  public static void sort(int[] arr) {
    if (arr.length < 2)
      return;

    int mid = arr.length / 2;
    int[] left = new int[mid];
    for (int i = 0; i < mid; i++)
      left[i] = arr[i];

    int[] right = new int[arr.length - mid];
    for (int i = mid; i < arr.length; i++)
      right[i - mid] = arr[i];

    sort(left);
    sort(right);
    merge(left, right, arr);
  }

  private static void merge(int[] left, int[] right, int[] result) {
    int i = 0, j = 0, k = 0;
    while (i < left.length && j < right.length) {
      if (left[i] <= right[j])
        result[k++] = left[i++];
      else
        result[k++] = right[j++];
    }

    while (i < left.length)
      result[k++] = left[i++];

    while (j < right.length)
      result[k++] = right[j++];
  }
}


text:
// Java implementation of Counting Sort
class CountingSort {
	void sort(char arr[])
	{
		int n = arr.length;

		// The output character array that will have sorted arr
		char output[] = new char[n];

		// Create a count array to store count of individual
		// characters and initialize count array as 0
		int count[] = new int[256];
		for (int i = 0; i < 256; ++i)
			count[i] = 0;

		// store count of each character
		for (int i = 0; i < n; ++i)
			++count[arr[i]];

		// Change count[i] so that count[i] now contains actual
		// position of this character in output array
		for (int i = 1; i <= 255; ++i)
			count[i] += count[i - 1];

		// Build the output character array
		// To make it stable we are operating in reverse order.
		for (int i = n - 1; i >= 0; i--) {
			output[count[arr[i]] - 1] = arr[i];
			--count[arr[i]];
		}

		// Copy the output array to arr, so that arr now
		// contains sorted characters
		for (int i = 0; i < n; ++i)
			arr[i] = output[i];
	}

	// Driver method
	public static void main(String args[])
	{
		CountingSort ob = new CountingSort();
		char arr[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o',
					'r', 'g', 'e', 'e', 'k', 's' };

		ob.sort(arr);

		System.out.print("Sorted character array is ");
		for (int i = 0; i < arr.length; ++i)
			System.out.print(arr[i]);
	}
}
/*This code is contributed by Rajat Mishra */


text:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public void deleteNode(ListNode node) {
         node.val = node.next.val;

        // Step 2: Delete the next node from list
        node.next = node.next.next;
    }
}


text:
class Solution {
    public int rob(int[] nums) {
      if(nums==null || nums.length==0)
          return 0;
        if(nums.length==1)
            return nums[0];
        if(nums.length==2)
            return Math.max(nums[0],nums[1]);
        int dp[]=new int [nums.length];
        dp[0]=nums[0];
        dp[1]=Math.max(nums[0],nums[1]);
        for(int i=2;i<nums.length;i++)
        {
            dp[i]=Math.max(nums[i]+dp[i-2],dp[i-1]);
        }
        return dp[nums.length-1];
    }
}


text:
/**
 * HelloWorld
 */
public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}


text:
class HeapSort
{
/* function to heapify a subtree. Here 'i' is the
index of root node in array a[], and 'n' is the size of heap. */
static void heapify(int a[], int n, int i)
{
    int largest = i; // Initialize largest as root
    int left = 2 * i + 1; // left child
    int right = 2 * i + 2; // right child
    // If left child is larger than root
    if (left < n && a[left] > a[largest])
        largest = left;
    // If right child is larger than root
    if (right < n && a[right] > a[largest])
        largest = right;
    // If root is not largest
    if (largest != i) {
        // swap a[i] with a[largest]
        int temp = a[i];
        a[i] = a[largest];
        a[largest] = temp;

        heapify(a, n, largest);
    }
}
/*Function to implement the heap sort*/
static void heapSort(int a[], int n)
{
    for (int i = n / 2 - 1; i >= 0; i--)
        heapify(a, n, i);

    // One by one extract an element from heap
    for (int i = n - 1; i >= 0; i--) {
        /* Move current root element to end*/
        // swap a[0] with a[i]
        int temp = a[0];
        a[0] = a[i];
        a[i] = temp;

        heapify(a, i, 0);
    }
}
/* function to print the array elements */
static void printArr(int a[], int n)
{
    for (int i = 0; i < n; ++i)
        System.out.print(a[i] + " ");
}
public static void main(String args[])
{
    int a[] = {45, 7, 20, 40, 25, 23, -2};
    int n = a.length;
    System.out.print("Before sorting array elements are - \n");
    printArr(a, n);
    heapSort(a, n);
    System.out.print("\nAfter sorting array elements are - \n");
    printArr(a, n);
}
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Zohaib Hassan Soomro
 */

import java.util.*;

class Stack {

}

public class LinkedStack implements Stack {

    private int size;
    private Node top;

    private class Node {

        private Object object;
        private Node next;

        public Node(Object object, Node next) {
            this.object = object;
            this.next = next;
        }

    }

    @Override
    public Object peek() {
        if (this.isEmpty()) {
            throw new NoSuchElementException("Stack is Empty!");
        }
        return top.object;
    }

    @Override
    public Object pop() {
        if (this.isEmpty()) {
            throw new NoSuchElementException("Stack is Empty!");
        }
        Object obj = top.object;
        top = top.next;
        --size;
        return obj;
    }

    @Override
    public void push(Object obj) {
        top = new Node(obj, top);
        size++;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return (size == 0);
    }

    ///// toString() converts all data of current object into an string
    public String toString() {
        if (this.isEmpty()) {
            return "";
        }
        String string = "[";
        for (Node i = top; i != null; i = i.next) {
            string += String.valueOf(i.object + ",");
        }
        string = string.substring(0, string.lastIndexOf(',')) + "]";
        return string;
    }

    ///// equals() compares two stacks
    public boolean equals(Stack obj) {
        if (this.size() != obj.size()) {
            return false;
        }
        Object array[] = new Object[this.size()];
        Object array2[] = new Object[this.size()]; // as size of both are equal
        boolean areEqual = true;
        int i = 0; // counter variable
        for (; i < array.length; i++) {
            array[i] = this.pop(); // storing elements in array by popping so that we can store later same elements
            array2[i] = obj.pop();
            if (!array[i].equals(array2[i])) {
                areEqual = false;
            }
        }
        while (--i >= 0) {
            this.push(array[i]); // again inserting those elements in
            obj.push(array2[i]);
        }
        return areEqual;
    }

    //// findLast() finds last element in the stack
    public Object findLast() {
        if (this.isEmpty()) {
            throw new NoSuchElementException("Stack is empty!");
        }
        Node i = top;
        for (; i.next != null; i = i.next) // because if i.next=null it means i will be pointing to the last Object
        {
        }
        return i.object;
    }

    ///// toArrayStack() returns ArrayStack object equivalent to curent LinkedStack
    ///// object
    public ArrayStack toArrayStack() {
        if (this.isEmpty()) {
            return null;
        }
        Object array[] = new Object[this.size];
        int count = 0;
        ArrayStack stack = new ArrayStack(this.size);
        for (Node i = top; i != null; i = i.next) {
            array[count++] = i.object; // for preserving same order that's why storing elements in an Object array
        }
        for (int i = this.size - 1; i >= 0; i--) {
            stack.push(array[i]);
        }
        return stack;
    }

    public static void main(String[] args) {
        LinkedStack stack = new LinkedStack();
        stack.push(4);
        stack.push("Hello");
        stack.push(200);
        LinkedStack stack2 = new LinkedStack();
        stack2.push(4);
        stack2.push("Hello");
        stack2.push(200);
        System.out.println("stack.toString(): " + stack.toString());
        System.out.println("stack2.toString(): " + stack2.toString());
        System.out.println("stack.equals(stack2): " + stack.equals(stack2));
        System.out.println("stack.findLast(): " + stack.findLast());
        System.out.println("stack.toArrayStack().toString(): " + stack.toArrayStack().toString());

    }

}


text:
class Main {
  public static void main(String[] args) {

    // declare variables
    int a = 10, b = 6;

    // addition operator
    System.out.println("a + b = " + (a + b));

    // subtraction operator
    System.out.println("a - b = " + (a - b));

    // multiplication operator
    System.out.println("a * b = " + (a * b));

    // division operator
    System.out.println("a / b = " + (a / b));

    // modulo operator
    System.out.println("a % b = " + (a % b));
  }
}


text:
public class Palindrome {
    public static boolean isPalindrome(int n) {
      int temp = n;
      int rem;
      int ans = 0;
      while(n>0){
        rem = n%10;
        ans = ans*10+rem;
        n=n/10;
      }
      if(ans==temp){
        return true;
      }
      return false;
    }
    public static void main(String[] args){
        int N = 124321;
        boolean res = isPalindrome(N);
        System.out.print(res);
    }
}


text:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="MouseDemo.class" width=200 height=200> </applet>
*/

public class MouseDemo extends Applet implements MouseListener,MouseMotionListener
{
	int mousex=0,mousey=0;
	String msg="";
	public void init()
	{
		// setBackground(Color.red);
		// setForeground(Color.blue);
		addMouseListener(this);
		addMouseMotionListener(this);
	}

	public void mouseClicked(MouseEvent me)
	{
		mousex=10;
		mousey=20;
		msg="you have clicked the mouse";
		repaint();
	}

	public void mousePressed(MouseEvent me)
	{
		mousex=me.getX();
		mousey=me.getY();
		msg="you have pressed the mouse";
		repaint();
	}

	public void mouseReleased(MouseEvent me)
	{
		mousex=me.getX();
		mousey=me.getY();
		msg="you have Released the mouse";
		repaint();
	}

	public void mouseEntered(MouseEvent me)
	{
		mousex=60;
		mousey=40;
		msg="mouse is entered into applet";
		repaint();
	}

	public void mouseExited(MouseEvent me)
	{
		mousex=70;
		mousey=40;
		msg="mouse is exited from applet";
		repaint();
	}

	public void mouseDragged(MouseEvent me)
	{
		showStatus("mouse is Dragged from ("+me.getX()+","+me.getY()+")");
	}

	public void mouseMoved(MouseEvent me)
	{
		showStatus("mouse is Moved from ("+me.getX()+","+me.getY()+")");
	}

	public void paint(Graphics g)
	{
		g.drawString(msg,mousex,mousey);
	}

}


text:
#include <bits/stdc++.h>
using namespace std;

/* question link ~ https://leetcode.com/problems/longest-consecutive-sequence/

    THIS QUESTION IS A GREAT START TO UNDERSTAND UNION FIND.

    I have used a hashmap for FIND operation, and an array to store to parent of the given index

 */

/* APPROACH:
    We try to make a connected series of numbers that are consecutive.

    For eg, array is 1,3,100,5,6,4.

    first add 1, with its parent as itself, parent[0]=0;

    then add 3, we check if (3-1/3+1) number is previously encountered or not, since it is not, we simple add this in a separately
    as parent[1]=1;

    then same with 100, parent[2]=2;
    then same with 5, parent[3]=3;

    now, when we add 6, we see, we have (6-1=5) previously present, hence what we do is, connect 6 to 5,
    with first finding the parent of 5 and then, setting parent of 6 as parent of 5.

    similarily we continue for 4. . .
*/
int findParent(unordered_map<int, int>& par, int r) {
    return r == par[r] ? r : findParent(par, par[r]);
}

//main function to find the longest consecutive numbers in an array
int longestConsecutive(vector<int>& nums) {

    //map "par" used to store the parent index of a given element
    unordered_map<int, int> par;
    unordered_map<int, int> groupSize;

    int ans = 0;

    for (int num: nums) {

        //intitally put the number in map simply
        if (par.find(num) == par.end()) {
            par[num] = num;
            groupSize[num] = 1;
        }
        int numParent = findParent(par, num);

        //now check of there ia a number which is +1/-1 of the number
        for (int adj = num - 1; adj <= num + 1; adj += 2) {

            //if we find such number
            if (par.find(adj) != par.end()) {
                //find the parent of that particular number
                int adjParent = findParent(par, adj);

                //and hence connect this number an an extension to it
                if (numParent != adjParent) {
                    par[adjParent] = par[numParent];
                    groupSize[numParent] += groupSize[adjParent];
                }
            }
        }
            ans = max(ans, groupSize[numParent]);
        }

        return ans;
    }

int main(){

    //take user input
    int n;
    vector<int> nums(n,0);
    for(int i=0;i<n;i++){
        cin>>nums[i];
    }

    int ans=largestConsecutive(nums);
    return 0;

}


text:
#include <iostream>
#include<bits/stdc++.h>
using namespace std;

vector<vector<int>> dp;
int minPathSum(vector<vector<int>>& grid) {
    int n = grid.size(), m = grid[0].size();
    vector<vector<int>> dp(n, vector<int> (m, 0));

    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            if(i==0 && j==0)
                dp[i][j] = grid[i][j];

            else{
                int u = grid[i][j];
                if(i>0)
                    u += dp[i-1][j];

                else
                    u += 1e9;

                int l = grid[i][j];
                if(j>0)
                    l += dp[i][j-1];
                else l += 1e9;

                dp[i][j] = min(u, l);
            }
        }
    }

    return dp[n-1][m-1];
}

int main()
{
    vector<vector<int>> grid = {{1,3,1},{1,5,1},{4,2,1}};
    dp.resize(3, vector<int> (3, 0));

    int r = minPathSum(grid);
    cout << r;

}


text:
import java.util.Arrays;

public class MinMaxElementsOfArray {
    public static void main(String[] args) {
        int[] nums = { 12, 9, 5, 76, 3, 42, 76, 22, 44 };
        System.out.println("Array is");
        Arrays.stream(nums).forEach(System.out::println);
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > max) {
                max = nums[i];
            }
        }
        System.out.println("Max is " + max);
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] < min) {
                min = nums[i];
            }
        }
        System.out.println("Min is " + min);
    }
}


text:
#include <iostream>

#include <cstring> //string library

using namespace std;

int main() {
    int n; //length of string
    cin>>n;
    char s1[n];
    char s2[n];
    char s3[n]; //temporary string
    //Input String 1
    cin>>s1;
    //Input String 2
    cin>>s2;
    strcpy(s3,s1); //copy contents of s1 in s3
    strcpy(s1,s2);  // similar to  s1=s2
    strcpy(s2,s3);
    cout<<s1<<"\n";
    cout<<s2;
    return 0;
}


text:
// Java program to remove duplicates from ArrayList

import java.util.*;

public class duplicatelem {

    // Function to remove duplicates from an ArrayList
    public static <T> ArrayList<T> removeDuplicates(ArrayList<T> list)
    {

        // Create a new LinkedHashSet
        Set<T> set = new LinkedHashSet<>();

        // Add the elements to set
        set.addAll(list);

        // Clear the list
        list.clear();

        // add the elements of set
        // with no duplicates to the list
        list.addAll(set);

        // return the list
        return list;
    }

    // Driver code
    public static void main(String args[])
    {

        // Get the ArrayList with duplicate values
        ArrayList<Integer>
            list = new ArrayList<>(
                Arrays
                    .asList(1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5));

        // Print the Arraylist
        System.out.println("ArrayList with duplicates: "
                           + list);

        // Remove duplicates
        ArrayList<Integer>
            newList = removeDuplicates(list);

        // Print the ArrayList with duplicates removed
        System.out.println("ArrayList with duplicates removed: "
                           + newList);
    }
}


text:
/**
3. Product array puzzle
Given an array nums[] of size n, construct a Product Array P (of same size n) such that P[i] is equal to the product of all the elements of nums except nums[i].

Example 1:

Input:
n = 5
nums[] = {10, 3, 5, 6, 2}
Output:
180 600 360 300 900
Explanation:
For i=0, P[i] = 3*5*6*2 = 180.
For i=1, P[i] = 10*5*6*2 = 600.
For i=2, P[i] = 10*3*6*2 = 360.
For i=3, P[i] = 10*3*5*2 = 300.
For i=4, P[i] = 10*3*5*6 = 900.
Example 2:

Input:
n = 2
nums[] = {12,0}
Output:
0 12

Your Task:
You do not have to read input. Your task is to complete the function productExceptSelf() that takes array nums[] and n as input parameters and returns a list of n integers denoting the product array P. If the array has only one element the returned list should should contains one value i.e {1}
Note: Try to solve this problem without using the division operation.

Expected Time Complexity: O(n)
Expected Auxiliary Space: O(n)

Constraints:
1 <= n <= 1000
0 <= numsi <= 200
Array may contain duplicates.
**/
// { Driver Code Starts
//Initial template for C++

#include<bits/stdc++.h>
using namespace std;

 // } Driver Code Ends
//User function template for C++

class Solution{
  public:
    // nums: given vector
    // return the Product vector P that hold product except self at each index
    vector<long long int> productExceptSelf(vector<long long int>& nums, int n) {

        //code here
    }
};

// { Driver Code Starts.
int main()
 {
    int t;  // number of test cases
    cin>>t;
    while(t--)
    {
        int n;  // size of the array
        cin>>n;
        vector<long long int> arr(n),vec(n);

        for(int i=0;i<n;i++)    // input the array
        {
            cin>>arr[i];
        }
        Solution obj;
        vec = obj.productExceptSelf(arr,n);   // function call

        for(int i=0;i<n;i++)    // print the output
        {
            cout << vec[i] << " ";
        }
        cout<<endl;
    }
	return 0;
}  // } Driver Code Ends


text:
/* 	Given an array which consists of only 0, 1 and 2.
 	Sort the array without using any sorting algorithm.
	aka Dutch National Flag Problem.
*/

/*
Input:
8
0 1 2 0 1 2 0 1

Output:
0 0 0 1 1 1 2 2

*/
#include <bits/stdc++.h>
using namespace std;

void swap(int *a, int *b) {
	int t = *a;
	*a = *b;
	*b = t;
}

// For Sorting 3 Numbers
void sort012(int arr[], int n) {
	int low = 0, mid = 0, high = n - 1;

	while (mid <= high)
	{
		if (arr[mid] == 0) {
			swap(arr[low], arr[mid]);
			low++; mid++;
		} else if (arr[mid] == 1) {
			mid++;
		} else if (arr[mid] == 2) {
			swap(arr[mid], arr[high]);
			high--;
		}
	}
}
// For Sorting 2 Numbers
// void sort01(int arr[], int n) {
// 	int low = 0, high = n - 1;

// 	while (low <= high) {
// 		if (arr[low] == 0)
// 			low++;
// 		else {
// 			swap(arr[low], arr[high]);
// 			high--;
// 		}
// 	}
// }

int main()
{
	int n; cin >> n;

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

	sort012(arr, n);

	for (int i = 0; i < n; i++)
		cout << arr[i] << " ";

	return 0;
}


text:
// C++ Program to find smallest number in an array

#include <iostream>
using namespace std;

int main(){
    int input[100], count, i, min;

    cout << "Enter Number of Elements in Array\n";
    cin >> count;

    cout << "Enter " << count << " numbers \n";

    // Read array elements
    for(i = 0; i < count; i++){
        cin >> input[i];
    }

    min = input[0];
    // search num in inputArray from index 0 to elementCount-1
    for(i = 0; i < count; i++){
        if(input[i] < min){
            min = input[i];
        }
    }

    cout  << "Minimum Element\n" << min;

    return 0;
}


text:
#include <iostream>
using namespace std;

// Function to remove duplicate elements This function
// returns new size of modified array.
int removeDuplicates(int arr[], int n)
{
    // Return, if array is empty or contains a single
    // element
    if (n == 0 || n == 1)
        return n;

    int temp[n];

    // Start traversing elements
    int j = 0;
    // If current element is not equal to next element
    // then store that current element
    for (int i = 0; i < n - 1; i++)
        if (arr[i] != arr[i + 1])
            temp[j++] = arr[i];

    // Store the last element as whether it is unique or
    // repeated, it hasn't stored previously
    temp[j++] = arr[n - 1];

    // Modify original array
    for (int i = 0; i < j; i++)
        arr[i] = temp[i];

    return j;
}

// Driver code
int main()
{
    int arr[] = { 1, 2, 2, 3, 4, 4, 4, 5, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);

    // removeDuplicates() returns new size of array.
    n = removeDuplicates(arr, n);

    // Print updated array
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";

    return 0;
}


text:
// Time:  O(n^2)
// Space: O(n)

class Solution {
public:
    vector<int> createTargetArray(vector<int>& nums, vector<int>& index) {
        for (int i = 0; i < nums.size(); ++i) {
            for (int j = 0; j < i; ++j) {
                if (index[j] >= index[i]) {
                    ++index[j];
                }
            }
        }
        vector<int> result(nums.size(),0);
        for (int i = 0; i < nums.size(); ++i){
            result[index[i]] = nums[i];
        }
        return result;
    }
};

// Time:  O(n^2)
// Space: O(1)
class Solution2 {
public:
    vector<int> createTargetArray(vector<int>& nums, vector<int>& index) {
        vector<int> result;
        for (int i = 0; i < nums.size(); i++) {
            result.insert(begin(result) + index[i], nums[i]);
        }
        return result;
    }
};


text:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    int i,j,n,max,sum;
    cout<<"Enter size of array";
    cin>>n;
    cout<<"Enter sum";
    cin>>sum;
    int arr[n];
    cout<<"Enter elements in an array";
    for(i=0;i<n;i++){
        cin>>arr[i];
    }
    max=*max_element(arr,arr+n);
    int H[max]={0};
    for(i=0;i<n;i++){
        if(H[sum-arr[i]]!=0){
            cout<<"("<<arr[i]<<","<<sum-arr[i]<<")";
        }
        H[arr[i]]++;

    }
    return 0;
}


text:
#include <bits/stdc++.h>
using namespace std;

// Function to get the missing number
int getMissingNo(int a[], int n)
{
    int N = n + 1;

    int total = (N) * (N + 1) / 2;
    for (int i = 0; i < n; i++)
        total -= a[i];
    return total;
}
int main()
{
    int n;
    cout<<"Enter size of array"<<endl;
    cin>>n;
    int arr[n];
    cout<<"Enter elements"<<endl;
    for(int i=0;i<n;i++){
        cin>>arr[i];
    }
    int N = sizeof(arr) / sizeof(arr[0]);

    // Function call
    int miss = getMissingNo(arr, N);
    cout << miss;
    return 0;
}


text:
// Minimum Number of jumps to reach to end
// Valley Peak Approach.
/*
Input:
6
1 4 3 2 6 7

Output:
2
(1 -> 4 -> 7)
*/

#include <bits/stdc++.h>
using namespace std;

// int getNextIndex(int arr[], int n, int start, int end) {
// 	int max = arr[start];
// 	int index = start;

// 	for (int i = start + 1; i <= end; i++) {
// 		if (arr[i] + i >= n - 1) return i;
// 		if (arr[i] >= max) {
// 			max = arr[i];
// 			index = i;
// 		}
// 	}
// 	return index;
// }

// int minJumps(int arr[], int n) {
// 	int jump = 0;

// 	for (int i = 0; i <= n - 2;) {
// 		cout << i << " ";
// 		if (arr[i] == 0) return -1;

// 		if (arr[i] + i >= n - 1) {
// 			jump++; break;
// 		}
// 		i = getNextIndex(arr, n, i + 1, arr[i] + i);
// 		jump++;
// 	}
// 	return jump;
// }

int minJumps(int arr[], int n) {
	if (n <= 1) return 0;
	if (arr[0] == 0) return -1;

	int max_reach = arr[0], jump = 0, steps = arr[0];

	for (int i = 1; i < n; i++) {
		if (i > max_reach) return -1;

		if (i == n - 1) return ++jump;

		if (arr[i] + i > max_reach)
			max_reach = arr[i] + i;

		steps--;

		if (steps == 0) {
			jump++;
			steps = max_reach - i;
		}
	}
	return jump;
}

int main()
{
	int n; cin >> n;

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

	int jump = minJumps(arr, n);

	cout << jump;

	return 0;
}


text:
#include<bits/stdc++.h>

using namespace std;

//finds elements having at-least two greater elements

void greater_elements(int arr[], int n){
  cout << "\nElements which have at-least two greater elements are: ";

  for (int i = 0; i < n; i++){
    int
    var = 0;

    for (int j = 0; j < n; j++)

      if (arr[j] > arr[i])

        var ++;

    if (var >= 2)

      cout << arr[i] << " ";

  }

}

int main(){

  int arr[100], n, i;

  cout << "Enter number of elements: ";

  cin >> n;

  cout << "\nEnter elements: ";

  for (i = 0; i < n; i++)

    cin >> arr[i];

  cout << "Elements are: ";

  for (i = 0; i < n; i++)

    cout << arr[i] << " ";

  greater_elements(arr, n);

  return 0;

}


text:
#include<iostream>
using namespace std;
void maxAndSecondMax(int *arr, int size){
   int max= INT_MIN;
   int s_max= INT_MIN;
   for(int i=0;i<size; ++i){
      if(arr[i] >max){
         s_max= max;
         max= arr[i];
      }
      else if(arr[i]> s_max && arr[i]!= max){
         s_max= arr[i];
      }
   }
   if(s_max==INT_MIN){
      s_max= -1;
   }
   cout<<"1st max is "<<max<<" "<<"2nd Max is "<<s_max;
}
int main(){
   int n;
   cout<<"enter size of array "<<endl;
   cin>>n;
   int *arr=new int[n];
   cout<<"enter numbers "<<endl;
   for(int i=0;i<n;i++)
   {
    cin>>arr[i];
   }
   maxAndSecondMax(arr,n);
   delete [] arr;
   arr=0;
   return 0;
}


text:
// Find the Union and Intersection of the two sorted arrays.

/*
Input:
3
1 2 3
5
1 2 3 4 5

Output:
Union:
1 2 3 4 5

Intersection:
1 2 3

*/
#include<bits/stdc++.h>

using namespace std;

void findUnion(int a[], int n, int b[], int m) {
    int i = 0, j = 0;

    while (i < n && j < m) {
        if (a[i] < b[j])
            cout << a[i++] << " ";
        else if (a[i] > b[j])
            cout << b[j++] << " ";
        else {
            cout << a[i] << " ";
            i++; j++;
        }
    }

    while (i < n)
        cout << a[i++] << " ";
    while (j < m)
        cout << b[j++] << " ";
}

void findIntersection(int a[], int n, int b[], int m) {
    int i = 0, j = 0;

    while (i < n && j < m) {
        if (a[i] == b[j])
            cout << a[i] << " ";
        i++; j++;
    }
}

int main()
{
    int n; cin >> n;

    int a[n];
    for (int i = 0; i < n; i++)
        cin >> a[i];

    int m; cin >> m;

    int b[m];
    for (int i = 0; i < m; i++)
        cin >> b[i];

    cout << "Union:\n";
    findUnion(a, n, b, m);

    cout << "\n\nIntersection:\n";
    findIntersection(a, n, b, m);

    return 0;
}


text:
//GFG Problem:POTD

//https://practice.geeksforgeeks.org/problems/maximize-the-sum-of-selected-numbers-from-an-array-to-make-it-empty0836/1

/*Given a array of N numbers, we need to maximize the sum of selected numbers. At each step, you need to select a number Ai, delete
one occurrence of Ai-1 (if exists), and Ai each from the array.
Repeat these steps until the array gets empty. The problem is to maximize the sum of the selected numbers.*/

//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;

// } Driver Code Ends
class Solution{
    public:
    int maximizeSum(int a[], int n)
    {
        // Complete the function
         int ans=0;

        unordered_map<int,int> ump;

        for(int i=0;i<n;i++) ump[a[i]]++;

        // sort(a,a+n); array was already sorted but not mentioned

        for(int i=n;i>=0;i--)

        {

            if(ump[a[i]]>0)

            {

                ans+=a[i];

                ump[a[i]]--;

                if(ump[a[i]-1]>0) ump[a[i]-1]--;

            }

        }

        return ans;
    }

};

//{ Driver Code Starts.

int main()
{

    int t;cin>> t;
    while(t--)
    {
        int n;
        cin >> n;
        int arr[n];

        for(int i=0;i<n;i++)
            cin>>arr[i];
        sort(arr, arr+n);
        Solution ob;

        cout << ob.maximizeSum(arr, n) << endl;

    }

}

// } Driver Code Ends


text:
#include<bits/stdc++.h>
using namespace std;
int main(){
    vector<int> A = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
    int sum = A[0];
    int finalSum = sum;
    for(int i=1;i<A.size();i++){
        sum = sum+A[i];
        if(sum<0){
            sum = max(sum,A[i]);
            finalSum = max(finalSum,sum);
            sum = 0;
        }
        else{
            finalSum = max(sum,finalSum);
        }

    }
    cout<<" finalSum = "<<finalSum<<endl;
}


text:
#include <bits/stdc++.h>
using namespace std;

void bubbleSort(int arr[], int n)
{
	int i, j;
	for (i = 0; i < n - 1; i++)

		for (j = 0; j < n - i - 1; j++)
			if (arr[j] > arr[j + 1])
				swap(arr[j], arr[j + 1]);
}

void printArray(int arr[], int size)
{
	int i;
	for (i = 0; i < size; i++)
		cout << arr[i] << " ";
	cout << endl;
}

int main()
{
	int arr[] = { 5, 1, 4, 2, 8};
	int N = sizeof(arr) / sizeof(arr[0]);
	bubbleSort(arr, N);
	cout << "Sorted array: \n";
	printArray(arr, N);
	return 0;
}


text:
// Find the "Kth" max and min element of an array.

/*
Input:
8
3
1 2 3 4 5 6 7 8

Output:
3th Minimum Value: 3
3th Maximum Value: 6

*/
#include <bits/stdc++.h>
using namespace std;

void sort(int arr[], int n) {
	for (int i = 0; i < n - 1; i++) {
		for (int j = 0; j < n - i - 1; j++) {
			if (arr[j] > arr[j + 1]) {
				int t = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = t;
			}
		}
	}
}

int main()
{
	int n, k;
	cin >> n >> k;

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

	sort(arr, n);

	cout << k << "th Minimum Value: " << arr[k - 1] << "\n";
	cout << k << "th Maximum Value: " << arr[n - k];

	return 0;
}


text:
// PROBLEM :-
// https://leetcode.com/problems/merge-sorted-array/

// begin from last index of both array, compare two elements from both array,
// and overwrite in the last available position of nums1 (as it is meant to be INPLACE).

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {

        int itrA = m - 1;
        int itrB = n - 1;
        int itr = m + n - 1;
        while(itrA >= 0 && itrB >= 0){
            if(nums1[itrA] > nums2[itrB]){
                nums1[itr] = nums1[itrA];
                itr--;
                itrA--;
            }else{
                nums1[itr] = nums2[itrB];
                itr--;
                itrB--;
            }
        }

        while(itrB >= 0){
            nums1[itr] = nums2[itrB];
            itr--;
            itrB--;
        }

    }
};


text:
/**
2. Third largest element
Given an array of distinct elements. Find the third largest element in it.

Example 1:

Input:
N = 5
A[] = {2,4,1,3,5}
Output: 3
Example 2:

Input:
N = 2
A[] = {10,2}
Output: -1
Your Task:
Complete the function thirdLargest() which takes the array a[] and the size of the array, n, as input parameters and returns the third largest element in the array. It return -1 if there are less than 3 elements in the given array.

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)

Constraints:
1 ≤ N ≤ 105
1 ≤ A[i] ≤ 105
**/
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;

 // } Driver Code Ends
class Solution{
    public:
    //Function to count the frequency of all elements from 1 to N in the array.
    void frequencyCount(vector<int>& arr,int N, int P)
    {
        vector <int> arr2(P,0) ;
        for(int i =0;i<N;i++)
            arr2.push_back(0);
        for(int i=0;i<N;i++)
            arr2[arr[i]-1]++;
        arr=arr2;// code here
    }
};

// { Driver Code Starts.

int main()
{
	long long t;

	//testcases
	cin >> t;

	while(t--){

	    int N, P;
	    //size of array
	    cin >> N;

	    vector<int> arr(N);

	    //adding elements to the vector
	    for(int i = 0; i < N ; i++){
	        cin >> arr[i];
	    }
        cin >> P;
        Solution ob;
        //calling frequncycount() function
		ob.frequencyCount(arr, N, P);

		//printing array elements
	    for (int i = 0; i < N ; i++)
			cout << arr[i] << " ";
	    cout << endl;
	}
	return 0;
}

  // } Driver Code Ends


text:
class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        int n = nums.size();
        vector<vector<int>> ans;
        for (int i = 0; i < n; ++i) {
            for (int j = i + 1; j < n; ++j) {
                int l = j + 1, r = n - 1;
                int remain = target - nums[i] - nums[j];
                while (l < r) {
                    if (nums[l] + nums[r] == remain) {
                        ans.push_back({nums[i], nums[j], nums[l], nums[r]});
                        ++l; --r;
                        while (l < r && nums[l-1] == nums[l]) ++l; // Skip duplicate nums[l]
                    } else if (nums[l] + nums[r] > remain) {
                        --r;
                    } else {
                        ++l;
                    }
                }
                while (j+1 < n && nums[j] == nums[j+1]) ++j; // Skip duplicate nums[j]
            }
            while (i+1 < n && nums[i] == nums[i+1]) ++i; // Skip duplicate nums[i]
        }
        return ans;
    }
};


text:
//  Write a program to cyclically rotate an array by one.

/*
Input:
5
1 2 3 4 5

Output:
Rotated Array:
5 1 2 3 4

*/
#include <bits/stdc++.h>
using namespace std;

int main()
{
	int n; cin >> n;

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

	int first = arr[n - 1];
	for (int i = n - 1; i > 0; i--) {
		arr[i] = arr[i - 1];
	}

	arr[0] = first;

	cout << "Rotated Array: \n";
	for (int i = 0; i < n; i++)
		cout << arr[i] << " ";
	return 0;
}


text:
#include<iostream>
using namespace std;

struct Pair
{
	int min;
	int max;
};

struct Pair getMinMax(int arr[], int n)
{
	struct Pair minmax;
	int i;

	if (n == 1)
	{
		minmax.max = arr[0];
		minmax.min = arr[0];
		return minmax;
	}

	if (arr[0] > arr[1])
	{
		minmax.max = arr[0];
		minmax.min = arr[1];
	}

	else
	{
		minmax.max = arr[1];
		minmax.min = arr[0];
	}

	for(i = 2; i < n; i++)
	{
		if (arr[i] > minmax.max)
			minmax.max = arr[i];

		else if (arr[i] < minmax.min)
			minmax.min = arr[i];
	}

	return minmax;
}

int main()
{
	int n;
	cin>>n;

	int arr[n];

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

	struct Pair minmax = getMinMax(arr, n);

	cout << "Min: " << minmax.min << endl;
	cout << "Max: " << minmax.max;

	return 0;
}


text:
// maximum subarray sum program

#include <iostream>
#include <cmath>
using namespace std;

int maxSubarraySum(int arr[], int n)
{
    int res = arr[0];

    int maxEnding = arr[0];

    for (int i = 1; i < n; i++)
    {
        maxEnding = max(maxEnding + arr[i], arr[i]);

        res = max(maxEnding, res);
    }

    return res;
}

int main()
{

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

    cout << maxSubarraySum(arr, n);
}


text:
//  Reverse an array

/*
Input:
5
5 4 3 2 1

Output:
Reversed Array:
1 2 3 4 5
*/

#include <bits/stdc++.h>
using namespace std;

// void reverse(int arr[], int n) {
// 	for (int i = 0; i <= n / 2; i++) {
// 		int temp = arr[i];
// 		arr[i] = arr[n - i - 1];
// 		arr[n - i - 1] = temp;
// 	}
// }

void reverse(int arr[], int n) {
	int left = 0, right = n - 1;

	while (left < right) {
		swap(arr[left], arr[right]);
		left++;
		right--;
	}
}

int main()
{
	int n; cin >> n;

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

	reverse(arr, n);

	cout << "Reversed Array: \n";

	for (int i = 0; i < n; i++)
		cout << arr[i] << " ";

	return 0;
}


text:
#include <bits/stdc++.h>
using namespace std;
int main(){
	int t;
	cin>>t;
	while(t--){
		int n;
		cin>>n;
		int a[n];
		for(int i=1;i<=n;i++){
			cin>>a[i];
		}
		for(int i=1;i<=n;i++){
				if(a[1]!=a[2] && a[1]!=a[3]){
					cout<<1<<endl;
					break;
				}
				else if(a[i]!=a[1]){
					cout<<i<<endl;
				}
		}
	}
}


text:
// Move all the negative elements to one side of the array.

/*
Input:
6
2 -3 5 -1 -6 4

Output:
Negative Value First:
-3 -1 -6 2 5 4

*/
#include <bits/stdc++.h>
using namespace std;

void move_negative(int arr[], int n) {
	int neg = 0;

	for (int i = 0; i < n; ++i) {
		if (arr[i] < 0) {
			swap(arr[i], arr[neg]);
			neg++;
		}
	}
}

int main()
{
	int n; cin >> n;

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

	move_negative(arr, n);

	cout << "Negative Value First: \n";
	for (int i = 0; i < n; i++)
		cout << arr[i] << " ";

	return 0;
}


text:
// Find duplicate in an array of N+1 Integer

#include <bits/stdc++.h>
using namespace std;

// Print all Duplicate numbers
// void duplicateNums(int arr[], int n) {
// 	for (int i = 0; i < n; i++) {
// 		if (arr[abs(arr[i])] >= 0)
// 			arr[abs(arr[i])] = -arr[abs(arr[i])];
// 		else
// 			cout << abs(arr[i]) << " ";
// 	}
// }

int duplicateNums(int arr[], int n) {
	int slow = arr[0];
	int fast = arr[0];
	do {
		slow = arr[slow];
		fast = arr[arr[fast]];
	} while (slow != fast);

	fast = arr[0];

	while (slow != fast) {
		slow = arr[slow];
		fast = arr[fast];
	}
	return slow;
}

//  void duplicateNums(int arr[], int n) {
// 	int fqy[n + 1] = {0};

// 	for (int i = 0; i < n; i++)
// 		fqy[arr[i]]++;

// 	for (int i = 0; i < n; i++)
// 		if (fqy[i] >= 1)
// 			cout << i << " ";
// }

int main()
{
	int n; cin >> n;

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

	cout << duplicateNums(arr, n);

	return 0;
}


text:
// Next Permutation

#include <bits/stdc++.h>
using namespace std;

void nextPermutation(vector<int>& nums) {
	if (nums.size() <= 1) return;

	int i = nums.size() - 2;
	while (i >= 0 && nums[i] >= nums[i + 1])
		i--;

	if (i >= 0) {
		int j = nums.size() - 1;
		while (j > i && nums[j] <= nums[i])
			j--;
		swap(nums[i], nums[j]);
	}
	reverse(nums.begin() + i + 1, nums.end());
}

int main()
{
	int n; cin >> n;

	vector<int> nums;
	int x;

	for (int i = 0; i < n; ++i) {
		cin >> x;
		nums.push_back(x);
	}

	nextPermutation(nums);

	for (auto i : nums)
		cout << i << " ";

	return 0;
}


text:
// Time:  O(n^2)
// Space: O(1)

class Solution {
public:
    vector<vector<int>> threeSum(vector<int> &nums) {
        sort(begin(nums), end(nums));
        vector<vector<int>> result;
        for (int i = size(nums) - 1; i >= 2; --i) {
            if (i + 1 < size(nums) && nums[i] == nums[i + 1]) {
                continue;
            }
            const auto& target = -nums[i];
            int left = 0, right = i - 1;
            while (left < right) {
                if (nums[left] + nums[right] < target) {
                    ++left;
                } else if (nums[left] + nums[right] > target) {
                    --right;
                } else {
                    result.push_back({nums[left], nums[right], nums[i]});
                    ++left; --right;
                    while (left < right && nums[left] == nums[left - 1]) {
                        ++left;
                    }
                    while (left < right && nums[right] == nums[right + 1]) {
                        --right;
                    }
                }
            }
        }
        return result;
    }
};


text:
/**
4. Move all zeroes to end of array
Easy Accuracy: 51.81% Submissions: 10335 Points: 2
Given an array arr[] of N positive integers. Push all the zero’s of the given array to the right end of the array while maitaining the order of non-zero elements.

Example 1:

Input:
N = 5
Arr[] = {3, 5, 0, 0, 4}
Output: 3 5 4 0 0
Explanation: The non-zero elements
preserve their order while the 0
elements are moved to the right.
Example 2:

Input:
N = 4
Arr[] = {0, 0, 0, 4}
Output: 4 0 0 0
Explanation: 4 is the only non-zero
element and it gets moved to the left.

Your Task:
You don't need to read input or print anything. Complete the function pushZerosToEnd() which takes the array arr[] and its size n as input parameters and modifies arr[] in-place such that all the zeroes are moved to the right.

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)

Constraints:
1 ≤ N ≤ 105
0 ≤ arri ≤ 105

**/
// { Driver Code Starts
//Initial template for C++

#include<bits/stdc++.h>
using namespace std;

 // } Driver Code Ends
//User function template for C++

class Solution{
  public:
    // nums: given vector
    // return the Product vector P that hold product except self at each index
    vector<long long int> productExceptSelf(vector<long long int>& nums, int n) {

       int count=0;

     for(int i=0;i<n;i++)

     {

         if(nums[i]!=0)

         {

             swap(arr[i],arr[count]);

             count++;

         }

     }
    }
};

// { Driver Code Starts.
int main()
 {
    int t;  // number of test cases
    cin>>t;
    while(t--)
    {
        int n;  // size of the array
        cin>>n;
        vector<long long int> arr(n),vec(n);

        for(int i=0;i<n;i++)    // input the array
        {
            cin>>arr[i];
        }
        Solution obj;
        vec = obj.productExceptSelf(arr,n);   // function call

        for(int i=0;i<n;i++)    // print the output
        {
            cout << vec[i] << " ";
        }
        cout<<endl;
    }
	return 0;
}  // } Driver Code Ends


text:
// Merge Intervals

#include <bits/stdc++.h>
using namespace std;

vector<vector<int>> merge_interval(vector<vector<int>>& intervals) {
	vector<vector<int>> result;
	int len = intervals.size();
	if (len == 0) return result;

	sort(intervals.begin(), intervals.end());

	vector<int> one = intervals[0];
	for (int i = 1; i < len; i++) {
		if (intervals[i][0] <= one[1]) {
			one[0] = one[0];
			one[1] = max(one[1], intervals[i][1]);
		} else {
			result.push_back(one);
			one = intervals[i];
		}
	}
	result.push_back(one);
	return result;
}

// bool is_exists(vector<vector<int>>& intervals, vector<int> find) {
// 	for (vector<int> one : intervals) {
// 		if (one[1] >= find[1])
// 			return true;
// 	}
// 	return false;
// }

// vector<vector<int>> merge_interval(vector<vector<int>>& intervals) {
// 	vector<vector<int>> result;
// 	int len = intervals.size();
// 	if (len == 0) return result;

// 	sort(intervals.begin(), intervals.end());

// 	vector<int> one;
// 	for (int i = 0; i < len; i++) {
// 		if (!is_exists(result , intervals[i])) {
// 			one = intervals[i];
// 			for (int j = i + 1; j < len; j++) {
// 				if (intervals[j][0] <= one[1]) {
// 					one[0] = one[0];
// 					one[1] = max(one[1], intervals[j][1]);
// 				}
// 			}
// 			result.push_back(one);
// 		}
// 	}
// 	return result;
// }

int main()
{
	int n; cin >> n;

	vector<vector<int>> intervals;

	int x, y;
	for (int i = 0; i < n; i++) {
		cin >> x >> y;
		vector<int> temp{x, y};
		intervals.push_back(temp);
	}

	vector<vector<int>> result = merge_interval(intervals);

	for (vector<int> one : result) {
		cout << one[0] << "," << one[1] << "\n";
	}

	return 0;
}


text:
#include <stdio.h>

int main() {
   int array[10];
   int even[5] = {0, 2, 4, 6, 8};
   int odd[5]  = {1, 3, 5, 7, 9};

   int loop, index, e_len, o_len;

   e_len = o_len = 5;

   index = 0;

   for(loop = 0; loop < e_len; loop++) {
      array[index] = even[loop];
      index++;
   }

   for(loop = 0; loop < o_len; loop++) {
      array[index] = odd[loop];
      index++;
   }

   printf("\nEven:");

   for(loop = 0; loop < e_len; loop++)
      printf(" %d", even[loop]);

   printf("\nOdd:");

   for(loop = 0; loop < o_len; loop++)
      printf(" %d", odd[loop]);

   printf("\nConcat: ");

   for(loop = 0; loop < 10; loop++)
      printf(" %d", array[loop]);

   return 0;
}


text:
// Kadane's Algorithm.
// Find Largest sum contiguous Subarray.

/*
Input:
8
-2 -3 4 -1 -2 1 5 -3

Output:
7
(4,-1,-2,1,5)
*/
#include <bits/stdc++.h>
using namespace std;

// TC: O(n^3)  SC: O(1)
// int max_sum_subarray(int arr[], int n) {
// 	int maxSum = 0;

// 	for (int i = 0; i < n; i++) {
// 		for (int j = i; j < n; j++) {
// 			int sum = 0;
// 			for (int x = i; x <= j; x++)
// 				sum += arr[x];
// 			if (sum > maxSum)
// 				maxSum = sum;
// 		}
// 	}
// 	return maxSum;
// }

// TC: O(n^2)  SC: O(1)
// int max_sum_subarray(int arr[], int n) {
// 	int maxSum = 0;

// 	for (int i = 0; i < n; i++) {
// 		int sum = 0;
// 		for (int j = i; j < n; j++) {
// 			sum += arr[j];
// 			if (sum > maxSum)
// 				maxSum = sum;
// 		}
// 	}
// 	return maxSum;
// }

// TC: O(n)  SC: O(1)
int max_sum_subarray(int arr[], int n) {
	int maxSum = INT_MIN, sum = 0;

	for (int i = 0; i < n; i++)	{
		sum += arr[i];

		if (sum > maxSum)
			maxSum = sum;

		if (sum < 0)
			sum = 0;
	}
	return maxSum;
}

int main()
{
	int n; cin >> n;

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

	cout << max_sum_subarray(arr, n);

	return 0;
}


text:
/***
5. Rotate Array
Easy Accuracy: 50.28% Submissions: 65353 Points: 2
Given an unsorted array arr[] of size N, rotate it by D elements in the counter-clockwise direction.

Example 1:

Input:
N = 5, D = 2
arr[] = {1,2,3,4,5}
Output: 3 4 5 1 2
Explanation: 1 2 3 4 5  when rotated
by 2 elements, it becomes 3 4 5 1 2.
Example 2:

Input:
N = 10, D = 3
arr[] = {2,4,6,8,10,12,14,16,18,20}
Output: 8 10 12 14 16 18 20 2 4 6
Explanation: 2 4 6 8 10 12 14 16 18 20
when rotated by 3 elements, it becomes
8 10 12 14 16 18 20 2 4 6.

Your Task:
Complete the function rotateArr() which takes the array, D and N as input parameters and rotates the array by D elements. The array must be modified in-place without using extra space.

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)

Constraints:
1 <= N <= 107
1 <= D <= N
0 <= arr[i] <= 105

**/
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;

 // } Driver Code Ends

class Solution{
    public:
    //Function to rotate an array by d elements in counter-clockwise direction.
    void rotateArr(int arr[], int d, int n){
        // code here
	int temp[d];
        for(int i=0; i<d; i++)
        {
            temp[i]= arr[i];
        }
        for(int i=d; i<n; i++)
        {
            arr[i-d]= arr[i];
        }
        for(int i=0; i<d;i++){
            arr[n-d+i]= temp[i];
        }
    }

     void rotateArr2(int arr[], int d, int n){
        // code here
	    reverse(arr, arr+d);
            reverse(arr+d, arr+n);
            reverse(arr, arr+n);
    }
};

// { Driver Code Starts.

int main() {
	int t;
	//taking testcases
	cin >> t;

	while(t--){
	    int n, d;

	    //input n and d
	    cin >> n >> d;

	    int arr[n];

	    //inserting elements in the array
	    for(int i = 0; i < n; i++){
	        cin >> arr[i];
	    }
	    Solution ob;
	    //calling rotateArr() function
	    ob.rotateArr(arr, d,n);

	    //printing the elements of the array
	    for(int i =0;i<n;i++){
	        cout << arr[i] << " ";
	    }
	    cout << endl;
	}
	return 0;
}  // } Driver Code Ends


text:
// Minimaize the maximum difference between the Heights

/*
Input:
2 4
1 5 8 10

Output:
5
after modify: {3, 3, 6, 8}
5 = (8-3)

*/
#include <bits/stdc++.h>
using namespace std;

int getMaxDiffercence(int arr[], int n, int k) {
	sort(arr , arr + n);
	int diffMax = arr[n - 1] - arr[0];
	int mn, mx;

	for (int i = 0; i <= n - 2; i++) {

		if (arr[i + 1] < k) continue;

		mn = min(arr[i + 1] - k, arr[0] + k);
		mx = max(arr[i] + k, arr[n - 1] - k);

		diffMax = min(diffMax, mx - mn);
	}
	return diffMax;
}

int main()
{
	int k;  cin >> k;
	int n; cin >> n;

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

	cout << getMaxDiffercence(arr, n , k);

	return 0;
}


text:
/*
	Topic: Segment Tree
	Problem: Finding the maximum and the number of times it appears

	This code provides the template to solve above stated problem using
	segment tree.
*/

// storing pair of number at each vertex in tree
pair<int, int> seg[4*MAXN];

// function to combine 2 child vertex and form parent vertex

pair<int, int> combine(pair<int, int> a, pair<int, int> b) {
    if (a.first > b.first)
        return a;
    if (b.first > a.first)
        return b;
    return make_pair(a.first, a.second + b.second);
}

// function to build segment tree

void build(int a[], int v, int tl, int tr) {
    if (tl == tr) {
        seg[v] = make_pair(a[tl], 1);
    } else {
        int tm = (tl + tr) / 2;
        build(a, v*2, tl, tm);
        build(a, v*2+1, tm+1, tr);
        seg[v] = combine(seg[v*2], seg[v*2+1]);
    }
}

// function to get maximum among the values

pair<int, int> get_max(int v, int tl, int tr, int l, int r) {
    if (l > r)
        return make_pair(-INF, 0);
    if (l == tl && r == tr)
        return seg[v];
    int tm = (tl + tr) / 2;
    return combine(get_max(v*2, tl, tm, l, min(r, tm)),
                   get_max(v*2+1, tm+1, tr, max(l, tm+1), r));
}

// function to update values in segment tree

void update(int v, int tl, int tr, int pos, int new_val) {
    if (tl == tr) {
        seg[v] = make_pair(new_val, 1);
    } else {
        int tm = (tl + tr) / 2;
        if (pos <= tm)
            update(v*2, tl, tm, pos, new_val);
        else
            update(v*2+1, tm+1, tr, pos, new_val);
        seg[v] = combine(seg[v*2], seg[v*2+1]);
    }
}


text:
#include<bits/stdc++.h>

using namespace std;

void build(int a[], int s, int e, int tree[], int index) {
	if (s == e) {
		tree[index] = a[s];
		return;
	}
	int mid = (s + e) / 2;
	build(a, s, mid, tree, 2 * index);
	build(a, mid + 1, e, tree, 2 * index + 1);
	tree[index] = tree[2 * index] + tree[2 * index + 1];
	return;
}

int query(int tree[], int s, int e, int qs, int qe, int index) {
	if ((s >= qs) and (qe >= e)) {
		return tree[index];
	}
	if ((qe < s) or (qs > e)) {
		return 0;
	}
	int mid = (s + e) / 2;
	int left = query(tree, s, mid, qs, qe, 2 * index);
	int right = query(tree, mid + 1, e, qs, qe, (2 * index) + 1);
	return left + right;
}

void update(int tree[], int s, int e, int index, int key, int val) {
	if ((key > e) or (key < s)) return;
	if ((s == e) and (s == key)) {
		tree[index] = tree[index] + val;
		return;
	}
	int mid = (s + e) / 2;
	update(tree, s, mid, 2 * index, key, val);
	update(tree, mid + 1, e, 2 * index + 1, key, val);
	tree[index] = min(tree[2 * index], tree[2 * index + 1]);
	return;
}

int32_t main()
{
	// Input number of queries
	int n;
	cin >> n;
	int a[n];
	int tree[4 * n + 1];
	for(int i=0;i<n;i++) cin >> a[i];
	build(a, 0, n - 1, tree, 1);
	int m;
	cin >> m;
	while (m--) {
		int x, y;
		cin >> x >> y;
		cout << query(tree, 1, n , x, y, 1) << "\n";
	}

	return 0;
}


text:
#include <iostream>
using namespace std;

class stack{
private:
    int size, i = -1, temp, t;
    int arry[50];
    int *top = arry;

public:
    void push(int num){
        //cout << "| " << i << " |";
        if (i > 48){
            cout << "Stack Overflow";
        }
        else{
            *top = num;
            top++;
            i++;
            temp = i;
        }
    }
    char pop(){
        //i = temp;
        if(i <= -1){
            //cout << "Stack Underflow";
            return -1;
        }
        else{
            t = arry[i];
            top--;
            i--;
            return t;
        }
    }
    void display(){
        temp = i;
        //cout << "| " << i << " |";
        while (temp != -1){
            cout << arry[temp] << " ";
            temp--;
        }
    }
    stack copy(stack s) {
        stack st;
        temp = i;
        while (temp != -1){
            st.push(s.pop());
            //cout << "|-" << arry[temp] << " -| ";
            temp--;
        }
        return st;
    }
};

class queue{
public:
    stack s1,s2;
    void enqueue(int num){
        s1.push(num);
    }
    void dequeue(){
        int x = 0;
        //s2 = s1.copy(s1);
        while(x != -1){
            x = s1.pop();
            if(x != -1)
                s2.push(x);
        }
        s2.pop();
        //cout << "Deleted element: " << s2.pop();
        //while(s1.pop() != -1){}
        x = 0;
        while( x != -1){
            x = s2.pop();
            if(x != -1)
                s1.push(x);
        }
        //s1 = s2.copy(s2);
    }
    void display(){

        cout << "\n|-";
        s1.display();
        cout << "-|";

        cout << "\n<-";
        s2.display();
        cout << "->";
    }
};

int main(){
    int n;
    char c;
    queue q1;

    while(1){
        cout << "\nEnter 1 for enqueue and 2 for dequeue : ";
        cin >> c;

        switch (c){
        case '1':
            cout << "\nEnter the Num: ";
            cin >> n;
            q1.enqueue(n);
            q1.display();
            break;
        case '2':
            q1.dequeue();
            q1.display();
            break;
        default:
            cout << "You Entere a wrong Choice, Try Again:";
            break;
        }

    }
}


text:
#include <iostream>
#include <queue>

using namespace std;

// Print the queue
void showq(queue<int> gq)
{
    queue<int> g = gq;
    while (!g.empty()) {
        cout << '\t' << g.front();
        g.pop();
    }
    cout << '\n';
}

// Driver Code
int main()
{
    queue<int> gquiz;
    gquiz.push(10);
    gquiz.push(20);
    gquiz.push(30);

    cout << "The queue gquiz is : ";
    showq(gquiz);

    cout << "\ngquiz.size() : " << gquiz.size();
    cout << "\ngquiz.front() : " << gquiz.front();
    cout << "\ngquiz.back() : " << gquiz.back();

    cout << "\ngquiz.pop() : ";
    gquiz.pop();
    showq(gquiz);

    return 0;
}


text:
#include <bits/stdc++.h>
using namespace std;

int sumOfMinMax(vector<int> arr, int k) {
    int tot = 0, n = arr.size();
    deque<int> dqmax;
    deque<int> dqmin;

    for(int i=0; i<n; i++) {
        if(!dqmax.empty() && dqmax.front() == i-k) dqmax.pop_front();
        if(!dqmin.empty() && dqmin.front() == i-k) dqmin.pop_front();

        while(!dqmax.empty() && arr[dqmax.back()] < arr[i]) dqmax.pop_back();
        while(!dqmin.empty() && arr[dqmin.back()] > arr[i])  dqmin.pop_back();

        dqmax.push_back(i);
        dqmin.push_back(i);

        if(i >= k-1) {
            // cout<<arr[dqmax.front()]<<" + "<<arr[dqmin.front()]<<" = "<<arr[dqmax.front()] + arr[dqmin.front()]<<endl;
            tot += arr[dqmax.front()] + arr[dqmin.front()];
        }
    }

    while(!dqmax.empty()) {
        cout<<dqmax.front()<<" ";
        dqmax.pop_front();
    }
    cout<<endl;
    while(!dqmin.empty()) {
        cout<<dqmin.front()<<" ";
        dqmin.pop_front();
    }

    return tot;
}

int main() {
    vector<int> arr = {2, 5, -1, 7, -3, -1, -2, 3};
    int k = 4;

    cout<<sumOfMinMax(arr, k)<<endl;
    return 0;
}


text:
// Circular Queue Implementation in C
#include <stdio.h>
#define Max_Size 5

int queue[Max_Size];
int front=-1,rear=-1;

// Function to check if queue is full
int isFull(){
    if((front==rear+1)||(front==0&&rear==Max_Size))
        return 1;
    else
        return 0;
}

// Function to check if queue is empty
int isEmpty(){
    if(front==-1)
        return 1;
    else
        return 0;
}

// Function to enqueue a element in a queue
void Enqueue(int item){
    if(isFull())
        printf("\nQueue is Full...\n");
    else{
        if(front==-1)
            front=0;
        rear=(rear+1)%Max_Size;
        queue[rear]=item;
        printf("\n%d has been enqueued..\n",item);
    }
}

// Function to Dequeue a element from a queue
int Dequeue(){
    int item;
    if(isEmpty()){
        printf("\n Queue is Empty..\n");
        return -1;
    }
    else{
        item=queue[front];

        // If queue has only one elment
        if(front==rear){
            front=-1;
            rear=-1;
        }

        else
            front=(front+1)%Max_Size;
        printf("\n%d has been Dequeued from the queue...\n",item);
        return item;
    }
}

// Function to Display the Queue
void display(){
    int i;
    if(isEmpty())
        printf("\nQueue is Empty...\n");
    else{
        printf("\nThe Queue is:\n");
        for(i=front;i!=rear;i=(i+1)%Max_Size){
            printf("%d\t",queue[i]);
        }
        printf("%d ",queue[i]);
    }
}

int main(){
    Dequeue();//Queue is Empty, so it fails

    //5 elements are enqueued
    Enqueue(1);
    Enqueue(2);
    Enqueue(3);
    Enqueue(4);
    Enqueue(5);

    Enqueue(6);//This is not possible because Queue is full

    display();

    Dequeue();
    display();

    Enqueue(7);
    display();

    Enqueue(8);//This is not possible because Queue is full

    return 0;
}


text:
// C++ program to find celebrity
#include <bits/stdc++.h>
#include <list>
using namespace std;

// Max # of persons in the party
#define N 8

// Person with 2 is celebrity
bool MATRIX[N][N] = {{0, 0, 1, 0},
					{0, 0, 1, 0},
					{0, 0, 0, 0},
					{0, 0, 1, 0}};

bool knows(int a, int b)
{
	return MATRIX[a][b];
}

// Returns -1 if celebrity
// is not present. If present,
// returns id (value from 0 to n-1).
int findCelebrity(int n)
{
	//the graph needs not be constructed
	//as the edges can be found by
	//using knows function

	//degree array;
	int indegree[n]={0},outdegree[n]={0};

	//query for all edges
	for(int i=0; i<n; i++)
	{
		for(int j=0; j<n; j++)
		{
			int x = knows(i,j);

			//set the degrees
			outdegree[i]+=x;
			indegree[j]+=x;
		}
	}

	//find a person with indegree n-1
	//and out degree 0
	for(int i=0; i<n; i++)
	if(indegree[i] == n-1 && outdegree[i] == 0)
		return i;

	return -1;
}

// Driver code
int main()
{
	int n = 4;
	int id = findCelebrity(n);
	id == -1 ? cout << "No celebrity" :
			cout << "Celebrity ID " << id;
	return 0;
}


text:
/**
 * @author      : abhj
 * @created     : Friday Oct 01, 2021 17:31:47 IST
 * @filename    : c.cpp
 */

#include "bits/stdc++.h"
#define int          long long int
#define mp           make_pair
#define pb           emplace_back
#define F            first
#define S            second
using vi       =     std::vector<int>;
using vvi      =     std::vector<vi>;
using pii      =     std::pair<int, int>;
using vpii     =     std::vector<pii>;
using vvpii    =     std::vector<vpii>;
using namespace std;
const int inf  =     1e18 + 10;
const int N    =     2e6 + 10;
int n, m, x;
void solve() {
	cin >> n >> m >> x;
	vi a (n), b (m);
	for (int i = 0; i < n; i++)
		cin >> a[i];
	for (int i = 0; i < m; i++)
		cin >> b[i];
	int sum = 0, cnt = 0, temp = 0, i = 0, j = 0;
	while (i < n and sum + a[i] <= x) {
		sum += a[i];
		i++;
	}
	cnt = i;
	while (j < m and i >= 0) {
		sum += b[j];
		j++;
		while (sum > x and i > 0) {
			i--;
			sum -= a[i];
		}
		if (sum <= x and i + j > cnt)
			cnt = i + j;
	}
	cout << cnt;
}

int32_t main() {
	ios_base::sync_with_stdio (false);
	cin.tie (0);
	solve();
	return 0;
}


text:
#include <bits/stdc++.h>
using namespace std;

int main()
{
    cout<<"Stock Span Problem"<<endl;
    cout<<"Enter number of elements"<<endl;
    int n;
    cin>>n;
    int arr[n];
    cout<<"Enter elements"<<endl;
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    stack<pair<int,int>> s;
    vector<int> result;
    pair <int,int> p;
    for(int i=0;i<n;i++)
    {
        if(s.empty())
        {
            result.push_back(1);
        }
        else
        {
            while(s.empty()==false && s.top().second<=arr[i])       //Should be <= because the same element needs to be popped to get the correct number of days
            {
                s.pop();
            }
            if(s.empty())
            {
                result.push_back(1);
            }
            else
            {
                result.push_back(i-s.top().first);
            }
        }
        p.first=i;
        p.second=arr[i];
        s.push(p);
    }
    cout<<"Result"<<endl;
        for(int i=0;i<n;i++)
        {
            cout<<result[i]<<" ";
        }
    return 0;
}


text:
#include <bits/stdc++.h>
using namespace std;

// A structure to represent a stack
class Stack {
public:
    int top;
    unsigned capacity;
    char* array;
};

// function to create a stack of given
// capacity. It initializes size of stack as 0
Stack* createStack(unsigned capacity)
{
    Stack* stack = new Stack();
    stack->capacity = capacity;
    stack->top = -1;
    stack->array
        = new char[(stack->capacity * sizeof(char))];
    return stack;
}

// Stack is full when top is equal to the last index
int isFull(Stack* stack)
{
    return stack->top == stack->capacity - 1;
}

// Stack is empty when top is equal to -1
int isEmpty(Stack* stack) { return stack->top == -1; }

// Function to add an item to stack.
// It increases top by 1
void push(Stack* stack, char item)
{
    if (isFull(stack))
        return;
    stack->array[++stack->top] = item;
}

// Function to remove an item from stack.
// It decreases top by 1
char pop(Stack* stack)
{
    if (isEmpty(stack))
        return -1;
    return stack->array[stack->top--];
}

// A stack based function to reverse a string
void reverse(char str[])
{
    // Create a stack of capacity
    // equal to length of string
    int n = strlen(str);
    Stack* stack = createStack(n);

    // Push all characters of string to stack
    int i;
    for (i = 0; i < n; i++)
        push(stack, str[i]);

    // Pop all characters of string and
    // put them back to str
    for (i = 0; i < n; i++)
        str[i] = pop(stack);
}

// Driver code
int main()
{
    char str[] = "GeeksQuiz";

    reverse(str);
    cout << "Reversed string is " << str;

    return 0;
}


text:
/*
Given an array, find the nearest smaller element G[i] for every element A[i] in the array such that the element has an index smaller than i.

More formally,

    G[i] for an element A[i] = an element A[j] such that
    j is maximum possible AND
    j < i AND
    A[j] < A[i]
Elements for which no smaller element exist, consider next smaller element as -1.

Input Format

The only argument given is integer array A.
*/
vector<int> Solution::prevSmaller(vector<int> &A) {
    vector<int> ans;
    ans.resize(A.size());

    stack<int> st;

    for (int i = 0; i < A.size(); i++) {
        while (!st.empty() && st.top() >= A[i]) st.pop();
        if (st.empty()) {
            ans[i] = -1;
        } else {
            ans[i] = st.top();
        }
        st.push(A[i]);
    }
    return ans;
}


text:
#include<iostream>
#include<stack>
using namespace std;

bool paranChecker(string expr){
    stack<char> s;
    char ch;

    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;
        else{
            if(expr[i] == ')'){
                ch = s.top();
                s.pop();
                if(ch != '('){
                    return false;
                    break;
                }
            }
            else if(expr[i]=='}'){
                ch = s.top();
                s.pop();
                if(ch != '{'){
                    return false;
                    break;
                }
            }
            else{
                ch = s.top();
                s.pop();
                if(ch != '['){
                    return false;
                    break;
                }
            }
        }
    }
    if(s.empty())
        return true;
}

int main(){
    string s;
    cout<<"Input the paranthesis expression: ";
    cin>>s;
    if(paranChecker(s))
        cout<<"Balanced paranthesis\n";
    else
        cout<<"Unbalanced paranthesis\n";
    return 0;
}