<|start_filename|>C/cp/bulbSwitch.c<|end_filename|>
/*
Bulb Swither problem

There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.
On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb.
For the nth round, you only toggle the last bulb.

Return the number of bulbs that are on after n rounds.

Link to problem: https://leetcode.com/problems/bulb-switcher/
*/

#include<stdio.h>

int bulbSwitch(int n) {
	int bulb = 1, ans = 0;
	//A bulb is ON if it is toggled odd times
	while (bulb * bulb <= n) {
		ans++;
		bulb++;
	}
	return ans;
}

int main() {
	int n;
	printf("Enter the no. of bulbs: \n");
	scanf("%d", &n);
	printf("%d \n", bulbSwitch(n));
	return 0;
}

/*
 Sample Input:
 Enter the no. of bulbs:
 4
 Output:
 2
 Time complexity: O(n)
 Space complexity: O(1)
 */


<|start_filename|>Julia/dp/length_longest_common_subsequence.jl<|end_filename|>
"""Length of Longest Common Subsequence problem in Julia

Given two strings, we have to find the largest common subsequence in Julia

The problem can be solved using Dynamic Programming
"""

function lengthoflongestcommonsubsequence(S1, S2)
    # Build a 2D matrix in Bottom-Up manner. Every element
    # dp[i][j] contains the length of the longest common subsequence
    # of S1[0 .. i] and S2[0 .. j].
    n = length(S1)
    m = length(S2)

    # Fill every element of the 2D matrix with 0 as value
    dp = zeros(Int, n + 1, m + 1)

    for i in 1:(n + 1)
        for j in 1:(m + 1)

            # length of LCS when one of the string is empty is zero
            if i == 1 || j == 1
                dp[i,j] = 0

            # If the elements of both the strings match, then
            # the value of LCS increments by one.
            elseif S1[i - 1] == S2[j - 1]
                dp[i,j] = dp[(i - 1),(j - 1)] + 1
            else
            # Either include the last element from one string and exclude it from the other and 
            # compare them and vice versa and pick the one giving the maximum length out of the two 
                dp[i,j] = max(dp[(i - 1),j], dp[i,(j - 1)])
            end
        end
    end
    return dp[(n + 1),(m + 1)]
end


print("Enter the first string: ")
s1 = readline()
print("Enter the second string: ")
s2 = readline()
res = lengthoflongestcommonsubsequence(s1, s2)
print("The length of the longest common subsequence is ")
print(res)


# Time Complexity: O(n * m), where n, m are the size of the given strings
# Space Complexity: O(n * m)

# SAMPLE INPUT AND OUTPUT

# Enter the first string: cuckoo
# Enter the second string: cucumber
# The length of the longest common subsequence is 3


<|start_filename|>C-Plus-Plus/ds/Maximum_Element_of_Binary_Tree.cpp<|end_filename|>
/*

Introduction 
Given a Binary Tree , Print the value of maximum node key 

Argument/Return Type
Input of total no.of nodes is taken
Input of key values of nodes of tree are taken in level order form 
Incase of a null node , -1 is taken as input
A function which returns the maximum element 
If the root is NULL it prints -1

*/

//  Code / Solution

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

//Define Node as structure
struct Node 
{
    int key;
    Node* left;
    Node* right;
};
 
// Function to create a node with 'value' as the data stored in it. 
// Both the children of this new Node are initially null.
struct Node* newNode(int value)
{
    Node* n = new Node;
    n->key = value;
    n->left = NULL;
    n->right = NULL;
    return n;
}

// Function to build tree with given input
struct Node* createTree(vector<int>v)
{
    int n=v.size();
    if(n==0) 
      return NULL;
    vector<struct Node* >a(n);
    //Create a vector of individual nodes with given node values
    for(int i=0;i<n;i++)  
    {
        //If the data is -1 , create a null node
        if(v[i]==-1)  
          a[i] = NULL;
        else 
          a[i] = newNode(v[i]);
    }
    //Interlink all created nodes to create a tree
    //Use two pointers using int to store indexes
    //One to keep track of parent node and one for children nodes
    for(int i=0,j=1;j<n;i++) 
    {
        //If the parent node is NULL , advance children pointer twice
        if(!a[i])
        {
          j=j+2;
          continue;
        } 
        //Connect the two children nodes to parent node
        //First left and then right nodes
        a[i]->left = a[j++];
        if(j<n) 
          a[i]->right = a[j++];
    }
    return a[0];
}

//Function to return maximum value of root key of the given tree
int FindMax(struct Node* root)
{

    // If root is NULL , return -1
    if (root == NULL)
        return -1;
    //Initialise a maximum variable with -1 value 
    // keep track of it traversing the tree in Pre Order Fashion
    int maximum=-1;

    // Create an empty stack and push root to it
    stack<struct Node*> stack;
 
    while (1) 
    {
        while(root)
        {
            //keep visiting left branch , untill we reach extreme left node
            //During each visit , keep updating the maximum value
            maximum=max(maximum,root->key);
            stack.push(root);
            root=root->left;
        }
        if(stack.empty())
           break;
        // Now consider the most recently visited node
        root=stack.top();
        stack.pop();
        //and run Pre Order traversal for its right child 
        root=root->right;
        //repeat the process till there are no more nodes left
    }
    return  maximum;
}
 
// Driver code
int main()
{

    int n;
    cout<<"Enter total no.of nodes of the input Tree ( including NULL nodes ) : ";
    cin>>n;

    vector<int>v(n);
    cout<<"Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces"<<endl;
    for(int i=0;i<n;i++)
    {
        cin>>v[i]; //store the input values in a vector
    }

    //create the tree using input node values  
    struct Node* root=createTree(v); 

    //Call the function and print the result
    cout<<"The maximum value of the node key of given tree is "<<FindMax(root);
    
    return 0; 
}
    
/*
Input:
0 <= node->key < 1000000000
if node is NULL , -1 is entered as it's key

Sample Test Case 1  
Input Binary Tree :                   

               10                                
           /         \                          
         11              12                    
     /       \        /   \               
    5       NULL     6     13             
   / \      /  \    / \   /  \            
  4 NULL  NULL NULL 8  9 10  NULL         


Input Format : 
Example :
Enter total no.of nodes of the input Tree ( including NULL nodes ) : 15
Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces
10 11 12 5 -1 6 13 4 -1 -1 -1 8 9 10 -1

Output Format :
Example : ( Output to the above input example ) 
The maximum value of the node key of given tree is 13

Sample Test Case 2  
Input Binary Tree :                   

                  12                                
          /               \                          
         9                 17                    
     /       \          /      \               
    8       10         15       18             
   / \      /  \      / \      /  \            
  7 NULL  NULL NULL 14  16 NULL  20         


Input Format : 
Example :
Enter total no.of nodes of the input Tree ( including NULL nodes ) : 15
Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces
12 9 17 8 10 15 18 7 -1 -1 -1 14 16 -1 20

Output Format :
Example : ( Output to the above input example ) 
The maximum value of the node key of given tree is 20

Time/Space Complexity
Time Complexity : O(n) 
   Where n is the no.of nodes 
Space Complexity : O(n) 
   Where n is the no.of nodes
*/


<|start_filename|>C-Sharp/sort/QuickSort.cs<|end_filename|>
﻿public class QuickSort
{
    private static int partition(int[] array, int low, int high)
    {
        int pivot = array[high];

        // index of smaller element 
        int i = (low - 1);

        for (int j = low; j < high; j++)
        {
            if (array[j] < pivot)
            {
                i++;
                (array[i], array[j]) = (array[j], array[i]);
            }
        }

        (array[i + 1], array[high]) = (array[high], array[i + 1]);

        return i + 1;
    }

    public static void quickSort(int[] array, int low, int high)
    {
        if (low < high)
        {
            int partitioningIndex = partition(array, low, high);
            quickSort(array, low, partitioningIndex - 1);
            quickSort(array, partitioningIndex + 1, high);
        }
    }


    public static void Sort(int[] array)
    {
        quickSort(array, 0, array.Length - 1);
    }
}



<|start_filename|>Kotlin/Maths/Armstrong.kt<|end_filename|>
/*Kotlin Program to check Given number is an Armstrong Number or not*/
import java.util.*

// Function for check Armstrong Number
fun isArmstrong(num: Int): Boolean {
    var isArmNum = false
    var result : Int= 0
    var temp = num

    // Count No Digits in numbers
    val numberOfDigits = temp.toString().length

    while (temp > 0) {
        val remainder = temp % 10
        result += Math.pow(remainder.toDouble(), numberOfDigits.toDouble()).toInt()
        temp /= 10
    }

    if (result == num) {
        isArmNum = true
    }
    return isArmNum
}


// Main Function, Entry Point of Program
fun main(arg: Array<String>) {
    val sc = Scanner(System.`in`)

    println("Enter Number: ")
    val num: Int = sc.nextInt()

    // Call function to check number is Armstrong
    if (isArmstrong(num)) {
        println("$num is an Armstrong Number")
    } else {
        println("$num is not an Armstrong Number")
    }
}

/**
 * Sample input/output:
 * 
 * Enter Number: 
 * 153
 * 153 is an Armstrong Number
 * 
 * Enter Number: 
 * 224
 * 224 is not an Armstrong Number
 */


<|start_filename|>Java/cp/SudukoSolver.java<|end_filename|>
/**
A backtracking algorithm to solve 9X9 suduko
0's in the input are treated empty cells
Assumption : Given configuration is correct
**/

import java.io.*;
import java.util.*;

public class SudukoSolver {
  public static void display(int[][] board){
    for(int i = 0; i < board.length; i++){
      for(int j = 0; j < board[0].length; j++){
        System.out.print(board[i][j] + " ");
      }
      System.out.println();
    }
  }
  
  // backtracking soln
  public static boolean solve(int[][] board, int i, int j, 
    boolean[][] rows, boolean[][] cols, boolean[][][] boxes) {
      
      if(i == 9)
        return true;
        
      if(board[i][j] == 0) {
          
        for(int k=0; k<9; k++) {
            
          if(rows[k][i] == false && cols[k][j] == false
            && boxes[k][i/3][j/3] == false) {
              board[i][j] = k+1;
              rows[k][i] = true;
              cols[k][j] = true;
              boxes[k][i/3][j/3] = true;
                
              if(solve(board, i+j/8, (j+1)%9, rows, cols, boxes))
                return true;
                
              board[i][j] = 0;
              rows[k][i] = false;
              cols[k][j] = false;
              boxes[k][i/3][j/3] = false;
            }
        }
        
        return false;
      } else
        return solve(board, i+j/8, (j+1)%9, rows, cols, boxes);
    }

  public static void solveSudoku(int[][] board, int x, int y) {
    // write yopur code here
    boolean[][] rows = new boolean[9][9];
    boolean[][] cols = new boolean[9][9];
    boolean[][][] boxes = new boolean[9][3][3];
    
    for(int i=0; i<9; i++)
      for(int j=0; j<9; j++)
        if(board[i][j] != 0) {
          int num = board[i][j]-1;
          rows[num][i] = true;
          cols[num][j] = true;
          boxes[num][i/3][j/3] = true;
        }
        
    solve(board,0,0,rows,cols,boxes);
    display(board);
  }

  public static void main(String[] args) throws Exception {
    Scanner scn = new Scanner(System.in);
    int[][] arr = new int[9][9];
    for (int i = 0; i < 9; i++) {
      for (int j = 0; j < 9; j++) {
        arr[i][j] = scn.nextInt();
      }
    }

    solveSudoku(arr, 0, 0);
  }
}

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

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

The size of input is fixed, so the complexity does not change
**/

<|start_filename|>Go/math/Kaprekar_Number/kaprekarnumber.go<|end_filename|>
/* This is a program in go language to check if the number given is kaprekar
   number or not. A kaprekar number is a number where sum of the half parts
   of the squared digits of the orginal number is same as the input number.
   Example : 9 -> 81 -> 8+1 -> 9
   So, 9 is a kaprekar number.
*/

package main

import (

  "fmt"
  "math"

)

//global variables we use
var n int
var digits int
var square int
var sum int

// This function calculates the count of the digit we send to it
func digitcnt(){

  digits = 0
  for square != 0 {

     digits += 1
     square = square/10
  }

  square = n*n
}

// This function tells us if a number is a kaprekar number or not
func kaprekar(n int) int {

   // Base case
   if(n == 1) {
     fmt.Printf("The given number is a kaprekar number!")
     return 1;

   }

   // calling the digits count
   digitcnt()

   //here we calculate if the number is kaprekar or not
   for i:=1;i<digits;i++  {

      //To avoid the numbers like 10,100..as they are not kaprekar numbers
      res := int(math.Pow(10.0,float64(i)))

      if (res == n){
          continue
      }

      // calculating the sum of the 2 half
      sum = (square/res) + (square%res)
      if (sum == n) {
         fmt.Printf("The given number is kaprekar number!")
         return 1;

      }

   }

   // if the above sum != n then n is not kaprekar number
   fmt.Printf("The given number is not a kaprekar number!")
   return 0;

}

//driver function
func main() {

  //Scanning the input here
  fmt.Print("Enter the number :")
  fmt.Scanln(&n)

  square = n*n

  //callingg kaprekar function
  kaprekar(n)

}

/* Sample I/O :
    
   a) Is a kaprekar number :   

   Enter the number :297
   The given number is kaprekar number!

   b) Is not a kaprekar number :

   Enter the number :3
   The given number is not a kaprekar number!    
*/



<|start_filename|>C-Plus-Plus/ds/Binary_Tree_Print_All_Root_To_Leaf_Paths.cpp<|end_filename|>
/*

Introduction 
Given a Binary Tree ,Print all its root to leaf paths

Argument/Return Type
Input of total no.of nodes is taken
Input of key values of nodes of tree are taken in level order form 
Incase of a null node , -1 is taken as input
Function  prints all its root to leaf paths recursively

*/

//  Code / Solution

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

//Define Node as structure
struct Node 
{
    int key;
    Node* left;
    Node* right;
};
 
// Function to create a node with 'value' as the data stored in it. 
// Both the children of this new Node are initially null.
struct Node* newNode(int value)
{
    Node* n = new Node;
    n->key = value;
    n->left = NULL;
    n->right = NULL;
    return n;
}

// Function to build tree with given input
struct Node* createTree(vector<int>v)
{
    int n=v.size();
    if(n==0) 
      return NULL;
    vector<struct Node* >a(n);
    //Create a vector of individual nodes with given node values
    for(int i=0;i<n;i++)  
    {
        //If the data is -1 , create a null node
        if(v[i]==-1)  
          a[i] = NULL;
        else 
          a[i] = newNode(v[i]);
    }
    //Interlink all created nodes to create a tree
    //Use two pointers using int to store indexes
    //One to keep track of parent node and one for children nodes
    for(int i=0,j=1;j<n;i++) 
    {
        //If the parent node is NULL , advance children pointer twice
        if(!a[i])
        {
          j=j+2;
          continue;
        } 
        //Connect the two children nodes to parent node
        //First left and then right nodes
        a[i]->left = a[j++];
        if(j<n) 
          a[i]->right = a[j++];
    }
    return a[0];
}

//Utility Function to print given path
void PrintThisPath(vector<int>path)
{
   for( int i: path )   cout<<i<<" ";
   cout<<endl;
   return ;
}

//Utility Function to Generate paths
void GeneratePaths(struct Node* root, vector<int>path)
{
    if(root==NULL) 
    {
        //A null node is a leaf node obviously
        //Hence print its path
        PrintThisPath(path);
        return;
    }
    //If its not NULL node , append this node to the path array
    path.push_back(root->key);
    // If it is a leaf node , print its path 
    if(root->left==NULL && root->right==NULL)
    {
        PrintThisPath(path);
        return ;
    }
    //else continue generating paths
    GeneratePaths(root->left,path);
    GeneratePaths(root->right,path);
    return ;
}

// Function to print all root to leaf paths
void PrintRootToLeafPaths(struct Node* root)
{
    vector<int>path;
    GeneratePaths(root,path);
}
 
// Driver code
int main()
{

    int n;
    cout<<"Enter total no.of nodes of the input Tree ( including NULL nodes ) : ";
    cin>>n;

    vector<int>v(n);
    cout<<"Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces"<<endl;
    for(int i=0;i<n;i++)
    {
        cin>>v[i]; //store the input values in a vector
    }

    //create the tree using input node values  
    struct Node* root=createTree(v); 

    //Call the function and print the result
    cout<<"All root to leaf paths are "<<endl;
    PrintRootToLeafPaths(root);
    
    return 0; 
}
    
/*
Input:
0 <= node->key < 1000000000
if node is NULL , -1 is entered as it's key

Sample Test Case 1  
Input Binary Tree :                   

               1                                
           /         \                          
         2              11                    
     /       \        /   \               
    3        5       12    13             
   / \      /  \    / \   /  \            
  4 NULL    6  7    8  9 NULL  4         


Input Format : 
Example :
Enter total no.of nodes of the input Tree ( including NULL nodes ) : 15
Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces
1 2 11 3 5  12 13 4 -1 6 7 8 9 -1 4

Output Format :
Example : ( Output to the above input example ) 
All root to leaf paths are 
1 2 3 4
1 2 3
1 2 5 6
1 2 5 7
1 11 12 8
1 11 12 9
1 11 13
1 11 13 4

Sample Test Case 2  
Input Binary Tree :                   

                  12                                
          /               \                          
         9                 17                    
     /       \          /      \               
    8       10         NULL    18                                


Input Format : 
Example :
Enter total no.of nodes of the input Tree ( including NULL nodes ) : 7
Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces
12 9 17 8 10 -1 18 

Output Format :
Example : ( Output to the above input example ) 
All root to leaf paths are 
12 9 8
12 9 10
12 17
12 17 18

Time/Space Complexity
Time Complexity : O(n) 
   Where n is the no.of nodes 
Space Complexity : O(n) 
   Where n is the no.of nodes
*/


<|start_filename|>Java/ds/StackUsingQueue.java<|end_filename|>
/* Java Program to implement a stack using two queues
by making the push operation costly*/

import java.util.*;

public class StackUsingQueue {
    static class Stack {
        // the 2 queues
        Queue<Integer> qu1 = new LinkedList<>();
        Queue<Integer> qu2 = new LinkedList<>();

        // storing current size
        int currentSize;

        Stack() {
            currentSize = 0;
        }

        void push(int num) {
            currentSize++;

            // first, push num into an empty qu2
            qu2.add(num);

            // now we push the other elements from qu1 to qu2
            while (!qu1.isEmpty()) {
                qu2.add(qu1.peek());
                qu1.remove();
            }
        }

        void pop() {
            if (qu2.isEmpty()) {
                return;
            }

            // remove element and reduce size if qu2 not empty
            qu2.remove();
            currentSize--;
        }

        int top() {
            if (qu2.isEmpty()) {
                return -1;
            }

            // return the top element
            return qu2.peek();
        }

        int size() {
            return currentSize;
        }
    }

    public static void main(String[] args) {
        Stack stack = new Stack();

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter size:");
        int size = sc.nextInt();
        System.out.println("Enter the numbers:");
        for (int i = 0; i < size; i++) {
            stack.push(sc.nextInt());
        }
        sc.close();

        System.out.println("Current Size:" + stack.size());
        for (int i = size; i > 0; i--) {
            System.out.println(stack.top());
            stack.pop();
        }
        System.out.println("Current Size:" + stack.size());
    }
}

/**
 * Sample input/output:
 * 
 * Enter size:
 * 5
 * Enter the numbers:
 * 5
 * 4
 * 3
 * 2
 * 1
 * Current Size:5
 * 5
 * 4
 * 3
 * 2
 * 1
 * Current Size:0
 * 
 * Time complexity: O(n) for push, O(1) for pop
 * Space complexity: O(n)
 */


<|start_filename|>C/other/window_sliding_technique.c<|end_filename|>
/*
Given an array of N elements and a value K (K <= N) ,
calculate maximum summation of K consecutive elements in the array.
We can solve this problem by using Sliding Window Technique.
This technique will allow us to solve this problem in O(N)
*/

#include <stdio.h>

// This max_sum_by_sliding_window function will give us maximum sum
int max_sum_by_sliding_window(int ar[] , int N , int K)
{
    int sum = 0;
    if(N == K)
    {
        // max_sum will be the sum of all elements of array.
        for(int i = 0; i < N; i++)
        {
            sum += ar[i];
        }
        return sum;
    }
    if(N > K)
    {
        // calculate sum of first window of size K
        int max_sum = 0, win_sum = 0;
        for(int i = 0; i < K; i++)
            max_sum += ar[i];

        /*calculate sum of remaining windows
         by removing elements from first window simultaneously
         add elements to current window */
        win_sum = max_sum;
        for(int i = K; i < N; i++)
        {
            win_sum += (ar[i] - ar[i - K]);
            if(win_sum > max_sum)
            {
                max_sum = win_sum;
            }
        }
        return max_sum;
    }
}
int main()
{
    int N, K;
    printf("Enter array size and value\n");
    scanf("%d %d", &N, &K);
    int ar[N + 1];
    printf("Enter array elements \n");
    for(int i = 0; i < N; i++)
    {
        scanf("%d", &ar[i]);
    }
    int solve = max_sum_by_sliding_window(ar, N , K);
    printf("maximum summation of K consecutive elements in the array is: \n");
    printf("%d \n", solve);
}

/*
Standard Input and Output

1. if N == K
Enter array size and value
5 5
1 2 3 4 5
maximum summation of K consecutive elements in the array is:
15

2. if N > K
Enter array size and value
5 3
5 2 -1 0 3
maximum summation of K consecutive elements in the array is:
6

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

*/


<|start_filename|>Java/cp/Prime.java<|end_filename|>
// check whether a number is Prime or not without recursion

import java.util.Scanner;
class Prime
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter a number : ");
        int n=(int)Math.abs(sc.nextInt());
        int c=0;
        for(int i=2;i<n;i++)
        if (n%i==0)
        c++;
        System.out.println(n+((c==0)?" is a Prime Number." :" is not a Prime Number."));
    }
}

// Contributed By ErzaTitani-2001

/*
Sample Input and Output :
Input :
Enter a number : 13
Output :
13 is a Prime Number.
Space  Complexity : O(1)
Time Complexity : O(n)
*/


<|start_filename|>Java/cp/RatInAMaze.java<|end_filename|>
/*
__Rat In A Maze Problem__
Given a maze in the form of a matrix of size m * n. Each cell is either clear or blocked denoted by 1 and 0 respectively.
A rat sits at the top-left cell (matrix[0][0]) and there exists a block of cheese at the bottom-right cell (matrix[m-1][n-1]). Both these cells are guaranteed to be clear.
Find if the rat can get the cheese if it can move only in one of the two directions - down and right. It can’t move to blocked cells.

Input:
2 integers m and n denoting rows and columns
Next m lines contain n space-separated integers which are either 0 or 1

Output:
single line containing 1 or 0 based on whether the rat can get the cheese or not respectively.
*/

import java.util.*;

public class RatInAMaze{

    //global variable to store whether possible to reach cheese
    static boolean solution = false;
	
    //check if position maze[i][j] is free and lies on the grid
	private static boolean safestate(int[][] maze, int m, int n, int i, int j){
		if(i >= m || j>= n || maze[i][j]!=1) return false;
		return true;
	}

	private static void CheeseFinder(int[][] maze, int m, int n, boolean[][] visited, int i, int j){
		//base case
        if(i == m-1 && j == n-1){
            solution=true; 
            return;
        }
        //mark current position as visited
		visited[i][j] = true;
        //move down (backtracking)
		if(safestate(maze,m,n,i+1,j) && !visited[i+1][j]) CheeseFinder(maze, m,n,visited,i+1,j);
        //move right (backtracking)
		if(safestate(maze,m,n,i,j+1) && !visited[i][j+1]) CheeseFinder(maze,m,n,visited,i,j+1);
		visited[i][j] = false;
		return;
	}

	public static boolean canGetCheese(int[][] maze){
		solution = false;
		int m = maze.length;
		int n = maze[0].length;
		boolean[][] visited = new boolean[m][n];
		CheeseFinder(maze, m, n, visited, 0, 0);
		if(!solution) return false;
		return true;
	}

    public static void main(String[] args){
        Scanner inp = new Scanner(System.in);
        int m = inp.nextInt();
        int n = inp.nextInt();
        int[][] maze = new int[m][n];
        for(int x = 0; x < m; x++){
            for(int y = 0; y < n; y++){
                maze[x][y] = inp.nextInt();
            }
        }
        boolean PossibleToGetCheeese = canGetCheese(maze);
        if(PossibleToGetCheeese) System.out.println("1");
        else System.out.println("0");
        inp.close();
    }
}

/*Sample I/O
Sample 1
4 4
1 1 0 0
1 1 1 1
0 1 0 1
0 1 0 1

1   (Output)

Sample 2
4 4
1 1 0 0
1 1 1 1
0 1 1 0
0 1 0 1

0    (Output)

Time Complexity = O(2^(n^2))
Space Complexity = O(n^2)
*/


<|start_filename|>Java/ds/Queuell.java<|end_filename|>
//Queue implemetation Its readme file in wiki
import java.util.*;
import java.lang.*;
class myq<E> {
    static class Node<E>{
        E data;
        Node<E> next;
        Node(E a){
            this.data=a;
            next=null;
        }
    }
    Node<E> front;
    Node<E> rear;
    int c=0;
    boolean isempty(){
        return front==null;
    }
    void Enqueue(E a){
        Node<E> temp=new Node<E>(a);
        if(isempty()){
            front=temp;
            rear=temp;
            c++;
            return;
        }
        else{
            rear.next=temp;
            rear=temp;
            c++;
            return;
        }
    }
    E Dequeue() throws Exception{
        Node<E> t;
        if (isempty()){
            throw new Exception("EEEEEmpty");
        }
        else if(c==1){
            t=front;
            front=null;
            rear=null;
            c--;
        }
        else{
            t=front;
            front=front.next;
            c--;
        }
        return t.data;
    }
    E Front(){
        if (isempty()){
            return null;
        }
        else{
            return front.data;
        }
    }
    E Rear(){
        if (isempty()){
            return null;
        }
        else{
            return rear.data;
        }
    }
}
public class Queuell {
    public static void main(String[] args) throws  Exception{
        myq<Integer> qe = new myq<Integer>();
        qe.Enqueue(10);
        qe.Enqueue(20);
        qe.Enqueue(30);
        qe.Enqueue(40);
        System.out.println(qe.Front());
        System.out.println(qe.Rear());
        System.out.println(qe.Dequeue());
        System.out.println(qe.Dequeue());
        System.out.println(qe.Front());
        System.out.println(qe.Dequeue());
        System.out.println(qe.Dequeue());
        System.out.println(qe.Dequeue());

    }
}
/*
output:
10
40
10
20
30
30
40
Exception in thread "main" java.lang.Exception: EEEEEmpty
	at myq.remove(Queuell.java:37)
	at Queuell.main(Queuell.java:83)
 */


<|start_filename|>C-Sharp/math/Catalan_Number.cs<|end_filename|>
// Nth Catalan Number 
using System; 
class CatalanNumber 
{ 
    // A recursive function to find 
    // nth catalan number 
    static int catalan(int n) 
    { 
        int res = 0; 
        
        // Base case 
        if (n <= 1) 
        { 
            return 1; 
        } 
        for (int i = 0; i < n; i++) 
        {
            res += catalan(i) * catalan(n - i - 1); 
        } 
        return res; 
    } 
    
    // Main Function
    public static void Main() 
    { 
        int number;
        Console.Write("Enter the Number: ");
        number = int.Parse(Console.ReadLine());
        Console.Write("Nth Catalan numbers are: ");
        // Catalan Numbers
        for (int i = 0; i < number; i++) 
            Console.Write(catalan(i) + " "); 
    } 
} 

/*
Input:
Enter the Number: 4
Output:
Nth Catalan numbers are: 1 1 2 5

Time Complexity: O(2^n)
Space Complexity: O(1)
*/


<|start_filename|>C-Plus-Plus/cp/Space_Array.cpp<|end_filename|>
/* PROBLEM LINK: https://www.codechef.com/MARCH21C/problems/SPACEARR

**The rules of the game are as follows:
*Initially, a sequence a1,a2,…,aN is given.
*The players alternate turns.
*In each turn, the current player must choose
*an index i and increment ai, i.e. change ai to ai+1.
*Afterwards, if there is no permutation p1,p2,…,pN of the
*integers 1 through N such that ai=pi holds for each valid
*i,the current player loses.
*Otherwise, the game continues with the next turn.
*/

// Code
#include<bits/stdc++.h>
using namespace std;
//Function Code to Find Result of Game
int Game(int arr[],int n)
{
	int sum = 0, c = 0;
        for (int i = 0; i < n; i++) {
	//Cheking if index is graeter or less than element of array  at that position
	    if (arr[i] > (i + 1))
	    { 
        // true, increase value of c  i.e. count
		c = 1;                   
		break;
	     }
	//if not,take the sum of difference of index and array at that index.
	    sum += abs(arr[i] - (i + 1));    
	}
	//c is 1 i.e. arrayy is greater than element of array
	if (c == 1) 
	{
	//second player wins.
	    cout << "Second" << endl;       
	}
	else {
	    // if sum is even.
	  if (sum % 2 == 0)    
	   // second is winner.
	    cout << "Second" << endl;  
	  else
          // otherwise first will win.
	    cout << "First" << endl;  
		}
}
//Driver Code
int main() 
{
	//No of test Cases.
	int t;  
	cin >> t;
	while (t--) {
		 // No of elements in array
		int n;     
		cin >> n;
		int arr[n];
		 // i as Index of Array
		for (int i = 0; i < n; i++)           
			cin >> arr[i];		
                 //Sorting the Array
		sort(arr, arr + n);    
		//Finding who will win 
		Game(arr,n);
	}
	return 0;
}
/*
Example Input
4
4
1 2 3 3
4
1 1 3 3
5
1 2 2 1 5
3
2 2 3
Example Output
First
Second
Second
Second

Time complexity: 0.06 sec using above algo, "MAX time complexity can be 1 sec "
Memory used: 6.5 MB uisng above algo, MAx space complexity for his problem is: 50000 Bytes"
*/




<|start_filename|>Java/ds/SegmentTree.java<|end_filename|>
/*Implementation of Segment Tree for a problem where
	we have to find the sum of element from a given range(l,r) 
and also perform the update operation at particular index/*
*/

public class SegmentTree{
	
//	A function for returning the size of the segment Tree
	public static int sizeOfSegmentTree(int n) {
		 
		 int y = (int) (Math.ceil(Math.log(n) / Math.log(2))); 
		 int size = 2 * (int) Math.pow(2, y) - 1; 
	  
	  return size;
	}
	
	
//	A recursive function for creating a segment tree from a given array	
	public static void buildTree(int start,int end,int treeIndex,int arr[],int tree[]) {

		if(start==end) {
			tree[treeIndex]=arr[start];
			return;
		}
		
		int mid=(start+end)/2;
		buildTree(start, mid, 2*treeIndex, arr, tree);
		buildTree(mid+1, end, 2*treeIndex+1, arr, tree);
		
		tree[treeIndex]=tree[2*treeIndex]+tree[2*treeIndex+1];
	}
	
	
//	Function for updating a value at particular index	
	public static void update(int start,int end,int index,int value,int treeIndex,int arr[],int tree[]) {
		
		if(start==end) {
			arr[start]=value;
			tree[treeIndex]=value;
			return;
		}
		
		int mid=(start+end)/2;
		if(index>mid) {
//			right side tree
			update(mid+1, end, index, value, 2*treeIndex+1, arr, tree);
		}else {
//			left side tree
			update(start, mid, index, value, 2*treeIndex, arr, tree);
		}
		
		tree[treeIndex]=tree[2*treeIndex]+tree[2*treeIndex+1];
	}
	
//	Function which return the sum of elements from left index to right index	
	public static int query(int start,int end,int left,int right,int treeIndex,int tree[]) {
		
//		Completely outside
		if(start>right||end<left) {
			return 0;
		}
//		Completely inside
		if(start>=left&&end<=right) {
			return tree[treeIndex];
		}
//		Partial 
		int mid=(start+end)/2;
		
		int leftSum=query(start, mid, left, right, 2*treeIndex, tree);
		int rightSum=query(mid+1, end, left, right, 2*treeIndex+1, tree);
		
		return (leftSum+rightSum);
	}
	
	public static void main(String[] args) {
		
		int arr[]= {1,3,2,4,1,5};
		int n=arr.length;
		
		int size=sizeOfSegmentTree(n);
		
//		Segment Tree
		int tree[]=new int[size];
		buildTree(0, n-1, 1, arr, tree);
		
		System.out.println("Sum of element from 2 to 5 index : "+query(0, n-1, 2, 5, 1, tree));
		
//		Updating value at index 3 in given array to 6
		int index=3;
		int value=6;
		update(0, n-1, index, value, 1, arr, tree);
//		After updation new Array : {1,3,2,6,1,5}
		
		
		System.out.println("Sum of element from 2 to 5 index : "+query(0, n-1, 2, 5, 1, tree));
		
	}

}


<|start_filename|>JavaScript/cp/FirstNegativeIntegerInEveryWindowOfSizeK.js<|end_filename|>
/* Given an array of integers and a an integer k, we are supposed to return an array 
which contains the first negative integer in every window of size k */

/* Function to calculate the first negative integer in every window of size k */
const firstNegativeIntegerInEveryWindowOfSizeK = (array, k) => {

    let window = [];

    /* Generating the initial window */
    for (let i = 0; i < k; i++) {

        /* Storing the index if it is a negative number */
        if (array[i] < 0) {
            window.push(i);
        }
    }

    /* Answer array */
    let ans = new Array(array.length - k + 1);

    /* Storing the answer if there exists a negative number */
    if (window.length > 0) {
        ans[0] = array[window[0]];
    } else {
        ans[0] = 0;
    }

    /* Generating k-1 windows */
    for (let i = k; i < array.length; i++) {

        /* Removing the indices which are out of bound */
        while (window.length > 0 && window[0] < i - k + 1) {
            window.shift();
        }

        /* Storing the index if it is a negative number */
        if (array[i] < 0) {
            window.push(i);
        }

        if (window.length > 0) {
            ans[i - k + 1] = array[window[0]];
        } else {
            ans[i - k + 1] = 0;
        }

    }

    return ans;
}

//Using the readline() function of JavaScript to take input from the user
console.log("Enter the elements of of the array along with the size of the window");

//list is input array
let list = readline()
    .split(" ")
    .map((x) => parseInt(x));

// First n elements represent the elements in the array
let n = list.length-1;

// Last element of the list represents the size of the window k
let k = list[n];

/* Using list slicing and passing the first n elements to the
 function as the first parameter and k as the second parameter */
console.log("Array of first negative integer in every window of size ", k ," is ", 
firstNegativeIntegerInEveryWindowOfSizeK(list.slice(0, n), k));

/*
Example 1:

Input:

-8 2 3 -6 10 2

Output:

Array of first negative integer in every window of size 2 is [-8, 0, -6, -6]

Time Complexity: O(N)
Space Complexity: O(K)
*/



<|start_filename|>Java/cp/Zig_Zag.java<|end_filename|>
import java.util.*;
import java.lang.*;
import java.io.*;

class ZigZag {
    public String convert(String s, int numRows) {
        
        if (numRows == 1 || numRows >= s.length()) return s; 
        
        ArrayList<String> arrLL = new ArrayList<>();
        
        for (int i = 0; i < Math.min(numRows, s.length()); i++)
            arrLL.add("");
        
        int counter = 0;
        boolean b = false;
        int size = Math.min(numRows, s.length());
        for (char c : s.toCharArray()){
            String str = Character.toString(c);
            String initial = "";
           
            if (counter < arrLL.size() || arrLL.get(counter) != "") {
                initial = arrLL.get(counter);
                arrLL.add(counter, initial + str);
                arrLL.remove(counter+1);
                
            }
            if (counter == 0 || counter + 1 == numRows) b = !b;   
            counter += b ? 1 : -1;     // adding -1 in b if b is false 
                                      // adding 1 in b if b is true
        }
        
        String ans = "";
        for (int i =0; i< arrLL.size(); i++){
            ans += arrLL.get(i);
        }
        
        
        return ans;
    }
}

/*
TIME COMPLEXITY: 0(N) where n is size of string
SPACE COMPLEXITY:0(N) where n is size of string
TEST CASE

INPUT
"PAYPALISHIRING"

OUTPUT
"PAHNAPLSIIGYIR"

INPUT
"PAYPALISHIRING"
4

OUTPUT
"PINALSIGYAHRPI"

*/



<|start_filename|>Java/math/HappyNumber.java<|end_filename|>
/* This code checks if a number is a happy number. A number is
   called happy if it becomes 1 after iterating thorugh a several
   number of steps wherein each step the number is replaced by the
   sum of its digits.*/

import java.util.*;
//import java.lang.*;

class HappyNumber{
   
   /*This function takes a number as input and returns
     sum of its digits.*/
   static int sumOfSquares(int n){
      
       int sum = 0;
       while(n != 0){
           /*Taking mod of number with 10 each time
            gives its units place digit. We add its
            square to the sum.*/
           int d = n%10;
           sum += d*d;
           //Replace the number with number / 10.
           n = Math.floorDiv(n,10);
       }

       return sum;
   }   
       
   /*This function takes a number as input and checksif the number is a 
     happy number.*/
   static boolean happyNumber(int n){
       
       int first = n;
       int second = n;

       while(true){

          //The first variable calling sum of digits function once 
          first = sumOfSquares(first);

          //The second variable calling sum of digits function twice
          second = sumOfSquares(second);
          second = sumOfSquares(second);

          /*If the first one equals the second, we break out of the loop. Otherwise,
            it will run into an infinite loop.*/
          if(first == second)
             break;
          else
             continue;    
       }   

       /*The number is happy if at the end of iterations the number
          becomes 1. If it is one, then we return True*/ 
       if(first == 1)
          return true;
       else
          return false; 

   }

   public static void main(String[] args){
     
       Scanner scan = new Scanner(System.in);
       System.out.print("Enter the number :");
       //Taking input from the user 
       int n = scan.nextInt();
       scan.close();       
       
       //checker
       boolean check = happyNumber(n);      
        
       //If the above function returns True, it means number is a happy number
       if(check == true){
          System.out.println("The given number "+n+" is a happy number!");
       }
       else
          System.out.println("The given number "+n+" is not happy number!");   
   }

}
/*
   Simple I/O :
   
   a) Is a happy number!   

   Enter the number :13
   The given number 13 is a happy number! 

   b) Is not a happy number!

   Enter the number :67
   The given number 67 is not happy number!     
*/



<|start_filename|>C-Plus-Plus/ds/BST_from_Preorder_Traversal.cpp<|end_filename|>
//Given an array of integers which represents the preorder traversal of a Binary Search Tree 
//Construct the BST and return its root.

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

//Structure for node contains data, pointer to the left child and pointer to the right child
struct Node{
    int data;
    Node *left;
    Node *right;
};

//Function to create a new node with desired value and return its address
Node* CreateNode (int val){
    Node* new_node = new Node;
    new_node->data = val;
    new_node->left = new_node->right = NULL;
    return new_node;
}

//Function to generate BST from preorder traversal 
//Iterative solution using stack which runs in O(n) time
Node* BstFromPreorder (int pre[], int size){
    stack <Node*> stk;
    //First element of preorder traversal is always the root
    Node *root = CreateNode (pre[0]);     
    Node *p = root;
    //count maintains number of nodes in tree                      
    int count = 1;                        
    //Iterate through the rest of pre[] array
    while (count < size){
        if (pre[count] < p->data)  
        //If the element is less than the element pointed by p 
        {
            Node *temp = CreateNode ( pre[count++] );
            p->left = temp;
            stk.push (p);
            p = temp;
        }
        else 
        {
            //If the element is greater than the element pointed by p and is smaller than the element at top of stack 
            if ((pre[count] > p->data) && ((stk.size()==0) || (pre[count] < stk.top()->data))){
                Node *temp = CreateNode ( pre[count++] );
                p->right = temp;
                p = temp;
            }
            //If the element is greater than element pointed by p and at the top of stack
            else{
                p = stk.top();
                stk.pop();
            }
        }
    }
    return root;  
}

//Function to print inorder traversal of tree
void Inorder (Node* node)  
{  
    if (node == NULL)
    {
        return; 
    }   
    Inorder (node->left);  
    cout << node->data<<" ";  
    Inorder (node->right);  
} 

int main ()  
{  
    int size,pre[30];
    cout << "Enter the number of nodes in tree: ";
    cin >> size;   
    cout << "Enter a valid preorder traversal :";
    for (int i=0 ; i<size ; i++) 
    {
        cin >> pre[i];
    }
    Node *root = BstFromPreorder(pre, size);  
    cout<<"Inorder traversal of the constructed tree: \n"; 
    Inorder(root);  
    return 0;  
}

/*
Time Complexity : O(n)
Space Complexity : O(n)

Sample Input:
Enter the number of nodes in tree:8
Enter a valid preorder traversal :30 20 10 15 25 40 50 45

Sample Output:
Inorder traversal of the constructed tree:
10 15 20 25 30 40 45 50
*/

<|start_filename|>Java/cp/LongestSubarraySum.java<|end_filename|>
/**
 * Longest Subarray Having Sum K
 * Given an array of integers, find the length of the longest sub-array 
 * having sum equal to the given value K.
 */

import java.io.*;
import java.util.*; 
public class LongestSubarraySum {

    public static int findLongestSubarray(int[] numArray, int K) {

        //HashMap containing (sum, index) key:value pairs
        HashMap<Long, Integer> hMap = new HashMap<>(); 

        long sum = 0l; //Stores cumulative sum as we traverse the integer array
        int length = 0; //Stores length of longest valid subarray

        for(int i=0; i<numArray.length; i++) {
            sum += numArray[i]; 

            if(sum == K)
                length = Math.max(length, i+1); 

            //Only the first index of occurrence of a particular sum is stored,
            //as we need to find length of longest valid subarray
            if(!hMap.containsKey(sum)) 
                hMap.put(sum, i); 

            //Checking if HashMap contains (sum-K) as we know that:
            // (sum - (sum - K)) = K, which is the required sum
            if(hMap.containsKey(sum - K))
                length = Math.max(length, i - hMap.get(sum - K)); 
        }

        return length; 
    }
    
    public static void main(String[] args) throws IOException{
        InputStreamReader read = new InputStreamReader(System.in);
	    BufferedReader buf = new BufferedReader(read); 

        //Taking input from user
        System.out.println("Enter length of array of integers: ");
	    int len = Integer.parseInt(buf.readLine());
        System.out.println("Enter array of integers: ");
	    StringTokenizer st = new StringTokenizer(buf.readLine());
	    int numArray[] = new int[len];
	    for(int i=0; i<len; i++) {
	        numArray[i] = Integer.parseInt(st.nextToken()); 
	    } 
        System.out.println("Enter sum: ");
	    int K = Integer.parseInt(buf.readLine()); 
	    
        System.out.print("Length of longest subarray having sum " + K + ": "); 
        System.out.println(findLongestSubarray(numArray, K)); 
    }

}

/*
    Time complexity: O(N)
    Space complexity: O(N) (for the HashMap)

    TEST CASES

    INPUT
    Enter length of array of integers: 
    8
    Enter array of integers: 
    2 1 3 2 1 1 1 3
    Enter sum: 
    4
    OUTPUT
    Length of longest subarray having sum 4: 3

    INPUT
    Enter length of array of integers:
    6
    Enter array of integers:
    -5 8 -14 2 4 12
    Enter sum:
    -5
    OUTPUT
    Length of longest subarray having sum -5: 5

 */


<|start_filename|>Julia/cp/isPowerOf2.jl<|end_filename|>
#= Given a number N check if it is a power of 2 in O(1). We will be 
using bitwise operator to get the calculation.=#

## Function

function isPowerOfTwo(n)
    return (n & (n - 1) == 0)
end

## Input

println("Enter the number : ")
n = readline()
n = parse(Int64, n)

## Calling the function

if (isPowerOfTwo(n))
    println("Its a power of 2")
else
    println("Its not a power of 2")
end

#=
Sample Test Case
Input: 
    Enter a number : 4294967296
Output:
    Its a power of 2
Time complexity: O( 1 ) 
=#


<|start_filename|>Java/other/LetterCodeRecursion.java<|end_filename|>
import java.util.Scanner;

public class LetterCodeRecursion {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.println("Codes will be decoded according to positions of letters, for example: 1=A, 2=B, ..., 26=Z");
        System.out.println("Enter the length of given code:");
        int size = scanner.nextInt();
        int[] arr = new int[size];
        System.out.println("Enter the numbers of the given code (with spaces):");
        for (int i = 0; i < size; i++) {
            arr[i] = scanner.nextInt();
        }
        scanner.close();

        int result = countCodes(arr, size);

        System.out.println("Number of codes:" + result);
    }

    private static int countCodes(int[] arr, int size) {

        // basic situation
        if (size == 1 || size == 0) {
            return 1;
        }

        // for a situation for example 0543
        if (arr[0] == 0) {
            return 0;
        }

        int count = 0; // initialize count

        if (arr[size-1] > 0) {
            // only if the digit under counting is greater than 0
            count = countCodes(arr, size - 1);
        } else {
            // cannot find codes if a digit is 0
            return 0;
        }

        if (arr[size - 2] == 1 || (arr[size - 2] == 2 && arr[size - 1] < 7) ) {
            count += countCodes(arr, size - 2);
        }

        return count;
    }
}

/*
* Sample input/output:
* Codes will be decoded according to positions of letters, for example: 1=A, 2=B, ..., 26=Z
* Enter the length of given code:
* 4
* Enter the numbers of the given code (with spaces):
* 1 2 3 4
* Number of codes:3
*
* (ABCD, LCD, AWD)
*
* Time complexity = O(2^n)
*/


<|start_filename|>Java/other/FindNumbers.java<|end_filename|>
import java.util.HashMap;
import java.util.Scanner;

public class FindNumbers {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter number of elements:");
        int size = scanner.nextInt();
        int[] arr = new int[size];
        System.out.println("Enter array elements:");
        for (int i = 0; i < size; i++) {
            arr[i] = scanner.nextInt();
        }
        scanner.close();

        findNonRepeating(arr, size);
    }

    private static void findNonRepeating(int[] arr, int length) {
        HashMap<Integer, Integer> freq = new HashMap<Integer, Integer>();
        for (int i = 0; i < length; i++) {
            if (freq.containsKey(arr[i])) {
                freq.put(arr[i], freq.get(arr[i]) + 1);
            } else {
                freq.put(arr[i], 1);
            }
        }

        System.out.println("Unique terms are:");
        for (Integer i : freq.keySet()) {
            if (freq.get(i) == 1) {
                System.out.println(i);
            }
        }
    }
}

/*
* Sample input/output
* Enter number of elements:
* 6
* Enter array elements:
* 1 2 3 2 1 4
* Unique terms are:
* 3
* 4
*
* Time and space complexity: O(n)
*/


<|start_filename|>Go/math/areas/2D/Areas2D.go<|end_filename|>
package main

import (
	"fmt"
	"math"
)

// Area of a Rectangle

func rectangle(l, b float64) float64 {
	return l * b
}

// Area of a Square

func square(l float64) float64 {
	return l * l
}

// Area of a Triangle

func triangle(b, h float64) float64 {
	return (b * h) / 2.0
}

// Area of a Circle

func circle(r float64) float64 {
	return math.Pi * math.Pow(r, 2)
}

// Area of a Parallelogram

func parallelogram(b, h float64) float64 {
	return b * h
}

// Area of a Trapezium

func trapezium(a, b, h float64) float64 {
	return (a + b) * h / 2.0
}

func main() {
	fmt.Println(rectangle(3.0, 5.0))
	fmt.Println(square(4.0))
	fmt.Println(triangle(4.0, 6.0))
	fmt.Println(circle(3.5))
	fmt.Println(parallelogram(4.0, 7.0))
	fmt.Println(trapezium(4.0, 3.5, 6.5))
}

// Time Complexity - O(1)
// Space Complexity - O(1)


<|start_filename|>Java/math/Euler's_Totient_function.java<|end_filename|>
/*
Euler's totient function, also known as phi-function ϕ(n), counts the
numberof integers between 1 and n inclusive, which are coprime to n.
*/
import java.util.Scanner;

public class Euler_Totient {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter an integer: ");
		int n = sc.nextInt();

		int temp = n;
		//This gives euler totient function for N
		// Time Complexity: O(N*root(N))
		int ans = n;
		for (int i = 2; i <= n; ++i) {
			if (n % i == 0) {
				ans = ans - ans / i;
				while (n % i == 0)
					n /= i;
			}
		}
		if (n > 1) {
			ans = ans - ans / n;
		}
		n = temp;
		System.out.println("\nThe euler totient function for " + n + " is " + ans);

		//This gives euler totient function from 1 to N
		// Time Complexity: O(N loglogN) - same as Sieve of Eratosthenes
		int phi[] = new int[n + 1];
		for (int i = 0; i <= n; ++i) {
			phi[i] = i;
		}
		for (int i = 2; i <= n; ++i) {
			if (phi[i] == i) {
				for (int j = i; j <= n; j += i) {
					phi[j] = phi[j] - phi[j] / i;
				}
			}
		}
		System.out.println("\nThe euler totient function for all integers from 1 to " + n + " is:\n");
		for (int i = 1; i <= n; ++i) {
			System.out.println(i + " " + phi[i]);
		}
	}
}

/*
OUTPUT
Enter an integer: 10
The euler totient function for 10 is: 4
The euler totient function for all integers from 1 to 10 is:
1: 1
2: 1
3: 2
4: 2
5: 4
6: 2
7: 6
8: 4
9: 6
10: 4
-----
(1,3,7,9) are coprime to 10
*/


<|start_filename|>C/dp/Max_Sum_Rectangle.c<|end_filename|>
//C code to implement maximum sum rectangle in a 2D matrix 

#include <stdio.h>
#include<stdbool.h>
#include<string.h>
#include <limits.h>

int main() {
    
  // R & C are the number of rows and columns 
  int R, C; 
  printf("Input-->\n");
  printf("Enter the row-sze: \n");
  scanf("%d", & R);
  printf("Enter the column-sze: \n");
  scanf("%d", & C);
  int matrix[R][C], temp[R], top, bottom;
  printf("Enter the elements of 2-D matrix :\n");
  for (int ol = 0; ol < R; ol++) {
    for (int inloop= 0; inloop < C; inloop++) {
      scanf("%d", & matrix[ol][inloop]);
    }
  }
  int maxSum = INT_MIN, finalTop, finalBottom, finalRight, finalLeft;

  for (int Left= 0; Left < C; Left++) {
    // Initialize the all elements of temp as 0
    memset(temp, 0, sizeof(temp));
    for (int Right = Left; Right < C; Right++) {
      for (int i = 0; i < R; i++) temp[i] += matrix[i][Right];
      int max = INT_MIN, S = 0, localTop = 0, sum;
      bool flag = false;
      for (int index = 0; index < R; index++) {
        if (temp[index] >= 0) flag = true;
        S = S + temp[index];
        if (S < 0) {
          S = 0;
          localTop = index+ 1;
        } else if (S > max) {
          max = S;
          top = localTop;
          bottom = index;
        }
      }
      if (flag) {
        sum = max;
      } else {
        max = INT_MIN;
        //To find the maximum element in array  
        for (int index = 0; index < R; index++) {
          if (max < temp[index]) {
            max = temp[index];
            top = bottom = index;
          }
        }
        sum = max;;
      }
      // Comparison of  sum with maximum sum 
      if (sum > maxSum) {
        maxSum = sum;
        finalTop = top;
        finalBottom = bottom;
        finalLeft = Left;
        finalRight = Right;
      }
    }
  }
  printf("\nOutput-->\n");
  printf("Maximum sumRectangle is : %d\n", maxSum);

  return 0;
}

/*
 Input-->
 Enter the row-sze: 4
 Enter the column-sze: 5
 Enter the elements of 2-D matrix :
 1 2 -1 -4 -20
 -8 -3 4 2 1
 3 8 10 1 3
 -4 -1 1 7 -6
 
 Output-->
 Maximum sumRectangle is : 29
 
 Time Complexity: O(cols^2 * rows) 
 Space Complexity: O(rows)
 */


<|start_filename|>C-Plus-Plus/other/big_mod_algorithm.cpp<|end_filename|>
/*
Given a number's base and power.
return the number.

base and power can be large as 10^6 to 10^9
so we need to mod with some big number in order to get the number
this can be done by bigmod algorithm
*/

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

// this get_new_number_by_bigmod will give us the new number
long long int get_new_number_by_bigmod(long long int base, long long int power, long long int mod_number)
{
    long long int new_number;
    if(power == 0)
    {
        // no matter what base is , as power is 0 answer 1
        return 1;
    }
    else if(power % 2 == 0)
    {
        /* as power is even,
        we will divide the power each step by 2
        9^18 will be 9^9 , 9^9
        and thus goes on  by recursive call
        */
        new_number = get_new_number_by_bigmod(base , power / 2, mod_number);
        return ((new_number * new_number) % mod_number);

    }
    else
    {  /* as power is odd,
        we will  take power - 1
        9^15 = 9^14 , 9^1
        and thus goes on  by recursive call
        */
        long long int temp = get_new_number_by_bigmod(base , power - 1 , mod_number);
        return ((( base % mod_number)* temp)% mod_number);

    }
}

int main()
{
    cout << "Enter the base number and power number : ";
    long long int base , power;
    scanf("%lld %lld", &base, &power);
    cout << "Enter the mod number: ";
    long long int mod_number;
    scanf("%lld", &mod_number);

    long long int new_number = get_new_number_by_bigmod(base, power, mod_number);

    cout << "After applying Bigmod algorithm the new number is : \n";
    cout << new_number << endl;
}

/*
Standard Input and Output

Enter the base number and power number :
45 67
Enter the mod number: 1000456

After applying Bigmod algorithm the new number is :
595941

Time Complexity : O( log N )
Space Complexity : O( 1 )

*/


<|start_filename|>C-Plus-Plus/math/Word_break.cpp<|end_filename|>
// A backtracking problem for checking whether a given string can be segmented into space seperated words in dictionary
#include <iostream>
#include<string.h>
using namespace std;

//This function is used for checking whether a word is present in our array or not
int presentInArray(string &word){
    string arr[] = {"micro","soft","hi","ring","hiring","microsoft"};
    int n = sizeof(arr)/sizeof(arr[0]);
    for(int i=0;i<n;i++){
        if(arr[i].compare(word) == 0){
            return true;
        }
    }
    return false;
}

//this function is used for storing all the words with spaces
void breakingwords(string str, int n, string ans){
    //Process all wordes one by one
    for(int i=1;i<=n;i++){
        string word = str.substr(0,i);
         
        if(presentInArray(word)){
            if(i==n){
                ans += word;
                cout<<ans<<endl;
                return;
            }
        breakingwords(str.substr(i,n-i),n-i,ans + word +" ");
        }
    }
}


// It will Print all possible word breaks of given string
void BreakWords(string str){
    breakingwords(str,str.size(),"");
}

int main() {
    string s;
    cin>>s;
    BreakWords(s);
    return 0;
}

/*
eg.
input - microsofthiring
output - 
micro soft hi ring
micro soft hiring
microsoft hi ring
microsoft hiring
Time Complexity - O(n2)
Space Complexity - O(1)
*/


<|start_filename|>C-Plus-Plus/cp/Rainwaterharvesting.cpp<|end_filename|>
/*
A very popular problem asked in interviews medium difficulty
Apoorvaa has created an elevated roof. She wants to know how much water can she save during rain.

Given n non negative integers representing the elevation map where width of every bar is 1, Find the maximum water that she can save.

Explanation for the Sample input Testcase: 
![image](https://user-images.githubusercontent.com/44130067/94519631-84921880-0248-11eb-8515-416d81534168.png)
So the total units of water she can save is 5 units

**Input Format**
First line contains an integer n. Second line contains n space separated integers representing the elevation map.

**Constraints**
1 <= N <= 10^6

**Output Format**
Print a single integer containing the maximum unit of waters she can save.

**Sample Input**
10
0 2 1 3 0 1 2 1 2 1
**Sample Output**
5
**Explanation**
Refer to the image for explanation. Count the number of cells having water in them.
*/
#include<iostream>
using namespace std;
int maxWater_optimized(int arr[], int n)
{
    int water = 0; // To store the final ans

    int left_max = 0;  // Which stores the current max height of the left side
    int right_max = 0; // Which stores the current max height of the right side

    int lo = 0;     // Counter to traverse from the left_side
    int hi = n - 1; // Counter to traverse from the right_side

    while (lo <= hi)
    {

        if (arr[lo] < arr[hi])
        {

            if (arr[lo] > left_max)
            {
                left_max = arr[lo]; // Updating left_max
            }
            else
            {

                water += left_max - arr[lo]; // Calculating the ans
            }
            lo++;
        }
        else
        {

            if (arr[hi] > right_max)
            {
                right_max = arr[hi]; // Updating right_max
            }
            else
            {
                water += right_max - arr[hi]; // Calculating the ans
            }
            hi--;
        }
    }

    return water;
}
int main() {
	int n,arr[1000000];
	cin >> n;
	for(int i=0;i<n;i++)
	{
		cin >> arr[i];
	}
	int water=maxWater_optimized(arr,n);
	cout<<water;
	return 0;
}


<|start_filename|>C-Sharp/search/LinearSearch.cs<|end_filename|>
﻿public class LinearSearch<T>
{
    public static int Search(T[] array, T element)
    {
        for (int i = 0; i < array.Length; i++)
        {
            if (array[i].Equals(element))
            {
                return i;
            }
        }

        return -1;
    }
}



<|start_filename|>C-Plus-Plus/cp/Merge_Intervals.cpp<|end_filename|>
/*
  Given a 2D vector of intervals where intervals[i]={start_time,end_time} ,
  merge all the overlapping intervals and
  return the array of non-overlapping intervals that cover all the intervals in the input.
*/


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

vector<vector<int>> merge_interval(vector<vector<int>> interval);

int main()
{
    //number of intervals
    int n;
    cin>>n;

    // input 2D vector
    vector<vector<int>> intervals;

    //taking data from user
    int x,y;
    for(int i=0;i<n;i++)
    {
        cin>>x>>y;
        intervals.push_back({x,y});
    }

    vector<vector<int>> result;

    //calling function merge_interval
   result = merge_interval(intervals);

   //displaying output
   for(int i=0;i<result.size();i++)
   {
       cout<<result[i][0]<<","<<result[i][1];
       cout<<endl;
   }

    return 0;
}

vector<vector<int>> merge_interval(vector<vector<int>> interval)
{
    if(interval.size()==0)
        return interval;

    //sorting the vector in ascending order
    sort(interval.begin(),interval.end());

    //for result to store
    vector<vector<int>> merged;

    vector<int> temp = interval[0];

    for(int i=0;i<interval.size();i++)
    {
        //interval[i](start_time) is less than temp(end_time)
        //then it is merged
        if(interval[i][0] <= temp[1])
        {
            if(interval[i][1] >= temp[1])
            temp[1] = interval[i][1];
        }
        //interval[i](start_time) is greater than temp(end_time)
        else
        {
            merged.push_back(temp);
            temp = interval[i];
        }

    }
     //last interval
    merged.push_back(temp);

    return merged;
}


/*
   Time Complexity: O(NlogN) + O(N) ...N is the number of intervals
                    (sorting)  (traversing)
   Space Complexity:O(N)
*/

/*   Examples:

   1)Input:
     3   ...N
     2 4
     3 8
     10 12

    Output:
     2,8
     10,12

*/


<|start_filename|>C-Plus-Plus/cp/Conversion_from_Binary_to_Decimal.cpp<|end_filename|>
/* C++ Program for Conversion of Binary Number to Decimal Number
In this Program only input line contains an integer input 'number'. Its length does not exceed 10.
Here, a function named 'binary_to_decimal' will convert the given binary input into decimal number.
And output contain Decimal Conversion of input in a single line.
*/  
#include<bits/stdc++.h>
using namespace std;
int binary_to_decimal(int number){
    int i, remainder, store, output;    
    remainder=1;
    store=1;
    output=0;  
    for(i=0;number>0;i++){
        //dividing number by 10 to get digits according to place value     
        remainder=number%10;
        //multiplying remainder with power of 2 according to its place value
        store=remainder*(pow(2,i));
        //storing this in 'output' in each iteration
        output=output+store;
        number=number/10;
    }
    return output;
}
int main(){
    int numberInput,l,k;
    cin>>numberInput;
    cout<<binary_to_decimal(numberInput)<<endl;
    return 0;
}

/* SAMPLE
Testcase 1
INPUT   100
OUTPUT  4   
Time Complexity is O(T)    where T is number of digit in 'number'
Space Complexity is O(1)   */


<|start_filename|>C-Plus-Plus/math/counting_divisors_using_sieve_of_eratosthenes.cpp<|end_filename|>
/*
Given a positive integer, count the number of its divisors.

A divisor is a number that divides another number either completely or with a remainder.

Approach used: Extract the prime factors of the given number along with their
respective contributing powers using the sieve of Eratosthenes and then calculate
the divisors by applying basic permutation and combination on these powers.

Explanation : Suppose the prime factorization of the number is a^x1+b^x2+c^x3...and so
on, where a,b,c,etc are its prime factors and x1,x2,x3 their respective powers.
Then, the divisor count is equal to (x1+1)*(x2+1)*(x3+1)....
*/

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

vector<int> prime_sieve(int P[], int n)
{
    P[0] = P[1] = 0;
    P[2] = 1;
    // Mark all odd numbers as prime as even numbers can't be prime.
    for (int i = 3; i < n; i += 2)
    {
        P[i] = 1;
    }
    // Sieve
    for (int i = 3; i < n; i += 2)
    {
        // If the current number is marked 1,it is prime.
        // Hence,its multiples can't be prime.
        if (P[i] == 1)
        {
            // Marking multiples of i, not prime.
            for (int j = i * i; j < n; j += 2 * i)
            {
                P[j] = 0;
            }
        }
    }
    vector<int> primes;
    primes.push_back(2);
    for (int i = 3; i < n; i += 2)
    {
        if (P[i] == 1)
        {
            primes.push_back(i);
        }
    }
    return primes;
}

int count_of_divisors(vector<int> primes, int num)
{
    int i = 0, final_ans = 1;
    int flag = primes[0];
    while (flag * flag <= num)
    {
        if (num % flag == 0)
        {
            // Counting powers of prime factors
            int count = 0;
            while (num % flag == 0)
            {
                count++;
                num = num / flag;
            }
            final_ans = final_ans * (count + 1);
        }
        i++;
        flag = primes[i];
    }
    // If the number is not equal to 1,then it itself is a prime.
    if (num != 1)
    {
        final_ans = final_ans * 2;
    }
    return final_ans;
}

int main()
{
    // Precomputational step
    // Use a helper array to extract prime numbers into a vector using prime sieve.
    int helper_arr[10000] = { 0 };
    vector<int> primes = prime_sieve(helper_arr, 10000);

    int num;
    cout << "Enter the number whose divisor count is to be found : " << endl;
    cin >> num;
    cout << "Count of divisors : " << endl;
    cout << count_of_divisors(primes, num) << endl;

    return 0;
}


/*Example

Sample input: Enter the number whose divisor count is to be found : 60
Sample Output: Count of divisors : 12

Explanation: 60=2^2+3^1+5^1
             Divisor count=(2+1)*(1+1)*(1+1)=12

Time complexity : O(log N)(If we ignore the precomputation time complexity of O(N log(log N))
Space complexity : O(N) (Due to sieve preparation)
*/


<|start_filename|>C-Plus-Plus/other/check_set_clear_bit.cpp<|end_filename|>
#include<bits/stdc++.h>
using namespace std;
//This functions returns the least significant bit
int check_bit(int n){
    return n&1;
}
//This functions sets the given bit from the right
//example n=11001 pos=2 , makes -> 11011 i.e second bit from right
int set_bit(int n,int pos){
    int mask =1;
    mask<<=pos-1;
    return n|mask;
}
//Returns the complement of a number
int complement(int n, int bits){
    return ((1<<bits)-1) ^ n;
}
//Clears the bit at given position from the right
int clear_bit(int n,int pos){
    int mask = 1;
    mask<<=pos-1;
    int bits = floor(log2(n)) + 1;
    mask = complement(mask,bits);
    return n&mask;
}
int main(){
    int n,pos; cin>>n>>pos;
    cout<<check_bit(n)<<endl;
    cout<<set_bit(n,pos)<<endl;
    cout<<clear_bit(n,pos)<<endl;
    return 0;
}
/*
Input:
25 1
Output
1
25
24

Time complexity: O(1) for all
Space complexity: O(1) for all
*/


<|start_filename|>JavaScript/ds/LinkedList.js<|end_filename|>
/**
 * Nodes are the "elements" of a linked list.
 * They are represented as objects here to include the "next node" property
 */
class Node {
  constructor(data) {
    this.data = data;
    this.next = null;
  }
}

/**
 * With nodes defined, we can create a LinkedList class
 * that will use nodes to instantiate LinkedList objects.
 */
class LinkedList {
  // TODO: Re-implement the constructor to receive an array, and then convert it to a LinkedList.
  constructor(head = null) {
    this.head = head;
  }

  size() {
    let count = 0;
    let node = this.head;
    while (node) {
      count++;
      node = node.next;
    }
    return count;
  }

  clear() {
    this.head = null;
  }

  getLast() {
    let lastNode = this.head;
    if (lastNode) {
      while (lastNode.next) {
        lastNode = lastNode.next;
      }
    }
    return lastNode;
  }

  getFirst() {
    return this.head;
  }
}

// Just a simple implementation of the Linked List

// First, we define the values.
const arr = [0, 1, 2, 3, 4];

// Second, we create the nodes.
const firstNode = new Node(arr[0]);
const secondNode = new Node(arr[1]);
const thirdNode = new Node(arr[2]);
const fourthNode = new Node(arr[3]);
const fifthNode = new Node(arr[4]);

// Third, we establish the linking between nodes.
firstNode.next = secondNode;
secondNode.next = thirdNode;
thirdNode.next = fourthNode;
fourthNode.next = fifthNode;

// Fourth, we instantiate a LinkedList only using the first node (head).
const linkedList = new LinkedList(firstNode);

// Calling some Linked List methods.
console.log("After populating the linked list:");
console.log("First node: ", linkedList.getFirst());
console.log("Last node: ", linkedList.getLast());
console.log("List size: ", linkedList.size());

// Clearing linked list
console.log("\nAfter clearing the list:");
linkedList.clear();
console.log("First node: ", linkedList.getFirst());
console.log("Last node: ", linkedList.getLast());
console.log("List size: ", linkedList.size());

/**
 * This is just a simple implementation. My challenge for you now,
 * is to implement the LinkedList constructor in such way, that when
 * you pass an array as argument, it will automate the node creation
 * and linking. Good luck!
 */


<|start_filename|>Java/cp/Min_Element_Rotated_array.java<|end_filename|>
import java.util.*;
class Min_Element_Rotated_array {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the elements");
        int min = sc.nextInt();
        while (sc.hasNextInt()) {
            int num = sc.nextInt();
            if (num < min)
                min = num;
        }
        System.out.println(" Minimum element in the list : " + min);
    }
}
/* Sample Input and Output :
 * Minimum element in the list : 2
Enter the elements
3
4
5
1
2

 Minimum element in the list : 1
Time Complexity : O(n)
Space Complexity : O(1)
 */


<|start_filename|>C/sort/shaker_sort.c<|end_filename|>
/* Shaker Sort In C
The algorithm extends the bubble sort by operating in two directions
*/
#include <stdio.h>

void shakersort(int[], int);
void swap(int *, int *);
int main()
{
	int num, i, arr[10000];
	printf("Enter the number of elements:");
	scanf("%d", &num);
	for (i = 0; i < num; i++)
	{
		scanf("%d", &arr[i]);
	}

	printf("Enter the elements to be sorted:");
	for (i = 0; i < num; i++)
	{
		printf("%d ", arr[i]);
	}

	shakersort(&arr[0], num);
	printf("\n");
	printf("Sorted Array:");
	for (i = 0; i < num; i++)
	{
		printf("%d ", arr[i]);
	}

	return 0;
}
// Sorts the given array bidirectionally
void shakersort(int arr[], int num)
{
	int end, start, i;
	end = num - 1;
	start = 1;
	// Bidirectional comparison
	while (start <= num / 2)
	{
		for (i = start - 1; i < end; i++)
		{
			if (arr[i] > arr[i + 1])
				swap(&arr[i], &arr[i + 1]);
		}

		end = end - 1;
		for (i = end; i >= start; i--)
		{
			if (arr[i] < arr[i - 1])
				swap(&arr[i], &arr[i - 1]);
		}

		start = start + 1;
	}
}
// Swaps two elements
void swap(int *x, int *y)
{
	int temp;
	temp = *x;
	*x = *y;
	*y = temp;
}

/*
Sample Output
Enter the number of elements: 13
Enter the elements to be sorted:86 74 -2 -9 67 25 33 86 17 -8 42 10 0
Sorted Array:-9 -8 -2 0 10 17 25 33 42 67 74 86 86  

Complexities
Worst case performance:O(n^2)
Best case performance:O(n)
Average performance: O(n^2)
Worst Case Space complexity: O(1) 
*/



<|start_filename|>C-Plus-Plus/other/odd_even_linked_list.cpp<|end_filename|>
/* Program to rearrange a given linked list so that all odd indexed nodes are arranged first,
   followed by the even indexed nodes in one iteration through the linked list*/

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

class ListNode {
public:
    int val;
    ListNode* next;
};

ListNode* odd_even_linked_list(ListNode* head)
{

    //if linked list has only 1 node, no rearrangement required
    if (head->next == NULL) {
        return head;
    }

    //Head of the LinkedList containing odd indexed elements
    ListNode* head_odd = new ListNode();

    //Head of the LinkedList containing even indexed elements
    ListNode* head_even = new ListNode();

    head_odd = head;
    head_even = head->next;

    //Counter for odd indexed nodes
    ListNode* counter_odd = head_odd;
    //Counter for even indexed nodes
    ListNode* counter_even = head_even;

    while ((counter_odd->next) != NULL && (counter_even->next) != NULL) {
        //pointer to next odd indexed element
        counter_odd->next = counter_odd->next->next;
        //pointer to next even indexed element
        counter_even->next = counter_even->next->next;
        counter_odd = counter_odd->next;
        counter_even = counter_even->next;
    }

    //join the 2 linked list
    counter_odd->next = head_even;

    return head;
}

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

    int node_value;
    cin >> node_value;

    ListNode* head = new ListNode();

    head->val = node_value;
    head->next = NULL;

    ListNode* temp = head;

    for (int i = 1; i < nodes; i++) {
        cin >> node_value;
        ListNode* new_node = new ListNode();
        new_node->val = node_value;
        temp->next = new_node;
        new_node->next = NULL;
        temp = temp->next;
    }

    ListNode* head_new = odd_even_linked_list(head);

    //print the rearranged linked list
    temp = head_new;
    while (temp != NULL) {
        cout << temp->val << " ";
        temp = temp->next;
    }
}

/*  Testcase 1:
    n= 7
    Input Linked List: 1->2->3->4->5->6->7
    Output Linked List: 1->3->5->7->2->4->6

    Testcase 2:
    n= 4
    Input Linked List: 2->4->6
    Output Linked List: 2->6->4

    Time Complexity: O(n)  (We have traversed the linked list just once)
    Space Complexity: O(1) (No extra space is used)*/


<|start_filename|>C-Plus-Plus/graphs/Largest_distance_between_2_nodes_in_a_tree.cpp<|end_filename|>
/*Given an unweighted rooted tree which consists of N nodes, find the largest distance between 2 nodes in a tree.
Since this is a tree, there will be a unique path between any 2 nodes.
The tree is given in the form of an array A, there is an edge connecting A[i] and i.
A[0] will be -1, since it denotes the root node

The approach is to use DFS here, first we will find the node which is at farthest distance from the root node by DFS
After this we will take this new node and run DFS from it to the farthest node.
The distance between these 2 nodes is the answer
It can be proven that the node found to be farthest from root node, has to be one of the end points of the largest distance path*/

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

/*We maintain a visited array to keep track of what all nodes have already been visited
  And an adjacency list(adj) can be formed using the given input array(A)*/
int visited[40010];
vector<int> adj[40010];
vector<int> A;

//mx stores the answer at all times
int mx;

/*DFS function runs a DFS from the source node (node), and keeps updating the max distance until all nodes are visited
  nd stores the node which is found to be at farthest distance from the source node (node)*/
void dfs(int node, int dist, int& nd)
{
    if (dist > mx) {
        mx = dist;
        nd = node;
    }

    visited[node] = 1;
    for (int i = 0; i < adj[node].size(); i++) {
        //If any node in the source node's adjacency list is found to be unvisited, we call a DFS with that node as a source and distance dist+1
        int s = adj[node][i];
        if (visited[s]) {
            continue;
        }
        dfs(s, dist + 1, nd);
    }
}

//solve function calls DFS twice as discussed above
int solve(int n)
{

    //If there is only one node, then the largest distance from that node is 0
    if (n == 1) {
        return 0;
    }

    //Call DFS from root node
    mx = 0;
    int nd = -1;
    dfs(0, 0, nd);

    //Reset the visited array
    for (int i = 0; i < n; i++) {
        visited[i] = 0;
    }

    //Call DFS from the node found to be farthest from root
    mx = 0;
    int md = -1;
    dfs(nd, 0, md);

    return mx;
}

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

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

    //Generate Adjacency list from input array A
    for (int i = 0; i < n; i++) {
        if (A[i] == -1) {
            continue;
        }
        adj[i].push_back(A[i]);
        adj[A[i]].push_back(i);
    }

    cout << solve(n) << endl;
}

/*Test Case 1:
  n= 5
  A= [-1, 0, 0, 0, 3]
  output = 3

  Tree:
        0
      / | \
     1  2  3
            \
             4
  Clearly, largest distance is 3 (from node 1 to 4 or 2 to 4)

  Test Case 2:
  n= 7
  A= [ -1, 0, 0, 1, 2, 1, 5 ]
  output = 5

  Tree:
        0
      /   \
     1     2
    / \      \
   3   5      4
        \
         6
  Clearly, largest distance is 5 (from node 4 to 6)

  Time Complexity: O(n)
  Space Complexity: O(n)*/


<|start_filename|>C-Plus-Plus/other/Find_Common_Element_in_matrix.cpp<|end_filename|>
/*  Find a Common element in rows of a given row-wise sorted matrix. */

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

/* Function to find common element in the matrix */
int solve()
{
    /* Input row = size of row.
       Input col = size of column. */
    int row,col;
    cin >> row >> col;

    /* Input elements in matrix. */
    int a[row][col];
    for (int i = 0; i < row; ++i)
    {
        for (int j = 0; j < col; ++j)
        {
            cin >> a[i][j];
        }
    }
    
    /* Create a hash map to store 
     count of element */
    unordered_map<int, int> count;
  
    for (int i = 0; i < row; i++) {
        
        for (int j = 1; j < col; j++) {

            /* Insert elements of the first row and
               initialize them with a value of 1 */
            if (i == 0) {
                count[a[0][i]] = 1;
            }
            
            /* Check if the current element exists
               in the map and first in the current row */
            if (a[i][j] != a[i][j - 1])
                count[a[i][j]]++;
        }
    }
      
    /* Return the element having a count 1 */
    for (auto element : count) {
        if (element.second == row)
            return element.first;
    }

    /* Return the element having a count not equal to 1 */
    return -1;
}

int main()
{
    int common = solve();

    if (common == -1)
        cout << "No Common element"<< endl;
    else
        cout << "Common element is : " << common << endl;
    return 0;
}

/*
Test cases :
    
    Input 1 :

        4 5
        1 2 3 4 5
        2 4 5 8 10
        3 5 7 9 11
        1 3 5 7 9

    Output 1 :

        Common element is : 5

    Input 2 :

        4 5
        2 4 3 8 7
        1 3 5 6 8
        1 2 3 1 3
        4 5 0 2 3
    
    Output 2 :
    
        No Common element
    
    Time complexity: O(r*c)
    Space Complexity: O(1)
*/


<|start_filename|>C-Plus-Plus/ds/Trie_implementation.cpp<|end_filename|>
/*Tries are tree based structures used for efficient 
retrieval of key form huge set of strings.

This is a basic implementation of Trie in which strings are inserted and 
then there are some queries to find if strings are present in trie or not.

Time Complexity for insert and find function: 
O(l) where l is the length of word. 
Space complexity: O(n*m) where n is number of keys 
and m=max(l) i.e max length of input strings.*/

#include<bits/stdc++.h>
using namespace std;
//Trie Node
class Node{
public:
	char data;
	//to store children of node
	unordered_map<char,Node*> children;
	bool terminal;
	Node(char d){
		data=d;
		terminal=false;
	}
};

class Trie{
Node*root;
public:
	Trie(){
		root=new Node('\0');
	}
	//to insert strings in Trie
	void insert(string w){
		Node*temp=root;
		for(int i=0;w[i]!='\0';i++){
			char ch=w[i];
			if(temp->children.count(ch)){
				temp=temp->children[ch];
			}
			else{
				Node*n=new Node(ch);
				temp->children[ch]=n;
				temp=n;
			}
		}
		temp->terminal=true;
	}
	//To find if string is present or not
	bool find(string w){
		Node*temp=root;
		for(int i=0;w[i]!='\0';i++){
			char ch=w[i];
			if(temp->children.count(ch)==0){
				return false;
			}
			else{
				temp=temp->children[ch];
			}
		}
		return temp->terminal;
	}
	//to delete a string from trie
	void deletion(string w){
		Node*temp=root;
		for(int i=0;w[i]!='\0';i++){
			char ch=w[i];
			if(temp->children.count(ch)==0){
				return;
			}
			else{
				temp=temp->children[ch];
			}
		}
		temp->terminal=false;
	}
};

int main(){
    //initialize trie
	Trie T;
	cout<<"Enter number of strings:"<<endl;
	int n;
	cin>>n;
	string*arr=new string[n];
	cout<<"Enter the strings:"<<endl;
	for(int i=0;i<n;i++){
		cin>>arr[i];
		T.insert(arr[i]);
	}
	cout<<"Enter number of queries to find if strings are present or not"<<endl;
	int q;
	cin>>q;
	cout<<"Enter a string for each query:"<<endl;
	while(q--){
		string s;
		cin>>s;
		if(T.find(s)){
			//String is present in set of strings
			cout<<"The given string is present in the set of strings"<<endl;
		}
		else{
			cout<<"The given string is absent in the set of strings"<<endl;
		}
	}
	//for deletion
	string str;
	cin>>str;
	T.deletion(str);
	if(T.find(str)){
		//String is present in set of strings
		cout<<"The given string is present in the set of strings"<<endl;
		}
	else{
		cout<<"The given string is absent in the set of strings"<<endl;
	}
}

/*Sample input:
5
"a"
"hello"
"HEllo"
"apple"
"news"
6
"a"
"hello"
"HEllo"
"not"
"new"
"news"
"news"

Sample output:
The given string is present in the set of strings
The given string is present in the set of strings
The given string is present in the set of strings
The given string is absent in the set of strings
The given string is absent in the set of strings
The given string is present in the set of strings
The given string is absent in the set of strings
*/



<|start_filename|>C-Plus-Plus/dp/Tiling_2xN.cpp<|end_filename|>
/* Problem Statement =>
    Given a “2 x n” board and tiles of size “2 x 1”, count the number of ways to
   tile the given board using the 2 x 1 tiles.
    A tile can either be placed horizontally i.e., as a 1 x 2 tile or vertically
   i.e., as 2 x 1 tile. */

#include <iostream>
#include <climits>
#include <vector>
#include <algorithm>
using namespace std;

long long numberOfWays(long long length){
    int mod = 1000000007;
    vector<long long> dp(length + 1, 0);

    // Case 1: if n == 1 , only 1 configuration of tile is possible
    dp[1] = 1;

    // Case 2: if n == 2 , only 2 configurations are possible
    dp[2] = 2;
    
    /* Case 3: if n > 2, then we got 2 possible subcases:
        Subcase 1: if we place length wise, call dp[i-2];
        Subcase 2: if we place width wise, call dp[i-1];  */
    for (int i = 3; i <= length; i++){
        dp[i] = ((dp[i - 2] % mod) + (dp[i - 1] % mod)) % mod;
    }
    return dp[length];
}

int main(){
    long long length;
    cout << "Enter the length of the floor: " << endl;
    cin >> length;
    cout << "Number of ways to tile floor of length 2 x " << length << " are: " << numberOfWays(length) << endl;
}

/*  Sample Input:
        n=3
    Sample Output:
        3
    Expected Time Complexity:
        O(n)
    Expected Space Complexity:
        O(n)
*/


<|start_filename|>C-Plus-Plus/other/MEX_of_an_array.cpp<|end_filename|>
/*
Given an array of N elements.
Find MEX ( Minimum Excluded Element ) of input array.

Mex of an array is the minimum positive integer that doesn't appear in this array.
For example, MEX of the array containing 1, 3 and 4 is equal to 2.
*/

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

// this get_MEX_of_array function will give us MEX of input array
int get_MEX_of_array(int ar[],int N)
{
    /* will insert array's elements into the set
    as set contain unique values in ascending order
    */
    set < int > mex_find;
    for(int i = 0; i < N; i++)
    {
       mex_find.insert(ar[i]);

    }
    // set MEX as 1
    int MEX = 1;
    for(auto i : mex_find)
    {
        /* if current element of Set is equal to MEX
        we will increment MEX by 1
        and if current element of Set is greater to MEX
        means we have got our MEX.
        */
        if(i == MEX)
        {
            MEX++;
        }
        else if(i > MEX)
        {
            //we have got our MEX
            break;
        }
    }
    return MEX;
}

int main()
{
    cout << "Enter the size of the array : \n";
    int N;
    cin >> N;
    int ar[N + 1];
    cout << "Enter array elements :\n";
    for (int i = 0; i < N; i++)
    {
	    cin >> ar[i];
    }
    int MEX_of_array = get_MEX_of_array(ar , N);
    cout << "MEX of the Array is : \n";
    cout << MEX_of_array << endl;

}
/*
Standard Input and Output

Enter the size of the array :
8
Enter array elements :
8 2 7 4 6 2 1 4

MEX of the Array is :
3

Time Complexity : O( logN )
Space Complexity : O(N)

*/


<|start_filename|>C-Sharp/sort/InsertionSort.cs<|end_filename|>
﻿public class InsertionSort
{
    public static void Sort(int[] array)
    {
        for (int i = 0; i < array.Length - 1; i++)
        {
            int minIndex = i;

            for (int j = i + 1; j < array.Length; j++)
            {
                if (array[j] < array[minIndex])
                {
                    minIndex = j;
                }
            }

            if (minIndex != i)
            {
                (array[i], array[minIndex]) = (array[minIndex], array[i]);
            }
        }
    }
}


<|start_filename|>C/other/leftmost_nonrepeating_char.c<|end_filename|>
#include <stdio.h>
#include <stdlib.h>

struct pair
{
    int first;
    int second;
};

int find_char_index(char *str)
{
    struct pair p[256] = {0};
    for (int i = 0; str[i]; i++)
    {
        (p[str[i]].first)++;
        p[str[i]].second = i;
    }
    int index = 10001;
    for (int i = 0; i < 256; i++)
    {
        if (p[i].first == 1)
            index = index > p[i].second ? p[i].second : index;
    }
    return index;
}

int main()
{
    char str[10000];
    printf("Enter a string: ");
    scanf("%s", str);
    int index = find_char_index(str);
    if (index == 10001)
        printf("%d", -1);
    else
        printf("%d", index);
    return 0;
}

/*
Given a string, find the index of the leftmost non repeating character in it.
Example: s = "hello", output should be: 0 (index of h)
s = "aabcdb", output should be: 3 (index of c)
s = "xxyyzz", output should be -1 (since there is no non repeating character in this string)

Time Complexity: O(n)
Space Complexity: O(n)
*/


<|start_filename|>C-Plus-Plus/ds/Tim_Sort.cpp<|end_filename|>
// TimSort implementation in C++

#include<iostream>
using namespace std;
const int N = 32;

// this function sorts array from left index to right index which is of size atmost RUN
void insertionSort(int arr[], int left, int right)
{
  for (int i = left + 1; i <= right; i++)
  {
    int temp = arr[i];
    int j = i - 1;
    while (arr[j] > temp && j >= left)
    {
      arr[j + 1] = arr[j];
      j--;
    }
    arr[j + 1] = temp;
  }
}

// merge function merges the sorted runs
void merge(int arr[], int l, int m, int r)
{
  // original array is broken in two parts
  // left and right array
  int len1 = m - l + 1, len2 = r - m;
  int left[len1], right[len2];
  for (int i = 0; i < len1; i++)
    left[i] = arr[l + i];
  for (int i = 0; i < len2; i++)
    right[i] = arr[m + 1 + i];

  int i = 0;
  int j = 0;
  int k = l;

  // after comparing, we merge those two array in larger sub array
  while (i < len1 && j < len2)
  {
    if (left[i] <= right[j])
    {
      arr[k] = left[i];
      i++;
    }
    else
    {
      arr[k] = right[j];
      j++;
    }
    k++;
  }

  // copy remaining elements of left, if any
  while (i < len1)
  {
    arr[k] = left[i];
    k++;
    i++;
  }

  // copy remaining element of right, if any
  while (j < len2)
  {
    arr[k] = right[j];
    k++;
    j++;
  }
}

// iterative Timsort function to sort the array[0...n-1]
void timSort(int arr[], int n)
{
  // Sort individual subarrays of size RUN
  for (int i = 0; i < n; i += N)
    insertionSort(arr, i, min((i + 31), (n - 1)));

  // start merging from size RUN (or 32). It will merge to form size 64, then 128, 256 and so on ....
  for (int size = N; size < n; size = 2 * size)
  {
    // pick starting point of left sub array. We are going to merge arr[left..left+size-1] and arr[left+size, left+2*size-1]
    // After every merge, we increase left by 2*size
    for (int left = 0; left < n; left += 2 * size)
    {
      // find ending point of left sub array mid+1 is starting point of right sub array
      int mid = left + size - 1;
      int right = min((left + 2 * size - 1), (n - 1));

      // merge sub array arr[left.....mid] & arr[mid+1....right]
      merge(arr, left, mid, right);
    }
  }
}

// function to print the Array
void printArray(int arr[], int n)
{
  for (int i = 0; i < n; i++)
    cout << arr[i] << " ";
  cout << endl;
}

int main()
{
  int n, arr[n];
  cout << "Enter the number of elements of the array: ";
  cin >> n;
  cout << "Enter the elements of the array to be sorted: ";
  for (int i = 0; i < n; i++) {
    cin >> arr[i];
  }
  cout << "Given Array is:" << endl;
  printArray(arr, n);

  timSort(arr, n);

  cout << "After Sorting Array is:" << endl;
  printArray(arr, n);
  return 0;
}


<|start_filename|>Java/ds/linkedList.java<|end_filename|>
import java.util.*;
public class Main 
{
    static Node head;
    class Node{
    	public int data;
    	public Node next;
    	Node(int data){
    		this.data=data;
    	}
    }
    
    public void insert_At_beginning(int data) {
    	Node ptr = new Node(data);
    	if(head!=null)
          {
    		ptr.next=head;
    		head=ptr;
          }
    	else 
    	  {     
		ptr.next=null;
    	        head=ptr;
       	  }
    }
    public boolean isEmpty()
    {
      if(head==null)
       return true;
      return false;
    }
    public void print() {
    	Node ctr=head;	
    	while(ctr!=null)
    	{
    		System.out.print(ctr.data);
    		ctr=ctr.next;
    	}
    	System.out.println();
    }  
    public void insert_At_End(int data)
    {    Node ctr=head;
    	 Node ptr = new Node(data);
    	 if(ctr==null)
    	 { head=ptr;
    	   ptr.next=null;
    	   return ;
    	 }
    	 else {
    	   while(ctr.next!=null)
    		 ctr=ctr.next;
    	   ctr.next=ptr;
           ptr.next=null;
    	 }
    } 
    public void delete_From_Beginning()
    {   if(head!=null)
    	  head = head.next;
        else 
    	System.out.println("Linked list is empty");
    }
    public void delete_From_End()
    {   
    	Node ctr=head;
    	if(ctr!=null && ctr.next!=null)
	   {
    	     while(ctr.next.next!=null)
    		ctr=ctr.next;
    	     ctr.next=null;
    	  }
    	else if( ctr!=null && ctr.next==null)
    	   head = null;
    	else
    	  System.out.println("Linked list is empty");  
    }
    public void delete_At_Position(int c)
    {   
    	int i=1;Node ctr=head,ptr;
    	if(ctr!=null && ctr.next!=null) 
	{
    	   while(i<c-1 && ctr.next!=null)
    		ctr=ctr.next;
    	   ptr=ctr.next;
    	   ctr.next=ptr.next;
        }
	else if( ctr!=null && ctr.next==null)
    	   head = null;    
        else
    	 System.out.println("Linked list is empty"); 
       return ;
   }
   public void insert_At_Position(int c,int data)
    {
    	int i=1;Node ctr=head;
    	if(ctr!=null)
	{
    	  while(i<c-1 && ctr.next!=null)
    	  {
    	      ctr=ctr.next;
    	      i++;
    	  }
    	  Node ptr = new Node(data);
    	  ptr.next=ctr.next;
    	  ctr.next=ptr;
    	}
    	else
    	{
    		Node ptr = new Node(data);
    		ptr.next=null;
		head=ptr;
        }
    }
  public void count()
    {
    	Node ptr = head;int count = 0;
        while (ptr!=null)
    		{
    			count++;
    			ptr=ptr.next;
    		}
    	System.out.println(count);
    }
  public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    Main ll = new Main();
    System.out.println("Enter 1 to insert at beginning, 2 to insert at end, 3 to insert at position, 4 to delete from beginning, 5 to delete from end, 6 to delete at position and 7 to find the length of Linked List");
    System.out.println("Enter choice from 1-7");
    boolean f=true;int choice;
    while(f)
    {
    	 choice = sc.nextInt();
         switch(choice)
	 {
           case 1: {
                    int data=sc.nextInt();
                    ll.insert_At_beginning(data);ll.print();
                     break;
                   }
           case 2:{
    	            int data=sc.nextInt();
    	            ll.insert_At_End(data);ll.print();break;
                  }
           case 3:{
    	           int data=sc.nextInt();
                   int c=sc.nextInt();
    	           ll.insert_At_Position(c, data);ll.print();break;
                  }
           case 4:{
    	          ll.delete_From_Beginning();ll.print();break;
                  }
           case 5:{
    	          ll.delete_From_End();ll.print();break;
                  }
           case 6:{
    	          int c=sc.nextInt();
    	          ll.delete_At_Position(c);ll.print();break;
                  }
           case 7:{
   	          ll.count();
   	          break;
                  }
           default:f=false;
        }
       System.out.println("Enter choice from 1-7");
     }
   }
}


<|start_filename|>Java/ds/linkedListReverse.java<|end_filename|>
import java.util.Scanner;

public class linkedListReverse {
static Node head;
class Node{
	public int data;
	public Node next;
	Node(int data){
		this.data=data;
	}
}

void add(int data)
{   Node ctr=head;
	Node ptr = new Node(data);
	if(ctr==null)
	{
		head=ptr;
		ptr.next=null;
	}
	else 
	{
		
		while(ctr.next!=null)
			ctr=ctr.next;
		ctr.next=ptr;
		ptr.next=null;
	}
}

public void print() {
	Node ctr=head;
	

	
	while(ctr!=null)
	{
		System.out.print(ctr.data+" ");
		ctr=ctr.next;
	}
	
	
	
}

public static void main(String[] args)
{
	Scanner sc=new Scanner(System.in);
	linkedListReverse ll = new linkedListReverse();
	String choice;int data; 
	
	System.out.println("Enter y to add a data to Linked List");
	
	choice = sc.nextLine();
		while(!choice.isEmpty() && choice.charAt(0)=='y') {
			
		
		System.out.println("Enter data to enter into the linked list");
		data=sc.nextInt();
		ll.add(data);
		ll.print();
		System.out.println();
System.out.println("Enter y to add a data to Linked List");
		sc.nextLine();
		choice = sc.nextLine();
	}
	Node ctr=head;Node ptr,temp;
	if(ctr==null)
		System.out.println("Linked List is empty");
	else {
	ptr=null;
	temp=ctr.next;
	while(ctr.next!=null)
	{
		ctr.next=ptr;
		ptr=ctr;
		ctr=temp;
		temp=temp.next;
		
		
	}
	ctr.next=ptr;
head=ctr;
ll.print();
}
}
}


<|start_filename|>C-Plus-Plus/cryptography/HillCipher.cpp<|end_filename|>
/* This code is an implementation of Hill Cipher. It
   is a polygraphic substitution cipher. It forms a 
   nxn matrix of key and nx1 matrix(s) of the plaintext
   and then multiplies the two matrices to obtains the
   matrix of ciphertext.*/

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

//This function prints the cipher text
void printciphertext(int cipherMatrix[SIZE][1]){
    
    string output;
    for(int i=0;i<SIZE;i++){
        output += cipherMatrix[i][0]+97;
    }

    cout<<"The cipher text is :"<<output;
}

//This function calculates the matrix multiplication
void cipher(int cipherMatrix[SIZE][1],int keyMatrix[SIZE][SIZE],int plaintextMatrix[SIZE][1]){

      //calculating the multiplication 
      for(int i=0;i<SIZE;i++){
          cipherMatrix[i][0] = 0;
          for(int j=0;j<SIZE;j++){
              cipherMatrix[i][0] += keyMatrix[i][j]*plaintextMatrix[j][0];
          }

          cipherMatrix[i][0] = cipherMatrix[i][0]%26;
      }     
}

//This function builds the key matrix
void buildkeyMatrix(int keyMatrix[SIZE][SIZE],string key){
 
    int counter =0;
    //storing the key in matrix
    for(int i=0;i<SIZE;i++){
        for(int j=0;j<SIZE;j++){
            keyMatrix[i][j] = key[counter]%97;
            counter++; 
        }
    }
}

//This function builds the plaintext matrix
void buildplaintextMatrix(int plaintextMatrix[][1],string plaintext){

    //storing the plaintext in matrix form
    for(int i=0;i<SIZE;i++){
        plaintextMatrix[i][0] = (plaintext[i])%97;
    }
}

//This fuinction helps us in calling all the functions in sequential order
void hillcipher(string plaintext,string key){

    int plaintextMatrix[SIZE][1];
    buildplaintextMatrix(plaintextMatrix,plaintext);

    int keyMatrix[SIZE][SIZE];
    buildkeyMatrix(keyMatrix,key);

    int cipherMatrix[SIZE][1];
    cipher(cipherMatrix,keyMatrix,plaintextMatrix);

    printciphertext(cipherMatrix);
}

int main(){

    string plaintext;
    string key;

    cout<<"The plaintext size you need to enter is :"<<SIZE<<endl;

    cout<<"Enter the plaintext here same :";
    //Taking plaintext from here
    cin>>plaintext;
   
    cout<<"Enter the key here :";
    //Taking key from here
    cin>>key; 

    int size1 = plaintext.length();
    int size2 = key.length(); 

    //validating for the input given 
    if(size2 != size1*size1 || size1 != SIZE){
        cout<<"The key input is wrong!"<<endl;
        return 0;
    }
    else 
        hillcipher(plaintext,key);

    return 0;
}
/*
    Sample I/O :

    The plaintext size you need to enter is :3
    Enter the plaintext here same :ask
    Enter the key here :thisiskey
    The cipher text is :yma
*/


<|start_filename|>Go/dp/stack/stack.go<|end_filename|>
// Stack in Go

package main

import "fmt"

type stack []int

var limit = 5

func (stk *stack) pushStack(ele int) {
	if !((*stk).isFull()) {
		*stk = append(*stk, ele)
		fmt.Printf("Added element: %v\n", ele)
	} else {
		fmt.Println("Stack is full!")
	}
}

func (stk *stack) popStack() {
	if !((*stk).isEmpty()) {
		top_ele, top := (*stk).peekStack()
		fmt.Printf("Popped Element: %v\n", top_ele)
		(*stk) = (*stk)[:top]
	} else {
		fmt.Println("Stack is empty!")
	}
}

func (stk *stack) isEmpty() bool {
	return len(*stk) == 0
}

func (stk *stack) isFull() bool {
	return len(*stk) == limit
}

func (stk *stack) peekStack() (int, int) {
	top := len(*stk) - 1
	top_ele := (*stk)[top]
	return top_ele, top
}

func main() {
	fmt.Println("Welcome to Stack program in Go!")
	var stack1 stack
	stack1.pushStack(4)
	stack1.pushStack(5)
	stack1.pushStack(1)
	stack1.pushStack(3)
	stack1.pushStack(7)
	stack1.pushStack(9)
	stack1.popStack()
	stack1.popStack()
	stack1.popStack()
	topOfStack, topIndex := stack1.peekStack()
	fmt.Printf("Top element of stack: %v\tIndex of top element: %v\n", topOfStack, topIndex)
}


<|start_filename|>Go/cryptography/Vigenere_Cipher/Vigenere_Cipher.go<|end_filename|>
/* Below code is an implementation of Vigenere Cipher in golang.
It is a form of substitution cipher. Given a plaintext and a key.
If the length of key is smaller than that of plaintext, then we 
repeat the contents of the key in a circular fashion till both of
their lengths is same. Plaintext and key are converted to number 
[0-25] and then each character of plaintext is shifted by character
present at the same index in the key to form the encrypted message.*/

package main

import (
	"fmt"
	"strings"
	"unicode"
)

/*This method generates the key if the length of key
is shorter than the length of the plaintext.*/
func keygen(key string, length int) string {

	if(len(key) < length) {
		var pad string
		for j := 0; j < len(key) ; j++ {
			pad += string(key[j])
		}
		/*In a circular fashion, we add the contents
		of the key from front to the end, till the
		length of the key becomes equal to the length
		of the plaintext.*/
		for i := 0; i < (length - len(key)); i++ {
			pad += string(key[i % len(key)])
		}
		return pad
	}
	// Return the final key to be used
	return key
}

// This is the encryption function
func encrypt(plaintext, key string) string {

	/* Calling the above function to ensure that
	the length of the key is same as length of
	the plaintext*/
	var pad string = keygen(key, len(plaintext))
	var encrypted string

	// Shifting the plaintext to generate the ciphertext
	for i := 0; i < len(plaintext); i++ {
		var temp int = (int(plaintext[i]) - 97 + int(pad[i]) - 97) % 26
		temp = temp + 97
		encrypted += string(temp)
	}
	// Returns the ciphertext
	return encrypted
}

/* This method formats the ciphertext according to
the plaintext. From the encrypt function above, we
send plaintext in lowercase. So, the ciphertext we
get is also in all lowercase. Here, we format the
ciphertext so that wherever there is capital letter
in the plaintext, same follows in the ciphertext.*/
func format(plaintext, ciphertext string) string {

	var enc string
	/* Check wherever the plaintext is capital and
	then capitalize that character in the ciphertext*/
	for i := 0; i < len(plaintext); i++ {
		if(unicode.IsUpper(rune(plaintext[i]))) {
			enc += strings.ToUpper(string(ciphertext[i]))
		} else {
			enc += string(ciphertext[i])
		}
	}
	// Return the final formatted ciphertext
	return enc
}

func main() {

	// Taking plaintext as input from the user
	var plaintext string
	fmt.Print("Enter a plaintext to encrypt: ")
	fmt.Scan(&plaintext)

	// Taking key as input from the user
	var key string
	fmt.Print("Enter a key: ")
	fmt.Scan(&key)

	// Generating the ciphertext
	var ciphertext string = encrypt(strings.ToLower(plaintext), strings.ToLower(key))

	// Formatting the ciphertext
	var encrypted string = format(plaintext, ciphertext)
	fmt.Print("\nEncrypted plaintext is: ", encrypted, "\n")
}

/* Sample I/O:

Enter a plaintext to encrypt: ThisIsAPlainText
Enter a key: Mercury

Encrypted plaintext is: FlzuCjYBprkhKcjx

*/



<|start_filename|>C/dp/Unique_BST.c<|end_filename|>
// Unique BSTs using DP
// Given n, how many structurally unique BST's that store values 1 ... n?

#include <stdio.h>

int max(int num1, int num2) {
	return (num1 > num2) ? num1 : num2;
}

int uniqueBST(int n) {
	int count[n + 1];
	for (int i = 0; i < n + 1; i++)
		count[i] = 0;
	// for each 'i' number of nodes
	for (int i = 1; i <= n; ++i) {
		for (int j = 0; j < i; ++j) {
			// No. of trees if j is a root
			count[i] += max(count[j], 1) * max(count[i - j - 1], 1);
		}
	}
	return count[n];
}

int main() {
	int n;
	printf("Enter the number: \n");
	scanf("%d", &n);
	int num = uniqueBST(n);
	printf("Number of Unique BSTs %d is: \n", num);
	return 0;
}

/*
input:
Enter value:3
output:
Number of Unique BSTs 5
Time complexity : O(n^2)
*/


<|start_filename|>Go/math/Mystery_Number/Mystery_Number.go<|end_filename|>
/* Below checks checks if a number is a mystery number.
Mystery number - A number that can be represented by sum
of two numbers, such that the two numbers are reverse of
each other.*/

package main

import (
	"fmt"
	"strconv"
)

/* This function takes a number as a input and returns
a number with the digits reversed*/
func rev(number int) int {

	var reverse string
	for number > 0 {
		/* The number is broken into pieces by taking mod 10.
		Each digit is converted to string and concatenated.*/
		str := strconv.Itoa(number % 10)
		reverse += str
		number = number / 10
	}
	// Finally the reversed string is converted back to integer
	revs, err := strconv.Atoi(reverse)
	if(err == nil) {
		// If there were no errors we return the number
		return revs
	}
	return -1
}

// This function checks if the number is a mystery number
func mystery(number int) int {

	// We iterate till the middle of the number
	var distance int = number / 2
	for i:= 1; i <= distance; i++ {
		// Check the sum of number with its reverse
		if(i + rev(i) == number) {
			// If its is equal to the given number we return and print
			fmt.Print("\nThe two digits are: ", i, " ", rev(i))
			return 1
		}
	}
	// Else return -1
	return -1
}

func main() {

	// Taking number as input from the user
	fmt.Print("Enter a number to check if it's a mystery number: ")
	var number int
	fmt.Scan(&number)

	// Calling the mystery function
	var result int = mystery(number)

	// If the result is 1, the number is a mystery number
	if(result == 1) {
		fmt.Print("\nThe number ", number, " is a mystery number.\n")
	} else {
		// Else it is not a mystery number
		fmt.Print("\nThe number ", number, " is not a mystery number.\n")
	}
}

/* Sample I/O:

Enter a number to check if it's a mystery number: 33

The two digits are: 12 21
The number 33 is a mystery number.

*/


<|start_filename|>Dart/sort/BubbleSort.dart<|end_filename|>
/**
Function to sort list using bubble sort technique.
We use one extra temporary variable to help us out in swapping. 
isSorted checks if the list is already sorted.
 */
import 'dart:io';

// the function which runs the bubble sort algorithm
List bubbleSort(List arr) {
  int len = arr.length;
  int temp = 0;
  for (int i = 0; i < len; i++) {
    bool isSorted = true;
    for (int j = 1; j < (len - i); j++) {
      if (arr[j - 1] > arr[j]) {
        // swap elements
        temp = arr[j - 1];
        arr[j - 1] = arr[j];
        arr[j] = temp;
        isSorted = false;
      }
    }
    if (isSorted) {
      break;
    }
  }
  return arr;
}

// Main function, entry point of the program
void main() {
  print("Enter the size of list:");
  int size = int.parse(stdin.readLineSync()!);
  List arr = [];
  print("Enter the numbers:");
  for (int i = 0; i < size; i++) {
    arr.add(int.parse(stdin.readLineSync()!));
  }
  // sorting
  arr = bubbleSort(arr);
  print("Sorted list:");
  for (int i = 0; i < size; i++) {
    print(arr[i]);
  }
}

/**
 * Sample input/output
 * Enter the size of list:
 * 6
 * Enter the numbers:
 * 5
 * 4
 * 3
 * 2
 * 1
 * 0
 * Sorted list:
 * 0
 * 1
 * 2
 * 3
 * 4
 * 5
 *
 * Space complexity: O(1)
 * Time complexity: O(n^2) {worst} / O(n) {best}
 */


<|start_filename|>C/ds/Dijsktra.c<|end_filename|>
/*	Dijkstra's Algorithm 
To find the shortest path between nodes in a graph*/
#include <stdio.h>
#include <stdlib.h>

void minimum_distance_path(int, int[][20], int, int);
void dijkstra_algo(int[][20], int[], int[][20], int, int, int);
void main()
{

	int size;
	//Enter the maximum size of the node
	//for cost distance and path
	printf("Enter the maximum size of node:");
	scanf("%d", &size);
	int cost[size][size], distance[size], path[size][size], n, v, p, row, column, min, index = 1, i, j;
	//use enters no of nodes
	printf("Enter no of nodes :  ");
	scanf("%d", &n);

	//user enters cost of matrix
	printf("Enter cost matrix :  ");
	for (i = 1; i <= n; i++)
	{
		for (j = 1; j <= n; j++)
		{
			scanf("%d", &cost[i][j]);
		}
	}
	//user enters node to be visited
	printf("Enter node to visit :  ");
	scanf("%d", &v);
	//user enters no of paths for particular node
	printf("Enter paths for the selected node : ");
	scanf("%d", &p);

	//path matrix
	printf("Enter path matrix \n");
	for (i = 1; i <= p; i++)
	{
		for (j = 1; j <= n; j++)
		{
			scanf("%d", &path[i][j]);
		}
	}
	dijkstra_algo(cost, distance, path, n, v, p);
}
// Implementing Dijkstra's Algorithm 
void dijkstra_algo(int cost[][20], int distance[], int path[][20], int n, int v, int p)
{
	int i, row, column, min, j, index;
	for (i = 1; i <= p; i++)
	{
		distance[i] = 0;
		row = 1;
		for (j = 1; j < n; j++)
		{
			if (row != v)
			{
				//till i visit the last node
				column = path[i][j + 1];
				distance[i] = distance[i] + cost[row][column];
			}
			row = column;
		}
	}

	//which distance to be considered
	min = distance[1];
	for (i = 1; i <= p; i++)
	{
		if (distance[i] <= min)
		{
			min = distance[i];
			index = i;
		}
	}
	minimum_distance_path(min, path, index, n);
}
// Function to print the minimum path distance
void minimum_distance_path(int min, int path[][20], int index, int n)
{
	int i;
	printf("min distance is %d\n", min);
	printf("min distance path is\n");
	for (i = 1; i <= n; i++)
	{
		if (path[index][i] != 0)
			printf("--->%d", path[index][i]);
	}
}
/*
Time Complexity : O(N^2)

Sample Input Output
Enter the size of the node : 10
Enter no of nodes :  5
Enter cost matrix :  0
4
0
8
0
4
0
3
0
0
0
3
0
4
0
8
0
4
0
7
0
0
0
7
0
Enter node to visit :  5
Enter paths for the selected node : 2
Enter path matrix
1
2
3
4
5
1
4
5
0
0
min distance is 15
min distance path is
--->1--->4--->5
*/



<|start_filename|>Java/ds/DeleteElementLL.java<|end_filename|>
/*
   We will create a LinkedList first and display its elements.
   After that we will delete some elements from the LinkedList
   * Delete from beginning - In this case we will simply move the head pointer
      to the next node. In case if we have only one element in the LL then we 
      will assign null to head which is the pointer to the first and only node in the LL. 
   * Delete from end - In this case we will take a pointer and initialize 
      it to the head pointer and we will move this pointer till end-1 so 
      that we can access the last node.    
   * Delete from any position - In this case we will take a pointer variable
      and initialize it to the head pointer and we will move this pointer till 
      position-1 so that we can access the desired position node.
*/

import java.util.Scanner;

public class DeleteElementLL {
     
	//creating the Node class having one data part and one pointer to the next node
	class Node{
		 int data;      
		 Node next;
		 
		 // Constructor to initialize the data and next pointer
		 Node(int data){
			 this.data = data;      
			 this.next = null;  
		 }
	}
	  
	  // creating the head of the list
	  Node head = null; 
	  
	  public void createList(int newData) {
		  
		/* creating a new node with data value.
		   If list is empty head points to the newly
		   created node and if list is not empty, we create
		   temp variable and traverse the list till end
		   and insert the node at the end */
             
		  Node new_Node = new Node(newData); 
		  Node temp = head;
		  if(head==null) {
			  head = new_Node;
		  }
		  else {
		     	while(temp.next!=null) {
		     		temp = temp.next;
		     	}
		     	temp.next = new_Node;
		  }
	  } 
	
	  public void displayList() {
		  /* creating a temp variable 
		     traversing and printing the list*/
		  
		  Node temp = head;  
		 
		  while(temp != null) {
			  System.out.print(temp.data + " ");
			  temp = temp.next;
		  }
		  System.out.println();
	  }
	  
	  public void deleteFromBeg() {
		  /* if list is empty nothing to delete
		    else head points to the second element in the list */
		   
		  if(head==null){
			  System.out.println("List is Empty.");
			  return;
		  }
		  else {
			  head = head.next; 
		  } 
	  }
	  
	  public void deleteFromEnd() {
		  /* if only one element is present in the list
		     delete it otherwise create a temp variable
		     and traverse the list till the second
		     last element and at last temp should
		     point null to remove last node */
		   
		   
		  Node temp = head;
		
		  if(head.next == null) {
			  head = null;
		  }
		  
		  else{
			   while(temp.next.next != null) {
				   temp = temp.next;
			   }
			   temp.next = null;
		  }
	  }
	  
	  public void deleteFromAnyPosition(int pos) {
		  /* create a temp variable and initialize it to head.
		     Then traverse the list till position-1 and at 
		     last link the previous node of the node to-be-deleted
		     to the node after it. */
		  
		  Node temp = head;
		  int i=1;
		  while(i<pos-1) {
			  temp = temp.next;
			  i++;
		  }
		  
		  Node next = temp.next.next; 
	      temp.next = next;
		  
	  }
	  
	public static void main(String[] args) {
		 
		   DeleteElementLL list = new DeleteElementLL();
		   
		    Scanner input = new Scanner(System.in);
		   System.out.println("Enter the number of elements you want to insert in the List: ");
		   int n = input.nextInt();
		   System.out.println("Enter the elements of the List: ");
		   for(int i=0; i<n; i++) {
			   list.createList(input.nextInt());
		   }
		   
		   System.out.print("Initial List: ");
		   list.displayList();
		   
		   list.deleteFromBeg();
		   System.out.print("List after deletion from the Beginning: ");
		   list.displayList();
		   
		   list.deleteFromEnd();
		   System.out.print("List after deletion from the End: ");
		   list.displayList();
		 
		   System.out.println("Enter the position of the element you want to delete: ");
		   int position = input.nextInt(); 
		   input.close();
		   
		   list.deleteFromAnyPosition(position);
		   System.out.print("List after deletion from the desired position: " );
		   list.displayList();
		
	}

}

/*
  Enter the number of elements you want to insert in the List: 
  9
  Enter the elements of the List: 
  3 5 8 2 10 7 21 6 1
  Initial List: 3 5 8 2 10 7 21 6 1 
  List after deletion from the Beginning: 5 8 2 10 7 21 6 1 
  List after deletion from the End: 5 8 2 10 7 21 6 
  Enter the position of the element you want to delete:
  3
  List after deletion from the desired position: 5 8 10 7 21 6 


  Time Complexity - O(n) Worst case
                    O(1) Best case
                    
 */


<|start_filename|>Java/cp/Longest_Pallindromicsubstring.java<|end_filename|>

/* This is a Java program  to find the longest palindromicsubstring from a word using dynamic programming approach

Pallindromic substring means a part of a word which reads the same backward as forward.
There may be more than one pallindromic substring in a word but this program gives the longest pallindromic
substring in terms of length.
*/
import java.util.*;
 
class PallindromicSubstr{

    public static String expandbothside(String str, int low, int high)
    {
        int len = str.length();
     
        // expand in both directions
        while (low >= 0 && high < len &&
            (str.charAt(low) == str.charAt(high))) {
                low--;
                high++;
            }
            return str.substring(low + 1, high);
    }
     
        
        public static String longestPallindromeSubstr(String str, int len)
        {
            // `max_str` stores the maximum length palindromic substring     
            String max_str = "", curr_str;
     
            // `max_length` stores the maximum length of palindromic     
            int max_len = 0, curr_len;
     
            for (int i = 0; i < len; i++)
            {
                // find the longest odd length palindrome with `str[i]` as a midpoint
     
                curr_str = expandbothside(str, i, i);
                curr_len = curr_str.length();    
     
                // update maximum length palindromic substring if odd length palindrome has a greater length
     
                if (curr_len > max_len)
                {
                    max_len = curr_len;
                    max_str = curr_str;
                }

                curr_str = expandbothside(str, i, i + 1);
                curr_len = curr_str.length();
     
                // update maximum length palindromic substring if even length palindrome has a greater length
     
                if (curr_len > max_len)
                {
                    max_len = curr_len;
                    max_str = curr_str;
                }
            }
     
            return max_str;
        }
 
public static void main(String[] args)
{
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter word");
    String str = sc.nextLine();
    System.out.print("\nLength of longest pallindrome substring is: "
         + longestPallindromeSubstr(str,str.length() - 1));
}
}

/* Time complexity is O(n*n)
Space complexity is O(1)

Input :
Enter word
mallammalayalamaaabbaa

output:
Length of longest pallindrome substring is: malayalam
*/


<|start_filename|>C/sort/beadSort.c<|end_filename|>
/* Bead sort, also called as gravity sort, is a natural sorting algorithm since this algorithm was inspired
from natural phenomenons and was designed keeping in mind objects(or beads) falling under the influence of gravity.
The bead sort operation can be compared to the manner in which beads slide on parallel poles, such as on an abacus.
However, each pole may have a distinct number of beads. */

#include <stdio.h>
#include <stdlib.h>
#define BEAD(i, k) beads[i * max + k]

void bead_sort(int *arr, int n){
    int max=arr[0],sum,i,k;
	for (i = 1; i < n; i++)
		if (arr[i] > max)
		    max = arr[i];

	// pointer to the first character of string beads
	unsigned char *beads;

	// allocate one block of memory of size (max*n) to first char beads and initialize it to 0
	beads = calloc(1, max * n);

	for (i = 0; i < n; i++){
	    for (k = 0; k < arr[i]; k++){
	        BEAD(i, k) = 1;
	    }

	}

	for (k = 0; k < max; k++) {
		sum=0;
		for (i = 0; i < n; i++) {
			sum = sum + BEAD(i, k);
			BEAD(i, k) = 0;
		}
		for (i = n - sum; i < n; i++)
		    BEAD(i, k) = 1;
	}

	for (i = 0; i < n; i++) {
		for (k = 0; k < max && BEAD(i, k); k++);
		arr[i] = k;
	}

	//deallocate the memory allocated to beads
	free(beads);
}

int main(void) {

	int n, i, k;
	printf("Enter the number of elements in the array : ");
	scanf("%d",&n);

	int nums[n];
	printf("Enter the elements of the array : ");
	for(i = 0; i < n; i++){
	    scanf("%d",&nums[i]);
	}
        bead_sort(nums, n);

	printf("The array elements after sorting are : ");
	for (i = 0; i < n; i++)
		printf("%d\n", nums[i]);

	return 0;
}

/*

Input:
Enter the number of elements in the array : 5
Enter the elements of the array : 14 26 43 92 18

Output:
The array elements after sorting are : 14
18
26
43
92

Time Complexities:
Bead sort can be implemented with four general levels of complexity, among others:
O(n): in best case
O(S): in worst case, where S is the sum of all beads

*/


<|start_filename|>C-Plus-Plus/ds/DoublyLinkedList.cpp<|end_filename|>
/* This program implements Doubly Linked List for creation,insertion and Reversing the Linked List

A Doubly Linked List (DLL) contains an extra pointer, typically called previous pointer, together with next pointer and data which are there in singly linked list.

@author: GudlaArunKumar
@created: 30/06/2020
*/



#include <iostream>
using namespace std;

struct Node{          // Created structure Node which contains Data, previous and Next pointer 
    struct Node *prev;
    int data;
    struct Node *next;
}*first=NULL;         //Declared struct object as First globally

void create(int arr[],int n){   //Creation of Doubly Linked List
struct Node *tmp,*last;
first=new Node;
first->data=arr[0];
first->prev=first->next=NULL;
last=first;
for(int i=1;i<n;i++)
{
 tmp = new Node;
 tmp->data = arr[i];
 tmp->next=last->next;
 tmp->prev=last;
 last->next=tmp;
 last=tmp;
}
 }
 
void display(struct Node *p)   //Displaying the elements in Doubly Linked List while travsersing through Next pointer only
{
     cout <<"Elements in doubly Linked list are:" << endl;
    while(p!=NULL)
    {
        cout << p->data << " ";
        p=p->next;
    }
    cout << endl;
}

int Length(struct Node *p)   //Calculates Length of DLL
{
    int count =0;
    while(p!=NULL)
    {
        count++;
        p=p->next;
    }
    return count;
}

void Insert(int pos,int x)   //Insertion operation takes place with repect to position given by User
{
    struct Node *tmp,*p=first;
    if(pos==0)
    {
     tmp = new Node;
     tmp->data=x;
     tmp->next=first;
     tmp->prev=NULL;
     first->prev=tmp;
     first=tmp;
    }
else
{
    tmp = new Node;
    tmp->data=x;
    for(int i=0;i<pos-1;i++)
    {
        p=p->next;
    }
    tmp->next=p->next;
    tmp->prev=p;
    if(p->next)
    {
        p->next->prev=tmp;
    }
    p->next=tmp;
}
}

void ReverseList(struct Node *p)   //Reversing the DLL by swapping Prev and Next Pointer of each Node
{
    p=first;
    struct Node *temp;
    while(p!=NULL)
    {
        temp=p->prev;
        p->prev=p->next;
        p->next=temp;
        p=p->prev;
        if(p!=NULL && p->next==NULL)
        {
            first=p;
        }
    }
}

int main(){
    int arr[7]={10,20,30,40,50,60,70};
    int pos,element;
    create(arr,7);
    display(first);   // Displaying DLL
    cout << "Length of List is: " << Length(first) << endl;
    cout << "Enter position and element to insert in the Linked List" << endl;  //Data will be inserted at "Position+1" in Doubly Linked List
    cin >> pos;
    cin >> element;
    Insert(pos,element);
    display(first);
    cout << "After Reversing the Linked List, ";
    ReverseList(first);
    display(first);
    return 0;
}


<|start_filename|>Java/cp/MaximumEachSubarray.java<|end_filename|>
/**
 * Maximum of All Subarrays of Size k
 * Java program to find the maximum integer in each subarray of 
 * fixed size k, given an array of integers, using the 'Sliding 
 * Window Technique'. 
 */

import java.io.*;
import java.util.*; 
public class MaximumEachSubarray {

    private static String findMaxEachSubarray(int[] numArray, int k) {
        String result = ""; 

        //ArrayDeque stores indices of useful elements for each window.
        //These indices are sorted in decreasing order, so that for each
        //window, index of maximum element is at the front. 
        ArrayDeque<Integer> indices = new ArrayDeque<>();
        
        //For first window 
        for(int i=0; i<k; i++){

            //For any element, all elements smaller than it and to its left in 
            //the window are useless as they cannot be the maximum for that 
            //window. Hence, we remove them from rear of deque. 
            while(!indices.isEmpty() && (numArray[i] >= numArray[indices.peekLast()]))
                indices.removeLast(); 

            //Adding newest element to rear of deque
            indices.addLast(i); 
        }
        
        //For first window
        result += (numArray[indices.peek()] + " "); 
        
        //The same process is repeated over all windows of length k.
        for(int i=k; i<numArray.length; i++) {

            //If window has crossed the index at front of deque
            if(indices.peek() <= (i-k)) 
                indices.removeFirst(); 

            while(!indices.isEmpty() && (numArray[indices.peekLast()] <= numArray[i]))
                indices.removeLast(); 
            indices.addLast(i); 
            result += (numArray[indices.peek()] + " "); 
        }

        return result;
    }

    public static void main(String[] args) throws IOException {
        InputStreamReader read = new InputStreamReader(System.in);
	    BufferedReader buf = new BufferedReader(read); 

        //Taking input from user
        System.out.println("Enter length of array of integers: ");
	    int len = Integer.parseInt(buf.readLine());
        System.out.println("Enter array of integers: ");
	    StringTokenizer st = new StringTokenizer(buf.readLine());
	    int numArray[] = new int[len];
	    for(int i=0; i<len; i++) {
	        numArray[i] = Integer.parseInt(st.nextToken()); 
	    }
        System.out.println("Enter size of window: ");
	    int K = Integer.parseInt(buf.readLine()); 
	    
        //Output is a String in which the first integer is maximum for 1st K-sized window, 
        //the second integer is maximum for 2nd K-sized window, and so on.
        System.out.println("String of maximum integers in all K-sized subarrays: ");
        System.out.println(findMaxEachSubarray(numArray, K));
    }

}

/*
    Time complexity: O(N)
    Space complexity: O(k) (ArrayDeque used to store indices can be, 
                            at most, k in length)

    TEST CASES

    INPUT
    Enter length of array of integers: 
    10
    Enter array of integers: 
    12 3 4 5 1 7 2 9 1 18
    Enter size of window: 
    4
    OUTPUT
    String of maximum integers in all K-sized subarrays:
    12 5 7 7 9 9 18 

    INPUT
    Enter length of array of integers: 
    8
    Enter array of integers: 
    1 3 -1 -3 5 3 6 7 
    Enter size of window: 
    3
    OUTPUT
    String of maximum integers in all K-sized subarrays:
    3 3 5 5 6 7

 */


<|start_filename|>C-Plus-Plus/other/Kth_permutation_sequence.cpp<|end_filename|>
/* 
Kth - Permutation Sequence 

The set [1, 2, 3, ..., n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence in the string type.

*/

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

string Solve(int n, int k)
{
    // factorial is the variable to store the n!
    long long int factorial = 1;
    // vector to store the number from 1 to n
    vector<int> num;
    for(int i = 1;i < n;i++)
    {
        factorial = factorial * i;
        num.push_back(i);
    }
    num.push_back(n);
    // str variable to store the ans or kth sequence
    string str = "";
    k = k - 1;
    while(true){
        // adding the k / factorial number in the string
        str += to_string(num[k / factorial]);
        // erasing the element from the vector as it is already added in the string
        num.erase(num.begin() + k / factorial);
        if(num.size() == 0){
            break;
        }
        // updating the k
        k %= factorial;
        // updating the factorial
        factorial /= num.size();
    }
    return str;
}

int main()
{
    int testCases;
    cout << "Enter the number of testcases: ";
    cin >> testCases;
    while(testCases--){
        //n is the size of the each permutation
        int n; 
        cout<<"Enter the number n: ";
        cin>>n;
        // k is the kth - permutation in the set of n!
        int k;
        cout<<"Enter the number k: ";
        cin>>k;
        string ans = Solve(n,k);
        cout<<"The kth permutation is: '"<<ans<<"'"<<endl;
    }
    return 0;
}

/*

FOR EXAMPLE:--

Example 1:
Input:-
Enter the number of testcases: 2
Enter the number n: 4
Enter the number of k: 17
Enter the number n: 3
Enter the number k: 2
Output:-
The kth permutation is: '3412'
The kth permutation is: '132'


SPACE COMPLEXITY = O(n)(Storing the ans string)
TIME COMPLEXITY = O(n ^ 2)

*/


<|start_filename|>C-Plus-Plus/ds/LevelOrderTraversal.cpp<|end_filename|>
/*


This program is about Traversing elements of a binary Tree in a Level Order way.Here we will enter the values for
the nodes of the tree. 
It will simply print the elements of the tree level by level by simply storing the  
addresses of the nodes in a queue and printing the node whose address is on the front 
,and calling the same function for left and right subtree recursively and the process 
is iterated untill  queue doesn't gets emptied.


*/
#include <iostream>

#include<queue>

using namespace std;

//  Basic Definition of node in a Binary Tree

struct child {
    int data;
    child*LeftPtr;
    child*RightPtr;

    child(int value) {
        data = value;
        LeftPtr = NULL;
        RightPtr = NULL;
    }
};

//  Function to build tree Recursively 

child * buildTree() {
    int d;
    cin >> d;

    if (d == -1) {
        return NULL;
    }

    child*root = new child(d);

    root->LeftPtr = buildTree();

    root->RightPtr = buildTree();

    return root;
}

//  Function for implementing level order traversal using Queue

void levelOrder(child * root) {

    if (root == NULL)
        return;

    queue <child*> q;

    q.push(root);

    while (!q.empty()) {
        child*t = q.front();
        cout << t -> data << endl;

        if (t->LeftPtr)
            q.push(t->LeftPtr);
        if (t->RightPtr)
            q.push(t->RightPtr);

        q.pop();
    }

}

int main() {

    cout << "Enter the values of nodes of the tree: " << endl;

    child*root = buildTree();

    cout << "Level Order Traversal for the following Tree will be:" << endl;

    levelOrder(root);

    return 0;
}

/*  
Output:-
Enter the values of nodes of the tree:
3
4
6
-1
-1
7
-1
-1
5
-1
-1


Level Order Traversal for the following Tree will be:
3
4
5
6
7

Time Complexity:- O(n)
Space Complexity:- O(n) 

*/


<|start_filename|>C/sort/bubble_sort.c<|end_filename|>
#include <stdio.h>
#define MAX 100

/*Bubble sort is an algorithm that compares the adjacent elements and swaps 
their positions if they are not in the intended order. 
The order can be ascending or descending.
*/

//prototyping the bubble sort function
void bubble_sort(int a[], int len); //utility function to sort
void print_array(int a[], int n);   //utility function for printiong an array
//initializing main function

int main(int argc, char const *argv[])
{
    //initial array to store elements for sorting.
    int A[MAX];

    //size element to define the size of the array.
    int size, i, j;

    printf("enter the size of array you want:");
    scanf("%d", &size);

    //taking the elements in the array

    for (i = 0; i < size; i++)
    {
        /* take the elements from user */
        printf("\n");
        printf("enter the element of the array:");
        scanf("%d", &A[i]);
    }

    printf("\n");
    printf("the initial unsorted array:");
    print_array(A, size);

    bubble_sort(A, size);

    printf("\n\n");
    printf("The final sorted array:");
    print_array(A, size);

    return 0;
}

void bubble_sort(int a[], int n)
{

    int i, j;
    for (i = 0; i < n - 1; i++)
    {
        j = i;
        for (j = 0; j < n - i - 1; j++)
        {
            if (a[j] > a[j + 1])
            {
                /* code */
                int temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
            }
        }
    }
}

void print_array(int a[], int n)
{
    for (int i = 0; i < n; i++)
    {
        /* code */
        printf(" %d ", a[i]);
    }
}

<|start_filename|>C-Plus-Plus/cp/Reverse_string_using_stack.cpp<|end_filename|>
//Given a string,print reverse of the string using stack
//Approach:-
//In stack,we know LIFO principle works.
//First,i create an empty stack,then i push each character of string in stack
//then,using for loop i popped out every single character.

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

//function to reverse the string
void reverse(string &s)
{
	int i;
	stack<int> str;

	for(char ch:s){
        str.push(ch);
    }
    for(i=0;i<s.size();i++){
        s[i]=str.top();
        str.pop();
    } 
}

int main()
{
	cout<<"***********Program to reverse a string using stack***********"<<endl;
	string s;
	cout<<"Enter a string you want to reverse: ";
	cin>>s;
	reverse(s);
      cout<<"String After Reverse: ";
	cout<<s;
	return 0;
}

/*
Test Case 1:
Input :
***********Program to reverse a string using stack***********
Enter a string you want to reverse: Harshit
Output :
String After Reverse: tihsrah

Time Complexity : O(n), where n is the length of the input string.
Space Complexity : O(n) for stack.
*/


<|start_filename|>C/ds/postfix_to_prefix.c<|end_filename|>
/*
Infix, postfix and prefix are three different but equivalent notations of writing
algebraic expressions.
In postfix notation, operators follow their operands. 
In prefix notation, operators precede their operands.
    In this program, the user inputs a postfix expression and the prefix notation for that
given postfix notation is the output. Postfix notation is converted to prefix notation with
the help of stack data structure.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX 30

struct stack
{
	char sta[MAX];
	struct stack * next;
};
struct stack *st = NULL;
char a[MAX], b[MAX], c[MAX];

//push function of stack
void push(char s[MAX])
{
	struct stack *temp = (struct stack *) malloc(sizeof(struct stack));
	strcpy(temp->sta, s);
	temp->next = NULL;
	if (temp == NULL)
		printf("Memory Overflow\n");
	else
	{
		if (st == NULL)
			st = temp;
		else
		{
			temp->next = st;
			st = temp;
		}
	}
}

//pop function of stack
void pop(char d[])
{
	struct stack *t = st;
	st = t->next;
	strcpy(d, t->sta);
	free(t);
}

//Function to count number of elements in stack
int count()
{
	int c = 0;
	struct stack *t = st;
	while (t != NULL)
	{
		c++;
		t = t->next;
	}

	return c;
}

//Function to convert postfix expression to prefix expression
void PostfixToPrefix(char post[], char pre[])
{
	int i = 0;
	char op[3];
	while (post[i] != '\0')
	{
		if (isalpha(post[i]) != 0 || isdigit(post[i] != 0))
		{
			op[0] = post[i];
			op[1] = '\0';
			push(op);
		}
		else
		{
			if (count() < 2)
			{
				printf("Not sufficient values in the expression\n");
				exit(1);
			}
			else
			{
				op[0] = post[i];
				op[1] = '\0';
				pop(a);
				pop(b);
				c[0] = '\0';
				strcat(c, op);
				strcat(c, b);
				strcat(c, a);
				push(c);
			}
		}

		i++;
	}

	if (count() == 1)
	{
		pop(pre);
		printf("Prefix Expression: %s", pre);
	}
	else
	{
		printf("Invalid user input");
	}
}

void main()
{
	char pre[MAX], post[MAX];
	printf("Enter a postfix expression: ");
	gets(post);
	PostfixToPrefix(post, pre);
}

/*
Time Compexity:
Push function - O(1)
Pop function - O(1)
Count funtion - O(n)
PostfixToPrefix function - O(n)

Space Complexity: O(n)

Sample Output: 
Enter a postfix expression: ABCDE-+^*EF*-
Prefix Expression: -*A^B+C-DE*EF
*/


<|start_filename|>C-Plus-Plus/search/Manacher's_Algorithm.cpp<|end_filename|>
#include <bits/stdc++.h>
using namespace std;
/*
Manacher's Algorithm is used to the find all the pairs (i,j) such that substring s[i…j] is a palindrome.
*/

int main() {
    string str;
    cin>>str;
    int n=str.size();
    vector<int> d1(n), d2(n); //d1 - odd length palindrome, d2 - even length palindrome
    for(int i=0, l=0, r=-1; i<n; ++i) {
        int k;
        if(i>r)
            k=1;
        else
            k=min(d1[l+r-i],r-i+1);
        while(0<=i-k && i+k<n && str[i-k]==str[i+k]){
            k++;
        }
        d1[i]=k--;
        if(i+k>r){
            l=i-k;
            r=i+k;
        }
    }
    for(int i=0, l=0, r=-1; i<n; ++i){
        int k;
        if(i>r)
            k=0;
        else
            k=min(d2[l+r-i+1],r-i+1);
        while(0<=i-k-1&&i+k<n&&str[i-k-1]==str[i+k]){
            k++;
        }
        d2[i]=k--;
        if(i+k>r){
            l=i-k-1;
            r=i+k ;
        }
    }
    int ans=0;
    cout<<"Following are the pairs which are palindromes: \n";
    for(int i=0; i<n; ++i){
        int x=d1[i];
        while(x){
            ans=max(ans, 2*x-1);
            cout<<i-x+1<<" "<<i+x-1<<"\n";
            x--;
        }
    }
    for(int i=0; i<n; ++i){
        int x=d2[i];
        while(x){
            ans=max(ans, 2*x);
            cout<<i-x<<" "<<i+x-1<<"\n";
            x--;
        }
    }
    cout<<"Length of longest palindromic substring: "<<ans;
    return 0;
}

/*
Time Complexity: O(N)
Space Complexity: O(N)

INPUT
abcba

OUTPUT
Following are the pairs which are palindromes: 
0 0
1 1
0 4
1 3
2 2
3 3
4 4
Length of longest palindromic substring: 5


INPUT
abba

OUTPUT
Following are the pairs which are palindromes: 
0 0
1 1
2 2
3 3
0 3
1 2
Length of longest palindromic substring: 4
*/


<|start_filename|>C-Plus-Plus/graphs/Bridges.cpp<|end_filename|>

#include <bits/stdc++.h> 
using namespace std;
typedef long long ll;
typedef vector<ll> vl; 
#define pb push_back 

#define loop(x,n) for(ll x = 1; x <= n; ++x)

//Adjacency List of an Undirected Graph
vl graph[100001];  

bool vis[100001];

ll in[100001],low[100001];

ll timer=1;  

void dfs(ll source,ll parent){
   vis[source]=true;
   in[source]=low[source]=timer;
   timer++;
   for(auto child:graph[source]){
       
       //if child equal to parent
       if(parent==child) continue;
       
       if(vis[child]==true)
       //back edge
        low[source]=min(low[source],in[child]);
        
        else{
            dfs(child,source);
            
            //condition for having a bridge
            if(low[child]>in[source])
             cout<<source<<"-"<<child<<" is a bridge\n";
             
             //visited forward edge
             low[source]=min(low[source],low[child]);
        }
   }
    
}
 
int main() 
{ 
    ios_base::sync_with_stdio(false); 
    cin.tie(NULL); 
    
    ll n,m,a,b;
    //n=no. of vertices, m=no. of edges
    cin>>n>>m;     
    
    loop(i,m){
     cin>>a>>b;
     graph[a].pb(b);
     graph[b].pb(a);
     }

     loop(i,n){
        //initialise visited array as false;
     vis[i]=false;    
     }
    
    loop(i,n){
       //dfs call
      if(vis[i]==false) dfs(i,-1);  
    } 
    return 0; 
}

/*
Input:
First line contains two space separated integers,(n,m) 
n- no of vertices, m- no of edges.
Then m lines follow, each line has 2 space separated integers ui ,vi which denotes edge between vertex ui to vi.


TEST CASE
4 4
1 2
2 3
2 4
3 4

OUTPUT
1-2 is a bridge

Time- complexity: O(n+m)

Space Complexity: O(n)

*/



<|start_filename|>C-Plus-Plus/cp/longest_substring_with_k_unique_characters.cpp<|end_filename|>
/**
 * Longest Substring with k Distinct Characters
 * Given a string, print the longest possible substring that 
 * has exactly K unique characters.
 */

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

int kUniqueChar(string str, int k)
{
    //2 Pointers to point to start and end of current window
    int start = 0, end = 0;
    int len = str.length();
    //Map maintains current count of each letter
    map<char, int> charCount;
    //Variable ans stores the length of longest possible substring that has exactly n unique characters
    int ans = 0;
    //Iterate until end of current window reaches end of string
    while (end < len) {
        //Updating count of current letter
        charCount[str[end]]++;
        //unique elements less than required increase window size
        if (charCount.size() < k)
            end++;
        /*if unique element equals to required we need to check
          if on increasing the window size whether repetitive element is present or not
          if present then update it as ans and increase window size*/
        else if (charCount.size() == k) {
            ans = max(ans, end - start + 1);
            end++;
        }
        else if (charCount.size() > k) {
            /*If there are more than k unique characters in
              current window, remove element from left side*/
            while (charCount.size() > k) {
                charCount[str[start]]--;
                // If occurence of character becomes 0,then we will remove it from map
                if (charCount[str[start]] == 0)
                    charCount.erase(str[start]);
                start++;
            }
            /*move forward
              increment end*/
            end++;
        }
    }
    return ans;
}

int main()
{
    string str;
    int k;
    cout << "Enter a string: ";
    cin >> str;
    cout << "Enter number of distict characters: ";
    cin >> k;
    cout << "Longest substring with " << k << " distinct characters: ";
    cout << kUniqueChar(str, k);
}

/*
	Test cases:

	INPUT:
	Enter a string: aabcbcbcbd
	Enter number of distict characters: 3
	OUTPUT:
	Longest substring with 3 distinct characters: 9

	INPUT:
	Enter a string: perepeereyjjjjj
	Enter number of distict characters: 4
	OUTPUT:
	Longest substring with 4 distinct characters: 10

	Time complexity: O(N)
	Space complexity: O(N)

*/


<|start_filename|>C-Plus-Plus/stack/CheckPalindrome.cpp<|end_filename|>
/*Check if a given string is a
palindrome or not using stacks*/

#include<iostream>
#include<string>
#include<stack>
using namespace std;

void CheckPalindrome(string s){
    stack<char> st;
    /*Push each string character onto the stack.
    This stack will have string characters in reverse order
    from top to bottom*/
    for(int i=0; i<s.length(); i++){
        st.push(s[i]);
    }
    bool flag = true;
    /*While traversing the string, take the top element
    from the stack(which will be the last element
    of string) and compare it with string's characters
    starting from s[0].*/
    for(int i=0; i<s.length(); i++){
        char x = st.top();
        /*if characters from stack and string don't match
        then mark flag as false*/
        if(x!=s[i]){
            flag = false;
            break;
        }
        //pop to got the next element of stack
        st.pop();
    }
    if(flag){
        cout<<"'"<<s<<"'"<<" is a palindrome string"<<endl;
    }
    else{
        cout<<"'"<<s<<"'"<<" is not a palindrome string"<<endl;
    }
}

int main(){
   string s;
   cout<<"Enter a string : ";
   cin>>s;
   CheckPalindrome(s);
   return 0;
}

/* SAMPLE TEST CASES :
-----------------------------------
Test 1:

Enter a string : Hello
'Hello' is not a palindrome string
-----------------------------------
Test 2:

Enter a string : abaCaba
'abaCaba' is a palindrome string
-----------------------------------
Time complexity : O(n)
Space complexity : O(n)
*/


<|start_filename|>JavaScript/other/RemoveOuterParenthesis.js<|end_filename|>
const removeOuterParenthesis = (str) => {

  // breaking the string into an array of characters
  let strArr = str.split('');
  let stack=[];

  // looping the array to check the characters
  for(let i = 0; i < strArr.length; i++){

    // we store the index if the character is an opening parenthesis
    if(strArr[i] == '(') {
      stack.push(i);
    } else {
      // removing the elements of stack
      let ele = stack.pop();

      // this checks if we have reached the outermost
      // closing parenthesis
      if(!stack.length){
        // replace the outermost characters with 0
        strArr[i] = '0';
        strArr[ele] = '0';
      }
    }
  }
  // return the string after removing the 0's and joining the characters
  return strArr.filter(x=>x!='0').join('');
}

console.log(removeOuterParenthesis("(()())(())"));
console.log(removeOuterParenthesis("(()())(())(()(()))"));

/**
 * Output for the above inputs:
 * ()()()
 * ()()()()(())
 * 
 * Time complexity: O(n)
 * Space complexity: O(n)
 */


<|start_filename|>Java/math/PalindromeRecursion.java<|end_filename|>
// Checking Palindrome number with Recursion

import java.util.Scanner;
class PalindromeRecursion
{
    static long revNum=0; //stored reversed number
    public static long palindrome(long i)
    { if(i>0) //base class
        { revNum=(revNum*10)+(i%10);
            palindrome(i/10);
        }
        else
        return revNum;
        return revNum;
    }
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.print("N = ");
        long n=sc.nextLong();
        if(n==palindrome(n))
        System.out.println(n+" is a Palindrome number");
        else
        System.out.println(n+" is not a Palindrome number");
    }
}

/*
Sample Input and Output :
 N = 153
153 is not a Palindrome number
Space Complexity: O(1)
Time Complexity : O(i) i=Number of digits in n
*/


<|start_filename|>Java/cp/MergeOverlappingArray.java<|end_filename|>
//Given a collection of intervals, merge all overlapping intervals.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class MergeOverlappingArray {

	public static int[][] merge(int[][] intervals) {
		List<int[]> list = new ArrayList<>();

		if (intervals.length == 0 || intervals == null)
			list.toArray(new int[0][]);

		Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
		int begin = intervals[0][0];
		int end = intervals[0][1];
		for (int [] j : intervals) {
			if (j[0] <= end) {
				end = Math.max(end, j[1]);
			} else {
				list.add(new int[] {begin, end});
				begin = j[0];
				end = j[1];
			}
		}
		list.add(new int[] {begin, end});
		intervals = list.toArray(new int[0][]);
		return intervals;

	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the number of intervals: ");
		int n = sc.nextInt();
		System.out.println("Enter intervals: ");
		int[][] arr = new int[n][2];
		for (int k = 0; k < arr.length; k++) {
			for (int l = 0; l < arr[k].length; l++) {
				arr[k][l] = sc.nextInt();
			}
		}
		int[][] t = merge(arr);
		for (int[] row : t) {
			System.out.println(Arrays.toString(row));
		}
		sc.close();
	}
}

/*

Input and Output of Program

Enter the number of intervals:
2
Enter intervals:
1 8
2 7
[1, 8]

Enter the number of intervals:
4
Enter intervals:
1 3
2 6
8 10
15 18
[1, 6]
[8, 10]
[15, 18]

Time Complexity: O(nlogn) + O(n)
Space Complexity: O(n)

*/


<|start_filename|>Java/dp/Climb_Stairs_With_Minimum_Moves.java<|end_filename|>
// Problem Link- https://www.pepcoding.com/resources/online-java-foundation/dynamic-programming-and-greedy/climb-stairs-with-minimum-moves-official/ojquestion
/* You are given a number n (the number of stairs in a staircase)
 * You are on the 0th step and are required to climb to the top.
 * You are given n numbers, where ith element's value represents till how far from the step you could jump to in a single move.
 * You are required to print the number of minimum moves in which you can reach the top of staircase.
*/

import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }
        int res = countStairMin(arr);
        System.out.println(res);
    }

    public static int countStairMin(int[] arr) {
        // We will use tabulation Method (Bottom Up Dynamic Programming)
        Integer[] dp = new Integer[arr.length + 1];
        // smallest problem is at end (i.e. 0 move)
        dp[arr.length] = 0;
        for (int i = arr.length - 1; i >= 0; i--) {
            // if having more than 0 steps
            if (arr[i] > 0) {
                int min = Integer.MAX_VALUE;
                // loop for number of steps
                for (int j = 1; j <= arr[i] && i + j < dp.length; j++) {
                    // getting minimum of all moves
                    if (dp[i + j] != null) {
                        min = Math.min(min, dp[i + j]);
                    }
                    if (min != Integer.MAX_VALUE) {
                        dp[i] = min + 1;
                    } else {
                        dp[i] = null;
                    }
                }
            }
        }
        return dp[0];
    }
}

/*
 * Sample input- 10 3 3 0 2 1 2 4 2 0 0 
 * Sample Output- 4
 */

 /* Time Complexity: O(N) 
  * Auxiliary Space: O(N)
*/


<|start_filename|>C-Plus-Plus/cp/max_consecutive_ones.cpp<|end_filename|>
/*
Given a binary array, binary means array's element will be 0 or 1.
find the maximum number of consecutive 1's in this array.
*/

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

int get_max_consecutive_ones(int ar[] , int N)
{
    int max_consecutive_ones = 0 , count_1 = 0;
    for(int i = 0; i < N; i++)
    {
        if(ar[i] == 1)
        {
            count_1++;
            /* here we will keep the maximum value of consecutive
            1's  */
            max_consecutive_ones = max(max_consecutive_ones, count_1);
        }
        else if(ar[i] == 0)
        {
            count_1 = 0;
            /* as array's element is zero (0)
            we will set count_1 as zero */

        }
    }
    return max_consecutive_ones;
}

int main()
{
    cout << "Enter the size of the array : \n";
    int N;
    cin >> N;
    int ar[N + 1];
    cout << "Enter array elements :\n";
    for (int i = 0; i < N; i++) 
    {
	 cin >> ar[i];
    }
    int max_consecutive_ones = get_max_consecutive_ones(ar , N);
    cout << "Maximum Consecutive Ones in this array is : ";
    cout << max_consecutive_ones << endl;
}
/*
Standard Input and Output

Enter the size of the array :
6
Enter array elements :
1 1 0 1 1 1
Maximum Consecutive Ones in this array is : 3

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

*/


<|start_filename|>C-Plus-Plus/cp/NQueens.cpp<|end_filename|>
/**
N-Queens problem is a famous problem
The paradigm used to solve the problem is backtracking
The problem is to find a way to place n queens on nXn board
such that no queen can kill the other
**/

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

#define N 20
    
void solve(bool board[N][N], bool cols[N], bool ndiag[2*N-1], bool rdiag[2*N-1], int row, string asf, int n) {
    
    if(row == n) {
        cout << asf << '.' << '\n';
        return;
    }
    
    for(int col=0; col<n; col++) {
        if(cols[col] == false && ndiag[row+col] == false && 
            rdiag[row-col+n-1] == false) {
                // place the queen
                cols[col] = true;
                ndiag[row+col] = true;
                rdiag[row-col+n-1] = true;
                board[row][col] = true;
                solve(board, cols, ndiag, rdiag, row+1, asf+to_string(row)+"-"+to_string(col)+", ", n);
                // backtrack
                cols[col] = false;
                ndiag[row+col] = false;
                rdiag[row-col+n-1] = false;
                board[row][col] = false;
            }
    }
}

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

	bool board[N][N];
    bool cols[N];
    bool ndiag[2*N-1], rdiag[2*N-1];

	// initialize
	for(int i = 0; i < n; i++)
		for(int j = 0; j < n; j++)
			board[i][j] = false;

    // initialize that no column has a queen
	for(int i = 0; i < n; i++)
		cols[i] = false;

	for(int i = 0; i < 2*n-1; i++) {
		ndiag[i] = false;
		rdiag[i] = false;
	}

	solve(board, cols, ndiag, rdiag, 0, "", n);
}

/**
Input :
4
Output :
0-1, 1-3, 2-0, 3-2, .
0-2, 1-0, 2-3, 3-1, .
Space Complexity : O(n^2)
Time Complexity : upperbounded by O(n^n)
**/

<|start_filename|>Java/cp/Queue_using_Stack.java<|end_filename|>

// Java program to implement Queue using two stacks with costly enQueue()  
import java.util.*; 
  
class QueuetoStack  
{  
static class Queue  
{  
    static Stack<Integer> stk1 = new Stack<Integer>();  
    static Stack<Integer> stk2 = new Stack<Integer>();  
  
    static void enQueue(int x)  
    {  
        // Move all elements from stk1 to stk2  
        while (!stk1.isEmpty()) 
        {  
            stk2.push(stk1.pop());  
            //stk1.pop();  
        }  
  
        // Push item into stk1  
        stk1.push(x);  
  
        // Push everything back to stk1  
        while (!stk2.isEmpty())  
        {  
            stk1.push(stk2.pop());  
            //stk2.pop();  
        }  
    }  
  
    // Dequeue an item from the queue  
    static int deQueue()  
    {  
        // if first stack is empty  
        if (stk1.isEmpty())  
        {  
            System.out.println("Q is Empty");  
            System.exit(0);  
        }  
  
        // Return top of stk1  
        int s = stk1.peek();  
        stk1.pop();  
        return s;  
    }  
};  
  
// Main method 
public static void main(String[] args)  
{  
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter limit");
    int n = sc.nextInt();
    Queue qu = new Queue();
    for(int i = 1; i <= n; i++)
       qu.enQueue(i);  
    for(int i = 1; i <= n; i++)
       System.out.println(qu.deQueue());  
    
}  
}


/* Time Complexity:
  1) Push operation: O(N).
  2) Pop operation: O(1).

Space Complexity: O(N).

Input:
10

Output:
1
2
3
4
5
6
7
8
9
10
*/


<|start_filename|>C-Plus-Plus/ds/Descending_priority_queue.cpp<|end_filename|>
/*
AIM :: TO IMPLEMENT DESCENDING PRIORITY QUEUE 

            WHAT IS DESCENDING PRIORITY QUEUE ?
 In descending order priority queue, a higher priority number is given as a higher priority in a priority. For example, 
 we take the numbers from 1 to 5 arranged in descending order like 5, 4, 3, 2, 1; 
 therefore, the largest number, i.e., 5 is given as the highest priority in a priority queue.

*/

#include <iostream>
using namespace std;

//Prototypes
void enq(int *, int &, int &, int); // for insertion
void deq(int *, int &, int &, int); // for deletion
void display(int *, int, int);      // for display

// for checking queue is full or not
int q_full(int, int);
// for checking queue is empty or not
int q_empty(int, int);

int main()
{
    int size = 100, choice;
    int Q[size];

    /*
    Initially front and rear will be at -1
    deletion will be done from front end & insertion will be done from rear end
    */
    int front = -1;
    int rear = -1;

    cout << "\t\t\nDESCENDING PRIORITY QUEUE" << endl;

    while (true)
    {
        cout << "\n1. ENQ\n2. DEQ\n3. DISPLAY\n4. EXIT" << endl;
        cout << "Enter your choice :: ";
        cin >> choice;

        switch (choice)
        {
        case 1:
            enq(Q, front, rear, size);
            break;

        case 2:
            deq(Q, front, rear, size);
            break;

        case 3:
            display(Q, front, rear);
            break;

        case 4:
            cout << "\nexiting..." << endl;
            exit(0);
            break;

        default:
            cout << "\nInvalid choice :(" << endl;
            break;
        }
    }
    return 0;
}

void enq(int Q[], int &front, int &rear, int size)
{
    int data, temp;

    if (q_full(front, size))
        cout << "QUEUE OVERFLOW" << endl;
    else
    {
        cout << "Enter the data :: ";
        cin >> data;

        //inserting for first time
        if (front == -1)
            front++;

        //find the appropriate place for the data given by the user
        for (temp = rear; temp >= 0 && data > Q[temp]; temp--)
            Q[temp + 1] = Q[temp];

        // insert data at it's right place
        Q[temp + 1] = data;
        rear++;

        display(Q, front, rear);
    }
}

void deq(int Q[], int &front, int &rear, int size)
{
    if (q_empty(front, rear))
        cout << "\nQUEUE UNDERFLOW";
    else
    {
        //storing data which is to be deleted
        int data = Q[front];

        //if front and rear is equal means there was only one element left ,So now reset front and rear
        if (front == rear)
            front = rear = -1;
        else
            front++;

        display(Q, front, rear);
    }
}

void display(int Q[], int front, int rear)
{
    if (q_empty(front, rear))
        cout << "\nQUEUE IS EMPTY :(" << endl;
    else
    {
        cout << "\nQUEUE :: ";
        for (int i = front; i <= rear; i++)
            cout << Q[i] << "    ";
        cout << '\n';
    }
}

int q_full(int rear, int size)
{
    if (rear >= size)
        return 1;

    return 0;
}

int q_empty(int front, int rear)
{
    if (front == -1 || front > rear)
        return 1;

    return 0;
}

/*
TEST CASE


DESCENDING PRIORITY QUEUE

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 1
Enter the data :: 10

QUEUE :: 10

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 1
Enter the data :: 20

QUEUE :: 20    10

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 1
Enter the data :: 15

QUEUE :: 20    15    10

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 1
Enter the data :: 5

QUEUE :: 20    15    10    5

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 2

QUEUE :: 15    10    5

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 2

QUEUE :: 10    5

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 2

QUEUE :: 5

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 2

QUEUE IS EMPTY :(

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 4

exiting...

TIME COMPLEXITY 
    INSERTION O(n)
    DELETION O(1)
*/


<|start_filename|>Java/search/Fibonacci_search.java<|end_filename|>
// Find a Fibonacci number that is greater than or equal to the size of the array in which we are searching for the key.
// Compare the key with the predecessor of the Fibonacci number obtained in Step 1 and store it in index.
// If the key and array element at index are equal then the key is present at position index + 1.        
// If the key is less than array element at index, then search the left sub-tree to index.
// If the given key is greater than the array element at index, then search the right sub-tree to index.  
// If the key is not found, repeat the steps from Step 1 to Step 5 as long as index = 0, that is, Fibonacci number >= array_size. 
// After each iteration the size of array array_size is reduced.

package Java;
import java.util.*;

public class FibonacciSearch {
    public static int getFibanociNumber(int array_Size) {
        int fibk = 0;
        int fibk2 = 0;
        int fibk1 = 1;
        if (array_Size == 0 || array_Size == 1) {
            return 0;
        }
        while (fibk < array_Size) {
            fibk = fibk1 + fibk2;
            fibk2 = fibk1;
            fibk1 = fibk;
        }
        return fibk2;
    }

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int sorted_Array[] = new int[100];
        int key, index, low, high, flag, location, array_Size;

        System.out.println("Enter the size of the array: ");
        array_Size = s.nextInt();
        System.out.println("Enter the elements of the array: ");
        for (int i = 0; i < array_Size; i++) {
            sorted_Array[i] = s.nextInt();
        }
 
        low = 0;
        location = -1;
        high = array_Size - 1;
        flag = 0;

        System.out.println("Enter the element which is to be searched: ");
        key = s.nextInt();
        s.close();

        index = 0;
        while (flag != 1 && low <= high) {
            index = getFibanociNumber(array_Size);
            if (key == sorted_Array[index + low]) {
                location = low + index;
                flag = 1;
                break;
            }
            else if (key > sorted_Array[index + low]){ 
                low = low + index + 1;
            } 
            else {
                high = low + index - 1;
            }
            array_Size = high - low + 1;
        }
        if (flag == 1){
            location += 1;
            System.out.println("The given element " + key + " found at location " + location + " ");
        }
        else {
            System.out.println("The given element " + key + " is not present in the given array");
        }
    }
}

/*TEST CASES

   Enter the size of the array: 10 
   Enter the elements of the array: -15 0 9 14 23 35 49 52 65 77 
   Enter the element which is to be searched: 52 
   The given element 52 found at location 8

  COMPLEXITY
  Time complexity O(log n) 
  Space Complexity O(1)
 */



<|start_filename|>C-Plus-Plus/math/Check_whether_a_number_is_power_of_2.cpp<|end_filename|>
/*
Given a number , check whether the number is power of 2 or not.
We can check this by doing some bitwise operation. Bitwise operations are best because they perform the operation in least possible time.
*/

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

bool number_is_power_of_2(int number)
{
    if((number & (number - 1)) == 0)
        return true;
    return false;
}
int main()
{
    cout << "Enter the number \n";
    int number;
    cin >> number;
    bool solve = number_is_power_of_2(number);
    if(solve)
        cout << "The Number is power of 2\n";
    else
        cout << "No. the number is not power of 2\n";
}
/*
Standard Input and Output

Enter the number
64
The Number is power of 2

Enter the number
34
No. the number is not power of 2

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

*/


<|start_filename|>C/ds/iterative_postorder.c<|end_filename|>
/*
The traversal operation is a frequently used operation on a binary tree. This operation is used to visit each node in the tree exactly once
A full traversal on a binary tree gives a linear ordering of data in the tree .  This is the iterative postorder tree traversal algorithms
*/
#include <stdio.h>
#include <stdlib.h>
//structure for the binary tree node
typedef struct Tree
{
    char data;
    struct Tree *left;
    struct Tree *right;
} TreeNode;
//structure for stack which is used for the iterative traversal algorithms
//stack is implemented using linked list
typedef struct Stack
{
    TreeNode *node;
    struct Stack *next;
} Stack;
//push operation for the stack
void push(Stack **s, TreeNode *node)
{
    Stack *New = (Stack *)malloc(sizeof(Stack));
    New->node = node;
    New->next = (*s);
    (*s) = New;
}
// pop operation for the stack
TreeNode *pop(Stack **s)
{
    if ((*s) != NULL)
    {
        TreeNode *ptr = (*s)->node;
        (*s) = (*s)->next;
        return ptr;
    }
}
//checks whether the stack is empty or not
int isEmpty(Stack **s)
{
    if ((*s) == NULL)
    {
        return 1;
    }
    return 0;
}
//iterative postorder traversal
void postorder(TreeNode *root)
{
    Stack *s1 = NULL;
    Stack *s2 = NULL;
    TreeNode *ptr = root;
    push(&s1, root);
    while (!isEmpty(&s1))
    {
        ptr = pop(&s1);
        if (ptr != NULL)
        {
            push(&s2, ptr);
        }
        if (ptr->left)
        {
            push(&s1, ptr->left);
        }
        if (ptr->right)
        {
            push(&s1, ptr->right);
        }
    }
    while (!isEmpty(&s2))
    {
        printf("%c ", pop(&s2)->data);
    }
}
//Search_Link returns the pointer to the node which contains the value key , it is used in the insertion operation
TreeNode *Search_Link(TreeNode *root, char key)
{
    TreeNode *ptr = root;
    if (ptr->data != key)
    {
        if (ptr->left != NULL)
        {
            Search_Link(ptr->left, key);
        }
        if (ptr->right != NULL)
        {
            Search_Link(ptr->right, key);
        }
        if (ptr->right == NULL && ptr->left == NULL)
        {
            return NULL;
        }
    }
    else
    {
        return ptr;
    }
}
// Insertion operation of the binary tree
void insert(TreeNode *root, char key, char c)
{
    TreeNode *ptr = Search_Link(root, key);
    if (ptr == NULL)
    {
        printf("Search Unsuccessfull No Insertion \n");
        return;
    }
    char option;
    if (ptr->left == NULL || ptr->right == NULL)
    {
        printf("Enter Where to insert left or right (L/R)\n");
        scanf(" %c", &option);
        if (option == 'L' || option == 'l')
        {
            if (ptr->left == NULL)
            {
                TreeNode *New = (TreeNode *)malloc(sizeof(TreeNode));
                ptr->left = New;
                New->data = c;
                printf("Inserting %c as the left\n", c);
                New->left = NULL;
                New->right = NULL;
            }
            else
            {
                printf("Insertion not Possible as Left child \n");
            }
        }
        else
        {
            if (ptr->right == NULL)
            {
                TreeNode *New = (TreeNode *)malloc(sizeof(TreeNode));
                ptr->right = New;
                New->data = c;
                printf("Inserting %c as the right\n", c);
                New->left = NULL;
                New->right = NULL;
            }
            else
            {
                printf("Insertion not possible as the right child \n");
            }
        }
    }
    else
    {
        printf("The Node Already has child");
    }
}

int main()
{
    printf("Enter the value for root node\n");
    TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode));
    char c;
    scanf("%c", &c);
    root->data = c;
    root->right = NULL;
    root->left = NULL;
    char choice = 'y';
    char data;
    do
    {
        printf("Enter the Node to be Inserted \n");
        scanf(" %c", &data);
        printf("Enter the Parent node of the node to be inserted\n");
        scanf(" %c", &c);
        insert(root, c, data);
        printf("Do you want to continue (y/n)\n");
        scanf(" %c", &choice);
    } while (choice == 'y' || choice == 'Y');
    printf("Postorder Traversal of the Tree \n");
    postorder(root);
    return 0;
}
/*
Sample I/O:

Enter the value for root node
A
Enter the Node to be Inserted
B
Enter the Parent node of the node to be inserted
A
Enter Where to insert left or right (L/R)
L
Inserting B as the left
Do you want to continue (y/n)
y
Enter the Node to be Inserted
C
Enter the Parent node of the node to be inserted
A
Enter Where to insert left or right (L/R)
R
Inserting C as the right
Do you want to continue (y/n)
n
Preorder Traversal of the Tree
B C A

Time Complexity = O( n )
Space Complexity = O( n )
*/


<|start_filename|>Java/search/ManacherAlgorithm.java<|end_filename|>
import java.util.*;

class ManacherAlgorithm {

    public static String manacherSearch(String str) {

        // array for holding the palindromic sequence around every center
        ArrayList<Integer> positions = new ArrayList<Integer>();
        int start = 0;
        int end = 0;

        // i is our current center
        for (int i = 0; i < str.length();) {

            // we check on both sides of i till where we can find same letters on 2
            // positions
            while (start > 0 && end < str.length() - 1 && str.charAt(start - 1) == str.charAt(end + 1)) {
                start--;
                end++;
            }

            // getting the length of palindrome around current center
            positions.add(i, end - start + 1);

            // this is case 2. Current palindrome is proper suffix of input. Meaning input
            // is the longest palindrome
            if (end == (str.length() - 1)) {
                break;
            }

            // Mark newCenter to be either end or end + 1 depending on if we dealing with
            // even or old number input.
            int newCenter = end + (i % 2 == 0 ? 1 : 0);

            for (int j = i + 1; j <= end; j++) {

                // Its possible left mirror might go beyond current center palindrome. So take
                // minimum of either left side palindrome or distance of j to end.
                // T[j] = Math.min(T[i - (j - i)], 2 * (end - j) + 1);
                positions.add(j, (Math.min(positions.get(i - (j - i)), 2 * (end - j) + i)));

                // This check is to make sure we do not pick j as new center. As soon as we find
                // a center lets break out of this inner loop.
                if (j + positions.get(i - (j - i)) / 2 == end) {
                    newCenter = j;
                    break;
                }
            }

            // make i as newCenter. Set right and left to atleast the value we already know
            // should be matching based of left side palindrome.
            i = newCenter;
            if (i < positions.size()) {
                end = i + positions.get(i) / 2;
                start = i - positions.get(i) / 2;
            }

        }

        int max = Collections.max(positions);
        int pos = positions.indexOf(max);

        if (str.length() % 2 == 0) {
            str = str.substring(pos - (max / 2), pos + (max / 2) + 1);
        } else {
            str = str.substring(pos - (max / 2), pos + (max / 2));
        }

        // removing $ signs
        str = originalString(str);

        return str;
    }

    public static String originalString(String str) {
        StringBuilder sBuilder = new StringBuilder();

        // getting original String from processed one
        for (int i = 0; i < str.length(); i++) {
            if (i % 2 != 0) {
                sBuilder.append(str.charAt(i));
            }
        }
        return sBuilder.toString();
    }

    public static String process(String str) {
        StringBuilder sBuilder = new StringBuilder();

        // preprocessing string and adding a symbol between letters to take care of
        // strings with even number of characters
        for (int i = 0; i < str.length(); i++) {
            sBuilder.append("$");
            sBuilder.append(str.charAt(i));
        }
        sBuilder.append("$");
        return sBuilder.toString();
    }

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a string:");
        String str = sc.nextLine();
        sc.close();

        str = process(str);

        str = manacherSearch(str);
        System.out.println("Longest palindromic substring: " + str);
        System.out.println("Length of longest substring: " + str.length());
    }
}

/*
 * Sample input/output
 *
 * Enter a string: abba Longest palindromic substring: abba Length of longest
 * substring: 4
 *
 * Enter a string: babcbaabcbaccba Longest palindromic substring: abcbaabcba
 * Length of longest substring: 10
 *
 * Time complexity: O(n) Space complexity: O(n)
 */


<|start_filename|>C-Plus-Plus/cp/NextPermutation.cpp<|end_filename|>
/**
Given an array, fing the next lexicographical largest permutation
**/

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

vector<int> nextPermutation(vector<int> &A) {
    int k = A.size()-1;
    while(A[k-1] >= A[k] && k > 0)
        k--;
    if(k == 0)
        reverse(A.begin(), A.end());
    else {
        int t = A[k-1];
        int m = k;
        for(int i=k+1; i<A.size(); i++)
            if(A[i] > t && A[i] < A[k])
                m = i;
        A[k-1] = A[m];
        A[m] = t;
        sort(A.begin()+k, A.end());
    }
    return A;
}

int main() {
    int n;
    cin >> n;
    vector<int> arr(n);
    for(int i = 0; i < n; i++)
        cin >> arr[i];
    nextPermutation(arr);
    cout << "The next permutation of the array is : \n";
    for(int i = 0; i < n; i++)
        cout << arr[i] << ' ';
    cout << '\n';
    return 0;
}

/**

Input :
6
5 3 4 9 7 6
Output :
6
5 3 4 9 7 6

Time Complexity : O(nlogn)
Space Complexity : O(n)

**/

<|start_filename|>C-Plus-Plus/cp/Peak_element.cpp<|end_filename|>
/**An array element is a peak if it is NOT smaller than
its neighbours. For corner elements, we need to
consider only one neighbour.
Since an array always have a maximum value therefore an peak element always be there and there can be many peak element.
Approach :If the middle element is not the peak element, then check if the element on the right side is greater than the middle element 
then there is always a peak element on the right side. 
If the element on the left side is greater than the middle element then there is always a peak element on the left side.
**/
#include <bits/stdc++.h>
using namespace std;

// recursive approach
int find_peak_recursive(vector<int> v, int l, int r)
{
	if (l < r)
	{
		int mid = l + (r - l) / 2;
		// for corner cases
		if (mid == 0 || mid + 1 == v.size())
		{
			if (mid == 0)
			{
				if (v[0] >= v[1])
					return v[0];
				else
					return v[1];
			}
			else
			{
				if (v[mid] >= v[mid - 1])
					return v[mid];
				else
					return v[mid - 1];
			}
		}
		else if (v[mid] >= v[mid - 1] && v[mid] >= v[mid + 1])
			return v[mid];

		else if (v[mid] < v[mid + 1])
			return find_peak_recursive(v, mid + 1, r);

		else
			return find_peak_recursive(v, l, r - 1);
	}

	return -1;
}

// using while loop approach
int find_peak_iter(vector<int> arr)
{
	int start = 0, n = arr.size();
	int end = n - 1;
	while (start <= end)
	{
		int mid = start + (end - start) / 2;
		if (mid - 1 >= 0 && mid + 1 < n)
		{
			if (arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1])
			{
				return arr[mid];
			}
			else if (arr[mid] < arr[mid - 1])
			{
				end = mid - 1;
			}
			else
			{
				start = mid + 1;
			}
		}

		// for corner cases
		else if (mid == 0)
		{
			if (arr[0] > arr[1])
			{
				return arr[0];
			}
			else
			{
				return arr[1];
			}
		}

		// for corner cases
		else if (mid == n - 1)
		{
			if (arr[n - 1] > arr[n - 2])
			{
				return arr[n - 1];
			}
			else
			{
				return arr[n - 2];
			}
		}
	}

	return -1;
}

int main()
{
	int n;
	cout << "Enter the number of elements in the array : ";
	cin >> n;
	vector<int> v(n);
	cout << "\nEnter the elements of the array : \n";
	for (int i = 0; i < n; i++)
	{
	    cin >> v[i];
	}

	int peak_recursive = find_peak_recursive(v, 0, n - 1);
	cout << "Peak element (Recursive approach) : " << peak_recursive << "\n";

	int peak_iter = find_peak_iter(v);
	cout << "Peak element (Iterative approach) : " << peak_iter << "\n";

	return 0;
}

/**
Eg. :
Input: 
Enter the number of elements in the array : 7
Enter the elements of the array : 10 20 15 2 23 90 67

Output: 
Peak element (Recursive approach) : 90
Peak element (Iterative approach) : 20

Time Complexity : O(log(N))
Space Complexity : O(N)
**/


<|start_filename|>C/cp/max_sum_subarray.c<|end_filename|>
#include<stdio.h>

int max(int a,int b) {
    return (a >= b) ? a : b;
}

int max_sum_crossing(int arr[], int lo, int mid, int hi) {
    int cur = 0, presum = -1e9;
    for (int i = mid; i >= lo; --i) {
        cur += arr[i];
        presum = max(presum, cur);
    }
    cur = 0;
    int postsum = -1e9;
    for (int i = mid + 1; i <= hi; ++i) {
        cur += arr[i];
        postsum = max(postsum, cur);
    }

    return max(max(presum, postsum), presum + postsum);

}

int max_sum_subarray(int arr[], int lo, int hi) {
    if(lo == hi) {
        return arr[lo];
    }
    int mid = lo + (hi - lo) / 2;
    return max(max(max_sum_subarray(arr, lo, mid), max_sum_subarray(arr, mid+1, hi)), max_sum_crossing(arr, lo, mid, hi));
}

int main() {
    int n;
    scanf("%d", &n);
    int arr[n];
    for (int i = 0; i < n; ++i) {
        scanf("%d", &arr[i]);
    }
    int ans = max_sum_subarray(arr, 0, n-1);
    printf("The maximum sum subarray is: %d", ans);
    return 0;
}

/*
Time Complexity: O(N logN)

INPUT 1:
5
1 3 2 4 7
OUTPUT 1:
The maximum sum subarray is: 17

INPUT 2:
5
1 -1 2 3 -2
OUTPUT 2:
The maximum sum subarray is: 5

*/


<|start_filename|>C/cp/catalan_number.c<|end_filename|>
/*
The Catalan numbers form a sequence of natural numbers that occur in various 
counting problems, often involving recursively-defined objects.

Application in some combinatorial problems:
1.Number of correct bracket sequence consisting of n opening and n closing brackets.
2.The number of rooted full binary trees with n+1 leaves (vertices are not numbered). A rooted binary tree is full if every vertex has either two children or no children.
3.The number of ways to completely parenthesize n+1 factors. 
*/

#include <stdio.h>

int catalan(int num)
{
	if (num <= 1)
	{
		return 1;
	}

	int res = 0;
	for (int i = 0; i < num; i++)
		res += catalan(i) *catalan(num - i - 1);
	return res;
}

int main()
{
	int num;
	printf("Enter Number: ");
	scanf("%d", &num);
	printf("\n");
	for (int i = 1; i <= num; i++)
	{
		printf("%d ", catalan(i));
	}

	return 0;
}

/*
Sample input and output
Enter number: 7
1 2 5 14 42 132 429

time complexity: O(n^2)
space complexity: O(n)
*/ 


<|start_filename|>C/ds/Circular_LL.c<|end_filename|>
#include<stdio.h>
#include<stdlib.h>

typedef struct node
{
	int data;
	struct node * next;
}node;

node * insert_at_beg(node *,int);
node * insert_at_pos(node *,int,int);
node * insert_at_end(node *,int);
node * delete_at_beg(node *);
node * delete_at_pos(node *,int);
node * delete_at_end(node *);
node * count_length(node *);
node * display(node *);
node * check_empty(node *);
int search_element(node *,int);
void sortList(node *);
void reverseList(node **); 

node * insert_at_beg(node *head,int value)
{
    node *temp1=(node *)malloc(sizeof(node));
    temp1->data=value;
    if(head==NULL)
    {
        head=temp1;
        temp1->next=head;
    }
    else
    {
        temp1->next = head;
        node *ptr1 = head;
        while(ptr1->next != head)
        {
            ptr1= ptr1->next;
        }
        ptr1->next = temp1;
        head = temp1;
    }
    return head;
}

node * insert_at_pos(node *head,int value,int pos)
{
    node *temp2=(node *)malloc(sizeof(node));
    temp2->data=value;
    if(head==NULL)
    {
        printf("List is Empty.Inserting at beginning");
        head=insert_at_beg(head,value);
    }
    else if(pos==1)
        head=insert_at_beg(head,value);
    else
    {
        node *ptr2 = head;
        for(int i=2; i<=pos-1; i++)
        {
            ptr2 = ptr2->next;
        }
        temp2->next = ptr2->next;
        ptr2->next = temp2;
    }
    return head;
}

node * insert_at_end(node *head, int value)
{
    node *temp3=(node *)malloc(sizeof(node));
    temp3->data=value;
    node *ptr3=head;
    while(ptr3->next !=head)
        ptr3=ptr3->next;
    ptr3->next=temp3;
    temp3->next=head;
    return head;
}

node * delete_at_beg(node *head)
{
    if(head==NULL)
        printf("\n UNDERFLOW \n");
    else
    {
        node * temp4=head;
        while(temp4->next != head)
            temp4=temp4->next;
        head=head->next;
        printf("\n Deleted First Node\n");
        temp4->next=head;
    }
    return head;
}

node * delete_at_pos(node *head,int pos)
{
    node *temp5=(node *)malloc(sizeof(node));
    if(head==NULL)
    {
        printf("List is Empty.Nothing to delete.");
    }
    else if(pos==1)
        head=delete_at_beg(head);
    else
    {
        node *ptr5 = head;
        int i=1;
        while(i<pos)
        {
            temp5=ptr5;
            ptr5=ptr5->next;
            i++;
        }
        temp5->next = ptr5->next;
        free(ptr5);
    }
    return head;
}

node * delete_at_end(node * head)
{
    if(head==NULL)
        printf("\n UNDERFLOW\n");
    else if(head->next==head)
    {
        head=NULL;
        printf("\nDELETED\n");
    }
    else
    {
        node * temp6=head;
        node *ptr6=(node *)malloc(sizeof(node));
        while(temp6->next !=head)
        {
            ptr6=temp6;
            temp6=temp6->next;
        }
        ptr6->next=temp6->next;
        printf("\nDELETED LAST NODE\n");
    }
    return head;
}

node *count_length(node *head)
{
    int count=0;
    if(head==NULL)
    {
        printf("No of elements = 0");
    }
    else
    {
        node *temp7=(node *)malloc(sizeof(node));
        temp7=head;
        do{
            count++;
            temp7=temp7->next;
        }while(temp7 !=head);
        printf("Length of list : %d",count);
    }
    return head;
}

node * display(node *head)
{
    node *temp8;
    if(head == NULL)
    {
        printf("List is empty.\n");
    }
    else
    {
        temp8=head;
        do {
            printf("%d---->", temp8->data);
            temp8 = temp8->next;
        }while(temp8 != head);
    }
    return head;
}

node * check_empty(node *head)
{
    if(head==NULL)
        printf("List is empty");
    else
        printf("List is not empty");
    return head;
}

int search_element(node *head,int key)
{
    int j = 0;
    node *temp9 = head;
    do 
    {
		if (temp9 == NULL)
			return 0;
		
		if (temp9->data == key)
			return j;
        temp9 = temp9->next;
		j++;
    } while (temp9 != head);
    return -1;
}

void sortList(node *head)
{  
    node *temp10 = head;
    node *ptr10 = NULL;  
    int x;  
    if(head == NULL)  
        printf("List is empty");  
    else {  
        do{  
            ptr10 = temp10->next;  
            while(ptr10 != head) {  
                if(temp10->data > ptr10->data) {  
                    x =temp10->data;  
                    temp10->data= ptr10->data;  
                    ptr10->data = x;  
                }  
                ptr10= ptr10->next;  
            }  
            temp10 =temp10->next;  
        }while(temp10->next != head);   
    }  
}  

void reverseList(struct node **head) 
{
    struct node *prev, *cur, *next, *last;
    if (*head == NULL)
        printf("Cannot reverse empty list.\n");
    else
    {   last = *head;
        prev  = *head;
        cur   = (*head)->next;
        *head = (*head)->next;
        while (*head != last)
        {
            *head = (*head)->next;
            cur->next = prev;
            prev = cur;
            cur  = *head;
        }
        cur->next = prev;
        *head = prev;
    }
}


void main()
{
    node *head=NULL;
    int element,position,index;
    int choice=0;

    while (choice !=6)
    {
        printf("1-> Insert at beginning\n");
        printf("2-> Insert at position\n");
        printf("3-> Insert at end\n");
        printf("4-> Delete at beginning\n");
        printf("5-> Delete at position\n");
        printf("6-> Delete at end\n");
        printf("7-> Count No of nodes\n");
        printf("8-> Display \n");
        printf("9-> Check Empty \n");
        printf("10-> Search Element\n");
        printf("11-> Sort List\n");
        printf("12-> Reverse List\n");
        printf("13-> Exit\n");
        printf(" Enter Choice \n");
        scanf("%d",&choice);
        switch(choice)
        {
            case 1: printf("Enter the element\n");
                    scanf("%d",&element);
                    head=insert_at_beg(head,element);
                    printf("INSERTED\n");
                    break;
                    
            case 2: printf("Enter the element\n");
                    scanf("%d",&element);
                    printf("Enter the position\n");
                    scanf("%d",&position);
                    head=insert_at_pos(head,element,position);
                    printf("INSERTED\n");
                    break;

            case 3: printf("Enter the element\n");
                    scanf("%d",&element);
                    head=insert_at_end(head,element);
                    printf("INSERTED\n");
                    break;
                    
            case 4: head=delete_at_beg(head);
                    head=display(head);
                    printf("\n");
                    break;
            
            case 5:printf("Enter the position\n");
                    scanf("%d",&position);
                    head=delete_at_pos(head,position);
                    printf("DELETED\n");
                    break;
                    
            case 6: head=delete_at_end(head);
                    head=display(head);
                    printf("\n");
                    break;
                    
            case 7: head=count_length(head);
                    printf("\n");
                    break;
                    
            case 8: head=display(head);
                    printf("\n");
                    break;
                    
            case 9: head=check_empty(head);
                    printf("\n");
                    break;
                    
            case 10:printf("Enter element to search: ");
				    scanf("%d", &element);
				    index = search_element(head, element);
				    if (index == -1)
					    printf("%d not found in list.\n", element);
				    else 
                	    printf("%d found at %d position.\n", element, (index + 1));
                    break;
                    
            case 11:sortList(head);
                    break;
                    
            case 12: reverseList(&head);
                    printf("List reversed.\n");
                    break; 

            case 13: exit(0);
                    break;
                    
            default:printf("\nInvalid Choice !!\n");
                    break;
        }
    }
}




<|start_filename|>Java/ds/DEQueue.java<|end_filename|>
/**
 * Double Ended Queue is a linear data structure which follows both -
 * LIFO(Last In First Out) and FIFO(First In First Out).
 * 
 * Push Front  ---> O - O - O - O - O - O <---  Push Rear
 *                  |   |   |   |   |   |
 *   Pop Front <--- O - O - O - O - O - O ---> Pop Rear
 *              ^                   ^
 *            First                Last
 *           (Front)              (Rear)
 *            
 * The code has six methods:
 * void pushfront(int) - to insert a value at the front end of the queue
 * void pushrear(int) - to insert a value at the rear end of the queue
 * int popfront() - to delete a value from the front end of the queue
 * int poprear() - to delete a value from the rear end of the queue
 * void display() - to display the queue
 * void main() - driver code to execute all the methods
 * 
 * In addition to the methods, the code also has a default constructor DEQueue(int)
 * to initialize the global parameters:
 * integer array dequeue[] - to store the elements
 * integer variable elements - to keep a count of the number of elements in the queue
 * integer variable front - to point at the front end of the dequeue
 * integer variable rear - to point at the rear end of the dequeue
 * 
 * To take input from the user, Scanner class has been instantiated.
 * 
 */

import java.util.*;

public class DEQueue
{
    Scanner scanner = new Scanner(System.in);

    int dequeue[], elements, front, rear;

    DEQueue(int size)
    {
        dequeue = new int[size];
        elements=0;
        front=-1;
        rear=-1;
    }

    void pushfront(int value)
    {
        if(elements==dequeue.length)
        { 
            System.out.println("Overflow");
        }
        else
        {
            if(front==0)
            {
                System.out.println("Front full");
            }
            else
            {
                elements++;
                front--;
                dequeue[front]=value;
            }
        }
    }

    void pushrear(int value)
    {
        if(elements==dequeue.length)
        {
            System.out.println("Overflow");
        }
        else
        {
            elements++;
            rear++;
            if(front==-1)
            {
                front=0;
            }
            dequeue[rear]=value;
        }
    }

    int popfront()
    {
        int temp=0;
        if(elements==0)
        {
            System.out.println("Underflow");
        }
        else
        {
            temp=dequeue[front];
            front++;
            elements--;
            if(elements==0)
            {
                front=-1;
                rear=-1;
            }
        }
        return temp;
    }

    int poprear()
    {
        int temp=0;
        if(elements==0)
        {
            System.out.println("Underflow");
        }
        else
        {
            temp=dequeue[rear];
            rear--;
            elements--;
            if(elements==0)
            {
                front=-1;
                rear=-1;
            }
        }
        return temp;
    }

    void display()
    {
        if(elements==0)
        {
            System.out.println("Queue is empty!");
        }
        else
        {
            for(int pointer=front; pointer<=rear; pointer++)
            {
                System.out.print(dequeue[pointer]+" ");
            }
            System.out.println();
        }
    }

    void main()
    {
        // Driver code to call all the methods, until the user wishes

        System.out.println("Enter size of the dequeue: ");
        int size = scanner.nextInt(); 
        scanner.nextLine();

        DEQueue ob = new DEQueue(size);

        int flag=1,value;

        System.out.println("Which function would you like to implement?");
        System.out.println("1. Inserting element in the front of the dequeue");
        System.out.println("2. Inserting element in the rear of the dequeue");
        System.out.println("3. Deleting element from the front of the dequeue");
        System.out.println("4. Deleting element from the rear of the dequeue");
        System.out.println("5. Displaying the dequeue");

        while(flag!=0)
        {
            System.out.println("Enter your choice");
            int choice = scanner.nextInt(); 
            scanner.nextLine();
            
            switch(choice)
            {
                case 1:
                System.out.println("Enter element to be inserted: ");
                value = scanner.nextInt(); scanner.nextLine();
                    ob.pushfront(value);
                break;

                case 2:
                System.out.println("Enter element to be inserted: ");
                value = scanner.nextInt(); scanner.nextLine();
                    ob.pushrear(value);
                break;

                case 3:
                    ob.popfront();
                break;

                case 4:
                    ob.poprear();
                break;

                case 5:
                    ob.display();
                break;
            }
            System.out.println("Would you like to continue? Enter 1 for YES and 0 for NO:");
            flag = scanner.nextInt(); 
            scanner.nextLine();
        }
    }
}

/* Test Case-
Enter size of the dequeue: 
5
Which function would you like to implement?
1. Inserting element in the front of the dequeue
2. Inserting element in the rear of the dequeue
3. Deleting element from the front of the dequeue
4. Deleting element from the rear of the dequeue
5. Displaying the dequeue
Enter your choice
2
Enter element to be inserted: 
1
Would you like to continue? Enter 1 for YES and 0 for NO:
1
Enter your choice
2
Enter element to be inserted: 
2
Would you like to continue? Enter 1 for YES and 0 for NO:
1
Enter your choice
2
Enter element to be inserted: 
3
Would you like to continue? Enter 1 for YES and 0 for NO:
1
Enter your choice
5
1 2 3 
Would you like to continue? Enter 1 for YES and 0 for NO:
1
Enter your choice
3
Would you like to continue? Enter 1 for YES and 0 for NO:
1
Enter your choice
5
2 3 
Would you like to continue? Enter 1 for YES and 0 for NO:
1
Enter your choice
4
Would you like to continue? Enter 1 for YES and 0 for NO:
1
Enter your choice
5
2 
Would you like to continue? Enter 1 for YES and 0 for NO:
1
Enter your choice
4
Would you like to continue? Enter 1 for YES and 0 for NO:
1
Enter your choice
5
Queue is empty!
Would you like to continue? Enter 1 for YES and 0 for NO:
0
*/  
   
/* Time Complexity: O(1)
Space Complexity: O(size) */
 


<|start_filename|>C-Plus-Plus/cp/first1_binsearch.cpp<|end_filename|>
/*Code to find the first index in which 1 appears in an array of 0 and 1
APPROACH USED -Binary Search
*/
#include<bits/stdc++.h>
using namespace std;
int binSearch(int a[],int n)
{
    int l=0,r=n-1,mid=0;
    while(l<=r)
    {
        mid=(l+r)/2;
        if(a[mid]==1 && (mid==0 || a[mid-1]==0))
        return mid+1;
        else if(a[mid]==1)
        r=mid-1;
        else l=mid+1;
    }
    return -1;
}
int main()
{
    int n;
    cin>>n;
    int a[n];
    cout<<"Enter only 1 and 0 in sorted order\n";
    for(int i=0;i<n;i++)
    cin>>a[i];
    sort(a,a+n);
    cout<<binSearch(a,n);
}
/*
TIME COMPLEXITY: O(nlogn)
INPUT:
5
Enter only 1 and 0 in sorted order
1 1 1 1 1
OUTPUT:1

INPUT:
5
Enter only 1 and 0 in sorted order
0 0 0 0 0
OUTPUT:-1
*/


<|start_filename|>C-Plus-Plus/cp/Reverse_Lookup_in_1D_array.cpp<|end_filename|>
/*
Problem : 
	Given an array of size N. Find the total sum of all the subarrays in the array.

-->Efficient Method : (USING REVERSE LOOKUP)
	-> Find the count of subarrays where a particular element is included.
	-> Once we have the repetition number, we can multiply it with the value of element to get its contribution.
	-> For an element with value 'X' at i-th position :-
	    -- the number of subarrays starting from index 0 to i = i + 1 
	    -- the number of subarrays ending on indices from i to N-1 = N - i
    -> The total contribution by X = X * repetitions  = X * ((i + 1) * (N - i)).
    -> Total time complexity => O(N).

Note :- 
Modular arithmethic to avoid overflows:
-> (a + b) % M = ((a % M) + (b % M)) % M
-> (a * b) % M = ((a % M) * (b % M)) % M
where, M = 10^9 + 7
*/

#include <bits/stdc++.h>
using namespace std;
const long long M = 1e9 + 7;

/* function subset_sums() calculates the total sum of all subsets. 
   contribution variable denotes the contribution given by each element in the array.    
*/
long long subset_sums(vector<int>& array, int n){
    long long sum = 0, contribution;
    for (int i = 0; i < n; i++) {
        contribution = (((i+1) % M * (n-i) % M) % M * array[i] % M) % M;
        sum = ((sum % M) + (contribution % M)) % M;
    }
    return sum;
}

int main()
{
    int n, value;
    long long total_sum;
    vector<int> array;
    cin >> n; 

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

    // calculating subset sums
    total_sum = subset_sums(array, n);
    cout << total_sum << endl;

    return 0;
}


/*
Input : 
6
2 3 4 7 8 9

Output:
308

Time Complexity : O(n)
Space Complexity : O(1)
*/


<|start_filename|>Go/search/Binary_Recursive_Search/BinarySearchRecursive.go<|end_filename|>

/* Below code is an implementation of binary search in Golang using
recursive method. An array is taken as input from the user, followed
by the element the user wants to search in the array. The search function
is called. If the element is present in the array, then print the index
of the element in the array.
NOTE : For binary search to work, the input array must be SORTED*/

package main

import (
	"fmt"
)

// This function recursively searches for element in array
func search(array []int, left, right, element int) int {

	// If left pointer exceeds the right pointer
	if(left > right) {
		return -1
	} else {
		// Find the middle index
		var middle int = left + (right - left) / 2;
		// If element is found return index
		if(array[middle] == element) {
			return middle
		} else if(array[middle] > element) {
			/* If middle element is greater than the given
			element to search, then, recursively search in
			the left half of the array.*/
			return search(array, left, middle - 1, element)
		} else if(array[middle] < element) {
			/* If middle element is less than the given
			element to search, then, recursively search
			in the right half of the array.*/
			return search(array, middle + 1, right, element);
		}
	}
	// If not found, return -1
	return -1
}

func main() {

	// Take length of array as input from the user
	fmt.Print("Enter the length of the array: ")
	var n int
	fmt.Scan(&n)

	// Take elements of array as input from the user
	fmt.Print("Enter ", n, " elements followed by spaces: ")
	array := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&array[i])
	}

	// Take element to search as input from the user
	fmt.Print("Enter the element you want to search: ")
	var element int
	fmt.Scan(&element)

	// Call search function to find the index
	var index int = search(array, 0, n - 1, element)

	/* If index is -1, the element is not present
	Else print index of element in the array*/
	if(index == -1) {
		fmt.Print("\nThe element ", element, " is not present in the array.\n")
	} else {
		fmt.Print("\nThe element ", element, " is present at ", index, " index in the array.\n");
	}
}

/* Sample I/O:

a)

Enter the length of the array: 5
Enter 5 elements followed by spaces: -1 3 5 9 21
Enter the element you want to search: 3

The element 3 is present at 1 index in the array.

b)

Enter the length of the array: 5
Enter 5 elements followed by spaces: -2 -1 3 4 6
Enter the element you want to search: 2

The element 2 is not present in the array.
*/


<|start_filename|>C/sort/MergeSort.c<|end_filename|>
// MERGE SORT IN C
#include<stdio.h>
void main()
{
    int arraySize ,  index;
    printf("Please enter the size of the array\n");
    scanf("%d",&arraySize);
    int arr[arraySize];
    printf("Please enter the elements to sort\n");
    for(index=0 ; index<arraySize ; index++)
    {
        scanf("%d",&arr[index]);// You would now fill the array with the numbers you want to sort
    }

    // Now the lower bound and upper bound values would be defined

int lower_bound =0;
int upper_bound = arraySize-1;

// we pass three parameters to the mergeSort function

mergeSort(arr,lower_bound, upper_bound);

printf("SORTED ARRAY\n");

for(index=0 ; index<arraySize ; index++)
    {
        printf("%d\t",arr[index]);
    }

}
int mergeSort(int arr[],int lower_bound, int upper_bound)
{
    // We use recursion to divide the array

    if(lower_bound<upper_bound)
    {
        int mid = (lower_bound+upper_bound)/2;
        mergeSort(arr,lower_bound,mid);
        mergeSort(arr,mid+1,upper_bound);

        // Now we use merge function to join the array in a sorted manner
        merge(arr , lower_bound , mid , upper_bound );
    }
}
int merge(int arr[],int lower_bound , int mid , int upper_bound )
{
    int variable_a = lower_bound ;
   int variable_b = mid+1;
    int variable_c = lower_bound;
    int size = upper_bound+1 ;
    int arr_new[size]; // we create a new array by arr_new
    while(variable_a<=mid && variable_b<=upper_bound )
    {
        if(arr[variable_a]<=arr[variable_b])
{
    arr_new[variable_c] = arr[variable_a];
    variable_a++;

}
else
{
    arr_new[variable_c] = arr[variable_b];
    variable_b++ ;

}
variable_c++;
    }

    if(variable_a>mid)
    {
        while(variable_b<=upper_bound)
        {
            arr_new[variable_c] = arr[variable_b];
            variable_b++ ;
            variable_c++;

        }
    }
else
{
    while(variable_a<= mid )
    {
        arr_new[variable_c] = arr[variable_a];
        variable_a++ ;
        variable_c++ ;

    }
}
for(variable_c=lower_bound; variable_c<=upper_bound ; variable_c++)
    // Copying the sorted values from array_new to arr
    {
       arr[variable_c] = arr_new[variable_c];
    }

}





<|start_filename|>C/ds/reverse_linked_list.c<|end_filename|>
/* GIVEN A LINKED LIST ,TASK IS TO REVERSE THE LINKED LIST BY REVERSING THE LINKS */
#include<stdio.h>
#include<malloc.h>

/* structure containing data part and link part */
struct node
{
	int data;
	struct node *link;
};

void append(struct node** ,int);
void display(struct node*);
void reverse(struct node **);

int main()
{
    struct node* head = NULL;  
    int i,p,c;
    
    printf("ENTER THE NUMBER OF ELEMENTS IN LINKED LIST "); 
    scanf("%d",&i); 
    for(p=i;p>0;p--)  
    {  
        printf("\nENTER THE ELEMENT ");
        scanf("%d",&c);
        append(&head,c);  
    }
	
	printf("LINKED LIST: \n");
	display(head);
	reverse(&head);
	printf("\nREVERSED LINKED LIST: \n");	
	display(head);
						
	return 0;
}

/*adds node at the end of a linked list*/
void append(struct node **head_ref,int num)
{
	struct node *temp,*r;
	
	if(*head_ref==NULL)
	{
		temp=(struct node*)malloc(sizeof(struct node));
		temp->data=num;
		temp->link=NULL;
		*head_ref=temp;
	}
	else
	{
		temp=*head_ref;
		/* go to last node */
		while(temp->link != NULL)
		{
			temp = temp->link;
		}
		/* add node at end */
		r=(struct node*)malloc(sizeof(struct node));
		r->data=num;
		r->link=NULL;
		temp->link=r;
	}
}

/* displays the content of linked list */
void display(struct node *head_ref)
{	
	/* traverse the entire linked list */
	while(head_ref!=NULL)
	{
		printf("%d\t",head_ref->data);
		head_ref=head_ref->link;
	}
}

/*reverses the linked list*/
void reverse(struct node **head_ref)
{
	struct node *cur,*prev,*next;
	
	cur=*head_ref;
	prev=NULL;
	next=NULL;
	
	/*traverse the entire linked list*/
	while(cur!=NULL)
	{
		next=cur->link;
		/*reverse current node pointers*/
		cur->link=prev;
		/*move pointers one position ahead*/
		prev=cur;
		cur=next;
	}
	
	*head_ref=prev;
}

/*
SAMPLE INPUT OUTPUT

ENTER THE NUMBER OF ELEMENTS IN LINKED LIST 5

ENTER THE ELEMENT 4

ENTER THE ELEMENT 12

ENTER THE ELEMENT 6

ENTER THE ELEMENT 25

ENTER THE ELEMENT 41
LINKED LIST:
4       12      6       25      41
REVERSED LINKED LIST:
41      25      6       12      4

TIME COMPLEXITY -> O(n)
SPACE COMPLEXITY -> O(1)*/


<|start_filename|>C/operating_system/Round_Robin_Scheduling.c<|end_filename|>
/*
About Round Robin Scheduling:-
It is a CPU scheduling technique in which each process is given a fixed time quantum/slice.
Once the time quantum is over for a process, the CPU gets preempted to another process in the ready queue.
    -It is a preemptive scheduling technique.
    -As all processes get fair share of CPU, it a starvation-free CPU scheduling algorithm.
    -The disadvantage of it is more overhead of context switching.

Time related to each process-
Arrival Time(AT)-The time at which process enters into the ready queue.
Burst Time(BT)-The total time required by the CPU to execute the whole process.
Completion Time(CT)-The time at which the process enters into completion state.
Turn Around Time(TAT)-The total amount of time spent by the process from its completion.
                      It is calculated as - TAT=CT-AT
Waiting Time(WT)-The total time for which the process waits for the CPU to be assigned.
                 It is calculated as - WT=TAT-BT
Response Time(RT)-The difference between arrival time and the time at which the process first gets the CPU.
*/

#include<stdio.h>
#include<stdlib.h>

//Structure for queue
struct node
{
    int data;
    struct node *next;
};
struct node *front=NULL;
struct node *rear=NULL;

//push function for queue
void push(int x)
{
    struct node *new=(struct node*)malloc(sizeof(struct node));  
    new->data=x;
    new->next=NULL;
    if(front==NULL && rear==NULL)
    {
        front=rear=new;
    }
    else
    {
        rear->next=new;
        rear=new;
    }
}

//pop function for queue
int pop()
{
    int x;
    if(front==rear)
    {
        struct node *t=front;
        x=t->data;
        free(t);
        front=rear=NULL;
        return x;
    }
    else
    {
        struct node *t=front;
        x=t->data;
        front=front->next;
        free(t);
        return x;
    }
}

void GanttChartFormation(int *b1,int *at,int *gc,int tq,int *total_time,int N)
{
    int i,j,x,c;
    //pushes processes into ready queue with arrival time=0 
    i=0;
    while(i<N)
    {
        if(at[i]==0)
        push(i);
        i++;
    }
    printf("\nReady Queue: ");
    while(front!=NULL && rear!=NULL)
    {
        x=pop();
        printf("P%d  ",x);
        c=0;
        for(j=0;j<tq;j++)
        {
            if(b1[x]>0)
            {
                gc[*total_time]=x;
                b1[x]-=1;
                *total_time+=1;
                c++;
            }
        } 
        for(i=0;i<N;i++)
        {
            if(at[i]<=*total_time && at[i]>(*total_time-c))
            {
                push(i);
            }
        }
        if(b1[x]>0)
        push(x);
    }
}

//Calculates completion time,turn around time,waiting time,response time
void TimeCalculations(int *at,int *bt,int *ct,int *tat,int *wt,int *rt,int *gc,int total_time,int N)
{
    int i,j,k;
    for(j=0;j<N;j++)
    {
        for(i=total_time-1;i>=0;i--)
        {
            if(j==gc[i])
            {
                ct[j]=i+1;
                tat[j]=ct[j]-at[j];
                wt[j]=tat[j]-bt[j];
                break;
            }
        }
        for(k=0;k<total_time;k++)
        {
            if(j==gc[k])
            {
                rt[j]=k-at[j];
                break;
            }
        }
    }
}

/*Displays completion time,turn around time,waiting time,response time and
also calculates total waiting and turn around time*/
void DisplayTime(int at[],int bt[],int ct[],int wt[],int tat[],int rt[],int N)
{
    float total_wt=0,total_tat=0;
    printf("\nProcesses\tArrival time\tBurst time\tCompletion Time\t\tWaiting time\tTurn around time\tResponse time\n"); 
	for(int i=0;i<N;i++) 
	{ 
		total_wt=total_wt+wt[i]; 
		total_tat=total_tat+tat[i];
        printf("P%d\t\t%d\t\t%d\t\t%d\t\t\t%d\t\t%d\t\t\t%d\n",i,at[i],bt[i],ct[i],wt[i],tat[i],rt[i]);
	} 
	printf("\nAverage waiting time = %2.3f",total_wt/N); 
	printf("\nAverage turn around time = %2.3f ",total_tat/N);
}

int main()
{
    int N,MAX=0;
    printf("Enter the no. of processes: ");
    scanf("%d",&N);

    int bt[N],at[N],wt[N],ct[N],tat[N],rt[N],b1[N],i,total_time=0,tq;
    for(i=0;i<N;i++)
	{
        printf("\nEnter arrival time for process %d: ",i);
		scanf("%d",&at[i]); 
		printf("Enter burst time for process %d: ",i);
		scanf("%d",&bt[i]);
        b1[i]=bt[i];	
        MAX+=bt[i];
	}

    int gc[MAX];
    printf("\nEnter time quantum for each process: ");
    scanf("%d",&tq);

    GanttChartFormation(b1,at,gc,tq,&total_time,N);
    
    //displays the gantt chart
    printf("\nGantt Chart: ");
    for(i=0;i<total_time;i++)
    {
        printf("P%d   ",gc[i]);
    }
    printf("\n\nTotal time to complete all processes: %d",total_time);
    TimeCalculations(at,bt,ct,tat,wt,rt,gc,total_time,N);   
    DisplayTime(at,bt,ct,wt,tat,rt,N);
    return 0;
}

/*
Output:-

Enter the no. of processes: 4

Enter arrival time for process 0: 0
Enter burst time for process 0: 2

Enter arrival time for process 1: 1
Enter burst time for process 1: 3

Enter arrival time for process 2: 1
Enter burst time for process 2: 5

Enter arrival time for process 3: 2
Enter burst time for process 3: 4

Enter time quantum for each process: 2

Ready Queue: P0  P1  P2  P3  P1  P2  P3  P2
Gantt Chart: P0   P0   P1   P1   P2   P2   P3   P3   P1   P2   P2   P3   P3   P2

Total time to complete all processes: 14
Processes       Arrival time    Burst time      Completion Time         Waiting time    Turn around time        Response time
P0              0               2               2                       0               2                       0
P1              1               3               9                       5               8                       1
P2              1               5               14                      8               13                      3
P3              2               4               13                      7               11                      4

Average waiting time = 5.000
Average turn around time = 8.500
*/


<|start_filename|>C-Plus-Plus/other/AllocateMinPages.cpp<|end_filename|>
/* Given number of pages in n different books and m students.
   The books are arranged in Random order of number of pages.It is not compulsory to sort the Array.
   Every student is assigned to read some consecutive books.
   The task is to assign books in such a way that the maximum number of pages assigned to a student is minimum.
   Solution of this problem can be improved using the Binary Search Algorithm
*/

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

/* Utility function to check if current minimum value is feasible or not. */
bool isValid(int arr[],int size,int students,int mid){
	int student=1;
	int sum=0;
	for(int i=0;i<size;i++){
		sum+=arr[i];
		if(sum>mid){ /* If the sum exceeds the current minimum value then increase the count of students */
			student++;
			sum=arr[i]; //Reinitializing the sum with the current element of the Array
		}
		if(student >students) /* If the count of student till now becomes greater than the the students then return false */
		return false;
	}
	return true;
}

/* function to find minimum pages */
int findPage(int arr[],int size,int students){
	/* Base Condition */
	if(size<students) /* As mentioned in the condition , each student must have atleast one book */
	   return -1;
	
	/* Finding maximum in array */
	int maxi=INT_MIN;/*maxi will be the starting element of binary search for improving complexity */
	for(int i=0;i<size;i++){
		if(arr[i]>maxi)
		maxi=arr[i];
	}
	
	/* Finding sum of array */
	int sum{0};/* sum represents the end element in the worst case */
	for(int i=0;i<size;i++)
	sum+=arr[i];
	
	int start=maxi;
	int end=sum;
	int res=-1; /* Initialising the result with -1 */
	while(start<=end){
		int mid=start+(mid-start)/2; /* to avoid integer overflow */
		if(isValid(arr,size,students,mid)){
			res=mid;
			end=mid-1; /* to search the minimum number of pages */
		}
		else
		start=mid+1;
	}
	return res;
}

/* Drivers Code */
int main(){
	int size; //size of the array 
	cout<<"Enter the Size of the Array :";
	cin>>size;
	int students; //number of students
	cout<<"Enter the Number of students :";
	cin>>students;
	int arr[size]; // array represents number of pages in the different book
	cout<<"Enter the No of pages in every book :";
	for(int i=0;i<size;i++)
	cin>>arr[i];
	cout<<"Minimum number of pages : "<<findPage(arr,size,students);
	return 0; 
}

/*
   Time Complexity : O(size*log(sum(arr[]))
   Auxilary Space Comlexity : O(1)
   
   TestCase 1:
   Input:Enter the size of the Array :4
         Enter the Number of students :2
         Enter the No of pages in every book :10 20 30 40
  Output:Minimum number of pages :60
    
    TestCase 2:
    Input:Enter the Size of the Array :4
          Enter the Number of students :2
          Enter the No of pages in every book :12 34 67 90
   Output:Minimum number of pages : 113
         
*/


<|start_filename|>C-Plus-Plus/search/Binary_Search.cpp<|end_filename|>
#include <iostream>
#include <algorithm>
using namespace std;

//Function which returns true if element found in an array, else returns false.
bool binary_search(int *arr, int search_element, int lb, int ub) {
    while (lb <= ub) {
        int mid = lb + (ub - lb) / 2;
        if (arr[mid] == search_element) {
            return (true);
        } else if (arr[mid] > search_element) {
            ub = mid - 1;
        } else {
            lb = mid + 1;
        }
    }
    return (false);
}

/** Main function */
int main() {
    int t, n, search_element;
    int *arr = nullptr;
    cout << "Enter the number of test cases : " << std::endl;
    cin >> t;

    while (t--) {
        cout << "Enter the size of an array : " << std::endl;
        cin >> n;

        // dynamic memory allocation
        arr = new int[n];

        cout << "Enter the elements in an array : " << std::endl;
        for (int i = 0 ; i < n ; i++) {
            cin >> arr[i];
        }

        sort(arr, arr + n);

        cout << "Enter the element to search : " << std::endl;
        cin >> search_element;

        // call to binary search function
        bool result = binary_search(arr, search_element, 0, n);

        if(result) {
            cout << "Element found." << std::endl;
        } else {
            cout << "Element not found." << std::endl;
        }
        // free memory after use
        delete[] arr;
    }
    return 0;
}


<|start_filename|>JavaScript/ds/Hash.js<|end_filename|>
/*

A JavaScript program for creating a well known data structure "Hash Table". A hash table (often called a hash map) is a data structure 
that maps keys to values. Hash tables combine lookup, insert, and delete operations in an efficient way. Hash tables can perform in constant time.
In the worst-case scenario, the performance of hash tables can be as low as O(n).

In this program, user can provide a choice to perform operations on a Hash Table. It is created using a ES6 class syntax. 
prompt & colors are node packages for taking user input and displaying text in different colors respectively. 

*/

const prompt = require("prompt-sync")({ sigint: true });
const colors = require("colors");

// Setting the Color schema
colors.setTheme({
  display: "green",
  insert: "white",
  delete: "red",
  leave: "yellow",
  end: "rainbow",
  wrong: "america",
});

class HashTable {
  constructor(size) {
    // Set Hash Table size
    this.data = new Array(size);
  }

  // Generate a location using simple hash logic
  _hash(key) {
    let hash = 0;
    for (let i = 0; i < key.length; i++) {
      // Location mapping
      hash = (hash + key.charCodeAt(i) + i) % this.data.length;
    }

    return hash;
  }

  // Set the location of item in hash
  set(key, value) {
    let address = this._hash(key);
    if (!this.data[address]) {
      this.data[address] = [];
    }

    // Insert item at the desired location with [key, value] pair
    this.data[address].push([key, value]);
    return this.data;
  }

  // Get the location of item in hash table
  get(key) {
    let address = this._hash(key);
    const currentBucket = this.data[address];
    // Item at the location is not found , return undefined
    if (!currentBucket) return undefined;

    if (currentBucket.length) {
      for (let i = 0; i < currentBucket.length; i++) {
        if (currentBucket[i][0] === key) {
          return {
            data: [currentBucket[i][0], currentBucket[i][1]],
            location: address,
          };
        }
      }
    }
    return undefined;
  }

  // Delete item
  deleteItem(value) {
    let item = this.get(value);

    // Item is not present in hash table
    if (item === undefined)
      return console.log("Can't delete, no such item found");

    // Delete item present at that location from hash table
    delete this.data[item.location];
    return console.log("Deleted", item.data[0]);
  }

  // Display all items
  keys() {
    const keysArray = [];
    for (let i = 0; i < this.data.length; i++) {
      if (this.data[i]) keysArray.push(this.data[i][0][0]);
    }

    return keysArray;
  }
}

// Instantiating the HashTable
const myHashTable = new HashTable(100);

// Insert item in Hash Table
myHashTable.set("grapes", 1000); // Output - [['grapes', 1000]]
myHashTable.set("apple", 100); // Output - [['apple', 100], ['grapes', 1000]]
myHashTable.set("oranges", 50); // Output - [['apple', 100], ['grapes', 1000], ['oranges', 50]]

myHashTable.deleteItem("apple"); // Output - [['grapes', 1000], ['oranges', 50]]
myHashTable.deleteItem("fruits"); // Output - Can't delete, no such item found

let choice = 0;
let value, index;

// Asking user input for performing operations on Hash Table
do {
  console.log("\nWelcome to the Hash Table");
  console.log("Follow the instructions to get in the show");
  console.log("0. To exit without doing anything".yellow);
  console.log("1. Display all elements of the Hash Table".display);
  console.log("2. Insert element in the Hash Table".insert);
  console.log("3. Find element in Hash Table".display);
  console.log("4. Delete element from Hash Table".delete);

  choice = +prompt("Enter your choice - ");

  switch (choice) {
    case 0:
      console.log("Hmm, matter of choice!\n".rainbow);
      return;

    case 1:
      console.log("Hash Table - ", myHashTable.keys());
      break;

    case 2:
      value = prompt("Enter Value ( first value )  to Insert element - ");
      index = +prompt("Enter amount ( second value) to Insert element - ");

      if (index <= 0)
        return console.log("You know this is wrong, Bbye!\n".wrong);

      myHashTable.set(value, index);
      console.log("After Insertion Hash Table - ", myHashTable.keys());
      break;

    case 3:
      if (myHashTable.data.length === 0) {
        return console.log("Hash Table in empty".wrong);
      }

      value = prompt("Enter Value to find the element - ");
      let result = myHashTable.get(value);

      if (!result) console.log("Element not found");
      else console.log("Element ", result);
      break;

    case 4:
      if (myHashTable.data.length === 0) {
        return console.log(
          "404, you can't remove anything from empty hash table".wrong
        );
      }

      value = prompt("Enter Value to delete - ");
      myHashTable.deleteItem(value);
      console.log("After Deletion Hash Table - ", myHashTable.keys());
      break;

    default:
      console.log("You know this is wrong, Bbye!\n".wrong);
      return;
  }
} while (choice !== 0);


// Sample I/O of the above program -

/*

> node Hash

Welcome to the Hash Table
Follow the instructions to get in the show
0. To exit without doing anything
1. Display all elements of the Hash Table
2. Insert element in the Hash Table
3. Find element in Hash Table
4. Delete element from Hash Table
Enter your choice - 1
Hash Table -  [ 'grapes', 'oranges' ]

Welcome to the Hash Table
Follow the instructions to get in the show
0. To exit without doing anything
1. Display all elements of the Hash Table
2. Insert element in the Hash Table
3. Find element in Hash Table
4. Delete element from Hash Table
Enter your choice - 2
Enter Value ( first value )  to Insert element - Icecream
Enter amount ( second value) to Insert element - 250
After Insertion Hash Table -  [ 'Icecream', 'grapes', 'oranges' ]

Welcome to the Hash Table
Follow the instructions to get in the show
0. To exit without doing anything
1. Display all elements of the Hash Table
2. Insert element in the Hash Table
3. Find element in Hash Table
4. Delete element from Hash Table
Enter your choice - 3
Enter Value to find the element - grapes
Element  { data: [ 'grapes', 1000 ], location: 57 }

Welcome to the Hash Table
Follow the instructions to get in the show
0. To exit without doing anything
1. Display all elements of the Hash Table
2. Insert element in the Hash Table
3. Find element in Hash Table
4. Delete element from Hash Table
Enter your choice - 4
Enter Value to delete - grapes
Deleted grapes
After Deletion Hash Table -  [ 'Icecream', 'oranges' ]

Welcome to the Hash Table
Follow the instructions to get in the show
0. To exit without doing anything
1. Display all elements of the Hash Table
2. Insert element in the Hash Table
3. Find element in Hash Table
4. Delete element from Hash Table
Enter your choice - 0
Hmm, matter of choice!

*/

<|start_filename|>C-Plus-Plus/sort/counting_sort.cpp<|end_filename|>
/*
 Created by Sarthak-9 on 30-12-2020.
 Count Sort Algorithm for Sorting an array of small integers quickly.

 Worst complexity: O(n+k)
 Average complexity: O(n+k)
 Space complexity: O(n+k)
 where n is the number of elements input in array and k is the range of input.
*/

#include <iostream>

using namespace std;

int Min(long long int A[], long long int n) {
        long long int min = 100000;

        // finds the maximum element of the array
        for (long long int i = 0; i < n; i++) {
                if (A[i] < min) {
                        min = A[i];
                }
        }
        return min;
}

int Max(long long int A[], long long int n) {
        long long int max = A[0];

        // finds the maximum element of the array
        for (long long int i = 0; i < n; i++) {
                if (A[i] > max) {
                        max = A[i];
                }
        }
        return max;
}

void CountSort(long long int A[], long long int n) {
        long long int max = Max(A, n);
        long long int min = Min(A, n);
        int* count = new int [max- min + 1];

        // initializes the count array with all elements to zero
        for (long long int i = 0; i < n; i++) {
                count[A[i]-min] = 0;
        }

        // updates the count array with frequencies of given numbers
        for (long long int i = 0; i < n; i++) {
                count[A[i]-min]++;
        }

        int k = 0;

        for (int j = max; j >= min; j--)
        {
                for (int i = 0; i < count[j - min]; i++)
                {
                        A[k++] = j;
                }
        }

        delete [] count;
}

int main() {

        long long int n;
        long long int A[100000];
        cout << "Enter the size of array" << endl;
        cin >> n;
        cout << "Enter the elements" << endl;

            // inputs numbers from the user in an array
        for (long long int i = 0; i < n; i++) {
                cin >> A[i];
        }

        CountSort(A, n);

        cout << "The sorted array is :" << endl;

        // prints the sorted array
        for (long long int i = n-1; i >=0; i--) {
                cout << A[i] << " ";
        }
        cout << endl;
        return 0;
}

/*
 Input:
 Enter the size of array
 10
 Enter the elements
 -80 77 256 -125 910 746 -244 910 1012 488

 Output:
 The sorted array is :
 -244 -125 -80 77 256 488 746 910 910 1012
*/

<|start_filename|>Java/cp/remove_element_from_array.java<|end_filename|>
/*

Remove an element from the array

For a given array of integers arr[], and
a value key, your task is to remove all the instances of value present 
in the array, and return the new size of the array.
It is given that the arrangement should be done in-place i.e.
with no extra space used.

*/

import java.util.*;

class remove_element_from_array
{
    //function to find the new size of the array
    public int removeKey(int arr[], int key)
    {
        int pass=0;
        int size=arr.length;
        while(pass<size)
        {
            if(arr[pass]==key)
            {
                //on encountering the key value we replace the current element 
                //with the last element and then decreament the size of array
                // that is we basically remove key element from array  
                arr[pass]=arr[size-1];
                size--;//decrementing the size of array
            }
            else
            {
                pass++;
            }
        }
        return size;
    }

    //driver method
    public satic void main(String []args)
    {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the length of the array: ");
        int n = sc.nextInt();

        System.out.print("Enter the value to be removed: ");
        int key = sc.nextInt();
        
        int arr[] = new int[n];
        System.out.println("Enter the values for array: ");
        for(int i=0; i<n; i++)
        {
            arr[i] = sc.nextInt();
        }

        System.out.println("New size of the array after removing the key element "+key+" is: ");
        System.out.print(removeKey(arr, key));
    }

}

/*

EXAMPLES:

Example 1-
Input--
Enter the length of the array: 5
Enter the value to be removed: 1
Enter the values for array: 1 3 4 5 1
Output--
New size of the array after removing the key element 1 is: 3

Example 2-
Input--
Enter the length of the array: 8
Enter the value to be removed: 4
Enter the values for array: 2 4 4 4 4 5 6 7
Output--
New size of the array after removing the key element 4 is: 4

TIME COMPLEXITY --> O(N)

*/


<|start_filename|>C/cp/possible_code_recursion.c<|end_filename|>
#include <stdio.h>
#include <string.h>
#define MAX 10

void decode(char *code, char *ans, int i, int j) {
	// i is index of code array
	// j is index of ans array
	if (i >= strlen(code)) {
		printf("%s ", ans);
		return;
	}
	// getting all possible sequences recursives
	if (code[i + 1] != '0') {
		ans[j] = (code[i] - '0' + 96);
		decode(code, ans, i + 1, j + 1);
	}
	// converting a num to char
	if (code[i + 1]) {
		int result = (code[i] - '0') * 10 + (code[i + 1] - '0') - 1;
		if (result <= 25) {
			ans[j] = result + 97;
			ans[j + 1] = '\0';
			decode(code, ans, i + 2, j + 1);
		}
	}
}
int main() {
	// creating a null string
	char ans[50] = { '\0' };
	// input string
	char code[MAX];
	printf("Enter the code: ");
	scanf("%s", code);
	decode(code, ans, 0, 0);
}

/*
OUTPUT:
Enter the code: 1123
aabc aaw alc kbc kw
Time Complexity : O(n)
Space complexity : O(n)
*/


<|start_filename|>JavaScript/math/bin_exp.js<|end_filename|>
/*
Binary exponentiation (also known as exponentiation by squaring) is a trick which allows to calculate an using only O(logn) multiplications (instead of O(n) multiplications required by the naive approach).
*/

function binary_expo(a,b,mod)
{
    //End Result Store Here
    let ans=1;
    while(b>0)
    {
        if(b%2!=0)
        {
            //Making the power even
            ans=((ans%mod)*(a%mod))%mod;
            //Decrease the power by 1
            b--;
        }
        else
        {
            //performing sqaure to reduce the power by 2
            a=((a%mod)*(a%mod))%mod;
            //reducing the power by 2.
            b=b/2;
        }
    }
    return ans;
}
console.log(binary_expo(2,3,10000));
//binary_expo(number 1,number 2, mod) (a^b)%mod
//Time Complexity = O (log b)

<|start_filename|>C/math/Magic_Number.c<|end_filename|>
// A number is said to be Magic Number, when the recursive sum of the digits is 1.
#include <stdio.h>

int calsum(int);
int magic_num(int);
int main()
{
	int num;
	printf("Enter the number to be checked:");
	scanf("%d", &num);
	if (magic_num(num) == 1)
		printf("%d is a magic number", num);
	else
		printf("%d is not a magic number", num);
	return 0;
}

// Function to check if the number is a magic number or not
int magic_num(int num)
{
	int sum;
	while (num > 9)
	{
		sum = calsum(num);
		num = sum;
	}

	return num;
}

// Function to calculate the sum of digits
int calsum(int num)
{
	int sum = 0, rem;
	while (num > 0)
	{
		rem = num % 10;
		sum = sum + rem;
		num = num / 10;
	}

	return sum;
}

/*
Sample Output
Enter the number to be checked:1729
1729 is a magic number

Complexities
Time Complexity:O(n)
Space Complexity:O(n)
*/



<|start_filename|>C-Plus-Plus/sort/Cocktail_shaker_sort.cpp<|end_filename|>

// C++ Program for implementation of Cocktail shaker sort.

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

//  function to sort the array using Cocktail sort
void Cocktail_shaker_sort(int a[], int n)
{
	int initial = 0;
	int end = n - 1;
	bool flag = true;
	while (flag) 
	{
		flag = false;
		
		// loop from left to right
		for (int i = initial; i < end; ++i) 
		{
			if (a[i] > a[i + 1]) {
				swap(a[i], a[i + 1]);
				flag = true;
			}
		}
		
		// if nothing moved, then array is sorted
		if (!flag)
			break;

		flag = false;

		--end;

        // comparing from right to left
		for (int i = end - 1; i >= initial; --i) 
		{
			if (a[i] > a[i + 1]) {
				swap(a[i], a[i + 1]);
				flag = true;
			}
		}

		++initial;
	}
}

// Function to print the sorted array 
void Print(int a[], int n)
{
	for (int i = 0; i < n; i++)
		printf("%d ", a[i]);
	printf("\n");
}

// Main function
int main()
{
	int no_element;
	cout << "Enter the no of element to be sorted: "; 
  	cin >> no_element;
	int a[no_element];

	// taking input 
	for(int x=0; x < no_element; x++){
		cin>>a[x];
	}

	int n = sizeof(a) / sizeof(a[0]);
	Cocktail_shaker_sort(a, n);
	printf("The Sorted array :\n");
	Print(a, n);
	return 0;
}



<|start_filename|>C-Plus-Plus/cp/aggressive_cows.cpp<|end_filename|>
/*<NAME> has built a new long barn, with N (2 <= N <= 100,000) stalls.
The stalls are located along a straight line at positions x1,...,xN (0 <= xi <= 1,000,000,000).
His C (2 <= C <= N) cows don't like this barn layout and become aggressive towards each other once put into a stall. 
To prevent the cows from hurting each other, FJ wants to assign the cows to the stalls, 
such that the minimum distance between any two of them is as large as possible. 
What is the largest minimum distance?*/

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

bool canplacecows(int stalls[], int n, int c, int min_sep)
{
	int last_cow = stalls[0];
	int cnt = 1;
	for (int i = 1; i < n; i++)
	{
		if (stalls[i] - last_cow >= min_sep)
		{
			last_cow = stalls[i];
			cnt++;
			if (cnt == c)
			{
				return true;
			}
		}
	}

	return false;
}

int main()
{
	int stalls[100], n, cows;
	cout<<"Enter the the total no of stalls and cows: ";
	cin >> n >> cows;

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

	int start = 0;
	int end = stalls[n - 1] - stalls[0];
	int ans = 0;
	while (start <= end)
	{
		int mid = (start + end) / 2;
		bool canplacecow = canplacecows(stalls, n, cows, mid);
		
		if (canplacecow)
		{
			ans = mid;
			start = mid + 1;
		}
		else
		{
			end = mid - 1;
		}
	}

	cout << "the largest minimum distance: " << ans << "\n";
	return 0;
}
/* Example :
1)Input :
5 3
1 2 4 8 9
Output : 3

Time Complexity : O(nlog n)
Space Complexity : O(n)

*/


<|start_filename|>Java/cp/Median_of_two_sorted_arrays.java<|end_filename|>

//Given two sorted arrays nums1 and nums2 of size m and n 
//respectively, return the median of the two sorted arrays.

import java.io.*;
import java.util.*;

class Median_of_2_sorted_array {
    static double findMedianSortedArrays(int[] arr1, int[] arr2) {
    // length of the merged array
    int arr3length = arr1.length + arr2.length;
        int arr3[] = new int[arr3length];
        int j=0;
        //storing the elements of both arrays into nums3
        for(int i =0;i<arr1.length;i++)
        {
            arr3[j++] = arr1[i];
        }
        for(int i =0;i<arr2.length;i++)
        {
            arr3[j++] = arr2[i];
        }
        //sorting nums3 array
        Arrays.sort(arr3);
    double mid;
    //checking if length of merged array is odd
    
    if(arr3length % 2 != 0) {
        //return the median
        mid = arr3[arr3length / 2>>0];
        return mid;
    } 
    //if the length is odd
    else {
        //median is the average of two mid elements
        double first = arr3[arr3.length / 2>>0];
        double second = arr3[(arr3.length / 2 >> 0 )-1];
        mid =  first + second;
        return( mid ) / 2;
    }

    }

    public static void main(String args[]) 
    {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int arr1[] = new int[n];
        int arr2[] = new int[m];
        for(int i = 0;i < n; i++)
          arr1[i] = sc.nextInt();

        for(int i = 0;i < m; i++)
            arr2[i] = sc.nextInt();

        System.out.println(findMedianSortedArrays(arr1,arr2));
        
    }
}


/*
Time complexity: O(n)
Space complexity: O(n)

Example 1:

Input:
2 1
1 3
2

Output:
2.00000

Example 2:

Input:
5 3
1 5 7 8 9
2 4 4

Output:
4.50000

*/




<|start_filename|>Java/cp/UglyRecursion.java<|end_filename|>
//finding nth ugly number using recursion
import java.util.Scanner;
class UglyRecursion
{
   
       public static int ugly(int n) 
    { 
        
        if (n == 1)  //base cases
            return 1; 
        if (n <= 0) 
            return 0; 
        if (n % 2 == 0)  
            return (ugly(n / 2)); 
        
        if (n % 3 == 0) 
            return (ugly(n / 3)); 
        
        if (n % 5 == 0)  
            return (ugly(n / 5)); 
        
        return 0; 
    } 
  
       
    
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.print("N= ");
        int n=sc.nextInt();
        int i=1;
        while(n>0)
        { if(ugly(i)==1)
            n-=1;
            i++;
        }
        System.out.println(i--); //to avoid the last increment,we decrement by one
    }
}


/* Sample Input
   Input:
N = 10
Output: 12
Time Complexity : O(n)
Space Complexity : O(1)*/

<|start_filename|>JavaScript/other/largeNumberFactorial.js<|end_filename|>
const factorial = (n) => {
    let res = [];

    // Initialize result
    res[0] = 1;
    let resSize = 1;

    // Apply simple factorial formula n! = 1 * 2 * 3 * 4...*n
    for (let x = 2; x <= n; x++) {
        resSize = multiply(x, res, resSize);
    }

    console.log("Factorial of given number is ");
    var s = "";
    for (let i = resSize - 1; i >= 0; i--) {
        s = s + res[i];
    }

    console.log(s);
}

// for multiplications
const multiply = (x, res, resSize) => {
    let carry = 0; // Initialize carry

    // One by one multiply n with individual digits of res[]
    for (let i = 0; i < resSize; i++) {
        let prod = res[i] * x + carry;
        res[i] = prod % 10; // Store last digit of 'prod' in res[]
        carry = Math.floor(prod / 10); // Put rest in carry
    }

    // Put carry in res and increase result size
    while (carry != 0) {
        res[resSize] = carry % 10;
        carry = Math.floor(carry / 10);
        resSize++;
    }

    return resSize;
}

factorial(25);
factorial(50);

/**
 * Sample output for above input:
 * Factorial of given number is
 * 15511210043330985984000000
 * Factorial of given number is
 * 30414093201713378043612608166064768844377641568960512000000000000
 *
 * Time complexity: O(log(N!))
 */


<|start_filename|>C-Plus-Plus/sort/Binary_Insertion_Sort.cpp<|end_filename|>
/*
We can use binary search to reduce the number of comparisons in normal insertion sort.
Binary Insertion Sort uses binary search to find the proper location to insert the selected item at each iteration. 
In normal insertion sort, it takes O(n) comparisons (at nth iteration) in the worst case.
We can reduce it to O(log n) by using binary search.
*/

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

//searching element in array a by binary search algoritm
int binarySearch(int a[], int element, int low, int high)
{
    if (high <= low){
        return (element > a[low]) ? (low + 1) : low;
    }
    int mid = (low + high) / 2;
    if (element == a[mid]){
        return mid + 1;
    } 
    if (element > a[mid]){
        return binarySearch(a, element, mid + 1, high);
    }
    return binarySearch(a, element, low, mid - 1);
}
// sorting using insertion sort
void insertionSort(int arr[], int n)
{
    // initializing variables
    int i, place, j, k, selected;
    for (i = 1; i < n; ++i) 
    {
        j = i - 1;
        selected = arr[i];

        // location where selected sould be inseretd
        place = binarySearch(a, selected, 0, j);

        // Move all elements after location to create space
        while (j >= place) 
        {
            arr[j + 1] = arr[j];
            j--;
        }
        arr[j + 1] = selected;
    }
}

signed main()
{
    //Taking Input
    int n; cin>>n;
    int arr[n];
    for(int i=0;i<n;i++){
        cin>>arr[i];
    }

    //Applying Sort
    //calling sort function
    insertionSort(a, n);
    cout<<"Sorted Array is :-";
    for (int i = 0; i < n; i++){ 
        cout<<arr[i]<<" ";
    }
    return 0;
}
/* Sample Input
11
35 23 12 17 12 72 31 46 180 88 54
*/
/* Sample Output
Sorted Array is:- 12 12 17 23 31 35 46 54 72 88 180
*/

// Time Complexity -O(n^2)
//Space Complexity -O(n)


<|start_filename|>C-Plus-Plus/cp/generate_valid_parenthesis.cpp<|end_filename|>
/*Problem Statement: 
You are given a number n, your job is to find all the n balanced parenthesis
combinations possible */

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

/*Function description : 
At any index i, 
BASE CASE : 
The combination of brackets can at maximum reach 2*n length
therefore, if index reaches 2*n then print combination
RECURSIVE CASE:
1) If an open bracket is to be generated in the combination then,
	count of(open) bracket should be less than n
2) If a closed bracket is to be generated in the combination then,
	count of(close) bracket should be less than count of(open) bracket */

void FindValidParenthesis(char *out, int n, int index, int open, int close)
{
	if (index == 2 *n)
	{
		out[index] = '\0';
		cout << out << endl;
		return;
	}

	//If the number of open brackets is less than n
	if (open < n)
	{
		out[index] = '(';
		FindValidParenthesis(out, n, index + 1, open + 1, close);
	}

	//If the number of close brackets is less than the number of open brackets
	if (close < open)
	{
		out[index] = ')';
		FindValidParenthesis(out, n, index + 1, open, close + 1);
	}

	return;
}

int main()
{
	int n;
	cin >> n;
	char out[1000];
	int index = 0;
	FindValidParenthesis(out, n, 0, 0, 0);
	return 0;
}

/*Examples : 
1)Input : n = 2
Output-
(())
()()
2)Input : n = 3
Output-
((()))
(()())
(())()
()(())
()()()

Time Complexity : O(2^n)
Space Complexity : O(n) */



<|start_filename|>C-Plus-Plus/ds/max_min_heap.cpp<|end_filename|>
#include<bits/stdc++.h>
using namespace std;
class heap{
    int n;
    int arr[];
    public:
    heap(){
        cout<<"Enter the total no. of elements in a heap u want ?"<<endl;
        cin>>n;
        arr[n+1];
        memset(arr,0,n+1);       //initialising the value 0 
    }
    void max_heap(){            //max heap function accepting values and calling insert_max to insert element to acc to max heap condition
        char ch;
        int j = n;
        int m ,i=1;
        do{
            cout<<"Enter element "<<i<<" :";
            cin>>m;
            arr[i] = m;
            insert_max(i);
            i++;
            j--;
        }while(j>=1);
        disp();
    }
    void insert_max(int i){ //always checking from its parent element if smaller then swapping is to be done
        int elem = arr[i];
        while(i>1 && arr[i/2]<elem){
            arr[i] = arr[i/2];
            i = i/2;
        }
        arr[i] = elem;
    }
    void min_heap(){ //min heap function accepting values and calling insert_min to insert element to acc to min heap condition 
        char ch;
        int j = n;
        int m ,i=1;
        do{
            cout<<"Enter element "<<i<<" :";
            cin>>m;
            arr[i] = m;
            insert_min(i);
            i++;
            j--;
        }while(j>=1);
        disp();
    }
    void insert_min(int i){
        int elem = arr[i];
        while(i>1 && arr[i/2]>elem){      //always checking from its parent element if greater then swapping is to be done
            arr[i] = arr[i/2];
            i = i/2;
        }
        arr[i] = elem;
    }
    void disp(){
        for(int i=1;i<n+1;i++){
            cout<<arr[i]<<"\t";
        }
        cout<<"\n";
    }
};
int main()
{
    heap h;
    int ch;
    do{
        cout<<"Enter the choice below :\n1.MAX heap \n2.MIN heap \n3.EXIT\n";
        cin>>ch;
        switch(ch)
        {
            case 1:
            h.max_heap();
            cout<<"Max heap created"<<endl;
            break;
            case 2:
            h.min_heap();
            cout<<"Min heap created"<<endl;
            break;
            case 3:
            exit(0);
        }
    }while(ch!=3);
    return 0;
}
/*
Enter the total no. of elements in a heap u want ?
5
Enter the choice below :
1.MAX heap 
2.MIN heap 
3.EXIT
1
Enter element 1 :8
Enter element 2 :4
Enter element 3 :12
Enter element 4 :4
Enter element 5 :2
12	4	8	4	2	
Max heap created
Enter the choice below :
1.MAX heap 
2.MIN heap 
3.EXIT
2
Enter element 1 :5
Enter element 2 :2
Enter element 3 :7
Enter element 4 :5
Enter element 5 :1
1	2	7	5	5	
Min heap created
Enter the choice below :
1.MAX heap 
2.MIN heap 
3.EXIT

*/


<|start_filename|>C-Plus-Plus/dp/longest_increasing_subsequence.cpp<|end_filename|>
//the following program finds length of longest increasing subsequence in the given array using dynamic programming
//the subsequence is a part of given parent array that has same order of elements as of parent array.
#include<iostream>
using namespace std;

int
main ()
{
  
int arr[8] = { 10, 22, 9, 33, 21, 50, 41, 6 };
  
cout << "The elements of array are:";
  
for (int i = 0; i < 8; i++)
    {
      
cout << arr[i] << " ";
    
} 
int n = 8;		//number of elements in array
  int count[n];
  
for (int i = 0; i < n; i++)
    {
      
count[i] = 1;		//initially assign every element as 1 because every element is longest increasing subsequence in itself
  } 
for (int i = 1; i < n; i++)
    {				//loop starts from index 1
      for (int j = 0; j < i; j++)
	{			//next loop runs till one index less than i
	  if (arr[i] > arr[j] && count[j] + 1 > count[i])
	    {			// if it finds number smaller than current ith index and it's next element in count array is greater than ith index by one 
	      count[i] = count[j] + 1;	//then increment the count of ith element in count array by 1
	    }
	
}
    
}
  
int max = 0;			//initially assign max variable as 0
  for (int i = 0; i < n; i++)
    {
      
if (count[i] > max)
	{			//if current element is larger than max
	  max = count[i];	//assign maximum value in max variable
	}
    
}
  
cout << "\n" << "The length of longest increasing subsequence is " << max;

}


<|start_filename|>Julia/dp/golomb_sequence.jl<|end_filename|>
"""Julia program to print the n'th term in the Golomb sequence 
Golomb sequence is a non-decreasing integer sequence where n'th 
term is  equal to the number of times n appears in the sequence"""

function golomb_sequence(n)
    dp = zeros(Int, n + 1)
    dp[1] = 1

    for i in 2:n
        dp[i] = 1 + dp[i - dp[dp[i - 1]]]
    end
    return dp[n]
end

print("Enter the value of n?, where you need the n'th number in the golomb sequence. ")
n = readline()
n = parse(Int, n)
if (n <= 0)
    println("The given value of n is invalid.")
    exit()
end
res = golomb_sequence(n)
println("The $n'th term in the golomb sequence is $res.")

"""
Time Complexity: O(n), where 'n' is the given number
Space Complexity: O(n)

SAMPLE INPUT AND OUTPUT

SAMPLE 1
Enter the value of n?, where you need the n'th number in the golomb sequence. 5
The 5'th term in the golomb sequence is 3.

SAMPLE 2
Enter the value of n?, where you need the n'th number in the golomb sequence. 867
The 867'th term in the golomb sequence is 79.

"""


<|start_filename|>C/cp/arrays_duplicate_elements.c<|end_filename|>
/*
Given an array of N elements, each element's occurrence in the array can be more than once.
Find all elements whose occurrence is more than 1.
Formally find all duplicate elements of the array.
*/

#include <stdio.h>
#include <string.h>

//From this dupicate_elements function we will print duplicate elements of the array
void dupicate_elements(int ar[] ,int N)
{
    /* we will insert the array elements into visited array. if current element already
    in the visited array
    then definitely that element's occurrence is more than 1.
    Hence it is duplicate and will print it*/
    printf("Duplicate elements are : \n");
    int i = 0;
    int visited_array[N + 1];
    memset(visited_array, 0, sizeof(visited_array));
    for(i = 0; i < N; i++)
    {
        if(visited_array[ar[i]] != 0)
        {
            // this element is duplicate
            printf("%d ", ar[i]);
        }
        if(visited_array[ar[i]] == 0)
        {
            visited_array[ar[i]]++;
        }
    }
    return;
}

int main()
{
    printf("Enter the size of the array : ");
    int N;
    scanf("%d", &N);
    int ar[N + 1];
    printf("Enter array elements :\n");
    for(int i = 0; i < N; i++)
    {
        scanf("%d", &ar[i]);
    }
    dupicate_elements(ar , N);
}

/*
Standard Input and Output

Enter the size of the array : 7
Enter array elements :
1 2 4 5 5 7 8
Duplicate elements are :
5 8

Time Complexity : O(N)
Space Complexity : O(N)

*/


<|start_filename|>C/dp/length_longest_increasing_subsequence.c<|end_filename|>
// C program to find the Length of Longest Increasing Subsequence
/*
In this problem, given an array we have to find the length of the longest increasing subsequence that array can make.
The problem can be solved using Dynamic Programming
*/
#include <stdio.h>
#include <string.h>

int length_longest_increasing_subsequence(int arr[], int n)
{
    int dp[n], max_len = 0;

    /* Initialize the dp array with the 1 as value, as the maximum length
       at each point is atleast 1, by including that value in the sequence  */
    for (int i = 0; i < n; ++i)
        dp[i] = 1;

    /* Now Lets Fill the dp array in Bottom-Up manner
       Compare Each i'th element to its previous elements from 0 to i-1, 
       If arr[i] > arr[j](where j = 0 to i-1), then it qualifies for increasing subsequence and
       If dp[i] < dp[j] + 1, then that subsequence  qualifies for being the longest one */
    for (int i = 1; i < n; i++)
    {
        for (int j = 0; j < i; j++)
        {
            if (arr[i] > arr[j] && dp[i] < dp[j] + 1)
                dp[i] = dp[j] + 1;
        }
    }

    //Now Find the maximum element in the 'dp' array
    for (int i = 0; i < n; i++)
    {
        if (dp[i] > max_len)
            max_len = dp[i];
    }

    return max_len;
}

int main()
{
    int n, max_len;
    printf("\nWhat is the length of the array? ");
    scanf("%d", &n);
    int arr[n];
    printf("Enter the numbers: ");
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &arr[i]);
    }
    max_len = length_longest_increasing_subsequence(arr, n);

    printf("The length of the longest increasing subsequence of the given array is %d", max_len);
    return 0;
}

/*
Time Complexity: O(num ^ 2), where 'num' is the size of the given array
Space Complexity: O(num)

SAMPLE INPUT AND OUTPUT

SAMPLE 1
What is the length of the array? 5
Enter the numbers: 1 2 3 4 3
The length of the longest increasing subsequence of the given array is 4

SAMPLE 2
What is the length of the array? 5
Enter the numbers: 5 4 3 2 1
The maximum sum of an increasing subsequence of the given array is 1
*/


<|start_filename|>C-Plus-Plus/other/DynamicHuffman.cpp<|end_filename|>
/*
Given a string S encode it according to the Dynamic Huffman Encoding Technique.
In Dynamic Huffman encoding technique we generate new code for each character dynamically i.e. it changes after we scan a new character.
*/
#include <bits/stdc++.h>
using namespace std;

class TreeNode
{
public:
    int freq;
    char symbol;
    TreeNode *parent;
    TreeNode *left;
    TreeNode *right;
    TreeNode()
    {
        //Intially Frequency of non character element is zero
        this->freq = 0;
        //Root is represented by '*'
        this->symbol = '*';
        this->left = NULL;
        this->right = NULL;
        this->parent = NULL;
    }
};

//Function to print the corresponding Dynamic Huffman Tree during Dynamic encoding of each character
void printTree(TreeNode *root)
{
    //Using queue to print Tree level order wise
    queue<TreeNode *> q;
    q.push(root);
    q.push(NULL);
    while (!q.empty())
    {
        TreeNode *curr = q.front();
        q.pop();
        //Marking end of current level
        if (curr == NULL)
        {
            cout << endl;
            if (!q.empty())
                q.push(NULL);
            continue;
        }
        //Printing of symbol along with its frequency
        cout << curr->symbol << curr->freq;
        cout << "  ";
        //Pushing children of current node to the queue
        if (curr->left != NULL)
        {
            q.push(curr->left);
        }
        if (curr->right != NULL)
        {
            q.push(curr->right);
        }
    }
}

//Function to Return Reverse Level Order of the given tree to check Balancing.
vector<TreeNode *> ReverseLevelOrder(TreeNode *root)
{
    //vector to store reverse level order
    vector<TreeNode *> reverse_level_order;
    //To help in reversing of level order
    vector<TreeNode *> current;
    //queue to store Treenode
    queue<TreeNode *> q;
    q.push(root);
    q.push(NULL);
    while (!q.empty())
    {
        TreeNode *curr = q.front();
        q.pop();
        if (curr == NULL)
        {
            //Inserting reverse level order at the end of current list
            current.insert(current.end(), reverse_level_order.begin(), reverse_level_order.end());
            reverse_level_order = current;
            current.clear();
            if (!q.empty())
                q.push(NULL);
            continue;
        }
        current.push_back(curr);
        if (curr->left != NULL)
        {
            q.push(curr->left);
        }
        if (curr->right != NULL)
        {
            q.push(curr->right);
        }
    }
    return reverse_level_order;
}

//Function to correct the tree
void correctTree(TreeNode *root)
{
    if (root == NULL)
    {
        return;
    }
    if (root->left == NULL && root->right == NULL)
    {
        return;
    }
    //Correcting each subtree first
    correctTree(root->left);
    correctTree(root->right);

    //Correcting the root
    int freq = 0;
    if (root->left)
    {
        freq += root->left->freq;
    }
    if (root->right)
    {
        freq += root->right->freq;
    }
    if (root->freq != freq)
    {
        root->freq = freq;
    }
}

//Function to swap the tree nodes
void swapTreeNode(TreeNode *root, TreeNode *a, TreeNode *b)
{
    //Getting each node parent
    TreeNode *parentA = a->parent;
    TreeNode *parentB = b->parent;
    //Swapping the parent
    a->parent = parentB;
    b->parent = parentA;
    //Chaning parent corresponding node
    if (parentA->left == a)
    {
        parentA->left = b;
    }
    else
    {
        parentA->right = b;
    }
    if (parentB->left == b)
    {
        parentB->left = a;
    }
    else
    {
        parentB->right = a;
    }
    correctTree(root);
}

//Function to get Code corresponding to each character
void getCodes(TreeNode *n, string code)
{
    if (n->left == NULL && n->right == NULL)
    {
        //If symbol is '*' that means it needs not to be coded
        if (n->symbol == '*')
        {
            return;
        }
        //Printing code for the symbol
        cout << "'" << n->symbol << "':" << code << " ";
        return;
    }
    //Adding "0" for left sub-tree
    getCodes(n->left, code + "0");
    //Adding "0" for right sub-tree
    getCodes(n->right, code + "1");
}
//Function to insert the corresponding Node to the tree
TreeNode *insertIntoTree(TreeNode *insertion, TreeNode *node)
{
    //Making the new TreeNode for addition of the next Node
    TreeNode *newInsertion = new TreeNode();
    //Incrementing Frequency of Parent by 1 for height balancing
    insertion->freq++;
    //Inserting the corresponding node to right
    insertion->right = node;
    //Making Parent of the node as this Insertion Node
    node->parent = insertion;
    //Making this next insertion point to the left of previous insertion point
    insertion->left = newInsertion;
    //Making parent of next insertion point previous insertion point
    newInsertion->parent = insertion;
    // Increment Each Parent Frequency by 1
    while (insertion->parent != NULL)
    {
        insertion->parent->freq++;
        insertion = insertion->parent;
    }
    return newInsertion;
}
//Function to Balance the Tree
TreeNode *checkTree(TreeNode *root)
{
    //Reverse Level Order
    vector<TreeNode *> seq = ReverseLevelOrder(root);
    //Swap Tree Node of the corresponding sub-tree is not balanced
    for (int i = 0; i < seq.size() - 1; i++)
    {
        if (seq[i]->freq > seq[i + 1]->freq)
        {
            for (int j = seq.size() - 1; j > i; j--)
            {
                if (seq[j]->freq < seq[i]->freq)
                {
                    //Function to swap the Tree nodes
                    swapTreeNode(root, seq[i], seq[j]);
                    TreeNode *temp = seq[i];
                    seq[i] = seq[j];
                    seq[j] = temp;
                    i--;
                    break;
                }
            }
        }
    }
    return root;
}

//Function to encode the string according to Dynamic Huffman
void dynamic_huffman(string input)
{
    //Intializing root
    TreeNode *root = new TreeNode();
    //Insertion is equal to root as we will intially insert character to root
    TreeNode *insertion = root;
    //Map to track apperance of each character in string
    unordered_map<char, int> apperance;
    //This will map character to its corresponding TreeNode
    unordered_map<char, TreeNode *> node;

    //For loop to iterate over each character in string
    for (int i = 0; i < input.size(); i++)
    {
        //If this is the first ever apperance of the given character
        if (apperance[input[i]] == 0)
        {
            //Creating a new TreeNode for the current character
            TreeNode *current = new TreeNode();
            //Making its frequency 1
            current->freq = 1;
            //Storing it's symbol
            current->symbol = input[i];
            //Inserting it to the tree
            insertion = insertIntoTree(insertion, current);
            //Updating the map to Map this character to current TreeNode
            node[input[i]] = current;
            //Marking that the character is visited
            apperance[input[i]]++;
        }
        else
        {
            //Getting the TreeNode Corresponding to the given character
            TreeNode *current = node[input[i]];
            //Incrementing the frequency by 1
            current->freq++;
            //Updating each parent frequency by 1 to balance the tree later on
            while (current->parent != NULL)
            {
                current->parent->freq++;
                current = current->parent;
            }
        }

        //Balancing the Tree
        root = checkTree(root);
        //Printing the Tree level order wise
        printTree(root);
        //Printing code corresponding to each character
        cout << "Codes:\t";
        getCodes(root, "");
        cout << endl
             << endl;
    }
}
int main()
{
    string input;
    cout << "Enter the input string:\t";
    getline(cin, input);
    dynamic_huffman(input);
    return 0;
}

/*Time complexity : O(n^2)
Input : "Dynamic"
Output:
*1
*0  D1        
Codes:  'D':1 

*2
*1  D1        
*0  y1
Codes:  'y':01 'D':1 

*3
*2  D1
*1  y1
*0  n1
Codes:  'n':001 'y':01 'D':1

*4
*2  *2
D1  y1  *1  n1
*0  a1
Codes:  'D':00 'y':01 'a':101 'n':11 

*5
*2  *3
D1  y1  *2  n1
*1  a1
*0  m1
Codes:  'D':00 'y':01 'm':1001 'a':101 'n':11

*6
*2  *4  
D1  y1  *2  *2
n1  a1  *1  m1
*0  i1
Codes:  'D':00 'y':01 'n':100 'a':101 'i':1101 'm':111

*7
*3  *4
D1  *2  *2  *2  
*1  i1  n1  a1  y1  m1
*0  c1
Codes:  'D':00 'c':0101 'i':011 'n':100 'a':101 'y':110 'm':111
*/


<|start_filename|>Dart/maths/ArmstrongRecursive.dart<|end_filename|>
/**
This function is a recursive function, which calls itself over and over
according to the number of digits in the number. Using that and adding each
digit raised to the power of the number of digits, it keeps adding them
and we get the sum we need to compare with the number input.
 */
import 'dart:io';
import 'dart:math';

// recursive function which add digits raised to the power of number of digits
int armstrong(int num, int len) {
  if(num < 10) {
    return pow(num, len).toInt();
  } else {
    return (pow(num % 10, len).toInt() + armstrong(num ~/ 10, len));
  }
}

// Main Function, Entry Point of Program
void main() {
  print("Enter a number:");
  int num = int.parse(stdin.readLineSync()!);
  int len = num.toString().length;

  // Call function to check number is Armstrong
  if (num == armstrong(num, len)) {
    print("$num is an Armstrong Number");
  } else {
    print("$num is not an Armstrong Number");
  }
}

/**
Sample Input and Output :
Enter a number:
153
153 is an Armstrong Number

Enter a number:
213
213 is not an Armstrong Number

Time complexity = O(n)
Space complexity = O(1)
 */


<|start_filename|>Java/dp/Rectangle_cutting.java<|end_filename|>
/*
Given an a×b rectangle, your task is to cut it into squares. On each move you can select a rectangle and cut it into two
rectangles in such a way that all side lengths remain integers. What is the minimum possible number of moves?

Input

The only input line has two integers a and b.

Output

Print one integer: the minimum number of moves.

Constraints

1≤a,b≤500

Example

Input:
3 5

Output:
3

*/

/*
                                APPROACH
            ----------------------------------------------------
            We will make all the horizontal cuts and try to find 
            after which move we have to make minimum moves to make 
            all squares,
            Similarly,
            We do the same with vertical moves,
            We will divide the recetanle in two parts and add the 
            result for both parts and find minimum among all moves
            which will be our ans.

            Time Complexity : O(a*b)
            Space Complexity : O(a*b) due to the 2d array of size (a+1) by (b+1)
*/
import java.util.Scanner;

class Rectangle_cutting {
    static int dp[][]; // declaring dp array for memorization.

    static int cutting(int a, int b) {
        // if side lengths are equal then no move required.
        if (a == b)
            return 0;
        // for a by 1 or 1 by b rectangle we have to make a-1 and b-1 cuts respectively.
        if (a == 1 || b == 1)
            return Math.max(a, b) - 1;

        // if the result is stored already return it.
        if (dp[a][b] != -1)
            return dp[a][b];

        int ans = Integer.MAX_VALUE;

        // recursivly making cuts.
        // loop to make all the horizontal cuts
        /*
         * iterate upto a/2 only wwwww
         */
        for (int i = 1; i <= a / 2; i++) {
            // making every position move and taking the minimum out of it.
            ans = Math.min(ans, cutting(i, b) + cutting(a - i, b));
        }

        // loop to make all the vertical cuts
        for (int i = 1; i <= b / 2; i++) {
            // making every position move and taking the minimum out of it.
            ans = Math.min(ans, cutting(a, i) + cutting(a, b - i));
        }
        return dp[a][b] = 1 + ans; // this 1 corressponds to one of the minimum move we have done above.
    }

    static int cutting_iterative(int a, int b) {
        int dp[][] = new int[a + 1][b + 1];

        // These 2 loops are for base case.
        for (int i = 1; i <= a; i++)
            dp[i][1] = i - 1;
        for (int i = 1; i <= b; i++)
            dp[1][i] = i - 1;
        for (int i = 2; i < a + 1; i++) {
            for (int j = 2; j < b + 1; j++) {
                if (i == j)
                    dp[i][j] = 0;
                else {
                    int ans = Integer.MAX_VALUE;
                    for (int k = 1; k <= i / 2; k++)
                        ans = Math.min(ans, dp[k][j] + dp[i - k][j]);
                    for (int k = 1; k <= j / 2; k++)
                        ans = Math.min(ans, dp[i][k] + dp[i][j - k]);
                    dp[i][j] = 1 + ans;
                }
            }
        }
        return dp[a][b];
    }

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        dp = new int[501][501]; // because a,b <=500
        int a = sc.nextInt();
        int b = sc.nextInt();
        for (int i = 0; i <= a; i++)
            for (int j = 0; j <= b; j++)
                dp[i][j] = -1; // initialising the DP Array for Memorization.
        System.out.println(cutting(a, b));
        System.out.println(cutting_iterative(a, b));
        sc.close();
    }

}


<|start_filename|>C-Plus-Plus/dp/longest_common_subsequence.cpp<|end_filename|>
/*
Given two sequences, find the length of longest subsequence present in both of them.
A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous.
*/

#include <iostream>
#include <vector> // for 2D vector
using namespace std;

int lowest_common_subsequence(string &x, string &y)
{
    int len_x = x.length();
    int len_y = y.length();

    vector<vector<int> > dp (len_x+1, vector<int> (len_y+1,0));

    for(int i=1;i<=len_x;i++)
    {
        for(int j=1;j<=len_y;j++)
        {
            int q=0;

            if(x[i-1]==y[j-1]) //if matches
                q=1+dp[i-1][j-1];
            else     //if doesn't match
                q=max(dp[i-1][j],dp[i][j-1]);

        dp[i][j]=q;
        }
    }

    return dp[len_x][len_y]; //return last element
}

int main()
{
    string str1,str2;
    cout<<"Enter string1 and string2: ";
    cin>>str1>>str2;
    cout<<"output : "<<lowest_common_subsequence(str1,str2)<<endl;
}

/*
   Enter string1 and string2 : ABCDEFGH BDHCEG
   output : 4
*/

// Time and Space complexity : O(mn), where m = length of string1 and n = length of string2


<|start_filename|>Java/math/polynomial.java<|end_filename|>
/******************************************************************************
Author - @Suvraneel 
        <NAME>
* Implementation of a Polynomial Addition & multiplication using Linked Lists in Java *
******************************************************************************/

import java.util.*;
class LinkedList
{
	// Structure containing exponent and coefficient of variable 
	static class Term { 
		int coefficient;
		int exponent;
		//Link to next Term in singly LL
		Term link; 
	}

	// Function add a new Term at the end of list 
	static Term addTerm(Term head, int coefficient, int exponent) 
	{
		// Create a new Term 
		Term nd = new Term(); 
		nd.coefficient = coefficient; 
		nd.exponent = exponent;
		//Link pointing to null because this is leaf node as of yet
		nd.link = null; 

		// If linked list is empty
		if (head == null) 
			return nd;

		// Initiate a pointer at the head to start traversal 
		Term ptr = head;
		// Traverse until leaf Term
		while (ptr.link != null) 
			ptr = ptr.link;
		//return leaf term
		ptr.link = nd; 
		return head; 
	} 

	// Function to collapse the expanded form by merging duplicates in 1 term
	static void collapse(Term head) 
	{ 
		Term polyA;
		Term polyB;
		polyA = head; 
		//outer loop => for every term in poynomial,
		while (polyA != null && polyA.link != null) { 
			polyB = polyA;
			//inner loop => iterate through the rest of the loop to find redundant elements
			while (polyB.link != null) {
				// If exponent of two elements are same
				if (polyA.exponent == polyB.link.exponent) { 
					// Collapse them onto the 1st occurance of that term (ie, term currently in outer loop)
					polyA.coefficient += polyB.link.coefficient;
					polyB.link = polyB.link.link;
				}
				// If exponent not same, check the other terms - inner loop
				else polyB = polyB.link;
			}
			//check similarly for the next term as well - outer loop
			polyA = polyA.link;
		}
	}

	// Function two Add two polynomial Numbers 
	static Term sum(Term poly1, Term poly2, Term sumPoly) 
	{ 
		// Initiate 2 pointers for the 2 polynomials
		Term polyA;
		polyA = poly1;
		Term polyB;
		polyB = poly2;
		// Copy the terms of 1st polynomial to sumpoly
		while (polyA != null) {
			sumPoly = addTerm(sumPoly, polyA.coefficient, polyA.exponent);
			polyA = polyA.link;
		}
		//Add the terms of 2nd polynomial to sumPoly
		while (polyB != null) {
			sumPoly = addTerm(sumPoly, polyB.coefficient, polyB.exponent);
			polyB = polyB.link;
		}
		//call collapse function to minimise number of similar terms
		collapse(sumPoly);
		return sumPoly;
	}

	// Function two Multiply two polynomial Numbers 
	static Term multiply(Term poly1, Term poly2, Term pdtPoly) 
	{ 
		// Initiate 2 pointers for traversing the 2 polynomials
		Term polyA;
		Term polyB;
		polyA = poly1;
		polyB = poly2;
		//for every term in 1st polynomial, multiply it with each term in 2nd polynomial
		while (polyA != null) { 
			while (polyB != null) {
				int coefficient;
				int exponent;
				// Add the exponents to get result exponent
				exponent = polyA.exponent + polyB.exponent; 
				// Call Multiply function passing the coefficients
				coefficient = polyA.coefficient * polyB.coefficient; 
				// call addTerm function passing 3 parameters
				// thus adding the resultant term as node in the resultant polynomial
				pdtPoly = addTerm(pdtPoly, coefficient, exponent); 
				// move the pointer to the next term (node)
				polyB = polyB.link; 
			} 
			// Reset the pointer for new loop
			polyB = poly2; 
			//move the pointer to the next term (node) 
			polyA = polyA.link; 
		} 
		// collapse function (since pdt is in expanded form, minimise it)
		collapse(pdtPoly); 
		return pdtPoly; 
	} 

	// Function To Display The passed polynomial's LL
	static void displayPoly(Term ptr) 
	{ 
		//traverse & keep printing as long as leaf node is not found
		while (ptr.link != null) { 
			System.out.print( ptr.coefficient + "x^" + ptr.exponent + " + ");
			ptr = ptr.link; 
		}
		// Print the leaf node (ie, coefficient of x^0 term) 
		System.out.print( ptr.coefficient +"\n"); 
	} 

	// Main Driver Code 
	public static void main(String[] args) 
	{ 
		//Initiate nodes for holding input polynomials & resultant polynomials to null
		Term poly1 = null;
		Term poly2 = null;
		Term sumPoly = null;
		Term pdtPoly = null;
		Scanner myObj = new Scanner(System.in);

		//Take input for 1st polynomial
		System.out.print("Enter number of terms in 1st Polynomial: \t");
		int noOfTerms = myObj.nextInt();
		System.out.print("Enter 1st Polynomial as <coefficient exponent> : \t"); 
		for (int i=0; i<noOfTerms; i++){
			int coff = myObj.nextInt();
			int exp = myObj.nextInt();
			// Add the term as a node into the 1st polynomial LL
			poly1 = addTerm(poly1, coff, exp);
		}

		//Take input for 2nd polynomial
		System.out.print("Enter number of terms in 2nd Polynomial: \t");
		noOfTerms = myObj.nextInt();
		System.out.print("Enter 2nd Polynomial as <coefficient exponent> : \t"); 
		for (int i=0; i<noOfTerms; i++){
			int coff = myObj.nextInt();
			int exp = myObj.nextInt();
			// Add the term as a node into the 2nd polynomial LL
			poly2 = addTerm(poly2, coff, exp);
		}
		
		// Displaying 1st polynomial 
		System.out.print("1st Polynomial = \t\t"); 
		displayPoly(poly1); 
		// Displaying 2nd polynomial 
		System.out.print("2nd Polynomial = \t\t"); 
		displayPoly(poly2); 

		//calling sum function to evaluate (poly1 + poly2)
		sumPoly = sum(poly1, poly2, sumPoly);
		System.out.print( "Resultant Sum Polynomial = \t"); 
		displayPoly(sumPoly);

		// calling multiply function to evaluate (poly1 * poly2)
		pdtPoly = multiply(poly1, poly2, pdtPoly); 
		// Displaying Resultant Polynomial 
		System.out.print( "Resultant Product Polynomial = \t"); 
		displayPoly(pdtPoly); 
	}
}

/*
Time Complexity: O(n^2)
  AddTerm = O(n)
  Collapse = O(n^2)
  Sum = O(n^2) (for collapse call)
  Multiply = O(n^2)
  Print LL = O(n)
Sample Run:
  Enter number of terms in 1st Polynomial:        5
  Enter 1st Polynomial as <coefficient exponent> :        10 6 5 4 3 3 4 1 7 0
  Enter number of terms in 2nd Polynomial:        3
  Enter 2nd Polynomial as <coefficient exponent> :        6 3 2 1 5 0
  1st Polynomial =        		10x^6 + 5x^4 + 3x^3 + 4x^1 + 7
  2nd Polynomial =        		6x^3 + 2x^1 + 5
  Resultant Sum Polynomial =      10x^6 + 5x^4 + 9x^3 + 6x^1 + 12
  Resultant Product Polynomial =  60x^9 + 50x^7 + 68x^6 + 10x^5 + 55x^4 + 57x^3 + 8x^2 + 34x^1 + 35
*/



<|start_filename|>Go/math/Decimal_to_Binary/dectobin.go<|end_filename|>
/*
    This is a simple program in go language to conver a given
    number if in range ( i.e number <= 2147483647 ) into its
    binary equivalent and print it out.

*/

package main

import (

  "fmt"

)

// global variable
var array[32] int

// This funtion prints the binary equivalent of decimal number
func printnumbers(counter int) {

   fmt.Print("The binary equivalent of the given number is :")

   var i int
   for i = counter-1; i >= 0; i-- {

       fmt.Print(array[i])

   }

}

/* This function converts the entered number from decimal to 
   binary number and stores the elements in a array*/
func dectobin(n int) {

   var r int
   r = 0

   var counter int
   counter = 0

   /* We divide the number by 2 and store its remainder in
      an array and then update the number as the quotient
      divided by 2*/
   for n != 0 {

      r = n % 2
      array[counter] = r
      n = n/2

      counter +=1

   }

   //calling printnumbers function to print the binary number
   printnumbers(counter)

}

//driver function
func main() {

   var number int

   //The decimal number we need to convert
   fmt.Print("Enter the number you want to convert :")
   fmt.Scan(&number)

   // checking if the entered number is in range or not
   if(number <= 2147483647) {

       dectobin(number)

   }else {

       fmt.Print("The number entered not in range")

   }

}

/*
   Sample I/O :

   a) In range :

   Enter the number you want to convert :10
   The binary equivalent of the given number is :1010      

   b) Not in range :

   Enter the number you want to convert :2147483648 
   The number entered not in range

*/



<|start_filename|>C-Plus-Plus/ds/Zig_Zag_Level_Order_Traversal_Binary_Tree.cpp<|end_filename|>
/*
Introduction 
Given a Binary Tree , Print it in Zig Zag level order.
(i.e., from left to right, then right to left for the next level and alternate between).

Argument/Return Type
Input of total no.of nodes is taken
Input of key values of nodes of tree are taken in level order form 
Incase of a null node , -1 is taken as input
*/

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

//Define Node as structure
struct Node 
{
    int key;
    Node* left;
    Node* right;
};
 
// Function to create a node with 'value' as the data stored in it. 
// Both the children of this new Node are initially null.
struct Node* newNode(int value)
{
    Node* n = new Node;
    n->key = value;
    n->left = NULL;
    n->right = NULL;
    return n;
}

// Function to build tree with given input
struct Node* createTree(vector<int>v)
{
    int n=v.size();
    if(n==0) 
      return NULL;
    vector<struct Node* >a(n);
    //Create a vector of individual nodes with given node values
    for(int i=0;i<n;i++)  
    {
        //If the data is -1 , create a null node
        if(v[i]==-1)  
          a[i] = NULL;
        else 
          a[i] = newNode(v[i]);
    }
    //Interlink all created nodes to create a tree
    //Use two pointers using int to store indexes
    //One to keep track of parent node and one for children nodes
    for(int i=0,j=1;j<n;i++) 
    {
        //If the parent node is NULL , advance children pointer twice
        if(!a[i])
        {
          j=j+2;
          continue;
        } 
        //Connect the two children nodes to parent node
        //First left and then right nodes
        a[i]->left = a[j++];
        if(j<n) 
          a[i]->right = a[j++];
    }
    return a[0];
}

// Function to print Tree in zig zag level order
void ZigZagLevelOrderTraversal(struct Node* root)
{
    // If root is NULL , return 
    if (root == NULL)
        return ;

    vector<int>v;
    //Define a variable to store level
    int curr_level=0;

    // Create an queue
    queue<struct Node*> q;
    //Enqueue the root node and a null node to indicate a level is completed
    q.push(root);
    q.push(NULL);
 
    while (!q.empty()) 
    {
        if(q.front()==NULL)
        {
            curr_level++;
            q.pop();
            if(!q.empty())
            {
                //If there are more nodes in q , push a NULL node
                q.push(NULL);
            }
            //When a level is completed , print its elements
            //If it is a odd level, print from left to right
            //else print from right to left
            if(curr_level%2)
            {
                for(int i=0;i<v.size();i++)
                  cout<<v[i]<<" ";
            }
            else
            {
                for(int i=v.size()-1;i>=0;i--)
                  cout<<v[i]<<" ";
            }
            //Clear the vector after printing
            v.clear();
        }
        else
        {
            v.push_back(q.front()->key);
            //Enqueue node's children , if they exist
            if(q.front()->left)
               q.push(q.front()->left);
            if(q.front()->right)
               q.push(q.front()->right);
            q.pop();
        }
    }
    return ;
}
    
// Driver code
int main()
{

    int n;
    cout<<"Enter total no.of nodes of the input Tree ( including NULL nodes ) : ";
    cin>>n;

    vector<int>v(n);
    cout<<"Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces"<<endl;
    for(int i=0;i<n;i++)
    {
        cin>>v[i]; //store the input values in a vector
    }

    //create the tree using input node values  
    struct Node* root=createTree(v); 

    //Call the function and print the result
    cout<<"Zig Zag Level Order Traversal of given tree is : ";
    ZigZagLevelOrderTraversal(root);
    
    return 0; 
}
    
/*
Input:
0 <= node->key < 1000000000
if node is NULL , -1 is entered as it's key

Sample Test Case 1  
Input Binary Tree :                   

               1                                
           /         \                          
         2              11                    
     /       \        /   \               
    3        5       12    13             
   / \      /  \    / \   /  \            

  4 NULL    6  7    8  9 NULL  4         

Input Format : 
Example :
Enter total no.of nodes of the input Tree ( including NULL nodes ) : 15
Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces
1 2 11 3 5 12 13 4 -1 6 7 8 9 -1 4

Output Format :
Example : ( Output to the above input example ) 
Zig Zag Level Order Traversal of given tree is : 1 11 2 3 5 12 13 4 9 8 7 6 4 

Time/Space Complexity
Time Complexity : O(n) 
   Where n is the no.of nodes 
Space Complexity : O(n) 
   Where n is the no.of nodes
*/


<|start_filename|>Kotlin/Maths/ArmstrongRecursive.kt<|end_filename|>
/*Kotlin Program to check Given number is an Armstrong Number or not*/
import java.util.*

// Function for check Armstrong Number
fun isArmstrongNumber(num: Int, size: Int): Int {
    if (num<10) {
        return Math.pow(num.toDouble(), size.toDouble()).toInt()
    } else {
        return(Math.pow((num % 10).toDouble(), size.toDouble()).toInt() + isArmstrongNumber(num / 10, size))
    }
}

// Main Function, Entry Point of Program
fun main(arg: Array<String>) {
    val sc = Scanner(System.`in`)

    println("Enter Number: ")
    val num: Int = sc.nextInt()
    val size: Int = Integer.toString(num).length

    // Call function to check number is Armstrong
    if (num == isArmstrongNumber(num, size)) {
        println("$num is an Armstrong Number")
    } else {
        println("$num is not an Armstrong Number")
    }
}

/**
 * Sample input/output:
 * 
 * Enter Number: 
 * 153
 * 153 is an Armstrong Number
 * 
 * Enter Number: 
 * 224
 * 224 is not an Armstrong Number
 */


<|start_filename|>C-Plus-Plus/graphs/shortest_path_using_bfs.cpp<|end_filename|>
#include<bits/stdc++.h>
using namespace std;
void bfs(int source,vector <int> adj[],bool visited[],int parent[]){
    //Initializing a queue and pushing the source into it and marking visited for source as true
    queue<int> q; 
    q.push(source);
    visited[source] = true;
    while(!q.empty()){
        int curr = q.front();
        q.pop();
        //Traversing all the adjacents of the node
        for(auto s: adj[curr]){
            //Checking if this adjacent is visited or not
            if(!visited[s]){
                //Pushing into the queue
                q.push(s);
                //Marking visited as true
                visited[s] = true;
                //If not visited, this parent is the one closet to the source, i.e from 0->curr->s is the shortest path till s
                parent[s] = curr;
            }
        }
    }
}
int main(){
    int n,m; cin>>n>>m;
    vector <int> adj[n];
    int a,b;
    for(int i=0;i<m;i++){
        cin>>a>>b;
        adj[a].push_back(b);
        adj[b].push_back(a);
    }
    bool visited[n];
    memset(visited,false,sizeof(visited));
    //Parents array for storing the parent a nodes parent closest to the source
    int parent[n];
    //Considering 0 as the source
    parent[0] = -1;
    bfs(0,adj,visited,parent);
    //Printing shortest paths for each node from node 0
    for(int i=1;i<n;i++){
        int curr = i;
        vector<int> ans;
        while(curr!=-1){
            ans.push_back(curr);
            curr = parent[curr];
        }
        reverse(ans.begin(),ans.end());
        for(auto s: ans){
            cout<<s<<" ";
        }cout<<endl;
    }
    return 0;
}
/*
Input:
6 7
0 1
1 2
2 0
0 3
3 4
4 5
1 5

Output:
0 1 
0 2 
0 3 
0 3 4 
0 1 5

Time complexity : O(n+m)
Space complexity : O(n)
*/


<|start_filename|>Julia/cp/factorials.jl<|end_filename|>
#=Given a number N, find its factorial using recursion. It is quite easy
but we want to add recursion algorithms in Julia.=#

## Function 

function fact(n)
    if (n == 0)
        return 1
    end
    if (n == 1)
        return 1
    end
    return n * fact(n - 1)
end

## Input

n = readline()
n = parse(Int64, n)

## Calling the Function

fact(n)

#=
Sample Test Case:
Input:
    n=10
Output:
    3628800
Time complexity: O( N )
=#


<|start_filename|>C-Plus-Plus/other/merge_2_sorted_arrays_without_extra_space.cpp<|end_filename|>
#include<bits/stdc++.h>
using namespace std;

int main() {

  int m, n;
  cout << "Enter the total number of elements in array1 and array2 respectively\n";
  cin >> m >> n;

  int arr1[m], arr2[n];
  cout << "enter 1st array elements\n";
  for (int i = 0; i < m; i++) {
    cin >> arr1[i];
  }
  cout << "enter 2nd array elements\n";
  for (int i = 0; i < n; i++) {

    cin >> arr2[i];
  }
  
  // iterating through first array from the end and the second array from start.
  for (int i = m - 1, j = 0; i >= 0 && j < n; i--, j++) {
    int temp;
    // swap if number in 1st array is greater than 2nd array.
    if (arr1[i] > arr2[j]) {
      swap(arr1[i] , arr2[j]); 
    }
  }
  
  //sorting both the arrays to get final result.
  sort(arr1, arr1 + m);
  sort(arr2, arr2 + n);
  cout << "answer: ";
  for (int i = 0; i < m; i++) {
    cout << arr1[i] << " ";
  }
  for (int i = 0; i < n; i++) {
    cout << arr2[i] << " ";
  }
  cout << endl;

  return 0;
}

/*

Time complexity : NlogN (where N will be max of n and m)

Sample output:
Enter the total number of elements in array1 and array2 respectively
3 4
enter 1st array elements
2 4 6
enter 2nd array elements
1 3 5 7
answer: 1 2 3 4 5 6 7

*/


<|start_filename|>Java/graphs/DFS.java<|end_filename|>
import java.util.Scanner;

public class DFS{

	//dfs function for connected graph
	public static void dfsHelper(int[][] edges,
	 int noVertices, int startVertex, boolean[] visited){

	 	System.out.print(startVertex +  " ");
	 	visited[startVertex] = true;

	 	for(int i = 0; i < noVertices; i++){
	 		if(i == startVertex)
	 			continue;

	 		/*If there is an edge b/w starting vertex
	 		and curr vertex, call print on curr vertex */
	 		if(edges[startVertex][i] == 1){

	 			/*If we have already visited curr vertex,
	 			we will not call print on it */
	 			if(visited[i])
	 				continue;

	 			dfsHelper(edges, noVertices, i, visited);
	 		}
	 	}

	}

	//this works for disconnected graph also
	public static void dfs(int[][] edges, int noVertices){
		boolean[] visited = new boolean[noVertices];

		for(int i = 0; i < noVertices; i++){
			if(!visited[i])
				dfsHelper(edges, noVertices, i, visited);
		}

	}

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);

		System.out.println("Enter the number of vertices in Graph : ");
		int n = scanner.nextInt();  // no. of vertices

		System.out.println("Enter the number of edges in the Graph : ");
		int e = scanner.nextInt();  // no. of edges

		// Adjacency Matrix
		int[][] edges = new int[n+1][n+1];

		//Take input of all edges
		System.out.println("Enter the edges :");
		for(int i = 0; i < e; i++){
			int firstVertex = scanner.nextInt();
			int secondVertex = scanner.nextInt();
			edges[firstVertex][secondVertex] = 1;
			edges[secondVertex][firstVertex] = 1;;
		}

		System.out.println("DFS Traversal : ");
		dfs(edges, n);
	}
}

/*
Sample Case : 
Enter the number of vertices in Graph : 
10
Enter the number of edges in the Graph : 
8
Enter the edges :
1 2
1 3
2 4
4 6
3 5
5 0
7 8
8 9
DFS Traversal : 
0 5 3 1 2 4 6 7 8 9
*/
	 


<|start_filename|>C-Plus-Plus/heap/Reconstruct_Itinerary.cpp<|end_filename|>
/*--------------- RECONSTRUCT ITINERARY-------*/

/* In this problem we are given a 2-d vector named Tickets
   You are given a list of airline tickets where 
   tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight.

   ---TASK---
   You are to return the vector that contains the inorder form of the intinerary. 
   All of the tickets belong to a man who departs from "JFK", thus, the itinerary 
   must begin with "JFK". 
   If there are multiple valid itineraries, you should return the itinerary that has 
   the smallest lexical order when read as a single string. 

   ---EXAMPLE---
   Given tickets vector
   [["MUC","LHR"],
    ["JFK","MUC"],
    ["SFO","SJC"],
    ["LHR","SFO"]]

   ---APPROACH---
   1. Make an adjacency list from the given 2-d vector of the form 
       string -> multiset of strings
   2. Make a stack
   3. Iterate over the list, for every list[i] add the strings in the multiset to stack and remove it from the set
   4. If the list[i] is empty then, pop the top element from the stack ans push it to the final answer vector
   5. Keep on repeating the steps 3 and 4 untill the stack is empty
   6. Now the answer vector stores the reverse inorder for our itinerary
   7. Reverse the ans vector and then return.
*/

#include <bits/stdc++.h>
using namespace std;
vector<string> findItinerary(vector<vector<string>> &tickets)
{
    // map to store the adjacency list of the airports
    // Multiset is used so that the airports are in lexicographic order
    map<string, multiset<string>> adj;

    // vector to store the answer
    vector<string> ans;

    stack<string> myStack;
    myStack.push("JFK"); // for the starting is always from JFK

    // making the adjacency list of the strings
    for (int i = 0; i < tickets.size(); i++)
    {
        adj[tickets[i][0]].insert(tickets[i][1]);
    }
    // Iterating over the list and stack
    while (!myStack.empty())
    {
        //  get the top element
        string src = myStack.top();

        // check if size of multiset of src is zero or not
        if (adj[src].size() == 0)
        {
            ans.push_back(src);
            myStack.pop();
        }
        else
        {
            auto desti = adj[src].begin();
            myStack.push(*desti);
            adj[src].erase(desti);
        }
    }
    // reverse the ans vector to get the final inorder
    reverse(ans.begin(), ans.end());
    return ans;
}

int main()
{
    // n denotes the number of tickets
    int n;
    cin >> n;

    vector<vector<string>> tickets(n);
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < 2; j++)
        {
            string a;
            cin >> a;
            tickets[i].push_back(a);
        }
    }

    vector<string> ans = findItinerary(tickets);
    // printing the ans vector
    for (int i = 0; i < ans.size(); i++)
    {
        if (i == ans.size() - 1)
            cout << ans[i] << endl;
        cout << ans[i] << " -> ";
    }
}
/*------ CODE COMPLEXITY------
1. Firstly, making of adjacency list takes O(n) time
2. Then we enter the while loop, in which we traverse over every airport once and perform some 
   constant check-> O(2*n)
3. reverse the whole answer vector which also takes O(n) time

in whole TC of the code = O(n) + O(2*n) + O(n) = O(n) 
*/

/*-----SAMPLE INPUT-------
        
        MUC LHR 
        JFC MUC 
        SFO SJC 
        LHR SFO
 
 ------SAMPLE OUTPUT------
  
      JFK -> MUC -> LHR -> SFO -> SJC
 
 
 */


<|start_filename|>Java/cp/LongestSubstring_without_repeating_characters.java<|end_filename|>
import java.util.*;
class Longest_Substring {
    public int lengthOfLongestSubstring(String s) {
        if (s.length() == 1) return 1;
        
        ArrayList<Character> arrLL = new ArrayList<>();
        int si = 0;
        int ei = 0 ;
        int currlen = 0;
        int maxlen = 0;
        
        while (ei < s.length() && si < s.length()){

            if (!arrLL.contains(s.charAt(ei))){
                arrLL.add(s.charAt(ei));
                 ei++;
                currlen = ei - si;
                if (maxlen < currlen) maxlen = currlen;
            }

            else{
                arrLL.remove(Character.valueOf(s.charAt(si)));
                si++;
            }
        }
        return maxlen;
    }
    
    public void main(){
        Scanner s = new Scanner(System.in);
        String str = s.next();
        int ans = lengthOfLongestSubstring(str);
        System.out.println(ans);
}

/*
TIME COMPLEXITY O(N) where n is length of the the given string
SPACE COMPLEXITY O(1)

TEST CASE

INPUT
s = "bbbbb"
OUTPUT
1

INPUT 
s = "abcabcbb"
OUTPUT
3

*/



<|start_filename|>C-Plus-Plus/dp/fibonacci_bottom_up.cpp<|end_filename|>
#include <iostream>
using namespace std;

//space O(n)
int fib(int n,int dp[]){
	for(int i=2;i<=n;i++){
		dp[i]=dp[i-1]+dp[i-2];
	}
	return dp[n];
}

//space O(1)
int fib_Space_Opt(int n){
	//base case
	if(n == 0 || n == 1) return n;

	int a = 0;
	int b = 1;
	int c;

	for(int i=2;i<=n;i++){
		c = a + b;
		a = b;
		b = c;
	}
	return c;
}


int main() {
 int n;
 cout<<"Enter number 'n' to find nth fibonacci number: ";
 cin>>n;
 int dp[n+1]={0};
 dp[1] = 1;

 cout<<"Output calculated with space complexity O(n): ";
 cout<<fib(n,dp)<<endl;
 cout<<"Output calculated with space complexity O(1): ";
 cout<<fib_Space_Opt(n)<<endl;

return 0;
}

/*
sample input output
input: 10
output: 55
*/

/*
Time O(n)
*/


<|start_filename|>C/ds/MinimumElemetInStack.c<|end_filename|>
/*C program to find Minimum Element in a Stack in Constant Time i.e O(1).
    Maintain an additional stack that will keep track of the minimum element
    of the Original Stack.

    Every push to the primary STACK, compare the current value
    with the TOS of the temporary Stack and IF the current value is less
    than the TOS push the current value to the temporary STACK,such that
    the minimum element is always at the top of the STACK

*/

#include <stdio.h>
#include <malloc.h>

typedef struct Node {
  int value;
  struct Node *next;
} Node;

/* Stack1 pointer points to the original stack and stack2 pointer
   points to the temporary stack which will hold the minimum values
*/
Node *stack1 = NULL, *stack2 = NULL;

// check whether stack is empty or not
int isEmpty(Node *head) {
  // When stack-1 is empty return true
  if (head == NULL) {
    return 1;
  }
  return 0;
}

// Dynamically generate the node
Node *gen_node(int val) {
  Node *newnode;
  newnode = (Node *)malloc(sizeof(Node));
  if (newnode == NULL) {
    printf("\nMemory was not allocated");
    return 0;
  } else {
    newnode->value = val;
    newnode->next = NULL;
    return newnode;
  }
}

// Returns the top of the temporary stack
int peek() {
  int topVal;
  if (stack2 != NULL) {
    topVal = stack2->value;
  }
  return topVal;
}

// Push the element at the top of the stack
void push() {
  int val;
  Node *newNode, *temp;
  scanf("%d", &val);
  newNode = gen_node(val);

  if (stack1 == NULL) {
    stack1 = newNode;
    stack2 = newNode;
    stack1->next = stack2->next = NULL;
  } else {
    /* IF passed value is less than TOS of the temporary stack i.e stack2
        push the value,such that minimum element is always at the TOS of stack2
    */
    if (val <= peek()) {
      temp = stack2;
      stack2 = newNode;
      stack2->next = temp;
    }

    // Push data to original stack i.e stack1
    temp = stack1;
    stack1 = newNode;
    stack1->next = temp;
  }
}

int pop() {
  Node *temp;
  int tempVal;

  if (isEmpty(stack1)) {
    printf("\nStack is empty");
    return;
  } else {
    /* pop the min element from temporary stack ,if the value at originl STACK
     matches,such that minimum element is always at the top
     */
    if (stack1->value == peek()) {
      temp = stack2;
      stack2 = stack2->next;
    }
    temp = stack1;
    tempVal = temp->value;
    stack1 = stack1->next;
    free(temp);
  }
  return tempVal;
}

// Finding the minimum element from the temporary stack
int findMin() { peek(); }

int main() {
  int size, i;
  printf("Enter the size of the Stack:");
  scanf("%d",&size);

  printf("\nEnter the elements of the Stack:\n");
  for (i = 0; i < size; i++) {
    push();
  }

  printf("\n%d is popped from the stack", pop());
  printf("\nSmallest element in the Current Stack: %d", peek());

  return 0;
}

/*
  Time complexity: O(1) for finding the minimum
  Space complexity: O(n)
  
  Sample input/output:
  Enter the size of the Stack:5

  Enter the elements of the Stack:
  11
  5
  7
  2
  -5

  -5 is popped from the stack:
  Smallest element in the Current Stack: 2
  
 */


<|start_filename|>C-Plus-Plus/dp/Kadane_Algorithm.cpp<|end_filename|>
/*Kadane's Algorithm implementation
We use Kadane's algorithm when we need to find Maximum Array Sum .
The subarrays consist of both positive and negative numbers. Also it can be
modified to solve the variations as well */
# include <bits/stdc++.h>
using namespace std;

int kadane_1(int arr[], int arr_len)
{
	int max_sum = INT_MIN;
	int curr_sum = 0;

	for (int ind = 0; ind < arr_len; ind++)
	{
		// take sum of all the elements in the array
		curr_sum += arr[ind];
		//for maximum sum subarray when we comes across negative numbers the sum
		// made 0 as it reduces the sum
		if (curr_sum < 0)
			curr_sum = 0;
		max_sum = max(curr_sum, max_sum);
	}
	return max_sum ;
}
// we can also implement kadane's algorithm by storing current maximum sum and
// taking maximum of current sum + a[i] and a[i] in place of reducing negative sum to 0
int kadane_2(int arr[], int arr_len)
{
	int curr_sum_arr[arr_len];
	curr_sum_arr[0] = arr[0];
	for (int ind = 1; ind < arr_len; ind++) {
		curr_sum_arr[ind] = max(arr[ind], (curr_sum_arr[ind - 1] + arr[ind]));
	}
	int ans = INT_MIN;
	for (int ind = 0; ind < arr_len; ind++)
	{
		ans = max(ans, curr_sum_arr[ind]);
	}
	return ans;
}
int main()
{
	int arr_len; // length of array
	cin >> arr_len;
	int arr[arr_len];
	for (int ind = 0; ind < arr_len; ind++)
		cin >> arr[ind];
	cout << kadane_1(arr, arr_len);
	cout << '\n';
	cout << kadane_2(arr, arr_len);
	cout << '\n';

	return 0;
}


<|start_filename|>Java/dp/LCS.java<|end_filename|>
//program to find longest common subsequence using dynamic programming in java
import java.util.*;
public class lcsdp
{

  public static void main(String args[]) 
     {
   	Scanner s=new Scanner(System.in);
	System.out.println("Enter first string: ");//input the string1
	String a=s.next(); //sample input- asdfgk
	System.out.println("Enter second string: ");//input the string2
	String b=s.next();//sample input- adflom
	lcs(a,b);//call lcs function
	 //sample output-3
	s.close();
     }
		
   public static void lcs(String s1, String s2)
     {
			
	int[][] storage = new int[s1.length() + 1][s2.length() + 1];
	System.out.println("The length of lcs is " +lcsDP(s1, s2, storage));
     }

   public static int lcsDP(String s, String t, int[][] storage)
     {
	int m = s.length();
	int n = t.length();
	int storage1[][] = new int[s.length() + 1][t.length() + 1];
	for(int i=0;i<=m;i++)
	{ //initialize 1st row as 0
	  storage1[i][0]=0;
	 }
	for(int i=0;i<=n;i++)
	{//initialize 1st column as zero
           storage1[0][i]=0;
	 }
	 for(int i=1;i<=m;i++){
            for(int j=1;j<=n;j++){
		 if(s.charAt(m-i)==t.charAt(n-j)){//down to top approach
		      storage1[i][j]=1+storage1[i-1][j-1];
	            }
		  else{
		      storage1[i][j]=Math.max(storage1[i][j-1],storage1[i-1][j]);
	               //maximum out of the two
		       }
		}
	   }
	   return storage1[m][n];
     }

}
/*
Input:
Enter first string:
asdfghjk
Enter second string:
adfgiou
Output:
The length of lcs is 4
Time Complexity  : O(m*n)
Space Complexity : O(m*n)
*/


<|start_filename|>C-Plus-Plus/cp/sort_characters_by_their_occurrence.cpp<|end_filename|>
/*
Given a string,
sort it in decreasing order based on the occurrence of each characters.
then return new string.
*/

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

// this get_string_sort_characters_by_their_occurrence will give us the new string
string get_string_sort_characters_by_their_occurrence(string s)
{
    // we will insert characters into the map
    map < char, int > occur_char;
    for(int i = 0; i < (int)s.size(); i++)
    {
        occur_char[s[i]]++;
    }
    /* multimap can contain duplicate keys. that's why we will use it.
    here multimap's key is the occurrence of each character
    and multimap's value is that particular character.
    greater < int > will store them in descending order.
    */
    multimap < int , char, greater < int > > occur_char_2;
    for(auto i : occur_char)
    {
        occur_char_2.insert( { i.second , i.first } );
    }

    string new_string = "";

    for(auto i : occur_char_2)
    {
        int freq = i.first;
        while(freq--)
        {
            /* for each occurrence
            we will add particular character to
            our new string
            */
            new_string += i.second;
        }

    }
    return new_string;
}

int main()
{
    cout << "Enter the string : ";
    string s;
    cin >> s;
    string new_string = get_string_sort_characters_by_their_occurrence(s);
    cout << "The New String based on the occurrence of each characters is : \n";
    cout << new_string << endl;
}

/*
Standard Input and Output

Enter the string :
GMAFGGGMMAF

The New String based on the occurrence of each characters is :
GGGGMMMAAFF

Time Complexity : O( log N )
Space Complexity : O( N )

*/


<|start_filename|>Java/Algorithms/Strassens_Algo_for_Matrix_multiplication.java<|end_filename|>
/*
	Strassen's Algorithm is an algorithm for Matrix multiplication.
	It is faster(optimal) than the standard matrix multiplication algorithm and
	is useful in practice for large matrices. It uses the Divide N Conquer Approach
	and recursively divides a Matrix into four small matrices.
*/

import java.util.Scanner;

public class Strassens_Algo_for_Matrix_multiplication {

    // Function to multiply matrices
    // A and B are the two matrices to be multiplied
    public int[][] multiply(int[][] A, int[][] B) {
        // Order of matrix
        int n = A.length;

        // Creating a 2D square matrix with size n
        int[][] output = new int[n][n];

        // Base case
        // If there is only single element in the two matrices
        if (n == 1)

            // Returnng the simple multiplication of
            // two elements in matrices
            output[0][0] = A[0][0] * B[0][0];

        else {
            // Dividing the two Matrices into parts
            // by storing sub-parts to variables
            /*
             * A = [A11 A12 A21 A22]
             *
             * B = [B11 B12 B21 B22]
             */
            int[][] A11 = new int[n / 2][n / 2];
            int[][] A12 = new int[n / 2][n / 2];
            int[][] A21 = new int[n / 2][n / 2];
            int[][] A22 = new int[n / 2][n / 2];
            int[][] B11 = new int[n / 2][n / 2];
            int[][] B12 = new int[n / 2][n / 2];
            int[][] B21 = new int[n / 2][n / 2];
            int[][] B22 = new int[n / 2][n / 2];

            // Dividing matrix A into 4 halves i.e A11, A12, A21, A22
            split(A, A11, 0, 0);
            split(A, A12, 0, n / 2);
            split(A, A21, n / 2, 0);
            split(A, A22, n / 2, n / 2);

            // Dividing matrix B into 4 halves i.e B11, B12, B21, B22
            split(B, B11, 0, 0);
            split(B, B12, 0, n / 2);
            split(B, B21, n / 2, 0);
            split(B, B22, n / 2, n / 2);

            // Using Formulas as described in the algorithm
            // You can check it out on https://en.wikipedia.org/wiki/Strassen_algorithm

            // Calculating M1, M2, M3, M4, M5, M6, M7 by recursively calling multiply()

            // M1:=(A11+A22)×(B11+B22)
            int[][] M1 = multiply(add(A11, A22), add(B11, B22));

            // M2:=(A21+A22)×B11
            int[][] M2 = multiply(add(A21, A22), B11);

            // M3:=A11x(B12-B22)
            int[][] M3 = multiply(A11, sub(B12, B22));

            // M4:=A22×(B21−B11)
            int[][] M4 = multiply(A22, sub(B21, B11));

            // M5:=(A11+A12)×(B22)
            int[][] M5 = multiply(add(A11, A12), B22);

            // M6:=(A21-A11)×(B11+B12)
            int[][] M6 = multiply(sub(A21, A11), add(B11, B12));

            // M7:=(A12-A22)×(B21+B22)
            int[][] M7 = multiply(sub(A12, A22), add(B21, B22));

            // Output Matrix after multiplication:-
            /*
             * output = [C11 C12 C21 C22]
             */

            // C11:=M1+M4−M5+M7
            int[][] C11 = add(sub(add(M1, M4), M5), M7);

            // C12:=M3+M5
            int[][] C12 = add(M3, M5);

            // C21:=M2+M4
            int[][] C21 = add(M2, M4);

            // C22:=M1−M2+M3+M6
            int[][] C22 = add(sub(add(M1, M3), M2), M6);

            // Join 4 halves into one result matrix
            join(C11, output, 0, 0);
            join(C12, output, 0, n / 2);
            join(C21, output, n / 2, 0);
            join(C22, output, n / 2, n / 2);
        }

        // Step 4: Return result
        return output;
    }

    // Funtion to substract two matrices
    public int[][] sub(int[][] A, int[][] B) {
        int n = A.length;

        // Resultant Matrix
        int[][] C = new int[n][n];

        // Outer loop for rows
        for (int i = 0; i < n; i++)

            // Inner loop for columns
            for (int j = 0; j < n; j++)

                // Substracting corresponding elements
                // from matrices
                C[i][j] = A[i][j] - B[i][j];

        return C;
    }

    // Funtion to add two matrices
    public int[][] add(int[][] A, int[][] B) {
        int n = A.length;

        // Resultant matrix
        int[][] C = new int[n][n];

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

                // Adding corresponding elements
                // of matrices
                C[i][j] = A[i][j] + B[i][j];

        return C;
    }

    // Funtion to split the parent matrix
    // into child matrices
    public void split(int[][] P, int[][] C, int iP, int jP) {
        // iP and jP are starting indexes to split the Parent Matrix
        // Outer loop for rows
        for (int i1 = 0, i2 = iP; i1 < C.length; i1++, i2++)

            // i1 and j1 used to traverse child matrix
            // i2 and j2 used to traverse Parent matrix
            // Inner loop for columns

            for (int j1 = 0, j2 = jP; j1 < C.length; j1++, j2++)

                C[i1][j1] = P[i2][j2];
    }

    // Funtion to join child matrices
    // into the Parent matrix
    // iP and jP are starting indexes to join into the Parent Matrix
    public void join(int[][] C, int[][] P, int iP, int jP)

    {
        // Outer loop for rows
        for (int i1 = 0, i2 = iP; i1 < C.length; i1++, i2++)

            // Inner loop for columns
            for (int j1 = 0, j2 = jP; j1 < C.length; j1++, j2++)

                P[i2][j2] = C[i1][j1];
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Strassen Multiplication Algorithm Implementation For Matrix Multipication :\n");

        Strassens_Algo_for_Matrix_multiplication s = new Strassens_Algo_for_Matrix_multiplication();

        System.out.println("Enter the order of the matrices:- ");
        int N = sc.nextInt();

        // Matrix A
        int[][] A = new int[N][N];
        System.out.println("Enter elements of Matrix A:- ");

        for (int i = 0; i < N; i++) {

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

                A[i][j] = sc.nextInt();
            sc.nextLine();
        }

        // Matrix B
        int[][] B = new int[N][N];
        System.out.println("Enter elements of Matrix B:- ");

        for (int i = 0; i < N; i++) {

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

                B[i][j] = sc.nextInt();
            sc.nextLine();
        }

        // Resultant Matrix after multiplying matrices A and B
        int[][] output = s.multiply(A, B);

        System.out.println("\nProduct of matrices A and B : ");

        for (int i = 0; i < N; i++) {

            for (int j = 0; j < N; j++)
                System.out.print(output[i][j] + " ");

            System.out.println();
        }
    }
}

/*
 * Note*:- This Algorithm is mainly used to multiply two square Matrices(NxN).
 * Also this Algorithm provides an optimized way to multiply two large matrices.
 *
 *
 * Time Complexity of Strassen's Algorithm:- O(n^2.81) log2(7) = 2.8073 i.e 2.81
 * Space Complexity:- O(n^2.81)
 */

/*
Sample Testcase:
A =  1 2 3 4
	 4 3 0 1
	 5 6 1 1
	 0 2 5 6

B =  1 0 5 1
	 1 2 0 2
	 0 3 2 3
	 1 2 1 2

output = 7 21 15 22
		 8  8 21 12
		12 17 28 22
		 8 31 16 31
*/


<|start_filename|>C/cp/prefix_sum.c<|end_filename|>
/*
Given an array of N elements , find it's prefix sum array. In Competitive Programming, many times we need to calculate prefix sum array to solve our problem.
*/

#include <stdio.h>

void prefix_sum_array(int ar[] ,int N)
{
    int pref_ar[N + 1];
    pref_ar[0] = ar[0];
    int i = 0;
    /* we will add the current element of ar[] array
    and previous element of pref_ar [] array */
    for(i = 1; i < N; i++)
    {
        pref_ar[i] = ar[i] + pref_ar[i - 1];
    }
    printf("The New Prefix sum array is \n");
    for(int i = 0; i < N; i++)
    {
        printf("%d ",pref_ar[i] );
    }
    printf("\n");
    return;
}

int main()
{
    printf("Enter the size of array \n");
    int N;
    scanf("%d", &N);
    int ar[N + 1];
    printf("Enter array elements \n");
    for(int i = 0; i < N; i++)
    {
        scanf("%d", &ar[i]);
    }
    prefix_sum_array(ar , N);
}
/*
Standard Input and Output

Enter the size of array 
7
Enter array elements
10 4 16 34 23 5 90

The New Prefix sum array is
10 14 30 64 87 92 182

Time Complexity : O(N)
Space Complexity : O(N)

*/


<|start_filename|>C/sort/tim_sort.c<|end_filename|>
// C Program to implement Tim Sort
/*  
Tim Sort is a stable sorting algorithm that combines the capabilities of  Merge sort and Insertion sort.
It first splits the array into  small segments and sort them using Insertion Sort, and then merges the small segments using merge operation.
It is used in Java’s Arrays.sort() as well as Python’s sorted() and sort()
*/
#include <stdio.h>
const int SIZE = 16;

//Helper function to find the minimum of two variables
int min(int a, int b)
{
    if (a < b)
        return a;
    return b;
}

// Perform insertion sort
void insertion_sort(int arr[], int start, int end)
{
    for (int i = start + 1; i <= end; i++)
    {
        int temp = arr[i], j = i - 1;

        /* Shift elements of arr[0..i-1], that are 
        greater than temp, to one position ahead 
        of their current position */
        while (j >= start && arr[j] > temp)
        {
            arr[j + 1] = arr[j];
            j--;
        }
        arr[j + 1] = temp;
    }
}

// Merge operation to merge two sorted segments
void merge(int arr[], int start, int mid, int end)
{
    int n = mid - start + 1, m = end - mid;
    int arr1[n], arr2[m];

    for (int i = 0; i < n; i++)
        arr1[i] = arr[start + i];
    for (int i = 0; i < m; i++)
        arr2[i] = arr[mid + 1 + i];

    int i = 0, j = 0, k = start;

    while (i < n && j < m)
    {
        if (arr1[i] <= arr2[j])
        {
            arr[k] = arr1[i];
            i++;
        }
        else
        {
            arr[k] = arr2[j];
            j++;
        }
        k++;
    }
    while (i < n)
    {
        arr[k] = arr1[i];
        k++;
        i++;
    }
    while (j < m)
    {
        arr[k] = arr2[j];
        k++;
        j++;
    }
}

// Sort the array using Tim Sort
void tim_sort(int arr[], int n)
{
    // Sort individual subarrays of size SIZE
    for (int i = 0; i < n; i += SIZE)
        insertion_sort(arr, i, min((i + 15), (n - 1)));

    // Merge all the small segments formed
    for (int size = SIZE; size < n; size = 2 * size)
    {
        // From the start of the array, we are going to merge two segments each of size SIZE.
        for (int left = 0; left < n; left += 2 * size)
        {
            // Find  mid point
            int mid = left + size - 1;
            int right = min((left + 2 * size - 1), (n - 1));
            // Merge the two subarrays
            merge(arr, left, mid, right);
        }
    }
}

int main()
{
    int n;
    printf("\nHow many numbers do you want to sort? ");
    scanf("%d", &n);
    int arr[n];

    if (n <= 0)
    {
        printf("There are no numbers to sort!!!");
        return 0;
    }
    // Input the numbers to sort
    printf("Enter the numbers: ");
    for (int i = 0; i < n; i++)
        scanf("%d", &arr[i]);

    tim_sort(arr, n);

    printf("The numbers in sorted order is: ");
    // Print the sorted array
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");

    return 0;
}

/*
Time Complexity: O(n*log(n)), where 'n' is the number of elements to sort
Space Complexity- O(n)

SAMPLE INPUT AND OUTPUT

SAMPLE 1
How many numbers do you want to sort? 5
Enter the numbers: 1 3 5 2 4
The numbers in sorted order is:  1  2  3  4  5


SAMPLE 2
How many numbers do you want to sort? 0
There are no numbers to sort!!!

*/


<|start_filename|>C-Plus-Plus/other/string_rotation.cpp<|end_filename|>
/*
String Rotation
---------------

Problem Statement:
Rotate a given string in specified direction by specified magnitude.
After each rotation make a note of the first character of the rotated String, After all rotation are performed the 
accumulated first character as noted previously will form another string, say FIRSTCHARSTRING.
Check If FIRSTCHARSTRING is an Anagram of any substring of the Original string.
If yes print "YES" otherwise "NO".
Input
The first line contains the original string s. The second line contains a single integer q. The ith of the next q 
lines contains character d[i] denoting direction and integer r[i] denoting the magnitude.
*/

#include <string.h>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;

// performing left shift operation
string shiftLeft(string s, int c) 
{
    return s.substr(c) + s.substr(0, c);
}

// performing right shift operation
string shiftRight(string s, int c) 
{
    return s.substr(c + 1) + s.substr(0, c + 1);
}

// DRIVER FUNCTION
int main()
{
    char str[200], direction;
    int queries, amount;
    // first characters after performing each query is concatenated
    string firstchar = ""; 
    // getting the input string
    cin >> str;            
    cin >> queries;
    for (int query_num = 0; query_num < queries; query_num++)
    {
        // getting the direction and amount
        cin >> direction >> amount; 
        // if direction is left, perform left shift
        if (direction == 'L')       
        {
            firstchar += shiftLeft(str, amount)[0];
        }
        // if direction is right, perform right shift
        else if (direction == 'R') 
        {
            firstchar += shiftRight(str, amount)[0];
        }
    }
    map<char, int> mp1, mp2;
    for (auto &i : firstchar)
        // storing occurrence of characters in firstchar in map
        mp1[i]++; 
    unsigned i = 0, d = firstchar.size();
    // check if the size id greater than that of original string
    if (d > (int)strlen(str)) 
    {
        cout << "NO";
        return 0;
    }
    for (i = 0; i < d; i++)
        // storing occurrence of characters in str in map
        mp2[str[i]]++; 
    for (; i < (int)strlen(str); i++)
    {
        mp2[str[i]]++;
        if (mp2[str[i - d]] == 1)
        {
            mp2.erase(mp2.find(str[i - d]));
        }
        else
            mp2[str[i - d]]--;
        // condition to check whether firstchar is an anagram of str
        if (mp1 == mp2) 
        {
            cout << "YES";
            return 0;
        }
    }
    // if firstchar is not an anagram of str, print NO
    cout << "NO"; 
    return 0;
}
/*
For ex:
Example1:
Input:
career
3
L 2
R 3
L 2

Output:
NO

Example 2:
Input:
carrace
2
L 3
R 3
YES
*/

<|start_filename|>C/sort/Iterative_Merge_Sort.c<|end_filename|>
/* program for executing merge sort in a iterative manner*/
/* TIME COMPLEXITY: O(nlogn) */

#include <stdio.h>
#include<stdlib.h>

//function for taking input
void input(int a[],int n)
{
    for(int i=1; i<=n; i++)
    {
      printf("\nElement: " );
      scanf("%d",&a[i] );
    }
}

//function for swapping
void swap(int *x,int *y)
{
  int temp=*x;
  *x=*y;
  *y=temp;
}

//function for merging element
void Merge(int A[],int l,int mid,int h)
{
  //variable declaration
  int i=l,j=mid+1,k=l;
  int B[100];

  //loop for merging element
  while(i<=mid && j<=h)
  {
    if(A[i]<A[j])
    {
      B[k++]=A[i++];
    }
    else
    {
      B[k++]=A[j++];
    }
  }

  //loops for leftover element
  for(;i<=mid;i++)
  {
    B[k++]=A[i];
  }
  for(;j<=h;j++)
  {
    B[k++]=A[j];
  }
  for(i=l;i<=h;i++)
  {
     A[i]=B[i];
  }
}
void IMergeSort(int A[],int n)
{
  //variable declaring
  int p,l,h,mid,i;

  //loop for executing iterative merge sort
  for(p=2;p<=n;p=p*2)
  { for(i=0;i+p-1<=n;i=i+p)
    {
      //calculating value for low, high and mid
      l=i;
      h=i+p-1;
      mid=(l+h)/2;
      //function calling
      Merge(A,l,mid,h);
    }
  }

  //if p/2 is less than n
  if(p/2<n)
  {
    //function calling
    Merge(A,0,p/2-1,n);
  }

}
int main()
{
  //declaring and inputting array
  int size,*p;
  printf("\nEnter size of array: " );
  scanf("%d",&size );
  p=(int * )malloc(size*sizeof(int));
  input(p,size);

  //calling iterative merge sort
  IMergeSort(p,size);

  //loop for displaying
  printf("\nSorted Array:\n " );
  for(int i=0;i<size;i++)
  {
    printf("%d ",p[i]);
  }
  printf("\n");

  return 0;
}

/*sample input/output */
/*
Enter size of array: 5

Element: 80

Element: 100

Element: 20

Element: 60

Element: 40

Sorted Array:
 20 40 60 80 100

Press any key to continue . . .
*/


<|start_filename|>C-Sharp/math/tower_of_hanoi.cs<|end_filename|>
// Tower of Hanoi problem a mathematical problem
// The Time complexity of this problem is O(2^n) and Space complexity is O(n).

using System; 
  
class towerOfHanoi
{ 
	// recursive function to move complete disks from starting rod to final rod
	
    static void moveDisks(int n, int start_rod, int final_rod, int aux_rod) 
    { 
        if (n>0) 
        { 
        moveDisks(n-1, start_rod, aux_rod, final_rod); 
        Console.WriteLine("Move disk " + n + " from rod " + start_rod + " to rod " + final_rod); 
        moveDisks(n-1, aux_rod, final_rod, start_rod); 
        }
    } 
      
    public static void Main() 
    { 
        Console.WriteLine("Enter the number of disks: ");
        int num = Convert.ToInt32(Console.ReadLine());
          
        moveDisks(num, 1, 3, 2);  
    } 
}

/* Sample input/output
Enter the number of disks: 
4
Move disk 1 from rod 1 to rod 2
Move disk 2 from rod 1 to rod 3
Move disk 1 from rod 2 to rod 3
Move disk 3 from rod 1 to rod 2
Move disk 1 from rod 3 to rod 1
Move disk 2 from rod 3 to rod 2
Move disk 1 from rod 1 to rod 2
Move disk 4 from rod 1 to rod 3
Move disk 1 from rod 2 to rod 3
Move disk 2 from rod 2 to rod 1
Move disk 1 from rod 3 to rod 1
Move disk 3 from rod 2 to rod 3
Move disk 1 from rod 1 to rod 2
Move disk 2 from rod 1 to rod 3
Move disk 1 from rod 2 to rod 3
*/


<|start_filename|>Dart/maths/Armstrong.dart<|end_filename|>
import 'dart:math';
import 'dart:io';

// checks if num is armstrong or not
bool isArmstrong(int num) {
  bool isArmNum = false;
  int result = 0;
  int temp = num;

  // Count No Digits in numbers
  int numberOfDigits = temp.toString().length;

  while (temp > 0) {
    int remainder = temp % 10;
    result += pow(remainder, numberOfDigits).toInt();
    temp ~/= 10;
  }

  if (result == num) {
  isArmNum = true;
  }
  return isArmNum;
}

// Main Function, Entry Point of Program
void main() {
  print("Enter a number:");
  int num = int.parse(stdin.readLineSync()!);

  // Call function to check number is Armstrong
  if (isArmstrong(num)) {
    print("$num is an Armstrong Number");
  } else {
    print("$num is not an Armstrong Number");
  }
}
/**
 * Sample input/output:
 * Enter Number: 
 * 153
 * 153 is an Armstrong Number
 * 
 * Enter Number: 
 * 224
 * 224 is not an Armstrong Number
 */


<|start_filename|>Julia/sort/comb_sort.jl<|end_filename|>
"""Julia program to implement Comb Sort
Comb sort is an improvised Bubble sort. Bubble sort removes its inversions one by one whereas In Comb sort,
more than one inversion is removed by one swap and hence it is more efficient than Bubble sort.
"""

function comb_sort(arr, n)
    flag = 1
    space = n
    while (space > 1 || flag == 1)
        # Here empirically found shrink factor 1.3 is used.
        space = (space * 10) ÷ 13

        # Assigning space its minimum value of 1
        if (space < 1)
            space = 1
        end
        flag = 0

        # Compare elements with the space value
        for i in 1:(n - space)
            if (arr[i] > arr[i + space])
                arr[i], arr[i + space] = arr[i + space], arr[i]
                flag = 1
            end
        end
    end
end
    
     

print("How many numbers do you want to sort? ")
n = readline()
n = parse(Int64, n)
if (n <= 0)
    println("No numbers to sort!!!")
    exit()
end
arr = Int[]
print("Enter the numbers: ")
arr = [parse(Int, num) for num in split(readline())]
comb_sort(arr, n)
print("The numbers in sorted order is ")
print(arr)


"""
Time Complexity - O(n^2), where 'n' is the size of the array
Space Complexity - O(n)

SAMPLE INPUT AND OUTPUT

SAMPLE I
How many numbers do you want to sort? 6
Enter the numbers: 123 13 42 324 153 43 
The numbers in sorted order is [13, 42, 43, 123, 153, 324]
"""


<|start_filename|>C/math/Palindrome.c<|end_filename|>
/* Below code checks if the given input string is
a palindrome or not. The string is traversed till
its middle index and beginning and end of the string
is compared.*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Define maximum length of input string
#define MAXLENGTH 100

// This function checks if string is a palindrome
int check_palindrome(char* string) {
	
	// Iterate till the middle of the string
	for(int i = 0; i < (strlen(string) - 1) / 2; i++) {
		/* Check if character at beginning index of the
		string matches the end of the string at same index*/
		if(string[i] != string[strlen(string) - 2 - i]) {
			// If it does not then return -1
			return -1;
		}
	}
	// If everything matches then return 1
	return 1;
}

int main() {

	// Take string as input from the user
	char string[MAXLENGTH];
	printf("Enter a string to check if it is a palindrome: ");
	fgets(string, MAXLENGTH, stdin);

	// Calling the function to check
	int result = check_palindrome(string);
	
	// If the string is a palindrome
	if(result == 1) {
		printf("The given string is a palindrom.\n");
	}
	// If the string is not a palindrome
	else {
		printf("The given string is not a palindrom.\n");
	}
	
	return 0;
}

/* Sample I/O:
	Enter a string to check if it is a palindrome: This is a si sihT
	The given string is a palindrom.
*/



<|start_filename|>C-Plus-Plus/sort/sleep_sort.cpp<|end_filename|>
#include<iostream>
#include<thread>
#include<chrono>
#include<vector>

std::vector <int> Sorted;

void CountDown(int Sec)
{
	std::this_thread::sleep_for(std::chrono::seconds(Sec));
	Sorted.push_back(Sec);
}

void Multithread(int NumList[], int n){
    std::vector <std::thread> Threads;
    for (int i = 0; i <= n; i++)
	{
		Threads.push_back(std::thread(CountDown, NumList[i]));
	}
	for (auto& thread : Threads)
	{
		thread.join();
	}
}

int main()
 {
    	int n,i;
	std::cin >> n;
	int NumList[n];
	for(i = 0; i < n; i++)
	{
           std::cin >> NumList[i];
	}
	Multithread(NumList, n);
	for (auto& Num : Sorted)
	{
		std::cout << Num<<std::endl;
	}
    return 0;
}

/*
Sample Input : n = 3
	       89
	       12
               26
Sample Output: 12
	       26
               89
Time Complexity : O(NlogN + max(input)) where input is maximum of input array elements.
Space Complexity : All the things are done by the internal priority queue of the OS. Hence auxiliary space is ignored
*/


<|start_filename|>Go/sort/merge_sort/mergeSort.go<|end_filename|>
// Author : @belikesayantan

package main

import (
	"bufio"
	"errors"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"
	"time"
)

func main() {
	var strArray []string
	var intArray []int

	fmt.Println("Enter an array with spaces")
	reader := bufio.NewReader(os.Stdin)
	arr, err := reader.ReadString('\n')
	if err != nil {
		inputErr := errors.New("something is wrong with your array input")
		log.Fatal(inputErr)
	}
	arr = strings.TrimSpace(arr)
	strArray = strings.Split(arr, " ")

	for _, val := range strArray {
		ele, err := strconv.Atoi(val)
		if err != nil {
			panic(err)
		}
		intArray = append(intArray, ele)
	}

	start := time.Now() // timer starts and records running time of MergeSort Algorithm
	fmt.Println("Sorted Array is: ", MergeSort(intArray))
	end := time.Now() // timer stops and recording running time of MergeSort Algorithm is completed

	fmt.Println("\nRunning Time of MergeSort Algorithm is: ", end.Sub(start))
}

func merge(arr1 []int, arr2 []int) []int {
	i, j := 0, 0

	arr := make([]int, len(arr1)+len(arr2))

	for i < len(arr1) && j < len(arr2) {
		if arr1[i] < arr2[j] {
			arr[i+j] = arr1[i]
			i++
		} else {
			arr[i+j] = arr2[j]
			j++
		}
	}

	for i < len(arr1) {
		arr[i+j] = arr1[i]
		i++
	}
	for j < len(arr2) {
		arr[i+j] = arr2[j]
		j++
	}

	return arr
}

// MergeSort Algorithm Time Complexity : O(nlogn) in worst-case
func MergeSort(arr []int) []int {
	if len(arr) == 0 {
		return nil
	}

	if len(arr) < 2 {
		return arr
	}
	mid := len(arr) / 2
	left := MergeSort(arr[:mid])
	right := MergeSort(arr[mid:])

	return merge(left, right)
}

/*
	I/O Sample:

	Sample 1:
	❯ go run mergeSort.go
	Enter an array with spaces
	5 3 2 4 5 84 6 1 54
	Sorted Array is:  [1 2 3 4 5 5 6 54 84]

	Running Time of MergeSort Algorithm is:  280.029µs


	Sample 2:
	❯ go run mergeSort.go
	Enter an array with spaces
	5 8 6 9 1 3 2 7 4
	Sorted Array is:  [1 2 3 4 5 6 7 8 9]

	Running Time of MergeSort Algorithm is:  83.639µs



	Time Complexity:
		1. Ω(n log(n)) in best case
		2. O(n log(n)) in average case
		3. O(n log(n)) in worst case

	Space Complexity: O(n) in worst case

*/


<|start_filename|>C/ds/Preordertraversal.c<|end_filename|>
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

struct BST{
 int data;
 struct BST *left;
 struct BST *right;
};

struct BST* create();
void insert(struct BST*, struct BST*);
void preorderRecursive(struct BST*);
void preorderIterative(struct BST*);

int main(){
 char ch;
 struct BST *root=NULL, *temp;
 do{
    temp=create();
    if(root==NULL){
        root=temp;
	printf("Element inserted successfully! \n");
        }
    else{ 
        insert(root,temp);
        printf("Element inserted successfully! \n");
    }
    printf("Do you want to enter more data? (y/n) ");
    getchar();
    scanf("%c", &ch);
 }while(ch=='y' || ch== 'Y');
 printf("\nPreorder traversal using recursion\n");
 preorderRecursive(root);
 printf("\nPreorder traversal using iteration\n");
 preorderIterative(root);
 getch();
 return 0;
}

struct BST *create(){
 struct BST *temp;
 printf("Enter data: ");
 temp=(struct BST*)malloc(sizeof(struct BST*));
 scanf("%d", &temp->data);
 temp->left=NULL;
 temp->right=NULL;
 return temp;
}

void insert(struct BST *root, struct BST *temp){
 if(temp->data<root->data){
   if(root->left==NULL){
    root->left=temp;
   }
   else{
    root=root->left;
    insert(root, temp);
   }
 }
 else if(temp->data>root->data){
   if(root->right==NULL){
    root->right=temp;
   }
   else{
    root=root->right;
    insert(root, temp);
   }
 }
}

void preorderRecursive(struct BST *root){
    if(root!=NULL){
        printf("%d ", root->data);
        preorderIterative(root->left);
        preorderIterative(root->right);
    }
}

void preorderIterative(struct BST* root)
{
    while(root){
        if(root->left!=NULL){
            struct BST* node = root->left;
			while(node->right && node->right != root){
			    node=node->right;
			}
			if(node->right==root){
				node->right=NULL;
				root=root->right;
			}
			else{
		        printf("%d ", root->data);
				node->right=root;
				root=root->left;
			}
        }
        else{
		    printf("%d ", root->data);
			root=root->right;
        }
    }
}

//  Sample Output

// Enter data: 5
// Element inserted successfully! 
// Do you want to enter more data? (y/n) y
// Enter data: 3
// Element inserted successfully! 
// Do you want to enter more data? (y/n) y
// Enter data: 8
// Element inserted successfully! 
// Do you want to enter more data? (y/n) y
// Enter data: 7
// Element inserted successfully! 
// Do you want to enter more data? (y/n) n

// Preorder traversal using recursion
// 5 3 8 7 
// Preorder traversal using iteration
// 5 3 8 7 


<|start_filename|>C-Sharp/other/prime_factor_sieve.cs<|end_filename|>
/* Prime Factorization using Sieve */

using System; 
using System.Collections; 
  
class PFS
{ 
    static int MAX = 100001; 
    static int[] small_pf = new int[MAX]; 
      
    static void prime_sieve() 
    { 
        small_pf[1] = 1; 
        for (int i = 2; i < MAX; i++) 
            small_pf[i] = i; 
      
        for (int i = 4; i < MAX; i += 2) 
            small_pf[i] = 2; 
      
        for (int i = 3; i * i < MAX; i++) 
        { 
            if (small_pf[i] == i) 
            { 
                for (int j = i * i; j < MAX; j += i) 
                    if (small_pf[j] == j) 
                        small_pf[j] = i; 
            } 
        } 
    } 

    static ArrayList get_Factor(int x) 
    { 
        ArrayList r = new ArrayList(); 
        while (x != 1) 
        { 
            r.Add(small_pf[x]); 
            x = x / small_pf[x]; 
        } 
        return r; 
    } 
      
    public static void Main() 
    { 
        prime_sieve(); 
        Console.WriteLine("Enter a value:");
        int val = Convert.ToInt32(Console.ReadLine());
        
        Console.WriteLine("Prime factors are:"); 
        ArrayList p = get_Factor(val); 
      
        for (int i = 0; i < p.Count; i++) 
            Console.Write(p[i] + " "); 
        Console.WriteLine(""); 
    } 
} 
  
/* OUTPUT

Enter a value:                                                                                                                                
562                                                                                                                                           
Prime factors are:                                                                                                                            
2 281

*/

<|start_filename|>C/sort/pigeon_hole_sort.c<|end_filename|>
// C program to implement Pigeon Hole  Sort
#include <stdio.h>

struct MaxAndMin
{
    int maximum;
    int minimum;
};

//To find the Maximum and Minimum elements in an array with minimum comparisons
struct MaxAndMin find_max_min_elements(int arr[], int n)
{
    struct MaxAndMin pair;
    int i;
    //If there is only one element
    if (n % 2 == 1)
    {
        pair.minimum = arr[0];
        pair.maximum = arr[0];
        i = 1;
    }
    else //Else If there is more than one element
    {
        if (arr[0] > arr[1])
        {
            pair.minimum = arr[1];
            pair.maximum = arr[0];
        }
        else
        {
            pair.minimum = arr[0];
            pair.maximum = arr[1];
        }
        i = 2;
    }

    while (i < n - 1)
    {
        if (arr[i] > arr[i + 1])
        {
            if (arr[i] > pair.maximum)
                pair.maximum = arr[i];

            if (arr[i + 1] < pair.minimum)
                pair.minimum = arr[i + 1];
        }
        else
        {
            if (arr[i + 1] > pair.maximum)
                pair.maximum = arr[i + 1];

            if (arr[i] < pair.minimum)
                pair.minimum = arr[i];
        }
        i = i + 2;
    }
    return pair;
}

// Pigeon hole sort
void pigeon_hole_sort(int arr[], int n)
{
    struct MaxAndMin pair = find_max_min_elements(arr, n);

    // Find statistical range of the given array
    int range = pair.maximum - pair.minimum + 1;

    // Declare an array with the size of the range.
    int holes[range];

    //Initialize the new array with value 0.
    for(int i = 0;i < range;i++)
    {
        holes[i] = 0;
    }

    //Filling the 'holes' array with the input array values
    for (int j = 0; j < n; j++)
        holes[arr[j] - pair.minimum]++;

    // Put the elements back into the array in ascending occurence order.
    int j = 0;
    for (int i = 0; i < range; i++)
        while (holes[i]-- > 0)
        {
            arr[j] = i + pair.minimum;
            j++;
        }
}

int main()
{
    int n;
    printf( "\nHow many numbers do you want to sort? ");
    scanf("%d", &n);
    int arr[n];

    if (n <= 0)
    {
        printf( "The array is Empty!!!");
        return 0;
    }
    // Input the numbers to sort
    printf( "Enter the numbers: ");
    for (int i = 0; i < n; i++)
        scanf("%d", &arr[i]);

    //Call the sort function
    pigeon_hole_sort(arr, n);

    printf( "The numbers in sorted order is: ");
    // Print the sorted array
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");

    return 0;
}

/*
Time Complexity: O(n+range), where 'range' is statistical range of the given input values
Space Complexity: O(n)

SAMPLE INPUT AND OUTPUT

SAMPLE 1

How many numbers do you want to sort? 5
Enter the numbers: 1 3 5 2 4
The numbers in sorted order is:  1  2  3  4  5

SAMPLE 2

How many numbers do you want to sort? 0
The array is Empty!!!

*/


<|start_filename|>C/sort/oddevensort.c<|end_filename|>
/*   C Program to Implement Oddeven Sort */

#include <stdio.h>
#define MAX 7
 
void swap(int *,int *);
void oddeven_sort(int *);
 
void main()
{
    int a[MAX], i;
 
    printf("enter the elements into the matrix :");
    for (i = 0;i < MAX;i++)
    {
        scanf("%d", &a[i]);
    }
    printf("sorted elements are :\n");
    oddeven_sort(a);
    for (i = 0;i < MAX;i++)
    {
        printf(" %d", a[i]);
    }
}
 
/* swaps the elements */
void swap(int * x, int * y)
{
    int temp;
 
    temp = *x;
    *x = *y;
    *y = temp; 
}
 
/* sorts the array using oddeven algorithm */
void oddeven_sort(int * x)
{
    int sort = 0, i;
 
    while (!sort)
    {
        sort = 1;
        for (i = 1;i < MAX;i += 2)
        {
            if (x[i] > x[i+1])
            {
                swap(&x[i], &x[i+1]);
                sort = 0;
            }
        }
        for (i = 0;i < MAX - 1;i += 2)
        {
            if (x[i] > x[i + 1])
            {
                swap(&x[i], &x[i + 1]);
                sort = 0;
            }
        }
    }
}


<|start_filename|>C-Plus-Plus/ds/AVL_Tree_or_not.cpp<|end_filename|>
/*
Introduction 
Given a Binary Search Tree ,Check if its a AVL Tree or not
A BST is said to be a AVL Tree 
- if difference between heights of its subtrees is atmost 1


Argument/Return Type
Input of total no.of nodes is taken
Input of key values of nodes of tree are taken
*/

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

//Define Node as structure
struct Node 
{
    int key;
    Node* left;
    Node* right;
};
 
/* Function to create a node with 'value' as the data stored in it. 
 Both the children of this new Node are initially null. */
struct Node* newNode(int value)
{
    Node* n = new Node;
    n->key = value;
    n->left = NULL;
    n->right = NULL;
    return n;
}

// Function to insert a node with given value to the root
struct Node* insert(struct Node* root,int element) 
{
    /*If the root is NULL , create a node with given element and assign it to root
    else if the root itself is the node with given data , return 
    else recursively insert it in one of the subtrees accordingly */
    if(root==NULL)
        root = newNode(element);
    else if(root->key < element)
        root->right = insert(root->right,element);
    else if(root->key > element)
        root->left = insert(root->left,element);
    
    return root;
}

// Function to calculate height of a given Tree recursively
int Height(struct Node* root)
{
    /* If root is a NULL node return 0
    else recursively calculate heights of subtrees and get height of the root */
    if(root==NULL)
      return 0;
    else
      return 1 + max( Height(root->left) , Height(root->right) );
}

//Function to determine whether given Tree is AVL Tree or not
bool IsAVLTree(struct Node* root)
{
    /* If heights of subtrees differ atmost by 1 , return True
     else return False */
    if(abs( Height(root->left) - Height(root->right) ) <= 1)
      return true;
    else
      return false;
}

// Driver code
int main()
{
    int n;
    cout<<"Enter total no.of nodes of the input Tree ( including NULL nodes ) : ";
    cin>>n;

    //create a null node  and initialise it as a NULL node
    struct Node* root;
    root=NULL;
    
    cout<<"Enter value of each node of the Tree , with head as the first value ( if a node is NULL , enter -1 ) with spaces"<<endl;
    for(int i=0;i<n;i++)
    {
        int data;
        cin>>data; 
        //take input of data of each node and insert it in the root
        root = insert(root,data);
    }

    //Call the function and print the result
    if(IsAVLTree(root))
        cout<<"Hence given BST is a AVL Tree";
    else
        cout<<"Hence given BST is not a AVL Tree";

    return 0; 
}
    
/*
Input:
0 <= node->key < 1000000000
While entering node values of the tree , 
value of the head of the tree should be enetered first

Sample Test Case 1  
Input Binary Tree 1:                    
            11                                                             
          /     \                                             
         2      20                                      
        / \                              
       1   5                                
           /
          4
Input Format : 
Example :
Enter total no.of nodes of the input Tree ( including NULL nodes ) : 6
Enter value of each node of the Tree , with head as the first value ( if a node is NULL , enter -1 ) with spaces
11 2 20 1 5 4

Output Format :
Example : ( Output to the above input example ) 
Hence given BST is not a AVL Tree

Time/Space Complexity
Time Complexity : O(n) 
   Where n is the no.of nodes ofthe tree
Space Complexity : O(h) 
   Where h is the height of the tree
*/


<|start_filename|>Java/ds/SparseMatrix.java<|end_filename|>
import java.util.Scanner;
// Java program for Sparse Matrix Representation using Array 

class SparseMatrix {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System. in );
    System.out.println("Input :");
    System.out.println("Enter the row size");
    int row = sc.nextInt();
    System.out.println("Enter the column size");
    int colmn = sc.nextInt();
    int sparseMatrix[][] = new int[row][colmn];
    System.out.println("Enter the element of 2-D matrix");
    for (int loop = 0; loop < row; loop++) {
      for (int inloop = 0; inloop < colmn; inloop++) {
        sparseMatrix[loop][inloop] = sc.nextInt();
      }
    }
    int count = 0;
    for (int loop = 0; loop < row; loop++) {
      for (int inloop = 0; inloop < colmn; inloop++) {
        if (sparseMatrix[loop][inloop] != 0) {
          count++;
        }
      }
    }
    /* number of columns in Triplet Matrix(count) must be 
         equal to number of non - zero elements in sparseMatrix */
    int tripletMatrix[][] = new int[count][3];
    /* Making of new matrix called TripletMatrix(row,column,value)
          all the non-zero elements are stored in revised Sparse Matrix */
    int index = 0;
    for (int loop = 0; loop < row; loop++) {
      for (int inloop = 0; inloop < colmn; inloop++) {
        if (sparseMatrix[loop][inloop] != 0) {
          tripletMatrix[index][0] = loop;
          tripletMatrix[index][1] = inloop;
          tripletMatrix[index][2] = sparseMatrix[loop][inloop];
          index++;
        }
      }
    }
    System.out.println("Output :");
    System.out.println("Triplet Matrix Representation :-");
    System.out.println("rows columns values");
    for (int loop = 0; loop < count; loop++) {
      for (int inloop = 0; inloop < 3; inloop++) {
        System.out.print(tripletMatrix[loop][inloop]);
      }
      System.out.println();
    }
  }
}
/*
  Input :
  Enter the row size 
  4
  Enter the column size
  5
  Enter the elements of 2-D matrix
  0 0 1 5 0
  0 0 6 0 0
  7 0 0 0 1
  0 8 0 0 0
  Output:
  Triplet Matrix Representation :-
  rows  columns values
  0     2       1
  0     3       5
  1     2       6
  2     0       7
  2     4       1
  3     1       8
 */
/*
  Time Complexity:O(noOfTerms*noOfcolumn)
  Space Complexity:O(1)
 */

<|start_filename|>C/ds/Open_hashing.c<|end_filename|>
/*
___Implement Open Hashing___
Hashing is an important data structure that is used to map a given value with a particular index
for faster access of elements. But sometimes more than one value gets mapped with a particular index.
This can be resolved using open hashing.
In open hashing, keys are stored in linked lists attached to cells of a hash table.
*/

#include<stdio.h>
#include<stdlib.h>
#define SIZE 10
struct node
{
    int data;
    struct node *next;
};
//array of pointers
struct node *head[SIZE]={NULL},*c;
void openDisplay();
void openInsert();
void openSearch();
void main()
{
    //prints the hash function used in the program
    printf("\nHash function : h(k)=k (mod 10)+1");
    int size,i,temp,ch=0;
    while(ch!=4)
    {
        printf("\n");
        printf("1.Insert\n2.Search\n3.Display\n4.Exit\n");
        printf("Enter your choice : ");
        scanf("%d",&ch);
        switch(ch)
        {
        case 1:
           openInsert();
           break;
        case 2:
           openSearch();
           break;
        case 3:
           openDisplay();
           break;
        case 4:
           break;
        default:
            printf("Invalid choice\n");
        }
    }
}

/*
This function inserts elements into the hash table.
Duplication is not allowed in hash table.
We use an array of linked list to store the elements.
*/
void openInsert()
{
    int i,j,key;
    printf("Enter the element  :  ");
    scanf("%d",&key);
    i=key%SIZE+1;
    for(c=head[i];c!=NULL;c=c->next)
        {
            if(c->data==key)  //checks for duplication
            {
                printf("Duplication\n");
                return;
            }
        }
    //dynamically allocates memory for the node
    struct node *newnode=(struct node*)malloc(sizeof(struct node));
    newnode->data=key;
    newnode->next=NULL;
    //if head is empty then element made as head
    if(head[i]==NULL)
        head[i]=newnode;
    else
    {
        c=head[i];
        while(c->next!=NULL)
            c=c->next;
        c->next=newnode;
    }
}

/*
This function search for an element in the hash table.
The index corresponding to that particular value is found.
Search is made in the linked list whose head is at that index of the array.
*/
void openSearch()
{
    int key,index;
    printf("Enter the element  :  ");
    scanf("%d",&key);
    index=key%SIZE+1;  //finds the index of the key value
    //checks whether the head of the linked list is empty or not
    if(head[index]==NULL)  
        printf("Element not found\n");
    else
    {
        //traverse through the linked list
        for(c=head[index];c!=NULL;c=c->next)
        {
            if(c->data==key)  
            {
                printf("%d found at index %d\n",key,index);
                break;
            }
        }
        if(c==NULL)
            printf("Element not found\n");
    }
}

/*
This function displays elements in the hash table.
If no element is present the it displays "--" in the column value.
*/
void openDisplay()
{
    int i;
    printf("Index\tValue\n");
    printf("---------------\n");
    for(i=1;i<=SIZE;i++)
    {
        if(head[i]==NULL)
        {
            printf("%d\t--",i);
            printf("\n");
            continue;
        }
        else
        {
            c=head[i];
            printf("%d\t%d",i,c->data);
            c=c->next;
            for(;c!=NULL;c=c->next)
                printf("->%d",c->data);
        }
        printf("\n");
    }
}

/*
Sample Input and Output:
Hash function : h(k)=k (mod 10)+1
1.Insert
2.Search
3.Display
4.Exit
Enter your choice
1
Enter the element  :  44

1.Insert
2.Search
3.Display
4.Exit
Enter your choice
1
Enter the element  :  14

1.Insert
2.Search
3.Display
4.Exit
Enter your choice : 1
Enter the element  :  12

1.Insert
2.Search
3.Display
4.Exit
Enter your choice : 1
Enter the element  :  89

1.Insert
2.Search
3.Display
4.Exit
Enter your choice : 1
Enter the element  :  90

1.Insert
2.Search
3.Display
4.Exit
Enter your choice : 1
Enter the element  :  11

1.Insert
2.Search
3.Display
4.Exit
Enter your choice : 3
Index   Key
---------------
1       90
2       11
3       12
4        --
5        44->14
6        --
7        --
8        --
9        --
10      89

Time complexity :
Insertion - O(1)
Deletion - O(1)
*/


<|start_filename|>Kotlin/sort/BubbleSort/src/BubbleSort.kt<|end_filename|>
fun bubbleSort(list: MutableList<Int>): List<Int>{
    // taking a note of the lists length
    val length = list.size - 1

    // the first loop runs for the number of items there are in the list
    for (i in 0 until length) {
        // a swapped variable which tracks if one of the variables was swapped
        // in one iteration
        var swapped =  false

        // inner loop going from first element till the last element
        // in each round we have the last element as the greatest number
        // so next round has one less element
        // i.e equal to the number of iteration we are in currently.
        for (j in 0 until (length - i)) {
            // if current element is bigger than next element
            if (list[j] > list[j + 1]) {
                // do the swap
                list[j + 1] = list[j].also { list[j] = list[j + 1] }
                // take a note of that swap
                swapped = true
            }
        }
        // check if any swaps happened in this iteration. if there aren't any
        // swaps leave the function cause we have a sorted list.
        if (!swapped){
            return list
        }
    }
    return list
}

fun main() {
    val list = listOf(11,22,33,45,34,53,27,36)
    println("unsorted list is $list")
    val sorted = bubbleSort(list.toMutableList());
    println("sorted list is $sorted")
}

<|start_filename|>Julia/cp/GCD.jl<|end_filename|>
#= Finding the Greatest Common Divisor of 2 numbers using the Euclidean
Formula to lessen the time complexity.
=#

## Function

function GCD(a, b)
    if (a == 0)
        return b
    end
    if (b == 0)
        return a
    end
    if (a < b)
        a, b = b, a
    end
    ans = a % b
    while (ans != 0)
        a = b
        b = ans
        ans = a % b
    end
    return b
end

## Input

a = readline()
a = parse(Int64, a)
b = readline()
b = parse(Int64, b)

## Calling the function

GCD(a, b)

#=
Sample Test case:
Input: 
    a = 1001  b = 2352
Output:
    7
Time complexity: O( log (min(a,b)) )
=#


<|start_filename|>C-Plus-Plus/graphs/FloodFill.cpp<|end_filename|>
/*
Flood Fill Algorithm determines the area connected to the given node in a multidimensional array.

Problem Statement: To fill connected, similarly-coloured areas with a different color.

Idea (DFS): Start from the current source node and replace its color with the replacement color
and recursively explore all valid neighbours and replace their color as well.

Idea(BFS): To apply BFS and process all 8 adjacent pixels of the current one and enqueue each
valid pixel which has the same color as that of the previous one.

Input for the algorithm: matrix, a start node, target color, replacement color.

Time Complexity: O(M.N)
*/

#include <bits/stdc++.h>
#define M 10
#define N 10
using namespace std;

//for processing 8 directions
int row[] = {-1, -1, -1, 0, 0, 1, 1, 1};
int col[] = {-1, 0, 1, -1, 1, -1, 0, 1};

//to check the valid neighbours
bool safe(char matrix[M][N], int start_x, int start_y, char target)
{
    return (start_x >= 0 && start_y >= 0 && start_x < M && start_y < N && matrix[start_x][start_y] == target);
}

void floodFillDFS(char matrix[M][N], int start_x, int start_y, char target, char replacement)
{
    queue<pair<int, int>> q;
    q.push({start_x, start_y});

    while (!q.empty())
    {
        pair<int, int> node = q.front();
        q.pop();
        int x = node.first;
        int y = node.second;
        matrix[x][y] = replacement;
        //Processing all 8 dircetions
        for (int k = 0; k < 8; k++)
        {
            if (safe(matrix, x + row[k], y + col[k], target))
            {
                q.push({x + row[k], y + col[k]});
            }
        }
    }
}

void floodFillBFS(char matrix[M][N], int start_x, int start_y, char target, char replacement)
{
    //replacing color of current cell
    matrix[start_x][start_y] = replacement;
    //processing all 8 neighbours recursively
    for (int k = 0; k < 8; k++)
    {
        if (safe(matrix, start_x + row[k], start_y + col[k], target))
        {
            floodFillBFS(matrix, start_x + row[k], start_y + col[k], target, replacement);
        }
    }
}

int main()
{
    char matrix[M][N];
    //input for matrix
    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; j++)
        {
            cin >> matrix[i][j];
        }
    }
    //starting node
    int start_x, start_y;
    cin >> start_x >> start_y;
    //color to be replaced
    char target_color;
    cin >> target_color;
    //color to be filled in place of target
    char replacement_color;
    cin >> replacement_color;

    floodFillDFS(matrix, start_x, start_y, target_color, replacement_color);

    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; j++)
        {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }

    floodFillBFS(matrix, start_x, start_y, target_color, replacement_color);

    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; j++)
        {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
}

/*
Sample input:
Y Y Y G G G G G G G
Y Y Y Y Y Y G X X X
G G G G G G G X X X
W W W W W G G G G X
W R R R R R G X X X
W W W R R G G X X X
W B W R R R R R R X
W B B B B R R X X X
W B B X B B B B X X
W B B X X X X X X X
3 9
X
C

Sample output:
Y Y Y G G G G G G G
Y Y Y Y Y Y G C C C
G G G G G G G C C C
W W W W W G G G G C
W R R R R R G C C C
W W W R R G G C C C
W B W R R R R R R C
W B B B B R R C C C
W B B C B B B B C C
W B B C C C C C C C
*/

<|start_filename|>Go/sort/selection_sort/selectionSort.go<|end_filename|>
// Author: @belikesayantan

package main

import (
	"bufio"
	"errors"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"
	"time"
)

func main() {
	var strArray []string
	var intArray []int

	fmt.Println("Enter an array with spaces")
	reader := bufio.NewReader(os.Stdin)
	arr, err := reader.ReadString('\n')
	if err != nil {
		inputErr := errors.New("something is wrong with your array input")
		log.Fatal(inputErr)
	}
	arr = strings.TrimSpace(arr)
	strArray = strings.Split(arr, " ")

	for _, val := range strArray {
		ele, err := strconv.Atoi(val)
		if err != nil {
			panic(err)
		}
		intArray = append(intArray, ele)
	}

	start := time.Now() // timer starts and records running time of SelectionSort Algorithm
	fmt.Println("Sorted Array is: ", SelectionSort(intArray))
	end := time.Now() // timer stops and recording running time of SelectionSort Algorithm is completed

	fmt.Println("\nRunning Time of SelectionSort Algorithm is: ", end.Sub(start))
}

// SelectionSort Algorithm Time Complexity : O(n^2)
func SelectionSort(arr []int) []int {
	for i := 0; i < len(arr); i++ {
		min := i
		for j := i + 1; j < len(arr); j++ {
			if arr[j] < arr[min] {
				min = j
			}
		}
		if min != i {
			swap(arr, i, min)
		}

	}

	return arr
}

func swap(arr []int, i, j int) {
	temp := arr[i]
	arr[i] = arr[j]
	arr[j] = temp
}

/*
	I/O Sample:

	Sample 1:
	❯ go run selectionSort.go
	Enter an array with spaces
	5 3 2 4 5 84 6 1 54
	Sorted Array is:  [1 2 3 4 5 5 6 54 84]

	Running Time of SelectionSort Algorithm is:  73.83µs


	Sample 2:
	❯ go run selectionSort.go
	Enter an array with spaces
	5 8 6 9 1 3 2 7 4
	Sorted Array is:  [1 2 3 4 5 6 7 8 9]

	Running Time of SelectionSort Algorithm is:  39.509µs



	Time Complexity:
		1. Ω(n^2) in best case
		2. O(n^2) in average case
		3. O(n^2) in worst case

	Space Complexity: O(1) in worst case

*/


<|start_filename|>JavaScript/ds/DoublyLinkedList.js<|end_filename|>
/*

A doubly linked list is a linked data structure that consists of a set of sequentially linked records called nodes. Each node contains three fields: two link fields (references to the previous and to the next node in the sequence of nodes) and one data field. 
The beginning and ending nodes' previous and next links, respectively, point to some kind of terminator, typically a sentinel node or null, to facilitate traversal of the list.

Below, is the implementation of doubly linked list. In this program, user can provide a choice to perform operations on a Doubly Linked List. It is created using a ES6 class syntax. 
prompt & colors are node packages for taking user input and displaying text in different colors respectively. 

*/

const prompt = require("prompt-sync")({ sigint: true });
const colors = require("colors");

// Setting the Color schema
colors.setTheme({
  display: "green",
  insert: "white",
  delete: "red",
  leave: "yellow",
  end: "rainbow",
  wrong: "america",
});

// Creating the node class to create nodes
class Node {
  constructor(value, next = null, prev = null) {
    this.value = value, 
    this.next = next, 
    this.prev = prev
  }
}

// Creating Doubly Linked List class to perform operations 
class DoublyLinkedList {
  constructor(value) {
    this.head = {
      value: value,
      prev: null,
      next: null,
    };

    this.tail = this.head;
    this.length = 1;
  }

   // Looping to a given index in doubly Linked List
  traverseToIndex(index) {
    let counter = 1;
    let currentNode = this.head;

    while (counter !== index) {
      currentNode = currentNode.next;
      counter++;
    }

    return currentNode;
  }

  // Case : The very "first node" insertion in doubly linked list
  firstNode(value) {
    let newNode = new Node(value);

    this.head = newNode;
    this.head.next = null;
    this.head.prev = null;
    this.tail = this.head;

    this.length++;
    return this;
  }

  // Appending (at the end) node in doubly linked list
  append(value) {
    if (!this.head) return this.firstNode(value);
    const newNode = new Node(value);

    this.tail.next = newNode;
    newNode.prev = this.tail;

    this.tail = newNode;
    this.length++;
    return this;
  }

  // Prepending ( at the beginning ) of doubly linked list
  prepend(value) {
    if (!this.head) return this.firstNode(value);
    const newNode = new Node(value);

    this.head.prev = newNode;
    newNode.next = this.head;
    this.head = newNode;
    this.length++;

    return this;
  }

  // Inserting node at a given position in doubly linked list
  insert(index, value) {
    if (index === 1) return this.prepend(value);
    if (index > this.length) return this.append(value);

    const newNode = new Node(value);
    if (index === this.length) {
      newNode.prev = this.tail.prev;
      this.tail.prev.next = newNode;
      this.tail.prev = newNode;
      newNode.next = this.tail;
      this.length++;

      return this;
    }

    let currentNode = this.traverseToIndex(index - 1);

    newNode.next = currentNode.next;
    currentNode.next.prev = newNode;
    newNode.prev = currentNode;
    currentNode.next = newNode;

    this.length++;
    return this;
  }

  // Removing the element node form doubly linked list
  remove(index) {
    if (this.length === 1) { // If length of doublyLL is one
      this.head = null;
      this.tail = this.head;
    } else if (index === 1) { // If entered position is one 
      this.head = this.head.next;
      this.head.prev = null;
    } else if (index === this.length) { // If entered postion is equal to the length of doublyLL
      this.tail = this.tail.prev;
      this.tail.next = null;
    } else { // for the rest of cases
      //Traverse to that particular index of element 
      let currentNode = this.traverseToIndex(index - 1);
      currentNode.next.next.prev = currentNode;
      currentNode.next = currentNode.next.next;
    }

    this.length--;
    return this;
  }

  // Reverse the doubly linked list
  reverse() {
    // if only one node is present
    if (!this.head.next) {
      return this.head;
    }

    let first = this.head;
    this.tail = this.head;
    let second = first.next;

    // Start looping & changing the prev & next pointer of nodes
    while (second) {
      const temp = second.next;
      second.prev = second.next;
      second.next = first;
      first = second;
      second = temp;
    }

    this.head.prev = this.head.next;
    this.head.next = null;
    this.head = first;
  }

  // Displaying all the nodes of doubly linked list
  printList() {
    let array = [];
    let currentNode = this.head;

    while (currentNode !== null) {
      array.push(currentNode.value);
      currentNode = currentNode.next;
    }

    return array;
  }

}

// Instantiating the doubly Linked List class
const myDoublyLinkedList = new DoublyLinkedList(22);

let choice = 0;
let value, index;

// Asking user input for performing operations on doubly Linked List
do {
  console.log("\nWelcome to the Doubly Linked List Show");
  console.log("Follow the instructions to get in the show");
  console.log("0. To exit without doing anything".yellow);
  console.log("1. Display the Doubly Linked List".display);
  console.log("2. Append element in the Doubly Linked List".insert);
  console.log("3. Prepend element in the Doubly Linked List".insert);
  console.log("4. Insert anywhere in between the Doubly Linked List".insert);
  console.log("5. Delete element from Doubly Linked List".delete);
  console.log("6. Reverse the Doubly Linked List".display);

  choice = +prompt("Enter your choice - ");

  switch (choice) {
    case 0:
      console.log("Hmm, matter of choice!\n".rainbow);
      return;

    case 1:
      console.log("Doubly Linked List - ", myDoublyLinkedList.printList());
      break;

    case 2:
      value = +prompt("Enter Value to Append element - ");
      myDoublyLinkedList.append(value);
      console.log(
        "After Append Doubly Linked List - ",
        myDoublyLinkedList.printList()
      );
      break;

    case 3:
      value = +prompt("Enter Value to Prepend element - ");
      myDoublyLinkedList.prepend(value);
      console.log(
        "After Prepend Doubly Linked List - ",
        myDoublyLinkedList.printList()
      );
      break;

    case 4:
      value = +prompt("Enter Value to Insert element - ");
      index = +prompt("Enter Position to Insert element - ");

      if (index <= 0)
        return console.log("You know this is wrong, Bbye!\n".wrong);
      
      myDoublyLinkedList.insert(index, value);
      console.log(
        "After Insertion Doubly Linked List - ",
        myDoublyLinkedList.printList()
      );
      break;

    case 5:
      if (myDoublyLinkedList.length === 0) {
        return console.log("404, you can't remove anything from void".wrong);
      }
  
      index = +prompt("Enter position of element - ");
      if (index <= 0 || index > myDoublyLinkedList.length)
        return console.log("You know this is wrong, Bbye!\n".wrong);
  
      myDoublyLinkedList.remove(index);
      console.log( "After Deletion Doubly Linked List - ", myDoublyLinkedList.printList());
      break;

    case 6:
      if (myDoublyLinkedList.length === 0) {
        return console.log("404, well DLL is empty".wrong);
      }
  
      myDoublyLinkedList.reverse();
      console.log("Reversed Doubly Linked List - ", myDoublyLinkedList.printList());
      break;

    default:
      console.log("You know this is wrong, Bbye!\n".wrong);
      return;
  }
} while (choice !== 0);


// Sample I/O of the above program -

/*

> node DoublyLinkedList

Welcome to the Doubly Linked List Show
Follow the instructions to get in the show
0. To exit without doing anything
1. Display the Doubly Linked List
2. Append element in the Doubly Linked List
3. Prepend element in the Doubly Linked List
4. Insert anywhere in between the Doubly Linked List
5. Delete element from Doubly Linked List
6. Reverse the Doubly Linked List
Enter your choice - 1
Doubly Linked List -  [ 22 ]

Welcome to the Doubly Linked List Show
Follow the instructions to get in the show
0. To exit without doing anything
1. Display the Doubly Linked List
2. Append element in the Doubly Linked List
3. Prepend element in the Doubly Linked List
4. Insert anywhere in between the Doubly Linked List
5. Delete element from Doubly Linked List
Enter your choice - 3
Enter Value to Prepend element - 23
6. Reverse the Doubly Linked List
After Prepend Doubly Linked List -  [ 23, 22 ]

Welcome to the Doubly Linked List Show
Follow the instructions to get in the show
0. To exit without doing anything
1. Display the Doubly Linked List
2. Append element in the Doubly Linked List
3. Prepend element in the Doubly Linked List
4. Insert anywhere in between the Doubly Linked List
5. Delete element from Doubly Linked List
Enter your choice - 5
Enter position of element - 2
6. Reverse the Doubly Linked List
After Deletion Doubly Linked List -  [ 23 ]

( add few elements > 21, 45, 62, 12, 40 )

Enter your choice - 1
Doubly Linked List - [23, 21, 45, 62, 12, 40]

Enter your choice - 6
Reversed Doubly Linked List - [40, 12, 62, 45, 21, 23]


*/



<|start_filename|>C-Plus-Plus/math/Sum_of_digits.cpp<|end_filename|>
// C++ PROGRAM TO COMPUTE THE SUM OF DIGITS OF A NUMBER

#include <iostream>
using namespace std;

// Function to calculate the sum of digits
int sum_of_digits(int N)
{
    int sum = 0;
    while(N != 0)
    {
        // Adding the last digit of the number to the sum
        int rem = N % 10;
        sum += rem;
        // Removing the last digit
        N = N / 10;
    }
    return sum;
}

int main()
{
    int N;
    cout << "Enter any integer:";
    cin >> N;
    
    cout << "Sum of the digits of a number:" << sum_of_digits(N) << endl;
    return 0;
}

/*
Example 1:
Input : N = 453
Output: 12
Explanation: Sum of digits of number = (4+5+3) = 12

Example 2:
Input : N = 101
Output: 2
Explanation: Sum of digits of number = (1+0+1) = 2
*/


<|start_filename|>Java/sort/RadixSort.java<|end_filename|>
/** 
Radix sort is based on counting sort
This sort is used for non-negative elements
Assuming the range is fixed, as int capacity
is limited in any language, this sort takes

MAX_INT contains 10 decimal values
If range is not fixed, this sort takes O(kn) time
where k is #decimal places in the number
This works because of the nature of counting sort
Counting sort is a stable sort
**/

public class RadixSort {
    // required variables
	private static int M = 10, K = 10;
	private static void counting_sort(int[] arr, int  n, int p) {
		int element = (int)Math.pow(10, p), i;
		int divs = element / 10;
		// counting array
		int[] count = new int[M];
		for(i = 0; i < M; i++)
			count[i] = 0;
		for(i = 0; i < n; i++)
			count[(arr[i] % element) / divs] ++;
		for(i = 1; i < M; i++)
			count[i] += count[i-1];
		int[] op = new int[n];
		for(i = n-1; i >= 0; i--) {
		    op[count[(arr[i] % element) / divs] - 1] = arr[i];
		    count[(arr[i] % element) / divs] --;
		}
		// copying the array back
		for(i = 0; i < n; i++)
			arr[i] = op[i];
	}

	private static void radix_sort(int[] arr, int n) {
		// apply counting sort for all decimal places
		for(int i = 1; i <= K; i++)
			counting_sort(arr, n, i);
	}

	public static void main(String[] args) {
		int n, i;
		Scanner sc= new Scanner(System.in);
		n = sc.nextInt();
		int[] arr = new int[n];
		// taking ip
		for(i = 0; i < n; i++)
			arr[i] = sc.nextInt();
		// perform the sort
		radix_sort(arr, n);
		for(i = 0; i < n; i++)
			System.out.print(arr[i] + " ");
		System.out.println();
	}
}

/**
Input : 
8
175 45 75 90 802 24 2 66
Output :
2 24 45 66 75 90 175 802

Time complexity : O(n)
Space complexity : O(n)
**/


<|start_filename|>Java/cp/Longest_Common_Prefix.java<|end_filename|>
import java.util.*;
class Longest_Common_Prefix{
    public static String LongestCommonPrefixFn(String[] strs) {
        if(strs.length==0){
            return "";
        }
        String st = strs[0];
        for(int i=1; i<strs.length; i++){
            while(strs[i].indexOf(st)!=0){
                st = st.substring(0, st.length()-1);
            }
        }
        return st;
    }
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter strings");
        String st = sc.nextLine();
        String[] arrOfStr = st.split(" ");
        System.out.println("Longest Common Prefix : "+LongestCommonPrefixFn(arrOfStr));
    }
}

/*sample input and output:

Enter strings
encourage encoder enchant

Longest Common Prefix : enc

Complexities
Time: O(n^2)
Space: O(n)*/


<|start_filename|>C-Plus-Plus/ds/Detet_Cycle_In_LinkedList.cpp<|end_filename|>
/*
    Author: <NAME> (@Sakshi0401)

    A Linked List is a linear data structure which includes a series of connected nodes. Each node stores the data and the address of the next node.
    If any node is visited more than once while traversing the list then we can say that it contains cycle/loop.
     Example:
                1 -> 2 -> 3
                    ^     |
                    |     v
                    5 <-  4   
     Output:
            true

    Method:In this method we will traverse the linkedlist using two pointers is slow and fast. 
    Move the slow pointer by one position and fast pointer by two positions.
    If these two pointers meet together at any point at same node then we can say that there is loop/cycle inside linkedlist. 
*/

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

/* Link list node */
class Node
{
public:
    int data;
    Node *next;
};

void push_node(Node **head_ref, int new_data)
{
    /* allocate node */
    Node *new_node = new Node();

    /* put in the data */
    new_node->data = new_data;

    /* link the old list off the new node */
    new_node->next = (*head_ref);

    /* move the head to point to the new node */
    (*head_ref) = new_node;
}

int detectLoop(Node *list)
{
    Node *slow_p = list, *fast_p = list;

    while (slow_p && fast_p && fast_p->next)
    {
        slow_p = slow_p->next;
        fast_p = fast_p->next->next;
        if (slow_p == fast_p)
        {
            return 1;
        }
    }
    return 0;
}

/* Driver code*/
int main()
{
    /* Start with the empty list */
    Node *head = NULL;
    int n = 0;
    cout << "Enter size of linked list" << endl;
    cin >> n;
    int i;
    int d;
    cout << "Enter the elements of linked list" << endl;
    for (int i = 0; i < n; i++)
    {
        cin >> d;
        push_node(&head, d);
    }

    /* Create a loop for testing */
    head->next->next->next->next = head;
    if (detectLoop(head))
        cout << "true";
    else
        cout << "false";
    return 0;
}

/*
 Time complexity: O(n)
 Space complexity: O(1)
 
 Input :
 Enter size of linked list
 5
 Enter the elements of linked list
 45 24 32 72 54

 Output :
 true
*/


<|start_filename|>C-Plus-Plus/cp/tkt_auction.cpp<|end_filename|>
/*
Author: @Suvraneel
	<NAME>

Problem Statement:
* There are n concert tickets available, each with a certain price. Then, m customers arrive, one after another.
* Each customer announces the maximum price he or she is willing to pay for a ticket (like an auction)
* They will get a ticket with the nearest possible price such that it does not exceed the maximum price.

Input:
* The first line contains integers n and m: the number of tickets and the number of customers.
* The next line contains n integers h1,h2,…,hn: the price of each ticket.
* The last line contains m integers t1,t2,…,tm: the maximum price for each customer.

Output:
For each customer, the price that they'll pay for their ticket. Same ticket can't be purchased again.
If a customer cannot get any ticket, print −1.

Constraints:
*   1   ≤   n,m    ≤2⋅105
*   1   ≤  hi,ti   ≤109
*/


#include <iostream>
//For cin and cout
using namespace std;

//Swap function --> simply exchanges the values of inputs
void swap(int *xp, int *yp) 
{ 
    int temp = *xp; 
    *xp = *yp; 
    *yp = temp; 
} 

int partition(int array[], int lo, int hi)
{
    int i = (lo - 1);
    // Select the pivot element
    int pivot = array[hi];
    //Traverses the array - whenever an element < pivot occurs, swap it with (i+1)th element 
    //This leads to elements < pivot on the left & elements > pivot on the right wrt the pivot
    for (int j = lo; j < hi; j++) {
        if (array[j] <= pivot) {
            i++;
            swap(&array[i], &array[j]);
        }
    }
    //Place the pivot element at i+1 (between smaller and larger elements)
    swap(&array[i + 1], &array[hi]);
    //Returns the pivot position
    return (i + 1);
}

void quickSort(int array[], int lo, int hi) {
    //If starting index crosses end index, then there're no elements to sort further, thus return
    if( lo >= hi ){
        return;
    }
    // Select pivot position and put all the elements smaller 
    // than pivot on left and greater than pivot on right
    int pivot = partition(array, lo, hi);
    // Sort the elements on the left of pivot
    quickSort(array, lo, pivot - 1);
    // Sort the elements on the right of pivot
    quickSort(array, pivot + 1, hi);
}
  
//Main driver program
int main() {
    //tkt = no. of tickets; cust = no. of customers
    int tkt, cust, i, j;
    //implies initially no customer had any ticket
    int sold = -1;
    cin >> tkt >> cust;
    int price[tkt], bid[cust];
    for (j = 0; j < tkt; j++)
    {
        //accepts price of each ticket
        cin >> price[j];                       
    }
    for (i = 0; i < cust; i++)
    {
        //accepts maximum bid by each customer
        cin >> bid[i];                       
    }
    //calls sorting algorithm on ticket price array
    quickSort(price, 0, tkt-1);
    //loop for considering each customer
    for ( i = 0; i < cust; i++)
    {
	//loop for examining each ticket starting from expensive so as to confirm maximum bid
        for ( j = tkt-1; j >= 0; j--)            
        {
	    //for each ticket sold
            if (bid[i]>=price[j])
            {
		//track successful bids
                sold = price[j];
                //set the price as max integer possible so that noone else can buy the same ticket
                price[j] = INT_MAX;                                     
                break;
            }
        }
        //output successful bids for each customer
        cout << sold << endl;                  
        //(-1) indicates the customer was unable to acquire a ticket
        //reset the 'sold' parameter for the next ticket
        sold = -1;
    }
    
	return 0;   
}

/*
Time complexity:    Sorting = O(n)          where n = no. of tickets
                    Auction = O(mn)         where m = no. of customer
Space Complexity:   O(n)

Sample Input:
5 3
5 3 7 8 5
4 8 3

Standard Output:
3
8
-1
*/


<|start_filename|>C-Plus-Plus/math/n_queen.cpp<|end_filename|>
//This problem is of placing n queens on n*n chessboard which is solved using backtracking so no two queens can attack each other
// like we place n queens in n*n chessboard in such a way so that no two queens should be placed in same row, same column and same diagonal
#include <iostream>
using namespace std;

// To check whether the curren posotion is safe for placing the queen or not
bool isSafe(int board[][10],int i,int j,int n){
    // To check whether the queen is placed in current column or not
    for(int row=0;row<i;row++){
        if(board[row][j] == 1){
            return false;
        }
    }

    // To check whether the queen is placed in current left diagonal or not
    int x = i;
    int y = j;
    while(x>=0 && y>=0){
        if(board[x][y] == 1){
            return false;
        }
        x--;
        y--;
    }

    // To check whether the queen is placed in current column or not
     x = i;
     y = j;
    while(x>=0 && y<n){
        if(board[x][y] == 1){
            return false;
        }
        x--;
        y++;
    }

    // if we can place our queen in the current cell then return true
    return true;
}

// A recursive function to solve n queen problem
bool solveNqueen(int board[][10], int i, int n){
    //base case
    if(i == n){
        // we have successfully placed all the n queens from row(0 to n)
        // therefore print the board
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                if(board[i][j] == 1){
                    cout<<"1 ";
                }
                else{
                    cout<<"0 ";
                }
            }
            cout<<endl;
        }
        // We are return false here to print all the ways to plave n queens
       cout<<endl<<endl;
       return false;
    }

    // recusive case
    for(int j=0;j<n;j++){
        // we will check whether a given cell is save for placing queen or not
        if(isSafe(board,i,j,n)){
            board[i][j] = 1;  // if safe we will place the queen
            //we will check for next row if the cell placed in current cell is safte
            bool nextQueenPlaced = solveNqueen(board,i+1,n);
            if(nextQueenPlaced){
                return true;
            }
            // it means our assumptio is wrong it is not the right position to place our queen
            board[i][j] = 0;
        }
    }

     // if we have tried all the position in current row then we will return the false
    return false;
}

//Driver code
int main() {
    //n is no. of queens to be placed 
    int n;
    cin>>n;
    int board[10][10] = {0};
    solveNqueen(board,0,n);
    return 0;
}

/*
Input: 4
Output:
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0
time complexity - O(n*n)
space complexity - O(n)
*/


<|start_filename|>C/ds/EvaluationOfPostfixExpression.c<|end_filename|>
/*
A postfix expression is a collection of operators and operands in which the operator is placed after the operands. 
To evaluate a postfix expression using Stack data structure we can use the following steps...
1.Create an empty stack and start scanning the postfix expression from left to right. 
2.If the element is an operand, push it into the stack.
3.If the element is an operator O, pop twice and get A and B respectively. Calculate B operator A and push it back to the stack.
4.When the expression is ended, the value in the stack is the final answer.
*/

#include <stdio.h>
#include <unistd.h>
struct stack
{
    int top;
    float a[50];
}
s;
int EvalPostfix(char postfix[])
{
    float num1,num2,num3;
    int i;
    s.top = -1;
    printf("\n\n Enter the postfix expression: ");
    scanf("%s", postfix);
    for (i = 0; postfix[i] != '\0'; i++)
    {
        switch (postfix[i])
        {
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                s.a[++s.top] = postfix[i] - '0';
                break;
            case '+':
                num1 = s.a[s.top--];
                num2 = s.a[s.top--];
                s.a[++s.top] = num1 + num2;
                break;
            case '-':
                num2 = s.a[s.top--];
                num1 = s.a[s.top--];
                s.a[++s.top] = num1 - num2;
                break;
            case '*':
                num2 = s.a[s.top--];
                num1 = s.a[s.top--];
                s.a[++s.top] = num1 * num2;
                break;
            case '/':
                num2 = s.a[s.top--];
                num1 = s.a[s.top--];
                s.a[++s.top] = num1 / num2;
                break;
        }
    }
}
int main()
{
    char postfix[50];
    EvalPostfix(postfix);
    printf("\n Expression value is %5.2f", s.a[s.top]);
    getchar();
}

/*
Sample Case:
Example 1:
Enter the postfix expression: 56*7+
Expression value is :37.00

Example 2:
Enter the postfix expression: 6523+8*+3+*
Expression value is :288.00
*/


<|start_filename|>C/dp/cutting_a_rod.c<|end_filename|>
// C Program to implement the Cutting a Rod problem
/*  
We are given a rod of length 'n' and the cost of the rod of different length from
1 to n. We need to find the maximum sell price that can be obtained by cutting the rod
at any lengths.
 
This problem can be solved by using Dynamic Programming, 
*/
#include <stdio.h>
#include <limits.h>
//Helper function to find the maximum of two values
int max(int a, int b)
{
    if (a > b)
        return a;
    return b;
}

// We build a dp table in bottom-up manner
int max_sell_price(int n, int cost[])
{
    int dp[n + 1];
    dp[0] = 0;
    for (int i = 1; i <= n; i++)
    {
        int curr_max = INT_MIN;
        for (int j = 0; j < i; j++)
            curr_max = max(curr_max, cost[j] + dp[i - j - 1]);

        // Stores the maximum cost achieved for a rod of length i
        dp[i] = curr_max;
    }

    return dp[n];
}

int main()
{
    int n;
    printf("\nWhat is the length of the rod? ");
    scanf("%d", &n);
    int cost[n], max_price;

    if (n <= 0)
    {
        printf("The given rod length is Invalid!!!");
        return 0;
    }
    // Input the cost of the rod of different length
    printf("Enter the cost of the rod for length 1 to  %d: ", n);
    for (int i = 0; i < n; i++)
        scanf("%d", &cost[i]);

    max_price = max_sell_price(n, cost);

    printf("The maximized sell price of the: ");
    // Print the maximized sell price
    printf("%d ", max_price);
    return 0;
}

/*

Time Complexity- O(n^2), where 'n' is the length of the rod
Space Complexity- O(n)

SAMPLE INPUT AND OUTPUT

SAMPLE 1
What is the length of the rod? 5
Enter the cost of the rod for length 1 to  5: 2 5 7 8 10
The maximized sell price of the: 12 


SAMPLE 2
What is the length of the rod? 0
The given rod length is Invalid!!!

*/


<|start_filename|>C/cryptography/Columnar_Cipher.c<|end_filename|>
/*In Columnar Cipher, we are given a plaintext and a key. The plaintext is written out in rows and the ciphertext
 * is formed by reading out columns one by one according to the order of the key given. Key is converted to its 
 * corresponding numerical(Ex A-0, B-1, C-2, ...... , Z-25). Cipher text is formed by reading the columns corresponding
 * to the lowest numerical value in the key to highest numerical value.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>

//Defining maximum length of plaintext and key
#define MAXLENGTH 100

//Sort function, returns sorted integer array
int* sort(int arr[], int len) {

	//Bubble sort is used here
	for(int i = 0; i < len - 1; i++) {
		for(int j = 0; j < len - 1 - i; j++) {
			if(arr[j] > arr[j + 1]) {
				int temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
	return arr;
}

/*This function returns the corresponding numerical value 
  of the key in the form of an array
*/
int* order(char* key) {

	int length = strlen(key);

	static int order_key[MAXLENGTH];
	
	/*We find the numerical value of each alphabet
	  corresponding to the key*/
	for(int i = 0; i < length; i++) {
		order_key[i] = key[i] - 0;
		order_key[i] -= 65;
	}

	static int temp[MAXLENGTH];

	//Storing the numerical value temporarily
	for(int i = 0; i < length; i++) {
		temp[i] = order_key[i];
	}

	/*Finding the relative numbering of
	  each alphaet in the key*/
	int* sorted;
	sorted = sort(order_key, length);

	static int index[MAXLENGTH];

	for(int i = 0; i < length; i++) {
		for(int j = 0; j < length; j++) {
			if(temp[i] == sorted[j]) {
				index[i] = j+1;
			}
		}
	}
	/*Returning the array containing the numerical
	  value of key in relative order*/
	return index;
}

/*This is the encrypt function that takes
  plaintext and key as input*/
char* encrypt(char* message, char* key) {

	//varible to store the correspoding cipher text
	static char decrypted_message[MAXLENGTH];

	int length_key = strlen(key);
	int length_message = strlen(message) - 1;

	/*Replacing any spaces in the plaintext with
	  underscores*/
	for(int i = 0; i < length_message; i++) {
		if(message[i] == ' ') {
			message[i] = '_';
		}
	}
	
	/*If in the matrix any row is left vacant at the
	  end, we fill the blank spaces with underscores*/
	if((length_message % length_key) != 0) {
		int extra = length_key - length_message % length_key;
		for(int i = 0; i < extra; i++) {
			message[length_message + i] = '_';
		}
		//Update the length of the message accordingly
		length_message = strlen(message);
	}

	//Define the matrix to transpose and get the cipher
	char matrix[(length_message / length_key)][length_key];

	int count = 0;
	int* columns;
	columns = order(key);

	//Fill in the values of plaintext in the matrix row by row
	for(int i = 0; i < (length_message/length_key); i++) {
		for(int j = 0; j < length_key; j++) {
			matrix[i][columns[j] - 1] = message[count];
			count++;
		}
	}

	int* sorted;
	sorted = sort(columns, length_key);
	int cnt = 0;
	
	/* Now create the ciphertext by reading values from the matrix 
	   in a column by column fashion*/
	for(int i = 0; i < length_key; i++) {
		for(int j = 0; j < (length_message / length_key); j++) {
			//If there is a space, replace it with an underscore
			if(matrix[j][sorted[i] - 1] == ' ') {
				decrypted_message[cnt] = '_';
			}
			else {
				decrypted_message[cnt] = matrix[j][sorted[i] - 1];
			}
			cnt++;
		}
	}
	//return the encrypted ciphertext
	return decrypted_message;
}

int main() {

	//Declaring variables for the message and key
	char key[MAXLENGTH];
	char plaintext[MAXLENGTH];

	//Taking message and key as input from the user
	printf("Enter plaintext       : ");
	fgets(plaintext, MAXLENGTH, stdin);
	printf("Enter key             : ");
	scanf("%s", key);

	//Print the encrypted message by calling the encrypt function
	printf("The encrypted text is : %s\n", encrypt(&plaintext[0], &key[0]));

	return 0;
}

/*Sample I/O :
 
  	Enter plaintext       : NeoAlgoIsAwesome
	Enter key             : HACK
	The encrypted text is : egAooowmNlssAIee
	
 	Enter plaintext       : THIS IS A PLAINTEXT
	Enter key             : KEY
	The encrypted text is : H__PIE_TSS_ATTIIALNX_	
 */



<|start_filename|>C-Plus-Plus/cp/painter_partition.cpp<|end_filename|>
/*
You have to paint N boards of length {A0, A1, A2, A3 … AN-1}. There are K 
painters available and you are also given how much time a painter takes to
 paint 1 unit of board. You have to get this job done as soon as possible
 under the constraints that any painter will only paint contiguous sections
  of board. Return the ans % 10000003

Input Format
First line contains three space seperated integers N,K and T ,where
N = Size of array,
K = No of painters available ,
T = Time taken to print each board by one painter
Next line contains N space seperated positive integers denoting size of N boards.

Constraints
1<=N<=100000
1<=K<=100000
1<=T<=1000000
1<=Li<=100000

Output Format
Return minimum time required to paint all boards % 10000003.

Sample Input
2 2 5
1 10
Sample Output
50
Explanation
The first painter can paint the first board in 5 units of time and the second painter 
will take 50 units of time to paint the second board. Since both can paint simultaneously,
 the total time required to paint both the boards is 50.
*/

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

bool painters(int* arr,long long int maxtime,int n,int k)
{
	long long int time=0;
	int p_used=1;
	for(int i=0;i<n;i++)
	{
		time += arr[i];
		if(time > maxtime)
		{
			time=arr[i];
			p_used++;
			if(p_used>k)
			{
				return false;
			}
		}
	}
	return true;
}

long int minimum_time(int* arr,int n ,int k,int t,long long int sum)
{
	long long int start = *max_element(arr, arr + n);
	long long int end   = sum;
	long long int ans;
	while(start<=end)
	{
		long long mid = (start+end)/2;
		if(painters(arr,mid,n,k))
		{
			ans=mid;
			end=mid-1;
		}
		else
                {
                        start=mid+1;
                }
        }
        return (ans*t)%10000003;
}

int main()
{
	int n,k,t;
	long long int sum=0;
	cin>>n>>k>>t;
	int* arr=new int[n];
	for(int i=0;i<n;i++)
        {
	       	cin>>arr[i];
                sum += arr[i];
	}
	cout<<minimum_time(arr,n,k,t,sum);	
	delete[] arr;
	return 0;
}


<|start_filename|>C-Plus-Plus/ds/ancestors_of_given_number_BST.cpp<|end_filename|>
/*
Given a Binary Search Tree, the program finds the Youngest and Oldest 
member of given two numbers.
Youngest member is the Parent of the given 2 nodes only if they are siblings.
Oldest member is the root node of the BST.
*/

#include<iostream>
using namespace std;

struct BST
{
	int a,count = 0, level = 0; 
	BST *left = NULL;
	BST *right = NULL;
};

//points to the root node
BST *start = NULL; 
int l1,l2;

//function to convert array into Binary Search Tree with shortest height
BST *arr_to_BST(int arr[20], int beg, int end) 
{
	BST *ptr;
	
	if(beg <= end)
	{
		ptr = new BST;
		ptr->left = NULL;
		ptr->right = NULL;
		ptr->a = arr[(beg+end)/2];
		int mid = (beg+end)/2;
		ptr->left = arr_to_BST(arr,beg,mid-1);
		ptr->right = arr_to_BST(arr,mid+1,end);	
		return ptr;
	}
	else
		return NULL;
}

//function to print Binary Search Tree
void Display_BST(BST *ptr) 
{
	cout<<"\na:"<<ptr->a;
	
	if(ptr->left != NULL)
		cout<<"\tleft:"<<ptr->left->a;
	
	if(ptr->right != NULL)
		cout<<"\tright:"<<ptr->right->a;
	
	if(ptr->left != NULL)
		Display_BST(ptr->left);
	
	if(ptr->right != NULL)
		Display_BST(ptr->right);
}

//function to assign level values to corresponding nodes
void level_assign(BST *ptr, int value=0) 
{
	ptr->level = value;
	if(ptr->left != NULL)
		level_assign(ptr->left,value+1);
	if(ptr->right != NULL)
		level_assign(ptr->right,value+1);
}

//returns level of the number
int find_number(BST *ptr,int n) 
{
	if(ptr->a == n)
		return ptr->level;
	else if(n < ptr->a)
		find_number(ptr->left,n);
	else
		find_number(ptr->right,n);
}

//function to print the value of youngest member for given numbers
void Display(BST *ptr, int n1, int n2) 
{
	if(n1 < ptr->a && n2 > ptr->a)
	{
		cout<<"\nyoungest:"<<ptr->a;
		return;
	}
	else if(ptr->level == (l1-1) || ptr->level == (l2-1))
	{
		cout<<"\nyoungest:"<<ptr->a;
		return;
	}
	if(ptr->left != NULL && (n1 < ptr->a || n2 < ptr->a))
		Display(ptr->left,n1,n2);
	else if(ptr->right != NULL && (n1 > ptr->a || n2 > ptr->a))
		Display(ptr->right, n1, n2);
}

int main()
{
	int n, arr[20], n1, n2, T;
	cout<<"\nEnter number of elements:"; 
	cin>>n;
	cout<<"\nEnter sorted array:";
	for(int i = 0 ; i < n ; i++)
	{
		cin>>arr[i];
	}
	start = arr_to_BST(arr, 0, n-1);	
	level_assign(start);
	cout<<"\nEnter number of test cases:";
	cin>>T;
	
	Display_BST(start);
	
	while(T--)
	{
		cout<<"\nEnter first number:";
		cin>>n1;
		cout<<"\nEnter second number:";
		cin>>n2;
		l1 = find_number(start,n1);
		l2 = find_number(start,n2);
//print the eldest member of Binary Search Tree
		cout<<"\neldest:"<<start->a;	
		if(n1 > n2)
		{
			if(n2 < start->a && n1 > start->a)
				;
			else
				Display(start, n2, n1);
		}
		else
		{
			if(n1 < start->a && n2 > start->a)
				;
			else
				Display(start, n1, n2);
		}
	}
	return 0;
}

/*
For example:
The sample output screen will be:

Enter number of elements:7

Enter sorted array:
12 34 45 56 67 78 89

a:56    left:34 right:78
a:34    left:12 right:45
a:12
a:45
a:78    left:67 right:89
a:67
a:89

//the program runs for n test cases
Enter number of test cases:3

Enter first number:78

Enter second number:89

eldest:56
youngest:56
Enter first number:12

Enter second number:45

eldest:56
youngest:34

Enter first number:34

Enter second number:78

eldest:56
*/


<|start_filename|>C-Plus-Plus/other/Rabin_Karp_Algorithm_using_rolling_hash.cpp<|end_filename|>
/*
Rabin Karp Algorithm (using rolling hash)
=========================================
Given a text and a pattern, find all the occurences of the pattern in the text

Time Complexity: O(n) n=size of string
Space Complexity: O(1)
*/
#include <bits/stdc++.h>
#define int long long
using namespace std;

const int mod = 1e9 + 7;
const int p = 31;

// returns (a^b)%mod
int powr(int a, int b) {
	int ans = 1;
	while (b) {
		if (b & 1LL) {
			ans *= a;
			ans %= mod;
		}
		a *= a;
		b = b >> 1;
		a %= mod;
	}
	return ans % mod;
}

// returns (a^-1)%mod
int inv(int a) {
	return powr(a, mod - 2) % mod;
}

// Assigns hash to a string
int polyHashString(string s) {
	int hash = 0;
	int coef = 1;
	for (int i = 0; i < s.size(); i++) {
		hash += (s[i] - 'a' + 1) * coef;
		coef *= p;
		coef %= mod;
		hash %= mod;
	}
	return hash % mod;
}

// Rabin Karp Algorithm for pattern matching
// returns indices of pattern in string s
void rabinKarp(string s, string pat) {

	int n = s.size();
	int m = pat.size();

	int patHash = polyHashString(pat);
	// Maintains hash of current window of size m
	int currHash = polyHashString(s.substr(0, m));

	bool patFound = 0;

	// If first window matches pattern
	if (currHash == patHash) {
		cout << 0 << endl;
		patFound = 1;
	}

	// coefficient for next character
	int coef = powr(p, m - 1);

	for (int i = 1; i <= (n - m); i++) {
		int newHash = currHash;

		// Subtract previous character
		newHash -= s[i - 1] - 'a' + 1;
		newHash += mod; newHash %= mod;

		// divide by prime
		newHash *= inv(p);
		newHash %= mod;

		// Add next char
		newHash += (s[i + m - 1] - 'a' + 1) * coef;
		newHash %= mod;

		// Check
		if (newHash == patHash) {
			cout << i << endl;
			patFound = 1;
		}

		currHash = newHash;
	}

	if (!patFound) {
		cout << "Not found";
	}
}

// Driver Code
signed main() {

	// Take input
	string s, pat;
	cin >> s >> pat;

	rabinKarp(s, pat);
}

/*
Input:
ilovecoding
love

Output:
1

Input:
aaaaaaaa
aaa

Output:
0
1
2
3
4
5
*/

<|start_filename|>C/cp/doublefactorial.c<|end_filename|>
#include <stdio.h>

int iterative_doublefactorial(int n) {
  int res = 1;
  for (int i = n; i > 0; i -= 2) {
    if (n == 0 || n == 1)
      return res;
    else
      res = res * i;
  }

}

int recursive_doublefactorial(int n) {
  if (n == 0 || n == 1)
    return 1;
  else
    return n * recursive_doublefactorial(n - 2);
}

int main() {
  int n;
  printf("Enter the number :");
  scanf("%d", & n);
  int k;
  do {
    printf("Enter the choice below :\n1.Iterative solution \n2.Recursive Solution \n3.Exit \n");
    scanf("%d", & k);
    switch (k) {
    case 1:
      printf("The Double Factorial is : %d\n", iterative_doublefactorial(n));
      break;
    case 2:
      printf("The Double Factorial is : %d\n", recursive_doublefactorial(n));
      break;
    }
  } while (k != 3);

  return 0;
}

/*
Enter the number :7
Enter the choice below :
1.Iterative solution 
2.Recursive Solution 
3.Exit 
1
The Double Factorial is : 105
Enter the choice below :
1.Iterative solution 
2.Recursive Solution 
3.Exit 
2
The Double Factorial is : 105
Enter the choice below :
1.Iterative solution 
2.Recursive Solution 
3.Exit 
3
*/


<|start_filename|>C-Plus-Plus/ds/prims_algo.cpp<|end_filename|>
/*Prim's algorithm is a minimum spanning tree algorithm that takes a graph as input and finds 
the subset of the edges of that graph which. form a tree that includes every vertex. 
has the minimum sum of weights among all the trees that can be formed from the graph.
(issue-3304)*/
#include<bits/stdc++.h> 
/*This includes functions like strlen and strcpy,It's the C++ version of header from C*/
using namespace std;
int operation(int array[] , int row, int coloumn, int graph[4][4]); 
#define number 4
/* separate function is declared to form process and output
which takes 2 for loops with min val of vertex displays output 
in 2 columns where Weight of ele and Edge of graph*/
int operation(int array[], int row, int coloumn, int graph[4][4]) {
        int least_val = 100;
        for (int index_x = 0 ; index_x < number; index_x ++) {
      if (array[index_x]) {
        for (int index_y = 0 ; index_y < number; index_y++) {
          if (!array[index_y] && graph[index_x][index_y])  {  
            if (least_val> graph[index_x][index_y] ){
             least_val = graph[index_x][index_y];
             row= index_x , coloumn= index_y;
            } } } } }
    cout << graph[row][coloumn]<<"  "<<row<< " - " << coloumn << endl;
    array[coloumn] = true;
    }
/* in main we give inputs to graph array and calls operation function */ 
int main() {
  int all_edges;
   int array[number];
/*memset Sets the first num bytes of the block of memory 
pointed by ptr to the specified value faster than loop*/
  memset(array, false, sizeof(array));
  all_edges = 0;
  array[0] = true;
 cout<<"enter the elements into graph array "<< endl ;
 /* taking the inputs for graph in form of loop
 which is of having number(of rows and coloumns) */
  int row , coloumn; 
int graph[number][number];
        for (int i =0; i< number ; i++){
    for(int j=0 ; j< number ; j++){
        cin>>graph[i][j];
    } }
cout <<"Weight of ele,"<< " "<<"Edge of graph" <<"\n";
/* iterate while loop till all edges are lesser than num-1 */
  while ( number - 1 > all_edges) {
    row = 0,coloumn = 0;
    operation(array,row,coloumn,graph);
    all_edges++;
    }
  return 0;
}
/* input:
enter the elements into graph array                                                                                                                                                  
1 4 78 15                                                                                                                                                                            
1 75 48 6                                                                                                                                                                            
45 7 8 36                                                                                                                                                                            
2 4 67 59   
output:
Weight of ele, Edge of graph                                                                                                                                                         
4  0 - 1                                                                                                                                                                             
6  1 - 3                                                                                                                                                                             
48  1 - 2 
time_complexity_O(ElogV) where v no of vertices and e no of edges

*/


<|start_filename|>C-Plus-Plus/sort/wiggle_sort.cpp<|end_filename|>
/* WIGGLE SORT
   This program accepts an array of unsorted numbers and
   sorts the array such that arr[0]<arr[1]>arr[2]<arr[3]...

*/

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

void wiggle_sort(int n, vector<int> arr)
{
    int left, right;
    //A new vector res is initialized to store sorted array
    vector<int> res(arr);
    //res is sorted with the built-in sort() function.
    sort(res.begin(), res.end());

    /*res is partitioned into two such that left sub-array 
      contains elements less than the elements in right sub-array*/

    // left points to the end of left sub-array 
    left = (n - 1) / 2;
    // right points to the end of right sub-array
    right = n - 1;
    
    //Elements in the left sub-array  are added to the even indices of vector res
    for (int k = 0; k < n; k += 2)
        // left is decremented
        arr[k] = res[left--];

    //Elements in the right sub-array are added to the odd indices of vector x
    for (int k = 1; k < n; k += 2)
        // right is decremented
        arr[k] = res[right--];

    cout << "[";
    for (int i = 0; i < n; i++)
    { //for printing the wiggle sorted array
        cout << arr[i];
        if (i != n - 1)
            cout << ", ";
    }
    cout << "]"
         << "\n";
}

int main()
{
    int element, i, no_of_elements;
    cin >> no_of_elements;
    vector<int> arr;
    for (int i = 0; i < no_of_elements; i++)
    { //The given array is stored in a vector arr
        cin >> element;
        arr.push_back(element);
    }
    //to wiggle sort arr
    wiggle_sort(no_of_elements, arr);
    return 0;
}

/*1. Sample input:
     6
     1 3 2 2 3 1
     Sample output:
     [2,3,1,3,1,2]

  2. Sample input:
     10
     1 4 6 2 3 7 9 2 1 0
     [2, 9, 2, 7, 1, 6, 1, 4, 0, 3]
*/

/*
   Time Complexity : O(nlogn)   (Sorting takes O(n logn) and traversal takes O(n))
   Space Complexity : O(n)   (New array to store the wiggle sorted elements)
*/

<|start_filename|>C/cp/Count_Distinct_Elements_in_Every_Window.c<|end_filename|>
// C program to Count of distinct elements in every window.

#include<stdio.h>
void distCount(int a[], int n, int k) {
    int count[100000] = {0};
    int i, d = 0;
    printf("Count of distinct elements in every window: ");
    for (i = 0; i < k; i++) {
        count[a[i]] += 1;
        if (count[a[i]] == 1)
            d++;
    }

    printf("%d ", d);
    for (i = k; i < n; i++) {
        count[a[i - k]] -= 1;
        if (count[a[i - k]] == 0)
            d--;
        if (count[a[i]] == 0)
            d++;
        count[a[i]] += 1;
        printf("%d ", d);
    }
}

int main() {
    int i, n, k, a[100000];
    printf("Enter the size of array: ");
    scanf("%d", &n);
    printf("Enter the elements of array: ");
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);
    printf("Enter the size of window: ");
    scanf("%d", &k);
    distCount(a, n, k);
    return 0;
}

/*
    Sample input/output:
    Enter the size of array: 10
    Enter the elements of array: 10 9 8 9 7 8 5 6 6 5
    Enter the size of window: 4
    Count of distinct elements in every window: 3 3 3 4 4 3 2

    Time Complexity= O(n)
    Space Complexity= O(n)
*/


<|start_filename|>C-Plus-Plus/search/Jump_Search.cpp<|end_filename|>
/*JUMP SEARCH:
Jump Search is a searching algorithm for sorted arrays. 
The basic idea is to check fewer elements (than linear search) by jumping ahead by fixed steps or skipping some elements in place of searching all elements.
*/

#include<iostream>
#include<cmath>

using namespace std;

int jump_search(int a[], int n, int find)
{
    int step = sqrt(n);
    int pre_step = 0;
    while (a[min(step, n) - 1]  < find) 
    { 
        pre_step = step; 
        step += sqrt(n); 
        if (pre_step >= n)
        {
            return -1;	
        } 
    }
    while(a[pre_step] < find)
    {
        pre_step++;
        if(pre_step == min(step,n))
        {
            return -1;
        }
    }
    if(a[pre_step] == find)
    {
        return pre_step;
    }
    else
    {
        return -1;
    }
}

int main()
{
    int n,search;
    cout << "Enter no. of elements in an array: ";
    cin >> n;
    int arr[n];
    cout << "Enter elements in an array in increasing order: ";
    for(int i=0;i<n;i++)
    {
        cin >> arr[i];
    }
    cout << "Enter a number to be searched: ";
    cin >> search;
    int result = jump_search(arr,n,search);
    if(result == -1)
    {
        cout << search << " is not present in the array." << endl;
    }
    else
    {
        cout << search << " is present at index no " << result+1 << endl;
    }
    return 0;
}

/*
SAMPLE INPUT:
Enter no. of elements in an array: 
12
Enter elements in an array in increasing order: 
2 4 6 8 10 11 14 17 20 33 36 40
Enter a number to be searched: 
17

SAMPLE OUTPUT:
17 is present at index no 8
*/


<|start_filename|>C/other/Tower_Of_Hanoi.c<|end_filename|>
#include <stdio.h>

void TowerOfHanoi(int n,int a,int b,int c){
    if(n){
        TowerOfHanoi(n-1,a,c,b);
        printf("%d -> %d\n", a,b);
        TowerOfHanoi(n-1,c,b,a);
    }
}

int main(){
    int number_of_discs;
    printf("Enter the value of n: ");
    scanf("%d",&number_of_discs);
    printf("\nThe value of n is: %d\n", number_of_discs);
    TowerOfHanoi(number_of_discs,1,2,3);
    //each rod is numbered as 1,2,3
    return 0;
}

/*
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
1) Only one disk can be moved at a time.
2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
3) No disk may be placed on top of a smaller disk.

In this code, we use the recursive definition of Tower of Hanoi.

Time Complexity: O(2^N)
Space Complexity: O(N)

OUTPUT
Enter the value of n: 4
The value of n is: 4
1 -> 3
1 -> 2
3 -> 2
1 -> 3
2 -> 1
2 -> 3
1 -> 3
1 -> 2
3 -> 2
3 -> 1
2 -> 1
3 -> 2
1 -> 3
1 -> 2
3 -> 2
*/


<|start_filename|>Kotlin/sort/SelectionSort/src/SelectionSort.kt<|end_filename|>
fun selectionSort(list: MutableList<Int>): List<Int>{
    // run the code as many times as there are elements in the list
    for (i in 0 until list.size){
        // store the first element as the smallest one as well as store the
        // index so that you know which number we are dealing with
        var minimum = list[i];
        var indexMinimum = i

        // check the elements in the list ahead of our currently selected
        // element and see if there are any numbers smaller than it
        for(x in i+1 until list.size){
            // actual checking of the smaller value
            if (list[x] < minimum){
                // change our minimum value
                minimum = list[x]
                // as well as store the index of the minimum value
                indexMinimum = x
            }
        }
        // put the minimum value at the very beginning and put the beginning value
        // at the place of the minimum value
        list[i] = minimum.also { list[indexMinimum] = list[i] }
    }

    // return the sorted list
    return list
}

// driver and example code for selection sort
fun main() {
    val unsorted = listOf(20,12,10,15,2,22,35,27,16)
    val sorted = selectionSort(unsorted.toMutableList())
    print(sorted)
}

<|start_filename|>C-Plus-Plus/math/Strong_Number.cpp<|end_filename|>
//Strong number is a special number whose sum of factorial of digits is equal to the original number.
//For example: 145 is strong number. Since, 1! + 4! + 5! = 145

#include <bits/stdc++.h>
using namespace std;
int main()
{
    long long int num, n, factorial=1, sum=0;
    int i, digit;
    cout<<"Enter a number to check whether it is a strong number or not: ";
    cin>>num;
    n=num;
    for(n=num; n>0; n=n/10)
    {
        digit=n%10;     //digit of the number
        if(digit!=0)
        {
            factorial=1;
            for(i=1; i<=digit; i++)
                factorial*=i;    //code for calculating factorial of digits
        }
        else
            digit=1;
        sum+=factorial;     //sum of factorial of digits
    }
    if(sum==num)
        cout<<sum<<" is a strong number."<<endl;
    else
        cout<<num<<" is not a strong number."<<endl;
    return 0;
}

/*
Time Complexity: O(n*9)
Space Complexity: O(1)

sample 1:
Input: Enter a number to check whether it is a strong number or not:  145
Output: 145 is a strong number.
sample 2:
Input: Enter a number to check whether it is a strong number or not: 2
output: 2 is not a strong number.
*/ 


<|start_filename|>C-Sharp/other/CountInversions.cs<|end_filename|>
﻿//Count Inversion problem with mergesort algorithm where i < j and arr[j] < arr[i] is an inversion
using System;

namespace CountInversionsProblem
{
    class Count_Inversions
    {
        //The merge step to sort the elements and count inversions
        private static int Merge(int[] arr, int[] temp, int leftStart, int mid, int rightEnd)
        {
            int left = leftStart, right = mid + 1, index = left, count = 0;
            //Compare Elments from arr portion and sort them in temproray array temp
            while (left < mid + 1 && right <= rightEnd)
            {
                if (arr[right] < arr[left])
                {
                    temp[index] = arr[right++];
                    count += mid + 1 - left;
                }
                else
                {
                    temp[index] = arr[left++];
                }
                index++;
            }
            // if the arr porion sorted but i didn't reach the last element place the rest in temp 
            for (; left <= mid; left++)
                temp[index++] = arr[left];
            // if the arr porion sorted but j didn't reach the last element place the rest in temp 
            for (; right <= rightEnd; right++)
                temp[index++] = arr[right];
            //Place the sorted elements from temp into arr
            for (left = leftStart; left <= rightEnd; left++)
                arr[left] = temp[left];

            return count;
        }
        // recursive part in merge sort to break the array into smaller portions and count inversions
        private static int CountInversions(int[] arr, int[] temp, int leftStart, int rightEnd)
        {
            if (leftStart < rightEnd)
            {
                int count = 0;
                int mid = leftStart + (rightEnd - leftStart) / 2;
                count += CountInversions(arr, temp, leftStart, mid);
                count += CountInversions(arr, temp, mid + 1, rightEnd);
                count += Merge(arr, temp, leftStart, mid, rightEnd);
                return count;
            }
            return 0;

        }
        //Limit the number of parameters
        public static int CountInversions(int[] arr)
        {
            int count = CountInversions(arr, new int[arr.Length], 0, arr.Length - 1);
            return count;
        }
        static void Main(string[] args)
        {
            Console.Write("Enter array size: ");
            int n = Convert.ToInt32(Console.ReadLine());
            int[] arr = new int[n];
            Console.WriteLine("Enter array Elements: ");
            for (int i = 0; i < n; i++)
            {
                arr[i] = Convert.ToInt32(Console.ReadLine());
            }
            int count = CountInversions(arr);
            Console.WriteLine($"\n\nNumber of inversions = {count}");
        }
    }
}
/*
Sample Input


Enter array size: 5
Enter arry elements : 
2
1
3
1
2

input array : 2 1 3 1 2

number of inversions output : 4 
Complexity:
Merge sort takes time complexity of O(nlogn) and space complexity of O(n)
 
 */



<|start_filename|>Java/cp/RemoveDuplicateElementWithoutExtraSpace.java<|end_filename|>
import java.util.Scanner;

public class RemoveDuplicateElementWithoutExtraSpace{

    // Function to remove duplicate elements
    // This function returns new size of modified
    // array.
    static int removeDuplicates(int arr[], int n)
    {
        if (n == 0 || n == 1)
            return n;

        // To store index of next unique element
        int j = 0;

        // Doing same as done in Method 1
        // Just maintaining another updated index i.e. j
        for (int i = 0; i < n-1; i++)
            if (arr[i] != arr[i+1])
                arr[j++] = arr[i];

        arr[j++] = arr[n-1];

        return j;
    }

    public static void main (String[] args)
    {
        // taking the input from the user
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the length of the array : ");
        int n = sc.nextInt();
        
        int arr[] = new int[n];
        System.out.println("Enter the values for the array elements : ");
        // taking the values for the array from the user
        for(int i=0; i<n; i++)
        {
            arr[i] = sc.nextInt();
        }

        n = removeDuplicates(arr, n);

        // Print updated array
        for (int i=0; i<n; i++)
            System.out.print(arr[i]+" ");
    }

}

/*

Example:

Input: 
Enter the length of the array : 5
Enter the values for the array elements : 
1 1 1 3 4

Output:
1 3 4

*/


<|start_filename|>Go/cryptography/PlayFair_Cipher/playfaircipher.go<|end_filename|>
/*
   The Playfair cipher( Playfair square ) encrypts pairs of letters (digraphs),
   instead of single letters as in the simple substitution cipher. The Playfair
   is thus significantly harder to break since the frequency analysis used for 
   simple substitution ciphers does not work with it.
*/

package main

import (

  "fmt"
  "bufio"
  "os"

)

// Global variables
var plaintext string
var key string
var keyMatrix[5][5] string
var output string
var list[4] int
var alph string = "abcdefghijklmnopqrstuvwxyz"

//This function will form the 5x5 key Matrix 
func keyTable() {

     i:=0
     j:=0
     c:=0
     var index[26] int;

     //initializing the array to 0 as it stores garbage values
     for z:=0;z<26;z++ {
         index[z] = 0;
     }

     var hash[100] int;
     //marking the alphabets in key
     for i=0;i<len(key);i++ {
         if(key[i] != 'j'){
            for j=0;j<26;j++ {
                if(key[i] == alph[j]){
                   index[j] = 2;
                   hash[c] = j;
                   c++;
                }
            }
         }
     }

     //marking alphabetic j
     index[9] = 1;
     i = 0;
     j = 0;

     //adding the marked alphabets  
     for k:=0;k<len(key);k++ {
         if(index[hash[k]] == 2) {
            index[hash[k]] -= 1;
            keyMatrix[i][j] = string(key[k]);
            j++;

            if(j==5){
              i++;
              j=0;
            }
         }
     }

     //adding the remaining alphabets
     for  k:=0;k<26;k++ {
         if(index[k] == 0){
            keyMatrix[i][j] = string(alph[k]);
            j++;

            if(j==5){
               i++;
               j=0;
            }
         }
     }
}

/* This function searches for the characters of the digraph in key matrix
   generated and gives their position*/
func search(x,y string) {

     //replacing j with i   
     if(x == "j'") {
         x = "i";
     }else if(y =="j") {
         y = "i";
     }

     //returning the positions of characters through list    
     for i:=0;i<5;i++ {
         for j:=0;j<5;j++ {
             if(keyMatrix[i][j] == x) {
                list[0] = i;
                list[1] = j;
             }else if(keyMatrix[i][j] == y) {
                list[2] = i;
                list[3] = j;
             }
         }
      }
}

// This function ciphers the plane text 
func cipher() {

     i := 0;
     //cipher the plain text with the key matrix we built
     for i<len(plaintext) {

         search(string(plaintext[i]),string(plaintext[i+1]))

         if(list[0] == list[2]) {
            output += string(keyMatrix[list[0]][(list[1]+1)%5]);
            output += string(keyMatrix[list[0]][(list[3]+1)%5]);
         } else if(list[1] == list[3]){
            output += string(keyMatrix[(list[0]+1)%5][list[1]]);
            output += string(keyMatrix[(list[2]+1)%5][list[1]]);
         }else{
            output += string(keyMatrix[list[0]][list[3]]);
            output += string(keyMatrix[list[2]][list[1]]);
         }
         i+=2;
     }
}

// This function will encript the plaintext to cipher in playfail cipher
func playfaircipher() {

    if(len(plaintext)%2 != 0 ){
         plaintext += "z";
    }

    //generating key table
    keyTable();

    //cipher the plane text
    cipher();

}

//driver function
func main() {

     // Taking the plaintext as input from user
     fmt.Print("Enter the plaintext : ")
     scanner := bufio.NewScanner(os.Stdin)
     scanner.Scan()

     plaintext = scanner.Text()

     // Taking the keyword as input from the user
     fmt.Print("Enter the keyword : ")
     scanner.Scan()
     key = scanner.Text()

     playfaircipher()

     // printing the cipher text
     fmt.Print("The cipher text is : ",output)

}

/*
     Sample I/O :

     Enter the plaintext : hello 
     Enter the keyword : world
     The cipher text is : kbekdv 

*/


<|start_filename|>Java/math/FactorialUsingBigInteger.java<|end_filename|>
// Calculating Factorial Using Big Integer
// https://www.hackerearth.com/practice/notes/factorial-of-large-number/
import java.math.BigInteger;
import java.util.*;
import java.io.*;
import java.lang.*;

class FactorialUsingBigInteger
{
    //Main Method
    public static void main(String[] args) throws IOException
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number of times you want to calculate Factorial:");
        int t = sc.nextInt();
        HashMap<Integer,BigInteger> hashmap = new HashMap<>();
        int maxKey = -1;
        for(int i=0;i<t;i++){
            System.out.println("Enter the value of N:");
            int N = sc.nextInt();
            if(N>=0)
            {
                BigInteger f = new BigInteger("1"); // Or BigInteger assigned to ONE
                // Multiply f with number till N
                int initial = 2;
		//Checking if inputted number exists in map or not
                if (hashmap.containsKey(N)){
                    f = hashmap.get(N);
                } else {
		    // For a given number, Checking whether any sub factorial has some element present in hashmap
                    if (maxKey!=-1){
                        initial = maxKey;
                    }
                    for (int j = initial; j <= N; j++) {
                        if (hashmap.containsKey(j)) {
                            f = f.multiply(hashmap.get(j));
                        } else {
                            f = f.multiply(BigInteger.valueOf(j));
                            maxKey = j;
                            hashmap.put(j, f);
                        }
                    }
                }
                System.out.println("Factorial of given number is :"+f);
            }else{
                System.out.println("Number Should be greater than 0");
            }
        }
    }
} 
/*
Time Complexity:O(t*N)
Space Complexity:O(1)
Input:
Enter the number of times you want to calculate Factorial:
3
Enter the value of N:
20   //O(N) ==>20*19*18.....*1
Enter the value of N:
80  // O(N) ==>80*79*78.....*21*hashmap[20]
Enter the value of N:
10  // O(1) ==>hashmap[10]
Output:
Factorial of given number is : 2432902008176640000
Factorial of given number is : 71569457046263802294811533723186532165584657342365752577109445058227039255480148842668944867280814080000000000000000000
Factorial of given number is : 3628800
*/

<|start_filename|>Java/Operating-System/alloc.java<|end_filename|>
/* 
Title: Memory Allocation in Operating Systems in Java

Description:
(a) First-Fit: 
- Allocate the first hole that is big enough. 
- Searching can start either at the beginning of the set of holes or where the previous first search ended. 
- Stop searching as soon as we find a free hole that is large enough.
(b) Best-Fit: 
- Allocate the smallest hole that is big enough. 
- Search the entire list unless the list is ordered by size.
(c) Worst-Fit: 
- Allocate the largest hole. 
- Search the entire list unless the list is ordered by size.
 
*/

import java.util.ArrayList;
import java.util.Scanner;

public class memory1 {
 public void first()
 {
  System.out.println("ENTER THE NUMBER OF PROCESSES");
        int size = s.nextInt();
        System.out.println("ENTER THE SIZES OF PROCESSES");
        int s1[] = new int[size];
        for (int i = 0; i < size; i++) {
          int a = s.nextInt();
          s1[i] = a;
        }

        System.out.println("ENTER THE SIZE OF MEMORY BLOCK");
        int size1 = s.nextInt();
        System.out.println("ENTER THE MEMORY PARTITIONS");
        int s2[] = new int[size1];
        for (int i = 0; i < size1; i++) {
          int a1 = s.nextInt();
          s2[i] = a1;
        }
        int allocation[] = new int[size];

        for (int i = 0; i < allocation.length; i++) //initialize to -1
        {
          allocation[i] = -1;
        }

        for (int i = 0; i < size; i++) {
          for (int j = 0; j < size1; j++) {
            if (s2[j] >= s1[i]) {

              allocation[i] = j;
              s2[j] -= s1[i];

              break;
            }
          }
        }   
        System.out.println("\nProcess No.\t\tProcess Size\t\tBlock no.");
        for (int i = 0; i < size; i++) {
          System.out.print(" " + (i + 1) + "\t\t\t" + s1[i] + "\t\t\t");
          if (allocation[i] != -1) System.out.print(allocation[i] + 1);
          else System.out.print("Not Allocated");
          System.out.println();
        }
 }
 
 public void best()
 {
  System.out.println("ENTER THE NUMBER OF PROCESSES");
        size = s.nextInt();
        System.out.println("ENTER THE SIZES OF PROCESSES");
        int s11[] = new int[size];
        for (int i = 0; i < size; i++) {
          int a = s.nextInt();
          s11[i] = a;
        }

        System.out.println("ENTER THE SIZE OF MEMORY BLOCK");
        size1 = s.nextInt();
        System.out.println("ENTER THE MEMORY PARTITIONS");
        int s21[] = new int[size1];
        for (int i = 0; i < size1; i++) {
          int a1 = s.nextInt();
          s21[i] = a1;
        }
        int allocation1[] = new int[size];
        for (int i = 0; i < allocation1.length; i++) {
          allocation1[i] = -1;
        }

        for (int i = 0; i < size; i++) {

          int best = -1;
          for (int j = 0; j < size1; j++) {
            if (s21[j] >= s11[i]) {
              if (best == -1) best = j;
              else if (s21[best] > s21[j]) best = j;
            }
          }

          if (best != -1) {

            allocation1[i] = best;
            s21[best] -= s11[i];
          }
        }        
        System.out.println("\nProcess No.\t\tProcess Size\t\tBlock no.");
        for (int i = 0; i < size; i++) {
          System.out.print("   " + (i + 1) + "\t\t\t" + s11[i] + "\t\t\t");
          if (allocation1[i] != -1) System.out.print(allocation1[i] + 1);
          else System.out.print("Not Allocated");
          System.out.println();
        }        
 }
 
 public void worst(){
  System.out.println("ENTER THE NUMBER OF PROCESSES");
        size = s.nextInt();
        System.out.println("ENTER THE SIZES OF PROCESSES");
        int s111[] = new int[size];
        for (int i = 0; i < size; i++) {
          int a = s.nextInt();
          s111[i] = a;
        }

        System.out.println("ENTER THE SIZE OF MEMORY BLOCK");
        size1 = s.nextInt();
        System.out.println("ENTER THE MEMORY PARTITIONS");
        int s211[] = new int[size1];
        for (int i = 0; i < size1; i++) {
          int a1 = s.nextInt();
          s211[i] = a1;
        }
        int allocation11[] = new int[size];

        for (int i = 0; i < allocation11.length; i++) {
          allocation11[i] = -1;
        }
        for (int i = 0; i < size; i++) {

          int wst = -1;
          for (int j = 0; j < size1; j++) {
            if (s211[j] >= s111[i]) {
              if (wst == -1) wst = j;
              else if (s211[wst] < s211[j]) wst = j;
            }
          }

          if (wst != -1) {

            allocation11[i] = wst;

            s211[wst] -= s111[i];
          }
        }        
        System.out.println("\nProcess No.\t\tProcess Size\t\tBlock no.");
        for (int i = 0; i < size; i++) {
          System.out.print("   " + (i + 1) + "\t\t\t" + s111[i] + "\t\t\t");
          if (allocation11[i] != -1) System.out.print(allocation11[i] + 1);
          else System.out.print("Not Allocated");
          System.out.println();
        }       
 }
}

public class alloc {

  public static void main(String[] args) {
    Scanner s = new Scanner(System. in );
    int u = 0;
    System.out.println("MEMORY ALLOCATION TECHNIQUES");
    do {
      memory1 c1=new memory1();
      System.out.println("ENTER 1 FOR FIRST FIT");
      System.out.println("ENTER 2 FOR BEST FIT");
      System.out.println("ENTER 3 FOR WORST FIT");
      System.out.println("PRESS O FOR EXIT ");
      u = s.nextInt();
      switch (u) {
      case 1:
        c1.first();
        break;

      case 2:
        c1.best();
        break;

      case 3:
        c1.worst();
        break;
      }
    } while ( u != 0 );
   
   }
 
}

  /*
 *MEMORY ALLOCATION TECHNIQUES
ENTER 1 FOR FIRST FIT
ENTER 2 FOR BEST FIT
ENTER 3 FOR WORST FIT
PRESS O FOR EXIT 
1
ENTER THE NUMBER OF PROCESSES
5
ENTER THE SIZES OF PROCESSES
210
167
34
356
267
ENTER THE SIZE OF MEMORY BLOCK
5
ENTER THE MEMORY PARTITIONS
100
300
200
400
378

Process No.		Process Size		Block no.
 1			210			2
 2			167			3
 3			34			1
 4			356			4
 5			267			5

ENTER 1 FOR FIRST FIT
ENTER 2 FOR BEST FIT
ENTER 3 FOR WORST FIT
PRESS O FOR EXIT 
1
ENTER THE NUMBER OF PROCESSES
5
ENTER THE SIZES OF PROCESSES
200
13
678
456
789
ENTER THE SIZE OF MEMORY BLOCK
5
ENTER THE MEMORY PARTITIONS
100
500
200
346
135

Process No.		Process Size		Block no.
 1			200			2
 2			13			1
 3			678			Not Allocated
 4			456			Not Allocated
 5			789			Not Allocated

ENTER 1 FOR FIRST FIT
ENTER 2 FOR BEST FIT
ENTER 3 FOR WORST FIT
PRESS O FOR EXIT 
3
ENTER THE NUMBER OF PROCESSES
5
ENTER THE SIZES OF PROCESSES
100
300
478
124
245
ENTER THE SIZE OF MEMORY BLOCK
5
ENTER THE MEMORY PARTITIONS
100
500
300
245
357

Process No.		Process Size		Block no.
   1			100			2
   2			300			2
   3			478			Not Allocated
   4			124			5
   5			245			3
   
ENTER 1 FOR FIRST FIT
ENTER 2 FOR BEST FIT
ENTER 3 FOR WORST FIT
PRESS O FOR EXIT 
0
*/


<|start_filename|>C/graphs/Prim_Algorithm.c<|end_filename|>
#include<stdio.h>
#include<stdbool.h> 

#define INF 9999999

// number of vertices in graph
#define V 5

// create a 2d array of size 5x5
//for adjacency matrix to represent graph
int G[V][V] = {
  {0, 9, 75, 0, 0},
  {9, 0, 95, 19, 42},
  {75, 95, 0, 51, 66},
  {0, 19, 51, 0, 31},
  {0, 42, 66, 31, 0}};

int main() {
  int no_edge;  // number of edge

  // create a array to track selected vertex
  // selected will become true otherwise false
  int selected[V];

  // set selected false initially
  memset(selected, false, sizeof(selected));
  
  // set number of edge to 0
  no_edge = 0;

  // the number of egde in minimum spanning tree will be
  // always less than (V -1), where V is number of vertices in
  //graph

  // choose 0th vertex and make it true
  selected[0] = true;

  int x;  //  row number
  int y;  //  col number

  // print for edge and weight
  printf("Edge : Weight\n");

  while (no_edge < V - 1) {
    //For every vertex in the set S, find the all adjacent vertices
    // , calculate the distance from the vertex selected at step 1.
    // if the vertex is already in the set S, discard it otherwise
    //choose another vertex nearest to selected vertex  at step 1.

    int min = INF;
    x = 0;
    y = 0;

    for (int i = 0; i < V; i++) {
      if (selected[i]) {
        for (int j = 0; j < V; j++) {
          if (!selected[j] && G[i][j]) {  // not in selected and there is an edge
            if (min > G[i][j]) {
              min = G[i][j];
              x = i;
              y = j;
            }
          }
        }
      }
    }
    printf("%d - %d : %d\n", x, y, G[x][y]);
    selected[y] = true;
    no_edge++;
  }

  return 0;
}


<|start_filename|>Java/ds/postorder_Traversal.java<|end_filename|>

import java.util.*;
class node{
    int value;
    node left;
    node right;

    node(int key)
    {
        value = key;
        left = null;
        right = null;
    }
    node(int key, node left, node right )
    {
        this.value = key;
        this.left = left;
        this.right = right;

    }

}
class stack
{
    node[] array = new node[10000];
    private int top;
    stack()
    {
        top = 0;
    }
    void push(node item)
    {
        array[++top] = item;
    }
    node pop()
    {
        
        int temp  = top;
        --top;
        return array[temp];
    }
    boolean isEmpty()
    {
        if(top == 0)
         return true;
         else
         return false;
    }
}
public class postorder_Traversal {
    node root;
    void postorder_traversal_Iterative()
    {
        stack stack1 = new stack();
        stack stack2 = new stack();
        if(root == null)
        return;
        stack1.push(root);
        while(!stack1.isEmpty())
        {
            node item = stack1.pop();
            stack2.push(item);
            if(item.left!=null)
            {
                stack1.push(item.left);
            }
            if(item.right!=null)
            {
                stack1.push(item.right);
            }
        }
        while(!stack2.isEmpty())
        {
            node item = stack2.pop();
            System.out.print(item.value+" ");
        }
        System.out.print("\n");
    }
    public void postorderRecursive(node root)
    {
        if(root == null)
        return;
        postorderRecursive(root.left);
        postorderRecursive(root.right);
        System.out.print(root.value + " ");
        
    }
    void postorder_traversal_recursive()
    {
        postorderRecursive(root);
    }
    public postorder_Traversal(){
        root=takeInput(null,false);
    }
      node takeInput(node parent,Boolean isleftorright){
          Scanner s = new Scanner(System.in);
        if(parent==null){
            System.out.println("Enter the value of root node");
        }
        else {
            if(isleftorright){
                System.out.println("enter the value of left child of "+parent.value);
            }
            else {
                System.out.println("enter the value of right child "+parent.value);
            }
        }
        int value=s.nextInt();
        node node=new node(value,null,null);
        boolean choice;
        System.out.println("Do you have left child of "+node.value);
        choice=s.nextBoolean();
        if(choice){
            node.left=takeInput(node,true);
        }

        System.out.println("Do you have right child of "+node.value);
        choice=s.nextBoolean();
        if(choice){
            node.right=takeInput(node,false);
        }
        return node;
    }
    
    public static void main(String args[])
    {
      postorder_Traversal binaryTree = new postorder_Traversal();  
      binaryTree.postorder_traversal_Iterative();
      binaryTree.postorder_traversal_recursive();
    }
}
/* for this tree
       
                 1
               /   \
              2     3 
            /   \  /  \ 
           4     5 6   7
          /      \ /    \
         null null null null
        
 post orde traversal of above tree is 
          4 5 2 6 7 3 1
*/


<|start_filename|>C/cryptography/MonoAlphabeticCipher.c<|end_filename|>
/* Monoalphabetic substitution cipher basically replaces each letter of a plaintext by another letter or symbol, depending only on the letter.
   The same plaintext letter is always replaced by the same ciphertext letter and the same letter can be replaced by letter itself.
   Example if a is there we replace it with B to Z and so on for the others.*/

#include<stdio.h>
#include<string.h>

//this is the encription function
void monoalphebaticcipher(char input[100],int size){
     
     char output[size-1]; 
     char cipherer[26] = {'Z','Y','X','W','V','U','T','S','R','Q','P','O','N','M','L','K','J','I','H','G','F','E','D','C','B','A'};     
     char list[26] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o','p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};  
     char space = ' ';
     //iterate through input and cipher the plane text as output
     for(int i=0;i<size-1;i++){     
         for(int j=0;j<26;j++){
             if(input[i]==list[j])
                output[i] = cipherer[j];
             else if( input[i] == space)
                output[i] = space;    
         } 
     } 
  
     printf("The Cipher text :");
     for(int j=0;j<size-1;j++)
         printf("%c",output[j]);  
}

int main(void){

     char input[100];
     printf("Give the plain text here in small letters :");
     //Taking input from user
     fgets(input,100,stdin);
     int size = strlen(input);
     //calling monoalphabeticcipher
     monoalphebaticcipher(input,size);
     return 0;
}
/*
  Sample I/O :
  Give the plain text here in small letters :hello world
  The Cipher text :SVOOL DLIOW
*/


<|start_filename|>C/math/armstrong_number.c<|end_filename|>
// C Program to check whether a number is Armstrong or not

#include<stdio.h>
#include<math.h>

void ArmstrongNumber(int n){
	int num=n, rem, sum=0;
	
	// Counting number of digits
	int digits = (int) log10(num) + 1;

    while(num > 0) 
    {  
        rem = num % 10; 
        sum = sum + pow(rem,digits); 
        num = num / 10; 
    } 
    
    if(n==sum)
    	printf("%d is an Armstrong number.",n);
    else
    	printf("%d is not an Armstrong number.",n);
}

int main(){
	int num;
	
	printf("Enter the number: ");
	scanf("%d",&num);
	
	ArmstrongNumber(num);
	
	return 0;
}

/*
	Sample input/output:
	
	Example 1:
	Enter the number: 153
	153 is an Armstrong number.

	Example 2:
	Enter the number: 1094
	1094 is not an Armstrong number.
	
	Time Complexity= O(log(n)) 
	Space Complexity= O(1)
*/


<|start_filename|>C-Plus-Plus/sort/Bubble_Sort.cpp<|end_filename|>
/*Bubble Sort Algorithm is the simplest sorting algorithm in which each element is compared to its adjacent element 
and if first elememt is greater than second element ,then the swapping occurs.
The swapping occurs till the array is sorted.
*/
#include <bits/stdc++.h>			//Header file
using namespace std;	//For cin and cout
void bubblesort(int[], int);
int main()
{
	int n, arr[100], num;	//Declarartion of required variables
	cout << "Enter the number of elements of the array: ";
	cin >> n;	//Getting the number of elements of the array from the user
	cout << endl << "Enter the elements of the array to be sorted: " << "\n";
	for (int i = 0; i < n; i++)
	{
		//For loop for taking elements of the array from the user, can be space-seperated as well
		cin >> num;
		arr[i] = num;
	}
	bubblesort(arr, n);
	cout << "Array after sorting is:" << endl;
	for (int i = 0; i < n; i++)
	{
		//For loop for printing out the array after sorting
		cout << arr[i] << " ";
	}
}
void bubblesort(int arr[], int n)
{
	int temp;
	for (int i = 0; i < n - 1; i++)
	{
		bool sorted = true;	// declaring a sorted variable which will check if array is already sorted or not
		for (int j = 0; j < n - 1 - i; j++)
		{
			//Inner for loop
			if (arr[j] > arr[j + 1])
			{
				temp = arr[j + 1];	//Swapping the elements, temp is used to store the temporary variable
				arr[j + 1] = arr[j];
				arr[j] = temp;
				sorted = false;	// sorted value will be updated to false if there is swapping of elements occured 
			}
		}
		if (sorted)
		{
			break;
		}
	}
}
/*
Sample Output
Enter the number of elements of the array: 5
Enter the elements of the array to be sorted:6 5 2 3 1
Array after sorting is:
1 2 3 5 6

Time complexities:
Worst Case:O(n2)
Best Case:O(n)    
Average Case:O(n2)  

Space Complexity: Auxilary Space:O(2) because of variable temp and sorted.  
*/



<|start_filename|>Dart/sort/InsertionSort.dart<|end_filename|>
/**
Function to sort a list of inputs using Insertion sort technique.
In every iteration we choose one value and put it at a position after
comparing it with all the other elements before it in the list.
 */
import 'dart:io';

// function that implements insertion sort
List insertionSort(List arr) {
  // this loop runs from 2nd element
  for (int i = 1; i < arr.length; i++) {
    int k = i - 1;
    int temp = arr[i];
    // this loop compares all elements before temp with temp
    // and changes positions
    while (k >= 0 && arr[k] > temp) {
      arr[k + 1] = arr[k];
      k--;
    }
    // after shifting we have one spot for temp, so we place it there
    // and close the loop
    arr[k + 1] = temp;
  }
  return arr;
}

// main function, entry point of the program
void main() {
  print("Enter the size of list:");
  int size = int.parse(stdin.readLineSync()!);
  List arr = [];
  print("Enter the numbers:");
  for (int i = 0; i < size; i++) {
    arr.add(int.parse(stdin.readLineSync()!));
  }
  // sorting
  arr = insertionSort(arr);
  print("Sorted list:");
  for (int i = 0; i < size; i++) {
    print(arr[i]);
  }
}

/**
Enter the size of list:
6
Enter the numbers:
5
0
2
1
4
3
Sorted list:
0
1
2
3
4
5

Time Complexity: O(n*2)
Space Complexity: O(1)
 */


<|start_filename|>Java/cp/Meetings.java<|end_filename|>
/*
 - Meetings :
      We will give the input as our available time and if our available time is in between
      meeting_hour1 to meeting_hour2 then we are able to attend the meeting otherwise not
      time is a string in the format "HH:MM AM" or "HH:MM PM" (without quotes)

 - Example : Let the available time be 01:04 AM and scheduled meeting time be 12:00 AM to 03:00 PM
             now, 01:04 AM lies between 12:00 AM to 03:00 PM hence, we can attend the meeting

 - Approach :
   1. As the time is in the form of String so we have to convert it to the integer and we will use
      time conversion method

   2. If time is in AM then just multiply hour by 100 and add minutes to it
      for example - time is 01:04 AM
                    multiply hour by 100(1*100 = 100) and then add minutes(100 + 04 = 104)

   3. If time is in PM then multiply hour by 100 and add 1200 + minutes to it
      for example - time is 01:04 PM
                    multiply hour by 100(1*100 = 100) and then add 1200 + minutes(100 + 1200 + 04 = 1304)

   4. After converting String to integer check the condition (available_time >= meeting_hour1 && available_time <= meeting_hour2)
      if it is true then you can attend the meeting otherwise not
 */

import java.util.Scanner;

public class Meetings {

	//method to convert String to an integer
	public static int timeConversion(String s) {

        //taking first 2 characters of String
		int hour = Integer.parseInt(s.substring(0, 2)) % 12;
		hour = hour*100;

        //If String ends with PM then add 1200 to hour
		if (s.endsWith("PM")) {
			hour += 1200;
		}
		//adding minutes to hour
		int minute = Integer.parseInt(s.substring(3, 5));
		hour = hour + minute;

		return hour;
	}

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

		Scanner sc = new Scanner(System.in);

		//Enter the time when you are available
		System.out.print("Enter Time : ");
		String date1=sc.nextLine();

		int available_time = Meetings.timeConversion(date1);

		//Enter your scheduled meeting time
		System.out.print("Enter the Meeting Time : ");
		String p = sc.nextLine();

		String time = p.substring(0, 8);
		int meeting_hour1 = Meetings.timeConversion(time);
		String time2 = p.substring(9, 17);
		int meeting_hour2 = Meetings.timeConversion(time2);

		String result ;
		//Checking condition (meeting_hour1 <= available_time <= meeting_hour2)
		if(available_time >= meeting_hour1 && available_time <= meeting_hour2) {
			result = "Yes, you can attend the meeting";
		}else {
			result = "No, you can not attend the meeting";
		}
		//Printing Result
		System.out.println(result);
	}
}
/*
 - Test Cases :
    1. Input : Enter Time : 12:01 AM
               Enter the Meeting Time : 12:00 AM 03:00 PM
      Output : Yes, you can attend the meeting

- Complexity Analysis :
  * Time Complexity : O(1)
   	     this program runs at constant time

  * Space Complexity : O(1)
	  	 Auxiliary space : O(1)  +  input space : O(1)
 */
   


<|start_filename|>Kotlin/Maths/Areas3D.kt<|end_filename|>
package kotlin.math

// Area of a Cube

fun cube(a: Double): Double {
    return 6 * a * a
}

// Area of a Cuboid

fun cuboid(l: Double, b: Double, h: Double): Double{
    return 2 * ((l*b) + (b*h) + (h*l))
}

// Area of a Cone

fun cone(r: Double, l: Double): Double{
    return (PI * r * r) + (PI * r * l)
}

// Area of a Cylinder

fun cylinder(r: Double, h: Double): Double{
    return (2.0 * (PI * r * r)) + (r * h)
}

// Area of a Sphere

fun sphere(r: Double): Double{
    return 4.0 * PI * r * r
}
// Area of a Hemi Sphere

fun hemisphere(r: Double): Double{
    return (2.0 * PI * r * r) + (PI * r * r)
}


fun main() {
    println(cube(2.0))
    println(cuboid(2.0, 4.6, 3.5))
    println(cone(5.0, 4.0))
    println(cylinder(2.0,4.0))
    println(sphere(4.5))
    println(hemisphere(2.5))
}


// Time Complexity - O(n)
// Space Complexity - O(n)


<|start_filename|>C-Plus-Plus/ds/Common_Ancestors_Of_Nodes_Of_Binary_Tree.cpp<|end_filename|>
/*

Introduction 
Given a Binary Tree , print all common ancestors of given two nodes
It is guaranteed that given Binary Tree will have all unique node values

Argument/Return Type
Input of total no.of nodes is taken
Input of key values of nodes of tree are taken in level order form 
Incase of a null node , -1 is taken as input
Function to find and print all common ancestors of given two nodes

*/

//  Code / Solution

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

//Define Node as structure
struct Node 
{
    int key;
    Node* left;
    Node* right;
};
 
// Function to create a node with 'value' as the data stored in it. 
// Both the children of this new Node are initially null.
struct Node* newNode(int value)
{
    Node* n = new Node;
    n->key = value;
    n->left = NULL;
    n->right = NULL;
    return n;
}

// Function to build tree with given input
struct Node* createTree(vector<int>v)
{
    int n=v.size();
    if(n==0) 
      return NULL;
    vector<struct Node* >a(n);
    //Create a vector of individual nodes with given node values
    for(int i=0;i<n;i++)  
    {
        //If the data is -1 , create a null node
        if(v[i]==-1)  
          a[i] = NULL;
        else 
          a[i] = newNode(v[i]);
    }
    //Interlink all created nodes to create a tree
    //Use two pointers using int to store indexes
    //One to keep track of parent node and one for children nodes
    for(int i=0,j=1;j<n;i++) 
    {
        //If the parent node is NULL , advance children pointer twice
        if(!a[i])
        {
          j=j+2;
          continue;
        } 
        //Connect the two children nodes to parent node
        //First left and then right nodes
        a[i]->left = a[j++];
        if(j<n) 
          a[i]->right = a[j++];
    }
    return a[0];
}

//Utility function to print common of both given vectors
void printCommon(vector<int>a,vector<int>b)
{
    //As ancestors are pushed in revrese order , 
    //we must print common elements of vector from reverse
   int n1=a.size()-1;
   int n2=b.size()-1;
   //Print elements from end , till they we reach least common ancestor
   while(a[n1]==b[n2])
   {
       cout<<a[n1]<<" ";
       n1--;
       n2--;
       //If we complete one vector , break and return
       if(n1<0 || n2<0)
         break;
   }
   return ;
}

//Utility Function to Generate Ancestors of the node
bool GenerateAncestors(struct Node *root, int Node_value , vector<int>& path)
{
  // base cases 
  if (root == NULL)
     return false;
  
  //If the node is found return True to its parent's node
  if (root->key == Node_value)
     return true;
  
  // If target is present in either left or right subtree of this node,
  // then print this node
  if ( GenerateAncestors(root->left, Node_value,path) ||  GenerateAncestors(root->right, Node_value,path) )
  {
     path.push_back(root->key);
     return true;
  }
  
  //If its not in either of the subtrees, return false 
  return false;
}

//Function to get ancestors of both nodes and print common of them
void FindnPrintCommonAncestorNodes(struct Node* root,int Node_1_value,int Node_2_value)
{
   vector<int>AncestorsOfNode1;
   GenerateAncestors(root,Node_1_value,AncestorsOfNode1);
   vector<int>AncestorsOfNode2;
   GenerateAncestors(root,Node_2_value,AncestorsOfNode2);
   printCommon(AncestorsOfNode1,AncestorsOfNode2);
}

// Driver code
int main()
{

    int n;
    cout<<"Enter total no.of nodes of the input Tree ( including NULL nodes ) : ";
    cin>>n;

    vector<int>v(n);
    cout<<"Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces"<<endl;
    for(int i=0;i<n;i++)
    {
        cin>>v[i]; //store the input values in a vector
    }

    int Node_1_value,Node_2_value;
    cout<<"Enter values of two nodes of tree whose common ancestors are to be found , with space : ";
    cin>>Node_1_value>>Node_2_value;

    //create the tree using input node values  
    struct Node* root=createTree(v); 


    //Call the function and print the result
    cout<<"Hence the values of common ancestor nodes of given nodes are ";
    FindnPrintCommonAncestorNodes(root,Node_1_value,Node_2_value);
    
    return 0; 
}
    
/*
Input:
0 <= node->key < 1000000000
if node is NULL , -1 is entered as it's key

Sample Test Case 1  
Input Binary Tree :                   

               1                                
           /         \                          
         2              11                    
     /       \        /   \               
    3        5       12    13             
   / \      /  \    / \   /  \            

  4 NULL    6  7    8  9 NULL  4         


Input Format : 
Example :
Enter total no.of nodes of the input Tree ( including NULL nodes ) : 15
Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces
1 2 11 3 5 12 13 4 -1 6 7 8 9 -1 4
Enter values of two nodes of tree whose common ancestors are to be found , with space : 6 7

Output Format :
Example : ( Output to the above input example ) 
Hence the values of common ancestor nodes of given nodes are 1 2 5

Sample Test Case 2  
Input Binary Tree :                   

                  12                                
          /               \                          
         9                 17                    
     /       \          /      \               
    8       10         NULL    18                                


Input Format : 
Example :
Enter total no.of nodes of the input Tree ( including NULL nodes ) : 7
Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces
12 9 17 8 10 -1 18
Enter values of two nodes of tree whose common ancestors are to be found , with space : 10 18

Output Format :
Example : ( Output to the above input example ) 
Hence the values of common ancestor nodes of given nodes are 12 

Time/Space Complexity
Time Complexity : O(n) 
   Where n is the no.of nodes 
Space Complexity : O(n) 
   Where n is the no.of nodes
*/


<|start_filename|>Java/cryptography/SimpleColumnarTranspositionCipher.java<|end_filename|>
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.ListIterator;
import java.util.Scanner;

/**
 * <h1>Columnar</h1>
 * <p>
 * Columnar class acts as a custom Data Structure which consits of a List of Characters.
 * </p>
 */
class Columnar
{
    List<Character> characterList;
}

/**
 * <h1>Simple Columnar Transposition Cipher</h1>
 * <p>
 * To Implement Simple Columnar Transposition Cipher
 * </p>
 * <b>Description</b>
 * <p>
 * class SimpleColumnarTranspositionCipher is used to encrypt plainText to cipherText using Columnar Transposition and
 * decrypt cipherText to plainText using the respective algorithm, Simple Columnar Transposition is a variation of
 * Transposition technique just like Rail Fence Cipher
 * </p>
 * <b>Requirements</b>
 * <p>
 * A string plain text and a string key are required for encryption and for decryption the cipher text which is
 * calculated from the given key and the key itself.
 * </p>
 */
public class SimpleColumnarTranspositionCipher
{
    /**
     * <p>
     * This is a private method used to validate the key provided by the user.
     * </p>
     * <b>Validation Scheme</b>
     * <p>
     * There must be NO occurance of repetative characters in a string, occurance of repetative characters can lead to
     * malfunctioning of the code and algorithm leading to mismatched output.
     * </p>
     * <p>
     * Thou same letters with different cases(UpperCase and LowerCase) can be accepted.
     * </p>
     * <p>
     * Example: AaZ can be a valid key, but AAZ will not be considered as a valid key.
     * </p>
     * 
     * @param key This is a String parameter to validateKey method, this signifies key which is passed to perform encryption
     *            and decryption.
     * 
     * @return Boolean Tells whether the key entred is a valid key or not
     */
    private Boolean validateKey(String key)
    {
        for (int i = 0; i < key.length() - 1; i++)
        {
            for (int j = i + 1; j < key.length(); j++)
            {
                // An occurance of same character in key found.
                if (key.charAt(i) == key.charAt(j))
                {
                    return false;
                }
            }
        }
        // No occurance of same character in key found.
        return true;
    }
    
    /**
     * <p>
     * This is a public method which is used to encrypt plain text using Simple Columnar Transposition technique.
     * </p>
     *
     * <b>Process</b>
     * <ul>
     * <li>The plain text is placed row-wise in the columnar table</li>
     * <li>According to the ascending order of the characters in key, its particular column is fetched and appended in
     * cipher text</li>
     * </ul>
     * 
     * @param plainText This is a String parameter to encrypt method, this signifies plain text which is passed.
     * @param key       This is a String parameter to encrypt method, this signifies key which is passed to encrypt
     *                  plainText.
     * 
     * @return String This returns the cipherText.
     */
    public String encrypt(String plainText, String key)
    {
        Columnar[]    columnars   = new Columnar[key.length()];// used to store plainText in columnar sequence given by algorithm
        StringBuilder cipherText  = new StringBuilder("");     // used to store cipher text
        Integer       columnIndex = 0;                         // used to store current column index of columnars
        
        // Initializing columnars
        for (int i = 0; i < key.length(); i++)
        {
            columnars[i] = new Columnar();
            columnars[i].characterList = new ArrayList<Character>();
        }
        
        // Iterates through plainText and stores its characters in a columnar sequence given by the algorithm
        for (int i = 0; i < plainText.length(); i++)
        {
            // It the value of columnIndex reaches to its peak then it is reassigned its value to 0, to start from a new row
            if (columnIndex == key.length())
            {
                columnIndex = 0;
            }
            
            // Adds plainText character to columnars
            columnars[columnIndex].characterList.add(plainText.charAt(i));
            
            // Incrementes the value of columnIndex by 1
            columnIndex++;
        }
        
        // sorts the characters in key in ascending order and stores it in sortedKey
        char[] keyArray = key.toCharArray();
        Arrays.sort(keyArray);
        String sortedKey = new String(keyArray);
        
        // Iterates through the columnars
        for (int i = 0; i < key.length(); i++)
        {
            char                    currentChar             = sortedKey.charAt(i);               // used to store the current character in sorted key
            int                     indexOfCurrentCharInKey = key.indexOf(currentChar);          // used to store the index of currentChar in key
            Columnar                columnar                = columnars[indexOfCurrentCharInKey];// used to get Columnar at position indexOfCurrentCharInKey
            List<Character>         characterList           = columnar.characterList;            // used to store the List of Characters in columnar
            ListIterator<Character> characterListIterator   = characterList.listIterator();      // used as an iterator for characterList
            
            // Iterates through characterList
            while (characterListIterator.hasNext())
            {
                // Appends plainText characters which were stored in columnars column wise
                cipherText.append(characterListIterator.next());
            }
        }
        
        // cipher text is retured
        return cipherText.toString();
    }
    
    /**
     * <p>
     * This is a public method which is used to decrypt cipher text using Simple Columnar Transposition technique.
     * </p>
     *
     * <b>Process</b>
     * <ul>
     * <li>As the length of cipher text and plain text is the same, we first create a placeholder columnar for getting an
     * idea of the size of each column</li>
     * <li>Arranging cipherText characters in columnar according to the size of the column</li>
     * <li>Iterating through columnar row-wise and appending each character in plain text</li>
     * </ul>
     * 
     * @param cipherText This is a String parameter to decrypt method, this signifies cipher text which is passed.
     * @param key        This is a String parameter to decrypt method, this signifies key which is passed to decrypt
     *                   cipherText.
     * 
     * @return String This returns the plainText.
     */
    public String decrypt(String cipherText, String key)
    {
        StringBuilder plainText             = new StringBuilder("");     // used to store plain text
        Columnar[]    columnars             = new Columnar[key.length()];// used to store columnar
        Columnar[]    columnarsForPlacement = new Columnar[key.length()];// used as a placeholder/template for columnars
        Integer       columnIndex           = 0;                         // used to store column index in columnars
        Integer       indexForCharacter     = 0;                         // used to store index of character in cipherText
        
        // sorts the characters in key in ascending order and stores it in sortedKey
        char[] keyArray = key.toCharArray();
        Arrays.sort(keyArray);
        String sortedKey = new String(keyArray);
        
        // Initializing columnars and columnarsForPlacement
        for (int i = 0; i < key.length(); i++)
        {
            columnars[i] = new Columnar();
            columnars[i].characterList = new ArrayList<Character>();
            columnarsForPlacement[i] = new Columnar();
            columnarsForPlacement[i].characterList = new ArrayList<Character>();
        }
        
        // Creating a placeholder for getting an idea of size of column
        for (int i = 0; i < cipherText.length(); i++)
        {
            if (columnIndex == key.length())
            {
                columnIndex = 0;
            }
            columnarsForPlacement[columnIndex].characterList.add('*');
            columnIndex++;
        }
        
        // Arranges cipherText characters according to the columnar algorithm sequence
        for (int i = 0; i < key.length(); i++)
        {
            Character               currentKeyCharacter   = sortedKey.charAt(i);                    // used to store current character in sorted key
            Integer                 indexForColumnar      = key.indexOf(currentKeyCharacter);       // used to store index of currentKeyCharacter in key
            Columnar                columnarPlaceholder   = columnarsForPlacement[indexForColumnar];// used to store Columnar at position indexForColumnar
            List<Character>         characterList         = columnarPlaceholder.characterList;      // used to store List of Characters in columnarsForPlacement
            ListIterator<Character> characterListIterator = characterList.listIterator();           // used as an iterator for characterList
            
            // Iterates through characterList
            while (characterListIterator.hasNext())
            {
                // Adds a character in cipherText at indexForCharacter to characterList
                columnars[indexForColumnar].characterList.add(cipherText.charAt(indexForCharacter));
                // Iterates over to the next element in characterListIterator
                characterListIterator.next();
                // Incrementes the value of indexForCharacter by 1
                indexForCharacter++;
            }
        }
        
        // Keeps a counter of key index
        Integer keyIndex = 0;
        
        // Iterates through cipherText
        for (int i = 0; i < cipherText.length(); i++)
        {
            // If keyIndex reaches its maximum possible limit(length of key) then it is assigned 0
            if (keyIndex >= key.length())
            {
                keyIndex = 0;
            }
            
            Columnar        columnar      = columnars[keyIndex];   // used to store Columnar of columnars at index keyIndex
            List<Character> characterList = columnar.characterList;// used to store List of Characters in columnar
            
            if (!characterList.isEmpty())
            {
                // appends characters at 0th position to plainText
                plainText.append(characterList.get(0));
                // removes the 0th character in characterList which makes it self iterative and saves space
                characterList.remove(0);
            }
            
            // Increments keyIndex by 1
            keyIndex++;
        }
        
        // plain text is retured
        return plainText.toString();
    }
    
    /**
     * This is the main method which makes use of the following methods:
     * <ul>
     * <li>encrypt</li>
     * <li>decrypt</li>
     * </ul>
     * 
     * And uses the following objects of types:
     * <ul>
     * <li>java.util.Scanner</li>
     * <li>SimpleColumnarTranspositionCipher</li>
     * </ul>
     * 
     * @param args not used
     */
    public static void main(String[] args)
    {
        
        String                            key;                                                                        // Created an object of String class for storing key to be
                                                                                                                      // entered by the user
        String                            plainText;                                                                  // Create an object of String class for storing plain text to
                                                                                                                      // be entered by the user
        Scanner                           scan                              = new Scanner(System.in);                 // Created an object of Scanner class for asking for user
                                                                                                                      // input.
        SimpleColumnarTranspositionCipher simpleColumnarTranspositionCipher = new SimpleColumnarTranspositionCipher();// Created an object of SimpleColumnarTranspositionCipher for
                                                                                                                      // accessing it's method for encryption and decryption
        
        // Asking user to enter plain text
        System.out.println("Please Enter Plain Text:");
        plainText = scan.nextLine();
        
        // Asking user to enter String key
        System.out.println("Please Enter Key:");
        key = scan.next();
        
        // Checks if the key entered is valid or not
        Boolean keyValidationStatus = simpleColumnarTranspositionCipher.validateKey(key);
        
        // If the key entered by the user is valid
        if (keyValidationStatus)
        {
            // Accessing method 'encrypt' of SimpleColumnarTranspositionCipher class to encrypt plainText by key
            String cipherText = simpleColumnarTranspositionCipher.encrypt(plainText, key);
            // Printing cipher text
            System.out.println("Cipher Text: " + cipherText);
            
            // Accessing method 'decrypt' of SimpleColumnarTranspositionCipher class to decrypt cipherText by key
            String decryptedText = simpleColumnarTranspositionCipher.decrypt(cipherText, key);
            // Printing decrypted text
            System.out.println("Decrypted Text: " + decryptedText);
        }
        // If the key entered by the user is not valid
        else
        {
            // Printing error message
            System.out.println("An Occurance of repetative characters in key is found, please enter unique characters");
        }
        
        // Closing the Scanner object scan
        scan.close();
    }
}
/*
 * OUTPUT:
 * 
 * Please Enter Plain Text:
 * 
 * Attack Alice's troops at 5:00 PM today
 * 
 * Please Enter Key:
 * 
 * ATCK13pa
 * 
 * Cipher Text: c's0aks yAlr tco:oaep0dtio5tAttM aP
 * 
 * Decrypted Text: Attack Alice's troops at 5:00 PM today
 */

<|start_filename|>Java/ds/RemDupInLLWithoutExtraSpace.java<|end_filename|>
//Java Program to Remove Duplicates from a Unsorted Linked List 
//Without using any Extra Space i.e while finding Duplicates we can't
//use any Data Structure to store values.
//Then we can use two pointers approach :current and runner ,current iterates through the linked list
//and runner check all subsequent nodes for every current and try to find duplicates in the list.

import java.util.*;
//class structure for Linked List
public class RemDupInLLWithoutExtraSpace {
  static Node head;
  class Node {
    public int data;
    public Node next;
    Node(int data) {
      this.data = data;
    }
  }
  
  //insert new node at the beginning
  public void insert_At_beginning(int data) {
    Node ptr = new Node(data);
    if (head != null) {
      ptr.next = head;
      head = ptr;
    } else {
      ptr.next = null;
      head = ptr;
    }
  }

  //check whether a Linked List is empty or not
  public boolean isEmpty() {
    if (head == null)
      return true;
    return false;
  }

  public void display() {
    Node ctr = head;
    if (!isEmpty()) {
      while (ctr != null) {
        System.out.print(ctr.data + " ");
        ctr = ctr.next;
      }
      System.out.println();
    } else {
      System.out.println("List is empty");
    }
  }

  /*
  Two pointers current and runner is used
  current will iterate through the linked list and runner will
  check all the subsequent nodes for duplicates
  */
  public void delete_Duplicates() {
    Node current = head;
    while (current != null) {
      //Remove all future nodes that have the same value
      Node runner = current;
      while (runner.next != null) {
        if (runner.next.data == current.data) {
          runner.next = runner.next.next;
        } else {
          runner = runner.next;
        }
      }
      current = current.next;
    }
  }

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    RemDupInLLWithoutExtraSpace ll = new RemDupInLLWithoutExtraSpace();

    System.out.print("Enter the size of Linked List: ");
    int size = sc.nextInt();

    System.out.println("Enter the values of the Linked List: ");
    for (int i = 0; i < size; i++) {
      ll.insert_At_beginning(sc.nextInt());
    }

    System.out.println("List with duplicates values:");
    ll.display();

    //deleting the duplicates from the Linked List if it has any 
    ll.delete_Duplicates();
    System.out.println("List after deleting duplicates:");
    ll.display();

  }
}
/**
Sample input/output:
 
Enter the size of Linked List: 5
Enter the values of the Linked List:
-2
7
1
7
5
List with duplicates values:
5 7 1 7 -2
List after deleting duplicates:
5 7 1 -2
  
Time complexity: O(n^2) for finding duplicates
Space complexity: O(n)

 */

<|start_filename|>Java/dp/CoinChangeUsingDp.java<|end_filename|>
import java.util.Scanner;

public class CoinChangeUsingDp {
	
	public static int coinChange(int[] coins, int amount) {
		
        if(amount==0) {
            return 0;
        }
        
        int n = coins.length;
        int t [][] = new int [n+1][amount+1];
        
        for(int i=0; i<amount+1; i++) {
            t[0][i] = Integer.MAX_VALUE-1;
        }
        
        for(int i=1; i<n+1; i++) {
            t[i][0] = 0;
        }
        
        for(int i=1; i<amount+1; i++) {
        	
            if(i%coins[0] == 0) {
                t[1][i] = i/coins[0];
            }
            else {
                t[1][i] = Integer.MAX_VALUE-1;
            }
        }
        
        for(int i=2; i<n+1; i++) {
        	
            for(int j=1; j<amount+1; j++) {
            	
                if(coins[i-1] <= j) {
                    t[i][j] = (1 + t[i][j-coins[i-1]]) < t[i-1][j] ? (1 + t[i][j-coins[i-1]]) : t[i-1][j];
                }
                else
                    t[i][j] = t[i-1][j];
            }
        }
        
        if(t[n][amount] == Integer.MAX_VALUE-1) {
            return -1;
        }
        else {
            return t[n][amount];
        }
    }

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		System.out.println("Please input the length of the array ");
		int size = sc.nextInt();
		int array[] = new int [size];
		System.out.println("Please input the " + size + " elements of the array ");
		for(int i=0; i<size; i++) {
			array[i] = sc.nextInt();
		}
		System.out.println("Please input the required sum ");
		int sum = sc.nextInt();
		
		System.out.println(coinChange(array, sum));
	}

}

/* 
Sample Input
5
1 2 15 25 27
30
Output
2
Explanation
Here, by using greedy algorithm, the minimum number of coins would have been 27+2+1 but using dynamic programming, the answer comes out to be 2 i.e, 15+15
*/


<|start_filename|>Kotlin/sort/RadixSort/src/RadixSort.kt<|end_filename|>
// Function to Implement Radix Sort
// The radix sorting algorithm is an integer sorting algorithm, 
// that sorts by grouping numbers by their individual digits (or by their radix).
// It uses each radix/digit as a key, and implements counting sort or 
// bucket sort under the hood in order to do the work of sorting.

// Takes an IntArray as arguments and returns a sorted IntArray to the caller function
fun radixSort(original: IntArray): IntArray {
    // Array needs to be mutable
    var old = original
    for (shift in 31 downTo 0) {
        val tmp = IntArray(old.size)
        // The number of 0s
        var j = 0
        // Move the 0s to the new array, and the 1s to the old one
        for (i in 0 until old.size) {
            // If there is a 1 in the bit we are testing, the number will be negative
            val move = (old[i] shl shift) >= 0
            // If this is the last bit, negative numbers are actually lower
            val toBeMoved = if (shift != 0) move else !move
            if (toBeMoved) {
                tmp[j++] = old[i]
            }
            else {
                // It's a 1, so stick it in the old array for now
                old[i - j] = old[i]
            }
        }
        // Copy over the 1s from the old array
        for (i in j until tmp.size) {
            tmp[i] = old[i - j]
        }
        old = tmp
    }
    return old
}

fun main(args: Array<String>) {
    print("Enter N: ");
    val n= readLine()!!.toInt();
    println("Enter array of N integers: ");
    val arrays = IntArray(n) { readLine()!!.toInt() }
    val array= radixSort(arrays);
    print("Array after Radix Sort is: ")
    for(i in array){
        print("$i ")
    }
}

/*
Time Complexity: O(log n)
Sample Input:
Enter N: 5
Enter array of N integers:
3
-1
2
3
4

Sample Output:
Array after Radix Sort is: -1 2 3 3 4
 */


<|start_filename|>Java/other/AdjacentElementProduct.java<|end_filename|>
/*Find the pair of adjacent elements that have the largest product   
 in a given array and return that product.
 
 Example: Let a={3, 6, -2, -5, 7, 3} be an array, then adjacent
 elements at position 4 & 5 i.e. 7 & 3 in the given array
 have the maximum product among adjacent elements = 21.
 Hence, the method will return 21.
 */

import java.util.*;

public class AdjacentElementProduct {
    //method to find largest adjacent elements product
    public static int largest_product(int[] arr) {
        /*let the initial max_prod be product of first two elements &
         then go on comparing it with the next adjacent element's products.
         If it is more then current max_prod value, update max_prod value. 
         */
        int max_product = arr[0] * arr[1];
        for (int i = 0; i < arr.length - 1; i++) {
            if (arr[i] * arr[i + 1] > max_product) {
                max_product = arr[i] * arr[i + 1];
            }
        }
        return max_product;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter size of the array : ");
        int n = sc.nextInt();

        int[] a = new int[n];
        System.out.print("Enter array elements : ");
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
        }

        System.out.print("Largest adjacent elements product is : " 
                         +largest_product(a));
    }
}

/*SAMPLE TEST CASE:
Enter size of the array : 10
Enter array elements : 2 -9 30 4 -8 10 11 7 -61 100
Largest adjacent elements product is : 120

Time Complexity : O(n)
Space Complexity : O(n)
*/


<|start_filename|>C-Plus-Plus/cp/SudukoSolver.cpp<|end_filename|>
/**
A backtracking algorithm to solve 9X9 suduko
0's in the input are treated empty cells
Assumption : Given configuration is correct
**/

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

#define N 9

void display(int board[N][N]){
  for(int i = 0; i < N; i++){
    for(int j = 0; j < N; j++){
      cout << board[i][j] << ' ';
    }
    cout << '\n';
  }
}

// backtracking soln
bool solve(int board[N][N], int i, int j, 
  bool rows[N][N], bool cols[N][N], bool boxes[N][3][3]) {
    
    if(i == 9)
      return true;
      
    if(board[i][j] == 0) {
        
      for(int k=0; k<9; k++) {
          
        if(rows[k][i] == false && cols[k][j] == false
          && boxes[k][i/3][j/3] == false) {
            board[i][j] = k+1;
            rows[k][i] = true;
            cols[k][j] = true;
            boxes[k][i/3][j/3] = true;
              
            if(solve(board, i+j/8, (j+1)%9, rows, cols, boxes))
              return true;
              
            board[i][j] = 0;
            rows[k][i] = false;
            cols[k][j] = false;
            boxes[k][i/3][j/3] = false;
          }
      }
      
      return false;
    } else
      return solve(board, i+j/8, (j+1)%9, rows, cols, boxes);
  }

void solveSudoku(int board[N][N], int x, int y) {
  // write yopur code here
  bool rows[N][N], cols[N][N], boxes[9][3][3];

  // intialization
  for(int i=0; i<N; i++)
    for(int j=0; j<N; j++) {
      rows[i][j] = false;
      cols[i][j] = false;
    }

  // intialization
  for(int i=0; i<N; i++)
    for(int j=0; j<3; j++)
      for(int k=0; k<3; k++)
        boxes[i][j][k] = false;
  
  for(int i=0; i<9; i++)
    for(int j=0; j<9; j++)
      if(board[i][j] != 0) {
        int num = board[i][j]-1;
        rows[num][i] = true;
        cols[num][j] = true;
        boxes[num][i/3][j/3] = true;
      }
      
  solve(board,0,0,rows,cols,boxes);
  display(board);
}

int main() {
  int arr[N][N];

  // taking input
  for (int i = 0; i < 9; i++)
    for (int j = 0; j < 9; j++)
      cin >> arr[i][j];

  solveSudoku(arr, 0, 0);
  return 0;
}

/**
Input :
3 0 6 5 0 8 4 0 0
5 2 0 0 0 0 0 0 0
0 8 7 0 0 0 0 3 1
0 0 3 0 1 0 0 8 0
9 0 0 8 6 3 0 0 5
0 5 0 0 9 0 6 0 0
1 3 0 0 0 0 2 5 0
0 0 0 0 0 0 0 7 4
0 0 5 2 0 6 3 0 0
Output :
3 1 6 5 7 8 4 9 2 
5 2 9 1 3 4 7 6 8 
4 8 7 6 2 9 5 3 1 
2 6 3 4 1 5 9 8 7 
9 7 4 8 6 3 1 2 5 
8 5 1 7 9 2 6 4 3 
1 3 8 9 4 7 2 5 6 
6 9 2 3 5 1 8 7 4 
7 4 5 2 8 6 3 1 9 
Space Complexity : O(1)
Time Complexity : O(1)
The size of input is fixed, so the complexity does not change
**/

<|start_filename|>Go/math/Automorphic_Number/automorphicnumber.go<|end_filename|>
/* This is a simple program in go language to find if a give number
   is a automorphic number or not. An automorphic number is an
   integer whose square ends with the given integer, as (25)2 = 625,
   and (76)2 = 5776.
*/

package main

import (

  "fmt"

)

// This is a global variable
var n int

// This function tells us if the number is automorphic number or not 
func automorphicnumber() {

   var number int
   var b int
   b = n
   number = n*n
   i := 1

   //to construct the last digits
   for b != 0  {

     i = i*10
     b = b/10
   }

   //checking if the last digits form the orginal number
   if((number%i) == n) {

      fmt.Print("The given number is Automorphic number!")

   }else{

     fmt.Print("The given number is not Automorphic number!")
   }

}

// driver function
func main() {

   fmt.Print("Enter the number you want to check :")
   fmt.Scan(&n)

   // calling automorphic function 
   automorphicnumber()
}

/*
   Sample I/O :

   a) Is Automorphic Number :

   Enter the number you want to check :76
   The given number is Automorphic number!

   b) Is not Automorphic Number :

   Enter the number you want to check :7
   The given number is not Automorphic number! 
*/



<|start_filename|>C-Plus-Plus/cp/Generate_all_valid_parentheses_combinations.cpp<|end_filename|>
/*
Problem statement : Given n pairs of parentheses, we have to write a function to generate all combinations of well-formed parentheses.

Constraints:

1 <= n <= 8

Approach : We will be given a number n which represents the pairs of parentheses, and we need to find out all of their valid combinations.So there are n opening brackets and n closing brackets ,and each valid combination will be of length 2*n.

A valid parentheses combination is the one where every opening parenthesis ( has its corresponding closing ).We can solve this problem using recursion by generating all the combinations of parenthesis but this will be the naive approach as it generates all the permutations.So,
The time complexity of this approach will be O(2^2n) which is quite large.

So , we can improve this by generating only those combinations which we know for sure will be valid combination and so our time complexity will reduce considerably.We can use backtracking for this purpose.We need to keep some points in mind for the combination to be valid:

1. Base case when number of opening and closing parentheses is equal to 0.
2. A closing parenthesis cannot occur before the open parenthesis.

For n = 2 , recursive tree is as follows
open denotes open parentheses count , similarly close denotes close parentheses count


                                 output_string "" {open = 2, close = 2}
                                               /
                                 choose (     /
                                             /
                                            /
                                           /
                                 output_string "(" {open = 1, close = 2}
                                            /    \
                                choose (   /      \  choose )
                                          /        \
                                         /          \
                                        /            \
       output_string "((" {open = 0,close = 2}      output_string "()" {open = 1 , close = 1}
                                \                                     /
                                 \ choose )              choose (    /
                                  \                                 /
                                   \                               /
          output_string "(()" {open = 0, close = 1}         output_string "()(" {open = 0 , close = 1}
                                \                                      \
                                 \ choose )                             \
                                  \                                      \  choose )
                                   \                                      \
          output_string "(())" {open = 0, close = 0}           output_string "()()" {open = 0, close = 0}

                             *STOP AND RETURN*                                       *STOP AND RETURN*



*/
/* Input  : an interger n
   Output : vector of strings which will store our valid parentheses combination strings.
*/

// Code part

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


// This function is used to generate all well-formed combination of parentheses

void generateParenthesis(int open, int close, string op, vector<string>&ans)
{
    // Base case : if count of open and close parentheses is both 0.

	if (open == 0 && close == 0)
	{
	 // push the output valid string combination to the answer vector and return
		ans.push_back(op);

		return;
	}

    // open bracket will always be one of the choice , given only the condition that open != 0
	if (open != 0)
	{
		string op1 = op;

    // output1 string (like we can see in recursive tree , it is the output string of when  we select '(')
		op1.push_back('(');

	// now , count of open brackets will decrease by 1 as we have used it now , and output string will be given as the op1 string now.
		generateParenthesis(open - 1 , close, op1 , ans);
	}

    //close bracket will only be chooses if its count is not 0 , i.e close != 0 and count of close parenteses > count of open parenteses, i.e close > open

    // As the closing parenthesis cannot occur before the open parenthesis for generating valid combination.

	if (close != 0 && close > open)
	{
		string op2 = op;

    // output2 string (like we can see in recursive tree , it is the output string of when  we select ')')
		op2.push_back(')');

    // now , count of close brackets will decrease by 1 as we have used it now , and output string will be given as the op2 string now.
		generateParenthesis(open, close - 1, op2, ans);
	}
}

int main()
{
	int n;

	cout << "Enter the number:" << endl;

	cin >> n;

    // this is our output vector
	vector<string>ans;

    // this represents the open parentheses count.
	int open = n;

    // this represents the close parentheses count
	int close = n;

    // this is the output string , which will be out valid parentheses combination string , initially it is empty
	string op = "";

    // let's call the function
	generateParenthesis(open, close, op, ans);

    // printing the output vector
	for (int i = 0 ; i < ans.size(); i++)
	{
		cout << ans[i] << " ";
	}
	cout << endl;

	return 0;
}

/* Time complexity:It is somewhat hard to calculate time complexity for this problem.This indicates the nth Catalan number problem (Catalan numbers are a sequence of natural numbers that occurs in many interesting counting problems) which is bounded asymptotically by 4^n/(n\sqrt(n)), where n is the atmost steps during the backtracking procedure.So the time complexity is O(4^n/sqrt(n))

Space complexity:Logic is same for atmost n steps of backtracking procedure space complexity would be O(4^n/sqrt(n)) and for storing the results O(n).

Sample test cases :

n = 3, a solution set is:
[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

n = 2, a solution set is:
[
  "()()",
  "(())"
]

n = 1, a solution set is:
[
  "()"
]

*/




<|start_filename|>Java/sort/CocktailSort.java<|end_filename|>
import java.util.*;

public class CocktailSort {

    private static void swap(int arr[], int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    private static void cocktailSort(int arr[]) {
        boolean isSwapped = true;
        int begin = 0;
        int last = arr.length-1;

        while (isSwapped == true) {
            // set isSwapped to false so that if nothing gets
            // sorted in this iteration we can break right away
            isSwapped = false;

            for(int i = begin; i < last; i++) {
                // going forward
                if (arr[i] > arr[i+1]) {
                    swap(arr, i, i+1);
                    isSwapped = true;
                }
            }

            // if nothing swapped then the array is already sorted
            if (isSwapped == false)
                break;

            // else, reset isSwapped to check for next iteration
            isSwapped = false;

            // since largest item is now in last. we only need
            // to check for one place before it
            last -= 1;

            for (int i = last; i >= begin; i--) {
                // going backward
                if (arr[i] > arr[i+1]) {
                    swap(arr, i, i+1);
                    isSwapped = true;
                }
            }

            // now the smallest number is on first place
            // so move starting point one position ahead
            begin++;
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        //taking input array
        System.out.println("Enter size of array:");
        int size = sc.nextInt();
        int arr[] = new int[size];
        System.out.println("Enter array elements:");
        for (int i=0; i<size; i++) {
            arr[i] = sc.nextInt();
        }
        sc.close();

        // before sorting
        System.out.println("Array before Cocktail sort:");
        for (int i=0; i<arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();

        cocktailSort(arr);

        // after sorting
        System.out.println("Array after Cocktail sort:");
        for (int i=0; i<arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}
/**
 * Sample input/output
 * Enter size of array:
 * 10
 * Enter array elements:
 * 88 26 77 49 91 62 33 85 99 11
 * Array before Cocktail sort:
 * 88 26 77 49 91 62 33 85 99 11 
 * Array after Cocktail sort:
 * 11 26 33 49 62 77 85 88 91 99
 * 
 * Enter size of array:
 * 7
 * Enter array elements:
 * 5 1 4 2 8 0 2
 * Array before Cocktail sort:
 * 5 1 4 2 8 0 2 
 * Array after Cocktail sort:
 * 0 1 2 2 4 5 8
 * 
 * Worst case Time complexity = O(n*n)
 * Best case Time complexity = O(n) when array is already sorted
 * Auxillary space = O(1)
 */


<|start_filename|>C-Plus-Plus/ds/Structurally_Identical_Binary_Trees.cpp<|end_filename|>
/*
Introduction 
Given two Binary Trees , Check whether they are structurally identical or not.

Argument/Return Type
Input of total no.of nodes is taken
Input of key values of nodes of tree are taken in level order form 
Incase of a null node , -1 is taken as input
*/

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

//Define Node as structure
struct Node 
{
    int key;
    Node* left;
    Node* right;
};
 
// Function to create a node with 'value' as the data stored in it. 
// Both the children of this new Node are initially null.
struct Node* newNode(int value)
{
    Node* n = new Node;
    n->key = value;
    n->left = NULL;
    n->right = NULL;
    return n;
}

// Function to build tree with given input
struct Node* createTree(vector<int>v)
{
    int n=v.size();
    if(n==0) 
      return NULL;
    vector<struct Node* >a(n);
    //Create a vector of individual nodes with given node values
    for(int i=0;i<n;i++)  
    {
        //If the data is -1 , create a null node
        if(v[i]==-1)  
          a[i] = NULL;
        else 
          a[i] = newNode(v[i]);
    }
    //Interlink all created nodes to create a tree
    //Use two pointers using int to store indexes
    //One to keep track of parent node and one for children nodes
    for(int i=0,j=1;j<n;i++) 
    {
        //If the parent node is NULL , advance children pointer twice
        if(!a[i])
        {
          j=j+2;
          continue;
        } 
        //Connect the two children nodes to parent node
        //First left and then right nodes
        a[i]->left = a[j++];
        if(j<n) 
          a[i]->right = a[j++];
    }
    return a[0];
}

//Function to check whether given two binary trees are structurally identical or not
bool IsStructurallyIdentical(struct Node* root1, struct Node* root2)
{
    //If both are null nodes , return true
    if(!root1 && !root2)
      return true;
    
    //else if one of them is a null node , return false
    if(!root1 || !root2)
      return false;

    //else recursively find if their subtrees are structurally identical
    return IsStructurallyIdentical(root1->left,root2->left) && IsStructurallyIdentical(root1->right,root2->right);
}
                
// Driver code
int main()
{
    //Input of 1st Tree
    int n1;
    cout<<"Enter total no.of nodes of the 1st input Tree ( including NULL nodes ) : ";
    cin>>n1;

    vector<int>v1(n1);
    cout<<"Enter value of each node of the 1 st Tree  in level order ( if a node is NULL , enter -1 ) with spaces"<<endl;
    for(int i=0;i<n1;i++)
    {
        cin>>v1[i]; //store the input values in a vector
    }

    //create the tree using input node values  
    struct Node* root1=createTree(v1); 


    //Input of 2nd Tree
    int n2;
    cout<<"Enter total no.of nodes of the 2nd input Tree ( including NULL nodes ) : ";
    cin>>n2;

    vector<int>v2(n2);
    cout<<"Enter value of each node of the 2nd Tree  in level order ( if a node is NULL , enter -1 ) with spaces"<<endl;
    for(int i=0;i<n2;i++)
    {
        cin>>v2[i]; //store the input values in a vector
    }

    //create the tree using input node values  
    struct Node* root2=createTree(v2);

    //Call the function and print the result
    if(IsStructurallyIdentical(root1,root2))
      cout<<"Hence the given two trees are structurally identical";
    else
      cout<<"Hence the given two trees are not structurally identical";
    
    return 0; 
}
    
/*
Input:
0 <= node->key < 1000000000
if node is NULL , -1 is entered as it's key

Sample Test Case 1  
Input Binary Tree 1:                    Input Binary Tree 1: 
               1                                       10                          
           /         \                             /         \                   
         2              11                       22            3                  
     /       \        /   \                  /       \        /   \               
    3        NULL      NULL    13           13        NULL   NULL    1                        


Input Format : 
Example :
Enter total no.of nodes of the 1st input Tree ( including NULL nodes ) : 7
Enter value of each node of the 1 st Tree  in level order ( if a node is NULL , enter -1 ) with spaces
1 2 11 3 -1 -1 13
Enter total no.of nodes of the 2nd input Tree ( including NULL nodes ) : 7
Enter value of each node of the 2nd Tree  in level order ( if a node is NULL , enter -1 ) with spaces
10 22 3 13 -1 -1 1

Output Format :
Example : ( Output to the above input example ) 
Hence the given two trees are structurally identical

Time/Space Complexity
Time Complexity : O(n) 
   Where n is the min of no.of nodes of two trees
Space Complexity : O(h) 
   Where h is the min of heights of the two trees
*/


<|start_filename|>C/cp/Adjacent_Element_Product.c<|end_filename|>
//Find the pair of adjacent elements that have the largest product in a given array and return that product.
#include <stdio.h>

void prod_elements(int *, int *, int);
int largest_product(int *, int);
int main()
{
	int num, i, arr[1000], prod[1000];
	printf("Enter the number of elements:");
	scanf("%d", &num);
	printf("Enter the elements:");
	for (i = 0; i < num; i++)
	{
		scanf("%d", &arr[i]);
	}

	printf("Array=");
	for (i = 0; i < num; i++)
	{
		printf("%d ", arr[i]);
	}

	printf("\n");
	prod_elements(prod, arr, num);
	printf("Largest Adjacent Product in the Array=%d", largest_product(prod, num));
	return 0;
}

// Putting the product of adjacent elements in a new array
void prod_elements(int *prod, int *arr, int num)
{
	int i;
	for (i = 0; i < num - 1; i++)
	{*(prod + i) = (*(arr + i)) * (*(arr + i + 1));
	}
}

// Taking out the largest product from the prod array
int largest_product(int *prod, int num)
{
	int i, big;
	big = *prod;
	for (i = 0; i < num - 1; i++)
	{
		if (big<*(prod + i))
			big = *(prod + i);
	}

	return (big);
}

/*Sample Output
Enter the number of elements:6
Enter the elements:3 6 -2 -5 7 3
Array=3 6 -2 -5 7 3
Largest Adjacent Product in the Array=21
*/



<|start_filename|>C/cryptography/Vigenere_Cipher.c<|end_filename|>
/*Vigenere Cipher Algorithm is a famous cryptographic algorithm.
Vigenère cipher is a method of encrypting alphabetic text by using a series of interwoven Caesar ciphers*/

#include <stdio.h>
#include <string.h>

char key[100];
int x;

void encryption(char message[]) {
	for (int i = 0; i < strlen(message); ++i) {
		int t=(message[i] + key[i%x])%26;
    	message[i]=('A'+t);
	}
}

void decryption(char message[]) {
	for (int i = 0; i < strlen(message); ++i) {
	    int t=(message[i] - key[i%x] +26)%26;
	    message[i]=('A'+t);
	}
}

int main() {
	char message[100];
	printf("Enter Message To Encode: ");
	scanf("%s", message);
	//use only uppercase characters (you can modify the code for lowercase characters)
	printf("\nEnter Key:");
	scanf("%s", key);
	x=strlen(key);

	printf("Generated Key: %s\n", key);
	encryption(message);
	printf("Encrypted Message: %s\n",message);

	decryption(message);
	printf("Decrypted Message: %s",message);
	return 0;
}

/*
OUTPUT
Generated Key: NEOALGO
Encrypted Message: GIGSPXOPXQOOOBTRSOLRUB
Decrypted Message: TESSERACTCODINGNEOALGO
*/


<|start_filename|>C-Plus-Plus/heap/cheapest_flights_within_k_stops.cpp<|end_filename|>
/*
	Question link :https://leetcode.com/problems/cheapest-flights-within-k-stops/
	
	There are n cities connected by m flights. 
	Each flight starts from city u and arrives at v with a price w.
	Now given all the cities and flights, together with starting city src
 	and the destination dst, 
	your task is to find the cheapest price from src to dst with up to k stops. 
	If there is no such route, output -1.

	Example :
	Input: 
	n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
	src = 0, dst = 2, k = 1
	Output: 200

*/

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

int findCheapestPrice(int n, vector<vector<int>> &flights, int src, int dst, int K)
{

    vector<vector<pair<int, int>>> a(n);
    for (vector<int> &f : flights)
        a[f[0]].push_back({f[1], f[2]});

    priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>>> pq;
    //We push the distance,source and the number of edges
    pq.push({0, src, K + 1});

    while (!pq.empty())
    {
        vector<int> t = pq.top();
        pq.pop();

        //get the distance,vertex and number of edges

        int u = t[1];
        int distance = t[0];
        int edges = t[2];

        //if the destination becomes equal to the vertex we return the  distance
        if (dst == u)
            return distance;

        //If we can add any edges
        if (edges > 0)
        {
            //We search all the neighbours and push the distance and vertex level of the neighbour
            for (pair<int, int> &v : a[u])
                pq.push({distance + v.second, v.first, edges - 1});
        }
    }
    return -1;
}

int main()
{
    int n, src, dst, k, temp;
    cin >> n >> src >> dst >> k;

    vector<vector<int>> edges(n, vector<int>(3));

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

        for (int j = 0; j < 3; j++)
        {
            cin >> edges[i][j];
        }
    }
    int price = findCheapestPrice(n, edges, src, dst, k);
    //Print the cheapest price
    cout << price;
    return 0;
}
/*
   		Time complexity:O(nlogn)
   		Space Complexity:O(n)
   */
/*
    Input:
	3 0 2 1
   
	0 1 100
	1 2 100
	0 2 500
	
	Output:
	200
	*/


<|start_filename|>Java/Algorithms/ZAlgorithm.java<|end_filename|>
import java.util.Scanner;

public class ZAlgorithm {

    public static void main(String[] args) {
        // taking the user input
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the text:");
        String text = scanner.nextLine();
        System.out.println("Enter the pattern to be searched:");
        String pattern = scanner.nextLine();
        scanner.close();

        searchPattern(text, pattern);
    }

    private static void searchPattern(String text, String pattern) {
        String concatNewStr = pattern + "$" + text;
        int[] zArr = new int[concatNewStr.length()];

        //get the z array
        getZarr(concatNewStr, zArr);

        // looping to find the array locations
        for (int i = 0; i < zArr.length; i++) {
            if(zArr[i] == pattern.length()) {
                System.out.println("Found pattern at index " + (i - pattern.length() - 1));
            }
        }
    }

    private static void getZarr(String concatNewStr, int[] zArr) {
        int n = concatNewStr.length();

        // [left,right] make a window which matches with prefix of s
        int left = 0, right = 0;

        for (int i = 1; i < concatNewStr.length(); ++i) {

            // if i>right nothing matches
            if (i > right) {

                left = right = i;

                // right-left = 0 in starting, so it will start checking from 0'th index.
                while (right < n && concatNewStr.charAt(right - left) == concatNewStr.charAt(right)) {
                    right++;
                }

                zArr[i] = right - left;
                right--;

            } else {

                // k = i-left so k corresponds to number which matches in [left,right] interval.
                int k = i - left;

                // if zArr[k] is less than remaining interval then zArr[i] will be equal to zArr[k].
                if (zArr[k] < right - i + 1) {
                    zArr[i] = zArr[k];
                } else {
                    // else start from right and check manually
                    left = i;
                    while (right < n && concatNewStr.charAt(right - left) == concatNewStr.charAt(right)) {
                        right++;
                    }
                    zArr[i] = right - left;
                    right--;
                }
            }
        }
    }
}
/*
* Sample input/output:
* Enter the text:
* AABAACAADAABAABA
* Enter the pattern to be searched:
* AABA
* Found pattern at index 0
* Found pattern at index 9
* Found pattern at index 12
*
* Time complexity and Space complexity: O(m + n), length of text be n and of pattern be m
*/


<|start_filename|>C/cp/Reverse_String_Recursion.c<|end_filename|>
/*
Program to input an string to obtain the reversal string and it's length using recursion.
*/

#include<stdio.h>
#include<string.h>

void org_str(char *str);
void rev_str(char *str);
int length(char *str);

void org_str(char *str )
{
	if(*str == '\0')
	    return;
	putchar(*str );
	org_str(str+1);
}

void rev_str(char *str )	
{
	if(*str == '\0')
	    return;
	rev_str(str+1);
	putchar(*str );
}

main( )
{
	char str[100];
	printf("Enter the string : \n");
	gets(str);
	printf("Your entered string is : \n");
	org_str( str );
	printf("\n");
	printf("The reversed string is : \n");
	rev_str(str);
	printf("\n");
	printf("The length of the string is : \n");
	printf("%d",strlen(str));
	printf("\n");
}	

/*
Enter the string :                                                                                                                                               
string                                                                                                                                                           
Your entered string is :                                                                                                                                         
string                                                                                                                                                           
The reversed string is :                                                                                                                                         
gnirts                                                                                                                                                           
The length of the string is :                                                                                                                                    
6

Time Complexity : O(n)
Space Complexity : o(1)
*/


<|start_filename|>Go/math/Catalan_Number/catalannumber.go<|end_filename|>
/*
   This is a simple program in go language to calculate the
   catalan number if give a number as input.

   formula used : Co = 1 ; Cn+1 = summation from i = 0 to n (CiCn-1)

*/

package main

import (

  "fmt"

)

/* This function calculates and returns catalan number in a 
   recursive manner */
func catalannumber(n int) int {

   var catalan int
   catalan = 0

   if (n == 0 || n ==1 ) {

       return 1

   }else {

      for i:=0;i<n;i++ {

         catalan += catalannumber(i) * catalannumber(n-i-1);

      }

   }

   return catalan

}

// driver function
func main() {

   var number int

   // Taking the input from user here
   fmt.Print("Enter the number here :")
   fmt.Scan(&number)

   var catalan int
   catalan = 0 
   // calling the catalannumber function 
   catalan = catalannumber(number)

   // Printing the catalan number
   fmt.Print("The catalan number is : ",catalan)

}

/*
   Sample I/O :

   Enter the number here :5
   The catalan number is : 42 

*/



<|start_filename|>Go/math/factorial/factorial.go<|end_filename|>
/*Below code is an implementation of factorial in Go. Factorial
of a number n is defined as:
	fact(n) = n * (n - 1) * (n - 2) ........ * 1 
The code contains a factorial function which calculates the
factorial of the number iteratively.*/

package main

import (
	"fmt"
)

// This function calculates the factorial
func factorial(number int) uint64 {

	// Decalring variable to store the factorial
	var factorial_number uint64 = 1

	if(number >= 0) {
		// Multiply 1 * 2 * .... * (n) using for loop
		for i:=1; i <= number; i++ {
			// Type conerting i to uint64 for multiplication
			factorial_number = factorial_number * uint64(i)
		}
	} else {
		// If number is negative return 0
		return 0
	}
	// Return the factorial
	return factorial_number
}

func main() {

	// Taking a number as input from the user
	var number int
	fmt.Print("Enter a number to find its factorial: ")
	fmt.Scan(&number)

	// Calling the factorial function
	var factorial_value uint64 = factorial(number)

	/* If the returned value is zero, the number is negative
	   Else, the factorial of the number is printed.*/
	if(factorial_value == 0) {
		fmt.Print("Please enter a positive number.\n")
	} else {
		fmt.Print("Factorial of ", number, " is ", factorial_value, "\n")
	}
}

/* Sample I/O:

a) 
Enter a number to find its factorial: -3
Please enter a positive number.

b)
Enter a number to find its factorial: 11
Factorial of 11 is 39916800

Time Complexity - O(n)
Space Complexity - O(1)

*/



<|start_filename|>C/other/SudokuSolver.c<|end_filename|>
/*
SudokuSolver
Given a partially filled 9×9 2D array grid[9][9], the goal is to assign digits (from 1 to 9) 
to the empty cells so that every row, column, and subgrid of size 3×3 contains exactly one instance 
of the digits from 1 to 9.
*/

#include <stdio.h>
#include <stdbool.h>
#include <math.h>

bool isSafeToPut(int mat[][9], int i, int j, int n, int number)
{
    // Check the rows and cols
    for (int k = 0; k < n; k++)
    {
        if (mat[k][j] == number)
        {
            return false;
        }
    }

    for (int k = 0; k < n; k++)
    {
        if (mat[i][k] == number)
        {
            return false;
        }
    }

    n = sqrt(n);
    int starti = (i / n) * n;
    int startj = (j / n) * n;

    for (int k = starti; k < starti + n; k++)
    {
        for (int l = startj; l < startj + n; l++)
        {
            if (mat[k][l] == number)
            {
                return false;
            }
        }
    }
    return true;
}

bool SudokuSolver(int mat[][9], int i, int j, int n)
{
    if (i == n)
    {
        // Print the sudoku
        printf("\nSolved Sudoku:\n");
        for (int k = 0; k < n; k++)
        {
            for (int l = 0; l < n; l++)
            {
                printf("%d ", mat[k][l]);
            }
            printf("\n");
        }
        printf("\n");
        return true;
    }
    if (j == n)
    {
        return SudokuSolver(mat, i + 1, 0, n);
    }
    if (mat[i][j] != 0)
    {
        return SudokuSolver(mat, i, j + 1, n);
    }
    for (int number = 1; number <= n; number++)
    {
        if (isSafeToPut(mat, i, j, n, number))
        {
            mat[i][j] = number;
            bool t = SudokuSolver(mat, i, j + 1, n);
            if (t)
            {
                return true;
            }
            mat[i][j] = 0;
        }
    }
    return false;
}

int main()
{
    int mat[9][9];
    printf("Enter elements and type 0 for empty cells:\n");
    for (int i = 0; i < 9; i++)
    {
        for (int j = 0; j < 9; j++)
        {
            scanf("%d", &mat[i][j]);
        }
    }

    SudokuSolver(mat, 0, 0, 9);

    return 0;
}

/*
Sample input/output:
Enter elements and type 0 for empty cells:
3 0 6 5 0 8 4 0 0
5 2 0 0 0 0 0 0 0
0 8 7 0 0 0 0 3 1
0 0 3 0 1 0 0 8 0
9 0 0 8 6 3 0 0 5
0 5 0 0 9 0 6 0 0
1 3 0 0 0 0 2 5 0
0 0 0 0 0 0 0 7 4
0 0 5 2 0 6 3 0 0

Solved Sudoku:
3 1 6 5 7 8 4 9 2 
5 2 9 1 3 4 7 6 8 
4 8 7 6 2 9 5 3 1 
2 6 3 4 1 5 9 8 7
9 7 4 8 6 3 1 2 5
8 5 1 7 9 2 6 4 3
1 3 8 9 4 7 2 5 6
6 9 2 3 5 1 8 7 4
7 4 5 2 8 6 3 1 9

Time complexity: O(9^(n*n))
Space Complexity: O(n*n)
*/

<|start_filename|>C/other/concatenate_two_strings.c<|end_filename|>
//C Program to concatenate two strings without using the strcat() function.
#include <stdio.h>
#include <string.h> 

int main() {
  
  char str1[100], str2[100];
  printf("Enter the first string:");
  scanf("%s", str1);
  printf("Enter the second string:");
  scanf("%s", str2); 
  int length, j;

  length = 0;
  while (str1[length] != '\0') {
    ++length;
  }

  for (j = 0; str2[j] != '\0'; ++j, ++length) {
    str1[length] = str2[j];
  }

  str1[length] = '\0';

  printf("After concatenation, Final string will be:\n ");
  puts(str1);

  return 0;
}

/*
  INPUT:
  Enter the first string:Hello
  Enter the second string:World

  OUTPUT:
  After concatenation, Final string will be:
  HelloWorld
*/

<|start_filename|>Java/cp/Anagram.java<|end_filename|>
  /*This is a java code of checking whether the Strings are anagram to each other and not...
  An anagram of a string is another string that contains the same characters,
  Only the order of characters can be different.
  In other words, Two strings are said to be anagram if we can form one string
  by arranging the characters of another string.
  For example, Race and Care. Here, we can form Race by arranging the characters of Care.
  For example, “abcd” and “dabc” are an anagram of each other.
  */
  import java.util.Scanner;
  import java.lang.String;
  public class Annagram 
  {
	
        static boolean isAnagram(String first_string, String second_string) 
	{ 
              first_string = first_string.toLowerCase();
              second_string = second_string.toLowerCase();
              boolean check = true;
              int first_length[] = new int[256];
	  
	      /* system provided the ASCII table
              which had 256 characters and each ASCII code
	      (numerical code) was assigned to one character.
              */
              
	      int second_length[] = new int[256];
              
	      for (char each_char : first_string.toCharArray()) 
	       {
                   int index = (int) each_char;
                   first_length[index]++;
               }
              
	      for (char each_char : second_string.toCharArray()) 
	       {
                   int index = (int) each_char;
                   second_length[index]++;
               }
              
	      /*
              For comparing each character from one
              String to another.
              */
              
	      for (int i = 0; i < 256; i++) 
	      {
                  if (first_length[i] != second_length[i]) 
		  {
                      check = false;
                      break;
                  }
              }
              return check;
        }
        public static void main(String[] args) 
        {
            Scanner scan = new Scanner(System.in);
            System.out.println("Please enter the first String : ");
            String first_string = scan.next();
            System.out.println("Please enter the Second String : ");
            String second_string = scan.next();
            scan.close();
            boolean ret = isAnagram(first_string, second_string);
            System.out.println((ret) ? "String are Anagrams..." : "Strings are Not Anagrams...");
        }
  }
   /*
  Time complexity is O(n)
  Space complexity is O(1)

  Input :
  Please enter the first String :
  abcd
  Please enter the Second String :
  dcab

  Output:
  String are Anagrams...
  */


<|start_filename|>Java/cp/AggressiveCows.java<|end_filename|>
import java.util.*;

public class AggressiveCow {

    private static boolean checkDist(int dist, int cows, int arr[]) {
        int cowInStall = 1;
        int lastPos = arr[0];

        // here we check if the distance we have can be minimum distance or not
        // if yes, we return true
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] - lastPos < dist) {
                continue;
            }
            if(++cowInStall == cows) {
                return true;
            }
            lastPos = arr[i];
        }

        return false;
    }

    private static int binSearch(int cows, int arr[]) {
        int left = 0;
        int right = arr[arr.length - 1] - arr[0];

        // using binary search technique to find distances
        while (left <= right) {
            int mid = left + ((right - left) / 2);

            if (checkDist(mid, cows, arr)) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        return right;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of stalls and cows:");
        int stalls = sc.nextInt();
        int cows = sc.nextInt();
        int arr[] = new int[stalls];
        System.out.println("Enter stall indexes:");
        for (int i = 0; i < stalls; i++) {
            arr[i] = sc.nextInt();
        }
        sc.close();

        // sorting array so that we can use it in Binary search
        Arrays.sort(arr);

        int result = binSearch(cows, arr);

        System.out.println("Largest minimum distance:" + result);
    }
}
/**
 * Sample input/output:
 * 
 * Enter number of stalls and cows:
 * 5 3
 * Enter stall indexes:
 * 1 2 4 8 9
 * Largest minimum distance:3
 * 
 * Enter number of stalls and cows:
 * 6 4
 * Enter stall indexes:
 * 0 3 4 7 9 10
 * Largest minimum distance:3
 * 
 * Time complexity: O(N log(N))
 * Space complexity: O(N)
 * 
 * Link to the problem: https://www.spoj.com/problems/AGGRCOW/
 */


<|start_filename|>C-Plus-Plus/stack/infixToPostfix.cpp<|end_filename|>
/*
Infix to Postfix conversion using stacks in C++
ALGORITHM:
*Scan the element from left to right
*If the scanned element is a '(' push to stack
*If scanned element is a '), pop and output contents of stack till empty or '(' is encountered
*If scanned element is an operand output it
*If scanned element is an operator, then check for precedence
*If the precedence of scanned elements is less than the precedence of the operators in the stack then pop and output
*If the precedence of scanned elements is greater than the precedence of the operators in the stack then push into stack
*/
#include <bits/stdc++.h>
using namespace std;
int prec(char x)
{
    if (x == '+' || x == '-')
        return 1;
    else if (x == '*' || x == '/')
        return 2;
}
void infixToPostfix(string s)
{
    int l = s.length();
    stack<char> st;
    string new_string = "";
    st.push('X');
    for (int i = 0; i < l; i++)
    {
        if (s[i] == '(')
            st.push(s[i]);
        else if (s[i] == ')')
        {
            while (st.top() != 'X' && st.top() != '(')
            {
                char x = st.top();
                new_string += x;
                st.pop();
            }
            if (st.top() != 'X' && st.top() == '(')
            {
                st.pop();
            }
        }
        else if (s[i] == '+' || s[i] == '*' || s[i] == '/' || s[i] == '-')
        {
            while (st.top() != 'X' && prec(st.top()) >= prec(s[i]) && st.top() != '(')
            {
                new_string += st.top();
                st.pop();
            }
            st.push(s[i]);
        }
        else
        {
            new_string += s[i];
        }
    }
    while (st.top() != 'X')
    {
        new_string += st.top();
        st.pop();
    }
    cout << new_string << "\n";
}
int main()
{
    string s;
    cin >> s;
    infixToPostfix(s);
}
/*
Time Complexity: O(n^2)
INPUT:
a+b+(c*d)
OUTPUT:
ab+cd*+
*/


<|start_filename|>Java/cp/Duplicate_word.java<|end_filename|>
    /*This is a java code for removing duplicate words from sentence.
    remove instances of words that are repeated more than once,
    but retain the first occurrence of any case-insensitive repeated word
    For example, Sam went went to to to his school, will become Sam went to his school.
    For example, Hello hello Ab aB, will change to Hello Ab.
    */
    import java.lang.String;
    import java.util.Scanner;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;

    public class Duplicate_word
    {
    public Duplicate_word(String input, Pattern p)
    {
        Matcher m = p.matcher(input);
        // Check for subsequences of input that match the compiled pattern
        while (m.find())
        {
             input = input.replaceAll(m.group(), m.group(1));
        }
        // Prints the modified sentence.
        System.out.println(input);
    }
    public static void main(String[] args)
    {
          String regex = "\\b(\\w+)(?:\\W+\\1\\b)+";
          Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
          Scanner in = new Scanner(System.in);
          System.out.println("Please enter how many sentences you want correct : ")
          int numSentences = Integer.parseInt(in.nextLine());
          System.out.println("Please enter your sentence...")
          while (numSentences-- > 0)
          {
              String input = in.nextLine();
              Duplicate_word s = new Duplicate_word(input, p);
          }
          in.close();
    }
    }
    /*
    Time complexity is O(n)
    Space complexity is O(1)

    Input :
    Please enter how many sentences you want correct :
    5
    Please enter your sentence...
    Goodbye bye bye world world world.
    Sam went went to to to his business.
    Reya is is the the best player in eye eye game.
    in inthe.
    Hello hello Ab aB

    Output:
    Goodbye bye world
    Sam went to his business
    Reya is the best player in eye game
    in inthe
    Hello Ab
    */


<|start_filename|>C/math/happy_number.c<|end_filename|>
//C Program to check a number is Happy Number or not.
#include <stdio.h>

int happy_number(int);
int main()
{
	int n, ans;
	printf("Enter a number: ");
	scanf("%d", &n);
	ans = happy_number(n);
	if (ans == 1)
		printf("%d is a happy number", n);
	else
		printf("%d is not a happy number", n);
	return 0;
}

// Function to check if the number is a happy number or not
int happy_number(int n)
{
	int temp = n;
	int sum = 0, digit;
	while (sum != 1 && sum != 4)
	{
		sum = 0;
		while (temp != 0)
		{
			digit = temp % 10;
			sum += digit * digit;
			temp = temp / 10;
		}

		temp = sum;

	}

	return sum;
}

/*
Sample Output:
Enter a number: 32
32 is a happy number.

Complexities
Time Complexity:O(logn)
Space Complexity:O(1)
*/



<|start_filename|>C/ds/Priority_Queue_using_Linked_List.c<|end_filename|>
/*
AIM :: To implement Priority Queue (PQ) using Linked List (LL).

            WHAT IS PRIORITY QUEUE ?
A priority queue is an abstract data type that behaves similarly to the normal queue except that each element has some priority, 
i.e., the element with the highest priority would come first in a priority queue. 
The priority of the elements in a priority queue will determine the order in which elements are removed from the priority queue.

*/

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

struct node
{
    int data;          //for storing data
    int prior;         // for storing priority of the data
    struct node *next; // for storing next node's address
} * front;
typedef struct node PQ;

//protorypes
void enq();     // for insertion
void deq();     // for deletion
void display(); // for display

int main()
{
    int choice;
    printf("\n\t\tPRIORITY QUEUE IMPLEMENTION USING LINKED LIST\n\n");
    while (1)
    {
        printf("\nMAIN MENU\n");
        printf("1. ENQ\n2. DEQ\n3. DISPLAY\n4. EXIT\n");
        printf("Enter your choice :: ");
        scanf("%d", &choice);

        switch (choice)
        {
        case 1:
            enq();
            break;

        case 2:
            deq();
            break;

        case 3:
            display();
            break;

        case 4:
            printf("\nexiting...\n");
            exit(0);
            break;

        default:
            printf("\nINVALID CHOICE :(\n");
            break;
        }
    }
    return 0;
}

void enq()
{
    // creating new node
    PQ *new_node = (PQ *)malloc(sizeof(PQ));
    new_node->next = NULL;

    //take data and priority of that data form the user
    printf("\nenter data: ");
    scanf("%d", &new_node->data);

    printf("\nenter priority of %d: ", new_node->data);
    scanf("%d", &new_node->prior);

    // if queue is full then insert the new node at the beginning
    if (front == NULL || new_node->prior < front->prior)
    { // insertion at beginning
        new_node->next = front;
        front = new_node;
    }
    else
    {
        PQ *temp = front;

        //finding the appropriate position and insert the new node there
        while (temp->next != NULL && temp->next->prior <= new_node->prior)
            temp = temp->next;

        new_node->next = temp->next;
        temp->next = new_node;
    }
    display();
}

void deq()
{
    //if queue is already empty then display error message
    if (front == NULL)
        printf("\nPRIORITY QUEUE IS EMPTY :(\n");
    else
    {
        PQ *temp = front;

        //every time deleting the first
        front = front->next;
        temp->next = NULL;
        free(temp);

        display();
    }
}

void display()
{
    if (front == NULL)
        printf("\npriority queue is empty :(\n");
    else
    {
        //temp_data to store and display the data of queue while traversing
        PQ *temp_data = front;

        //temp_priority to store and display the priority of data that are being displayed
        PQ *temp_priority = front;

        // displaying data in queue
        printf("\nQUEUE     :: ");
        while (temp_data != NULL)
        {
            printf("%d  ", temp_data->data);
            temp_data = temp_data->next;
        }

        // displaying priority of all the data in the queue
        printf("\nPRIORIOTY :: ");
        while (temp_priority != NULL)
        {
            printf("%d  ", temp_priority->prior);
            temp_priority = temp_priority->next;
        }
        printf("\n");
    }
}

/*
TEST CASE

               PRIORITY QUEUE IMPLEMENTION USING LINKED LIST

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 1
Enter the data :: 30
Enter priority of 30 :: 2

DATA     :: 30
PRIORITY :: 2

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 1
Enter the data :: 10
Enter priority of 10 :: 1

DATA     :: 10    30
PRIORITY :: 1     2

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 2

DATA     :: 30
PRIORITY :: 2

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 4

Exiting...

TIME COMPLEXITY
    INSERTION :: O(n)
    DELETION :: O(n)
    DISPLAY  :: O(n)
*/


<|start_filename|>C-Plus-Plus/ds/Shortest_Distance_Between_Nodes_Of_BST.cpp<|end_filename|>
/*
Introduction 
Given a Binary Search Tree ,Find the shortest distance between given two nodes , which exist in the tree

Argument/Return Type
Input of total no.of nodes is taken
Input of key values of nodes of tree are taken
*/

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

//Define Node as structure
struct Node 
{
    int key;
    Node* left;
    Node* right;
};
 
// Function to create a node with 'value' as the data stored in it. 
// Both the children of this new Node are initially null.
struct Node* newNode(int value)
{
    Node* n = new Node;
    n->key = value;
    n->left = NULL;
    n->right = NULL;
    return n;
}

// Function to insert a node with given value to the root
struct Node* insert(struct Node* root,int element) 
{
    //If the root is NULL , create a node with given element and assign it to root
    //else if the root itself is the node with given data , return 
    //else recursively insert it in one of the subtrees accordingly
    if(root==NULL)
        root = newNode(element);
    else if(root->key < element)
        root->right = insert(root->right,element);
    else if(root->key > element)
        root->left = insert(root->left,element);
    
    return root;
}

//Function to find least common ancestor
struct Node* leastCommonAncestor(struct Node* root,int node_1_value,int node_2_value)
{
   //If both the given value nodes lie in left subtree of the root
   //Find LCA in left subtree recursively 
   if(node_1_value<root->key && node_2_value<root->key)
      return leastCommonAncestor(root->left,node_1_value,node_2_value);

  //Else If both the given value nodes lie in right subtree of the root
  //Find LCA in right subtree recursively 
   if(node_1_value>root->key && node_2_value>root->key)
      return leastCommonAncestor(root->right,node_1_value,node_2_value);

  //Else it means that one node is in left subtree and one node is in right sub tree
  //return root
   return root;
} 

//Utility function to find distance between a node and its ancestor
int ShortestDistanceUtill(struct Node* root,int value)
{
    //If root itself is the node with given value return 0
    //else recursively calculate distance between corresponding subtree by adding a edge (+1)
    if (root->key == value)
        return 0;
    else if (root->key > value)
        return 1 + ShortestDistanceUtill(root->left, value);
    return 1 + ShortestDistanceUtill(root->right, value);
}

//Function to find shortest distance of nodes with given values in the given tree
int ShortestDistance(struct Node* root,int node_1_value,int node_2_value)
{
  //Finf out the least common ancestor of given two nodes
   struct Node* LCA;
   LCA = leastCommonAncestor(root,node_1_value,node_2_value);

  //If least common ancestor is not found , return -1
   if(LCA==NULL)
     return -1;

   //Now calculate distance between given nodes by the formula below
   return ShortestDistanceUtill(LCA,node_1_value)+ShortestDistanceUtill(LCA,node_2_value);
} 

// Driver code
int main()
{
    int n;
    cout<<"Enter total no.of nodes of the input Tree ( including NULL nodes ) : ";
    cin>>n;

    //create a null node  and initialise it as a NULL node
    struct Node* root;
    root=NULL;
    
    cout<<"Enter value of each node of the Tree , with head as the first value ( if a node is NULL , enter -1 ) with spaces"<<endl;
    for(int i=0;i<n;i++)
    {
        int data;
        cin>>data; 
        //take input of data of each node and insert it in the root
        root = insert(root,data);
    }

    cout<<"Enter two node values of the given Tree : ";
    int node_1_value,node_2_value;
    cin>>node_1_value>>node_2_value;

    //Call the function and print the result
    cout<<"Hence the shortest distance between given two nodes is : "<<ShortestDistance(root,node_1_value,node_2_value);
    
    return 0; 
}
    
/*
Input:
0 <= node->key < 1000000000
While entering node values of the tree , 
value of the head of the tree should be enetered first

Sample Test Case 1  
Input Binary Tree 1:                    
            11                                                             
          /     \                                             
         2      20                                      
        / \    /  \                           
       1   5 NULL 25                                

Input Format : 
Example :
Enter total no.of nodes of the input Tree ( including NULL nodes ) : 6
Enter value of each node of the Tree , with head as the first value ( if a node is NULL , enter -1 ) with spaces
11 2 20 1 5 25
Enter two node values of the given Tree : 5 25

Output Format :
Example : ( Output to the above input example ) 
Hence the shortest distance between given two nodes is : 4

Time/Space Complexity
Time Complexity : O(n) 
   Where n is the no.of nodes ofthe tree
Space Complexity : O(h) 
   Where h is the height of the tree
*/


<|start_filename|>Java/cp/Maximum_Function.java<|end_filename|>
/*
 - Maximum Function (in Java) :
     A sequence is given A1,A2,…,An (atleast 3 elements you need to give)
     Find the maximum value of the expression |Ax − Ay|+|Ay − Az|+|Az − Ax|
     over all triples of pairwise distinct valid indices (x,y,z).

 - Approach :
     1. We need to sort the given array
     2. To find maximum difference of two elements we will subtract 1st element with the last element of the array (|Ax − Ay|)
     3. Next, we can take middle element as 2nd element of the array (Az)
     4. That means, Ax = 1st element of the sorted array, Ay = last element, Az = 2nd element
     5. Therefore, adding |Ax − Ay|+|Ay − Az|+|Az − Ax| will give maximum result everytime
 */

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

class MaximumFunction {
	//main method
	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		System.out.println("Enter number of elements you want in array");
		//Input the number of elements you want in the array
		long n = sc.nextLong();

		//Creating array of n Elements
		long[] array = new long[(int)n];

		System.out.println("Enter all the elements");
		//putting elements in the array
		for(long t = 0 ; t<n ; t++) {
			array[(int)t] = sc.nextLong();
		}
		//sorting the array
		Arrays.sort(array);
		//calculating max
		long max = Math.abs(array[0] - array[1]) + Math.abs(array[1] - array[(int)n-1]) + Math.abs(array[(int)n-1] - array[0]);
		//printing max
		System.out.println("Result = " + max);
	}
}
/*
 - Test Cases :
    1.  Input : Enter number of elements you want in array
                10
                Enter all the elements
                7 5 3 9 1 2 7 3 8 9
       Output : Result = 16

 - Complexity Analysis :
    * Time Complexity : O(n)
         We are using only one for loop, so it iterates maximum 'n' times while traversing for loop

    * Space Complexity : O(n)
         Auxiliary space : O(1)  +  input space : O(n)
 */
 


<|start_filename|>Julia/math/check_palindrome.jl<|end_filename|>
""" Julia program to Check if a number is a Palindrome Number or not.
A palindrome number is a number such that the reverse of the number is equal to the number itself 
"""

function check_palindrome(num)
    temp = num
    rev = 0
    while (temp > 0)
        rem = temp % 10
        rev = (rev * 10) + rem
        temp = temp ÷ 10;
    end
    if (num == rev)
        return true
    else
        return false
    end
end


print("Enter the number: ")
num = readline()
num = parse(Int, num)
res = check_palindrome(abs(num))
if res
    println("The given number $num is a Palindrome Number.")
else
    println("The given number $num is not a Palindrome Number.")
end


"""
Time Complexity: O(log(num)), where 'num' is the given number
Space Complexity: O(1)

SAMPLE INPUT AND OUTPUT

SAMPLE 1
Enter the number: 121
The given number 121 is a Palindrome Number.

SAMPLE 2
Enter the number: 1234
The given number 1234 is not a Palindrome Number.

"""


<|start_filename|>C-Plus-Plus/stack/palindromic_list.cpp<|end_filename|>
/* Code to check if a linked list is palindromic or not using stacks
OBJECTIVE:
1. Push the data of each node into the stack(LIFO)
2. Pop each element of the stack and compare with the linked list element
*/
#include <bits/stdc++.h>
using namespace std;
struct Node
{
    int data;
    Node *next;
};
void push(Node **head, int new_data)
{
    Node *temp = new Node();
    temp->data = new_data;
    temp->next = *head;
    *head = temp;
}
int checkPalin(Node *head)
{
    stack<int> s;
    Node *temp = head;
    while (temp != NULL)
    {
        s.push(temp->data);
        temp = temp->next;
    }
    Node *ref = new Node();
    ref = head;
    while (ref != NULL)
    {
        int i = s.top();
        s.pop();
        if (i != ref->data)
        {
            return -1;
        }
        ref = ref->next;
    }
    return 1;
}
//Driver code
int main()
{
    int n;
    cout<<"Enter the length of the list";
    cin>>n;
    int a[n];
    cin>>a[0];
    Node *head = new Node();
    head->data = a[0];
    head->next = NULL;
    for(int i=1;i<n;i++)
    {
        cin>>a[i];
        push(&head,a[i]);
    }
    cout << checkPalin(head) << "\n";
}
/*
Time Complexity:O(n)
INPUT: 
Enter the length of the list3
1
2
1
OUTPUT:
1
*/


<|start_filename|>Java/cp/FirstNegativeNumber.java<|end_filename|>
/**
 * First Negative Integer in Every Window of Size K
 * Java program to find the first negative integer in each subarray 
 * of fixed size K, given an array of integers, using the 'Sliding 
 * Window Technique'. In case there is no negative integer in given
 * window, print 0.  
 */

import java.io.*;
import java.util.*;

public class FirstNegativeNumber {

    public static String findFirstNegativeNumber(int[] numArray, int K) {
        String str = ""; 

        //The ArrayDeque contains indices of all negative integers in a given 
        //window, with the first element being the index of first negative
        //integer in given window.  
        ArrayDeque<Integer> adeque = new ArrayDeque<>(); 
		for(int i=0; i<K; i++){
		    if(numArray[i] < 0)
		        adeque.add(i);
		}
 
		for(int i=K-1; i < (numArray.length-1); i++) {

            //If ArrayDeque is not empty, then its first element is the index
            //of first negative integer in the current window. Once our window 
            //crosses this index, we remove it from the deque. 
		    if(!adeque.isEmpty()) {
		        str += (numArray[adeque.peek()] + " "); 
		        if(adeque.peek() <= (i-K+1))
		            adeque.removeFirst(); 
		    } else {
                //When there is no negative integer in the window
		        str += "0 "; 
		    }

            //Checking if the element added for the next window is negative
		    if(numArray[i+1] < 0) 
		        adeque.add(i+1); 
		}

        // For printing the first negative integer of last window
		if(adeque.isEmpty()) 
		    str += "0 "; 
		else 
		    str += (numArray[adeque.peek()] + " "); 
		
		return str;
    }
    public static void main (String[] args) throws IOException {
	    InputStreamReader read = new InputStreamReader(System.in);
	    BufferedReader buf = new BufferedReader(read); 

        //Taking input from user
        System.out.println("Enter length of array of integers: ");
	    int len = Integer.parseInt(buf.readLine());
        System.out.println("Enter array of integers: ");
	    StringTokenizer st = new StringTokenizer(buf.readLine());
	    int numArray[] = new int[len];
	    for(int i=0; i<len; i++) {
	        numArray[i] = Integer.parseInt(st.nextToken()); 
	    }
        System.out.println("Enter size of window: ");
	    int K = Integer.parseInt(buf.readLine()); 
	    
        //Printing output String 
        System.out.println("String of first negative number for each subarray of size "
                        + K + ": "); 
        System.out.println(findFirstNegativeNumber(numArray, K)); 
	}
}

/*
    Time complexity: O(N)
    Space complexity: O(K) (as maximum number of negative integers 
    stored in ArrayDeque at any point of time = K)

    TEST CASES

    INPUT
    Enter length of array of integers: 
    10
    Enter array of integers: 
    3 4 -1 6 7 8 -3 -1 0 12
    Enter size of window: 
    3
    OUTPUT
    String of first negative number for each subarray of size 3:
    -1 -1 -1 0 -3 -3 -3 -1

    INPUT
    Enter length of array of integers: 
    9
    Enter array of integers: 
    -1 2 0 3 -2 -1 -2 10 8
    Enter size of window: 
    5
    OUTPUT
    String of first negative number for each subarray of size 5:
    -1 -2 -2 -2 -2 

 */


<|start_filename|>Go/ds/linked_list/singly_linked_list_reversed/singly_linked_list_reversed.go<|end_filename|>
/*
 reverse linked list is an implimention of a singly linked list with an algorithm to reverce the order of the list
*/
package main

import (
	"fmt"
)

type Node struct {
	value int
	next  *Node
}

type List struct {
	head *Node
	tail *Node
	size int
}

// makeLinkedList: creates an empty linked list
func makeLinkedList() List {
	var node *Node = nil
	l := List{node, node, 1}
	return l
}

// createAtFront: create a node at the front of the list with the value the passed in int
func (list *List) createAtFront(data int) {
	var node Node
	node.value = data
	node.next = list.head
	if list.tail == nil {
		list.tail = &node
	}
	list.head = &node
	list.size++
	fmt.Printf("created a node with the value %d at the frount of the list\n", data)
}

// printList: prints out the linked list from head to tail.
// func (list *List) printList() {
// 	currentNode := list.head
// 	for currentNode != nil {
// 		fmt.Printf("%d ", currentNode.value)
// 	}
// }

// printList: prints out the linked list from head to tail
func (list *List) printList() {
	currentNode := list.head
	for currentNode != nil {
		fmt.Printf("%d->", currentNode.value)
		currentNode = currentNode.next
	}
	fmt.Printf("\n")
}

// reverseLinkedList: reverses the linked list
func (list *List) reverseLinkedList() {
	// grabs first node in the list
	currentNode := list.head
	// setting up the previous node
	var prev *Node = nil
	// grabs the next node in the list
	next := currentNode.next
	// while not at the end of the list
	for currentNode != nil {
		// takes the next node after the current node
		next = currentNode.next
		// swap the current nodes next node to previous
		currentNode.next = prev
		// the new previous becomse the old previous
		prev = currentNode
		// the current node becomes the next node
		currentNode = next
	}
	// the lists tail is now the head
	list.tail = list.head
	// the lists head is now the last not nil node
	list.head = prev
	fmt.Println("successfully reversed the linked list")
}

// fillListWithDummyData: add's values 1 - 9 to the linked list by calling create at frount 9 times
func (list *List) fillListWithDummyData() {
	for i := 0; i < 10; i++ {
		list.createAtFront(i)
	}
	fmt.Println("added to the list with numbers 0-9")
}

func main() {
	list := makeLinkedList()
	userInput := 0
	shouldRun := true
	// I used the format from the other linked list in go to keep consistency between the two programs
	for shouldRun == true {
		fmt.Printf("1 -> insert element at front\n")
		fmt.Printf("2 -> insert dummy data\n")
		fmt.Printf("3 -> print linked list\n4 -> reverse linked list\n")
		fmt.Printf("4 -> reverse linked list\n")
		fmt.Printf("5 -> quit\n")
		for userInput <= 0 && userInput <= 5 {
			fmt.Scanf("%d", &userInput)
		}
		switch userInput {
		case 1:
			var value int
			fmt.Scanf("%d", &value)
			list.createAtFront(value)
			break
		case 2:
			list.fillListWithDummyData()
			break
		case 3:
			list.printList()
			break
		case 4:
			list.reverseLinkedList()
			break
		case 5:
			shouldRun = false
			break
		}
		userInput = 0
		fmt.Printf("\n\n")
	}
}


<|start_filename|>Java/cryptography/caeserCipher.java<|end_filename|>
import java.util.*;
class caeserCipher
{
    static String encrypt( String str , int n )
    {
        String s1 = "";
        for(int indexI = 0; indexI < str.length(); indexI++)
        {
            s1 = s1 + (char)((str.charAt(indexI) - 65 + n) % 26 + 65);
        }
        return s1; 
    }
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a string to encrypt");
        String str = sc.nextLine();
        System.out.println("Enter a integer");
        int n = sc.nextInt();
        str = str.toUpperCase();
        String encryptedString, decryptedString;
        encryptedString =  encrypt(str,n);
        decryptedString =  encrypt(encryptedString,(26-n));
        System.out.println("Encrypted String " + encryptedString);
        System.out.println("Decrypted String " + decryptedString);
    }
}

/* 
Enter a string to encrypt
quick
Enter a integer
3
Encrypted String TXLFN
Decrypted String QUICK
*/


<|start_filename|>C-Plus-Plus/ds/Merge_sorted_lists.cpp<|end_filename|>
/*
in this problem we will have to merge two sorted linked list and will have to make a single list.
the list will be made by joining together the nodes of first two lists
*/
#include <iostream>
using namespace std;

//structure
class node{
    public:
        int data;
        node* next;

    //constructor
    node(int data){
        this->data = data;
        this->next = NULL;
    }    
};

// this function is for inserting nodes in each list
void insertAtTail(node* &head,int data)
{
    node* n = new node(data);
	if (head==NULL){
		head = n;
		return;
	}

	node* temp = head;
	while(temp->next != NULL) {
	    temp = temp->next;
	}
	temp->next = n;
}

// this function is the main function for merging two sorted linked list
node* merge(node* a, node* b)
{
    if(a == NULL){
        return b;
    }
    else if(b == NULL){
        return a;
    }
    node* c;
    //Compare a and b for smaller element
    if(a->data < b->data){
        c = a;
        c->next = merge(a->next, b);
    }  
    else{
        c = b;
        c->next = merge(a, b->next);        
    }  
    return c;
}

// Print function
void print(node* head)
{
    node* temp = head;
    while(temp != NULL)
    {
        cout<<temp->data<<" ";
        temp = temp->next;
    }
    cout<<endl;
}

// driver code
int main() {
    
        node* head1 = NULL;
        node* head2 = NULL;
        long long int n1,n2;
        // size of first list
        cin>>n1;
        // input nodes of first list
        while(n1--){
            int no;
            cin>>no;
            insertAtTail(head1,no);
        }
        // size of second list
        cin>>n2;
        // input nodes of second list
        while(n2--){
            int no;
            cin>>no;
            insertAtTail(head2,no);
        }  

        // head of new list that will be created
        node* head3 = merge(head1,head2);

        //printing new list
        print(head3);      
    
}
/* 
input - 
3
1 2 4
3
1 2 3
output - 
1 1 2 2 3 4 

Time Complexity - O(n)
Space Complexity - O(1)
*/


<|start_filename|>C-Plus-Plus/ds/SLL_Operations_Usnig_Unique_Key.cpp<|end_filename|>
/*
This is singly linked list implementation in which 
a unique key has to be given while entering the new node to the linked list,
and you cannot give same key to the different node.
*/

#include <iostream>
using namespace std;

class Node
{
public:
	int key; //key = index of particular node in linked list
	int data;
	Node *next;

	Node()
	{
		key = 0;
		data = 0;
		next = NULL;
	}
	Node(int k, int d)
	{
		int key = k;
		int data = d;
	}
};

class sll
{
public:
	Node *head;

	sll()
	{
		head = NULL;
	}
	sll(Node *n)
	{
		head = n;
	}

	// nexist : checks wether node exist in the linked list or not
	Node *nexist(int k) //k= key value
	{
		Node *temp = NULL;
		Node *ptr = head;

		while (ptr != NULL)
		{
			if (ptr->key == k)
			{
				temp = ptr;
			}
			ptr = ptr->next;
		}
		return temp;
	}

	// appendnode : adds the new node at the end of the linked list
	void appendnode(Node *n) //n= new node
	{
		if (nexist(n->key) != NULL)
		{
			cout << "Entered node exist " << n->key << endl;
		}
		else
		{
			if (head == NULL) //assuming that node is empty
			{
				head = n;
				cout << "Node appended" << endl;
			}
			else //assuming that node stores some data
			{
				Node *ptr = head;
				while (ptr->next != NULL)
				{
					ptr = ptr->next;
				}
				ptr->next = n;
				cout << "Node appended " << endl;
			}
		}
	}

	// prependnode : adds the node at the head of the linked list
	void prependnode(Node *n)
	{
		if (nexist(n->key) != NULL)
		{
			cout << "Node already exist = " << n->key << endl;
		}
		else
		{
			n->next = head;
			head = n;
			cout << "Node prepended " << endl;
		}
	}

	// insertnode : insert new node in the middle of the linked list.
	void insertnode(int k, Node *n)
	{
		Node *ptr = nexist(k);
		if (ptr == NULL) //checking wether the entered key node exist or not
		{
			cout << "No node exist with this key value = " << k << endl;
		}
		else
		{
			if (nexist(n->key) != NULL)
			{
				cout << "Node already exist with same key value = " << n->key << endl;
			}
			else
			{
				n->next = ptr->next;
				ptr->next = n;
				cout << "Node inserted " << endl;
			}
		}
	}

	// dnode : to delete the node from the linked list
	void dnode(int k)
	{
		if (head == NULL)
		{
			cout << "Node is empty " << endl;
		}
		else if (head != NULL)
		{
			if (head->key == k) // assuming that the head is being deleted
			{
				head = head->next;
				cout << "Node deleted " << endl;
			}
			else //assuming that any middle or last node is being is deleted
			{
				Node *temp = NULL;
				Node *prevptr = head;
				Node *currentptr = head->next;
				while (currentptr != NULL)
				{
					if (currentptr->key == k)
					{
						temp = currentptr;
						currentptr = NULL;
					}
					else
					{
						prevptr = prevptr->next;
						currentptr = currentptr->next;
					}
				}
				if (temp != NULL)
				{
					prevptr->next = temp->next;
					cout << "Node deleted " << k << endl;
				}
				else
				{
					cout << "No node exist with " << k << " value " << endl;
				}
			}
		}
	}

	// updatenode : by this you have to update the data entered in linked list
	void updatenode(int k, int d)
	{
		Node *ptr = nexist(k);
		if (ptr != NULL)
		{
			ptr->data = d;
			cout << "Node data updated successfully " << endl;
		}
		else
		{
			cout << "Node doesn't exist " << k << " value " << endl;
		}
	}

	// printlist : it prints the linked list
	void printlist()
	{
		if (head == NULL)
		{
			cout << "Node is empty " << endl;
		}
		else
		{
			cout << "\nSingly linked list values are " << endl;
			Node *temp = head;

			while (temp != NULL)
			{
				cout << "(" << temp->key << "," << temp->data << ")-->"
					 << " ";
				temp = temp->next;
			}
			cout << "NULL";
		}
	}
};

int main()
{
	sll s;
	int option;
	int key1, k1, data1;

	do
	{
		cout << "\nWhat operation you want to perform " << endl;
		cout << "1 Append the node or insert the node " << endl;
		cout << "2 Add the node in the begining " << endl;
		cout << "3 Insert the node in between " << endl;
		cout << "4 Delete the node " << endl;
		cout << "5 Update or make correction in the node " << endl;
		cout << "6 Print the node " << endl;
		cout << "7 Clear the screen\n"<< endl;

		cin >> option;
		Node *n1 = new Node();

		switch (option)
		{
		case 0:
			break;
		case 1:
			cout << "Append node operation choosed " << endl;
			cout << "Enter the key " << endl;
			cin >> key1;
			cout << "Enter the data " << endl;
			cin >> data1;
			n1->key = key1;
			n1->data = data1;

			s.appendnode(n1);
			break;
		case 2:
			cout << "Prepend operation choosed " << endl;
			cout << "Enter the key " << endl;
			cin >> key1;
			cout << "Enter the data " << endl;
			cin >> data1;
			n1->key = key1;
			n1->data = data1;

			s.prependnode(n1);
			break;
		case 3:
			cout << "Insert node operation selected " << endl;
			cout << "Enter the key after which you want to insert " << endl;
			cin >> k1;
			cout << "Enter the key " << endl;
			cin >> key1;
			cout << "Enter the data " << endl;
			cin >> data1;
			n1->key = key1;
			n1->data = data1;

			s.insertnode(k1, n1);
			break;
		case 4:
			cout << "Delete node operation selected " << endl;
			s.printlist();
			cout << "Enter the key to be deleted " << endl;
			cin >> k1;
			s.dnode(k1);
			break;
		case 5:
			cout << "Update operation selected " << endl;
			cout << "Enter the key " << endl;
			cin >> key1;
			cout << "Enter the NEW data " << endl;
			cin >> data1;

			s.updatenode(key1, data1);
			break;
		case 6:
			s.printlist();
			break;
		case 7:
			system("cls");
			break;
		default:
			cout << "Enter the proper option : " << endl;
		}
	} while (option != 0);
	{
		cout << "Thank you !!" << endl;
	}
	return 0;
}

/*

Test Case 1 :
input : 1 1 12 2 2 34 3 1 3 24 6
outout: (2,34)--> (1,12)--> (3,24)--> NULL

Test case 2:
input: 1 1 100 1 2 101 4 2 6
outout: (1,100)--> NULL

*/

/*
Time complexity - O(n)

Space complexity - O(n)
*/



<|start_filename|>C/ds/StackUsingQueue.c<|end_filename|>
/* C Program to implement a Stack using Queue.Here we will try to realise STACK
    using the properties OR functions of QUEUE and by making pop operation
   costly*/

#include <malloc.h>
#include <stdio.h>

struct Node {
  int data;
  struct Node *next;
};

/*Maintaining a front,rear pointer
 where insertion takes place at rear end and deletion at front
 and O(1) time is taken  for insertion by maintaining a rear pointer
*/
struct Node *front = NULL, *rear = NULL;
// Store size of queue
int qsize = 0;

// check whether queue is empty or not
int isEmpty(struct Node *q) {
  if (q == NULL) {
    // return true i.e Queue is empty
    return 1;
  }
  return 0;
}

// Enqueue i.e insert at the REAR end
int enQueue(int item) {
  struct Node *q;
  // creation of new node
  q = (struct Node *)malloc(sizeof(struct Node));
  q->data = item;
  q->next = NULL;

  /* If queue is empty
  i.e front is pointing to NULL update front*/
  if (front == NULL) {
    front = q;
  } else {
    (rear)->next = q;
  }

  rear = q;
  // increase current queue size
  qsize++;
  return 0;
}

// Dequeue i.e delete at the FRONT end
int deQueue() {
  int delElement;
  /*Queue is empty
  dequeue not possible*/
  if (isEmpty(front)) {
    return -1;
  } else {
    // store the dequeued element
    delElement = front->data;
    (front) = (front)->next;

    if ((front) == NULL) {
      (rear) == NULL;
    }
    // reduce the current queue size
    qsize--;
  }
  return delElement;
}

void push(int data) { enQueue(data); }

int pop() {
  int i, element;
  /* dequeue upto n-1 elements in the queue
     and enqueue the respective dequeued element
         at the REAR end of the queue*/
  for (i = 0; i < qsize - 1; i++) {
    element = deQueue();
    enQueue(element);
  }
  /* dequeue the element which will be first value of the STACK
   and return the element*/
  element = deQueue();
  if (element == -1) {
    printf("\n Stack is empty");
    return 0;
  }

  return element;
}

void display(struct Node *temp) {

  while (temp != NULL) {
    printf("%d ", temp->data);
    temp = temp->next;
  }
}

int main() {

  int i, val, size;
  printf("Enter the size: ");
  scanf("%d", &size);

  printf("Enter the numbers:\n");
  for (i = 0; i < size; i++) {
    scanf("%d", &val);
    push(val);
  }

  printf("Stack size:%d\n", qsize);
  printf("Popped Elements are:\n");
  while (qsize > 0) {
    printf("\n%d ", pop());
  }
  printf("\nStack size:%d", qsize);
  return 0;
}

/*
  Sample input/output:
  Enter the size: 5
  Enter the numbers:
  1
  2
  3
  4
  5
  Stack Size:5
  Popped Elements are:
  5
  4
  3
  2
  1
  Stack Size:0

  Time complexity: O(1) for push, O(n) for pop
  Space complexity: O(n)
 */


<|start_filename|>C-Plus-Plus/cryptography/Homophonic_Cipher.cpp<|end_filename|>
#include<bits/stdc++.h>
using namespace std;

//Mapping one plain-text alphabet to more than one cipher-text alphabet.
void mapping(vector<vector<char> > &code) {    
	code[0].push_back('Q');code[0].push_back('4');
	code[1].push_back('W');
	code[2].push_back('E');
	code[3].push_back('R');
	code[4].push_back('T');code[4].push_back('5');code[4].push_back('9');code[4].push_back('0');
	code[5].push_back('Y');
	code[6].push_back('U');
	code[7].push_back('I');
	code[8].push_back('O');code[8].push_back('8');
	code[9].push_back('P');
	code[10].push_back('A');
	code[11].push_back('S');
	code[12].push_back('D');
	code[13].push_back('F');code[13].push_back('7');
	code[14].push_back('G');code[14].push_back('2');
	code[15].push_back('H');
	code[16].push_back('J');
	code[17].push_back('K');
	code[18].push_back('L');code[18].push_back('1');
	code[19].push_back('Z');code[19].push_back('6');
	code[20].push_back('X');
	code[21].push_back('C');
	code[22].push_back('V');
	code[23].push_back('B');
	code[24].push_back('N');
	code[25].push_back('M');	
}

/* Encodes characters of plain text by one of the 
several different cipher text letters using a map. */
string encode(string plain) {
	
	vector<vector<char> >code(26);
	mapping(code);
	string encrypted = "";
	int n = plain.length();
	for(int i = 0;i < n; ++i) {
		//if lowercase character
		if(plain[i] >= 97) {
			int num = (rand() % (code[plain[i] - 97].size()));
			
			if(code[plain[i]-97][num] >= 65)
				encrypted = encrypted+char(code[plain[i]-97][num]- 65 + 97);
			else
				encrypted = encrypted+code[plain[i]-97][num];
		}
		//uppercase letter
		else {
			int num = (rand() % (code[plain[i]-65].size()));
			encrypted = encrypted+code[plain[i]-65][num];
		}
	}
	
	return encrypted;
}

int main(){
	
	vector<vector<char> >code(26);
	mapping(code);
	
	string plain,encrypt;
	cout<<"Enter the plain text: ";
	cin>>plain;
	
	encrypt = encode(plain);
	cout<<"Cipher Text: "<<encrypt<<endl;
	
}

/* Mapping used: 
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Q W E R T Y U I O P A S D F G H J K L Z X C V B N M
4       5       8         7 2       1 6            
        9                                          
        0                         

Example:
Plain Text : TESSERACTCODING
Cipher Text: 60LL5KQEZE2R87U

Plain Text : NeoAlgo
Cipher Text: 70gQsug

Time Complexity: O(n)
Space Complexity: O(1)                  
*/

<|start_filename|>C-Sharp/cryptography/vigenere_cipher.cs<|end_filename|>
/* Vigenere Cipher in C# */

using System; 
      
class Vigenere_Cipher  
{ 
    static String generateKey(String str, String key) 
    { 
        int x = str.Length; 
        for (int i = 0; ; i++) 
        { 
            if (x == i) 
                i = 0; 
            if (key.Length == str.Length) 
                break; 
            key+=(key[i]); 
        } 
        return key; 
    } 
  
    static String cipherText(String str, String key) 
    { 
        String cipher_text="";     
        for (int i = 0; i < str.Length; i++) 
        { 
            int x = (str[i] + key[i]) %26;    
            x += 'A';     
            cipher_text+=(char)(x); 
        } 
        return cipher_text; 
    } 
  
    static String originalText(String cipher_text, String key) 
    { 
        String orig_text="";     
        for (int i = 0 ; i < cipher_text.Length && i < key.Length; i++) 
        { 
            int x = (cipher_text[i] - key[i] + 26) %26; 
            x += 'A'; 
            orig_text+=(char)(x); 
        } 
        return orig_text; 
    } 
    
    public static void Main(String[] args)  
    { 
        String str;; 
        String word; 
        Console.WriteLine("Enter a string:");
        str = Console.ReadLine(); 
            
        Console.WriteLine("Enter a pattern word:"); 
        word = Console.ReadLine(); 
            
        String key = generateKey(str, word); 
        String cipher_text = cipherText(str, key); 
    
        Console.WriteLine("Ciphertext: " + cipher_text); 
        Console.WriteLine("Decrypted Text: " + originalText(cipher_text, key)); 
    } 
} 

/* OUTPUT

Enter a string:                                                                                                                               
HACKINCODES                                                                                                                              
Enter a pattern word:                                                                                                                         
HACK                                                                                                                                     
Ciphertext: OAEUCAWYULS                                                                                                                  
Decrypted Text: HACKINCODES 
  
*/  

<|start_filename|>C/ds/Finding_a_pair_of_element.c<|end_filename|>
/*
This progarm is about finding a pair of element with sum k using hash table in a
Unsorted array.
Here user going to give an input of k value based upon the input the code will
check whether all the possible pair sum from the array
is equal to k value or not.

Ex:-
array = {1,7,4,2,3} , K = 5

1 + 7 != 5
1 + 4  = 5
1 + 2 != 5
...
...
...
2 + 3  = 5

The above array is unsorted. The code will take up all the possible pair
from the array. It will keep on going
until array becomes empty and it will add up those pair from
array and check whether the pair of sum and k is equal or not.
If it is equal then it will show in the output screen else not.

*/
#include <stdio.h>
#include <stdlib.h>
// Define a structure for an array.
struct Array {
  int *A;
  int size;
};
void pairwithsumhash(struct Array arr) {
  int i, greatestno = 0, smallestno = 32767;
  int *H;
  int k;
  printf("Enter the sum of k:");
  scanf("%d", &k);
  for (i = 0; i < arr.size; i++) {
    // Checking for greatestno in the array
    if (arr.A[i] > greatestno)
      greatestno = arr.A[i];
    // Checking for smallestno in the array
    if (arr.A[i] < smallestno)
      smallestno = arr.A[i];
  }
  H = (int *)malloc((greatestno + 1) * sizeof(int));
  // Defining hash table size as per the greatestno
  for (int i = 0; i < greatestno + 1; i++)
    H[i] = 0;
  // Incrementing hash table for every array value.
  for (int i = 0; i < arr.size; i++)
    H[arr.A[i]] = 1;
  for (i = 0; i < arr.size; i++) {
    // Checking whether it is pair or not.
    if ((k - arr.A[i]) >= 0 && H[k - arr.A[i]] != 0) {
      // Printing the result if condition satisfies.
      printf("%d+%d=%d\n", arr.A[i], k - arr.A[i], k);
      // Decrementing hash table
      H[arr.A[i]]--;
    }
  }
  free(H);
  H = NULL;
}
int main() {
  struct Array arr;
  int ch, i;
  printf("Enter Size of Array");
  scanf("%d", &arr.size);
  arr.A = (int *)malloc(arr.size * sizeof(int));
  printf("Enter the array elements");
  for (i = 0; i < arr.size; i++) {
    scanf("%d", &arr.A[i]);
  }
  do {
    printf("\n1. Find a pair of element with sum k using hash in a Unsorted "
           "array: \n");
    printf("2. Exit\n");
    printf("enter you choice ");
    scanf("%d", &ch);
    switch (ch) {
    case 1:
      printf("Pair of Elements with sum k using hash table in a unsorted "
             "array: \n");
      pairwithsumhash(arr);
      break;
    }
  } while (ch < 2);
  free(arr.A);
  arr.A = NULL;
  return 0;
}

// Output:-
/*
Enter Size of Array5
Enter the array elements4
2
1
3
8

1. Find a pair of element with sum k using hash in a Unsorted array:
2. Exit
enter you choice 1
Pair of Elements with sum k using hash table in a unsorted array:
Enter the sum of k:5
4+1=5
2+3=5

*/



<|start_filename|>C-Plus-Plus/math/Euler's_Totient_function.cpp<|end_filename|>
// Euler's Totient Function represented by F(n)
// denotes the no. of coprime of n from 1 to n
#include <bits/stdc++.h>
using namespace std;
int F(int n){
    int arr[n + 1], i, j;
    arr[0] = 0, arr[1] = 1;     // as 1 is coprime with itself
    for(i = 2; i <= n; i ++){
     arr[i] = i;    // initialising arr[i] with i
     }  
    for(i = 2; i <= n; i ++){
        if(arr[i] == i){
            for(j = i; j <= n; j += i){
                arr[j] -= (arr[j] / i); // just like sieve of eratosthenes we are decreasing values of multiple of primes
            }  
        }
    }
    return arr[n];  //  here each arr[i] is giving number of coprimes of i from 1 to i
}

int main(){
    int n;
    cout<<"Enter a integer: " ;
    cin>>n;   // taking input as integer n
    cout<<F(n); // printing Euler's Totient Function for int n
return 0;
}
// time complexity O(nloglogn) same as sieve of eratosthenes
/*
Sample Input: 4
Sample Output: 2
Explanation: As 4 is coprime with 1 and 2 only so its Euler's Totient function value is 2;

Sample Input: 5
Sample Output: 4
Explanation: As 5 is a prime no. so it is coprime with all 1, 2, 3 & 4.
             So, its Euler's Totient Function value is 4;

*/


<|start_filename|>C/sort/OPtimizBubble_Sort.c<|end_filename|>
/*Bubble Sort Algorithm is the sorting algorithm in which each element is compared to its adjacent element 
and if first elememt is greater than second element ,then the swapping occurs.
The swapping occurs till the array is sorted.
*/

#include <stdio.h>
#include <stdbool.h>

void swap(int *, int *);
bool optimised_bubble(int[], int);
int main()
{
	int size, arr[size], temp;
	//Reading Input
	printf("Input :\n");
	printf("Enter the size of an array : \n");
	scanf("%d", &size);
	printf("Enter the elements of an array :\n");
	for (int index = 0; index < size; index++)
	{
		scanf("%d", &arr[index]);
	}

	optimised_bubble(arr, size);
	//Displaying Output
	printf("Output :\n");
	printf("The sorted array is :\n");
	for (int index = 0; index < size; index++)
	{
		printf("%d ", arr[index]);
	}

	return 0;
}

// Function to sort the array in an optimised way
bool optimised_bubble(int arr[], int size)
{
	int index;
	bool sort = true;
	for (int index = 0; index < size; index++)
	{
		for (int j = 0; j < size - 1 - index; j++)
		{
			if (arr[j] > arr[j + 1])
			{
				swap(&arr[j], &arr[j + 1]);
				sort = false;
			}
		}

		if (sort)
		{
			break;
		}
	}
}

// Function to swap two numbers
void swap(int *a, int *b)
{
	int temp;
	temp = *a;
	*a = *b;
	*b = temp;
}

/*
 Input:
 Enter the size of an array: 5
 Enter the elements of an array :
 7 9 8 2 4
 Output :
 2 4 7 8 9
 Time Complexity :  O(n)
 Space Complexity : O(1)
*/



<|start_filename|>C-Sharp/cp/LengthOfLongestSubstring.cs<|end_filename|>
public class Solution
{
	/*

	Given a string, return the length of the longest substring WITHOUT repeating characters.

	Samples...
	Example 1:
		Input: "abcabcbb"
		Output: 3
		Explanation: The answer is "abc", with the length of 3.

	Example 2:
	    Input: "bbbbb"
	    Output: 1
	    Explanation: The answer is "b", with the length of 1.

	Example 3:
	    Input: "pwwkew"
	    Output: 3
	    Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

	Algorithm complexity analysis:
	This is the sliding window solution for the 'Longest Substring without Repeating Characters' problem, which is far more efficient than the naive brute force approach.

	Time complexity: O(n), where n is the length of the input string.
	Space complexity: O(k), where k is the number of unique characters in the input string.

	*/

	public int LengthOfLongestSubstring(string s)
	{
		// pointers to the substring without duplicating characters
		int left = 0, right = -1;
		// length of the longest substring
		int longest_length = 0;
		// dictionary (HashMap) for storing indices of characters in the string
		Dictionary<char, int> d = new Dictionary<char, int>();


		for (int i = 0; i < s.Length; i++)
		{
			// get current char from string
			char c = s[i];

			// check if the char is already present in dictionary's keys. If not, then, add the character into our longest substring (by updating the right pointer to our sliding window)

			// If yes, then, check if the char is part of our CURRENT longest substring. If not, then, add the character into our longest substring
			if ((!d.ContainsKey(c)) || (d[c] < left))
			{
				d[c] = i;
				right += 1;
			}
			else
			{
				// If a repeating char is encountered, then update the left pointer to our current sliding window that tracks the current longest substring
				left = d[c] + 1;
				right += 1;
				d[c] = i;
			}

			// length of the current sliding window
			int length = (right - left) + 1;
			if (length > longest_length)
			{
				// update longest_length so far
				longest_length = length;
			}

		}

		return longest_length;
	}
}


<|start_filename|>C-Plus-Plus/dp/maxSquareMatrixWithOnes.cpp<|end_filename|>
#include <bits/stdc++.h>
using namespace std;

int maxSizeSquareWithOnes(int** input, int row, int col, int i, int j, int* ans, int** output){
    if(i == 0 || j == 0){
        output[i][j] = input[i][j];
        return input[i][j];
    }
    if(i < 0 || j < 0)
        return INT_MAX;
    if(output[i][j] > -1)
        return output[i][j];
    int option1 = maxSizeSquareWithOnes(input, row, col, i-1, j, ans, output);
    int option2 = maxSizeSquareWithOnes(input, row, col, i-1, j-1, ans, output);
    int option3 = maxSizeSquareWithOnes(input, row, col, i, j-1, ans, output);
    int res = min(option1, min(option2, option3));
    if(input[i][j] == 1)
        res++;
    if(input[i][j] == 0)
        res = 0;
    *ans = max(*ans, res);
    output[i][j] = res;
    return res;
}

int main()
{
    int row,col;
    cout << "Enter number of rows and colums: " << endl;
    cin >> row >> col;
    int** input = new int*[row];
    int** output = new int*[row];
    cout << "Enter elements for input matrix: " << endl;
    for(int i = 0; i < row; i++){
        input[i] = new int[col];
        output[i] = new int[col];
        for(int j = 0; j < col; j++){
            cin >> input[i][j];
            output[i][j] = -1;
        }
    }

    int ans = INT_MIN;
    maxSizeSquareWithOnes(input, row, col, row-1, col-1, &ans, output);
    cout << "Size of Maximum Square Matrix with all 1s is: " << ans << endl;

    for(int i = 0; i < row; i++){
        delete[] input[i];
        delete[] output[i];
    }
    delete[] input;
    delete[] output;
    return 0;
}

/*
Sample input/output:
Enter number of rows and colums:                                                                                                
6 5                                                                                                                             
Enter elements for input matrix:                                                                                                
0 1 1 0 1                                                                                                                       
1 1 0 1 0                                                                                                                       
0 1 1 1 0                                                                                                                       
1 1 1 1 0                                                                                                                       
1 1 1 1 1                                                                                                                       
0 0 0 0 0                                                                                                                       
Size of Maximum Square Matrix with all 1s is: 3 

Time complexity = O(rows * cols)
Space complexity = O(rows * cols)
*/

<|start_filename|>C-Plus-Plus/sort/Quotient-Remainder_Sort.cpp<|end_filename|>
/*
Implementation of Quotient-Remainder Sorting algorithm (non-negative numbers only) in C++
*/

#include <bits/stdc++.h>
#include <vector>
#include <list>
#include <utility>

using namespace std;

// Function for QR-Sort Algorithm implementation.
vector < int64_t > func(vector < int64_t > a, int64_t n) {
    vector < int64_t > ans;
    // Vector (v) of list of pair of type { arr[i] / n , arr[i]}.
    //  The index of vector represents remainder.
    vector < list < pair < int64_t, int64_t >>> v(n);
    for (int64_t i = 0; i < n; i++) {
        int64_t r = a[i] % n;
        v[r].push_back(make_pair(a[i] / n, a[i]));
    }
    // Add delimiter {-1,-1} for each index in the vector
    for (int64_t i = 0; i < n; i++) {
        v[i].push_back(make_pair(-1, -1));
    }
    // Run the loop until the size of output array is not equal to input array.
    while (ans.size() != n) {
        for (int64_t i = 0; i < n; i++) {
            while (!v[i].empty()) {
                pair < int64_t, int64_t > p = v[i].front();
                v[i].pop_front();
                if (p.first == -1) {
                    // Delimiter found break the loop
                    break;
                } else {
                    if (p.first == 0) {
                        // Add the array element in the output array
                        ans.push_back(p.second);
                    } else {
                        int64_t r1 = p.first % n;
                        int64_t q1 = p.first / n;
                        v[r1].push_back(make_pair(q1, p.second));
                    }
                }
            }
        }
        // Adding delimiter for next pass.
        for (int64_t i = 0; i < n; i++) {
            v[i].push_back(make_pair(-1, -1));
        }
    }
    return ans;
}

int main() {
    int64_t n;
    cout << "Enter input size" << "\n";
    cin >> n;
    vector < int64_t > a(n);
    vector < int64_t > ans;
    cout << "Enter input array:" << "\n";
    for (int64_t i = 0; i < n; i++) {
        cin >> a[i];
    }
    cout << "\n";
    if (n != 1) {
        ans = func(a, n);
    } else {
        ans.push_back(a[0]);
    }
    cout << "Output array:" << "\n";
    for (int64_t i = 0; i < n; i++) {
        cout << ans[i] << " ";
    }
    cout << "\n";
    return 0;
}

/*
   Sample example:
   Enter input size:
   5
   Enter input array:
   15 2 89 0 3
   Output array:
   0 2 3 15 89

   Time Complexity:-
         T(n)= { O(1) if n=1,
                 O(n*log(m base n) +n) if n>1
               }
   Space Complexity = O(2*n)
*/


<|start_filename|>C-Plus-Plus/cp/long_factorials.cpp<|end_filename|>
/*Finding huge factorials such as !100, !1000 is sometimes required but in languages such as C++
the datatypes are not even capable of storing such a big number. We could achieve calculation of
such a number via going back to the basis of how we used to muiltiply two numbers back in school days. 
We used to muiltiply numbers and would add the summation and get the final result. 
This program here uses a vector to store each particular digit in a single index of the vector. 
The carry is forwarded as basic maths and in the end the complete result gets stored in the vector*/

//The length of vector should be >= length of the resultant factorial

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

/*The function takes a number and muiltiplies the number in the school's old fashioned way 
where we muiltiply the complete digit by one digit and then add the results to get the final 
resultant. The carry is carried forwarded and in the end the final result gets stored in the 
array/vector. */

void factorial(int val)
{
    int carry = 0;       
    vector <int> arr(10000, 0);   
    arr[0] = 1;                   
    int k = 0;                         

    for(int i = 1; i <= val; i++) {
        for(int j = 0;j <= k; j++) {      
            arr[j] = arr[j] * i + carry;
            carry = arr[j] / 10;
            arr[j] = arr[j] % 10;
        }
        while(carry) {        
            k++;
            arr[k] = carry % 10;
            carry /= 10;
        }   
    }
    for(int i = k; i >= 0; i--) {  
        cout<<arr[i];
    }
    cout << "\n";
}
int main() {
    int num;
    cin>>num;
    factorial(num);
    return 0;
}

/*Sample test case 
Input: 15
Output: 1307674368000

Time Complexity = O(N)
Space Complexity = O(1)
 */



<|start_filename|>Java/cp/RemoveDuplicateElement.java<|end_filename|>
import java.util.Scanner;

public class RemoveDuplicateElement {

    /**
     *
     * Method 1 Using extra space
     *
     */



//     The function remove the duplicate element
//     Function take two argument array 'a' of size 'n'.
    static int DuplicateElement(int[] a, int n){

//        check if array is empty or it has only 1 element

        if (n==0 || n==1)
            return n;

//        Now we create an temporary array of  size an
//        it stores the unique element

        int[] temp = new int[n];

        int j=0;

//        start traversing the array

        for (int i=0; i<n-1; i++){
            // If current element is not equal
            // to next element then store that
            // current element

            if (a[i] != a[i+1]){

                temp[j++] = a[i];

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

//        modify original array

        for (int i=0; i<j; i++){
            a[i] = temp[i];
        }
        return j;
    }

    public static void main(String[] args) {
        
        // taking the input from the user
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the length of the array : ");
        int n = sc.nextInt();
        
        int a[] = new int[n];
        System.out.println("Enter the values for the array elements : ");
        // taking the values for the array from the user
        for(int i=0; i<n; i++)
        {
            a[i] = sc.nextInt();
        }

        n = DuplicateElement(a,n);

//        print the updated array
        for (int i=0; i<n; i++){
            System.out.print(a[i] + " ");
        }

    }

}

/*

Example : 

Input:
Enter the length of the array : 4
Enter the values for the array elements : 
1 1 2 2

Output:
1 2

*/


<|start_filename|>C/math/Sieve_of_Eratosthenes.c<|end_filename|>
/*Sieve_of_eratosthenes
  Sieve of Eratosthenes is an ancient algorithm for finding all prime numbers up to any given limit.
  It does so by iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with
  the first prime number, 2. The multiples of a given prime are generated as a sequence of numbers starting from that prime,
  with constant difference between them that is equal to that prime.*/

//Header files
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

void Sieve_of_eratosthenes(int n)
{
    // Creating an array for storing prime factors.
    // and if the i is not prime, mark it as 0 else 1
    int prime[n + 1];

    // Initialising all elements as 1
    for (int i = 2; i <= n; i++)
        prime[i] = 1;

    for (int i = 2; i * i <= n; i++)
    {
        // If prime[i] is marked 1, then it is a prime.
        if (prime[i] == 1) 
        {
            // Marking all multiples of i as 0
            for (int j = i * i; j <= n; j += i)
                prime[j] = 0;
        }
    }

    // Printing all the prime numbers
    for (int i = 2; i <= n; i++)
        if (prime[i])
        {
            printf("%d ", i);
        }
}
/**
 * Optimized version of Sieve of Eratosthenes using Dynamic Memory Allocation and using Boolean.
 */
void sieve(int N, bool * isprime) 
{
    isprime[0] = true;
    isprime[1] = true;
  
    // eliminating multiples of i 
    for (int i = 2; i * i <= N; ++i)
    {
        if (!isprime[i]) 
        {
            for (int j = i * i; j <= N; j = j + i) 
            {
                isprime[j] = true;
            }
        }
    }
    // Printing all the prime numbers
    for (int i = 1; i <= N; i++) 
    {
        if (!isprime[i]) 
        {
            printf("%d ", i);
        }
    }
    printf("\n ");
}

// Driver Function
int main() {
    int num;
    printf("Enter the number: \n");
    scanf("%d", & num);
    printf("The prime numbers smaller than or equal to %d are: \n", num);
    Sieve_of_eratosthenes(num);

    //Implementation of Optimized version of Sieve of Eratosthenes
    printf("\n Using optimized version of code: \n");
    bool * isprime = (bool * ) malloc(num * sizeof(bool));
    sieve(num, isprime);
    free(isprime);
    return 0;
}

/*Sample Input:
  Enter the number: 10
  
  Sample Outut:
  The prime numbers smaller than or equal to 10 are: 
  2 3 5 7 
  Using optimized version of code:
  2 3 5 7 
*/


<|start_filename|>C-Plus-Plus/cp/Check_for_Subsequence.cpp<|end_filename|>
#include <iostream>
using namespace std;

int main() {
	int t;
	cin >> t;
	while (t--) {
		int i = 0, j = 0;                                  //i will point str1 and j will point str2
		string str1, str2;                                 //str1 is substring
		cin >> str1 >> str2;                               //str2 is full string
		while (i < str1.length() && j < str2.length()) {
			if (str1[i] == str2[j]) {
				i++;
			}
			j++;
		}
		if (i == str1.length()) {
			cout << "Yes, str1 is substring of str2";
		}
		else {
			cout << "No, str1 is not substring of str2";
		}
		cout << endl;
	}
	return 0;
}

/*Time Complexity: O(n)
Input:
2
WGA AWRGNA
QBR EQVBA
Output:
Yes, str1 is substring of str2
No, str1 is not substring of str2
*/


<|start_filename|>C-Plus-Plus/ds/Leaf_Nodes_BST.cpp<|end_filename|>
/* COUNT OF LEAF NODES IN BINARY SEARCH TREE
    Binary Search Tree is a special type of binary tree where
    1. The value of all the nodes in the left sub-tree is less than or equal to the value of the root.
    2. The value of all the nodes in the right sub-tree is greater than value of the root.
    3. This rule will be recursively applied to all the left and right sub-trees of the root.

    Leaf node is a node which does not have left or right child
    No. of leaf nodes varies with the order in which the nodes are inserted
*/

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

// Declare treeNode with data , rc (right child) and lc (left child )
typedef struct treeNode
{
    int data;
    struct treeNode *lc;
    struct treeNode *rc;
} treeNode;

//to insert a node into BST
treeNode *insertIntoTree(treeNode *root, int data)
{
    //If tree is empty insert as root node
    if (root == NULL)
    {
        treeNode *ptr;
        ptr = new treeNode;
        ptr->data = data;
        ptr->lc = NULL;
        ptr->rc = NULL;
        root = ptr;
    }
    else
    {
        // insert recursively in accordance with BST properties
        if (root->data >= data)
        {
            root->lc = insertIntoTree(root->lc, data);
        }
        else if (root->data < data)
        {
            root->rc = insertIntoTree(root->rc, data);
        }
    }
    return root;
}

//to count the leaf nodes
int leaf_nodes(treeNode *root)
{
    //Initially count of leaf nodes is set as 0
    static int count=0;
    //If tree is not empty
    if (root)
    {
        //If the node doesn't have any child increment count
        if (root->lc == NULL && root->rc == NULL)
            count++;
        else
        {
            //recursively check left and right sub-trees
            if (root->lc)
                leaf_nodes(root->lc);
            if (root->rc)
                leaf_nodes(root->rc);
        }
    }
    return count;
}

// driver code
int main()
{
    //Initialize tree as empty
    treeNode *root;
    root = NULL;
    int n, data;
    //Accept the no. of elements and elements as user input
    scanf("%d", &n);

    for (int i = 0; i < n; i++)
    {
        scanf("%d", &data);
        root = insertIntoTree(root, data);
    }

    printf("\nNo. of leaf nodes in the binary search tree = %d", leaf_nodes(root));
    printf("\n");
    return 0;
}

/*
    Sample input:
    7
    1 6 2 5 3 8 4

    Sample output:
    No. of leaf nodes in the binary search tree = 2
*/

/*
    Time complexity : O(n)
    Space complexity : O(n)
*/



<|start_filename|>C-Plus-Plus/graphs/Adjacency_List.cpp<|end_filename|>
/* ADJACENCY LIST FOR REPRESENTING DIRECTED GRAPH
    It is a method of representing a digraph using 2 linked lists
        1. Node list
        2. Edge list corresponding to each node
    Edges arising from a node are stored in edge list of each node
*/

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

/* Declare a structure for representing digraph with data and 2 links
 * link represents the edge between the parent node and next node (edge list)
 * pnext point to the next node from which new edges arise(node list)
 * g points to the graph
*/
typedef struct AdjacencyList
{
    int data;
    struct AdjacencyList *link, *pnext;
} AdjacencyList;
AdjacencyList *g;

//to insert into the graph
void insert_to_graph(AdjacencyList *g, int parent, int value)
{
    //ptr points to the first node in the graph
    AdjacencyList *ptr = g->link, *p;
    //Check if the graph is empty
    if (g->link == NULL)
    {
        // ptr stores the value of parent node
        ptr = new AdjacencyList;
        ptr->data = parent;
        ptr->pnext = NULL;
        ptr->link = NULL;
        g->link = ptr;
    }
    else
    {
        //Search for parent in the node list
        while (ptr != NULL && ptr->data != parent)
        {
            p = ptr;
            ptr = ptr->pnext;
        }
        //If parent is not found in the node list insert as last node
        if (ptr == NULL)
        {
            ptr = new AdjacencyList;
            ptr->data = parent;
            ptr->pnext = NULL;
            ptr->link = NULL;
            p->pnext = ptr;
        }
    }
    //insert value in the edge list of parent node
    AdjacencyList *node;
    node = new AdjacencyList;
    node->data = value;
    node->link = NULL;
    node->pnext = NULL;
    //Traverse till the end of the edge list
    while (ptr->link != NULL)
        ptr = ptr->link;
    //Insert value as the last node in the edge list
    ptr->link = node;
}

//To delete a node from the graph
void delete_from_graph(AdjacencyList *g, int value)
{
    //Set flag as 0 assuming value is not present in the graph
    int flag = 0;
    //If the graph is not empty
    if (g->link != NULL)
    {
        //ptr points to first node
        AdjacencyList *ptr = g->link, *p, *pre;
        //If the first node in the node list is value
        if (ptr->data == value)
        {
            g->link = ptr->pnext;
            flag = 1;
        }
        else
        {
            //Traverse the node list till value is found
            while (ptr->pnext != NULL && ptr->data != value)
            {
                p = ptr;
                ptr = ptr->pnext;
            }
            //If value is found delete node and entire edge list of the node
            if (ptr->data == value)
            {
                p->pnext = ptr->pnext;
                flag = 1;
            }
        }
        ptr = g->link;
        //Traverse till the end of the node list
        while (ptr != NULL)
        {
            p = ptr;
            //traverse the edge list of p till value is found
            while (p->link && p->data != value)
            {
                pre = p;
                p = p->link;
            }
            // If value is found in the edge list of p delete edge
            if (p->data == value)
            {
                pre->link = p->link;
                flag = 1;
            }
            ptr = ptr->pnext;
        }
    }
    //If flag is 0 value in not present in the graph
    if (flag == 0)
        printf("Node %d does not exist !\n", value);
}

//to print the graph
void print_graph(AdjacencyList *g)
{
    //Check if graph is empty
    if (g->link == NULL)
        printf("Graph Empty !\n");
    else
    {
        AdjacencyList *ptr = g->link, *p;
        //Traverse the node list
        while (ptr)
        {
            p = ptr;
            printf("%d ->", ptr->data);
            //traverse the edge list of p and print all the nodes
            while (p->link)
            {
                printf(" %d", p->link->data);
                p = p->link;
            }
            printf("\n");
            ptr = ptr->pnext;
        }
    }
}

int main()
{
    AdjacencyList *g = (AdjacencyList *)malloc(sizeof(AdjacencyList) * 10);
    g->link = NULL;
    //menu driven program to insert, delete and print graph according to choice
    printf("1. Insert into graph\n2. Delete from graph\n3. Display\n4. Exit\n\n");
    while (1)
    {
        int choice;
        printf("Enter choice: ");
        scanf("%d", &choice);
        switch (choice)
        {
        case 1:
        {
            int parent, value;
            printf("Enter parent and value: ");
            scanf("%d %d", &parent, &value);
            insert_to_graph(g, parent, value);
        }
        break;

        case 2:
        {
            int value;
            printf("Enter value: ");
            scanf("%d", &value);
            delete_from_graph(g, value);
        }
        break;

        case 3:
        {
            print_graph(g);
        }
        break;

        case 4:
        {
            return 0;
        }
        }
    }

    return 0;
}
/*
    Sample I/O:
        1. Insert into graph
        2. Delete from graph
        3. Display
        4. Exit

        Enter choice: 1
        Enter parent and value: 2 3
        Enter choice: 1
        Enter parent and value: 3 4
        Enter choice: 1
        Enter parent and value: 1 5
        Enter choice: 1
        Enter parent and value: 2 4
        Enter choice: 3
        2 -> 3 4
        3 -> 4
        1 -> 5
        Enter choice: 4
*/
/*
    TIME COMPLEXITY
        Insertion - O(n)
        Deletion - O(n^2)
        Print graph - O(n^2)
    Total time complexity of the program - O(n^2)
    SPACE COMPLEXITY- O(n)
*/


<|start_filename|>Java/math/Complex.java<|end_filename|>
import java.util.Objects;


/**
 * 
 * This is an implementation of Complex numbers in Java. 
 * 
 * @author <NAME>
 * @since 12-01-2019
 * @version 1.0.0
 * 
 */
public class Complex {
    private double real;   // the real part
    private double imaginary;   // the imaginary part

    /**
     * Creates a complex number.
     * @param real
     * @param imaginary
     */
    public Complex(double real, double imaginary) {
        this.real = real;
        this.imaginary = imaginary;
    }
    public double getReal() {
        return real;
    }
    public double getImaginary() {
        return imaginary;
    }
    public void setReal(double real) {
        this.real = real;
    }
    public void setImaginary(double imaginary) {
        this.imaginary = imaginary;
    }
    /**
     * @return modulus/absolute value of a given complex number
     */
    public double abs() {
        return Math.hypot(real, imaginary);
    }
    /**
     * @return angle/phase/argument, normalized to be between -pi and pi
     */
    public double phase() {
        return Math.atan2(imaginary, real);
    }
    /**
     * @param b complex to be added
     * @return new Complex object whose value is (this + b)
     */
    public Complex add(Complex b) {
        Complex a = this;
        double real = a.real + b.real;
        double imag = a.imaginary + b.imaginary;
        return new Complex(real, imag);
    }
    /**
     * Static version of add method
     * @param a
     * @param b
     * @return
     */
    public static Complex add(Complex a, Complex b) {
        double real = a.real + b.real;
        double imag = a.imaginary + b.imaginary;
        return new Complex(real, imag);
    }
    /**
     * @param b
     * @return a new Complex object whose value is (this - b)
     */
    public Complex subtract(Complex b) {
        Complex a = this;
        double real = a.real - b.real;
        double imag = a.imaginary - b.imaginary;
        return new Complex(real, imag);
    }
    /**
     * @param b
     * @return a new Complex object whose value is (this * b)
     */
    public Complex multiply(Complex b) {
        Complex a = this;
        double resultReal = a.real * b.real - a.imaginary * b.imaginary;
        double resultImaginary = a.real * b.imaginary + a.imaginary * b.real;
        return new Complex(resultReal, resultImaginary);
    }
    /**
     * @param b
     * @return Complex a/b
     */
    public Complex divide(Complex b) {
        Complex a = this;
        return a.multiply(b.reciprocal());
    }
    /**
     * @return a new Complex object whose value is the complex exponential of this
     */
    public Complex exp() {
        return new Complex(Math.exp(real) * Math.cos(imaginary), Math.exp(real) * Math.sin(imaginary));
    }

    /**
     * @return a new Complex object whose value is the complex sine of this
     */
    public Complex sin() {
        return new Complex(Math.sin(real) * Math.cosh(imaginary), Math.cos(real) * Math.sinh(imaginary));
    }

    /**
     * @return a new Complex object whose value is the complex cosine of this
     */
    public Complex cos() {
        return new Complex(Math.cos(real) * Math.cosh(imaginary), -Math.sin(real) * Math.sinh(imaginary));
    }

    /**
     * @return a new Complex object whose value is the complex tangent of this
     */
    public Complex tan() {
        return sin().divide(cos());
    }
    /**
     * @param alpha
     * @return a new object whose value is (this * alpha)
     */
    public Complex scale(double alpha) {
        return new Complex(alpha * real, alpha * imaginary);
    }
    /**
     * @return a new Complex object whose value is the conjugate of this
     */
    public Complex conjugate() {
        return new Complex(real, -imaginary);
    }
    /**
     * @return a new Complex object whose value is the reciprocal of this
     */
    public Complex reciprocal() {
        double scale = real * real + imaginary * imaginary;
        return new Complex(real / scale, -imaginary / scale);
    }
    @Override
    public boolean equals(Object x) {
        if (x == null) return false;
        if (this.getClass() != x.getClass()) return false;
        Complex that = (Complex) x;
        return (this.real == that.real) && (this.imaginary == that.imaginary);
    }
    @Override
    public int hashCode() {
        return Objects.hash(real, imaginary);
    }
    @Override
    public String toString() {
        if (imaginary == 0) return real + "";
        if (real == 0) return imaginary + "i";
        if (imaginary < 0) return real + " - " + (-imaginary) + "i";
        return real + " + " + imaginary + "i";
    }
}

<|start_filename|>C/math/Noble_Integer.c<|end_filename|>
/*An integer x is said to be Noble given an array 
if the number of integers greater than x are equal to x.
If noble integer is not found output is -1.
*/
#include <stdio.h>

int nobleint(int *, int);
int main()
{
	int num, i, k, arr[1000], arr2[1000], m;
	printf("Enter the number of elements:");
	scanf("%d", &num);
	printf("Enter the elements:");
	for (i = 0; i < num; i++)
	{
		scanf("%d", &arr[i]);
	}

	m = nobleint(arr, num);
	printf("%d", m);

	return 0;
}

// To find the noble integer from the given array
int nobleint(int *arr, int num)
{
	int count, i, j, x = 0;
	for (i = 0; i < num; i++)
	{
		count = 0;
		for (j = 0; j < num; j++)
		{
			if (*(arr + i)<*(arr + j))
				count = count + 1;
		}

		if (count == *(arr + i))
		{
			x = 1;
			return (count);
		}
	}

	if (x == 0)
		return (-1);
}

/*
Sample Output

Enter the number of elements:4
Enter the elements:7 3 9 81
3
Enter the number of elements:3
Enter the elements:2 2 2
-1

Complexities
Time Complexity:O(n^2)
Space Complexity:O(1)
*/



<|start_filename|>Java/ds/MedianOfSortedArrays.java<|end_filename|>
/*
 *         Description
 *      
 *   Problem:  Finding median of two sorted array
 *  
 * we will have two sorted arrays of size N and M respectively and element in array, which can be duplicated.
 * we will find median of array without merging the two arrays.
 * example:  A = [1, 5, 8]
 *           B = [1,2, 3,9]
 *          merged : [1,2,3,4,5]  (If we merge, we have to use extra space)
 *          output : 3.0
 *          
 *  If we merge the job is so simple. In this case TC O(N+M) , SC O(N+M)
 *  but we will apply binary search which will do it in TC O(log(max-min)*(logm+logn)), SC O(1).    
 * 
 */
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class MedianOfArray {
	public static double findMedianSortedArrays(final List<Integer> a, final List<Integer> b) {
		int i, n = a.size(), m = b.size();
		int low = 0, high = 0;
		//Handling Edge Case
		if (n == 0) {
			low = b.get(0);
			high = b.get(m - 1);
		} else if (m == 0) {
			low = a.get(0);
			high = a.get(n - 1);
		} else {
			low = Math.min(a.get(0), b.get(0));
			high = Math.max(a.get(n - 1), b.get(m - 1));
		}
		//Main Code
		int k = ((n + m) / 2);
		double d1 = 0.0, d2 = 0.0;
		d1 = getAns(low, high, a, b, k);
		
		//check for even length median
		if ((n + m) % 2 == 0) {
			d2 = getAns(low, high, a, b, k - 1);
			System.out.println((d1 + d2) / 2);
			return (d1 + d2) / 2;
		} else {
			System.out.println(d1);  //odd length median
			return d1;
		}
	}
	public static double getAns(int low, int high, List<Integer> a, List<Integer> b, int k) {
		int mid = 0;
		while (low <= high) {
			mid = (high - low) / 2 + low;
			int p = countLess(a, mid) + countLess(b, mid);
			int q = countEqual(a, mid) + countEqual(b, mid);
			if (p > k)
				high = mid - 1;
			else {
				if (p + q <= k)
					low = mid + 1;
				else
					return mid;
			}

		}
		return mid;
	}
	public static int countLess(List<Integer> a, int x) {
		int low = 0, high = a.size() - 1;
		int mid = 0;
		int index = -1;
		while (low <= high) {
			mid = (high - low) / 2 + low;
			if (a.get(mid) >= x) {
				high = mid - 1;
			} else {
				index = mid;
				low = mid + 1;
			}
		}
		return index + 1;
	}
	private static int countEqual(List<Integer> a, int x) {
		int low = 0, high = a.size() - 1;
		int mid = 0;
		int index = -1;
		while (low <= high) {
			mid = (high - low) / 2 + low;
			if (a.get(mid) >= x) {
				index = mid;
				high = mid - 1;
			} else {
				low = mid + 1;
			}
		}
		int index2 = -1;
		low = 0;
		high = a.size() - 1;
		while (low <= high) {
			mid = (high - low) / 2 + low;
			if (a.get(mid) <= x) {
				index2 = mid;
				low = mid + 1;
			} else {
				high = mid - 1;
			}
		}
		if (index == -1)
			return 0;
		else
			return index2 - index + 1;
	}
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		//Size of First List
		int n=sc.nextInt();
		
		//Size of Second List
		int m=sc.nextInt();
		int i;
		List<Integer> firstList=new ArrayList<Integer>();
		for(i=0;i<n;i++) {
		  int val=sc.nextInt();	
		  firstList.add(val);
		}
		
		List<Integer> secondList=new ArrayList<Integer>();
		for(i=0;i<n;i++) {
		  int val=sc.nextInt();	
		  secondList.add(val);
		 }
		findMedianSortedArrays(firstList,secondList);
	}
}
/*
 * Finding Median of Two sorted arrays: 
 * 
 * Time Complexity: O(NlogN)
 * Space Complexity: O(1)
 * 
 * Sample Input:
 * 
 * Input1:
 * first sorted list: [1,2,3]
 * second sorted list: [4]
 * 
 * output 1: median : (2+3)/2 = 2.5
 *  
 * Input2: 
 * first sorted list: [1,4,9,10]
 * second sorted list: [2,3,7]
 * 
 * output2: 4.0
 * 
 * 
 * */


<|start_filename|>C/other/Find_the_numbers.c<|end_filename|>
//Program to find the Unique numbers in an array out of which two numbers occur exactly once and are distinct.
// You need to find the other two numbers and print them in ascending order.

// Also Taken help from geeksforgeeks

#include <stdio.h> 

void findUniquePair(int arr[], int size) 
{ 
	// XOR each element and get XOR of two unique elements(ans) 
	int XOR = arr[0]; 
	for (int i = 1; i < size; i++) 
		XOR = XOR ^ arr[i]; 

	// Get a set bit of XOR (We get the rightmost set bit) 
	int set_bit = XOR & ~(XOR-1); 

	// Now divide elements in two sets by comparing rightmost 
	int x = 0, y = 0; // Initialize missing numbers 
	for (int i = 0; i < size; i++) 
	{ 
		if (arr[i] & set_bit)
			x = x ^ arr[i]; //first unique number in arr[]
		else
			y = y ^ arr[i]; //second unique number in arr[]
	} 
	if(x>y)
		printf("Distinct Numbers are %d and  %d", y, x);
	else
		printf("Distinct Numbers are %d and %d", x, y);
	
} 

int main() 
{ 
	
	int size;
	printf("Enter Size:");
	scanf("%d", &size);
	int arr[size];
	printf("Enter elements:\n");
	for(int i = 0; i < size; i++)
	{
		scanf("%d", &arr[i]);
	}
	findUniquePair(arr, size); 
	return 0; 
} 
/*
Sample I/O:
Input:
	Enter Size:6
	Enter elements:
	1 2 3 2 1 4

Output:
	Distinct Numbers are 3 and 4

Time Complexity: O(size)
Space Complexity: O(1)
*/

<|start_filename|>Java/math/DoubleFactorial.java<|end_filename|>
/**
 * In mathematics, the double factorial or semi-factorial
 * of a number n (denoted by n!!) is the product of all
 * the integers from 1 up to n that have the same parity
 * (odd or even) as n.
 */
import java.util.*;

public class DoubleFactorial {

    // Recursive approach
    private static int recursiveDoubleFactorial(int num) {
        // checking for 1 and 0
        if (num == 0 || num == 1) {
            return 1;
        }

        // using recursion
        return num * recursiveDoubleFactorial(num - 2);
    }

    // Iterative approach
    private static int iterDoubleFactorial(int num) {
        int result = 1;
        // using iterations
        for (int i = num; i >= 0; i = i - 2) {

            if (i == 0 || i == 1) {
                return result;
            } else {
                result *= i;
            }
        }

        return result;
    }
    
    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number:");
        int num = sc.nextInt();
        System.out.println("Which approach would you like to use?");
        System.out.println("1. Recursive");
        System.out.println("2. Iterative");
        int ch = sc.nextInt();
        sc.close();

        int result;
        switch (ch) {
        case 1:
            result = recursiveDoubleFactorial(num);
            System.out.println("Double factorial:" + result);
            break;

        case 2:
            result = iterDoubleFactorial(num);
            System.out.println("Double factorial:" + result);
            break;

        default:
            System.out.println("Invalid choice.");
        }
    }
}
/**
 * Sample input/output
 * Enter the number:
 * 5
 * Which approach would you like to use?
 * 1. Recursive
 * 2. Iterative
 * 1
 * Double factorial:15
 * 
 * Enter the number:
 * 6
 * Which approach would you like to use?
 * 1. Recursive
 * 2. Iterative
 * 2
 * Double factorial:48
 * 
 * Time complexity for both the approaches is O(n)
 */


<|start_filename|>Kotlin/Maths/Areas2D.kt<|end_filename|>
package kotlin.math

// Area of a Square

fun square(a: Double): Double {
    return a * a
}

// Area of a Reactangle

fun rectangle(l: Double, b: Double): Double{
    return l * b
}

// Area of a Circle

fun circle(r: Double): Double{
    return PI * r * r
}

// Area of a Triangle

fun triangle(b: Double, h: Double): Double{
    return b * h/2.0
}

// Area of a Parallelogram

fun parallelogram(b: Double, h: Double): Double{
    return b * h
}

// Area of a Trapezium

fun trapezium(a: Double, b:Double, h:Double): Double{
    return (a+b)*h/2.0
}


fun main() {
    println(square(2.0))
    println(rectangle(2.0, 4.6))
    println(circle(5.0))
    println(triangle(2.0,3.0))
    println(parallelogram(4.5,2.3))
    println(trapezium(1.5,4.5,6.0))
}


// Time Complexity - O(n)
// Space Complexity - O(n)


<|start_filename|>JavaScript/search/binary_search.js<|end_filename|>
/*
 *	Author: <NAME> (@omonimus)
 * Date: 26/06/2020
 *
 * Summary: Implement binary search algorithm in Javascript
 */

// Search an element in using Binary Search algorithm O(log n) time;
// It works just if the list is already sorted;
function binary_search(arr, target) {
  // Define left and right index of the range where to search
  // our target
  let start = 0,
    end = arr.length - 1;

  // Iterate while start not meets end
  while (start <= end) {
    // Get middle index
    let middle = Math.floor((start + end) / 2);

    // If element is present at middle return True
    if (arr[middle] === target) return true;
    // Else look in left or right half accordingly
    else if (arr[middle] < target) start = middle + 1;
    else end = middle - 1;
  }
  // Target do not exists
  return false;
}

/*
 *   @Test
 *   output expected: 'false'
 */
function element_do_not_exists_test() {
  var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  var target = 14;
  console.log(binary_search(numbers, target));
}

/*
 *   @Test
 *   output expected: 'true'
 */
function element_exists_test() {
  var numbers = [1, 2, 3, 6, 9, 10];
  var target = 3;
  console.log(binary_search(numbers, target));
}

// Entry point of the application for testing purposes
element_do_not_exists_test();
element_exists_test();


<|start_filename|>C/dp/length_longest_common_subsequence.c<|end_filename|>
// C program to find to the length of the longest common subsequence
#include <stdio.h>

// Helper function to find the maximum of two elements
int max(int a, int b)
{
    if (a > b)
        return a;
    else
        return b;
}

// Length of Longest Common subsequence
int lcs(char s1[], int n, char s2[], int m)
{

    /* Builds a 2D table in a bottom Up manner, storing info regarding the 
    length of longest common subsequence of both strings till that index. */
    int dp[n + 1][m + 1];

    for (int i = 0; i <= n; i++)
    {
        for (int j = 0; j <= m; j++)
        {
            // If one of the string size is zero, then the length of LCS is also zero
            if (i == 0 || j == 0)
                dp[i][j] = 0;

            // If the elements of both the strings match, then the value of LCS increments by one.
            else if (s1[i - 1] == s2[j - 1])
                dp[i][j] = dp[i - 1][j - 1] + 1;

            /* Either include the last element from one string and exclude it from the other and 
            compare them and vice versa and pick the one giving the maximum length out of the two */
            else
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
        }
    }

    return dp[n][m];
}

int main()
{
    int n, m, ans;
    printf("\nEnter the length of the first string? ");
    scanf("%d", &n);
    char s1[n];
    printf("Enter the first string: ");
    scanf(" %s", s1);

    printf("\nEnter the length of the second string? ");
    scanf("%d", &m);
    char s2[m];
    printf("Enter the second string: ");
    scanf(" %s", s2);

    ans = lcs(s1, n, s2, m);
    printf("\nThe length of the longest common subsequence is: %d", ans);
    return 0;
}

/*

Time Complexity: O(m*n), where m, n is the size of the input strings
Space Complexity: O(m*n)

SAMPLE INPUT AND OUTPUT

Enter the length of the first string? 6
Enter the first string: cuckoo
Enter the length of the second string? 8
Enter the second string: cucumber
The length of the longest common subsequence is: 3

*/


<|start_filename|>JavaScript/ds/QueueLinkedList.js<|end_filename|>
/*

A queue is a linear data structure that follows the First in, First out principle (i.e.​ the first added elements are removed first).
Generally, a queue is implemented using Linked List but other approach can be used i.e using array ( which has high time complexity ) or using stack.
Below is the implementation of a queue using a linked list ( Singly Linked List ).

In this program, the user can provide a choice to perform operations on a Queue. It is created using an ES6 class syntax. 
prompt & colors are node packages for taking user input and displaying text in different colors respectively. 

*/

const prompt = require("prompt-sync")({ sigint: true });
const colors = require("colors");

// Setting the Color schema
colors.setTheme({
  display: "green",
  insert: "white",
  delete: "red",
  leave: "yellow",
  end: "rainbow",
  wrong: "america",
});

// Creating the node class to create nodes
class Node {
  constructor(value, next = null) {
    this.value = value;
    this.next = next;
  }
}

// Creating a Queue class to perform operations
class Queue {
  constructor() {
    this.first = null;
    this.last = null;
    this.length = 0;
  }

  // Get the first element of Queue
  peek() {
    if (this.length === 0) return console.log("Empty Queue");
    return console.log(this.first.value);
  }

  // Insert an element in the Queue
  enqueue(value) {
    const newNode = new Node(value);
    if (this.length === 0) {
      this.first = newNode;
      this.last = newNode;
    } else {
      this.last.next = newNode;
      this.last = newNode;
    }

    this.length++;
    return this;
  }

  // Delete an element from the Queue
  dequeue() {
    if (!this.first) return console.log("Queue is already empty");
    if (this.first === this.last) {
      this.first = null;
      this.last = null;
    } else {
      this.first = this.first.next;
    }

    this.length--;
    return this;
  }

  // Check whether the Queue is empty or not
  isEmpty() {
    if (this.length === 0) return console.log("Into the Void here");
    return console.log("There is something deep inside it");
  }

  // Print all the elements of Queue
  printList() {
    let currentNode = this.first;
    let queueItems = [];

    while (currentNode) {
      queueItems.push(currentNode.value);
      currentNode = currentNode.next;
    }

    return console.log("Queue", queueItems);
  }
}

// Instantiating the Queue class
const myQueue = new Queue();

let choice = 0;
let value;

// Asking user input for performing operations on Queue
do {
  console.log("\nWelcome to the Queue Linked List Show");
  console.log("Follow the instructions to get in the show");
  console.log("0. To exit without doing anything".yellow);
  console.log("1. Display the queue".display);
  console.log("2. Insert element in queue".insert);
  console.log("3. Get first element of queue".display);
  console.log("4. Check whether queue in empty or not".insert);
  console.log("5. Delete element from queue".delete);

  choice = +prompt("Enter your choice - ");

  switch (choice) {
    case 0:
      console.log("Hmm, matter of choice!\n".rainbow);
      return;

    case 1:
      myQueue.printList();
      break;

    case 2:
      value = prompt("Enter element to insert into the queue - ");
      myQueue.enqueue(value);
      myQueue.printList();
      break;

    case 3:
      myQueue.peek();
      break;

    case 4:
      myQueue.isEmpty();
      break;

    case 5:
      myQueue.dequeue();
      myQueue.printList();
      break;

    default:
      console.log("You know this is wrong, Bbye!\n".wrong);
      return;
  }
} while (choice !== 0);

// Sample I/O of the above program -

/*

> node QueueLinkedList

Welcome to the Queue Linked List Show
Follow the instructions to get in the show
0. To exit without doing anything
1. Display the queue
2. Insert element in queue
3. Get first element of queue
4. Check whether queue in empty or not
5. Delete element from queue
Enter your choice - 1
Queue []

Welcome to the Queue Linked List Show
Follow the instructions to get in the show
0. To exit without doing anything
1. Display the queue
2. Insert element in queue
3. Get first element of queue
4. Check whether queue in empty or not
5. Delete element from queue
Enter your choice - 2
Enter element to insert into the queue - 4
Queue [ '4' ]

*/




<|start_filename|>C-Plus-Plus/ds/BinaryTree_PreorderTraversal.cpp<|end_filename|>
#include <iostream>
#include <stack>
#include <vector>
using namespace std;

// every node of the binary tree is represented by a 'node' data type
struct node{
    int key_value;  // value the node holds
    node* left;     // address of its left child
    node* right;    // address of its right child
};

class binaryTree{
    private:
        node* root;
        void insertKey(int key, node* leaf);
        void preOrderTraversal_recursive(node* leaf);
    public:
        binaryTree();
        void insertKeys(vector<int> keys);
        void insertKey(int key);
        void preOrderTraversal_recursive();
        void preOrderTraversal_iterative();
};

// constructor. initializes root to NULL
binaryTree::binaryTree(){
    root = NULL;
}

// accepts a vector and calls insertKey(int) iteratively.
void binaryTree::insertKeys(vector<int> keys){
    int len = keys.size();
    for(int i=0;i<len;i++){
        insertKey(keys[i]);
    }
}

// When called for the first time(when root IS initialized as NULL), insertKey(int)
// initializes root to point to a node data type. This node data type gets it key_value
// as key(argument) and child nodes as NULL.
// For all calls other than the first time, it further calls insertKey(int, node*)
void binaryTree::insertKey(int key){
    if(root!=NULL){
        insertKey(key, root);
    }
    else{
        root = new node;
        root->key_value = key;
        root->left = NULL;
        root->right = NULL;
    }
}

// inserts the key, such that the Tree follows the definition of a binary tree.
// the function travels down the tree starting from the root to find a suitable position.
// if key is less than the key_value at a node, function calls itself with its left subtree.
// if key is greater than the key_value at a node, function calls itself with its right subtree.
// When it reaches a suitable place, it creates a new node. This node gets key_value as key and child nodes as NULL
void binaryTree::insertKey(int key, node* leaf){
    if(key< leaf->key_value){
        if(leaf->left!=NULL){
            insertKey(key, leaf->left);
        }
        else{
            leaf->left = new node;
            leaf->left->key_value = key;
            leaf->left->left = NULL;
            leaf->left->right = NULL;
        }
    }
    else if(key>= leaf->key_value){
        if(leaf->right!=NULL){
            insertKey(key, leaf->right);
        }
        else{
            leaf->right = new node;
            leaf->right->key_value = key;
            leaf->right->left = NULL;
            leaf->right->right = NULL;
        }
    }
}

// calls preOrderTraversal_recursive, a private member-function
void binaryTree::preOrderTraversal_recursive(){
    cout<<"PreOrderTraversal(recursive): ";
    preOrderTraversal_recursive(root);
}

// for a particular node, function prints its key_value and recursively calls
// its left and right subtree(in that order).
void binaryTree::preOrderTraversal_recursive(node* leaf){
    if(leaf!=NULL){
        cout<<leaf->key_value<<" ";
        preOrderTraversal_recursive(leaf->left);
        preOrderTraversal_recursive(leaf->right);
    }
}

// if root is NULL, function exits
// otherwise, it works as follows: 1. Sets root as current node.
// 2. It outputs the key_value of the current node,
// and pushes the address of its right subtree in stack. Also, sets current node as address of its left subtree
// This continues till the current node is NULL.
// 3. When it reaches NULL i.e. no left subtree is available, it sets current node as top value in the
// stack and pops it from the stack. Then it repeats step 2.
void binaryTree::preOrderTraversal_iterative(){
    cout<<"PreOrderTraversal(iterative): ";
    if(root==NULL)
        return;
    stack<node*> nodeAddr;
    node* currentNode = root;

    while(currentNode!=NULL || !nodeAddr.empty()){
        while(currentNode!=NULL){
            cout<<currentNode->key_value<<" ";
            if(currentNode->right!=NULL){
                nodeAddr.push(currentNode->right);
            }
            currentNode = currentNode->left;
        }
        if(!nodeAddr.empty()){
            currentNode = nodeAddr.top();
            nodeAddr.pop();
        }
    }
}

int main(){
    binaryTree Tree;
    vector<int> elements = {25,15,50,10,22,35,70,4,12,18,24,31,44,66,80}; //the elements to be inserted in the tree
    Tree.insertKeys(elements);
    Tree.preOrderTraversal_recursive(); //expected: 25 15 10 4 12 22 18 24 50 35 31 44 70 66 80
    cout<<endl;
    Tree.preOrderTraversal_iterative(); //expected: 25 15 10 4 12 22 18 24 50 35 31 44 70 66 80
    cout<<endl;
}


<|start_filename|>C-Sharp/math/Finding_no_of_digits_in_an_integer.cs<|end_filename|>
/*  Find number of digits in an integer : 
	This program will gives you the result in O(1) Time Complexity  
*/

using System; 
  
class CountDigits { 
  
    static int countDigit(long num) {
        return (int)Math.Floor(Math.Log10(num) + 1); 
    }
    
    public static void Main() 
    { 
        Console.WriteLine("Enter the number: ");
        long num = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Number of digits= " + countDigit(num)); 
    } 
}
/*
	Sample Input/Output-
	Enter the number: 7890
	Number of digits= 4

*/


<|start_filename|>C-Plus-Plus/other/insert_usernames_in_database.cpp<|end_filename|>
/*
Given a database with user names.
Each time a new user wants to register, he sends to the system a request with his name.
If such a name does not exist in the system database, it is inserted into the database.
and the user gets confirming the successful registration.
If the name already exists in the system database, the system makes up a new user name,
sends it to the user as a prompt Numbers, starting with 1, are appended one after another to
name (name1, name2..) and so on. Print all user names with their corresponding database names.
*/

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

// this insert_usernames_in_database function will print all user names with their corresponding database names
void insert_usernames_in_database(vector < string >user_names)
{
    map < string , int > user_entry;
    int size_of_username = user_names.size();
    for(int i = 0; i < size_of_username; i++)
    {
        if(user_entry.find(user_names[i]) == user_entry.end())
        {
            cout << "The User name is unique: ";
            cout << user_names[i] << endl;
            user_entry[user_names[i]]++;
        }
        else if(user_entry.find(user_names[i]) != user_entry.end())
        {
            cout << "The User name is not unique: ";
            cout << user_names[i] << user_entry[user_names[i]] << endl;
            user_entry[user_names[i]]++;

        }
    }
}

int main()
{
    cout << "Enter the number of User Names : \n";
    int Number;
    cin >> Number;
    vector < string > user_names;
    cout << "Enter user names:\n";
    for (int i = 0; i < Number; i++)
    {
	    string name;
	    cin >> name;
	    user_names.push_back(name);
    }
    insert_usernames_in_database(user_names);
}

/*
Standard Input and Output

Enter the number of User Names :
8
Enter user names:
karim
rahim
khan
bhab
gssoc
gssoc
karim
rahim
The User name is unique: karim
The User name is unique: rahim
The User name is unique: khan
The User name is unique: bhab
The User name is unique: gssoc
The User name is not unique: gssoc1
The User name is not unique: karim1
The User name is not unique: rahim1

Time Complexity : O( logN )
Space Complexity : O(N)

*/


<|start_filename|>C-Plus-Plus/cp/ElementsOccurrence_BinarySearch.cpp<|end_filename|>
/* To print the occurrence of the given number in the list/array using Binary Search Technique 

inputs:
Size of array/list
Elements in the array/list
A number whose occurrence is to be printed

The program should do :
Find the occurrence of the given number using the above technique

Sample Test Case:
Input :
5
1 4 2 3 4
4
Output:
Occurrence of '4': 2

Space Complexity - O(1)
Time complexity - logn
*/


#include <iostream>
using namespace std;


//Binary_search() for performing binary search on elements


int Binary_search (int array[], int sizeOf_array, int number, bool found)
{
    int start = 0, end = sizeOf_array - 1;
    int value = -1;
    while (start <= end)
    {
        int middle = start + ((end - start) / 2);

        if (number == array[middle]) 
        {
            value = middle;

            if (found)

                end = middle - 1;
            else 

                start = middle + 1;
            
        }

        else if (number < array[middle])
        {
            end = middle - 1;
        }

        else
        {
            start = middle + 1;
        }
    }

    return value;
}

//Partition() for quick_sort Algorithm


int Partition (int *Array, int start, int end)
{
    int pivot = Array[end];
    int partition_index = start;
    for(int i = start; i < end ;i++)
    {
        if(Array[i] <= pivot)
        {
            swap(Array[i], Array[partition_index]);
            partition_index++;


        }
    }

    swap(Array[partition_index], Array[end]);

    return partition_index; 

}

//Quick_sort() for performing quick_sort Algorithm

int Quick_sort (int array[] , int lower_bound , int  upper_bound)
{
    int temporary ;

    if (lower_bound < upper_bound)
    {
        temporary = Partition (array , lower_bound , upper_bound );
        Quick_sort (array , lower_bound , temporary - 1);
        Quick_sort (array , temporary + 1, upper_bound);
    }
}

//main function

int main()
{	
	int *array;
    int array_size;

    cout<<"The size of array is: ";
    cin>>array_size;

    array = new int [array_size];

    cout<<"Please input the elements in array:\n";
    for (int i = 0 ; i < array_size ; i++) 
    {
        cin>>array[i];
    }
    cout<<"\n";

    int number;

    cout<<"Enter the number to find its occurrence : ";
    cin>>number;

    int lower_bound = 0 , upper_bound = array_size - 1;

    Quick_sort (array , lower_bound , upper_bound);

    int first_occurrence_of_number = Binary_search (array, array_size, number, true); // function for finding first occurrence of element after sorting 

    int last_occurrence_of_number = Binary_search (array, array_size, number, false); // function for finding last occurrence of element after sorting

    int total_occurrences_of_number = last_occurrence_of_number - first_occurrence_of_number + 1; //to clculate the total number of occurrence
    
    if (first_occurrence_of_number != -1) //Occurrence Found
    {
        cout<<"Occurrence of  '"<<number<<"': " <<total_occurrences_of_number; 
    }
    else {                                  //occurrence not found
        cout<<"The number is not present in the array."; 
    }
    delete [] array;

    return 0;
}


<|start_filename|>Java/other/TowerOfHanoi.java<|end_filename|>
import java.util.*;

class TowerOfHanoi {

    public static void shiftRings(int n, int fromRod, int toRod, int midRod) {
        if(n == 1) {
            System.out.println("Shifting disk 1 from rod " + fromRod + " to rod " + toRod);
            return;
        }
        shiftRings(n-1, fromRod, midRod, toRod);
        System.out.println("Shifting disk " + n + " from rod " + fromRod+ " to rod " + toRod);
        shiftRings(n-1, midRod, toRod, fromRod);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number of rings:");
        int n = sc.nextInt();
        sc.close();

        shiftRings(n, 1, 3, 2);
    }
}
/**
 * Sample input/output: 
 * Enter the number of rings:
 * 4
 * Shifting disk 1 from rod 1 to rod 2
 * Shifting disk 2 from rod 1 to rod 3
 * Shifting disk 1 from rod 2 to rod 3
 * Shifting disk 3 from rod 1 to rod 2
 * Shifting disk 1 from rod 3 to rod 1
 * Shifting disk 2 from rod 3 to rod 2
 * Shifting disk 1 from rod 1 to rod 2
 * Shifting disk 4 from rod 1 to rod 3
 * Shifting disk 1 from rod 2 to rod 3
 * Shifting disk 2 from rod 2 to rod 1
 * Shifting disk 1 from rod 3 to rod 1
 * Shifting disk 3 from rod 2 to rod 3
 * Shifting disk 1 from rod 1 to rod 2
 * Shifting disk 2 from rod 1 to rod 3
 * Shifting disk 1 from rod 2 to rod 3
 * 
 * Time complexity: O(2^n)
 * Space complexity: O(n)
 */


<|start_filename|>C-Plus-Plus/ds/linked_list_middle_element.cpp<|end_filename|>
/*
 Author: <NAME> (@Sarthak-9)

 A Linked List is a linear data structure which includes a series of connected nodes. Each node stores the data and the address of the next node.
 Middle Element can be extracted using following two methods :
 Method 1 - MiddleNode1 finds the length of the linked list and the prints the data at position length/2.
 Time complexity of MiddleNode1 : O(n)
 Space Complexity of MiddleNode1 : O(1)
 Method 2 - MiddleNode2 is an optimized approach which uses two pointers namely slow and fast pointers. The fast pointer moves two steps in each iteration while the slow pointer jumps only one step.
 When the fast pointer reaches the end, the slow pointer reaches the middle element and its data is printed.
 Time complexity of MiddleNode2 : O(n/2)
 Space Complexity of MiddleNode2 : O(1)
*/

#include <iostream>
#include <cmath>

using namespace std;

class Node{
public:
        int data;
        Node* next;
};

Node* head = new Node;

void create(int arr[], int n){
        Node* temp;
        Node* tail;

        head->data = arr[0];
        head->next = nullptr;
        tail = head;

        // creates the linked list from array
        for (int i = 1; i < n; i++){
                temp = new Node;
                temp->data = arr[i];
                temp->next = nullptr;
                tail->next = temp;
                tail = temp;
        }
}

// counts the length of list and prints the value at length/2
void MiddleNode1(Node* p){

        int length = 0;

        // counts the length
        while (p){
                length++;
                p = p->next;
        }

        int index = (int) ceil(length / 2.0);

        Node* q = head;

        // traverses to the middle element
        for (int i = 0; i < index - 1; i++){
                q = q->next;
        }
        cout << "Middle Element (Method-I): " << q->data << endl;
}

// uses two pointers where 1st jumps two steps to reach end while the 2nd reaches middle element
void MiddleNode2(Node* p){

        Node* q = p;

        while (q){

                // q jumps two steps
                q = q->next;
                if (q){
                        q = q->next;
                }

                // p jumps one step
                if (q){
                        p = p->next;
                }
        }
        cout << "Middle Element (Method-II): " << p->data << endl;
}

int main() {

        int n;
        cout<<"Enter the size of list"<<endl;
        cin>>n;
        int arr[n];
        cout<<"Enter the elements of linked list"<<endl;

        // inputs the list in an array
        for(int i = 0; i < n; i++){
                cin>>arr[i];
        }

        create(arr,n);

        MiddleNode1(head);
        MiddleNode2(head);

        return 0;
}

/*

 Input :
 Enter the size of list
 8
 Enter the elements of linked list
 45 24 32 72 54 18 90 65

 Output :
 Middle Element (Method-I): 72
 Middle Element (Method-II): 72

*/


<|start_filename|>C-Plus-Plus/ds/quadratic-probing.cpp<|end_filename|>
#include <iostream>
using namespace std;

int Hash(int x, int s) {
	return x % s;
}
//Function to insert in hashtable.
void QuadProbe(int Q[], int s, int x) {
	int index = Hash(x, s);
	int i = 0;
	while (Q[index] != 0 && Q[index] != -1) {
		i++;
		index = (Hash(x, s) + (i * i)) % s;

	}
	Q[index] = x;
}
//Function to Search for an element in hashtable.
void QPSearch(int Q[], int s, int x) {
	int index = Hash(x, s);
	int i = 0;
	while (Q[index] != 0) {
		if (Q[index] == x) {
			cout << "Element found at index " << index << endl;
			return;
		}
		i++;
		index = (Hash(x, s) + (i * i)) % s;

	}
	cout << "Element not found " << endl;
}
//Function to Delete an element from Hashtable.
void QPDelete(int Q[], int s, int x) {
	int index = Hash(x, s);
	int i = 0;
	while (Q[index] != 0) {
		if (Q[index] == x) {
			cout << "Element deleted " << endl;
			Q[index] = -1;
			return;
		}
		i++;
		index = (Hash(x, s) + i) % s;

	}
	cout << "Element not found hence cant be deleted " << endl;

}
//Main Function
//Space Complexity: O(n)
//Time Complexity: O(m) - The algorithm would iterate through the array of size m to allocate the elements their proper positions.
int main() {
	int n, x;
	cout << "Hello world!" << endl;
	cout << "Enter number of elements " << endl;
	cin >> n;
	int s = 2 * n;
	int p = s;
	while (p > 0) {
		if ( ( ((p - 1) % 6 == 0) && ((p + 1) % 6 != 0) )  || ( ((p + 1) % 6 == 0) && ((p - 1) % 6 != 0) ))
			break;
		p--;
	}
	int L[s] = {0}, Q[s] = {0}, D[s] = {0};
	cout << "Enter elements for quad probing " << endl;
	for (int i = 0; i < n; i++) {
		cin >> x;

		QuadProbe(Q, s, x);

	}
	cout << "The hash table is" << endl;
	for (int i = 0; i < s; i++) {
		cout << Q[i] << endl;
	}

	cout << "Enter element to be searched in QP : ";
	cin >> x;
	QPSearch(Q, s, x);
	cout << "Enter element to be deleted in QP : ";
	cin >> x;
	LPDelete(Q, s, x);
	cout << "The hash table is " << endl;
	for (int i = 0; i < s; i++) {
		cout <<< < Q[i] << endl;
	}
	cout << "Enter element to be added : ";
	cin >> x;
	QuadProbe(Q, s, x);
	cout << "The hash table is " << endl;
	for (int i = 0; i < s; i++) {
		cout <<< < Q[i] << endl;
	}
	return 0;
}


<|start_filename|>C-Plus-Plus/math/sum_of_divisors.cpp<|end_filename|>
/*
Given a Number. Find it's Sum of Divisors.

The Number can be big such as 10^6 to 10^9
So, If we do this in O(N) we will get Time Limit Exceeded [TLE]
Better Approach is run a loop till sqrt(Number)
Example square root of 10^9 is 31622 (approx), so iteration optimized a lot.
*/

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

// this get_sum_of_divisors will count the sum of divisors of the number
long long int get_sum_of_divisors(int Number)
{
    /* Sum of Divisors may not fit in int range
    so better take long long int */
    long long int sum_of_divisors = 0;
    int limit = (int) sqrt(Number);
    for(int i = 1; i < limit; i++)
    {
        if(Number % i == 0)
        {
            /* Here i is a divisor of that number
            ( Number / i ) is also a divisor
            */
            sum_of_divisors += i;
            sum_of_divisors += (Number / i);
        }
    }

    if(Number % limit == 0)
    {
        if(limit * limit == Number)
        {
            //means perfect square number
            sum_of_divisors += limit;
        }
        else
        {
            sum_of_divisors += limit;
            sum_of_divisors += (Number / limit);
        }
    }
    return sum_of_divisors;
}

int main()
{
    cout << "Enter the number : \n";
    int Number;
    cin >> Number;
    long long int sum_of_divisors = get_sum_of_divisors(Number);
    cout << "Sum of Divisors of this Number is : ";
    cout << sum_of_divisors << endl;
}

/*
Standard Input and Output

Enter the number :
1000000000
Sum of Divisors of this Number is : 2497558338

Enter the number :
456723
Sum of Divisors of this Number is : 681408

Time Complexity : O( sqrt(N) )
Space Complexity : O( 1 )

*/


<|start_filename|>Java/cp/Remove_Outermost_parentheses.java<|end_filename|>
import java.util.*;
import java.lang.*;
import java.io.*;

class Stacks {
    public String removeOuterParentheses(String S) {
        if (S.length() == 0) return "";
        Stack<Character> stack = new Stack<>();
        int count = 0;
        
        for (int i = S.length() - 1; i > 0; i--)
            stack.push(S.charAt(i));
            
        String ans = "";
        while (!stack.isEmpty()){
            if (stack.peek() == '('){
                if (count >= 0)
                    ans+= stack.peek();
                count++;
            }
            else{
                if (count != 0)
                    ans += stack.peek();
                count --;
            }
            stack.pop();
        }
        return ans;
    }
}

/*
TIME COMPLEXITY: 0(N) where n is size of string
SPACE COMPLEXITY:0(N) where n is size of string
TEST CASE

INPUT
"(()())(())"

OUTPUT
"()()()"

INPUT
"(()())(())(()(()))"

OUTPUT
"()()()()(())"

*/



<|start_filename|>C-Plus-Plus/cp/length_of_last_word.cpp<|end_filename|>
/*
	Given a string s consists of some words separated by spaces,
	return the length of the last word in the string. 
	If the last word does not exist, return 0.
	A word is a maximal substring consisting of non-space characters only.
*/

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

/*
		Well, the basic idea is very simple. 
		Start from the tail of s and move backwards to find the first non-space character. 
		Then from this character, move backwards and count the number of non-space characters 
		until we pass over the head of s or meet a space character.
		The count will then be the length of the last word.
*/

int lengthOfLastWord(string s)
{
    int lengthofword = 0, tail = s.length() - 1;
    while (tail >= 0 && s[tail] == ' ')
        tail--;
    while (tail >= 0 && s[tail] != ' ')
    {
        lengthofword++;
        tail--;
    }
    return lengthofword;
}

int main()
{
    cout << "Enter the string:";
    string str;
    getline(cin, str);

    int ans = lengthOfLastWord(str);
    cout << "The length of the last word in the string is: " << ans;
}

/*
	   Input:Hello World
	   Output:5
*/
/*
	   Time Complexity:O(n),where n is the length of the string
	   Space Complexity:O(1)
*/


<|start_filename|>Julia/sort/insertion_sort.jl<|end_filename|>
"""Julia program to implement Insertion sort
In Insertion Sort we maintain a sorted part and an unsorted part,
and continously shift elements from unsorted part to the sorted part
thus getting the whole array sorted in the process.
"""

function insertion_sort(arr, n)
    # Begin the iteration from the second element considering, the first element as a part of the sorted part 
    for i in 2:n
        temp = arr[i]
        j = i - 1
        # Find the first element from the beginning of the array that is smaller than the temp element
        # And shift all the elements till then towards right. 
        while j > 0 && temp < arr[j]
            arr[j + 1] = arr[j]
            j = j - 1
        end
        arr[j + 1] = temp
    end
end



print("How many numbers do you want to sort? ")
n = readline()
n = parse(Int64, n)
if (n <= 0)
    println("No numbers to sort!!!")
    exit()
end
arr = Int[]
print("Enter the numbers: ")
arr = [parse(Int, num) for num in split(readline())]
insertion_sort(arr, n)
print("The numbers in sorted order is ")
print(arr)



"""
Time Complexity - O(n^2), where 'n' is the size of the array
Space Complexity - O(n)

SAMPLE INPUT AND OUTPUT

SAMPLE I
How many numbers do you want to sort? 6
Enter the numbers: 76 243 89 25 8337 72
The numbers in sorted order is [25, 72, 76, 89, 243, 8337]

"""


<|start_filename|>C-Plus-Plus/ds/Stack_using_LinkedList.cpp<|end_filename|>
/*
Implement the basic functionality of stack using Linked List Data structure

@author: Rishikeshrajrxl
@created: 17/08/2020
*/

#include <iostream>
using namespace std;

struct node
{                          //declaration of node
int data;
struct node*next;
}*head=NULL,*temp,*ptr;

void Push();             //Function declaration
void Peek();           
void Pop();
void Is_Empty();
void Display();
void count();
int ele;

int main()              //Main() starts
{
int ch;
cout<< "\n\n\t Implement the basic functionality of stack"<<endl;         //Displaying the Features in a tabular manner         
cout<<"\t **************************************************"<<endl;
do{
cout<<"\t 1) Push\t \t 2) Pop "<<endl; 
cout<<"\t 3) Peek\t \t 4) Is_Empty"<<endl;
cout<<"\t 5) Display\t \t 6) count"<<endl;
cout<<"\t 7) Exit"<<endl;
cout<<"\t ***************************************************\nENTER YOUR CHOICE : ";
cin >>ch;
  switch(ch)
  {
    case 1:
    Push();
    break;

    case 2:
    Pop();
    break;

    case 3:
    Peek();
    break;

    case 4:
    Is_Empty();
    break;

    case 5:
    Display();
    break;

    case 6:
    count();
    break;
    
    case 7:
    exit(0);
    break;
    
    default:
    cout<<"Invalid Input. Please enter the Number between 1 to 7 \n"<<endl;
  }
}while(ch!=0);
    return 0;
}                       // Main() Ends
//--------------------------------------------------------------------------
void Push()             //Insertion at the top 
{
    ptr=(struct node*)malloc(sizeof(struct node));
    cout<<"ENTER THE ELEMENT : ";
    cin>>ele;
    ptr->data=ele;
    ptr->next=head;
    head=ptr;
    cout<<"Pushed Successfully"<<endl;
}
//---------------------------------------------------------------------------
void Pop()                //deletion from the top
{
    if(head==NULL){
        cout<<"Stack is Empty"<<endl;
    }
    else{
        temp=head;
        head=head->next;
        cout<<"Poped Successfully"<<endl;
        free(temp);
    }
}
//---------------------------------------------------------------------------
void Peek()             //returns the value of the top
{
    cout<<"Peek Value is : "<< head->data<<endl;
}
//-----------------------------------------------------------------------------
void Is_Empty()           //returns Yes if Empty, else No
{
   if(head==NULL)
     cout<<"Yes"<<endl;
   else
     cout<<"No"<<endl;
}
//------------------------------------------------------------------------------
void Display()           //returns all the value inside the Stack
{
    if(head==NULL){
        cout<<"Stack is Empty "<<endl;
    } else{
        temp=head;
        cout<<"Data In Stack : ";
        while(temp!=NULL){
             cout<<temp->data<<" ";
             temp=temp->next;
        }cout<<""<<endl;
    }
}
//-------------------------------------------------------------------------------
void count()        //returns total no of nodes in stack
{
   int count=0;
   temp=head;
   while(temp!=NULL){
       count+=1;
       temp=temp->next;
   } cout<<"Total No is : "<<count<<endl;
}


<|start_filename|>C-Plus-Plus/cp/printallcodes_recursion.cpp<|end_filename|>
// This program prints all the possible codes for a given string.

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

void printallcodes(string number, string ans) {
	if (number.size() == 0) { //Base case
		cout << ans << endl;
		return;
	}

	int ch = number[0] - '0';

	if (ch != 0) {
		char code = char(ch - 1 + 'a'); //Extracting alphabet from its value
		string rstr = number.substr(1);
		printallcodes(rstr, ans + code);
	}

	if (number.size() >= 2) {
		int num = stoi(number.substr(0, 2));

		if (num >= 1 && num <= 26) {
			char code = char(num - 1 + 'a');
			string rstr = number.substr(2);
			printallcodes(rstr, ans + code);
		}
	}
}

int main() {
	string number;
	cout << "Enter the number";
	cin >> number;
	printallcodes(number, "");
	return 0;
}

/*
Example:
Input: s = "1123"
Output:
aabc
aaw
alc
kbc
kw
*/


<|start_filename|>C-Plus-Plus/ds/Reverse_Queue_content_using_Stack.cpp<|end_filename|>
/*
Problem - 
	To reverse the content of a queue using only a stack.

Algorithm - 
	First we pop each element from the queue and push it element by element into the stack. We keep doing this until the queue is empty.
	Then we pop each element from the stack and push it element by element into the queue. We keep doing this until the stack is empty.
	We get the content of queue reversed.
*/

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

// Displays all content of queue
void Q_Display(queue <int> q)
{
	while (!q.empty())
	{
		cout << q.front() << " ";
		q.pop();
	}
}

// Reverses content of queue using stack
void reverse_queue(queue <int> *q)
{
	stack <int> s;
	
	// Poping from queue and pushing into stack
	while (!q->empty())
	{
		s.push(q->front());
		q->pop();
	}
	// Poping from stack and pushing into queue
	while (!s.empty())
	{
		q->push(s.top());
		s.pop();
	}
}

int main()
{
	queue <int> q;
	int temp, n;
	
	cout << "Enter queue size : ";
	cin >> n;
	
	while (n--)
	{
		cout << "\nEnter a number : ";
		cin >> temp;
		q.push(temp);
	}
	
	cout << "\nOriginal queue : ";
	Q_Display(q);
	
	reverse_queue(&q);
	
	cout << "\nReversed queue : ";
	Q_Display(q);
}
/*
Test run example - 
	Enter queue size : 5
	Enter a number : 1
	Enter a number : 2
	Enter a number : 3
	Enter a number : 4
	Enter a number : 5
	
	Original queue : 1 2 3 4 5
	Reversed queue : 5 4 3 2 1

Time and Space Complexity - 
	Time - O(n)
	Space - O(n)
*/


<|start_filename|>JavaScript/Algorithms/Armstrong.js<|end_filename|>

// In this program we will check whether a number is an Armstrong number 
// An Armstrong number is a three-digit number in which 
// the sum of the cube of the digits is equal to the number itself. 
// Hence 153 is an Armstrong number -> 1^3 + 5^3 + 3^3 = 153


process.stdin.setEncoding("utf-8");
var str = "";
process.stdin.on("data", (data) => {
  str += data;
});
process.stdin.on("end", () => {
  str = str.split("\n");
  var number = str[0];
  var temp = number;
  var answer = 0;
  var rem = 0;
  var n = 0;
  while (temp != 0) {
    temp = Math.floor(temp / 10);
    n++;
  }

  temp = number;

  while (temp != 0) {
    rem = Math.floor(temp % 10);
    answer = answer + Math.pow(rem, n);
    temp = Math.floor(temp / 10);
  }

  if (answer == number)
    console.log(number + " is an Armstrong number.");
  else
    console.log(number + " is not an Armstrong number.");

});
// Example
// Input: 371
// Output: 371 is an Armstrong number.
// Explanation 3*3*3+7*7*7+1*1*1 = 371

// Example
// Input: 321
// Output: 321 is not an Armstrong number.
// Explanation 3*3*3+2*2*2+1*1*1 = 44

// Example
// Input: 4321
// Output: 4321 is not an Armstrong number.
// Explanation 4*4*4*4+3*3*3*3+2*2*2*2+1*1*1*1 = 354

// Example
// Input: 1634
// Output: 1634 is an Armstrong number.
// Explanation 1*1*1*1+6*6*6*6+3*3*3*3+4*4*4*4 = 1634

// Example
// Input: 0
// Output: 0 is an Armstrong number.
// Explanation 0 = 0



<|start_filename|>C-Plus-Plus/ds/BST_Range_Print.cpp<|end_filename|>
/*
Introduction 
Given a Binary Search Tree ,Print all the node values
which lies in the range of given low and high values inclusive


Argument/Return Type
Input of total no.of nodes is taken
Input of key values of nodes of tree are taken
*/

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

//Define Node as structure
struct Node 
{
    int key;
    Node* left;
    Node* right;
};
 
// Function to create a node with 'value' as the data stored in it. 
// Both the children of this new Node are initially null.
struct Node* newNode(int value)
{
    Node* n = new Node;
    n->key = value;
    n->left = NULL;
    n->right = NULL;
    return n;
}

// Function to insert a node with given value to the root
struct Node* insert(struct Node* root,int element) 
{
    //If the root is NULL , create a node with given element and assign it to root
    //else if the root itself is the node with given data , return 
    //else recursively insert it in one of the subtrees accordingly
    if(root==NULL)
        root = newNode(element);
    else if(root->key < element)
        root->right = insert(root->right,element);
    else if(root->key > element)
        root->left = insert(root->left,element);
    
    return root;
}

//Function to print all the node values of the BST within the given branch
void RangePrinter(struct Node* root,int low,int high)
{
    //if root is a NULL node , return
    if(root==NULL)
      return;
    
    //Traverse all required parts of the Tree , in Inorder Fashion
    //And Print the nodes if they satisfy the condition
    
    //If root key is greater than lower limit
    //recursively call the function for left subtree
    if(root->key > low)
      RangePrinter(root->left,low,high);
    
    //If root lies in the given range
    //Print its value
    if(root->key >= low && root->key <= high)
      cout<<root->key<<" ";

    //If root key is lesser than higher limit
    //recursively call the function for right subtree
    if(root->key < high)
      RangePrinter(root->right,low,high);
} 

// Driver code
int main()
{
    int n;
    cout<<"Enter total no.of nodes of the input Tree ( including NULL nodes ) : ";
    cin>>n;

    //create a null node  and initialise it as a NULL node
    struct Node* root;
    root=NULL;
    
    cout<<"Enter value of each node of the Tree , with head as the first value ( if a node is NULL , enter -1 ) with spaces"<<endl;
    for(int i=0;i<n;i++)
    {
        int data;
        cin>>data; 
        //take input of data of each node and insert it in the root
        root = insert(root,data);
    }

    cout<<"Enter two numbers for range , with space : ";
    int low,high;
    cin>>low>>high;

    //Call the function and print the result
    cout<<"Hence the node values within the given range is : ";
    RangePrinter(root,low,high);

    return 0; 
}
    
/*
Input:
0 <= node->key < 1000000000
While entering node values of the tree , 
value of the head of the tree should be enetered first

Sample Test Case 1  
Input Binary Tree 1:                    
            11                                                             
          /     \                                             
         2      20                                      
        / \    /  \                           
       1   5 NULL 25                                

Input Format : 
Example :
Enter total no.of nodes of the input Tree ( including NULL nodes ) : 6
Enter value of each node of the Tree , with head as the first value ( if a node is NULL , enter -1 ) with spaces
11 2 20 1 5 25
Enter two numbers for range , with space : 5 30

Output Format :
Example : ( Output to the above input example ) 
Hence the node values within the given range is : 5 11 20 25

Time/Space Complexity
Time Complexity : O(n) 
   Where n is the no.of nodes ofthe tree
Space Complexity : O(h) 
   Where h is the height of the tree
*/


<|start_filename|>C/dp/N-Queen.c<|end_filename|>
//This program solves the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other.
#include<stdio.h>

#include<conio.h>
#define INF 9999
char board[20][20];
int n, count;
int getMarked(int row)
{
  int i;
  for(i=0;i<n;i++)
  {
    if(board[row][i] == 'Q')
    {
      return i;
    }
  }
  return INF;
}
int feasible(int row, int col)
{
int i, tcol;
for(i=0;i<n;i++)
  {
    tcol = getMarked(i);
    if(col==tcol || abs(row-i)==abs(col-tcol))
    {
      return 0;
    }
  }
  return 1;
}
void printSolution()
{
  int i, j;
  printf("\n__Solution %d__\nCoordinates: ", count);
  for(i=0;i<n;i++)
  {
    for(j=0;j<n;j++)
    {
      if(board[i][j] == 'Q')
      {
        printf("(%d, %d)", i+1, j+1);
      }
    }
  }
  printf("\nBoard: __", count);
  for(i=1;i<=n;i++) 
  { 
    printf("___");
  }
  printf("\n      |  ");
  for(i=1;i<=n;i++) 
  { 
    printf(" %d ", i);
  }
  printf("|\n");
  for(i=0;i<n;i++)
  {
    printf("      |%d ", i+1);
    for(j=0;j<n;j++)
    {
      printf(" %c ", board[i][j]);
    }
    printf("|\n");
  }
  printf("       __");
  for(i=1;i<=n;i++) 
  { 
    printf("___");
  }
  printf("\n");
  getch();
}
void nQueens(int row)
{
  int i;
  if(row<n)
  {
    for(i=0;i<n;i++)
    {
      if(feasible(row,i))
      {
        board[row][i] = 'Q';
        nQueens(row+1);
        board[row][i] = '-';
      }
    }
  } 
  else
  {
    count++;
    printSolution();
  }
}
void main()
{
  int i, j;
  clrscr();
  printf("No of Queen (N) = ");
  scanf("%d", &n);
  for(i=0;i<n;i++)
  {
    for(j=0;j<n;j++)
    {
      board[i][j] = '-';
    }
  }
  nQueens(0);
  printf("\nTotal Solutions: %d", count);
  getch();
}


<|start_filename|>C/cp/painter_partition.c<|end_filename|>
#include <stdio.h>

int painters(int * arr, int maxtime, int len, int num) {
    int time = 0, count = 1;
    for (int i = 0; i < len; i++) {
        time += arr[i];
        if (time > maxtime) {
            time = arr[i];
            count++;
            if (count > num) {
                return 0;
            }
        }
    }
    return 1;
}

int get_max(int arr[], int len) {
    int max = arr[0];
    for (int i = 1; i < len; i++) {

        if (max < arr[i]) max = arr[i];
    }
    return max;
}

int main() {
    int len, num, time;
    int sum = 0;
    printf("Enter the length of array, num of painters and time: ");
    scanf("%d%d%d", & len, & num, & time);

    int arr[len];

    printf("Enter the array: ");
    for (int i = 0; i < len; i++) {
        scanf("%d", & arr[i]);
        sum += arr[i];
    }

    // Finding the max of array
    int start = get_max(arr, len);
    int end = sum, ans;
    while (start <= end) {
        int mid = (start + end) / 2;
        if (painters(arr, mid, len, num)) {
            ans = mid;
            end = mid - 1;
        } else {
            start = mid + 1;
        }
    }
    ans = ans * time;
    printf("Total time taken: %d", ans);

    return 0;
}
/*
Output:

Enter the length of array,num of painters and time: 2 2 5
Enter the array: 1 10
Total time taken: 50
Time complexity : O(n*log(N)) (where N is sum of array elements)
space complexity : O(n) (n is size of array)
*/


<|start_filename|>C-Plus-Plus/ds/Priority_Queue.cpp<|end_filename|>
#include<iostream>
#include<unordered_map>
#include<vector>
#include<algorithm>

using namespace std;

// MAX HEAP
class pQueue {
private:
  int heapSize;
  unordered_map <int, vector<int>> heapMap;
  vector <int> heapElements;

public:
  pQueue() {
    heapSize = 0;
  }

  void add(int element) {
    heapSize++;
    heapElements.push_back(element);
    if (heapMap.find(element) == heapMap.end()) {
      heapMap[element] = vector <int> ({heapSize - 1});
    } else {
      heapMap[element].push_back(heapSize - 1);
    }
    maintainLoopVariant(heapSize - 1);
  }

  void remove(int element) {
    if (heapMap.find(element) != heapMap.end()) {
      int index = heapMap[element][0];
      int lastIndex = heapSize - 1;
      swapBubbles(index, lastIndex);
      heapElements.pop_back();
      vector <int> newIndexes({});
      for (int i = 0; i < heapMap[element].size(); i++) {
        if (heapMap[element][i] != lastIndex) newIndexes.push_back(heapMap[element][i]);
      }
      heapMap[element] = newIndexes;
      heapSize--;
      maintainLoopVariant(index);
    }
  }

  void poll() {
    // remove the first element from heap array
    remove(heapElements[0]);
  }

  void maintainLoopVariant(int index) {
    /*
        Check for heap-invariant
        First check with the parent element, then the maximum of the children and lastly the minimum
    */
    int indexMaxChild = -1, indexMinChild = -1;
    if (2 * index + 2 < heapSize) {
      // both child exist
      indexMaxChild = heapElements[2 * index + 1] >= heapElements[2 * index + 2] ? 2 * index + 1 : 2 * index + 2;
      indexMinChild = heapElements[2 * index + 1] < heapElements[2 * index + 2] ? 2 * index + 1 : 2 * index + 2;
    }
    else if (2 * index + 1 < heapSize) {
      // only left child exist
      indexMaxChild = 2 * index + 1;
    }

    if ((index - 1) / 2 >= 0 && heapElements[index] > heapElements[(index - 1) / 2]) {
      swapBubbles(index, (index - 1) / 2);
      maintainLoopVariant((index - 1) / 2);
    } else if (indexMaxChild != -1 && heapElements[index] < heapElements[indexMaxChild]) {
      swapBubbles(index, indexMaxChild);
      maintainLoopVariant(indexMaxChild);
    } else if (indexMinChild != -1 && heapElements[index] < heapElements[indexMinChild]) {
      swapBubbles(index, indexMinChild);
      maintainLoopVariant(indexMinChild);
    }
  }

  void swapBubbles(int index, int newIndex) {
    int element = heapElements[index];
    int newElement = heapElements[newIndex];
    heapElements[index] = newElement;
    heapElements[newIndex] = element;

    for (int i = 0; i < heapMap[element].size(); i++) {
      if (heapMap[element][i] == index) {
        heapMap[element][i] = newIndex;
        sort(heapMap[element].begin(), heapMap[element].end());
        break;
      }
    }
    for (int i = 0; i < heapMap[newElement].size(); i++) {
      if (heapMap[newElement][i] == newIndex) {
        heapMap[newElement][i] = index;
        sort(heapMap[newElement].begin(), heapMap[newElement].end());
        break;
      }
    }
  }

  void show() {
    cout << "Elements in index-based heap: ";
    for (int i = 0; i < heapSize; i++) cout << heapElements[i] << " ";
    cout << endl;
  }
};

int main() {
  pQueue pq;

  // Inserting elements
  pq.add(7);
  pq.add(5);
  pq.add(1);
  pq.add(2);
  pq.add(3);
  pq.add(4);
  pq.add(6);

  // Showing index based heap
  pq.show();

  pq.remove(4);
  pq.show();

  pq.poll();
  pq.show();
}


<|start_filename|>C-Plus-Plus/other/find_duplicate_elements_from_an_array.cpp<|end_filename|>
/*
Given an array of N elements, each element's occurrence in the array can be more than once. Find all elements whose occurrence is more than 1.
Formally find all duplicate elements of the array. This can be done with the help of map and set data structure.
*/

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

void dupicate_elements(int ar[] ,int N)
{
    /* we will insert the array elements into the map. if current element already in the map,
    then definitely that element's occurrence is more than 1. 
    Hence it is duplicate and will insert in the set*/
    map < int, int > unique_elements;
    set < int > duplicates;
    for(int i = 0; i < N; i++)
    {
        if(!unique_elements[ar[i]])
            unique_elements[ar[i]]++;
       else
       {
           // this is a duplicate
           duplicates.insert(ar[i]);
       }
    }
    cout << "Duplicate elements are : ";
    for(auto i : duplicates)
        cout << i << ' ';
    cout << endl;
    return;
}

int main()
{
    cout << "Enter the size of the array : ";
    int N; 
    cin >> N;
    int ar[N + 1];
    cout << "Enter array elements :\n";
    for(int i = 0; i < N; i++)
    {
        cin >> ar[i];
    }
    dupicate_elements(ar , N);
}

/*
Standard Input and Output

Enter the size of the array : 12
Enter array elements
1 5 2 1 4 3 1 7 2 8 9 5
Duplicate elements are : 1 2 5

Time Complexity : O(logN)
Space Complexity : O(N)

*/


<|start_filename|>Julia/cp/Maximum_subarray_sum.jl<|end_filename|>
#=Given an Array you need to find the maximum sum of all the 
subarrays. Subarrays are consecutive elements of the array.
There are a total of n*(n+1)/2 subarrays in an array with 
n elements. Out of all these sub arrays find the subarray with
the maximum sum. Kadane's Algorithm helps us to do this in 
the least time complexity.=#

## Function

function maxSubArray(array)
    best = 0
    sum = 0
    for i in array
        sum = max(i, sum + i)
        best = max(sum, best)
    end
    return best
end

## Input

n = readline()
n = parse(Int64, n)
arr = Int64[]
for i = 1:n
    temp = readline()
    temp = parse(Int64, temp)
    push!(arr, temp)
end

## Calling the function

print(maxSubArray(arr))

#=
Sample test case:
Input:
    n = 5
    array = 2 -3 5 4 -7
Output:
    9

Time complexity: O(N)
=#


<|start_filename|>C-Plus-Plus/ds/avl_tree.cpp<|end_filename|>
/* 
AVL Trees: These are self-balancing trees where the difference between the heights
of left and right subtree(for any node) is not more than 1 and less than -1. This concept
came about so as to ensure that the opeations on BST doesn't become of the order of O(n)
as it becomes more and more skewed. In other words, AVL trees ensures that the balance of 
the tree is maintained, thus maintaining the order of the operations on it as O(log n).
properties of AVL:
 (1) It is a BST and (2) No duplicate nodes allowed 
 (3) |height of left subtree - height of right subtree| <=1
*/
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
struct Node{
    Node* left;
    Node* right;
    int data;
    int bf;//balance factor of the node
    int height;
};

int find_height(Node* current_node){
    if(current_node==NULL) return(0);
    //cur_node is the pointer to the current Node
    Node* node=current_node;
    //The balance factor >0 means that left subtree has greater height
    //if it is <0 then, right subtree has greater height
    if(node->bf>=0){
        node = node->left;
    }
    else if(node->bf<0){
        node = node->right;
    }
    int height=0;
    while(node!=NULL){
        height++;
        if(node->bf<0){
            node = node->right;
        }
        else if(node->bf>=0){
            node = node->left;
        }
    }
    //one is added as the height of a single node is 1 and is added to
    //the height of the longest subtree.
    return(1+height);
}

//critical node is a node which has a balance factor either
// greater than  1 or less than -1.

int find_balance_factor(Node* node){
    return(find_height(node->left)-find_height(node->right));
}


/*
right rotation can be illustrated as follows:

   (critical_node)                                     (next_node)
    /                       (right rotation)           /          \
 (next_node)             ====================>        x        (critical_node)        
  /    \                                                        /                     
 x      y                                                      y

   Steps performed for above transformation:
    (i)   store the right node(i.e. y here) of the (next_node) to a temporary node (temp).
    (ii)  assign (critical_node) as (next_node)'s right child.
    (iii) assign node stored in temp as the left node of (critical_node).
    (iv)  update the height and balance factor of the next_node and critical_node.
*/
Node* right_rotate(Node* critical_node){
    Node* next = critical_node->left;
    Node* temp = next->right;
    next->right=critical_node;
    critical_node->left=temp;

    //updating height and balance factors for the rotated nodes
    next->height=find_height(next);
    next->bf = find_balance_factor(next);

    critical_node->height=find_height(critical_node);
    critical_node->bf = find_balance_factor(critical_node);
    return(next);
}

/*
Left rotation can be illustrated as follows:

   (critical_node)                                          (next_node)
                \               (left rotation)            /           \
              (next_node)    ====================>     (critical_node)  z      
                /    \                                             \           
               y      z                                             y          

   Steps performed for above transformation:
    (i)   store the left node(i.e. y here) of the (next_node) to a temporary node (temp).
    (ii)  assign (critical_node) as (next_node)'s left child.
    (iii) assign node stored in temp as the right node of (critical_node).
    (iv)  update the height and balance factor of the next_node and critical_node.
*/

Node* left_rotate(Node* critical_node){
    Node* next = critical_node->right;
    Node* temp = next->left;
    next->left = critical_node;
    critical_node->right = temp;

    //updating height and balance factors for the rotated nodes
    next->height=find_height(next);
    next->bf = find_height(next->left)-find_height(next->right);

    critical_node->height=find_height(critical_node);
    critical_node->bf = find_height(critical_node->left)-find_height(critical_node->right);
    return(next);
}

/*
finds the parent node of the given node. It keeps
traversing the tree until it reaches the given node.
It traverses as:
 -> if(root->data > node->data) then node is to be searched in the left subtree.
 -> if(root->data < node->data) then node is to be searched in the right subtree.
*/
Node* find_parent_node(Node* root, Node* node){
    Node* parent=NULL;
    while(root!=node){
        parent=root;
        if(root->data>node->data){
            root=root->left;
        }
        else if(root->data<node->data){
            root=root->right;
        }
    }
    return(parent);
}

/*
This function finds the critical node in the AVL Tree
The idea here is that critical nodes closest to the
deleted or inserted node are more likely to be found
in the subtree which contains the "affected area" and within that subtree,
the longest subtree. So, traversal of the tree is done:
   (i) to the right  if the balance factor of the given node<-1
   (ii) to the left if balance factor>1
root of the affected subtree is given as the argument in this
function.
*/
Node* find_critical_node(Node* root){
    Node* critical_node=NULL;
    while(root!=NULL){
        root->bf=find_balance_factor(root);
        if(root->bf>1){
            critical_node=root;
            root=root->left;
        }
        else if(root->bf<-1){
            critical_node=root;
            root=root->right;
        }
        else{
            root=root->left;
        }
    }
    return(critical_node);
}

/*
This function finds the inorder predecessor of a node.
For a node, its predecessor can be found by finding the
rightmost element in the left subtree of the tree
whose root is the node whose predecessor is to be found.
*/
Node* find_predecessor(Node* root, Node* &parent){
    Node* node=root;
    parent=node;
    node=node->left;
    while(node->right!=NULL){
        parent=node;
        node=node->right;
    }
    return(node);
}

/*
this function balances our AVL tree(in case of deletion).
we have the following cases covered below:
 (1)if critical node has balance factor>1 and the node to
    its left has a balance factor either 0 or 1 then we apply right rotation.Example,
     y         y
    /         /
   x(0) or   z (1)
  / \       /
 w   z     x
 (2)if it has balance factor>1 and balance factor of its left node= -1, then,
     z                   z                    y
    / (left rotate)     /  (right rotate)    / \
    x    =======>      y      ========>     x   z
     \                /
      y              x

 (3)if node has balance factor<-1 and its right node has balance factor
    either 0 or -1 then apply left rotation. example of these cases,
    x                  w
     \                  \
      y(-1)      or      y(0)
       \                / \
        z              x   z

 (4)if it has balance factor<-1 and balance factor of its left node= 1, then,
    w(-2)                      w                          x
     \      (right rotate)      \      (left rotate)     / \
      y(1) ===============>      x    ===============>  w   y
     /                            \
    x                              y
*/
Node* balance_tree(Node* node){
    if(node->bf>1 && (node->left->bf==1 || node->left->bf==0)){
        node=right_rotate(node);
    }
    else if(node->bf>1 && node->left->bf==-1){
        node->left=left_rotate(node->left);
        node=right_rotate(node);
    }
    else if(node->bf<-1 && (node->right->bf==-1 || node->right->bf==0)){
        node=left_rotate(node);
    }
    else if(node->bf<-1 && node->right->bf==1){
        node->right=right_rotate(node->right);
        node=left_rotate(node);
    }
    return(node);
}

Node* delete_node(Node* node, int key ,int root_value){
    if(node==NULL){
        return(node);
    }
    if(node->data>key){
        node->left=delete_node(node->left,key,root_value);
    }
    else if(node->data<key){
        node->right=delete_node(node->right,key,root_value);
    }
    else{
        if(node->left==NULL && node->right==NULL){
            //for node having no child, just delete it.
            node=NULL;
        }
        else if(node->left!=NULL && node->right==NULL){
            //if node to be deleted only has left child
            node=node->left;
        }
        else if(node->left==NULL && node->right!=NULL){
            //if node to be deleted only has right child
            node=node->right;
        }
        else{
            /*
            if the node to be deleted has two child nodes, then we
            find its inorder predecessor and the parent node of that
            predecessor.
            we now have two cases:
             (i)if parent of predecessor = node to be deleted then the case
                would look like this:
                  (node to deleted)
                 /                 \
                (predecessor)     (right node)
                /
               (node)
               In this case, we just assign predecessor->right = (node_to_be_deleted)->right

             (ii)      (node_to_be_deleted)
                       /                  \
                      x                    z
                     / \
                    w   y
                    here, y is found to be the predecessor for the node to be deleted.
                    so we perform the following:
                     - y->left = node->left
                     - y->right= node->right
                     - x->right = NULL
                     - update the height and balance factor of predecessor and the parent of
                       predecessor.
                    x->right=NULL
            */
            Node* parent_of_pred=NULL;//parent of predecessor node
            Node* pred=find_predecessor(node,parent_of_pred);

            if(parent_of_pred==node){
                pred->right=node->right;
            }
            else{
                pred->left=node->left;
                pred->right=node->right;
                parent_of_pred->right=NULL;
                parent_of_pred->height=find_height(parent_of_pred);
                parent_of_pred->bf=find_balance_factor(parent_of_pred);
            }
            node=pred;
        }
        if(node!=NULL){
            //updating the height and balance factor of predecessor node
            //after inserting it in deleted node's position
            node->height=find_height(node);
            node->bf=find_balance_factor(node);
            if(node->bf>1 || node->bf<-1){
                node=balance_tree(node);
            }
        }
        if(key!=root_value){
            //if node deleted isn't root node
            return(node);
        }
        else if(node==NULL){
            //if only root node existed originally,
            //but now its deleted.
            return(node);
        }
    }
    if(key==root_value){
        /*
        if root node is deleted, then our recursive function won't be able to
        backtrack and check the balance of the tree after deletion.
        So, here we first find critical node and if any, then we find its
        parent as well. We then balance the tree using appropriate rotations and
        attach this new node to its parent node.
        Then we return the root node.
        */
        Node* critical=find_critical_node(node);

        if(critical!=NULL){
            Node* parent=find_parent_node(node,critical);

            critical=balance_tree(critical);

            if(parent->data>critical->data){
                parent->left=critical;
            }
            else{
                parent->right=critical;
            }
        }
        return(node);
    }
    /*
    if any other node is being deleted, then the function moves backwards
    from the position where the node is deleted from, and checks for the
    balance factor and updates it along with their height. If critical node
    is found then, the tree is balanced with appropriate rotations and that
    node is returned.
    */
    node->height=find_height(node);
    node->bf=find_balance_factor(node);
    node=balance_tree(node);
    return(node);
}

Node* create_node(int data){
    Node* node = new Node;
    node->bf=0;
    node->height=1;
    node->left=NULL;
    node->right=NULL;
    node->data=data;
    return(node);
}

Node* insert_node(Node* node,int data){
    if(node==NULL){
        node=create_node(data);
        return(node);
    }
    if(node->data>data){
        node->left=insert_node(node->left,data);
    }
    else if(node->data<data){
        node->right=insert_node(node->right,data);
    }
    else{
        //if the same data is added more than once then, it returns the existing node with that data
        return(node);
    }
    //Node->height=1+max(find_height(Node->left),find_height(Node->right));
    node->height=find_height(node);
    node->bf = find_balance_factor(node);

    if(node->bf>1 && node->left->bf==1){
        node=right_rotate(node);
    }
    else if(node->bf>1 && node->left->bf==-1){
        node->left=left_rotate(node->left);
        node=right_rotate(node);
    }
    else if(node->bf<-1 && node->right->bf==-1){
        node=left_rotate(node);
    }
    else if(node->bf<-1 && node->right->bf==1){
        node->right=right_rotate(node->right);
        node=left_rotate(node);
    }
    return(node);
}

/*
preorder traversal of AVL tree and for each node it also displays
their balance factor in brackets.
*/
void preorder_traversal(Node* node){
    if(node!=NULL){
        cout<<node->data<<"("<<node->bf<<") ";
        preorder_traversal(node->left);
        preorder_traversal(node->right);
    }
}

int main()
{
    Node* root=NULL;
    int n; //number of nodes in the tree
    cout<<"Enter the number of nodes to be inserted: ";
    cin>>n;
    cout<<"Enter the node values: ";
    vector<int>data(n);
    for(int i=0;i<data.size();i++){
        cin>>data[i];
        root=insert_node(root,data[i]);
    }
    cout<<"\npreorder traversal of the AVL tree:\n";
    preorder_traversal(root);
    cout<<"\n";

    int m;//number of elements to be deleted
    cout<<"\nEnter the number of nodes to be deleted: ";
    cin>>m;
    cout<<"Enter the node values to be deleted: ";
    vector<int>deletion_order(m);
    for(int i=0;i<deletion_order.size();i++){
        cin>>deletion_order[i];
        root=delete_node(root,deletion_order[i],root->data);
        cout<<"\nafter deleting node with key value = "<<deletion_order[i]<<"\n";
        preorder_traversal(root);
        cout<<"\n";
    }
    return 0;
}
/* 
Time Complexities:
 (1) insertion operation: O(log n)
 (2) deletion operation: O(log n)
 (3) finding critical node: O(log n)
 (4) finding parent node: O(log n)
 (5) finding height of the tree: O(log n)
*/

/*
Test Case 1:
  (insertion)

  Input:
  13
  14 17 11 7 53 4 13 12 8 60 19 16 20
  Output(preorder traversal):
  14(0) 11(0) 7(0) 4(0) 8(0) 12(-1) 13(0) 19(0) 17(1) 16(0) 53(0) 20(0) 60(0)

  (deletion)
  Input:
  5
  14 13 19 17 12
  Output:
  after deleting node with key value = 14
    13(0) 11(1) 7(0) 4(0) 8(0) 12(0) 19(0) 17(1) 16(0) 53(0) 20(0) 60(0)

  after deleting node with key value = 13
    12(0) 7(-1) 4(0) 11(1) 8(0) 19(0) 17(1) 16(0) 53(0) 20(0) 60(0)

  after deleting node with key value = 19
    12(0) 7(-1) 4(0) 11(1) 8(0) 17(-1) 16(0) 53(0) 20(0) 60(0)

  after deleting node with key value = 17
    12(0) 7(-1) 4(0) 11(1) 8(0) 53(1) 16(-1) 20(0) 60(0)

  after deleting node with key value = 12
    11(-1) 7(1) 4(0) 53(1) 16(-1) 20(0) 60(0)
*/

/*
The AVL Tree example used in this code:
                       14
                /            \
               11             19
              /   \         /    \
             7     12       17    53
            / \      \     /      / \
           4   8     13   16    20   60


after deleting 14 it should look like this:
                     13
                /            \
               11             19
              /   \         /    \
             7     12      17    53
            / \            /     / \
           4   8          16   20   60

after deleting 13 it should look like this:
                       12
                   /        \
                7             19
              /   \         /    \
            4      11      17    53
                   /       /     / \
                  8       16   20   60

after deleting 19 it should look like this:
                        12
                    /        \
                  7           17
                /   \        /  \
               4      11    16   53
                     /          /  \
                    8          20   60

after deleting 17 it should look like this:
                        12
                      /    \
                     7      53
                   /  \     / \
                  4   11   16  60
                     /       \
                    8         20

 */

//Other cases that you could try:
//vector<int>data={10,20,30,40,50,25};
//vector<int>data={33,13,53,9,21,61,8,11};
//vector<int>data={14,13};



<|start_filename|>C/cp/Activity_selection.c<|end_filename|>
// C Code for Activity Selection
//Greedy Algorithm approach
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

//swap function to check and swap values
void swap(int *x,int *y)
{
	int temp;
	temp=*x;
	*x=*y;
	*y=temp;
}

//Main function start
int main()
{
	int num,i,j,prev=0,count=1;
	int *start,*finish;
	//Dynamic Memory Allocation for arrays
	start = (int*) malloc(num * sizeof(int));
	finish = (int*) malloc(num * sizeof(int));
	//Take number of activites as a input
	printf("Enter the number of activities :");
	scanf("%d",&num);
	//Take start and finish time as a input
	printf("\nEnter the start and finish time of activities :\n");
	for(i=0;i<num;i++)
	{
		scanf("%d",&start[i]);
		scanf("%d",&finish[i]);
	}
	//sorting starts here
	//Bubble sort - compare adjacent element and swap it
	for(i=0;i<num;i++)
	{
		/*In bubble sort, 
		maximum value is placed at last index
		In each pass we left the last index i.e num-1-i
                */
		for(j=0;j<num-1-i;j++)
		{
			if(finish[j]>finish[j+1])
			{
				//call swap function
				//pass by address
				swap(&finish[j],&finish[j+1]);
				swap(&start[j],&start[j+1]);
			}
		}
	}
	/*condition for Activity selection
	update prev each time
	with current of start i.e i
	count variable will see
	number of activites possible
        */
	for(i=1;i<num;i++)
	{
		if(start[i]>=finish[prev])
		{
			count++;
			prev=i;
		}
	}
	//print the output
	printf("\tOUTPUT\n");
	printf("\nTotal number of activities person can perform at a time is -> %d \n",count);
	return 0;
}
//Main function end 

/*Sample Input Output
Enter the number of activities : 6
Enter the start and finish time of activities :
1 2
3 4
2 6
5 7
8 9
5 9
	OUTPUT
Total number of activities person can perform at a time is -> 4
*/

/*
Time Complexity :
The complexity of this problem is O(n log n) when the list is not sorted.
When the sorted list is provided the complexity will be O(n)
*/


<|start_filename|>C-Plus-Plus/dp/Max_subarray_sum(DP).cpp<|end_filename|>
/*
This approach uses Dynamic Programming and Prefix Sum to find out maximum
subarray sum in Linear time. Alternate approach could be to use Kadane's
algorithm using O(1) extra space.
*/

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

int main() {
	long long int t, n, i, j;                    //t -> no. of testcases, n -> size of array
	cin >> t;
	while (t--) {
		cin >> n;
		long long int a[n];
		for (i = 0; i < n; i++)                  //input array
			cin >> a[i];

		long long int pre_sum[n];
		pre_sum[0] = a[0];
		for (i = 1; i < n; i++)                  //array that stores prefix sum of input array
			pre_sum[i] = pre_sum[i - 1] + a[i];

		long long int res = INT_MIN, min_pre_sum = 0;
		for (i = 0; i < n; i++) {
			res = max(res, pre_sum[i] - min_pre_sum);               //loop through array while keeping track of minimum prefix sum so far and maximum subarray sum
			min_pre_sum = min(min_pre_sum, pre_sum[i]);
		}
		cout << res << "\n";
	}
	return 0;
}

/*
Time Complexity : O(n)
Space Complexity: O(n)

Sample Input:
2                        //no. of testcases
8                        //size of array
4 -8 9 -4 1 -8 -1 6
9                        //size of array
-2 1 -3 4 -1 2 1 -5 4
Sample Output:
9
6
*/


<|start_filename|>C/sort/ShellSort.c<|end_filename|>
//C Program to sort an array using Shell Sort technique
#include <stdio.h>
//ShellSort Function
void ShellSort(int arr[], int num)
{
    int gap, i, j, tmp;
    //this for loop of gap is the heart of Shell sort
    //In each pass w check the valu of gap
    //if gap=1 then we stop this loop
    for (gap = num / 2; gap > 0; gap = gap / 2)
    {
        for (i = gap; i < num; i++)
        {
        	//loop continue for index lesser then gap
            for(j = i - gap; j >= 0; j = j - gap)
            {
            	//if lesser index value is small
            	//compared to bigger index
            	//then continue
                if (arr[j+gap] >= arr[j])
                    break;
                //else    
                // Swap values of bigger index with smaller one   
                else
                {
                    tmp = arr[j];
                    arr[j] = arr[j+gap];
                    arr[j+gap] = tmp;
                }
            }
        }
    }
}
//Display function to print the result
void display(int arr[],int n)
{
	int i;
printf("\n\nSorted Array in ascending order is : \n");
for(i=0; i < n; ++i)
printf("%5d",arr[i]);
}
//Main Function
int main()
{
    int i,k, num;
    //Enter the number of element array have
    printf("Enter total number of elements :: ");
    scanf("%d",&num);
    //store the element of array
    int arr[num];
    //Input values of array
    printf("Enter elements :: ");
    for(i = 0; i < num; i++)
    {
        scanf("%d",&arr[i]);
    }
    //Call shell sort function
    ShellSort(arr,num);
    //call display function
    display(arr,num);
    return 0;
}
//end of Main function

/*Sample Input Output
Enter total number of elements :: 10
Enter elements : 36 432 43 44 57 63  94 3 5 6

Sorted Array in ascending order is :
    3    5    6    36     43     44     57     63     94     432
*/

/*Complexity

Worst case time complexity is O(n2) 
Best case complexity is O(nlog(n)).
Space complexity is O(1).
*/


<|start_filename|>C-Plus-Plus/cp/Array_Manipulation.cpp<|end_filename|>
/*
Problem link : https://www.hackerrank.com/challenges/crush/problem

Problem description:
Starting with a 1-indexed array of zeros and a list of operations, for each query add a value to each the array element between two given indices, inclusive.
Once all operations have been performed, return the maximum value in the array.
*/

#include <bits/stdc++.h>
using namespace std;
#define ll long long int

void Max_Value(int n, int m)
{
  int a, b, k;
  vector<ll> prefix_sum(n + 1, 0);
  for (ll queries = 1; queries <= m; queries++)
  {
    cin >> a >> b >> k;
    // Adding k at the starting point of the query
    prefix_sum[a] += k;
    // Subtracting K at the position after end point of query if and only if, it is valid.
    if ((b + 1) <= n)
    {
      prefix_sum[b + 1] -= k;
    }
  }
  ll answer = INT_MIN;
  for (ll index = 1; index <= n; index++)
  {
    prefix_sum[index] += prefix_sum[index - 1];
    answer = max(answer, prefix_sum[index]);
  }
  cout << answer << endl;
}

int main()
{
  ll n, m;
  cin >> n >> m;
  // Max_value function prints the required answer after performing all queries.
  Max_Value(n, m);
}

/*
Time Complexity  : O(n)
Space Complexity : O(n)
Input:
5 3
1 2 100
2 5 100
3 4 100
Output:
200
*/



<|start_filename|>C-Plus-Plus/ds/Balanced_BST_From_a_vector_of_values.cpp<|end_filename|>
/*
Introduction 
Given a vector of values , Build a Balanced BST with them

Argument/Return Type
Input of total no.of nodes is taken
Input of key values of nodes of tree are taken
*/

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

//Define Node as structure
struct Node 
{
    int key;
    Node* left;
    Node* right;
};
 
/* Function to create a node with 'value' as the data stored in it. 
 Both the children of this new Node are initially null. */
struct Node* newNode(int value)
{
    Node* n = new Node;
    n->key = value;
    n->left = NULL;
    n->right = NULL;
    return n;
}

// Function to insert a node with given value to the root
struct Node* insert(struct Node* root,int element) 
{
    /*If the root is NULL , create a node with given element and assign it to root
    else if the root itself is the node with given data , return 
    else recursively insert it in one of the subtrees accordingly */
    if(root==NULL)
        root = newNode(element);
    else if(root->key < element)
        root->right = insert(root->right,element);
    else if(root->key > element)
        root->left = insert(root->left,element);
    
    return root;
}

// Function to print Tree in  level order
void LevelOrderTraversal(struct Node* root)
{
    // If root is NULL , return 
    if (root == NULL)
        return ;

    // Create an queue
    queue<struct Node*> q;
    //Enqueue the root node 
    q.push(root);
 
    while (!q.empty()) 
    {
        cout<<q.front()->key<<" ";
        //Enqueue node's children , if they exist
        if(q.front()->left)
            q.push(q.front()->left);
        if(q.front()->right)
            q.push(q.front()->right);
        q.pop();
    }
    return ;
}

//Utility function to remove duplicates from a vector of sorted values
vector<int> RemoveDuplicates(vector<int>values)
{
   //declare a new vector
   vector<int>newVector;

   for(int i=0;i<values.size();i++)
   {
      //Push the values which are not already pushed
      if(i==0 || i && values[i]!=values[i-1])
          newVector.push_back(values[i]);
   }

   return newVector;
}

//Utility Function to build a balanced BST recursively after sorting the given vector values
struct Node* BuildBalancedBSTUtil(vector<int>v,int start,int end)
{
    //Declare a node and initialise it to NULL
    struct Node* root;

    if(start>end)
    {
        /*If start index is more than end index 
        assign a NULL node to the root */
        root = NULL;
    }
    else if(start==end)
    {
        /*If start index equal to end index 
        assign a new leaf node with the value as v[start] */
        root = newNode(v[start]);
    }
    else
    {
       /*else create a new node with a value of mid element of vector
       care must be taken to get mid index , to avoid overflow */
       int mid = start + (end-start)/2;
       root = newNode(v[mid]);

       //and recursively build subtrees of the root
       root->left = BuildBalancedBSTUtil(v,start,mid-1);
       root->right = BuildBalancedBSTUtil(v,mid+1,end);
    }
    
    return root;
}

//Function to build Balanced BST from given vector values
struct Node* BuildBalancedBST(vector<int>values)
{
    //sort the given vector values
    sort(values.begin(),values.end());
    
    /* To make sure there are no duplicate values ,
    Remove all the duplicates from the sorted vector */
    values = RemoveDuplicates(values);

    //Declare a node pointer and store the return value of the utility function
    struct Node* root = BuildBalancedBSTUtil(values,0,values.size()-1);

    return root;
}

// Driver code
int main()
{
    int n;
    cout<<"Enter total no.of nodes of the input Tree ( including NULL nodes ) : ";
    cin>>n;
    
    //create a vector to take input and store them
    vector<int>values;

    cout<<"Enter value of each node of the Tree , with spaces"<<endl;
    for(int i=0;i<n;i++)
    {
        int value;
        cin>>value; 
        values.push_back(value);
    }   

    //Call the function and print the result
    struct Node* root;
    root=BuildBalancedBST(values);
    cout<<"Hence the level order of Balanced BST built is : ";
    LevelOrderTraversal(root);

    return 0; 
}
    
/*
Input:
0 <= node->key < 1000000000
While entering node values of the tree , 
value of the head of the tree should be enetered first

Sample Test Case 1  
Input Binary Tree 1:                    
             5                                                             
          /     \                                             
         1      20                                      
        / \    /  \                           
    NULL   2  11  25                                

Input Format : 
Example :
Enter total no.of nodes of the input Tree ( including NULL nodes ) : 6
Enter value of each node of the Tree , with spaces
1 5 25 2 20 11

Output Format :
Example : ( Output to the above input example ) 
Hence the level order of Balanced BST built is : 5 1 20 2 11 25

Time/Space Complexity
Time Complexity : O(n) 
   Where n is the no.of nodes ofthe tree
Space Complexity : O(h) 
   Where h is the height of the tree
*/


<|start_filename|>C-Plus-Plus/ds/BinarySearchTree.cpp<|end_filename|>
#include <iostream>
using namespace std;

/* A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned properties

The value of the key of the left sub-tree is less than the value of its parent (root) node's key.

The value of the key of the right sub-tree is greater than or equal to the value of its parent (root) node's key.*/

// This program implements insetion,Deletion and Searching in Binary Search Tree(BST)

struct Node{               //Structure is declared which holds Node data and address of left and right child
    struct Node *lchild;
    int data;
    struct Node *rchild;
}*root=NULL;      // root object is declared globally for struct Node

void insert(int element)    //Insertion happens here
{
    struct Node *p=root;   // using 2 pointers for keeping track of Nodes
    struct Node *q,*tmp;
    tmp= new Node;
    tmp->data=element;
    tmp->lchild=tmp->rchild=NULL;
    if(root==NULL)
    {
        root=tmp;
    }
    else
    {
        while(p!=NULL)
        {
            q=p;
            if(p->data==element)
            {
                return;
            }
            else if(element < p->data)  //if Inserted data is less than current Node data, move to left child
            {
                p=p->lchild;
            }
            else{
                p=p->rchild;    //if Inserted data is greater than or equal to current Node data, move to right child
            }
        }
        if(element > q->data) 
        {
            q->rchild=tmp;
        }
        else
            q->lchild=tmp;
    }
}

void Search(Node *p,int key)  //Seraching operation takes key as input and search for key in BST
{
    if(p==NULL)
    {
        cout << " BST is empty" << endl;
    }
    else{
        while(p!=NULL)
        {
            if(p->data==key)
            {
                cout << "Element is found" << endl;
                return;
            }
            else if(key < p->data)
            {
                p=p->lchild;
            }
            else{
                p=p->rchild;
            }
        }
    }
    cout << "Element not found "<<endl;
        
}

void InOrder(Node *p)   //Inorder travesal is used because inorder of BST gives Sorted output
{
    if(p)
    {
        InOrder(p->lchild);
        cout << p->data << " ";
        InOrder(p->rchild);
    }

}

int Height(Node *p)  //To find height of corresponding Node
{
int x,y;
if(p==NULL)return 0;
x=Height(p->lchild);
y=Height(p->rchild);
return x>y?x+1:y+1;
}

/*For deleting any Node on BST, Deleted Node has to be replaced with Appropiate Node without affecting the property of BST
If we are deleting any node, corresponding Node should be replaced by either InOrder predecessor or Inorder Successor based on height condition*/

struct Node * InOrderpredecssor(Node *p)  //If height of left child is greater than right child,it will enter this loop
{
    while(p && p->rchild!=NULL)
    {
        p=p->rchild;
    }
    return p;
}

struct Node * InOrderSuccessor(Node *p)  //If height of left child is less than right child,it will enter this loop
{
    while(p && p->lchild!=NULL)
    {
        p=p->lchild;
    }
    return p;
}

struct Node * Delete(Node *p,int key)
{
    struct Node *q;
    if(p==NULL)
    {
        return NULL;
    }
    if(p->lchild==NULL && p->rchild==NULL)
    {
        delete p;
        return NULL;
    }
    if(key < p->data)
    {
        p->lchild=Delete(p->lchild,key);
    }
    else if(key > p->data)
    {
        p->rchild=Delete(p->rchild,key);
    }
    else
    {
        if(Height(p->lchild) > Height(p->rchild))
        {
            q=InOrderpredecssor(p->lchild);
            p->data=q->data;
            p->lchild=Delete(p->lchild,q->data);
        }
        else
        {
            q=InOrderSuccessor(p->rchild);
            p->data=q->data;
            p->rchild=Delete(p->rchild,q->data);
            
        }
    }
return p;
}

int main()
{
    int Num,data,searchdata;
    cout << "Enter Number of data to be instered in BST: "<<endl;
    cin >> Num;
    cout <<"Enter the node values: " << endl;  //Enter the Node values to be inserted into BST
    for(int i=0;i<Num;i++)
    {
        cin >> data;
        insert(data);
    }
    cout <<"Elements in BST are: "<< endl;
    InOrder(root);
    cout << endl;
    cout << "Enter any node value to search in BST:" << endl;
    cin >> searchdata;
    Search(root,searchdata);
    cout <<"Enter the value to be deleted in BST: " << endl;
    cin >> data;
    Delete(root,data);
    cout << "After deleting Node: " << endl;
    InOrder(root);
    cout << endl;
    return 0;
}


<|start_filename|>C/cryptography/Burrows_Wheeler_Transform.c<|end_filename|>
/*Below is an implementation of Burrows Wheeler Transform in C. It restructures
the given plaintext to forms the ciphertext. It first forms all possible cyclic
rotations of the plaintext, and then sorts the rotations lexicographically. Then,
ciphertext is formed by taking the last character of each rotation sorted in
lexicographical order. This code is implemented keeping in mind that characters
in the plaintext are all unique.*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Define maximum length of plaintext, ciphertext
#define MAXLENGTH 100

// Define size of plaintext
#define size 6

// This function generates all cyclic rotations of given plaintext
void generate(char* plaintext, char combinations[][size]) {

	int index = 0;
	for(int i = 0; i < size; i++) {
		for(int j = 0; j < size; j++) {
			// Mod is used to wrap around the index
			combinations[i][j] = plaintext[(index + j) % size];
		}
		index += 1;
	}
}

// This function sorts the above rotations lexicographically.
void sort(char* plaintext, char combinations[][size], int arr[size]) {

	// Calling the generate function to generate all rotations
	generate(&plaintext[0], combinations);

	int count = 0;
	int k = 0;

	while(k < size) {

		// Iterate through the first column
		for(int i = 0; i < 1; i++) {
			/* Char { is lexicograqphically greater than
			[A-Z] and [a-z]. So, we use it here as a maximum.*/
			char min = '{';
			int index;

			// Iterate though first element of each row
			for(int j = 0; j < size; j++) {
				if(combinations[j][i] < min) {
					// Find the minimum
					min = combinations[j][i];
					// Store its index
					index = j;
				}
			}
			// Add the index to the array
			arr[count++] = index;
			// Replace the minimum with {
			combinations[index][i] = '{';
		}
		k++;
	}
}

// This is the encrpytion function
char* encrypt(char* plaintext, char combinations[][size]) {

	int arr[size];

	// Calling the sort function to get the sorted order
	sort(plaintext, combinations, arr);

	// Declaring variable to store the ciphertext
	static char encrypted[MAXLENGTH];

	int count = 0;
	// Adding last element of sorted rotation to the encrypted text
	for(int i = 0; i < size; i++) {
		encrypted[count++]  = combinations[arr[i]][size - 1];
	}
	// Returning the encrypted message
	return encrypted;
}

int main() {

	printf("----------Burrows Wheeler Transform----------\n");
	printf("\nCurrent size of macro n is %d\n", size);

	// Taking plaintext as input from the user
	char plaintext[MAXLENGTH];
	printf("\nEnter plaintext of size %d: ", size);
	fgets(plaintext, MAXLENGTH, stdin);

	// Check if size of plaintext is equal to macro size
	if(strlen(plaintext) - 1 != size) {
		printf("Invalid message entered.\n");
		exit(0);
	}

	// Decalring matrix to store the rotations
	char combinations[size][size];

	// Calling the encrypted fuction and printing ciphertext
	char* encrypted = encrypt(&plaintext[0], combinations);
	printf("The encrypted plaintext is: %s\n", encrypted);

	return 0;
}

/* Sample I/O:
a)
----------Burrows Wheeler Transform----------

Current size of macro n is 10

Enter plaintext of size 10: plainwords
The encrypted plaintext is: lrapiwsodn

b)
----------Burrows Wheeler Transform----------

Current size of macro n is 6

Enter plaintext of size 6: iworld
The encrypted plaintext is: ldrwoi
*/



<|start_filename|>C-Plus-Plus/cp/Plus_One.cpp<|end_filename|>
/*
Introduction 
Given a non-empty vector of decimal digits representing a non-negative integer, increment one to the integer.
The digits are stored such that the most significant digit is at the head of the list, 
and each element in the array contains a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.

Argument/Return Type
Given a vector as input
return answer as vector and print the result
*/

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

//Function to print the elements of the given vector
void printVector(vector<int>& digits)
{
    //Print digits without space between them
    for(int i: digits)
      cout<<i;
}

//Function which adds 1 to the number given by 
vector<int> plusOne(vector<int>& digits) 
{
    /* If the last didgit is not 9 
    Add one to it and return the vector */
    if(digits[digits.size()-1]!=9)
    {
        digits[digits.size()-1]+=1;
        return digits;
    }

    /*Else traverse the vector from the end
     till we reach a non '9' digit */
    int index=digits.size()-1;
    while(digits[index]==9)
    {
        //Make each digit as '0'
        digits[index--]=0;

        /* If there are no more elements in vector
        insert a '1' at the beginning of the vector and return it */
        if(index<0)
        {
            digits.insert(digits.begin(),1);
            return digits;
        }
    }

    /*After crossing all digits which are '9'
      make the element at current index as digit '1' */
    digits[index]=digits[index]+1;
    return digits;  
}


// Driver code
int main()
{
    //Take the input of total no.of digits
    int n;
    cout<<"Enter the total no.of digits : ";
    cin>>n;

    //Take input of the digits as vector
    vector<int>digits;
    cout<<"Enter each digit of the number with space between them in order : ";
    for(int i=0;i<n;i++)
    {
        int digit;
        cin>>digit;
        digits.push_back(digit);
    }

    //Call the function and print the result
    vector<int>result;
    result=plusOne(digits);
    cout<<"Hence the result is ";
    printVector(result);

    return 0; 
}
    
/*
Input:
1 <= digits.length <= 100
0 <= digits[i] <= 9

Sample Test Case 1  

Input Format : 
Example :
Enter the total no.of digits : 5
Enter each digit of the number with space between them in order : 1 5 9 9 9

Output Format :
Example : ( Output to the above input example ) 
Hence the result is 16000

Time/Space Complexity
  Time Complexity : O(n) 
  Space Complexity : O(1) 
*/


<|start_filename|>C-Plus-Plus/math/ugly_numbers.cpp<|end_filename|>
'''
Ugly numbers are numbers whose only prime factors are 2, 3 or 5. 
The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … shows the first 11 ugly numbers. 
By convention, 1 is included. Write a program to find Nth Ugly Number.

Example 1:
Input:
N = 10
Output: 12
Explanation: 10th ugly number is 12.

Example 2:
Input:
N = 4
Output: 4
Explanation: 4th ugly number is 4.
'''

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

int main()
{
	//code
	int t;
	cin>>t;
	
	long long arr[10000];
	int c2 = 0, c3 = 0, c5 = 0;
	arr[0] = 1;
	
	for(int i=1; i<10000; i++)
	{
	    arr[i] = min(arr[c2]*2, min(arr[c3]*3, arr[c5]*5));
	    
	    if(arr[i] % 2 == 0)
	        c2++;
	    if(arr[i] % 3 == 0)
	        c3++;
	    if(arr[i] % 5 == 0)
	        c5++;
	}
	
	while(t>0)
	{
	    int n;
	    cin>>n;
	    cout<<arr[n-1]<<endl;
	    t--;
	}
	return 0;
}

<|start_filename|>Java/other/remove_element_from_array.java<|end_filename|>
/*

Remove Element from the Array

For a given array of integers arr[], and a key value 
remove the key values from the array if present, and 
return the new size of the array thus obtained.
It is given that removal of all the elements should be in-place,
there should be no use of extra space.

*/

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

class remove_elements_from_array
{
    //function to remove the key value
    //from arrray if present
    public int removeKey(int arr[], int key)
    {
        //simply returning for an empty array
        if(arr.length == 0){
            return 0;
        }

        int newSize = 0;
        
        for(int pass = 0; pass < arr.length; pass++)
        {
            if(arr[pass] != key)
            {
                arr[newSize] = arr[pass];
                newSize++;
            }
        }

        return newSize;
    }

    //driver method
    public static void main(String []args)
    {
        Scanner sc = new Scanner(System.in); 

        System.out.println("Enter the size of the array: "); 
        int size = sc.nextInt(); 

        System.out.println("Enter the key value: "); 
        int key = sc.nextInt(); 

        int arr[] = new int[size]; 

        System.out.println("Enter the elements of array: "); 
        for(int i = 0; i < size; i++) 
        { 
            arr[i] = sc.nextInt(); 
        } 

        System.out.println("New size of array thus formed after the removal of "+key+" is : ");
        System.out.print(removeKey(arr, key));
        System.out.println();
    }
}

/*

EXAMPLES:-

Example 1:
Input--
Enter the size of the array: 5
Enter the key value: 6
Enter the elements of array: 2 1 8 33 6  
New size of array thus formed after the removal of 6 is : 4

Example 2:
Input--
Enter the size of the array: 3
Enter the key value: 1
Enter the elements of array: 6 80 44
New size of array thus formed after the removal of 1 is : 3

Example 3:
Input--
Enter the size of the array: 1
Enter the key value: 0
Enter the elements of array: 1  
New size of array thus formed after the removal of 0 is : 1

TIME COMPLEXITY --> O(N)
SPACE COMPLEXITY --> O(1)
*/


<|start_filename|>Julia/cp/Sieve_of_Eratosthenes.jl<|end_filename|>
#=Given a posititve number n find all the numbers from 2 to n which 
are prime and print them. Sieve of Eratosthenes is an optimal approach
to find the prime numbers.We get an array of length n and if the value
of array at index i is zero the number i is prime.=#

## Function 

function primeSieve(n)
    a = zeros(Int64, n + 5)
    for i = 2:n
        if (a[i] == 0)
            for j = (i*i):i:n
                a[j] = 1
            end
        end
    end
    for i = 2:n
        if (a[i] == 0)
            print("$(i) ")
        end
    end
end

##Input

n = readline()
n = parse(Int64, n)

#Calling the function

primeSieve(n)

#=
Sample test case:
Input:
    n = 20
Output:
    2 3 5 7 11 13 17 19 
    
Time complexity: O( N * log(log(N)) )
=#

<|start_filename|>C/cryptography/Affine_Substitution_Cipher.c<|end_filename|>
// C program to illustrate Affine Substitution Cipher

/*
The Affine Substitution cipher is a type of monoalphabetic substitution cipher wherein each letter in an alphabet
is mapped to its numeric equivalent encrypted using a simple mathematical function and converted back to a letter.
*/

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
// function declaration
int CalculateGCD(int);
int CalculateMultiplicativeInverse(int);

int main()
{
    int size = 0;
    int index, indx, k, gcd, alpha, beta, num_msg[size], numcipher[size], numdecipher[size], decipher[size], alphaInverse;
    char *msg, *cipher;
    printf("Input:\n");
    printf("Enter the size of the array: ");
    scanf("%d", &size);
    // allocating memory dynamically
    msg = (char *)malloc(size * sizeof(char));
    if (msg == NULL)
    {
        printf("memory cannot be allocated\n");
    }
    else
    {
        printf("Enter the Cipher message: ");
        scanf("%s", &*(msg));
    }

    //converting entered string to Capital letters
    for (index = 0, indx = 0; index < strlen(msg); index++)
    {
        if (msg[index] != ' ')
        {
            msg[indx] = toupper(msg[index]);
            indx++;
        }
        else
        {
            msg[indx] = ' ';
            indx++;
        }
    }
    //adding '\0' at end of string
    msg[indx] = '\0';
    printf("Enter the value of the key alpha: ");
    scanf("%d", &alpha);
    //Checking whether key alpha is in range of(1-25)
    if (alpha < 1 || alpha > 25)
    {
        printf("Alpha should lie in between 1 and 25\nTry again !\n");
        exit(0);
    }

    //  calling CalculateGCD function
    gcd = CalculateGCD(alpha);
    if (gcd != 1)
    {
        printf("Mandatory condition : gcd(alpha,26)=1 but \n gcd(%d,26)=%d\n Try again !\n", alpha, gcd);
        exit(0);
    }

    printf("Enter the value of the key beta: ");
    scanf("%d", &beta);
    //Checking whether key beta is in range of(0-25)
    if (beta < 0 || beta > 25)
    {
        printf("Beta value should lie between 0 and 25\n");
        exit(0);
    }
    //Conditions Over
    //Storing message in terms of ASCII and replacing spaces used  to -20
    for (index = 0; index < strlen(msg); index++)
    {
        if (msg[index] != ' ')
            num_msg[index] = msg[index] - 'A';
        else
            num_msg[index] = -20;
    }

    //Ciphering Process
    printf("Output:\n");
    printf("Encrypted Message is: ");
    /* applying encryption formula ( alpha x + beta ) mod m {here x is num_msg[index] and m is 26} and added 'A' to
         bring it in range of ASCII alphabet[ 65-90 | A-Z ] */
    for (index = 0; index < strlen(msg); index++)
    {
        if (num_msg[index] != -20)
        {
            numcipher[index] = ((alpha * num_msg[index]) + beta) % 26;
            printf("%c", (numcipher[index] + 'A'));
            cipher[index] = numcipher[index] + 'A';
        }
        else
        {
            printf(" ");
            cipher[index] = ' ';
        }
    }

    //Deciphering Process
    for (index = 0; index < strlen(cipher); index++)
    {
        //Storing encrypted message in terms of ASCII and replacing spaces to -20
        if (cipher[index] != ' ')
            numdecipher[index] = cipher[index] - 'A';
        else
            numdecipher[index] = -20;
    }
    //For Decryption we need to find multiplicative inverse of Alpha
    alphaInverse = CalculateMultiplicativeInverse(alpha);
    printf("\nDecrypted Message is: ");
    /*Applying decryption formula alpha^-1 ( x - beta ) mod m  {here x is numdecipher[index] and m is 26} and added 'A'
     to bring it in range of ASCII alphabet[ 65-90 | A-Z ] */
    for (index = 0; index < strlen(cipher); index++)
    {
        if (numdecipher[index] != -20)
        {
            decipher[index] = (alphaInverse * (numdecipher[index] - beta)) % 26;
            if (decipher[index] < 0)
            {
                //To avoid negative numbers
                decipher[index] = decipher[index] + 26;
            }
            printf("%c", (decipher[index] + 'A'));
        }
        else
            //adding of  white space
            printf(" ");
    }
    printf("\n");
    return 0;
}
// main ends here

//CalculateGCD Function definition
int CalculateGCD(int alpha)
{
    int GCD;
    int a = alpha;
    int m = 26;
    while (m != 0)
    {
        GCD = m;
        m = a % m;
        a = GCD;
    }
    return (a);
}

//CalculateMultiplicativeInverse Function definition
int CalculateMultiplicativeInverse(int alpha)
{
    int count, a_inv;
    for (count = 1; count <= alpha; count++)
    {
        a_inv = ((count * 26) + 1);
        if (a_inv % alpha == 0)
        {
            break;
        }
    }
    a_inv = a_inv / alpha;
    return (a_inv);
}

/*
 Input:
 Enter the size of the array: 15
 Enter the Cipher message: AFFINE CIPHER
 Enter the value of the key alpha: 17
 Enter the value of the key beta: 20
 Output:
 Encrypted Message is: UBBAHK CAPJKX
 Decrypted Message is: AFFINE CIPHER
 Time Complexity:  O(n)
 Space Complexity: O(1)
 */


<|start_filename|>JavaScript/search/linear_search.js<|end_filename|>
/*
 *   Algorithm: Linear Search
 *   Author: <NAME> (@omonimus1)
 *   Date: 25/06/2020
 *   Last Modified by: <NAME> (@omonimus1) 26/06/2020
 *
 *	Linear search: compare every element for the beginning to the en
 *   with our target (element to find). It returns true if the target * is found, false otherwise
 */

/*
 *   Search in a list a target using linear search algorithm
 */
function linear_search(arr, target) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] == target) return "Found";
  }
  return "Not Found";
}

/*
 *	@Test : Search an element that exists in the list
 *   Output expected: Found
 */
function linear_search_pass_test() {
  var test1 = [1, 2, 3, 4, 5, 6, 7];
  console.log(linear_search(test1, 6));
}

/*
 *	@Test : Search an element that do not exists in the list
 *   Output expected: 'Not Found'
 */
function linear_search_failure_test() {
  var test1 = [1, 2, 4, 5];
  console.log(linear_search(test1, 9));
}

// Entry file of the js application
linear_search_pass_test();
linear_search_failure_test();


<|start_filename|>Java/ds/Huffman.java<|end_filename|>
/*
 Huffman Coding is a famous Greedy Algorithm.
 Huffman coding assigns codes to characters such that the length of the code depends on the relative frequency or weight of the corresponding character.
 It is a lossless data compression algorithm which uses a small number of bits to encode common characters.
 A Huffman tree, similar to a binary tree data structure, needs to be created having n leaf nodes and n-1 internal nodes·
 Priority Queue/heaps is used for the implmentation.

 Time complexity of the Huffman algorithm is O(nlogn).
 Space complexity = O(n)
 
*/

import java.util.Scanner;
import java.util.Vector;
import java.util.Comparator;


class huffman_node {

    int frequency;

    char character;

    huffman_node left;
    huffman_node right;

    huffman_node() {
        frequency = 0;
        character = ' ';
        left = null;
        right = null;
    }
}

class MyComparator implements Comparator < huffman_node > {
    public int compare(huffman_node x1, huffman_node y1) {
        return x1.frequency - y1.frequency;
    }
}

class priority_queue {
    
    Vector < huffman_node > v2;


    public priority_queue(int number1, MyComparator comp1) {
        v2 = new Vector();
    }

    int parent(int h) {
        // if i is  root 
        if (h == 0) {
            return 0;
        }
        return (h - 1) / 2;
    }
}

public class Huffman {

    // recursive function to print
    public static void printCode(huffman_node root, String s) {

        if (root.left == null && root.right == null &&
            Character.isLetter(root.character)) {

            System.out.println("   " + root.character + "      |      " + root.frequency +
                "        |     " + s);
            return;
        }

        // if left add "0" 
        printCode(root.left, s + "0");

        // if right add"1" 
        printCode(root.right, s + "1");
    }

  
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);

       
        int n = 0;
        int choice = 0;

        do {
            System.out.println("HUFFMAN ENCODER");
            System.out.println("PRESS 1 FOR HUFFMAN ENCODER");
            System.out.println("PRESS 2 FOR EXIT");
            System.out.println("  ");
            choice = s.nextInt();
            switch (choice) {
                case 1:
                    System.out.println("ENTER THE NUMBER OF CHARACTERS :");
                    do {
                        n = s.nextInt();
                        if (n < 0) {                        
                            System.out.println("THE VALUE CANNOT BE NEGATIVE. TRY AGAIN");
                        }
                    } while (n < 0);

                    System.out.println("  ");

                    //array to store characters
                    char[] arr1 = new char[n];

                    //array to store frequencies    	
                    int[] freq1 = new int[n];

                    System.out.println("ENTER THE  CHARACTERS AND FREQUENCIES :");

                    for (int i1 = 0; i1 < n; i1++) {
                        System.out.println("ENTER THE CHARACTER NUMBER " + (i1 + 1) + "  : ");
                        arr1[i1] = s.next().charAt(0);
                        System.out.println("ENTER THE FREQUENCY OF THe CHARACTER '" +
                            arr1[i1] + "' :");
                        freq1[i1] = s.nextInt();
                    }

                    System.out.println("  ");

                    System.out.print("CHARACTERS ARE : { ");
                    for (int i1 = 0; i1 < n; i1++) {
                        System.out.print(arr1[i1]);
                        if (i1 != n - 1) {
                            System.out.print(" , ");
                        }
                    }
                    System.out.print(" }");
                    System.out.println(" ");

                    System.out.println("  ");
                    System.out.print("FREQUENCIES ARE : { ");
                    for (int i1 = 0; i1 < n; i1++) {
                        System.out.print(freq1[i1] + "");
                        if (i1 != n - 1) {
                            System.out.print(" , ");
                        }
                    }
                    System.out.print(" }");
                    System.out.println(" ");
                    System.out.println(" ");

                    System.out.println("CHARACTER |  FREQUENCY    |  HUFFMAN CODE  ");

                    //create new object of class priority_queue
                    priority_queue q = new priority_queue(n, new MyComparator());

                    for (int i = 0; i < n; i++) {
                        //create new object of class huffman_node
                        huffman_node hn = new huffman_node();

                        hn.character = arr1[i];
                        hn.frequency = freq1[i];

                        hn.left = null;
                        hn.right = null;

                        //add the nodes in the priority queue
                        q.add(hn);
                    }

                    //Initialize root to null
                    huffman_node root = null;

                    //while loop when it is queue size is greater than one
                    while (q.size() > 1) {

                        huffman_node first = q.peek(); 
                        q.poll(); 

                        huffman_node second = q.peek(); 
                        q.poll(); 

                        huffman_node temp = new huffman_node();

                        //add the data of 2 nodes
                        temp.frequency = first.frequency + second.frequency;
                        temp.character = '-';

                        temp.left = first;

                        temp.right = second;

                        root = temp;

                        //add in the queue
                        q.add(temp);
                    }

                    // print the codes by traversing the tree 
                    printCode(root, " ");               
                    System.out.println(" ");
                    break;

                case 2:
                    System.out.println("THANK YOU !");
                    System.out.println("  ");
                    break;

                default:
                    System.out.println("WRONG CHOICE ! TRY AGAIN");
                    System.out.println(" ");
                    break;

            }
        } while (choice != 2);
    }
}


<|start_filename|>Go/ds/queue/queue_using_stack/queue_using_stack.go<|end_filename|>
/*
	==============================================================
			Implementing QUEUE using STACK data structure
	==============================================================
	  queue can be implemented in two ways:

	  1 -> By making enQueue() operation costly :
		This method push the new element at the top of enQueueStack,
		so that deQueue operation just pops from enQueueStack.
		To put the element at top of enQueueStack, deQueueStack is used.

	  2 -> By making deQueue() operation costly :
		In this method, in en-queue operation, the new element is entered at the top of enQueueStack.
		In de-queue operation, all the elements of enQueueStack are moved to deQueueStack and top of deQueueStack is returned.
		finally all the elements of deQueueStack are moved to enQueueStack

	This program uses second way

*/

package main

import (
	"fmt"
)

// LENGTH of every Stack and Queue in this program
const LENGTH int = 10

// STACK user-definded data type to hold the variables for our stack data structure
type STACK struct {
	top   int
	array [LENGTH]int
}

// init(): this will initialize the stack for use
func (stack *STACK) initStack() {
	stack.top = -1
}

// isEmpty(): this checks if stack is empty or not
func (stack *STACK) isEmpty() bool {
	if stack.top < 0 {
		return true
	}
	return false
}

// isFull(): this checks if stack is full or not
func (stack *STACK) isFull() bool {
	if stack.top >= LENGTH-1 {
		return true
	}
	return false
}

// push(): this will push the value to the top of the stack
func (stack *STACK) push(value int) {
	if stack.isFull() {
		fmt.Println("Stack is Full")
	} else {
		stack.top++
		stack.array[stack.top] = value

	}
}

// pop(): this will remove the value from the top of the stack
func (stack *STACK) pop() int {
	var data int
	if stack.isEmpty() {
		fmt.Println("Stack is empty")
	} else {
		data = stack.array[stack.top]
		stack.top--

	}

	return data
}

// QUEUE user-defined data type will use for implemnting Queue data structure using Stack
type QUEUE struct {
	front        int
	back         int
	enQueueStack STACK
	deQueueStack STACK
}

func (queue *QUEUE) initQueue() {
	queue.front = -1
	queue.back = -1
	queue.enQueueStack.initStack()
	queue.deQueueStack.initStack()
}

func (queue *QUEUE) length() {
	if queue.isEmpty() {
		fmt.Println("The current length of Queue is 0")
	} else {
		fmt.Printf("The current length of Queue is %d\n", queue.back-queue.front+1)
	}
}

// isEmpty(): checks if the both front and back are less than 0 it means Queue is empty
func (queue *QUEUE) isEmpty() bool {
	if queue.front < 0 && queue.back < 0 {
		return true
	}
	return false
}

// iFull(): checks if the back of Queue is greater or equals to last index of array,
// if so it will return true otherwise false
func (queue *QUEUE) isFull() bool {
	if queue.back >= LENGTH-1 {
		return true
	}
	return false
}

// enQueue(): it first checks if there is space available for new element,
// if available it will just push the value in the enQueueStack
func (queue *QUEUE) enQueue() {
	var data int
	if queue.isFull() {
		fmt.Println("Can't insert value")
		fmt.Println("Queue is full")
	} else {
		if queue.front < 0 {
			queue.front++
		}
		fmt.Print("enter the value: ")
		fmt.Scanf("%d", &data)
		queue.back++
		queue.enQueueStack.push(data)
		fmt.Println("value inserted succesfully at the end of the Queue")
	}
}

// deQueue(): if the underlying stacks are not empty then it will pop all elemnt from enQueueStack
// and push them to deQueueStack and return the value by poping it from deQueueStack
// and finally it will pop all element from deQueueStack and push them to enQueueStack again
func (queue *QUEUE) deQueue() {
	if queue.front < 0 || queue.front > queue.back {
		fmt.Println("Can't delete value")
		fmt.Println("Queue is empty")
	} else {
		for i := 0; i <= queue.back-queue.front; i++ {
			queue.deQueueStack.push(queue.enQueueStack.pop())
		}
		fmt.Printf("Succesfully deleted element %d from the front of the Queue\n", queue.deQueueStack.pop())
		queue.front++
		for i := 0; i <= queue.back-queue.front; i++ {
			queue.enQueueStack.push(queue.deQueueStack.pop())
		}
		if queue.front > queue.back {
			queue.initQueue()
		}
	}
}

// printQueue(): if queue is not empty then it will simply
// print all the elements of enQueueStack
func (queue *QUEUE) printQueue() {
	if queue.isEmpty() {
		fmt.Println("Queue is empty")
	} else {
		fmt.Println("Current state of Queue is")
		for i := 0; i <= queue.back-queue.front; i++ {
			fmt.Printf("%d ", queue.enQueueStack.array[i])
		}
		fmt.Print("\n")
	}
}

func main() {
	var queue QUEUE
	queue.initQueue() // initalizing queue for first time
	var choice int
	var isContinue bool = true
	fmt.Println("Please enter option")
	for isContinue {
		fmt.Println("1 -> insert element\n2 -> delete element\n3 -> print Queue\n4 -> print length\n5 -> exit program")
		fmt.Scanf("%d", &choice)

		switch choice {
		case 1:
			queue.enQueue()
			break
		case 2:
			queue.deQueue()
			break
		case 3:
			queue.printQueue()
			break
		case 4:
			queue.length()
			break
		case 5:
			isContinue = false
			break
		default:
			fmt.Println("Please enter correct option")
			break
		}
	}
}

/*
	input/output sample

	Please enter option
	1 -> insert element
	2 -> delete element
	3 -> print Queue
	4 -> print length
	5 -> exit program
	1
	enter the value: 4
	value inserted succesfully at the end of the Queue
	1 -> insert element
	2 -> delete element
	3 -> print Queue
	4 -> print length
	5 -> exit program
	1
	enter the value: 5
	value inserted succesfully at the end of the Queue
	1 -> insert element
	2 -> delete element
	3 -> print Queue
	4 -> print length
	5 -> exit program
	1
	enter the value: 6
	value inserted succesfully at the end of the Queue
	1 -> insert element
	2 -> delete element
	3 -> print Queue
	4 -> print length
	5 -> exit program
	3
	Current state of Queue is
	4 5 6
	1 -> insert element
	2 -> delete element
	3 -> print Queue
	4 -> print length
	5 -> exit program
	2
	Succesfully deleted element 4 from the front of the Queue
	1 -> insert element
	2 -> delete element
	3 -> print Queue
	4 -> print length
	5 -> exit program
	2
	Succesfully deleted element 5 from the front of the Queue
	1 -> insert element
	2 -> delete element
	3 -> print Queue
	4 -> print length
	5 -> exit program
	3
	Current state of Queue is
	6
	1 -> insert element
	2 -> delete element
	3 -> print Queue
	4 -> print length
	5 -> exit program
	4
	The current length of Queue is 1
*/


<|start_filename|>C-Plus-Plus/math/Smallest_divisible_number.cpp<|end_filename|>
//Given a number n find the smallest number evenly divisible by each number 1 to n.

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

// Function returns the gcd of first n numbers 
long long gcd(long long a,long long b )
{
    if (a == 0)
        return b;
    return gcd(b % a, a);
}

// Function returns the lcm of first n numbers 
long long lcm(long long n) 
{ 
	long long ans = 1;	 
	for (long long i = 1; i <= n; i++) 
		ans = (ans  *  i) /  (gcd(ans, i)); 
	return ans; 
} 
// Driver program to test the above function 
int main() 
{ 
	long long n;
	cout<< "Enter the number: ";
	cin>>n;             
	cout << lcm(n); 
	return 0; 
} 

/*
##Example :

1.Input : Enter the number: 4
  Output: 12

Explanation : 12 is the smallest numbers divisible by all numbers from 1 to 4

2.Input : Enter the number: 6
  Output: 60

##Time Complexity:O(nlogn)
##Space Complexity:O(1)								 

*/


<|start_filename|>Java/cp/Defanged_IPv4.java<|end_filename|>
import java.util.*;
class Main {
    public static void main(String args[]) {
        int c = 0;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter IPv4 address");
        String s = sc.next();
        for (int i = 0; i < s.length(); i++)
            if (s.charAt(i) == '.')
                c++;
        s = s.replace(".", "[.]");
        if (c == 3)
            System.out.println("Defanged IPv4 address : " + s);
        else
            System.out.println("Not a valid IPv4 address");

    }
}

/*
Sample Input and Output :

Enter IPv4 address
1.1.1.1
Defanged IPv4 address : 1[.]1[.]1[.]1
Enter IPv4 address
2500.100.50.0
Defanged IPv4 address : 2500[.]100[.]50[.]0
Enter IPv4 address
1.1.1.1.
Not a valid IPv4 address

Time Complexity: O(n) where n is the length of address
Space Complexity: O(1)
*/


<|start_filename|>C-Plus-Plus/cp/max_of_min_subarray.cpp<|end_filename|>
/**
 * Maximum of Minimum for Every Window Size in an Array
 * Find the maximum of the minimum of every window size in a given 
 * positive integer array of size len. The size of windows in an array 
 * vary from 1 to len. 
 */

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

void printMaxOfMin(int arr[], int len)
{ // Used to find previous and next smaller
    stack<int> s;

    // Arrays to store previous and next smaller
    int left[len + 1];
    int right[len + 1];

    // Initialize elements of left[] and right[]
    for (int i = 0; i < len; i++) {
        left[i] = -1;
        right[i] = len;
    }

    // Fill elements of left[]
    /* If stack is not empty, then pop an element from stack. 
       If the popped element is smaller than next, then 
    a) store it in left[]
    b) keep popping while elements are 
    smaller and stack is not empty */
    for (int i = 0; i < len; i++) {
        while (!s.empty() && arr[s.top()] >= arr[i])
            s.pop();

        if (!s.empty())
            left[i] = s.top();
        /* push next to stack so that we can find next greater for it */
        s.push(i);
    }

    // Empty the stack as stack is going to be used for right[]
    while (!s.empty())
        s.pop();

    // Fill elements of right[] using same logic as left
    for (int i = len - 1; i >= 0; i--) {
        while (!s.empty() && arr[s.top()] >= arr[i])
            s.pop();

        if (!s.empty())
            right[i] = s.top();

        s.push(i);
    }

    // Create and initialize answer array
    int ans[len + 1];
    for (int i = 0; i <= len; i++)
        ans[i] = 0;

    // Fill answer array by comparing minimums of all
    // lengths computed using left[] and right[]
    for (int i = 0; i < len; i++) {
        // length of the interval
        int len = right[i] - left[i] - 1;

        // arr[i] is a possible answer for this length
        // 'len' interval, check if arr[i] is more than
        // max for 'len'
        ans[len] = max(ans[len], arr[i]);
    }

    // Some entries in ans[] may not be filled yet. Fill
    // them by taking values from right side of ans[]
    for (int i = len - 1; i >= 1; i--)
        ans[i] = max(ans[i], ans[i + 1]);

    // Print the result
    cout << "Array of maximum of the minimum of every window size from 1 to " << len << ": ";
    for (int i = 1; i <= len; i++)
        cout << ans[i] << " ";
}

int main()
{ //Take input from user
    int len;
    cout << "Enter length of array of integers: ";
    cin >> len;
    int arr[len];
    cout << "Enter array of integers: ";
    for (int i = 0; i < len; i++)
        cin >> arr[i];
    printMaxOfMin(arr, len);
    return 0;
}

/*
    Test Cases

    INPUT
    Enter length of array of integers: 9
    Enter array of integers: 8 6 5 3 5 6 7 7 10
    OUTPUT
    Array of maximum of the minimum of every window size from 1 to 9: 10 7 7 6 5 3 3 3 3 

    INPUT
    Enter length of array of integers: 5
    Enter array of integers: 7 4 3 1 5
    OUTPUT
    Array of maximum of the minimum of every window size from 1 to 5: 7 4 3 1 1 

    Time complexity: O(N)
    Space complexity: O(N)

*/


<|start_filename|>Julia/sort/quick_sort.jl<|end_filename|>
"""Julia program to implement Quick sort
Quick Sort is a Divide and Conquer strategy based sorting algoithm, that partitions the array
around a selected pivot element. In the below implemented version of Quick Sort we always took the 
last element as the pivot element.

"""
function  partition(arr, low, high)
    # Select the last element as pivot
    pivot = arr[high]
    i = low - 1
    for j in low:high
        # Check if there is any element less than the pivot element
        if(arr[j] < pivot)
            i = i + 1
            # Swap such an element with the to the start position
            arr[i], arr[j] = arr[j], arr[i]
        end
    end
    # Now place the pivot to its original position
    arr[i+1], arr[high] = arr[high], arr[i+1]
    return (i+1)
end

function quick_sort(arr, low, high)
    if (low < high)
        pi = partition(arr, low, high)
        # Recursively call quick_sort function
        quick_sort(arr, low, pi - 1)
        quick_sort(arr, pi + 1, high)
    end
end
       


print("How many numbers do you want to sort? ")
n = readline()
n = parse(Int, n)
if (n <= 0)
    println("No numbers to sort!!!")
    exit()
end
arr = Int[]
print("Enter the numbers: ")
arr = [parse(Int, num) for num in split(readline())]
quick_sort(arr, 1, n)
print("The numbers in sorted order is ")
print(arr)



"""
Time Complexity - O(n^2), where 'n' is the size of the array
Space Complexity - O(n)

SAMPLE INPUT AND OUTPUT

SAMPLE I
How many numbers do you want to sort? 5
Enter the numbers: 4 2 5 1 3
The numbers in sorted order is [1, 2, 3, 4, 5]

"""


<|start_filename|>C/cryptography/Keyword_Cipher.c<|end_filename|>
/*Keyword cipher is a form of monoalphabetic substitution, where a keyword is used as the key. Now
  a encryption is formed of alphabets from [a-z] such that the first part of encrption contains 
  unique letters of the keyword and the rest are the remaining alphabets from [a-z]. That is,
  until the keyword is used up, whereupon the rest of the ciphertext letters are used in alphabetical 
  order, excluding those already used in the key.*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//Defining max length of plaintext, keyword, ciphertext
#define MAXLENGTH 100

/*This is the encryption function that takes plaintext message
  and keyword as input*/
char* encrypt(char* message, char* keyword) {

	//This variable contains encrypted message
	static char encrypted_message[MAXLENGTH];
	//This the pad to be generated using keyword
	static char pad[MAXLENGTH];

	int count = 0;
	int i = 0;

	/*If the plaintext contains spaces, replace it by
	  underscores*/
	for(int i = 0; i < strlen(message) - 1; i++) {
		if(message[i] == ' ') {
			message[i] = '_';
		}
	}
	
	/*This while loop finds all the unique alphabets in the
	  keyword and is inserted at the beginning of the pad*/
	while(i < strlen(keyword) - 1) {

		//If the keyword alphabet is a space, then leave it
		if(keyword[i] == ' ') {
			i++;
			continue;
		}
	
		int not_present = 0;
		
		for(int j = 0; j < strlen(keyword) - 1; j++) {
			if(keyword[i] != pad[j]) {
				not_present += 1;
			}
		}
		
		//If the keyword alphabet is not present in the pad
		if(not_present == strlen(keyword) - 1) {
			//add it
			pad[count] = keyword[i];
			count++;
		}
		i++;
	}

	/*After this while loop, we get first half of our pad.
	  For example, if the keyword is "well", then "wel" is
	  added to the pad*/

	/*Now to fill the pad, all the remaining alphabets those are not previously present 
	  are added to it*/
	char alphabet[26] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

	//This while loop completes the remaining of the pad
	i = 0;
	while(i < 26) {
		int np = 0;
		for(int j = 0; j < 26; j++) {
			if(alphabet[i] != pad[j]) {
				np += 1;
			}
		}
		if(np == 26) {
			pad[count] = alphabet[i];
			count++;
		}
		i++;
	}
	
	/*Now we the pad, and we have the plaintext message,
	  we replace alphabets of plaintext as per their
	  occurence in the pad*/
	for(int i = 0; i < strlen(message) - 1; i++) {

		/*If the message has space, add space to the
		  encrypted message also*/
		if(message[i] == '_') {
			encrypted_message[i] = ' ';
		}
		/*else replace it with the corresponding position
		  in the pad*/
		else {
			int index = 0;
			for(int j = 0; j < strlen(alphabet); j++) {
				if(message[i] == alphabet[j]) {
					index = j;
				}
			}
			encrypted_message[i] = pad[index];
		}
	}
	//return the encrypted message
	return encrypted_message;
}

int main() {

	//Declaring variables to store plaintext and keyword
	char plaintext[MAXLENGTH];
	char keyword[MAXLENGTH];

	//Taking input from the user
	printf("Enter the plaintext   : ");
	fgets(plaintext, MAXLENGTH, stdin);

	printf("Enter the keyword     : ");
	fgets(keyword, MAXLENGTH, stdin);
	
	//Printing the respective ciphertext by calling the encrypt function
	printf("The encrypted text is : %s\n", encrypt(&plaintext[0], &keyword[0]));

	return 0;
}

/*
 Sample I/O :

 	Enter the plaintext   : neo algo is awesome
	Enter the keyword     : a star
	The encrypted text is : kbl aidl fp awbpljb	
 */ 



<|start_filename|>Go/cryptography/Columnar_Cipher/Columnar_Cipher.go<|end_filename|>
/* In Columnar Cipher, we are given a plaintext and a key. The plaintext
is written out in rows and the ciphertext is formed by reading out columns
one by one according to the order of the key given. Key is converted to its
corresponding numerical(Ex A-0, B-1, C-2, ...... , Z-25). Cipher text is formed
by reading the columns corresponding to the lowest numerical value in the key to
the highest numerical value. */

package main

import (
	"fmt"
	"bufio"
	"os"
)

//Sort function, returns sorted integer array
func sort(array []int, length int) {

	//Bubble sort is used here
	for i := 0; i < length - 1; i++ {
		for j := 0; j < length - 1 - i; j++ {
			if(array[j] > array[j + 1]) {
				var temp int = array[j]
				array[j] = array[j + 1]
				array[j + 1] = temp
			}
		}
	}
}

/*This function returns the corresponding numerical
value of the key in the form of an array*/
func order(key string) []int {

	order_key := make([]int, len(key))

	/*We find the numerical value of each
	alphabet corresponding to the key*/
	for i := 0; i < len(key); i++ {
		order_key[i] = int(key[i])
		order_key[i] -= 65
	}

	temp := make([]int, len(key))

	//Storing the numerical value temporarily
	for i := 0; i < len(key); i++ {
		temp[i] = order_key[i]
	}

	/*Store according to relative numbering of
	each alphaet in the key*/
	sort(order_key, len(key))

	index := make([]int, len(key))

	for i := 0; i < len(key); i++ {
		for j := 0; j < len(key); j++ {
			if(temp[i] == order_key[j]) {
				index[i] = j+1
			}
		}
	}
	/*Returning the array containing the numerical
        value of key in relative order*/
	return index
}

/*This is the encrypt function that takes
plaintext and key as input*/
func encrypt(plaintext, key string) string {

	decrypted_message := [26]string{}

	var length_key int = len(key)
	var length_message int = len(plaintext)

	/*Replacing any spaces in the plaintext with
	underscores*/
	var message string
	for j:= 0; j < length_message; j++ {
		if(string(plaintext[j]) == " ") {
			message += string("_")
		} else {
			message += string(plaintext[j])
		}
	}

	/*If in the matrix any row is left vacant at the
	end, we fill the blank spaces with underscores*/
	if((length_message % length_key) != 0) {
		var extra int = length_key - length_message % length_key
		for i := 0; i < extra; i++ {
			message += "_"
		}
		//Update the length of the message accordingly
		length_message = len(message)
	}

	//Define the matrix to transpose and get the cipher
	var matrix = make([][]string, (length_message / length_key))
	for i := range matrix {
		matrix[i] = make([]string, length_key)
	}

	var count int = 0
	var columns []int = order(key)

	var cnt int = 0

	//Fill in the values of plaintext in the matrix row by row
	for i := 0; i < (length_message/length_key); i++ {
		for j := 0; j < length_key; j++ {
			matrix[i][columns[j] - 1] = string(message[count])
			count++
		}
	}

	sort(columns, length_key);

	/* Now create the ciphertext by reading values from the matrix
	in a column by column fashion*/
	for i := 0; i < length_key; i++ {
		for j := 0; j < (length_message / length_key); j++ {
			//If there is a space, replace it with an underscore
			if(matrix[j][columns[i] - 1] == " ") {
				decrypted_message[cnt] = "_"
			} else {
				decrypted_message[cnt] = matrix[j][columns[i] - 1]
			}
			cnt += 1
		}
	}

	var enc string

	// Convert the asrray to string
	for i := 0; i < len(decrypted_message); i++ {
		if(string(decrypted_message[i]) == "_") {
			enc += " "
		} else {
			enc += decrypted_message[i]
		}
	}

	//return the encrypted ciphertext
	return enc
}

func main() {

	// Taking plaintext as input from the user
	fmt.Print("Enter the plaintext  : ")
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	plaintext := scanner.Text()

	// Taking keyword as input from the user
	fmt.Print("Enter the keyword    : ")
	scanner.Scan()
	key := scanner.Text()

	//Print the encrypted message by calling the encrypt function
	var ciphertext string = encrypt(plaintext, key)
	fmt.Print("\nEncrypted plaitext is: ", ciphertext, "\n")
}

/* Sample I/O:

Enter the plaintext  : THIS IS A PLAINTEXT
Enter the keyword    : KEY

Encrypted plaitext is: H  PIE TSS ATTIIALNX

*/


<|start_filename|>C-Plus-Plus/other/Arranging_elements_of_array_to_form_biggestno.cpp<|end_filename|>
/*  

Arrange the elements of array such that to form the  
biggest possible number, by rearranging them.  

For a given array arr[] having numbers,  
your task is to arrange the elements of the array arr[],  
such that the new arrangement forms the biggest number.  
The output is given in a single number form  
i.e. the elements should be printed without spaces, 
forming a single number.
*/  

#include <bits/stdc++.h>  

using namespace std;  

//function to compare between elements  
int formBiggest(string str1, string str2)  
{  

    string appnd1 = str1.append(str2);  

    string appnd2 = str2.append(str1);  

    //comparing between appnd1 and appnd2  
    //and returning bigger one 
    return appnd1.compare(appnd2) > 0 ? 1 : 0;  

}  

//main function  
int main()  
{  

    int n;  

    cout<<"Enter the size of array: ";  
    cin>>n;  

    vector<string> arr(n);  

    cout<<"Enter the elements for the array: ";  

    for(int pass = 0; pass < n; pass++)  
    {  
        arr.push_back(arr[pass]);  
    }  
    cout<<"The biggest number so formed is: ";  

    sort(arr.begin(), arr.end(), formBiggest);   

    for(int pass = 0; pass < n; pass++){  
        cout<<arr[pass];  
    }  

    return 0;  

}  

/*  

EXAMPLES:-  

Example 1:  
Input--  
Enter the size of array: 5  
Enter the elements for the array: 44 66 88 01 56  
Output--  
The biggest number so formed is: 8866564401  

Example 2:  
Input--  
Enter the size of array: 3  
Enter the elements for the array: 200 545 76  
Output--  
The biggest number so formed is: 76545200   

Example 3:  
Input--  
Enter the size of array: 1  
Enter the elements for the array: 220  
Output--  
The biggest number so formed is: 220  

TIME COMPLEXITY -> O(Nlog(N))  
SPACE COMPLEXITY -> O(1)  

*/  


<|start_filename|>C/sort/radix_sort.c<|end_filename|>
/** 
Radix sort is based on counting sort
This sort is used for non-negative elements
Assuming the range is fixed, as int capacity
is limited in any language, this sort takes

MAX_INT contains 10 decimal values
If range is not fixed, this sort takes O(kn) time
where k is #decimal places in the number
This works because of the nature of counting sort
Counting sort is a stable sort
**/

#include <stdio.h>
#include <math.h>
#include <limits.h>

#define K 10
#define M 10

void counting_sort(int arr[], int  n, int p) {
	int element = pow(10, p), i;
	int divs = element / 10;
	int count[M];
	for(i = 0; i < M; i++)
		count[i] = 0;
	for(i = 0; i < n; i++)
		count[(arr[i] % element) / divs] ++;
	for(i = 1; i < M; i++)
		count[i] += count[i-1];
	int op[n];
	for(i = n-1; i >= 0; i--) {
	    op[count[(arr[i] % element) / divs] - 1] = arr[i];
	    count[(arr[i] % element) / divs] --;
	}
	// copying the array back
	for(i = 0; i < n; i++)
		arr[i] = op[i];
}

void radix_sort(int arr[], int n) {
	int i;
	// apply counting sort for all decimal places
	for(i = 1; i <= K; i++)
		counting_sort(arr, n, i);
}

int main() {
	int n, i;
	scanf(" %d", &n);
	int arr[n];
	// taking ip
	for(i = 0; i < n; i++)
		scanf(" %d", &arr[i]);
	// perform the sort
	radix_sort(arr, n);
	for(i = 0; i < n; i++)
		printf("%d ", arr[i]);
	printf("\n");
	return 0;
}

/**
Input : 
8
175 45 75 90 802 24 2 66
Output :
2 24 45 66 75 90 175 802

Time complexity : O(n)
Space complexity : O(n)
**/


<|start_filename|>C-Plus-Plus/math/int_to_roman.cpp<|end_filename|>
/*Problem Statement:
Given an integer, the task is to convert it to a roman numeral.
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000 */

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

string IntegerToRoman(int num) {
    string ans = "";
    vector<pair<int, string>> values = {{1000, "M"}, {900, "CM"}, {500, "D"}, 
                                       {400, "CD"}, {100, "C"}, {90, "XC"}, 
                                       {50, "L"}, {40, "XL"}, {10, "X"}, 
                                       {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}};
    vector<pair<int, string>>::iterator it; 
    it = values.begin(); //to iterate over the values
    while(num > 0 && it != values.end()) { 
        if(it -> first <= num){
            ans += it -> second;
            num -= it -> first;
        }
        else{
            it++;
        }
    }
    return ans;
}

int main() {
    int num;
    cin >> num;
    cout << IntegerToRoman(num);
    return 0;
}

/* Examples:
1. Input: num = 3
   Output: "III"
2. Input: num = 1994
   Output: "MCMXCIV" */



<|start_filename|>C-Plus-Plus/graphs/Tarjan's_Algoirthm.cpp<|end_filename|>

#include <bits/stdc++.h> 
using namespace std;
typedef long long ll;
typedef vector<ll> vl; 
#define pb push_back 

#define loop(x,n) for(ll x = 1; x <= n; ++x)

//Adjacency List of Graph
vl graph[100001];  

bool vis[100001],onstack[100001];

ll in[100001],low[100001];

stack<ll> st;

//scc=no. of strongly connected components
ll timer=1,scc=0;  

void dfs(ll source){
  vis[source]=1;
  //increase in time and low time
  in[source]=low[source]=timer++;  
  
  onstack[source]=true;
   // push into stack
  st.push(source);    
  
  for(auto child:graph[source]){
    if(vis[child]==true && onstack[child]==true)
        //change low time if back edge
          low[source]=min(low[source],in[child]);  
    
    else if(vis[child]==false){
       dfs(child);
    
      if(onstack[child]==true)
      //change low time if visited forward edge
       low[source]=min(low[source],low[child]);   
      }
  }
  
  //case for scc if in=low
  if(in[source]==low[source]){  
   scc++;
    cout<<"Strongly Connected Component #"<<scc<<":\n";

    ll s;
    while(1){
       s=st.top();
       //delete all elements from stack till it top element equal to scc node
       st.pop();          
       onstack[s]=false;
       
       cout<<s<<" ";
       if(s==source) break;   
      
     }
    cout<<"\n";
  }
    
}
 
int main() 
{ 
    ios_base::sync_with_stdio(false); 
    cin.tie(NULL); 
    
    ll n,m,a,b;
    //n=no. of vertices, m=no. of edges
    cin>>n>>m;     
    
    loop(i,m){
     cin>>a>>b;
     graph[a].pb(b);
     }

     loop(i,n){
        //initialise visited array as false;
     vis[i]=onstack[i]=false;    
     }
    
    loop(i,n){
       //dfs call
      if(vis[i]==false) dfs(i);  
    } 
    return 0; 
}

/*
Input:
First line contains two space separated integers,(n,m) 
n- no of vertices, m- no of edges.
Then m lines follow, each line has 2 space separated integers ui ,vi which denotes edge from vertex ui to vi.


TEST CASE
8 12
1 2
2 3
3 1
2 8
3 4
8 4
4 8
7 8
5 4
5 7
7 6
6 5

OUTPUT
Strongly Connected Component #1:
8 4 
Strongly Connected Component #2:
3 2 1 
Strongly Connected Component #3:
6 7 5

Time- complexity: O(n+m)

Space Complexity: O(n)

*/



<|start_filename|>Java/sort/CountingSort.java<|end_filename|>
import java.util.*;
import java.lang.*;

/*
Counting sort is an algorithm for sorting a collection of objects according to keys that are small integers; that is, it is an integer sorting algorithm. It operates by counting the number of objects that have each distinct key value, and using arithmetic on those counts to determine the positions of each key value in the output sequence. 
Worst complexity: O(n+k)
Average complexity: O(n+k)
Space complexity: O(n+k)
where n is the number of elements in input array and k is the range of input.
*/

class CountingSort
{
    static void sortIntegerArray(int arr[])
    {
        int i=0;
        int n = arr.length;
        int minElement=Integer.MAX_VALUE;
        int maxElement=Integer.MIN_VALUE;

        //Maximum and Minimum element from input array
        for(i=0;i<n;i++)
        {
            if (arr[i] > maxElement) {
                maxElement=arr[i];
            }
            if (arr[i] < minElement){
                minElement=arr[i];
            }
        }
        
        int range = maxElement-minElement+1;
        int[] arrElementCount = new int[range];
        int[] sortedArray = new int[n];
        
        //count occurance of an element
        for(i=0;i<n;i++)
        {
            arrElementCount[arr[i]-minElement]++;
        }
        //Accumulative sum of elements
        for(i=0;i<range-1;i++){
            arrElementCount[i+1]+=arrElementCount[i];
        }
        //Shift array by one index
        int temp=arrElementCount[0];
        for(i=1;i<range;i++){
            int nextTemp=arrElementCount[i];
            arrElementCount[i]=temp;
            temp=nextTemp;
        }
        arrElementCount[0]=0;
        //store element at right index
        for(i=0;i<n;i++){
            sortedArray[arrElementCount[arr[i]-minElement]]=arr[i];
            arrElementCount[arr[i]-minElement]++;
        }
        //copy sorted array to input array
        for(i=0;i<n;i++){
            arr[i]=sortedArray[i];
        }
    }
    
    static void sortCharArray(char arr[])
    {
        int i=0;
        int n = arr.length;
        int range=256;
        int[] arrElementCount = new int[range];
        char[] sortedArray = new char[n];

        //count occurance of an element
        for(i=0;i<n;i++)
        {
            arrElementCount[arr[i]]++;
        }
        //Accumulative sum of elements
        for(i=0;i<range-1;i++){
            arrElementCount[i+1]+=arrElementCount[i];
        }
        //Shift array by one index
        int temp=arrElementCount[0];
        for(i=1;i<range;i++){
            int nextTemp=arrElementCount[i];
            arrElementCount[i]=temp;
            temp=nextTemp;
        }
        arrElementCount[0]=0;
        //store element at right index
        for(i=0;i<n;i++){
            sortedArray[arrElementCount[arr[i]]]=arr[i];
            arrElementCount[arr[i]]++;
        }
        //copy sorted array to input array
        for(i=0;i<n;i++){
            arr[i]=sortedArray[i];
        }
    }

    public static void main (String[] args) throws java.lang.Exception
    {
	CountingSort sort = new CountingSort();

        Scanner sc = new Scanner(System.in);

        //Input:- Integer Array
        System.out.println("Enter space separated integer:");
        String intString[]= sc.nextLine().split(" ");
        int size = intString.length;
        int[] arrInt = new int[size];
        for(int i=0 ;i<size;i++){
            arrInt[i]= Integer.parseInt(intString[i]);
        }
        sort.sortIntegerArray(arrInt);
        System.out.println("Sorted Integer Array:- ");
        for(int i=0; i<size;i++)
        {
            System.out.print(arrInt[i]+" ");
        }
        System.out.println();

        //Input:- Character Array
        System.out.println("\nEnter space separated character:");
        String charString[] = sc.nextLine().split(" ");
        int Size=charString.length;
        char[] arrChar = new char[Size];
        for(int i=0 ;i<Size;i++){
            arrChar[i] = charString[i].charAt(0);
        }
        sort.sortCharArray(arrChar);
        System.out.println("Sorted Character Array:- ");
        for(int i=0; i<Size;i++)
        {
            System.out.print(arrChar[i]+" ");
        }
        System.out.println();
    }
}

/*
Sample Input-Output

Enter space separated integer:
7 8 9 4 5 6 7
Sorted Integer Array:- 
4 5 6 7 7 8 9

Enter space separated character:
a b t r a b c f
Sorted Character Array:- 
a a b b c f r t
*/


<|start_filename|>Java/sort/PancakeSort.java<|end_filename|>
import java.util.*;
class Main
{   
    static void reverseArray(int a[],int n) //This functions reverses the array upto index n
    {
        int temp[]=new int[n+1]; // temp is the temporary array 
        for(int i=0;i<=n;i++)
        {
            temp[i]=a[n-i];
            }
            for(int i=0;i<=n;i++)
            a[i]=temp[i];
        }
       static int findmax(int a[],int n) //Function to find index of max element upto index n
        {
            int max=a[0];int j=0; //j stores the index of max element
            for(int i=1;i<=n;i++)
              if(a[i]>max)
              {max=a[i];
                  j=i;
                }
                return j;
                
            }
    static void pancakesort(int a[],int n)
    {  int currentLength;
        for(currentLength=n;currentLength>0;--currentLength)
        {
            int j= findmax(a,currentLength-1);
            if(j!=currentLength)
            {
                reverseArray(a,j);
                reverseArray(a,currentLength-1);
            }
            }
        }
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        int i,j,k,l,m,n;
        n=sc.nextInt();
        int array[]=new int[n];
        for(i=0;i<n;i++)
        array[i]=sc.nextInt();
        pancakesort(array,n);
        for(i=0;i<n;i++)
        System.out.print(array[i]+" ");
        System.out.println();
    }
}


/* 
Input - 
5 //Array length
4 3 7 1 2 //Array Elements

Output - 
1 2 3 4 7 //Sorted Array
*/

<|start_filename|>Go/ds/stack/Stack.go<|end_filename|>
package main

import (
	"errors"
	"fmt"
	"math/rand"
)

// A linked list node
type node struct {
	data interface{}
	next *node
}

type stack struct {
	top  *node
	size int
}

func (obj *stack) isEmpty() bool {
	return obj.size == 0
}

// Adds the given element to the beginning of the stack
func (obj *stack) Push(value interface{}) {
	obj.top = &node{
		data: value,
		next: obj.top,
	}
	obj.size++
}

// Removes the element at the beginning of the stack
// and returns the element along with an error message
// if the stack is empty else 'nil'
func (obj *stack) Pop() (interface{}, error) {
	if obj.top == nil {
		return nil, errors.New("Empty stack")
	}

	var data interface{}
	data, obj.top = obj.top.data, obj.top.next
	obj.size--

	return data, nil
}

// Returns a random element to insert in the Stack
func getElement() interface{} {
	var temp interface{} = rand.Intn(100)
	fmt.Println("Element: ", temp)

	return temp
}

// Returns the value at the beginning of the stack
// along with the error message
func (obj *stack) Peek() (interface{}, error) {
	if obj.top == nil {
		return nil, errors.New("Empty stack")
	}

	return obj.top.data, nil
}

func main() {
	var object stack
	var flag bool = true
	var choice int

	for flag {
		fmt.Print("Menu\n1. Push element\n2. Pop element\n3. Peek element\n4. Count of elements\n5. Exit\nEnter your choice: ")
		fmt.Scan(&choice)

		switch choice {
		case 1:
			element := getElement()
			object.Push(element)
		case 2:
			element, err := object.Pop()
			fmt.Println("Element: ", element)
			fmt.Println("Error: ", err)
		case 3:
			element, err := object.Peek()
			fmt.Println("Element: ", element)
			fmt.Println("Error: ", err)
		case 4:
			fmt.Println("The total number of elements present in the Stack are: ", object.size)
		case 5:
			flag = false
		default:
			fmt.Println("Please enter valid choice.")
		}
	}
}


<|start_filename|>C-Plus-Plus/cp/Leftmostnonrepeatingchar.cpp<|end_filename|>
// Description: This program finds the leftmost non repeating character in a string.
// For example: s = "aabcdb", output should be: 3 (index of c)
#include<bits/stdc++.h>
using namespace std;

int leftmostnonrepeatingchar(string s){
    int res = numeric_limits<int>::max();  //Initialised res to infinity
    vector<int> fi(256, -1);               //An array to store first indices of string characters(size is 256 because there are 256 ascii characters
    for(int i = 0; i < s.size(); i++){     //Traversing through string   
        if(fi[s[i]] == -1){                //If this position in array is -1, that means its a non repeating element
            fi[s[i]] = i;
        }else{
            fi[s[i]] = -2;                 //If it is -2 that means this element has already been repeated before
        }
    }
    for(int i = 0; i < 256; i++){
        if(fi[i] >= 0){
            res = min(res, fi[i]);         //finding the leftmost non repeating char index
        }
    }
    return (res == numeric_limits<int>::max())? -1: res;
}

int main(){
    string s;
    cout << "Enter the string: ";
    cin >> s;
    cout << "The leftmost non repeating character in the string is: " << leftmostnonrepeatingchar(s);
    return 0;
}
/*Sample test case:
s = "aabcdb", all elements of fi array are initialised as -1
After traversing through string, our res would become 3 */



<|start_filename|>C-Plus-Plus/cp/find_first_and_last_position_index_of_a_number_in_array.cpp<|end_filename|>
/*
Given a sorted array of N elements and a value, find the first and last index position of the value number.
We can do this with the help of Binary Search.
*/

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

int f_indx(int ar[], int N , int value)
{
    int low = 0;
    int high = N;
    while (low < high)
    {
        int mid =  low + (high - low) / 2;
        /* here if the mid contains value greater than or equal to our targeted value
        we set that position as high */
        if (value <= ar[mid])
        {
            high = mid;
        }
        else
        {
            low = mid + 1;
        }
    }
    return low;
}

int l_indx(int ar[], int N , int value)
{
    int low = 0;
    int high = N;
    while (low < high)
    {
        int mid =  low + (high - low) / 2;
         /* here if the mid contains value greater than or equal to our targeted value
        we set that position as low */
        if (value >= ar[mid])
        {
            low = mid + 1;
        }
        else
        {
            high = mid;
        }
    }
    return low - 1;
}

int main()
{
    cout << "Enter the size of the array : \n";
    int N;
    cin >> N;
    cout << "Enter the target value\n";
    int value;
    cin >> value;
    int ar[N + 1];
    cout << "Enter array elements :\n";
    for(int i = 0; i < N; i++)
    {
        cin >> ar[i];
    }
    int first_index = f_indx(ar, N , value);
    int last_index = l_indx(ar, N , value);
    cout << "First index position is : ";
    cout << first_index << endl;
    cout << "Last index position is : ";
    cout << last_index << endl;
}

/*
Standard Input and Output

Enter the size of the array :
10
Enter the target value
12
Enter array elements :
1 2 4 6 8 10 12 12 12 12
First index position is : 6
Last index position is : 9

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

*/


<|start_filename|>C-Plus-Plus/cp/Spiral_Matrix.cpp<|end_filename|>
class Spiral_Matrix {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> arrLL;
        
        //EDGE CASE
        if (matrix.size()  == 0) return arrLL;
        
        int rows = matrix.size() ;
        int columns = matrix[0].size() ;
        
        if (rows == 1 && columns == 1) {
            arrLL.push_back(matrix[0][0]);
            return arrLL;
        }
        
        if (rows == 1) {
            for (int j = 0; j < columns; j++){
                arrLL.push_back(matrix[0][j]);  
            }
            return arrLL;
        }
        
        if (columns == 1){
            for (int i = 0; i < rows; i++){
                arrLL.push_back(matrix[i][0]);  
            }
            return arrLL;
        }
        
        int i, j, k1, k2, itr = 0;
        while (j < columns || i < rows || j > k1 || i > k2){
           
            bool cond1 = false;
            while (j < columns ){
                if (i != itr || i >= rows) break;
                arrLL.push_back(matrix[i][j]);
                j++;
                cond1 = true;
            }
        
            i++; j--; n--;
            bool cond2 = false;
            while (i < rows && cond1 == true){
                arrLL.push_back(matrix[i][j]);
                cond2 = true;
                i++;
            }
            
            j--; i--; m--;
            bool cond3 = false;
            while ( j>= k1  && cond2 == true){
                arrLL.push_back(matrix[i][j]);
                j--;
                cond3 = true;
            }
            
            j++; i--; k1++;
            while ( i > k2 && cond3 == true) {
                arrLL.push_back(matrix[i][j]);
                i--;
            }
            
            j++; i++; k2++;
            itr ++;
        }
        return arrLL;
    }
};

/*
TEST CASE

TIME COMPLEXITY : 0(N*M) 
SPACE COMPLEXITY: 0(N+M)

where N is number of rows and M is number of columns

INPUT
[[ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]]

OUTPUT
[1,2,3,6,9,8,7,4,5]

INPUT
[[1, 2, 3, 4],
 [5, 6, 7, 8],
 [9,10,11,12]]

OUTPUT
[1,2,3,4,8,12,11,10,9,5,6,7]
*/


<|start_filename|>Go/math/Strong_Number/strongnumber.go<|end_filename|>
/* This is Program in go language to check whether a given number is
   Strong number or not. Strong number is a special number whose
   sum of factorial of digits is equal to the original number.
   Eg: 145 is strong number. Since, 1! + 4! + 5! = 145   
*/

package main

import (

  "fmt"

)

//global variable
var a int

//This function will return us the factorial of a given number
func factorial(n int)int {

  if(n == 0){
     return 1
  }else{
     return n*factorial(n-1)
  }

}

//This function tells us if the given number is a strong number or not
func strongnumber() {

  var number int
  number = a
  var sum int
  sum = 0
  var digits int
  /* we calculate the sum of the factorials of individual digits 
     of the number given*/
  for number!=0 {

    digits = number%10
    sum += factorial(digits)
    number /= 10
  }

  // checking if the sum is same as orginal number
  if (sum == a){

    fmt.Print("The given number is a strong number!")

  }else{

    fmt.Print("The given number is not a strong number!")
  }

}

//driver function
func main() {

   fmt.Print("Enter the number we need to check :")
   // Taking the input for the number we need to check
   fmt.Scan(&a)

   //calling the strongnumber function
   strongnumber()
}

/*
   Simple I/O :

   a) Is a strong number :

   Enter the number we need to check :40585
   The given number is a strong number!

   b) Is not a strong number :

   Enter the number we need to check :45
   The given number is not a strong number!   
*/



<|start_filename|>Java/Algorithms/kadanes_Java.java<|end_filename|>
// Java Program for Kadane's Algorithm.

import java.util.*;
public class kadanes_Java {

   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      int n = sc.nextInt();
      int[] arr = new int[n];
      int maxSoFar = Integer.MIN_VALUE;
      int curSum = 0;
      for (int i = 0; i < arr.length; i++) {
         arr[i] = sc.nextInt();
      }
      for (int i = 0; i < arr.length; i++) {
         if (curSum + arr[i] < 0)
            curSum = 0;
         else
            curSum = curSum + arr[i];
         if (curSum > maxSoFar)
            maxSoFar = curSum;
      }
      System.out.println(maxSoFar);
      sc.close();
   }
}


<|start_filename|>Java/dp/MemoryAllocations.java<|end_filename|>
//                      Best Fit , First Fit , Worst Fit

//      Simulate first-fit, best-fit and worst-fit memory allocations

/*

    FIRST FIT (FF) 
*A resource allocation scheme (usually for memory). 
*First Fit fits data into memory by scanning from the beginning of available memory to the end, 
until the first free space which is at least big enough to accept the data is found.
*This space is then allocated to the data.
*Any left over becomes a smaller, separate free space. 
*If the data to be allocated is bigger than the biggest free space, 
the request cannot be met, and an error will be generated


    BEST FIT (BF) 
*The best fit deals with allocating the smallest free partition which meets the requirement of the requesting process. 
*This algorithm first searches the entire list of free partitions and considers the smallest hole that is adequate.
*It then tries to find a hole which is close to actual process size needed.


    WORST FIT (WF) 
*The algorithm searches for free-space in memory in which it can store the desired information. 
*The algorithm selects the largest possible free space that the information can be stored on 
(i.e. that is bigger than the information needing to be stored) and stores it there.
*This is directly opposed to the best fit algorithm which searches the memory in much the same way as before.



*/

import java.util.*;

public class MemoryAllocations {

    // Array for storing the size of differnt memory blocks
    static int block[] = new int[10];

    // Array for storing the size of memory
    // required by each process
    static int process[] = new int[10];

    static int i;
    static int j;
    static int b;
    static int p;

    public static void initialize() {

        // Creating Scanner Object to read input from user
        Scanner t = new Scanner(System.in);

        // Fill the number of blocks
        System.out.println("Enter the number of memory blocks");
        b = t.nextInt();

        // Fill the size of the blocks
        System.out.println("Enter the size of each memory block");
        for (i = 0; i < b; i++) {
            block[i] = t.nextInt();
        }

        // Fill the number of processes
        System.out.println("Enter the number of processes");
        p = t.nextInt();

        // Fill the size of the processes
        System.out.println("Enter the size of each process");
        for (i = 0; i < p; i++) {
            process[i] = t.nextInt();
        }

    }

    // Function to implement first fit allocation
    public static void firstfit() {

        int flag[] = new int[10];
        int allocated[] = new int[10];

        // Function call to initialize memory and process blocks
        initialize();

        System.out.println("First-Fit Memory Allocation");

        // Initially no block is assigned to any process
        for (i = 0; i < 10; i++) {
            flag[i] = 0;
            allocated[i] = -1;
        }

        /* pick each process and find suitable blocks
         according to its size and assign to it */
        for (i = 0; i < p; i++) {
            for (j = 0; j < b; j++) {
                if (flag[j] == 0 && block[j] >= process[i]) {
                    allocated[j] = i;
                    flag[j] = 1;
                    break;
                }
            }
        }

        // printing result after memory allocation
        System.out.println("Block no.\tsize\t\tprocess no.\t\tsize");

        for (i = 0; i < b; i++) {

            System.out.printf("\n%d\t\t%d\t\t", i + 1, block[i]);

            if (flag[i] == 1)
                System.out.printf("%d\t\t\t%d", allocated[i] + 1, process[allocated[i]]);

            else
                System.out.printf("Not allocated");

        }
    }

    // Function to implement best fit allocation
    public static void bestfit() {

        final int barray[] = new int[20];
        final int parray[] = new int[20];
        int fragment[] = new int[20];
        int temp;
        int lowest = 9999;

        // Function call to initialize memory and process blocks
        initialize();

        System.out.println("Best-Fit Memory Allocation");

        /* pick each process and find suitable blocks
         according to its size and assign to it
        */
        for (i = 0; i < p; i++) {

            // Find the best fit block for current process
            for (j = 0; j < b; j++) {

                if (barray[j] != 1) {

                    temp = block[j] - process[i];

                    if (temp >= 0) {

                        if (lowest > temp) {

                            parray[i] = j;

                            lowest = temp;
                        }
                    }
                }
            }
            // Remaining Size of that particular block selected after memory allocation
            fragment[i] = lowest;

            barray[parray[i]] = 1;

            lowest = 10000;

        }

        // printing result after memory allocation
        System.out.printf("\nProcess_no\tProcess_size\tBlock_no\tBlock_size\tFragment");

        for (i = 0; i < p && parray[i] != 0; i++)
            System.out.printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d", i, process[i], parray[i], block[parray[i]], fragment[i]);

    }

    // Function to implement worst fit allocation
    public static void worstfit() {

        int temp;
        int highest = 0;
        int fragments[] = new int[10];
        final int blockArr[] = new int[10];
        final int fileArr[] = new int[10];

        // Function call to initialize memory and process blocks
        initialize();

        System.out.printf("\n Worst-Fit Memory Allocation");
        for (i = 0; i < p; i++) {
            // Find the best fit block for current process
            for (j = 0; j < b; j++) {

                if (blockArr[j] != 1) {

                    temp = block[j] - process[i];

                    if (temp >= 0) {

                        if (highest < temp) {

                            fileArr[i] = j;
                            highest = temp;

                        }
                    }
                }

                // Remaining Size of that particular block selected after memory allocation
                fragments[i] = highest;
                blockArr[fileArr[i]] = 1;
                highest = 0;
            }

        }

        // printing result after memory allocation
        System.out.printf("\nFile Number\tFile Size\tBlock Number\tBlock Size\tFragment");
        for (i = 0; i < p; i++) {

            System.out.printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d", i, process[i], fileArr[i], block[fileArr[i]],
                    fragments[i]);

        }
        System.out.printf("\n");

    }

    public static void main(String[] args) {

        int choice;
        boolean flag = true;

        System.out.println("Press 1 to simulate first-fit memory allocation");
        System.out.println("Press 2 to simulate best-fit memory allocation");
        System.out.println("Press 3 to simulate worst-fit memory allocation");
        System.out.println("Press 4 to exit");
        System.out.println();

        while (flag) {
            System.out.printf("\nEnter the choice\n");
            // Creating Scanner Object to read input from user
            Scanner s = new Scanner(System.in);

            // Read the choice given by the user
            choice = s.nextInt();

            switch (choice) {
            case 1:
                firstfit();
                break;
            case 2:
                bestfit();
                break;
            case 3:
                worstfit();
                break;

            case 4:
                flag = false;
                break;
            }

        }

    }
}



/*
 * TEST CASES
 * 
 * 
 * Press 1 to simulate first-fit memory allocation 
 * Press 2 to simulate best-fit memory allocation 
 * Press 3 to simulate worst-fit memory allocation 
 * Press 4 to exit
 * 
 * 
 * Enter the choice 
 * 2 
 * Enter the number of memory blocks 
 * 5 
 * Enter the size of each memory block 
 * 10 15 5 9 3 
 * Enter the number of processes 
 * 4 
 * Enter the size of each process 
 * 1 4 7 12 
 * 
 * Best-Fit Memory Allocation
 * Process_no   Process_size   Block_no   Block_size  Fragment
 *  0           1              4          3           2          
 *  1           4              2          5           1 
 *  2           7              3          9           2
 *  3           12             1          15          3
 * 
 * 
 * Enter the choice 
 * 3 
 * Enter the number of memory blocks 
 * 5 Enter the size of each memory block 
 * 5 4 3 6 7 
 * Enter the number of processes 4 
 * Enter the size of each process 
 * 1 3 5 3
 * 
 * Worst-Fit Memory Allocation
 * File Number   File Size   Block Number   Block Size  Fragment 
 * 0             1           4              7           6 
 * 1             3           0              5           0 
 * 2             5           0              5           0 
 * 3             3           0              5           0
 * 
 * 
 * 
 * Enter the choice 
 * 1 
 * Enter the number of memory blocks 
 * 3 
 * Enter the size of each memory block 
 * 12 7 4 
 * Enter the number of processes 
 * 3 
 * Enter the size of each process 
 * 7 4 9 
 * 
 * First-Fit Memory Allocation
 * Block no.     size      process no.   size
 * 
 * 1             12        1              7 
 * 2             7         2              4 
 * 3             4         3              Not allocated
 * 
 * 
 * 
 * 
 */


  


<|start_filename|>Java/ds/queue.java<|end_filename|>

class Queue {

        int front, rear;
	int arr[] = new int[100005];

    Queue()
        {
		front=0;
		rear=0;
	}
	
	void push(int x)
	{
	   arr[rear]=x;
	   rear++;
	} 

	int pop()
	{
	    if(front==rear){
	        return -1;
	    }
	    int curr=arr[front];
	    front++;
	    return curr;
	}

	int pop()
	{
	    if(front==rear){
	        return -1;
	    }
	    int curr=arr[front];
	    front++;
	    return curr;
	} 
        
        int peek()
	{
	    if(front==rear){
	        return arr[front];
	    }
	    int curr=arr[rear];
	    return arr[rear];
	} 
}


<|start_filename|>C-Plus-Plus/dp/subsets_with_given_diff.cpp<|end_filename|>
/* 
   Find number of subsets with given difference between their sums 
 
   This approach uses dynamic programming and subset sum problem to find the count 
   of subsets whose difference is given. To count the subsets with a given a sum, we need a sum in this problem
   which can be found out by using the formula (diff + sum(arr))/2 explained below.
*/

#include <bits/stdc++.h>
using namespace std;
int dp[20001][20001];

int countSubsets(int arr[], int n, int sum)
{
	if (dp[n][sum] != -1)
		return dp[n][sum];
	// base case
	if (sum == 0)
		return 1;
	if (n == 0)
		return 0;
	if (arr[n - 1] <= sum)
		return dp[n][sum] = countSubsets(arr, n - 1, sum - arr[n - 1]) + countSubsets(arr, n - 1, sum);
		
	return dp[n][sum] = countSubsets(arr, n - 1, sum);
}

int subsetsDiff(int arr[], int n, int diff)
{
	int arr_sum = 0;
	// sum of the array
	for (int i = 0; i < n; i++)
		arr_sum += arr[i];
    /*
    Let there be two subsets with sum s1 and s2 respectively
	s1 + s2 = arr_sum
	s1 - s2 = diff
	so solving the above equations, we get:
	s1 = (diff + arr_sum)/2
	Therefore, we will find number of subsets with sum as s1
    */
	int sum = (diff + arr_sum) / 2;
	
	return countSubsets(arr, n, sum);
}

int main()
{
	// dp table
	memset(dp, -1, sizeof(dp));
	int n, diff; 
	cin >> n >> diff;
	int arr[n];
	for (int i = 0; i < n; i++)
	{
		cin >> arr[i];
	}

	cout << subsetsDiff(arr, n, diff);
	
	return 0;
}

/* 
 
 Sample I/O:
 First line contains two integers n and diff denoting size of array 
 and the required difference
 Next line contains n spaced integers
 4 1
 1 1 2 3

 Output: 3

 Explanation:
 Three pairs of subsets:
 1.[1, 1, 2] and[3]
 2.[1, 2] and[1, 3]
 3.[1, 3] and[1, 2] (Because there are two 1's, so repitition of pairs is there)
*/

/*
 Complexity Analysis: 
 Time Complexity: O(sum*n), where sum is the ‘sum’ in the function subsetsDiff and ‘n’ is the size of array.
 Auxiliary Space: O(sum*n), as the size of 2-D array is sum*n.
*/


<|start_filename|>Java/Operating-System/CPU_Scheduling_SRTF.java<|end_filename|>
/*
-SRTF(Shortest Remaining Time First) is the preemptive version of SJF scheduling. 
-In SRTF, the execution of the process can be stopped after certain amount of time. 
-At the arrival of every process, the short term scheduler schedules the process 
with the least remaining burst time among the list of available processes and the 
running process.
*/

import java.util.Scanner;

class process {
    int arrivalTime, burstTime, completionTime, turnaroundTime, waitingTime, remainingTime;
    int id;
    String name;

    process() {
        arrivalTime = 0;
        burstTime = 0;
        completionTime = 0;
        turnaroundTime = 0;
        waitingTime = 0;
        name = " ";
    }
}

public class CPU_Scheduling_SRTF {
    public static void main(String[] args) {
        Scanner SC = new Scanner(System.in);
        int num;
        int total_time = 0;
        float average_waiting_time = 0;
        float average_turnaround_time = 0;
        int min, select;

        System.out.println("Enter no of processes: ");
        num = SC.nextInt();

        process process[] = new process[20];

        for (int i = 0; i < num; i++) {
            process[i] = new process();
            System.out.println("Enter burst time: ");
            process[i].burstTime = SC.nextInt();
            process[i].remainingTime = process[i].burstTime;
            System.out.println("Enter arrival time: ");
            process[i].arrivalTime = SC.nextInt();
            System.out.println("Enter name of process: ");
            process[i].name = SC.next();
        }

        for (int i = 0; i < num; i++) {
            total_time = total_time + process[i].burstTime; // Calculation of total time
        }

        System.out.println("Total time: " + total_time);

        String gantt[] = new String[total_time]; // Array of gantt chart

        for (int i = 0; i < total_time; i++) {
            min = total_time;
            select = 0;
            for (int j = 0; j < num; j++) {
                if (process[j].arrivalTime <= i) {
                    if (process[j].remainingTime < min && process[j].remainingTime != 0) // check if min time is less than min
                    {
                        min = process[j].remainingTime;
                        select = j; // store min address in variable
                    }
                }
            }
            gantt[i] = process[select].name;

            process[select].remainingTime--;
        }

        System.out.println("Gantt chart is: ");
        for (int i = 0; i < total_time; i++) {
            System.out.print(gantt[i] + "\t");
        }

        System.out.println();

        for (int i = 0; i < num; i++) {
            int k = total_time - 1;
            while (process[i].name.compareTo(gantt[k]) != 0) {
                k--;
            }
            if (process[i].name.compareTo(gantt[k]) == 0) {
                process[i].completionTime = k + 1;
            }
        }
        for (int i = 0; i < num; i++) {
            process[i].turnaroundTime = process[i].completionTime - process[i].arrivalTime;
            process[i].waitingTime = process[i].turnaroundTime - process[i].burstTime;
            average_waiting_time = average_waiting_time + process[i].waitingTime;
            average_turnaround_time = average_turnaround_time + process[i].turnaroundTime;

        }
        average_waiting_time = average_waiting_time / num;
        average_turnaround_time = average_turnaround_time / num;

        System.out.println("Name\tAT\tBT\tFT\tTT\tWT");

        for (int i = 0; i < num; i++) {
            System.out.println(
                    process[i].name + " " + process[i].arrivalTime + "\t" + process[i].burstTime + "\t" + process[i].completionTime + "\t" + process[i].turnaroundTime + "\t" + process[i].waitingTime);
        }
        System.out.println("\nAverage Waiting Time : " + average_waiting_time);
        System.out.println("\nAverage Turnaround Time : " + average_turnaround_time);
        System.out.println();

    }

}

/*
 * Enter no of processes: 4 
 * Enter burst time: 6 
 * Enter arrival time: 0
 * Enter name of process: p1 
 * Enter burst time: 2 
 * Enter arrival time: 2 
 * Enter name of process: p2 
 * Enter burst time: 5 
 * Enter arrival time: 4 
 * Enter name of process: p3 
 * Enter burst time: 3 
 * Enter arrival time: 6 
 * Enter name of process: p4
 * 
 * Total time: 16
 * 
 * Gantt chart is: p1 p1 p2 p2 p1 p1 p1 p1 p4 p4 p4 p3 p3 p3 p3 p3
 * 
 * Name AT BT FT TT WT p1 0 6 8 8 2 p2 2 2 4 2 0 p3 4 5 16 12 7 p4 6 3 11 5 2
 * 
 * Average Waiting Time : 2.75 ms
 * 
 * Average Turnaround Time : 6.75 ms
 * 
 */

<|start_filename|>C-Plus-Plus/cp/CountofPinS.cpp<|end_filename|>
#include <iostream>
using namespace std;

// Problem Statement:
// Given a string, write a recursive function, to print the occurrences of string p in the string s(Overlap is allowed)
// Example :
// 1. Input: p = "aaa", s = "aaaaaa"
//   Output: 4
// 2. Input: p = "hi", s = "hihihithi"
//   Output: 4

void check_p_in_s(string p, string s, int stri, int count){ 
    if(stri == s.size()){ //When all the characters in string s are checked, print the count
        cout << count;
        return;
    }
    if(p == s.substr(stri, p.size())){ //When we find string p in string s, we increase the count and increment string index by 1
        return check_p_in_s(p, s, stri + 1, count + 1);
    }
    else{ //When string p does not match the substring in s, we just move to the next character without increasing the count
        return check_p_in_s(p, s, stri + 1, count); 
    }
}

int main(){
    string p, s;
    cout << "Enter the main string";
    cin >> s;
    cout << "Enter the string that you want to count in the main string";
    cin >> p;
    check_p_in_s(p, s, 0, 0);
    return 0;
}


<|start_filename|>C-Plus-Plus/ds/Max_Sum_Level_Of_Binary_Tree.cpp<|end_filename|>
/*

Introduction 
Given a Binary Tree , Print the level with maximum sum , and its corresponding sum.

Argument/Return Type
Input of total no.of nodes is taken
Input of key values of nodes of tree are taken in level order form 
Incase of a null node , -1 is taken as input
A function which returns the level with maximum sum and its corresponding sum.

*/

//  Code / Solution

#include <bits/stdc++.h> 
using namespace std;
// Declare global variables
long max_level;
long max_sum;

//Define Node as structure
struct Node 
{
    int key;
    Node* left;
    Node* right;
};
 
// Function to create a node with 'value' as the data stored in it. 
// Both the children of this new Node are initially null.
struct Node* newNode(int value)
{
    Node* n = new Node;
    n->key = value;
    n->left = NULL;
    n->right = NULL;
    return n;
}

// Function to build tree with given input
struct Node* createTree(vector<int>v)
{
    int n=v.size();
    if(n==0) 
      return NULL;
    vector<struct Node* >a(n);
    //Create a vector of individual nodes with given node values
    for(int i=0;i<n;i++)  
    {
        //If the data is -1 , create a null node
        if(v[i]==-1)  
          a[i] = NULL;
        else 
          a[i] = newNode(v[i]);
    }
    //Interlink all created nodes to create a tree
    //Use two pointers using int to store indexes
    //One to keep track of parent node and one for children nodes
    for(int i=0,j=1;j<n;i++) 
    {
        //If the parent node is NULL , advance children pointer twice
        if(!a[i])
        {
          j=j+2;
          continue;
        } 
        //Connect the two children nodes to parent node
        //First left and then right nodes
        a[i]->left = a[j++];
        if(j<n) 
          a[i]->right = a[j++];
    }
    return a[0];
}

//Function to update level with maximum sum and its corresponding sum
void FindMaxSum(struct Node* root)
{
    //Initialise current and maximum sums and corrresponding levels with 0 value
    long curr_sum=0,curr_level=0;
    max_sum=0;
    max_level=0;
    // If root is NULL , return current levels
    if (root == NULL)
        return ;

    // Create an queue
    queue<struct Node*> q;
    //Enqueue the root node and a null node to indicate a level is completed
    q.push(root);
    q.push(NULL);
 
    while (!q.empty()) 
    {
        //If we encounter a NULL node , it means a level is complete
        //Hence update max_sum and max_level 
        // Re initialise curr_sum to 0 , and increase curr_level by 1
        if(q.front()==NULL)
        {
            curr_level++;
            if(max_sum<curr_sum)
            {
                 max_sum=curr_sum;
                 max_level=curr_level;
            }
            curr_sum=0;
            q.pop();
            if(!q.empty())
            {
                //If there are more nodes in q , push a NULL node
                q.push(NULL);
            }
        }
        else
        {
            //Add the node's value to curr_sum
            curr_sum=curr_sum+q.front()->key;
            //Enqueue node's children , if they exist
            if(q.front()->left)
               q.push(q.front()->left);
            if(q.front()->right)
               q.push(q.front()->right);
            q.pop();
        }
    }
    return ;
}
 
// Driver code
int main()
{

    int n;
    cout<<"Enter total no.of nodes of the input Tree ( including NULL nodes ) : ";
    cin>>n;

    vector<int>v(n);
    cout<<"Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces"<<endl;
    for(int i=0;i<n;i++)
    {
        cin>>v[i]; //store the input values in a vector
    }

    //create the tree using input node values  
    struct Node* root=createTree(v); 

    //Call the function and print the result
    FindMaxSum(root);
    cout<<"Hence the level with max sum is level "<<max_level<<" with sum "<<max_sum;
    
    return 0; 
}
    
/*
Input:
0 <= node->key < 1000000000
if node is NULL , -1 is entered as it's key

Sample Test Case 1  
Input Binary Tree :                   

               10                                
           /         \                          
         11              12                    
     /       \        /   \               
    5       NULL     6     13             
   / \      /  \    / \   /  \            
  4 NULL  NULL NULL 8  9 10  NULL         


Input Format : 
Example :
Enter total no.of nodes of the input Tree ( including NULL nodes ) : 15
Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces
10 11 12 5 -1 6 13 4 -1 -1 -1 8 9 10 -1

Output Format :
Example : ( Output to the above input example ) 
Hence the level with max sum is level 4 with sum 31

Sample Test Case 2  
Input Binary Tree :                   

                  12                                
          /               \                          
         9                 17                    
     /       \          /      \               
    8       10         15       18             
   / \      /  \      / \      /  \            
  7 NULL  NULL NULL 14  16 NULL  20         


Input Format : 
Example :
Enter total no.of nodes of the input Tree ( including NULL nodes ) : 15
Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces
12 9 17 8 10 15 18 7 -1 -1 -1 14 16 -1 20

Output Format :
Example : ( Output to the above input example ) 
Hence the level with max sum is level 4 with sum 57

Time/Space Complexity
Time Complexity : O(n) 
   Where n is the no.of nodes 
Space Complexity : O(n) 
   Where n is the no.of nodes
*/


<|start_filename|>C/graphs/DFS.c<|end_filename|>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>


#define MAX 20
#define TRUE 1
#define FALSE 0


int g[MAX][MAX];
int v[MAX];
int n;

void main()
{
    int v1, v2;
    char ans;
    void create();
    void Dfs(int);
    create();
    printf("The Adjacency Matrix for the graph is \n");
    for (v1 = 0; v1 < n; v1++)
    {
        for (v2 = 0; v2 < n; v2++)
            printf("%d", g[v1][v2]);
        printf("\n");
    }
    getchar();
    do
    {
        for (v1 = 0; v1 < n; v1++)
        v[v1] = FALSE;
        printf("Enter the Vertex from which you want to traverse ");
        scanf("%d", &v1);
        if (v1 >= MAX)
            printf("Invalid Vertex\n");
        else
        {
            printf("The Depth First Search of the Graph is\n");
            Dfs(v1);
        }
        printf("\nDo you want to traverse By any other node?");
        ans = getchar();
    } while (ans == 'y');
}
void create()
{
    int ch, v1, v2, flag;
    char ans = 'y';
    printf("\n\t\t This is a program to create a Graph");
    printf("\n\t\t The Display Is In Depth First Manner");
    getch();


    printf("\nEnter no. of nodes");
    scanf("%d", &n);
    for (v1 = 0; v1 < n; v1++)
        for (v2 = 0; v2 < n; v2++)
            g[v1][v2] = FALSE;
    printf("\nEnter no. of nodes");
    scanf("%d", &n);
    printf("\nEnter the vertices no. starting from 0");
    do
    {
        printf("\nEnter the vertices v1 & v2");
        scanf("%d%d", &v1, &v2);
        if (v1 >= n || v2 >= n)
            printf("Invalid Vertex Value\n");
        else
        {
            g[v1][v2] = TRUE;
            g[v2][v1] = TRUE;
        }
        printf("\n\nAdd more edges??(y/n)");
        ans = getchar();
    } while (ans == 'y');
}
void Dfs(int v1)
{
    int v2;
    printf("% d",v1);
        v[v1] = TRUE;
    for (v2 = 0; v2 < MAX; v2++)
        if (g[v1][v2] == TRUE && v[v2] == FALSE)
            Dfs(v2);
}

/*
Sample Case : 
This is a Program To Create a Graph
The Display Is In Depth First Manner
Enter no. of nodes 4
Enter the vertices no. starting from 0
Enter the vertices v1 & v2
0 1
Add more edges??(y/n)y
Enter the vertices v1 & v2
0 2
Add more edges??(y/n)y
Enter the vertices v1 & v2
1 3
Add more edges??(y/n)y
Enter the vertices v1 & v2
2 3
Add more edges??(y/n)
The Adjacency Matrix for the graph is
0 1 1 0
1 0 0 1
1 0 0 1
0 1 1 0
Enter the Vertex from which you want to traverse : 1
The Depth First Search of the Graph is
1
0
2
3
Do you want to traverse from any other node?
*/


<|start_filename|>C-Plus-Plus/math/binomial_coefficient_under_modulo.cpp<|end_filename|>
#include<bits/stdc++.h>
using namespace std;

/*
This algorithm is used to calculate ncr under some mod.
ncr = factorial(n)/(factorial(r)*factorial(n-r))
ncr%mod = factorial(n)*inverse(factorial(r))%mod*inverse(factorial(n-r)%mod)%mod (here inverse is modinverse)

We use Fermat's little theorem to calculate modinverse of a value
According to Fermat's little theorem 
num^(p-1)=1(mod p)
Multiplying by side by num^-1, we get
num^(p-2)=num^-1(mod p)

So, to get inverse, we need to calulate (mod-2)th power of num under modulo mod.
*/

long long inverse(long long val,long long mod)
{
    long long power=mod-2;
    long long answer=1;
    while(power>0)
    {
        if(power%2==1)
        {
            answer=(answer*val)%mod;
        }
        val=(val*val)%mod;
        power=power/2;
    }
    return answer;
}

long long ncr(long long n,long long r,long long mod)
{
    long long facn,facr,facnr;
    long long curr_value=1;
    for(int i=1;i<=n;++i)
    {
        curr_value=curr_value*i;
        if(i==n)
        {
            facn=curr_value;
        }
        if(i==r)
        {
            facr=curr_value;
        }
        if(i==n-r)
        {
            facnr=curr_value;
        }
    }
    long long answer=facn*inverse(facr,mod)%mod*inverse(facnr%mod,mod)%mod;
    return answer;
}

int main()
{
    long long n,r,mod;
    cout<<"Enter value of n: ";
    cin>>n;
    cout<<"Enter value of r: ";
    cin>>r;
    cout<<"Enter value of mod: ";
    cin>>mod;
    cout<<"ncr%mod = "<<ncr(n,r,mod)<<"\n";
}

/*
Sample I/0

1. 
    INPUT 
    Enter value of n: 3
    Enter value of r: 2
    Enter value of mod: 1
    OUTPUT
    ncr%mod = 0
2.
    INPUT
    Enter value of n: 11
    Enter value of r: 7 
    Enter value of mod: 13
    OUTPUT
    ncr%mod = 5
*/

/*
Time Complexity: O(n)
Space Complexity: O(1)
*/



<|start_filename|>C-Plus-Plus/other/find_the_numbers.cpp<|end_filename|>
/*
You are given an array arr containing 2N+2 positive numbers, out of which 2N numbers exist in pairs whereas the
other two number occur exactly once and are distinct. You need to find the other two numbers and print them in
ascending order.
*/

#include <bits/stdc++.h>

using namespace std;

// DRIVER FUNCTION
int main()
{
    int t, n, size;
    // Getting the Number of test cases as input
    cin >> t;
    while (t--)
    {
        //Getting the value N
        cin >> n;
        //The Array contains 2N+2 numbers
        size = 2 * n + 2;
        int arr[size], index;
        //Declare a vector for storing the result
        vector<int> res(2);
        //Declare a map for storing the frequency of numbers
        map<int, int> mp;
        //Getting the array input
        for (index = 0; index < size; index++)
            cin >> arr[index];

        //Storing the frequencies of the elements in the map
        for (index = 0; index < size; index++)
            mp[arr[index]]++;

        int resInd = 0;
        //Declare an iterator to traverse through the map
        map<int, int>::iterator it;

        for (it = mp.begin(); it != mp.end(); it++)
        {
            //Checking if the an element occurred odd number of times
            //if so, we will add that element to the resultant vector
            if ((it->second) % 2 != 0)
            {
                res[resInd++] = it->first;
            }
        }
        //Since we need to print the other two numbers in ascending order,
        //the resultant vector is sorted
        sort(res.begin(), res.end());
        //print the two numbers stored in the resultant vector
        for (int ind = 0; ind < res.size(); ind++)
            cout << res[ind] << " ";
    }

    return 0;
}
/*
For example:

Example 1:
Input:
1
2
1 2 3 2 1 4

Output:
3 4

Example 2:
Input:
1
1
2 1 3 2

Output:
1 3
*/

<|start_filename|>Java/ds/Infix_to_Postfix.java<|end_filename|>
/* Java implementation to convert infix expression to postfix */
/* Time  Complexity - O(N) 
 * Space Complexity - O(N) */
import java.util.Scanner;
import java.util.Stack; 
public class Infix_to_Postfix {
	    //Given function returns the precedence of an operator,higher value indicates the higher precedence  
	    public static int precedence(char ch) 
	    { 
	        switch (ch) 
	        { 
	             // operator '+' & '-' have same precedence and lower precedence than '+', '-' & '^' operator
	          case '+': 
	          case '-': 
	                return 1; 
	             // operator '*' & '/' have same precedence and greater precedence than '+' & '-' operator
	          case '*': 
	          case '/': 
	                return 2; 
	             // operator '^' have highest precedence
	          case '^': 
	               return 3; 
	        } 
	        return -1; 
	    } 
	    //Given method which converts infix expression to postfix
	    public static String infixToPostfix(String exp) 
	    { 
	        // initializing empty String for result 
	        String result = ""; 
	          
	        // initializing empty stack 
	        Stack<Character> stack = new Stack<>(); 
	          
	        for (int i = 0; i<exp.length(); ++i) { 
	            
	        	char c = exp.charAt(i); 
	              
	            // If the scanned character is an 
	            // operand, add it to output
	            if (Character.isLetterOrDigit(c)) {
	                result += c; 
	               
	            // If the scanned character is an '(' parenthesis, then  
	            // push it to the stack 
	            } else if (c == '(') {
	                stack.push(c); 
	              
	            //  If the scanned character is an ')' parenthesis, then  
	            // pop an output from the stack  
	            // until an '(' parenthesis is encountered 
	            } else if (c == ')') { 
	                
	            	while (!stack.isEmpty() &&  stack.peek() != '(') {
	                    result += stack.pop(); 
	                } 
	            	// finally, pop '(' parenthesis from stack
	                stack.pop(); 
	            
	            } else { // an operator is encountered
	                // Check the precedence of current operator with the top of stack
	            	// If the precedence of curr operator is less than top of stack, then pop() and append it to the final answer 
	            	while (!stack.isEmpty() && precedence(c) <= precedence(stack.peek())) { 
	                    result += stack.pop(); 
	                } 
	            	// and push high precedence operator into the stack
	                stack.push(c); 
	            } 
	       } 
	       // pop all the operators from the stack 
	        while (!stack.isEmpty()){ 
	            if(stack.peek() == '(') {
	                return "Invalid Expression";
	            }    
	            result += stack.pop(); 
	         } 
	        return result; 
	    } 
	    // Main method  
	    public static void main(String[] args)  { 
	    	Scanner sc = new Scanner(System.in);
	        String exp = sc.next(); 
	        System.out.println(infixToPostfix(exp));
	        sc.close();
	    } 
	} 
/*
 * Sample Input1  : a+b*(c^d-e)^(f+g*h)-i
 * Sample Output1 : abcd^e-fgh*+^*+i-
 * Sample Input2  : a+b*c+d
 * Sample Output2 : abc*+d+
 * Sample Input2  : k+l-m*n+(o^p)*w/u/v*t+q
 * Sample Output2 : kl+mn*-op^w*u/v/t*+q+
 * */


<|start_filename|>C-Plus-Plus/graphs/number_of_connected_components.cpp<|end_filename|>
/*
Given total number of nodes in an undirected graph
numbered from 1 to n [ number of nodes] and total number of edges in the graph.
Calculate the total number of connected components in the graph.
*/

#include <bits/stdc++.h>
using namespace std;
vector < int > adj[10009];
int visited[10009];

// this dfs function will visit the nodes
void dfs(int node)
{
    /* for each node we will put  visited[node] = 1
    means that node is visited
    and then recursively will visit the
    adjacency vector
     */
    visited[node] = 1;
    for(auto child : adj[node])
    {
        if(visited[child] == 0)
        {
            dfs(child);
        }
    }
}

// this get_connected_components will count the number of connected components
int get_connected_components(int nodes)
{
    int connected_components = 0;
    for(int i = 1; i <= nodes; i++)
    {
        /* if the current visited[i] is zero , that means
        that node is not visited.
        so, we will make a dfs call
        and increment the connected_components
         */
        if(visited[i] == 0)
        {
            dfs(i);
            connected_components++;
        }

    }
    return connected_components;
}

int main()
{
    cout << "Enter the nodes and edges of the graph :\n";
    int nodes, edges;
    cin >> nodes >> edges;
    cout << "Enter the start and end points that have edges \n";
    for(int i = 1; i <= edges; i++)
    {
        int point1, point2;
        cin >> point1 >> point2;
        adj[point1].push_back(point2);
        adj[point2].push_back(point1);

    }
    int connected_components = get_connected_components(nodes);

    cout << "Number of Connected Components in this graph is: \n";
    cout << connected_components << endl;
}

/*
Standard Input and Output

Enter the nodes and edges of the graph :
8 5
Enter the start and end points that have edges
1 2
2 3
2 4
3 5
6 7

Number of Connected Components in this graph is:
3

Time Complexity : O( E + N) // Edges and Nodes
Space Complexity : O( N )

*/


<|start_filename|>C/ds/binary_tree_from_preorder_and_inorder.c<|end_filename|>
/*
Construction of binary tree from inorder and preorder traversal

binary tree can be uniquely constructed if it's preorder and inorder traversals
are given.
The following steps need to be followed
1. From the preorder traversal , it is evident that the first element is the root node
2. In inorder traversal, all the nodes which are on the left side of root (from preorder)
belong to the left sub-tree and those which are on right side of the root (from preorder)
are on right side of root (from preorder) belong to right sub-tree
3. Now the problem reduces to form sub-trees and the same procedure can be applied
repeatedly.
*/

#include <stdio.h>
#include <stdlib.h>
//struct for binary tree
typedef struct Tree
{
    char data;
    struct Tree *left;
    struct Tree *right;
} TreeNode;
// search function searches the inorder traversal and returns the index if found
int search(char in[], int start, int end, char key)
{
    for (int i = start; i <= end; i++)
    {
        if (in[i] == key)
        {
            return i;
        }
    }
}

// Build Tree Builds the tree from preorder and inorder traversals

TreeNode *BuildTree(char in[], char pre[], int start, int end)
{
    //preindex is static as it should get incremented after each recursive calls
    static int preindex = 0;
    if (start > end)
    {
        return NULL;
    }
    //get New node and make left and right as null
    TreeNode *node = (TreeNode *)malloc(sizeof(TreeNode));
    node->data = pre[preindex];
    node->left = NULL;
    node->right = NULL;
    preindex++;
    //if there is only one node return that node
    if (start == end)
    {
        return node;
    }
    // find the location of the root from the preorder traversal in the inorder
    //traversal and store it in loc
    int loc = search(in, start, end, node->data);
    //the elements to the left of the inorder traversal forms the left subtree
    node->left = BuildTree(in, pre, start, loc - 1);
    // the elements to the right of the inorder traversal forms the right subtree
    node->right = BuildTree(in, pre, loc + 1, end);
    return node;
}

void inorder(TreeNode *root)
{
    if (root != NULL)
    {
        inorder(root->left);
        printf("%c ", root->data);
        inorder(root->right);
    }
}

void preorder(TreeNode *root)
{
    if (root != NULL)
    {
        printf("%c ", root->data);
        preorder(root->left);
        preorder(root->right);
    }
}

void postorder(TreeNode *root)
{
    if (root != NULL)
    {
        postorder(root->left);
        postorder(root->right);
        printf("%c ", root->data);
    }
}

void printTree(TreeNode *root)
{
    printf("\nThe inorder traversal of the tree is\n");
    inorder(root);
    printf("\nThe preorder traversal of the tree is\n");
    preorder(root);
    printf("\nThe postorder traversal of the tree is\n");
    postorder(root);
    printf("\n");
}

int main()
{
    printf("Enter the number of nodes in the binary tree \n");
    int n;
    scanf("%d", &n);
    char *pre = (char *)malloc(sizeof(char) * (n + 1));
    char *in = (char *)malloc(sizeof(char) * (n + 1));
    printf("Enter the preorder traversal of the tree\n");
    for (int i = 0; i < n; i++)
    {
        scanf(" %c", &pre[i]);
    }
    printf("Enter the inorder traversal of the tree \n");
    for (int i = 0; i < n; i++)
    {
        scanf(" %c", &in[i]);
    }
    TreeNode *root = BuildTree(in, pre, 0, n - 1);
    printTree(root);
    return 0;
}
/*
Sample I/O :
1)
Enter the number of nodes in the binary tree
6
Enter the preorder traversal of the tree
A B D E C F
Enter the inorder traversal of the tree
D B E A F C

The inorder traversal of the tree is
D B E A F C
The preorder traversal of the tree is
A B D E C F
The postorder traversal of the tree is
D E B F C A


2)
Enter the number of nodes in the binary tree
4
Enter the preorder traversal of the tree
A B D C
Enter the inorder traversal of the tree
B D A C

The inorder traversal of the tree is
B D A C
The preorder traversal of the tree is
A B D C
The postorder traversal of the tree is
D B C A

Time complexity : O( n^2 )
Space complexity : O( n )
*/


<|start_filename|>C-Plus-Plus/sort/Shellsort.cpp<|end_filename|>
/*
Shell sort is a highly efficient sorting algorithm and is based on insertion sort algorithm.
This algorithm avoids large shifts as in case of insertion sort, if the smaller value is to the far right 
and has to be moved to the far left.This algorithm uses insertion sort on a widely spread elements, first to sort 
them and then sorts the less widely spaced elements. This spacing is termed as interval.
Worst case time complexity = O(n2)
Best case complexity = O(nlog(n)).
Space complexity = O(1).
*/


#include<iostream>
using namespace std;
/*Method to sort the list/array*/
void shellSort(int sort[],int size){
    for(int gap=size/2;gap>0;gap/=2){
        for(int i=gap;i<size;i++){
            int temp=sort[i];
            int j;
            for(j=i;j>=gap&&sort[j-gap]>temp;j-=gap){
                sort[j]=sort[j-gap];
            }
            sort[j]=temp;
        }
    }
}
//main program
int main(){
    int size;
    cout<<"Enter the size of the array: ";
    cin>>size;
    int sort[size];
    cout<<"Enter the Elements to be sorted:";
    for(int i=0;i<size;i++){
        cin>>sort[i];
    }
    shellSort(sort,size);
    cout<<"Array after sorting is: ";
    for(int i=0;i<size;i++){
        cout<<sort[i]<<" ";
    }
    cout<<endl;
    return 0;
}
/*       Output
Enter the size of the array: 5                                                                                                                
9 5 8 1 4                                                                                                                                            5                                                                                                                                             
Array after sorting is: 1 4 5 8 9                                                                                                                                           Array after sorting is: 1 4 5 8 9 
*/


<|start_filename|>C/sort/selection_sort.c<|end_filename|>
/*
selection sort is an in-place comparison sorting algorithm. It has an O(n²) time complexity, 
which makes it inefficient on large lists, and generally performs worse than the similar insertion 
sort. 

Time complexity:O(n^2)

The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning.
The algorithm maintains two subarrays in a given array.

1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.

In every iteration of selection sort, the minimum element (considering ascending order) from the 
unsorted subarray is picked and moved to the sorted subarray.

arr[] = 64 25 12 22 11   min(11,25,12,22,64)=11

// Find the minimum element in arr[0...4]
// and place it at beginning
11 25 12 22 64                                min(12,25,22,64) = 12

// Find the minimum element in arr[1...4]
// and place it at beginning of arr[1...4]
11 12 25 22 64                                min(25,22,64) = 22

// Find the minimum element in arr[2...4]
// and place it at beginning of arr[2...4]
11 12 22 25 64                                min(25,64) = 25

// Find the minimum element in arr[3...4]
// and place it at beginning of arr[3...4]
11 12 22 25 64                                 min(64) = 64

*/

#include <stdio.h>
#include <stdlib.h>

void swap(int *xp, int *yp)
{
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}
//create a array dynamically
int *create(int n)
{
    int *a = (int *)malloc(n * sizeof(int));

    for (int i = 0; i < n; i++)
    {
        /* take input using element */
        scanf("%d", (a + i));
    }

    return a;
}

//display the arrray
void display(int *a, int n)
{
    for (int i = 0; i < n; i++)
    {
        /* display it */
        printf("%d", *(a + i));
        printf(" ");
    }
}

//selection sort function
int *selection_sort(int *a, int n)
{
    int i, j, min_index;

    // One by one move boundary of unsorted subarray
    for (i = 0; i < n - 1; i++)
    {
        // Find the minimum element in unsorted array
        min_index = i;
        for (j = i + 1; j < n; j++)
            if (a[j] < a[min_index])
                min_index = j;

        // Swap the found minimum element with the first element
        swap(&a[min_index], &a[i]);
    }

    return a;
}

int main(int argc, char const *argv[])
{
    int n;

    printf("\nenter teh size of the array:");
    scanf("%d", &n);

    int *a = create(n);

    printf("\nunsorted array:");
    display(a, n);

    int *b = selection_sort(a, n);

    printf("\n\nsorted array:");
    display(b, n);

    return 0;
}


<|start_filename|>C-Plus-Plus/cp/Binary_Tree_Symmetric_or_not.cpp<|end_filename|>
/*  
This code checks if a binary tree is symmetric or not,
here we have a function "Check_Symmetry" which at first calculate the height of the given binary tree and then checks 
if all the levels of the given Binary tree are forming a palindrome or not, using "is_level_palindrome" function.
If all the level forms palindrome then it represent that the given binary tree is symmetric otherwise it is not symmetric.
If at the given level if some value is 'NULL', then we consider it as 'INT_MIN' while checking if level is palindrome or not.
*/

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

struct TreeNode{
	int value;
	struct TreeNode* left;
	struct TreeNode* right;
};

TreeNode* newNode(int n){
	TreeNode* t = new TreeNode;
	t->value = n;
	t->left = NULL;
	t->right = NULL;
	return t;
}

//this function calculate the height of the Binary Tree  
int height(TreeNode* A){		 
	if(A==NULL){
		return 0;
	}
	return 1 + max(height(A->left),height(A->right));
}

//This gives us the vector of values of all the nodes at the given height
void level_order(TreeNode* A, int h, vector<int> &v){ 		 
	if(A==NULL){
		v.push_back(INT_MIN);
		return;
	}
	if(h==1){
		v.push_back(A->value);
		return;
	}
	level_order(A->left,h-1,v);
	level_order(A->right,h-1,v);
}

// This function checks if particular level of given binary tree forms palindrome
bool is_level_palindrome(TreeNode* A, int h){		
	vector<int> v;
	level_order(A,h,v);
	for(int i=0;i<v.size()/2;i++){
		if(v[i]!=v[v.size()-1-i]){
			return false;
		}
	}
	return true;
}

//This function checks if given binary tree is symmetrical
bool Check_Symmetry(TreeNode* A){		   
	int h = height(A);
	for(int i=1;i<=h;i++){
		if(!is_level_palindrome(A,i)){
			return false;
		}
	}
	return true;
}

int main(){
	TreeNode* T = newNode(5);
	T->left = newNode(6);
	T->right = newNode(6);
	T->left->left = newNode(3);
	T->left->right = newNode(8);
	T->right->left = newNode(8);
	T->right->right = newNode(3);
	
	if(Check_Symmetry(T)){
		cout<<"Given Binary Tree is Symmetric."<<endl;
	}
	
	else{
		cout<<"Given Binary Tree is not Symmetric."<<endl;
	}
	
	return 0;
}

/*
Time Complexity : O(2^N)
Space Complexity : O(N)

Here we have given following binary tree as input:
    5
   / \
  6   6
 / \ / \
3  8 8  3 
This binary tree is symmetric, so output should be - "Given binary tree is symmetric."
*/



<|start_filename|>C-Plus-Plus/other/Median_in_row_wise_sorted_matrix.cpp<|end_filename|>
/* Find median in a row wise sorted Matrix in C++.

   We are given a row-wise sorted matrix of size r*c,
   we need to find the median of the matrix given.
   It is assumed that r*c is always odd.

   Example 1 : 

   Input 1 : 1 3 4
             2 6 9
             3 6 9
   
   Output 1 : Median is 4


   Example 2 : 

   Input 2 : 1 3 4
             2 5 6
             7 8 9
   
   Output 2 : Median is 5
  

   Formula for calculating the median.
   median = (1 + r * c) / 2

   Algorithm :-
   1) First, we need to find the minimum and maximum elements from the matrix.
   2) we can apply binary search on this range.
      The mid element can be calculated and number 
      of elements smaller or equal to mid can be calculated, 
      we have used upper_bound() function for this.
   3) Based on the value of our counter,
      the min and max can be adjusted accordingly based 
      on what we do for binary search.
*/

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


// Function to find median in the matrix
int solve()
{
    int r,c;
    cin>>r>>c;

    int a[r][c];
    for (int i = 0; i < r; ++i)
    {
        for (int j = 0; j < c; ++j)
        {
            cin>>a[i][j];
        }
    }


    int min = INT_MAX, max = INT_MIN;
    int desired_count = (1+(r*c)/2);
    for (int i=0; i<r; i++)
    {
        // Find the minimum element
        // and update the minimum element
        if (a[i][0] < min)
            min = a[i][0];

        // Find the maximum element
        // and update the maximum element
        if (a[i][c-1] > max)
            max = a[i][c-1];
    }

    int counter =0;
    while(min<max)
    {
        counter=0;
        //Find the middle element
        int mid = (max+min)/2;

        // Find count of element less then equal to mid
        // Using upper_bound function.
        for(int i= 0;i<r;i++)
        {
            counter += upper_bound(a[i], a[i]+c, mid) -  a[i];
        }
        if(counter < desired_count)
            min = mid+1;
        else
            max = mid;
    }
    // return the minumum index.
    return min;
}

int main()
{
    // Input the test cases.
    int t;
    cin>>t;
    while(t--)
    {
        int median = solve();
        cout<<"Median: "<<median<<endl;
    }
    return 0;
}

/*
Test cases :

    Input :

        2
        3 3
        1 3 4
        2 6 9
        3 6 9
        3 3
        1 3 4
        2 5 6
        7 8 9

    Output :

        Median: 4
        Median: 5



    Time complexity: O(r*log(c))
    Space Complexity: O(1)
*/


<|start_filename|>C/other/check_for_subsequence.c<|end_filename|>
#include <stdio.h>
#include <string.h>

int main()
{
    char str1[1000] , str2[1000];
    int i = 0 , j = 0;                    // i will point to string 1 and j will point to string 2 
    printf(" Enter first string :\n");
    scanf("%s" , str1);                   // str1 is substring
    printf(" Enter second string :\n");
    scanf("%s" , str2);                   //str2 is full string
    while (i < strlen(str1) && j < strlen(str2)) 
    {
		if (str1[i] == str2[j]) 
		{
			i++;
		}
		j++;
	}
	
	if (i == strlen(str1)) 
	{
		printf("Yes, str1 is substring of str2\n");
	}
	else 
	{
		printf("No, str1 is not a substring of str2\n");
	}
		
    return 0;
}

/*
Time Complexity: O(n)
Space Complexity: O(1)
Input:
DTH SDFDTHFGB
QBR EQVBA
Output:
Yes, str1 is substring of str2
No, str1 is not substring of str2
*/



<|start_filename|>C-Plus-Plus/math/Roman_To_Integer.cpp<|end_filename|>
/*
Introduction 
Given a roman numeral, convert it to an integer.

Argument/Return Type
Given a string which represents a roman numeral ,
return its corresponding decimal integer value
*/

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

//Function to convert the given roman numeral to its corresponding integer value
int romanToInt(string roman) 
{ 
    //Define a map     
    map<string,int>value;
    
    //Store the integer values of all valid roman symbols
    value["I"]  = 1;
    value["IV"] = 4;
    value["V"]  = 5;
    value["IX"] = 9;
    value["X"]  = 10;
    value["XL"] = 40;
    value["L"]  = 50;
    value["XC"] = 90;
    value["C"]  = 100;
    value["CD"] = 400;
    value["D"]  = 500;
    value["CM"] = 900;
    value["M"]  = 1000;
    
    //Now traverse over all characters of string
    int index=0;
    //Initiate the decimal value with 0
    int decimalValue=0;

    while(index<roman.length())
    {
        //If there is one more char after the current position
        if(index<roman.length()-1)
        {
            /* check if the substring corresponding to two chars 
            is a valid roman symbol */
            string sub=roman.substr(index,2);
            if(value[sub])
            {
                /* If substring is a valid roman symbol 
                 add it to decimal value and move the index forward two times */
                decimalValue=decimalValue+value[sub];
                index=index+2;
            }
            else
            {
                // else add the decimal value the char at this position 
                sub=roman.substr(index,1);
                decimalValue=decimalValue+value[sub];
                index=index+1;
            }
        }
        else
        {
            /* If current position is end of the string
             add the decimala value of this char and continue */
            string sub=roman.substr(index,1);
            decimalValue=decimalValue+value[sub];
            index=index+1;
        }
        
    }
    
    return decimalValue;
}


// Driver code
int main()
{
    //Take input of a roman numeral string
    string roman;
    cout<<"Enter a roman numeral : ";
    cin>>roman;

    //Call the function and print the result
    cout<<"Hence the integer value of given roman numeral is ";
    cout<<romanToInt(roman);

    return 0; 
}
    
/*
Input:
1 <= roman.length <= 15
roman contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
It is guaranteed that s is a valid roman numeral in the range [1, 3999].

Sample Test Case 1  

Input Format : 
Example :
Enter a roman numeral : MCMXCIV

Output Format :
Example : ( Output to the above input example ) 
Hence the integer value of given roman numeral is 1994

Time/Space Complexity
Time Complexity : O(n) 
Space Complexity : O(1) 
*/


<|start_filename|>Java/search/BinarySearchRecursive.java<|end_filename|>
/* Below code is an implementation of binary search in Java using
recursive method. An array is taken as input from the user, followed
by the element the user wants to search in the array. The search function
is called. If the element is present in the array, then print the index
of the element in the array.
NOTE : For binary search to work, the input array must be SORTED*/

import java.util.*;

public class BinarySearchRecursive {

	// This method recursively searches for element in array
	static int search(int array[], int left, int right, int element) {
		
		// If left pointer exceeds the right pointer
		if(left > right) {
			return -1;
		}
		
		else {
			// Find the middle index
			int middle = left + (right - left) / 2;
			// If element is found return index
			if(array[middle] == element) 
				return middle;
			/* If middle element is greater than the given element
			to search, then, recursively search in the left half of
			the array.*/
			else if(array[middle] > element) {
				return search(array, left, middle - 1, element);
			}
			/* If middle element is less than the given element to
			search, then, recursively search in the right half of
			the array.*/
			else if(array[middle] < element) {
				return search(array, middle + 1, right, element);
			}
		}
		// If not found, return -1
		return -1;
	}
	public static void main(String[] args) {
		
		Scanner scan = new Scanner(System.in);

		// Take length of array as input from the user
		System.out.print("Enter the length of array: ");
		int length = scan.nextInt();

		// Take elements of array as input from the user
		int[] array = new int[length];
		System.out.print("Enter " + length + " elements followed by spaces: ");
		for(int i = 0; i < length; i++) {
			array[i] = scan.nextInt();
		}

		// Take element to search as input from the user
		System.out.print("Enter the element you want to search: ");
		int element = scan.nextInt();

		// Call search function to find the index
		int index = search(array, 0, length - 1, element);
		
		// If index is -1, the element is not present
		if(index == -1) {
			System.out.println("\nThe element " + element + " is not present in the array.");
		}
		
		// Else print index of element in the array
		else {
			System.out.println("\nThe element " + element + " is present at " + index + " index in the array.");
		}
		scan.close();
	}
}

/* 
Sample I/O:

Enter the length of array: 6
Enter 6 elements followed by spaces: -2 -1 4 7 9 11
Enter the element you want to search: 11

The element 11 is present at 5 index in the array.

Here, O - Thetha
Time Complexity: O(logn)

Space Complexity: O(n)
*/



<|start_filename|>C/ds/stack_sort.c<|end_filename|>
/*
A stack is a linear data structure in which elements are added and removed only from
one end which is called the top. Hence, a stack is called a LIFO (Last-in-First-out) data structure.    
    In this program, the stack is sorted in ascending order without using another user defined stack.
Using the sort function, the elements of the stack are first popped out of the stack in a recursive manner.
Then, the insert function is called which pushes the elements back in the stack in ascending order. 
*/
#include <stdio.h>
#include <stdlib.h>

struct stack
{
	int *arr;
	int top;
	int size;
};

//push function of stack
void push(struct stack **s, int x)
{
	if ((((*s)->top)) == ((*s)->size) - 1)
		printf("STACK OVERFLOW\n");
	else
	{
		((*s)->top) += 1;
		(*s)->arr[(*s)->top] = x;
	}
}

//pop function of stack
int pop(struct stack **s)
{
	if ((*s)->top != -1)
	{
		int n = (*s)->arr[(*s)->top];
		((*s)->top) --;
		return n;
	}
}

//display function of stack
void display(struct stack **sta)
{
	struct stack *s = *sta;
	if (s->top == -1)
		return;
	else
	{
		int n = pop(&s);
		printf("%d ", n);
		display(&s);
		push(&s, n);
	}
}

//function used by sort function to push elements back in stack in ascending order
int insert(struct stack **sta, int x)
{
	struct stack *s = *sta;
	if (s->top == -1 || s->arr[s->top] > x)
	{
		push(&s, x);
		return 0;
	}

	int n = pop(&s);
	insert(&s, x);
	push(&s, n);
}

//function to sort the stack
void sort(struct stack **s)
{
	int n = pop(&(*s));
	if ((*s)->top != -1)
		sort(&(*s));
	insert(&(*s), n);
}

void main()
{
	struct stack *s = (struct stack *) malloc(sizeof(struct stack));
	printf("Enter the size of stack : ");
	scanf("%d", &s->size);
	s->arr = (int*) malloc((s->size) *(sizeof(int)));
	s->top = -1;
	int op;
	char c = 'Y';
	while (c == 'y' || c == 'Y') {
		printf("\nEnter an option:\n1.push()\t2.pop()\n3.display()\t4.sort()\n");
		printf("Enter your choice: ");
		scanf("%d", &op);
		switch (op)
		{
			case 1:
				{
					int x;
					printf("Enter the data: ");
					scanf("%d", &x);
					push(&s, x);
					break;
				}

			case 2:
				{
					int n = pop(&s);
					break;
				}

			case 3:
				{
					if (s->top == -1)
						printf("STACK UNDERFLOW\n");
					else
					{
						printf("The stack is: ");
						display(&s);
						printf("\n");
					}

					break;
				}

			case 4:
				{
					if (s->top == -1)
						printf("STACK UNDERFLOW\n");
					else
					{
						printf("The sorted stack is : ");
						sort(&s);
						display(&s);
						printf("\n");
					}

					break;
				}

			default:
				printf("Not an option\n");
		}

		printf("Do you want to continue : ");
		scanf(" %c", &c);
	} 
}

/*
Time Compexity:
Push function - O(1)
Pop function - O(1)
Display function - O(n)
Sort function - O(n)
Insert function - O(n)

Space Compexity: O(n)

Sample Output:

Enter the size of stack : 4

Enter an option:        
1.push()        2.pop() 
3.display()     4.sort()
Enter your choice: 1    
Enter the data: 5
Do you want to continue : y

Enter an option:        
1.push()        2.pop() 
3.display()     4.sort()
Enter your choice: 1    
Enter the data: 3
Do you want to continue : y

Enter an option:        
1.push()        2.pop()
3.display()     4.sort()
Enter your choice: 1
Enter the data: 8
Do you want to continue : y

Enter an option:
1.push()        2.pop()
3.display()     4.sort()
Enter your choice: 1
Enter the data: 2
Do you want to continue : y

Enter an option:
1.push()        2.pop()
3.display()     4.sort()
Enter your choice: 3
The stack is: 2 8 3 5
Do you want to continue : y

Enter an option:
1.push()        2.pop()
3.display()     4.sort()
Enter your choice: 4
The sorted stack is : 2 3 5 8
Do you want to continue : n
*/


<|start_filename|>Go/ds/binary_tree/inorder_traversal_binary_tree/inorder_traversal_binarytree.go<|end_filename|>
package main

import (
	"fmt"
	"os"
)

// Node defines the structure of a particular node in binary tree
type Node struct {
	data  int
	left  *Node
	right *Node
}

// NewNode creates a node and returns it's pointer
func NewNode(data int) *Node {
	return &Node{
		data: data,
	}
}

// CreateTree creates a new tree from level order array
func (root *Node) CreateTree(arr []int, pos, size int) *Node {
	var r *Node // nill by default
	if pos < size {

		r = NewNode(arr[pos])

		// fill left subtree
		r.left = r.CreateTree(arr, pos*2+1, size)

		// fill right subtree
		r.right = r.CreateTree(arr, pos*2+2, size)
	}
	return r
}

// InorderTraversal prints the Inorder traversal of tree
func (root *Node) InorderTraversal() {
	// Inorder Traversal : Left -> Root -> Right
	if root != nil {
		root.left.InorderTraversal()
		fmt.Printf("%v ", root.data)
		root.right.InorderTraversal()

	}
}

// Driver Code
func main() {
	// taking size of tree
	var size int
	fmt.Println("Enter size of the tree: ")
	_, err := fmt.Scanf("%d\n", &size)
	// exit on invalid size
	if err != nil {
		println("Invalid size")
		os.Exit(-1)
	}

	// allocating memory for array
	arr := make([]int, size)
	fmt.Println("Enter values in level order fashion: ")

	// Taking inpur
	for i := 0; i < size; i++ {
		_, err = fmt.Scanf("%d", &arr[i])

		if err != nil {
			println("Invalid argument")
			os.Exit(-1)
		}
	}

	// declaring root
	var root *Node

	// creating the tree
	root = root.CreateTree(arr, 0, size)

	// Calling InorderTraversal
	root.InorderTraversal()
}

/*
Sample input:
Enter size of the tree:
6
Enter values in level order fashion:
5 6 7 3 10 9

Example Input Tree

			  5
		    /   \
		  6      7
		 / \    /
		3  10  9

Output
3 6 10 5 9 7
*/


<|start_filename|>C-Plus-Plus/ds/vertical_order_traversal_BinaryTree.cpp<|end_filename|>
/*-----------------------VERTICAL ORDER TRAVERSAL---------------------------

In this we have to get the vertical order of the tree
-> The approach is to Level order traverse the Binary tree
-> keep a track of the horizontal distance and vertical distance of the nodes from the root which 
is at origin or say at (0,0)
-> All the nodes at same horizontal distance come in the same column of the vertical traversal

*CHECK*- In this there is also a possibility when we have more than two nodes at the same horizontal and
vertical distance then we have sorted the values in increasing order
 INPUT -> THE VALUES OF THE TREE
            (1)
           /   \
        (2)     (3)
       /  \    /   \
    (4)   (5) (6)   (7)
 
 OUTPUT -> 2-D VECTOR WHICH DISPLAYS THE VERTICAL ORDER
          [[4]
          [2]
          [1,5,6]
          [3]
          [7]]

*/

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

// ---------------THE BiNARY TREE NODE CLASS----------------------------
template <typename T>
class BinaryTreeNode
{
public:
    T data;
    BinaryTreeNode<T> *left;
    BinaryTreeNode<T> *right;

    BinaryTreeNode(T data)
    {
        this->data = data;
        this->left = NULL;
        this->right = NULL;
    }

    ~BinaryTreeNode()
    {
        delete left;
        delete right;
    }
};

// --------------------FUNCTION TO TAKE INPUT THE TREE--------------------------------

BinaryTreeNode<int> *TakeinputLevelWise()
{
    int data;
    cout << "enter the root data :" << endl;
    cin >> data;

    if (data == -1)
    {
        return NULL;
    }

    BinaryTreeNode<int> *root = new BinaryTreeNode<int>(data);
    queue<BinaryTreeNode<int> *> nodes;
    nodes.push(root);
    while (nodes.size() != 0)
    {
        BinaryTreeNode<int> *front = nodes.front();
        nodes.pop();
        int leftchild;
        int rightchild;
        cout << "Enter the left child of " << front->data << ":" << endl;
        cin >> leftchild;
        if (leftchild != -1)
        {
            BinaryTreeNode<int> *LChild = new BinaryTreeNode<int>(leftchild);
            front->left = LChild;
            nodes.push(LChild);
        }
        cout << " Enter the right Child of " << front->data << ":" << endl;
        cin >> rightchild;
        if (rightchild != -1)
        {
            BinaryTreeNode<int> *RChild = new BinaryTreeNode<int>(rightchild);
            front->right = RChild;
            nodes.push(RChild);
        }
    }

    return root;
}

// ----------------------FUNCTION TO PRINT THE TREE---------------------------------

void printLevelWise(BinaryTreeNode<int> *root)
{
    if (root == NULL)
        return;

    queue<BinaryTreeNode<int> *> nodes;
    nodes.push(root);
    while (nodes.size() != 0)
    {
        BinaryTreeNode<int> *front = nodes.front();
        cout << front->data << ":";
        nodes.pop();
        if (front->left)
        {
            nodes.push(front->left);
            cout << "L:" << front->left->data;
        }
        if (front->right)
        {
            nodes.push(front->right);
            cout << "R:" << front->right->data;
        }
        cout << endl;
    }
}

// ---------------COMPARE FUNCTION FOR THE SORT FUNCTION----------------------------

bool cmp(pair<int, int> l, pair<int, int> r)
{
    // check for the vertical distance first
    if (l.second < r.second)
        return true;
    else if (l.second > r.second)
        return false;
    //then if vertical distance is same than check for the node value
    else
        return (l.first <= r.first);
}

// -------------------THE FUNCTION------------------------------------

vector<vector<int>> verticalTraversal(BinaryTreeNode<int> *root)
{
    // map -> horizontal distance , (nodeValue, vertical distance)
    // map keeps track of all the nodes in the same horizontal distance with their vertical distance too
    map<int, vector<pair<int, int>>> mp;

    // queue -> Node, (horizontal Distance, vertical distance)
    // queue contains the node with its hd and vd ( it helps in the level order traversal)
    queue<pair<BinaryTreeNode<int> *, pair<int, int>>> q;
    //hd and vd of root is (0,0)
    int hd = 0;
    int vd = 0;
    // push the root
    q.push(make_pair(root, make_pair(hd, vd)));

    while (!q.empty())
    {
        // get the front node
        pair<BinaryTreeNode<int> *, pair<int, int>> temp = q.front();
        q.pop();

        // destructure the front node
        BinaryTreeNode<int> *node = temp.first;
        hd = temp.second.first;
        vd = temp.second.second;
        // push it into the map
        mp[hd].push_back(make_pair(node->data, vd));

        if (node->left)
        {
            q.push(make_pair(node->left, make_pair(hd - 1, vd + 1)));
        }
        if (node->right)
        {
            q.push(make_pair(node->right, make_pair(hd + 1, vd + 1)));
        }
    }

    // create the vector of size map
    vector<vector<int>> vertical(mp.size());

    int j = 0;
    // iterator for the map
    map<int, vector<pair<int, int>>>::iterator it;
    for (it = mp.begin(); it != mp.end(); it++)
    {
        sort(it->second.begin(), it->second.end(), cmp);
        for (int i = 0; i < it->second.size(); ++i)
            vertical[j].push_back(it->second[i].first);
        j++;
    }
    return vertical;
}

int main()
{
    BinaryTreeNode<int> *root = TakeinputLevelWise();
    printLevelWise(root);
    vector<vector<int>> ans = verticalTraversal(root);
    for (int i = 0; i < ans.size(); i++)
    {
        for (int j = 0; j < ans[i].size(); j++)
        {
            cout << ans[i][j] << " ";
        }
        cout << endl;
    }
}

/* COMPLEXITY ANALYSIS
   TIME-
   1. First we iterate over each and every node in the tree which takes O(n) time
   2. we insert the nodes in the map which takes O(logn) time
   3. Next we iterate over the map and add the nodes into the vector which also takes O(n) time
       total= O(nLogn) + O(n) => O(nLogn)
   
   SPACE-
   We have used map and queue which takes O(n) space in all

   Sample Input-
     1 2 3 4 5 6 7 -1 -1 8 9 -1 -1 -1 -1 -1 -1 -1 -1
   
   Sample Output
     4
     2 8
     1 5 6
     3 9
     7
*/


<|start_filename|>Go/math/Magic_Number/Magic_Number.go<|end_filename|>
/* This code checks if a number is a magic number.
Magic number - We find the recursive sum of digits
of number till a single digit. If the single digit 
is 1, then it is a magic number, else it is not.*/

package main

import (
	"fmt";
)

// This function finds sum of digits of a number
func sum_of_digits(n int) int {
	var sum int = 0
	for n != 0 {
		sum += n % 10
		n = n / 10
	}
	// Returning the sum
	return sum
}

// This function checks if number is a magic number
func check_magic_number(number int) int {
	var first int

	// Find the sum of digits of number
	first = sum_of_digits(number)

	/* Till we get a single digit, recursively
	call the sum function*/
	for first >= 10 {
		first = sum_of_digits(first)
	}

	// If the sum becomes 1, return 1 else -1
	if(first == 1) {
		return 1
	} else {
		return -1
	}
}

func main() {

	// Take number as input from the user
	var number int
	fmt.Print("Enter a number to check if it is a magic number: ")
	fmt.Scan(&number)

	// Call the magic number checker function
	var result int = check_magic_number(number)

	/* If returned value is 1, then the number is
	a magic number, else it is not*/
	if(result == 1) {
		fmt.Print("\nThe number ", number, " is a magic number.\n")
	} else {
		fmt.Print("\nThe number ", number, " is not a magic number.\n")
	}
}

/* Sample I/O:

Enter a number to check if it is a magic number: 1729

The number 1729 is a magic number.

*/



<|start_filename|>JavaScript/cp/SlidingWindowMaximum.js<|end_filename|>
/* Sliding Window Maximum is a famous problem where we are given a list of integers
 nums and an integer k, return the maximum values of each sublist of length k. */


/* Function to get the maximum element of each sliding window of size k */
const slidingWindowMaximum = (nums, k) => {

    /* Sliding window */
    let window = [];

    /* Generating the initial window */
    for(let i=0; i<k; i++){
        
        /* Pushing the index to the window if there are no elements */
        if(window.length == 0){
            window.push(i);
            continue;
        }

        /* Getting the last index of our sliding window */
        let index = window[window.length-1];

        /* Arranging the elements in the window in descending order by removing the smaller ones */
        while(nums[i] > nums[index] && window.length > 0){
            window.pop();
            if(window.length > 0)
            index = window[window.length-1];
        }

        /* Pushing the current element to the window */
        window.push(i);
    }

    /* Answer array */
    let array = [];

    /* Storing the first maximum element in the array */
    array[0] = nums[window[0]];

    /* Generating k-1 windows */
    for(let i=k; i<nums.length; i++){

        let index = window[0];

        /* Removing indices which are out of bound */
        while(index <= i-k && window.length > 0){
            window.shift();
            if(window.length > 0)
            index = window[0];
        }

        if(window.length > 0)
        index = window[window.length-1];

        /* Arranging the elements in the window in ascending order by removing the ones which are smaller */
        while(nums[i] > nums[index] && window.length > 0){
            window.pop();
            if(window.length > 0)
            index = window[window.length-1];
        }

        window.push(i);

        /* Pushing the new maximum to the array */
        array[i-k+1] = nums[window[0]];
    }

    /* Returning the answer */
    return array;
}

//Using the readline() function of JavaScript to take input from the user
console.log("Enter the elements of of the array along with the size of the window");

//list is input array
let list = readline()
    .split(" ")
    .map((x) => parseInt(x));

// First n elements represent the elements in the array
let n = list.length-1;

// Last element of the list represents the size of the window k
let k = list[n];

/* Using list slicing and passing the first n elements to the
 function as the first parameter and k as the second parameter */
console.log("Array of maximum element in every window of size ", k, " is" ,slidingWindowMaximum(list.slice(0, n), k));

/* 
Example 1:

Input:

3 2 1 2 3 2

Output:

Array of maximum element in every window of size 2 is [3, 2, 2, 3]

Time Complexity : O(N)
Space Complexity : O(K)
*/



<|start_filename|>C-Sharp/search/BinarySearch.cs<|end_filename|>
﻿public class BinarySearch
{
    // This search method work only on sorted array 
    static int Search(int[] array, int element)
    {
        int left = 0;
        int right = array.Length - 1;

        while (left <= right)
        {
            int middle = left + (right - left) / 2;

            if (array[middle] == element)
            {
                return middle;
            }

            // If element greater than the middle element we search on the right half 
            if (array[middle] < element)
            {
                left = middle + 1;
            }
            else
            {
                right = middle - 1;
            }
        }

        // element not found 
        return -1;
    }
}



<|start_filename|>C-Plus-Plus/cp/matrix_min_operations_for_equal_sum.cpp<|end_filename|>
/*
Problem: The input is n x n square matrix. The output is minimum number of operations required to convert input
matrix into the matrix in which sum of elements of each row & column is equal. One operation means incrementing any value of 
cell of matrix by 1. Also, the converted matrix is displayed on screen.
For Ex: I/P = 2
1 2
3 4

O/P : 4
4 3
3 4
In above example, input matrix is converted so that sum of each row and column of output matrix is 7. The minimum number of
operations required to do so are 4.

Solution: In find_min_steps function, first the sum of individual row and column is stored in 2 arrays, one for
storing sum of rows & other for sum of columns. The maximum of both the arrays is calculated(i.e maximum of sum of cells 
in individual rows & columns.) By iterating over the matrix and performing addition wherever required the sum of all 
individual rows & columns is made equal to maximum sum.
*/

#include<iostream>
using namespace std ;

//Function that converts matrix into matrix which contains equal row and column sum & returns number of operations required to do so.
int find_min_steps(int fn , int **finput_matrix)
{
    int *rowSum = NULL, *columnSum = NULL ;
    int i = 0, j = 0, maxSum = 0, operations = 0, diff = 0 ;

    /*
    Assigning memory to 2 sum arrays. rowSum stores the sum of cells of individual rows & columnSum stores the sum
    of cells of individual columns.
    */
    rowSum = new int[fn] ;
    columnSum = new int[fn] ;

    //Calculating sum of cells of each row and column and storing it in array rowSum & columnSum respectively.
    for(i=0 ; i<fn ; ++i)
    {
        for(j=0 ; j<fn ; ++j)
        {
            rowSum[i] = rowSum[i] + finput_matrix[i][j] ;
            columnSum[j] = columnSum[j] + finput_matrix[i][j] ;
        }
    }

    //Finding the maximum sum(i.e array element) among 2 arrays rowSum & columnSum.
    for(i=0 ; i<fn ; ++i)
    {
        maxSum = max(maxSum , columnSum[i]) ;
        maxSum = max(maxSum , rowSum[i]) ;
    }

    //i is counter for rows and j is counter for columns
    for(i=0, j=0 ; i<fn && j<fn ;)
    {
        /*
        We calculate the difference between maximum sum and sum of elements of ith row and jth column respectively.This
        minimum difference is added to the element [i][j]. Minimum among the both differences is considered so as to avoid
        increasing any row or column sum beyond the maximum sum.
        As the value of [i][j] th element is increased by diff, this diff has to be added in sum arrays rowSum[i] & columnSum[j].
        According to the problem statement, one operation means addition by one, hence the difference has to be added in number of
        operations as well.
        */
        diff = min(maxSum - rowSum[i] , maxSum - columnSum[j]) ;
        finput_matrix[i][j] = finput_matrix[i][j] + diff ;
        rowSum[i] = rowSum[i] + diff ;
        columnSum[j] = columnSum[j] + diff ;
        operations = operations + diff ;

        //If sum of elements in i th row becomes equal to maximum sum, we move on to the next row.Hence i is incremented.
        if(rowSum[i] == maxSum)
        {
            i = i + 1 ;
        }
        //If sum of elements in j th column becomes equal to maximum sum, we move on to the next column. Hence j is incremented
        if(columnSum[j] == maxSum)
        {
            j = j + 1 ;
        }
    }

    //Deallocate memory assigned to rowSum & columnSum array.
    delete[] rowSum ;
    delete[] columnSum ;

    return operations ;
}

int main(void)
{
    int **input_matrix = NULL ;
    int n = 0, i = 0, j = 0, min_operations  = 0 ;

    //Taking the input as number of rows and columns
    cout << "Enter the size of square matrix : " << endl ;
    cin >> n ;

    //Assigning the memory to the 2-D array according to given matrix size.
    input_matrix = new int*[n] ;
    for(i=0 ; i<n ; ++i)
    {
        input_matrix[i] = new int[n] ;
    }

    cout << "Enter the elements of matrix in row wise manner separated by space : " << endl ;
    //Taking user input as each element of matrix.
    for(i=0 ; i<n ; ++i)
    {
        for(j=0 ; j<n ; ++j)
        {
            cin >> input_matrix[i][j] ;
        }
    }

    //Calling the function find_min_steps
    min_operations = find_min_steps(n , input_matrix);

    //Display the number of operation and converted matrix on the screen.
    cout <<"The number of operations required = "<<min_operations<< endl;
    cout << endl << "The converted matrix with equal row & column sum:  " << endl ;
    for(i=0 ; i<n ; ++i)
    {
        for(j=0 ; j<n ; ++j)
        {
            cout << input_matrix[i][j] << "  " ;
        }
        cout << endl ;
    }

    //Deallocate the memory assigned to the input matrix.
    for(i=0 ; i<n ; ++i)
    {
        delete[] input_matrix[i] ;
    }
    delete[] input_matrix ;

    return 0 ;
}

/*
Sample I/O :
I/O:
3
1 2 3 4 5 6 7 8 9

O/P:
27
13 8  3
4  8  12
7  8  9

Explanation: Here, matrix size is 3 i.e 3x3 matrix.n next line each element of matrix is entered in row wise manner
separated by space. So input matrix is :   1 2 3
                                           4 5 6
                                           7 8 9
Maximum sum in this matrix is of last row i.e 7+8+9 = 24. So sum of each row and column is made equal to 24 by
performing addition. The minimum number of operations needed to convert input matrix is 27.


Time Complexity: O(n^2)
 Space Complexity: O(n)
*/



<|start_filename|>C-Plus-Plus/sort/radix_sort.cpp<|end_filename|>
/** 
-> Radix sort is based on counting sort
-> The following program sorts negative as well as 
positive integers.
-> Assuming the range is fixed, as ll capacity
is limited in any language, this sort takes
-> MAX_INT contains 10 decimal values
-> If range is not fixed, this sort takes O(kn) time
where k is #decimal places in the number
This works because of the nature of counting sort
-> Counting sort is a stable sort
**/

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

#define ll long long
#define K 10
#define M 10
#define DIF 2147483648

/* The idea behind sorting negative numbers too is below
-> A signed 32 bit integer goes from -2,147,483,648 to 2,147,483,647
and an unsigned integer from 0 to 4,294,967,295.
-> So you could just add 2,147,483,648 to the signed number to 
convert it to an unsigned one for sorting
then subtract to get back to signed numbers when you have finished sorting*/

void counting_sort(ll arr[], ll  n, ll p) {
    ll element = pow(10, p);
    ll divs = element / 10;
    ll count[M];
    for(ll i = 0; i < M; i++)
        count[i] = 0;
    for(ll i = 0; i < n; i++)
        count[(arr[i] % element) / divs] ++;
    for(ll i = 1; i < M; i++)
        count[i] += count[i-1];
    ll op[n];
    for(ll i = n-1; i >= 0; i--) {
        op[count[(arr[i] % element) / divs] - 1] = arr[i];
        count[(arr[i] % element) / divs] --;
    }
    // copying the array back
    for(ll i = 0; i < n; i++)
        arr[i] = op[i];
}

void radix_sort(ll arr[], ll n) {
    // apply counting sort for all decimal places
    for(ll i = 1; i <= K; i++)
        counting_sort(arr, n, i);
}

int main() {    
    ll n;
    cin >> n;
    ll arr[n];
    // Taking input
    for(ll i = 0; i < n; i++) {
        cin >> arr[i];
        // Adding DIF to make negative numbers positive
        arr[i]+=DIF;
    }
    // perform the sort
    radix_sort(arr, n);

    // Outputting the sorted array
    for(ll i = 0; i < n; i++) {
        cout << arr[i]-DIF << ' ';
    }
    cout << '\n';
    return 0;
}

/**
Sample Input 1: 
8
175 45 75 90 802 24 2 66
Sample Output 1:
2 24 45 66 75 90 175 802

Sample Input 2: 
8
175 -45 -75 90 -802 24 1 66
Sample Output 2:
-802 -75 -45 1 24 66 90 175

Time complexity : O(n)
Space complexity : O(n)
**/


<|start_filename|>C/math/Extended_Euclidean_Algorithm.c<|end_filename|>
/* Extended Euclidean Algorithm

  GCD of two numbers is the largest number that divides both of them.
  A simple way to find GCD is to factorize both numbers and multiply
  common factors.
 
     GCD(a,b) = ax + by
     
  If we can find the value of  x and y then we can easily find the
  value of GCD(a,b) by replacing (x,y) with their respective values.
*/

#include <stdio.h>

int extendedGCD(int a, int b, int *x, int *y)
{
    //base case
    if (a == 0)
    {
        *x = 0;
        *y = 0;
        return b;
    }
   
    int x1, y1;
   
    //recursive call
    int ans = extendedGCD(b % a, a, &x1, &y1);
   
    //Update x and y using results of recursive call
    *x = y1 - (b/a) * x1;
    *y = x1;
   
    return ans;
}

//Driver Code
int main()
{
    int x, y, a, b;
    printf("Enter the values of a and b : ");
    scanf("%d %d", &a, &b);
    int gextnd = extendedGCD(a, b, &x, &y);
    printf("\nGCD using Extended Euclidean algorithm is: %d ", gextnd);
    return 0;
}

/*
Time Complexity : O(log(max(A, B)))

Sample I/O :

Input :
Enter the values of a and b : 55 10                                                                                          
 
Output :
GCD using Extended Euclidean algorithm is: 5
*/


<|start_filename|>Java/dp/JobSequencingToMaximizeProfit.java<|end_filename|>
/* Problem Description

You are given a two-dimensional list of integers intervals where each list 
contains three values [start, end, profit]. Given you can only perform one
task at a time, return the maximum profit you can gain. */


import java.util.*;

public class JobSequencingToMaximizeProfit
{

    /* Creating a Job Class which stores the start time, end time and profit for that particular job */
    static class Job{
        int start;
        int end;
        int profit;
        Job(int start, int end, int profit){
            this.start = start;
            this.end = end;
            this.profit = profit;
        }
    }
    
    /* Defining a Comparator which sorts the Jobs based on end time in ascending order */
    static class SortByEndTime implements Comparator<Job>{
        
        public int compare(Job A, Job B){
            return A.end - B.end;
        }
    }

    /* Function created to get maximum profit in the intervals provided */
    public static int getMaxProfit(int[][] intervals) {

        /* Creating an Jobs array to easily sort the jobs */
        ArrayList<Job> array = new ArrayList<>();
        int n = intervals.length;

        /* Adding the jobs to the jobs array */
        for(int i=0; i<n; i++){
            int start = intervals[i][0];
            int end = intervals[i][1];
            int profit = intervals[i][2];
            array.add(new Job(start, end, profit));
        }
        
        /* Sorting the jobs based on End time */
        Collections.sort(array, new SortByEndTime());
        
        /* Initializing a dp array to store the max profit for i particular jobs i.e 
         It stores the maximum profit gained when only i jobs are present */
        int dp[] = new int[n];

        /* When we are including only one job, we can have a maximum profit of that particular job */
        dp[0] = array.get(0).profit;

        /* Filling the dp array */
        for(int i=1; i<n; i++){

            Job curr = array.get(i);

            /* Getting the current Jobs Profit */
            int ans = curr.profit;

            /* Getting the index of the first non-conflicting job */
            int index = lowerBound(array, curr.start, 0, i-1);

            /* Max profit we get by including the current job */
            if(index != -1){
                ans += dp[index];
            }

            /* Storing the max profit we get by either including the current job or excluding it */
            dp[i] = Math.max(dp[i-1], ans);
        }

        /* Returning the max Profit when we have "n" jobs */
        return dp[n-1];
        
    }

    /* Getting the index of the first non conflicting job using Binary Search */
    public static int lowerBound(ArrayList<Job> array, int start, int low, int high){


        int l = low;
        int h = high;
        int ans = -1;

        /* Iterative Binary Search */
        while(l <= h){
            int mid = (l+h)/2;
            Job j = array.get(mid);

            /* Going to the right if we found a non-conflicting job */
            if(j.end <= start){
                ans = mid;
                l=mid+1;
            }
            /* Going to the left if we found a conflicting job */
            else{
                h=mid-1;
            }
        }

        /* Returning the index */
        return ans;
    }

    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);

        int jobs = sc.nextInt();

        int intervals[][] = new int[jobs][3];

        for(int i=0; i<jobs; i++){
            int start = sc.nextInt();
            int end = sc.nextInt();
            int profit = sc.nextInt();

            intervals[i][0] = start;
            intervals[i][1] = end;
            intervals[i][2] = profit;
        }

        System.out.println(getMaxProfit(intervals));
    }  
}


/* Input

intervals = [
    [1, 2, 50],
    [3, 5, 20],
    [6, 19, 100],
    [2, 100, 200]
]

Output
250

Explanation
We can take intervals [1, 2, 50] and [2, 100, 200] thereby maximizing our profit, which is coming out to be 250


Time Complexity : O(N)
Space Complexity : O(N)
*/



<|start_filename|>C-Plus-Plus/dp/Egg_Dropping.cpp<|end_filename|>
//Egg Dropping problem
/*
The Egg Dropping Problem: There is a building with k floors. You are given n eggs.

An egg dropping from any floor is termed a “trial”. After a dropping, an egg can either survive or
break. A broken egg cannot be used whereas a survived egg can be used for another trial. All eggs are
identical, i.e. effect must be same for all eggs.

A floor is called the critical floor if an egg breaks from that floor and above but does not break from
any floor below that one. We assume that if an egg survives a fall, it survives a shorter fall. And if an
egg breaks from some floor, then it would break from higher floor also.

Given n and k, you have to find the minimum number of trials in the worst case.
*/

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

int egg,flr;
int **table= NULL;
int min_probes=0;

void input()
{
	cin>>egg;
	cin>>flr;
	table=new int*[flr+1];		//Initializing memory for DP Table
	for(int i = 0; i <= egg; ++i)
      table[i] = new int[flr+1];
  
}
int find_min_probes(int e,int f)
{   

	if(e==1)
		return f;

    if(f==0||f==1)
		return  f;
    
    int probes=INT_MAX;
    for(int k=1;k<=f;k++)
    {
		int temp=1+max(find_min_probes(e-1,k-1),find_min_probes(e,f-k));
        probes=min(probes,temp);
    }
   	return probes;
}

void display()
{
	cout<<"*************** Egg Droping Problem *****************"<<endl;
	cout<<endl<<"Number of eggs are: "<<egg;
	cout<<endl<<"Number of floors are: "<<flr<<endl;
	cout<<"\nMinimum number of trials in worst case with "<<egg<<" eggs and "<<flr<<" flrs are: "<<min_probes<<endl<<endl;
}

int main() 
{ 
    input(); 
    min_probes = find_min_probes(egg,flr);
	display();
	return 0;
} 

/*
Input:
2
10

Output:
*************** Egg Droping Problem *****************

Number of eggs are: 2
Number of floors are: 10

Minimum number of trials in worst case with 2 eggs and 10 flrs are: 4
*/

<|start_filename|>C-Plus-Plus/math/catalan_num.cpp<|end_filename|>
/*
Catalan numbers is a number sequence, which is found useful in a number of
combinatorial problems, often involving recursively-defined objects.
*/

#include <iostream>
using namespace std;

// To find nth catalan number using recursive function
unsigned long int catalan(unsigned int n)
{

  if (n <= 1)
    return 1;
  unsigned long int res = 0;
  for (int i = 0; i < n; i++)
    res = res + catalan(i) * catalan(n - i - 1);

  return res;
}

int main()
{
  cout << "Enter the Number:" << endl;
  int n;
  cin >> n;
  for (int i = 0; i < n; i++)
  {
    cout << catalan(i) << " ";
  }
  cout << endl;
  return 0;
}

/*
Input:
Enter the Number:
15
Ouput:
1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440

Time Complexity: O(2^n)
Space Complexity: O(1)
*/

<|start_filename|>Java/cryptography/HillCipher.java<|end_filename|>
/* This code is an implementation of Hill Cipher in Java.
   It is a polygraphic substitution cipher. It forms a nxn
   matrix of key and nx1 matrix(s) of the plaintext and then
   multiplies the two matrices to obtains the matrix of ciphertext.*/

import java.util.*;
import java.lang.*;

public class HillCipher {

	// This global variable defines the size of n
	public static int size = 3;

	/* This method forms the nxn matrix of keyword. The value of
	   n can be changed by setting the global vaiable size.*/
	static void generateKeyMatrix(String key, int[][] keymatrix) {

		int count = 0;
		for(int i = 0; i < size; i++) {
			for(int j = 0; j < size; j++) {
				// Stores decimal value of ASCII
				keymatrix[i][j] = key.charAt(count);
				/* Here, a = 97, b = 98 and so on.
			   	We want a = 0, b = 1 and so on. So,
				we subtract 97.*/
				keymatrix[i][j] -= 97;
				count = count + 1;
			}
		}
	}

	/* This method forms the nx1 matrix of the plaintext. The value of n can be
	   changed by setting the global variable size.*/
	static void generatePlaintextMatrix(String plaintext, int[][] plaintextmatrix) {

		int count = 0;
		for(int i = 0; i < size; i++) {
			for(int j = 0; j < 1; j++) {
				// Stores decimal value of ASCII
				plaintextmatrix[i][j] = plaintext.charAt(count);
				/* As we did above, we subtract 97 from the
				decimal value to start indexing from 0.*/
				plaintextmatrix[i][j] -= 97;
				count = count + 1;
			}
		}
	}

	/* This function forms the nx1 ciphertext matrix. The matrix of decimal is then converted
	to ascii value and combined and then returned.*/
	static String generateCiphertextMatrix(String plaintext, String key, int[][] ciphertextmatrix) {

		// Forming the keyword matrix
		int[][] keymatrix = new int[size][size];
		// Calling the keyord matrix function
		generateKeyMatrix(key, keymatrix);

		// Forming the plaintext matrix
		int[][] plaintextmatrix = new int[size][1];
		// Calling the plaintext matrix function
		generatePlaintextMatrix(plaintext, plaintextmatrix);

		/* Initializing the ciphertext matrix values to
		zero. Otherwise, it would store garbage values.*/
		for(int i = 0; i < size; i++) {
			for(int j = 0; j < 1; j++) {
				ciphertextmatrix[i][j] = 0;
			}
		}

		/* Multiplying key matrix with plaintext matrix
		and forming the ciphertext matrix. */
		for(int i = 0; i < size; i++) {
			for(int j = 0; j < 1; j++) {
				for(int k = 0; k < size; k++) {
					ciphertextmatrix[i][j] += keymatrix[i][k] * plaintextmatrix[k][j];
				}
			}
		}

		/* Taking mod 26 of obtained ciphertext values to
		ensure they lie within the range [0-25].*/
		for(int i = 0; i < size; i++) {
			for(int j = 0; j < 1; j++) {
				ciphertextmatrix[i][j] = ciphertextmatrix[i][j] % 26;
			}
		}

		// Decalaring the ciphertext string
		String cipher = new String("");

		/* Since, we decremented 97 from the decimal values
		of plaintext and key, we add back 97 to the ciphertext
		values, in order to get proper ASCII.*/
		for(int i = 0; i < size; i++) {
			for(int j = 0; j < 1; j++) {
				cipher += (char) (ciphertextmatrix[i][j] + 97);
			}
		}

		// Return the encrypted plaintext
		return cipher;
	}

	public static void main(String[] args) {

		Scanner scan = new Scanner(System.in);
		
		System.out.println("\n-----------------HILL CIPHER-----------------\n");
		System.out.println("The length of plaintext must be same as size\n");
		System.out.println("Current value of size is " + size + "\n");

		// Taking plaintext as input from the user
		System.out.print("Enter a plaintext of size " + size + ": ");
		String plaintext = scan.nextLine();

		// Checking if proper message is provided or not.
		if(plaintext.length() != size) {
			System.out.println("Enter a valid message.");
			System.exit(0);
		}
		
		// Taking key as input from the user
		System.out.print("Enter a keyword of size " + size*size + ": ");
		String key = scan.nextLine();

		// Checking if proper key is provided or not.
		if(key.length() != size*size) {
			System.out.println("Enter a valid key.");
			System.exit(0);
		}

		scan.close();

		int[][] ciphertextmatrix = new int[size][1];

		String ciphertext = new String("");

		// Calling the method to get the encrypted plaintext
		ciphertext = generateCiphertextMatrix(plaintext, key, ciphertextmatrix);

		System.out.println("The encrypted plaintext is: " + ciphertext);
	}
}

/* Sample I/O:
	
-----------------HILL CIPHER-----------------

The length of plaintext must be same as size

Current value of size is 3

Enter a plaintext of size 3: pie
Enter a keyword of size 9: chocolate    
The encrypted plaintext is: mem
*/



<|start_filename|>C-Plus-Plus/dp/floyd_warshall.cpp<|end_filename|>
#include<bits/stdc++.h>
using namespace std;
void floyd_warshall(int arr[][5]) {
	int i, j, k;
	//Add all vertex one by one
	for (k = 0; k < 5; k++) {
		//pick all as a source
		for (i = 0; i < 5; i++) {
			//pick all as a destination
			for (j = 0; j < 5; j++) {
				if ((arr[i][k] * arr[k][j] != 0) && (i != j)) {
					//If vertex k is on the shortest path from
					// i to j, then update the value of arr[i][j]
					if ((arr[i][k] + arr[k][j] < arr[i][j]) || (arr[i][j] == 0)) {
						arr[i][j] = arr[i][k] + arr[k][j];
					}
				}
			}
		}
	}
	//function to print solution
	cout << "\nOUTPUT" << endl;
	for (i = 0; i < 5; i++) {
		cout << "\nMinimum Cost for Node: " << i << endl;
		for (j = 0; j < 5; j++) {
			cout << arr[i][j] << "\t";
		}
	}
}
//Main function began
int main() {
	int a[5][5];
	//Enter values
	cout << "Enter values for matrix-\n\n";
	for (int i = 0; i < 5; i++) {
		cout << "Enter values for " << (i + 1) << " row :" << endl;
		for (int j = 0; j < 5; j++) {
			cin >> a[i][j];
		}
	}
	// call the floyd function
	floyd_waeshall(a);
}
//main function ends

/*
Sample Input Output:
Enter values for matrix-

Enter values for 1 row :
0
3
6
0
0
Enter values for 2 row :
3
0
2
4
0
Enter values for 3 row :
6
2
0
1
4
Enter values for 4 row :
0
4
1
0
2
Enter values for 5 row :
0
0
4
2
0

OUTPUT:
Minimum Cost for Node: 0
0	3	5	6	8
Minimum Cost for Node: 1
3	0	2	3	5
Minimum Cost for Node: 2
5	2	0	1	3
Minimum Cost for Node: 3
6	3	1	0	2
Minimum Cost for Node: 4
8	5	3	2	0

Time Complexity :O(N^3)
*/


<|start_filename|>Java/Greedy_Algorithms/Active_Selection.java<|end_filename|>
//Given N activities with their start and finish times. Select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a time.
//
//        Note : The start time and end time of two activities may coincide.
//
//        Input:
//        The first line contains T denoting the number of testcases. Then follows description of testcases. First line is N number of activities then second line contains N numbers which are starting time of activies.Third line contains N finishing time of activities.
//
//        Output:
//        For each test case, output a single number denoting maximum activites which can be performed in new line.
//
//        Constraints:
//        1<=T<=50
//        1<=N<=1000
//        1<=A[i]<=100
//
//        Example:
//        Input:
//        2
//        6
//        1 3 2 5 8 5
//        2 4 6 7 9 9
//        4
//        1 3 2 5
//        2 4 3 6
//
//        Output:
//        4
//        4
//
//        Explanation:
//        Test Case 1: The following activities can be performed (in the same order):
//        (1, 2)
//        (3, 4)
//        (5, 7)
//        (8, 9)



import java.util. * ;
import java.lang. * ;
import java.io. * ;

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

    Scanner s = new Scanner(System. in );
    int t = s.nextInt();
    while (t-->0) {
      int n = s.nextInt();
      int[] start = new int[n];
      int[] finish = new int[n];

      for (int i = 0; i < n; i++) {
        start[i] = s.nextInt();

      }
      for (int i = 0; i < n; i++) {
        finish[i] = s.nextInt();

      }
      for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - 1; j++) {
          if (finish[j] > finish[j + 1]) {
            int temp = finish[j];
            finish[j] = finish[j + 1];
            finish[j + 1] = temp;

            int te = start[j];
            start[j] = start[j + 1];
            start[j + 1] = te;
          }

        }

      }

      int i = 0;
      int c = 1;
      for (int j = 1; j < n; j++) {
        if (finish[i] <= start[j]) {
          c++;
          i = j;
        }

      }
      System.out.println(c);

    }

  }
}



<|start_filename|>JavaScript/math/Fibonacci.js<|end_filename|>
/*

In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence, called the Fibonacci sequence,
such that each number is the sum of the two preceding ones, starting from 0 and 1

Fibonacci Series - 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ....
Below is the program for implementing fibonacci series in 3 different ways 

*/

// Prompt node package for taking user input
const prompt = require("prompt-sync")({ sigint: true });

// Number of steps required to complete fora given fibonacci function
let iterativeCount = 0; // iterative function count
let recursiveCount = 0; // recursive function count
let memoizedCount = 0; // memoized function count

// Iterative function ( Looping )
function fibonacciIterative(n) {
  let array = [0, 1];

  for (let i = 2; i < n + 1; i++) {
    iterativeCount++;
    array.push(array[i - 2] + array[i - 1]);
  }

  return array[n];
}

// Recursive function
function fibonacciRecursive(n) {
  recursiveCount++;
  if (n < 2) {
    return n;
  }

  return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2);
}

// Memoization ( a technique which attempts to increase function's performance by caching its previously computed results)
function fibonacciMemoized() {
  let cache = {}; // store previously computed results

  return function fib(n) {
    memoizedCount++;
    if (n in cache) {
      return cache[n];
    } else {
      if (n < 2) {
        return n;
      } else {
        cache[n] = fib(n - 1) + fib(n - 2);
        return cache[n];
      }
    }
  };
}

/* Workflow of user input */

// Take the fibonacci number as input
let fibKey = +prompt("Enter number to find fibonacci series value - ");

// Check whether the entered value is number or not
if (isNaN(fibKey)) return console.log("Only numbers are allowed");

// Iterative Result
let result = fibonacciIterative(fibKey);
console.log(
  `Fibonacci Iterative result in ${iterativeCount} steps - ${result}`
);

// Memoization Result
let fasterFib = fibonacciMemoized(fibKey);
result = fasterFib(fibKey);
console.log(`Fibonacci Memoized result in ${memoizedCount} steps - ${result}`);

// Recursive Result
result = fibonacciRecursive(fibKey);
console.log(
  `Fibonacci Recursive result in ${recursiveCount} steps - ${result}`
);

// Sample I/O

/*

> node Fibonacci

Enter number to find fibonacci series value - 25
Fibonacci Iterative result in 24 steps - 75025
Fibonacci Memoized result in 49 steps - 75025
Fibonacci Recursive result in 242785 steps - 75025

*/



<|start_filename|>Java/other/InfixToPostfix.java<|end_filename|>
/**
 * Infix to Postfix Expression
 *
 * This program converts an infix expression entered by the user
 * into the Postfix expression.
 * The program uses a stack to keep the track of the operators and
 * paranthesis of the input expression.
 *
 * Author: iamvs-2002
 */

import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
import java.util.Stack;

public class InfixToPostfix 
{
    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Kindly enter the infix expression: ");
        String infix = sc.nextLine();

        InfixToPostfix x = new InfixToPostfix();
        String postfix = x.infixtopostfix(infix);

        System.out.println("Postfix Expression: "+postfix);
    }

    static int priority(char c)
    {
        switch (c)
        {
            case '+':
                return 1;
            case '-':
                return 1;
            case '*':
                return 2;
            case '/':
                return 2;
            case '^':
                return 3;
            default:
                return -1;
        }
    }

    private String infixtopostfix(String expression)
    {
        String result = "";

        Stack<Character> stack = new Stack<>();

        int i=0;
        for (i = 0; i < expression.length() ; i++) 
        {
            char c = expression.charAt(i);
            if(priority(c)>0)
            {
                //if the topmost operator in the stack has a priority greater than or equal to c
                //pop it and add to result string
                //else push it into the stack
                while(stack.isEmpty()==false && (priority(stack.peek())>=priority(c)))
                {
                    result = result + stack.pop();
                }
                stack.push(c);
            }
            else if(c==')')
            {
                //if character is ending bracket ')'
                //pop from stack, until '(' is found
                while(stack.peek()!='(')
                {
                    result = result + stack.peek();
                    stack.pop();
                }
                char x = stack.pop();
            }
            else if(c=='(')
            {
                stack.push(c);
            }
            else
            {
                result = result + c;
            }
        }

        while (!stack.isEmpty())  
			result = result + stack.pop();

        return result;
    }
}
/**
 * Sample Outputs:
 * 
 * Kindly enter the infix expression:
 * (X - Y / (Z + U) * V)
 * Postfix Expression: X  Y  Z  U+ / V*-
 *
 * Kindly enter the infix expression:
 * ab+
 * Postfix Expression: ab  +
 *
 * Time Complexity: O(n^2)
 * Space Complexity: O(n)
 */


<|start_filename|>C/ds/FindLinkedListPalindrome.c<|end_filename|>
/* C program to find whether a linked list is palindrome or not.
We need to detect whether the front half of the list is the reverse of the second half.
By reversing the front half of the list and for that stack can be used.

We know the size of the linked list, we can iterate onto the first half of the elements in a for loop,
pushing each element onto a stack. Now, we iterate the rest of the linked list. At each step, we compare
the node to the top of the stack. If we complete the iteration without finding the difference, 
then the linked list is a palindrome.

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

// structure of a node in a linked list
struct Node {
  int value;
  struct Node *next;
};

struct Node *head = NULL;

// Dynamically generate the node
struct Node *gen_node(int val) {
  struct Node *newnode;
  newnode = (struct Node *)malloc(sizeof(struct Node));
  if (newnode == NULL) {
    printf("\nMemory was not allocated");
    return 0;
  } else {
    newnode->value = val;
    newnode->next = NULL;
    return newnode;
  }
}

// Insert node at the beginning of the linked list
void insert_node_first() {
  int val;
  struct Node *newNode, *temp;
  printf("\nEnter the value for the node:");
  scanf("%d", &val);
  newNode = gen_node(val);
  if (head == NULL) {
    head = newNode;
    head->next = NULL;
  } else {
    temp = head;
    head = newNode;
    head->next = temp;
  }
}

// Find palindrome in the linked list
int find_Palindrome(int size) {
  int arr[size / 2], i = 0, j = 0;
  struct Node *fast = head;
  struct Node *slow = head;
  /* Push elements from first half of the linked list onto array.
  When fast pointer (which is moving at 2x speed)reaches the end of the linked
  list, then we know we are at the middle
  */
  while (fast != NULL && fast->next != NULL) {
    arr[i] = slow->value;
    slow = slow->next;
    fast = fast->next->next;
    i++;
  }

  // Has odd number of elements,so skip the middle elements
  if (fast != NULL) {
    slow = slow->next;
  }
  j = i - 1;
  while (slow != NULL) {
    int val = arr[j];

    // If the value are different ,then it's not a palindrome
    if (val != slow->value) {
      return 0;
    }
    slow = slow->next;
    j--;
  }
  return 1;
}

// Display the entered list
void display() {
  struct Node *temp;
  temp = head;
  while (temp != NULL) {
    printf("%d ", temp->value);
    temp = temp->next;
  }
}

int main() {
  int size, i, val, status;
  printf("Enter the size of the Linked List:");
  scanf("%d", &size);

  for (i = 0; i < size; i++) {
    insert_node_first();
  }

  printf("\nLinked List after Insertion:");
  display();

  status = find_Palindrome(size);

  if (status) {
    printf("\nThe above Linked List is Palindrome");
  } else {
    printf("\nThe above Linked List is Not Palindrome");
  }

  return 0;
}

/*
Sample input/output:

Enter the size of the Linked List:7

Enter the value for the node:1

Enter the value for the node:2

Enter the value for the node:3

Enter the value for the node:4

Enter the value for the node:3

Enter the value for the node:2

Enter the value for the node:1

Linked List after Insertion:1 2 3 4 3 2 1
The above Linked List is Palindrome

Time complexity: O(n)
Space complexity: O(n)

*/


<|start_filename|>Java/other/MinimumSumPartition.java<|end_filename|>
import java.util.*;

public class MinimumSumPartition {

    // Function to find the minimum sum
    public static int findMinSum(int[] arr, int i, int sumCalculated, int total)
    {
        // check for last element, meaning we have sum of one subset as sumCalculated and the other as
        // total - 2*sumCalculated, so we return their absolute difference
        if (i == 0) {
            return Math.abs((total-sumCalculated) - sumCalculated);
        }

        // returning minimum of when we first take arr[i] in first set and when we take it in 2nd set
        // recursive approach
        return Math.min(findMinSum(arr, i - 1, sumCalculated + arr[i-1], total),
                findMinSum(arr, i-1, sumCalculated, total));
    }

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter size for the array:");
        int size = scanner.nextInt();
        int[] arr = new int[size];
        System.out.println("Enter array elements:");
        for (int i = 0; i < size; i++) {
            arr[i] = scanner.nextInt();
        }
        scanner.close();

        // find total sum of all array elements
        int arraySum = 0;
        for (int i = 0; i < size; i++) {
            arraySum += arr[i];
        }

        int result = findMinSum(arr, size, 0, arraySum);

        System.out.println("The minimum difference between sum of 2 sets is:" + result);
    }
}
/*
* Sample input/output
* Enter size for the array:
* 6
* Enter array elements:
* 3 1 4 2 2 1
* The minimum difference between sum of 2 sets is:1
*
* Time complexity: O(2^n)
* Space complexity: O(n)
*/


<|start_filename|>Java/ds/MatrixSorting.java<|end_filename|>
//Java implementation to sort the given matrix 

import java.io.* ;
import java.util.* ;

public class MatrixSorting {

  // function to sort the given matrix 
  static void sortMatrix(int mat[][], int size) {
    // temporary matrix of size^2 
    int tempmat[] = new int[size * size];
    int index = 0;
    // copy the elements of matrix one by one into tempmat[] 
    for (int row = 0; row < size; row++) {
      for (int col = 0; col < size; col++) {
        tempmat[index++] = mat[row][col];
      }
    }
    // sort temporary matrix tempmat[] 
    Arrays.sort(tempmat);
    // copy the elements of tempmat[] one by one in mat[][] 
    index = 0;
    for (int row = 0; row < size; row++) {
      for (int col = 0; col < size; col++) {
        mat[row][col] = tempmat[index++];
      }
    }
  }

  // Driver program to test above 
  public static void main(String args[]) {
    Scanner sc = new Scanner(System. in );
    System.out.println("Input : ");
    System.out.println("Enter the size of matrix : ");
    int size = sc.nextInt();
    int matrix[][] = new int[size][size];
    System.out.println("Enter the elements of square matrix:");
    for (int row = 0; row < size; row++) {
      for (int col = 0; col < size; col++) {
        matrix[row][col] = sc.nextInt();
      }
    }
    sortMatrix(matrix, size);
    System.out.println("Output : ");
    System.out.println("The Sorted Matrix is :");
    for (int row = 0; row < size; row++) {
      for (int col = 0; col < size; col++) {
        //print the given matrix 
        System.out.print(matrix[row][col] + " ");
      }
      System.out.println();
    }
  }
}

/* 
  Input :
  Enter the size of matrix :
  3
  Enter the elements of square matrix :
  7 8 9
  5 6 4
  3 1 2
  Output :
  Sorted Matrix :
  1 2 3
  4 5 6
  7 8 9

  Time Complexity: O(n2log2n)
  Space Complexity : Auxiliary Space: O(n2)
 */


<|start_filename|>C-Plus-Plus/cryptography/Simple_Columnar_Transposition.cpp<|end_filename|>
//SIMPLE COLUMNAR TRANSPOSITION TECHNIQUE
/* It is a type of transposition cipher technique which encrypts the plain text 
message into a cipher text by rearranging the characters of the 
plain text. The plain text is written row-wise and read column-wise. */

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

string encrypt(string s) {
	float n = s.length();
	int row = ceil(n/5),col = 5;
	char arr[row][col];
	for(int i = 0;i < row; ++i) {
		for(int j = 0;j < col; ++j) {
			if((i*col + j) >= s.length()) {
				//1 is the bogus character  
				arr[i][j] = '1' ;
			}
			else
				arr[i][j] = s[i*col + j];
		}
	}
	vector<int>order;  
	//For example order of columns could be 1 0 2 3 4
	cout<<"Enter the order of repositioning columns: ";
	int x;
	for(int i = 0;i < col; ++i) {
		cin>>x;
		order.push_back(x);
	}
	string encString = "";
	for(int i = 0;i < col; ++i) {
		for(int j = 0;j < row; ++j) {
			encString += arr[j][order[i]];
		}	
	}
	return encString;
}

int main() {
	
	string s;
	cout<<"Enter the plain text: ";
	cin>>s;
	cout<<encrypt(s);

}

/*
Example:
Plain Text: TESSERACTCODING
Order of Columns: 2 3 1 0 4
Cipher Text: SCISTNEADTROECG

Plain Text: NEOALGO
Order of Columns: 3 0 1 4 2
Cipher Text: A1NGEOL1O1

Time Complexity: O(n)
Space Complexity: O(1)
*/


<|start_filename|>C-Plus-Plus/graphs/Diagonal_traversal.cpp<|end_filename|>
/*
 Program to print diagonal traversal of a binary tree.
 The idea is to use a queue to store only the left child of current node.
 After printing the data of current node make the current node to its right child, if present.
 A delimiter NULL is used to mark the starting of next diagonal.
*/

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

struct Node
{
    int data;
    struct Node * left;
    struct Node * right;
};
Node* root = NULL;

// Utility function to create a new Tree Node
Node* newNode(int val)
{
    Node *temp = new Node;
    temp->data = val;
    temp->left = NULL;
    temp->right = NULL;

    return temp;
}

// Function to insert item in a tree
void insertItem(int item)
{
    Node *newnode = newNode(item);
    if(!root) {
        root = newnode;
        return;
    }
    Node *cur, *prev;
    cur = root;
    while(cur!= NULL) {
        prev = cur;
        if(cur->data > item)
            cur = cur->left;
        else
            cur = cur->right;
    }
    if(prev->data > item)
        prev->left = newnode;
    else
        prev->right = newnode;
}

vector<int> diagonal(Node *root)
{
   // your code here
   vector<int> ans;
   queue<Node *> q;
    q.push(root);
    while(!q.empty()){
        Node *t=q.front();
        while(t){
            ans.push_back(t->data);
            if(t->left)
                q.push(t->left);
            t=t->right;
        }
        q.pop();
    }
    return ans;
}

int main()
{
    int n;
    cin>>n;
    int arr[n];
    for(int i = 0; i < n; i++) {
        cin>>arr[i];
        insertItem(arr[i]);
    }
    vector<int> ans = diagonal(root);
    for(int i = 0; i < ans.size(); i++) {
        cout<<ans[i]<<" ";
    }
    return 0;
}

/*
 Sample I/O
 Input format: The first line contains n - number of nodes in the tree
               The next line contains n spaced integers
 Output format: n spaced integers.
 Example:
 9
 8 11 2 1 6 14 4 9 13

 Output - 8 11 14 2 6 9 13 1 4

 Explanation:
            8
          /   \
         2     11
       /  \     \
      1    6     14
         /   \   /
        4     9 13

 1st diagonal - 8 11 14
 2nd diagonal - 2 6 9 13
 3rd diagonal - 1 4

*/

/*
 Complexity:
 Time complexity: O(N)
 Space complexity: O(N)
*/



<|start_filename|>C-Plus-Plus/cp/DistinctElementsinaWindow.cpp<|end_filename|>
// This program calculates the count of distinct elements in every window

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

void CountDist(int arr[], int n, int k) { //O(n) time and O(n) aux space
	unordered_map<int, int> freq;   //this map is for storing the frequency of elements
	for (int i = 0; i < k; i++) {
		freq[arr[i]]++;
	}
	cout << freq.size() << " ";     //This statement prints the number of first window's distinct elements
	for (int i = k; i < n; i++) {   //For calculating the ans for other windows, we decrement the freq of the 1st element of prev
		freq[arr[i - k]]--;         //window and add the freq of new element
		if (freq[arr[i - k]] == 0) {
			freq.erase(arr[i - k]);
		}
		freq[arr[i]]++;
		cout << freq.size() << " ";
	}
}

int main() {
	int n;
	cout << "Enter size of array";
	cin >> n;
	int arr[n];
	cout << "Enter array elements";
	for (int i = 0; i < n; i++) {
		cin >> arr[i];
	}
	int k;
	cout << "Enter the size of window";
	cin >> k;
	CountDist(arr, n, k);
	return 0;
}

/*
Examples:
1. For arr[] = {10, 20, 20, 10, 30, 40, 10}, k = 4
   Output = 2 3 4 3
2. For arr[] = {10, 10, 10, 10}, k = 3
   Output: 1 1
3. For arr[] = {10, 20, 30, 40}, k = 3
   Output: 3 3
*/



<|start_filename|>C-Plus-Plus/other/Rabin_Karp_Algorithm_using_prefix_sum.cpp<|end_filename|>
/*
Rabin Karp Algorithm (using prefix sum)
=========================================
Given a text and a pattern, find all the occurences of the pattern in the text

Time Complexity: O(n) n=size of string
Space Complexity: O(1)
*/
#include <bits/stdc++.h>
#define int long long
using namespace std;

const int mod = 1e9 + 7;
const int p = 31;

// returns (a^b)%mod
int powr(int a, int b) {
	int ans = 1;
	while (b) {
		if (b & 1LL) {
			ans *= a;
			ans %= mod;
		}
		a *= a;
		b = b >> 1;
		a %= mod;
	}
	return ans % mod;
}

// returns (a^-1)%mod
int inv(int a) {
	return powr(a, mod - 2) % mod;
}

// Assigns hash to a string
int polyHashString(string s) {
	int hash = 0;
	int coef = 1;
	for (int i = 0; i < s.size(); i++) {
		hash += (s[i] - 'a' + 1) * coef;
		coef *= p;
		coef %= mod;
		hash %= mod;
	}
	return hash % mod;
}

// Rabin Karp Algorithm for pattern matching
// returns indices of pattern in string s
void rabinKarp(string s, string pat) {

	int pat_hash = polyHashString(pat);
	int n = s.size(), m = pat.size();

	int pref[n] = {0};

	for (int i = 0; i < n; i++) {
		pref[i] = (s[i] - 'a' + 1) * powr(p, i);
		pref[i] %= mod;
	}

	for (int i = 1; i < n; i++) {
		pref[i] += pref[i - 1];
		pref[i] %= mod;
	}

	bool patFound = 0;
	for (int i = 0; i <= (n - m); i++) {
		// substring from s[l.......r]
		// r = i+m - 1
		int l = i;
		int r = i + m - 1;

		int new_hash = pref[r];

		if (i - 1 >= 0) {
			new_hash -= pref[l - 1];
		}

		new_hash += mod; new_hash %= mod;

		if (new_hash == (pat_hash * powr(p, l)) % mod) {
			cout << i << endl;
			patFound = 1;
		}
	}

	if (!patFound) {
		cout << "Not found";
	}
}

// Driver Code
signed main() {

	// Take input
	string s, pat;
	cin >> s >> pat;

	rabinKarp(s, pat);
}

/*
Input:
ilovecoding
love

Output:
1

Input:
aaaaaaaa
aaa

Output:
0
1
2
3
4
5
*/


<|start_filename|>C-Plus-Plus/other/remove_outermost_parenthesis.cpp<|end_filename|>
#include <bits/stdc++.h>
using namespace std;
//Main Begin
int main()
{
    string str, res;
    //Count variable take care
    //of number of count prsent
    int count = 0;
    //Input the String
    cout << "Enter String :" << endl;
    cin >> str;
    //For Each loop
    //traverse the entire str
    for (auto ch : str) {
        /*Check if '(' is present,
    	    then increment count variable
    	    by +1
    	    else decrement the count variable 
    	    by -1
    	    */
        if (ch == '(') {
            ++count;
            //if count >0 then
            //add ch to res String
            if (count != 1) {
                res += ch;
            }
        }
        else {
            --count;
            //if count >1 then
            //add ch to res String
            if (count != 0) {
                res += ch;
            }
        }
    }
    //Print the final output
    cout << "Output:" << res;
    return 0;
}

/* Sample Input Output 1.
Enter String : "(()())(())"
Output:  ()()()
Sample Input Output 1.
Enter String : "()()"
Output: ""
Complexities :
Time Complexity : O(n)
Space Complexity : O(n)
*/


<|start_filename|>C-Plus-Plus/cp/ratInAMaze.cpp<|end_filename|>
/*
Link of the problem:-  https://practice.geeksforgeeks.org/problems/rat-in-a-maze-problem/1
There is a rat who is at the starting point of a matrix and wants to reach
 to the ending point i.e at the last coordinate of the matrix.
 1 denotes the point where it is possible for the mouse to go and
 0 denotes the dead end 
 */
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
 /*
 *checking whether safe to move 
 */
bool issafetomove(int** arr, int x, int y, int row, int col)    
{
    if(x<row && y<col && arr[x][y]==1)
    {
        return true;
    }
    return false;
}
bool ratInMaze(int** arr, int x,int y,int row, int col, int** solution)
{
/* base condition  */
    if(x==row-1 && y==col-1)
    {
        solution[x][y]=1;
        return true;
    }

    if(issafetomove(arr,x,y,row,col))
    {
        solution[x][y]=1;

/*moving in right direction */
    if(ratInMaze(arr,x+1,y,row,col,solution))
    {
        return true;
    }

/*moving in down direction*/
    if(ratInMaze(arr,x,y+1,row,col,solution))
    {
        return true;
    }

/*backtracking  */
    solution[x][y]=0;
    return false;
    }
    return false;
}
int main()
{
    int row, col;
    cout<<"enter the rows and columns of the  matrix\n";
    cin>>row>>col;

    int** arr=new int*[row];
    for(int x=0;x<row;x++)
    {
        arr[x]=new int[col];
    }

    cout<<"enter the elements of the array\n";
    for(int i=0;i<row;i++)
    {
        for(int j=0;j<col;j++)
        {
            cin>>arr[i][j];
        }
    }

    int** solution=new int*[row];
     for(int i=0;i<row;i++)
    {
        solution[i]=new int[col];
        for(int j=0;j<col;j++)
        {
            solution[i][j]=0;

        }
    }
    if(ratInMaze(arr,0,0,row,col,solution))
    {
        cout<<"The path obtained is as follows\n";

    for(int i=0;i<row;i++)
    {
        for(int j=0;j<col;j++)
        {
            cout<<solution[i][j]<<" ";
        }
        cout<<endl;
    }
    }
    return 0;
}
//Output
/*enter the rows and columns of the  matrix
3 4
* enter the elements of the array
1 1 1 1
1 0 0 0
1 1 1 1

* The path obtained is as follows
1 0 0 0
1 0 0 0
1 1 1 1
*/


<|start_filename|>Java/dp/Optimal_Binary_Search_tree_using_DP.java<|end_filename|>
/*
    Problem Statement:-Given a sorted array of words to be searched and an array p[0.. n-1] 
    of frequency counts, where p[i] is the number of searches to keys[i]. 
    Also given an array q[0.. n-1] of frequency counts, where q[i] is the number of searches 
    for word keys[i] misspelled by the user. Construct a Binary Search Tree of all words such that 
    the total cost of all the searches(including the misspelled words) is as small as possible.
*/

import java.util.*;

public class Optimal_Binary_Search_tree_using_DP {
    public static void optimal_BST(int p[], int q[], String words[]){
        final int INF = 99999;

        //Creating the weight, cost and root matrices to get the Optimal BST
        //Weight matrix is used for creating our Cost Table
        //Cost table has values for optimal BST cost for the selected words everytime
        //root table contains the structure for Optimal BST
        int weight[][], cost[][], root[][];
        weight = new int[q.length][q.length];
        cost = new int[q.length][q.length];
        root = new int[q.length][q.length];

        //Creating Memoization Tables

        /*Recurrence Relation for Weight Table:-
            if(i == j) -> weight[i][j] = q[i]
            else -> weight[i][j] = weight[i][j-1] +q[j] + p[j-1]
        */

        //Filling Weight matrix diagonally
        for (int g = 0; g < q.length; g++) {
            for (int i = 0, j = g; j < q.length; j++, i++) {
                if (i == j)
                    weight[i][j] = q[i];
                else {
                    weight[i][j] = weight[i][j-1] +q[j] + p[j-1];
                }
            }
        }

        /*Recurrence Relation for Weight Table:-
            if(i == j) -> cost[i][j] = 0
            else -> cost[i][j] = weight[i][j] + min(cost[i][k] + cost[k+1][j])    where i<=k<j
        */

        //Filling Cost matrix diagonally
        for (int g = 1; g < q.length; g++) {
            for (int i = 0, j = g; j < q.length; j++, i++) {
                if (i == j)
                    cost[i][j] = 0;
                else {
                    int min = INF;
                    int m = i;
                    for (int k = i; k < j; k++) {
                        int partial_cost = cost[i][k] + cost[k+1][j];
                        if (partial_cost < min) {
                            min = partial_cost;
                            m = k+1;
                        }
                    }
                    cost[i][j] = min + weight[i][j];
                    //Storing 'm' in root matrix for defining the structure of BST in the root matrix
                    root[i][j] = m;
                }
            }
        }
        System.out.println("Cost of Optimal BST is:- " + cost[0][cost.length - 1]);
        print_Matrices(weight, cost, root);
    }

    public static void print_Matrices(int weight[][], int cost[][], int root[][]){
        System.out.println("Weight Matrix:- ");
        for (int i = 0; i < weight.length; i++) {
            for (int j = 0; j < weight.length; j++) {
                System.out.print(weight[i][j] + "\t");
            }
            System.out.println();
        }
        
        System.out.println("\n\nCost Matrix:- ");
        for (int i = 0; i < cost.length; i++) {
            for (int j = 0; j < cost.length; j++) {
                System.out.print(cost[i][j] + "\t");
            }
            System.out.println();
        }

        System.out.println("\n\n\nRoot matrix:-");
        for (int i = 0; i < root.length; i++) {
            for (int j = 0; j < root.length; j++) {
                System.out.print(root[i][j] + "\t");
            }
            System.out.println();
        }
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the no of words:- ");
        int n = sc.nextInt();
        
        System.out.println("Enter the words:- ");
        String words[] = new String[n];
        for(int i = 0; i<words.length; i++){
            words[i] = sc.next();
        }

        System.out.println("Enter the no of searches for each word:- ");
        int p[] = new int[n];
        for(int i = 0; i<n; i++){
            p[i] = sc.nextInt();
        }

        System.out.println("Enter the no of searches for each misspelled word");
        int q[] = new int[n+1];
        for(int j = 0; j<q.length; j++){
            q[j] = sc.nextInt();
        }        
        optimal_BST(p, q, words);
    }
}
/*
    Time Complexity:- O(n^3)
    Space Complexity:- O(n^2)
*/

/*
Sample Testcase:
Enter the no of words:-
4
Enter the words:-
words = {"auto", "for", "int", "short"}
Enter the no of searches for each word:-
p = {7, 3, 5, 2}
Enter the no of searches for each misspelled word:-
q = {1, 2, 4, 7, 3}

Output:-
Cost of Optimal BST is:- 72
Weight Matrix:- 
1       10      17      29      34      
0       2       9       21      26
0       0       4       16      21
0       0       0       7       12
0       0       0       0       3

Cost Matrix:-
0       10      26      55      72
0       0       9       30      47
0       0       0       16      33
0       0       0       0       12
0       0       0       0       0

Root matrix:-
0       1       1       2       3
0       0       2       3       3
0       0       0       3       3
0       0       0       0       4
0       0       0       0       0
*/


<|start_filename|>C-Plus-Plus/math/Binary_Exponentiation.cpp<|end_filename|>
// C++ Program to find Binary Exponent Iteratively and Recursively.

#include <iostream>

// Iterative function to calculate exponent.

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

// Recursive function to calculate exponent.

int binExpo_recurse(int a, int b)
{
    if (b == 0)
    {
        return 1;
    }
    int res = binExpo_recurse(a, b / 2);
    if (b % 2)
    {
        return res * res * a;
    }
    else
    {
        return res * res;
    }
}

// Main function

int main()
{
    int a, b;

    std::cin >> a >> b;

    if (a == 0 && b == 0)
    {
        std::cout << "Math Error" << std::endl;
    }
    else if (b < 0)
    {
        std::cout << "Exponent must be Positive" << std::endl;
    }
    else
    {
        int resIterate = binExpo_iterate(a, b);
        int resRecurse = binExpo_recurse(a, b);

        std::cout << resIterate << std::endl;
        std::cout << resRecurse << std::endl;
    }
}

<|start_filename|>Go/cryptography/Vernam_Cipher/Vernam_Cipher.go<|end_filename|>
/* This code is an implementation of Vernam Cipher in Go. In
Vernam cipher, also known as the One-Time Pad, the length of
the plaintext, ciphertext, and key is the same. Basically,
here the ith letter of the cipher text is fomred by shifting
the ith letter of the plaintext with the ith letter of key.
*/

package main

import (
	"fmt"
	"unicode"
	"strings"
	"os"
)

// This is the encryption function
func encryption(plaintext, key string) string {

	var encrypted string

	// Shifting the plaintext to generate the ciphertext
	for i := 0; i < len(plaintext); i++ {
		var temp int = (int(plaintext[i]) - 97 + int(key[i]) - 97) % 26
		temp = temp + 97
		encrypted += string(temp)
	}
	// Returns the ciphertext
	return encrypted
}

func format(plaintext, ciphertext string) string {

	var enc string

	/* Check wherever the plaintext is capital and
	then capitalize that character in the ciphertext*/
	for i := 0; i < len(plaintext); i++ {
		if(unicode.IsUpper(rune(plaintext[i]))) {
			enc += strings.ToUpper(string(ciphertext[i]))
		} else {
			enc += string(ciphertext[i])
		}
	}
	// Return the final formatted ciphertext
	return enc
}

func main() {

	// Taking plaintext as input from the user
	fmt.Print("Enter a message to encrypt: ")
	var plaintext string 
	fmt.Scan(&plaintext)

	// Taking key as input from the user
	fmt.Print("Enter a key of same length: ")
	var key string
	fmt.Scan(&key)

	/* If length of key is not equal to length
 	   of plaintext then exit the program.*/
	if(len(key) != len(plaintext)) {
		fmt.Print("\nInvalid key size.\n")
		os.Exit(0)
	}

	// Generating the ciphertext
	var ciphertext string = encryption(strings.ToLower(plaintext), strings.ToLower(key))

	// Formatting the ciphertext
	var encrypted string = format(plaintext, ciphertext)
	fmt.Print("\nEncrypted plaintext is    : ", encrypted, "\n")
}

/* Sample I/O:

a)
Enter a message to encrypt: ThisIsAMsg
Enter a key of same length: ThisisaKey

Encrypted plaintext is    : MoqkQkAWwe

b)
Enter a message to encrypt: PlaintextMessage
Enter a key of same length: Key

Invalid key size.
*/



<|start_filename|>C-Plus-Plus/math/Ackermann_function.cpp<|end_filename|>
#include<bits/stdc++.h>
using namespace std;
int Ackermann_Function(int m, int n) {
	if (m == 0)
		return n + 1;

	else if (m > 0 && n == 0)
		return Ackermann_Function(m - 1, 1);

	else if (m > 0 && n > 0)
		return Ackermann_Function(m - 1, Ackermann_Function(m, n - 1));
}

int main() {
	int m, n;
	cin >> m >> n;
	cout << Ackermann_Function(m, n);
	return 0;
}

/*
time complexity:-O(mA(m, n)) to compute A(m, n)
space complexity:- O(m) to compute A(m, n)
Examples:-
m=1,n=2
output=4
m=3,n=3
output=61
*/


<|start_filename|>JavaScript/Algorithms/ZAlgorithm.js<|end_filename|>
const searchPattern = (text, pattern) => {
  let concatNewStr = pattern + "$" + text;
  let zArr = [];

  //get the z array
  getZarr(concatNewStr, zArr);

  // looping to find the array locations
  for (let i = 0; i < zArr.length; i++) {
      if (zArr[i] == pattern.length) {
          console.log("Found pattern at index " + (i - pattern.length - 1));
      }
  }
};
const getZarr = (str, zArr) => {
  let n = str.length;

  // [left,right] make a window which matches with prefix of s
  let left = 0,
      right = 0;

  for (let i = 1; i < n; ++i) {
      // if i>right nothing matches
      if (i > right) {
          left = right = i;

          // right-left = 0 in starting, so it will start checking from 0'th index.
          while (right < n && str.charAt(right - left) == str.charAt(right)) {
              right++;
          }

          zArr[i] = right - left;
          right--;
      } else {
          // k = i-left so k corresponds to number which matches in [left,right] interval.
          let k = i - left;

          // if zArr[k] is less than remaining interval then zArr[i] will be equal to zArr[k].
          if (zArr[k] < right - i + 1) {
              zArr[i] = zArr[k];
          } else {
              // else start from right and check manually
              left = i;
              while (right < n && str.charAt(right - left) == str.charAt(right)) {
                  right++;
              }
              zArr[i] = right - left;
              right--;
          }
      }
  }
};

searchPattern("AABAACAADAABAABA", "AABA");

/*
Output:
Found pattern at index 0
Found pattern at index 9
Found pattern at index 12
Time complexity and Space complexity: O(m + n), length of text be n and of the pattern be m
*/

<|start_filename|>C-Plus-Plus/other/RussianPeasantAlgo.cpp<|end_filename|>
/*************************************************************
 Program to multiply two numbers using Russian peasant method
 Given two integers, write a function to multiply them without using multiplication operator.
 We double the first number and halve the second number repeatedly till the second number doesn’t become 1.
In the process, whenever the second number becomes odd, we add the first number to result.

 *************************************************************/

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

//implementation of logic
int fractionalknapsack(int m, int n)
{
    int result;
       while(n > 0)
    {
        if(n % 2 != 0)
        {
            result += m;
            m << 2;
            n >> 2;
        }
    }
    return result;
}

int main()
{
    int num1, num2, result = 0, m, n;
    cout<<"Enter two numbers: ";
    cin>>num1>>num2;
    result= fractionalknapsack(m, n);
    cout<<num1<<" * "<<num2<<" = "<<result;
    return 0;
}

/*
Sample Input Output
Enter two numbers: 12 13
12 * 13 = 156
*/



<|start_filename|>C/ds/infixToPrefix.c<|end_filename|>
/*
Given an infix expression, the aim is to convert it into prefix expression.
In order to do this, we first reverse the expression, and find it's postfix expression.
(Postfix expression can be found with the help of an operator stack, and precedence of operators)
The reverse of this resulting expression gives us the final infix expression.
*/

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

typedef struct stack {
    int capacity, top;
    char *arr;
} stack;

stack * createStack(int size) {
    struct stack *s = (struct stack *) malloc(sizeof(struct stack));
    s -> arr = (char *)malloc (size * sizeof(char));
    s -> top = -1;
    s -> capacity = size;
    return s;
}

int isEmpty(stack *s) {
    /* tells whether the stack is empty or not */
    return  s -> top == -1;
}

int isFull(stack *s) {
    /* tells whether a stack is full or not */
    return s -> top == s -> capacity - 1;
}

void push(stack *s, int data) {
    /* push a given element into the stack */
    s -> arr[ ++ s -> top] = data;
}

char pop(struct stack *s) {
    /* to pop the top element from stack */
    return s -> arr[s -> top --];
}

char peek(struct stack *s) {
    /* to get the top element of stack */
    return s -> arr[s -> top];
}

int precedence(char ch) {
    /* gives the precedence of operators */
    switch(ch) {
        case '+':
        case '-': return 1;
        case '/': 
        case '*': return 2;
        case '^': return 3;
        case ')': return 4;
    }
}

stack * infToPost(char infixExp[100]) {
    /* To reverse a given infix expression and convert to postfix expression */
    int index = 0;
    int contains = 0; /* using a variable to see if the operator stack contains a '(' at any time */
    int len = strlen(infixExp);
    stack *operatorStack = createStack(len);
    stack *postfixExp = createStack(len + 1);

    /* converting the reverse of given expression into postfix */
    for ( index = len - 2; index >= 0; index --) { 
        char ch = infixExp[index];
        if ( isspace(ch)) {
            continue;
        }
        if ( isalnum(ch) ) { /* if its an operand */
                push(postfixExp, ch);
                push(postfixExp, ' ');
        }
        else { /* if its an operator */
            if (ch == ')' ) {
                push(operatorStack, ch);
                contains += 1;
            }
            else if (isEmpty(operatorStack)) {
                push(operatorStack, ch);
            }
            else if ( ch == '(') { /* if the current character is '(', we empty the stack until we encounter ')' */
                while ( peek(operatorStack) != ')'){
                    push(postfixExp, pop(operatorStack));
                    push(postfixExp, ' ');
                }
                char waste = pop(operatorStack);
                contains -= 1;
            }
            else if ( (precedence( peek(operatorStack)) <= precedence(ch)) || contains  ) { /* comparing the preceedence */
                push(operatorStack, ch);
            }
            else {
                while (precedence( peek(operatorStack)) > precedence(ch)) { /* comparing the preceedence */
                    push(postfixExp, pop(operatorStack));
                    push(postfixExp, ' ');
                    if (isEmpty(operatorStack)) {
                        break;
                    }
                }
                push(operatorStack, ch);
            }    
        }
    }
    while ( !isEmpty(operatorStack)) {
        push(postfixExp, pop(operatorStack));
        push(postfixExp, ' ');
    }
    return postfixExp;
}

void displayInReverse(stack *s) {
    /* to display the stack in reverse order */
    for (int i = s -> top ; i >= 0; i --) {
            printf("%c", s -> arr[i]);
    }
    printf("\n");
}

void infToPre(char infixExp[100]) {
    /* converts a given infix expression to infix expression */
    stack *postfixExp = infToPost(infixExp);
    displayInReverse(postfixExp); /* reversing finally to get prefix of the given expression */
}

int main() {
    char infixExp[100];
    printf("Enter the Infix expression:\n");
    fgets(infixExp, 100, stdin);
    printf("The Prefix expression is:\n");
    infToPre(infixExp);
    return 0;
}


/*
SampleInput: (A + B) * (C + D)
Sample Output:  * + A B + C D
*/


<|start_filename|>C/math/Neon_number.c<|end_filename|>
/* C Program to check whether a number is Neon or not.
 A neon number is a number where the sum of digits of square of the number is equal to the number. 
 */

#include <stdio.h>
#include <math.h>
void neon(int n)
{
	int i, sum = 0, t = 1;
	t = pow(n, 2);
	while (t != 0)
	{
		sum = sum + (t % 10);
		t = t / 10;
	}
	if (sum == n)
	{
		printf("Neon number.\n");
	}
	else
	{
		printf("Not a neon number\n");
	}
}
int main()
{
	int n;
	printf("Enter a number ");
	scanf("%d", &n);
	neon(n);
}
/* Sample Input/output
Example 1-
Enter a number 9
Neon number.
Example 2-
Enter a number 144
Not a neon number

Space Complexity O(1)
Time Complexity  O(log(n))
*/


<|start_filename|>C-Plus-Plus/dp/Arithmetic_Slices.cpp<|end_filename|>
/*
An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.

For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences.
Given an integer array nums, return the number of arithmetic subarrays of nums.
*/

#include<iostream>
#include<vector>

using namespace std;

//Function takes array and the size of the array as an input, it returns the number of arthemetic slices present in the input array//
int numberOfArithmeticSlices(int A[],int size) {
    if(size<3) return 0;
    vector<int> res (size,0);
    
    /*
    -> Starting the loop from 2nd element in the array and check for an AP between 1st 2nd and 3rd element.
    -> If AP exists between these elements we check if there is a continuation of this AP from before by checking the previous index of the result Array.
    -> If the previous index is not zero that means it is a coninuation and hence we add the value of the previous index with one.
    -> We make the current value in the result index equal to the previous value + 1.
    -> In case it is not a continuation and the previous value is 0 in the result array we simple add 1 to the current value(0) and the current value becomes 1.
    */
    for(int i = 2;i<size;i++)
    {
        if(A[i]-A[i-1] == A[i-1]-A[i-2])
        {
            if(res[i-1]>0)
            {
                res[i] = res[i-1]+1;
            }
            else
            {
            res[i]++;
            }
        }
    }
    int ans = 0;
    
    /* Adding the values at all the indices we get the total number of arthemetic slices. */
    for(int i = 0;i<res.size();i++)
    {
        ans = ans+res[i];
    }
    return ans;
}


int main(){

    int size = 0;
    
    cout<<"Enter the size of the array- "<<endl;
    cin>>size;
    int arr[size];
    cout<<"Enter the values inside the array"<<endl;
    for(int i = 0; i<size ; i++)
    {
        int temp = 0;
        cin >> temp;
        arr[i] = temp;
    }

    cout<<"Number of Arithmetic Slices in the array is- "<<numberOfArithmeticSlices(arr,size)<<endl;
    
    return 0;
}

/*

Time Complexity: O(N)
Space Complexity: O(N)

I/O Example 1:
    Input: nums = [1,2,3,4]
    Output: 3
    Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.

I/O Example 2:
    Input: nums = [1]
    Output: 0

*/


<|start_filename|>C-Plus-Plus/dp/House_Robber_Problem.cpp<|end_filename|>
/*
Introduction 
You are a professional robber planning to rob houses along a street.
Each house has a certain amount of money stashed, 
the only constraint stopping you from robbing each of them is that 
adjacent houses have security systems connected and it will automatically contact the police 
if two adjacent houses were broken into on the same night.

Argument/Return Type
Given an integer array nums representing the amount of money of each house,
return the maximum amount of money you can rob tonight without alerting the police.
*/

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

//Function to find the maximum amount of money you can rob tonight without alerting the police
int MaxMoney(vector<int>&nums) 
{
    int n=nums.size();

    //If there are 0 houses , return 0
    if(n==0) 
        return 0;

    //If there is only one house , return its money
    if(n==1) 
        return nums[0];

    /* If there are atleast 2 houses ,create a dp vector and 
    calculate the maximum amount of money you can rob 
    without alerting the police till that particular house */
    vector<int>dp(n);
    dp[0]=nums[0];
    dp[1]=max(nums[1],dp[0]);
    for(int i=2;i<n;i++)    
    {
        /* At each i th house 
        either ( houses upto i-2 ) + ( i th house )
        or ( houses upto i-1 ) can be robbed */
        dp[i]=max(nums[i]+dp[i-2],dp[i-1]);
    }

    //Return the required answer which is the maximum amount of money that can be robbed till last house
    return dp[n-1];
}


// Driver code
int main()
{
    //Take input for size of nums vector
    int n;
    cout<<"Enter total no.of houses : ";
    cin>>n;

    //create a vector to take input and store them
    vector<int>nums;

    cout<<"Enter money in each house, with spaces between them : ";

    for(int index=0;index<n;index++)
    {
        //Take the input of each value and push it into the vector
        int value;
        cin>>value;
        nums.push_back(value);
    }   

    //Call the function and print the result
    cout<<"Hence the maximum amount of money you can rob tonight without alerting the police is ";
    cout<<MaxMoney(nums);

    return 0; 
}
    
/*
Input:
1 <= nums.length <= 100
0 <= nums[i] <= 400

Sample Test Case 1  

Input Format : 
Example :
Enter total no.of houses : 5
Enter money in each house, with spaces between them : 2 7 9 3 1

Output Format :
Example : ( Output to the above input example ) 
Hence the maximum amount of money you can rob tonight without alerting the police is 12

Time/Space Complexity
Time Complexity : O(n) 
Space Complexity : O(n) 
*/


<|start_filename|>C-Plus-Plus/ds/Binary_Search_Tree_Validation.cpp<|end_filename|>
/*

Introduction 
Given a Binary Tree , check if it is a valid Binary Search Tree

A valid Binary Search Tree is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.

Argument/Return Type
Input of total no.of nodes is taken
Input of key values of nodes of tree are taken in level order form 
Incase of a null node , -1 is taken as input
Bool is returned as a result and corresponding statement is printed

*/

//  Code / Solution

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

//Define Node as structure
struct Node 
{
    int key;
    Node* left;
    Node* right;
};
 
// Function to create a node with 'value' as the data stored in it. 
// Both the children of this new Node are initially null.
struct Node* newNode(int value)
{
    Node* n = new Node;
    n->key = value;
    n->left = NULL;
    n->right = NULL;
    return n;
}

// Function to build tree with given input
struct Node* createTree(vector<int>v)
{
    int n=v.size();
    if(n==0) 
      return NULL;
    vector<struct Node* >a(n);
    //Create a vector of individual nodes with given node values
    for(int i=0;i<n;i++)  
    {
        //If the data is -1 , create a null node
        if(v[i]==-1)  
          a[i] = NULL;
        else 
          a[i] = newNode(v[i]);
    }
    //Interlink all created nodes to create a tree
    //Use two pointers using int to store indexes
    //One to keep track of parent node and one for children nodes
    for(int i=0,j=1;j<n;i++) 
    {
        //If the parent node is NULL , advance children pointer twice
        if(!a[i])
        {
          j=j+2;
          continue;
        } 
        //Connect the two children nodes to parent node
        //First left and then right nodes
        a[i]->left = a[j++];
        if(j<n) 
          a[i]->right = a[j++];
    }
    return a[0];
}

// Utility function which keeps checking , three essential conditions to be a BST 
// Returns true if the given tree is a BST and its values are >= min and <= max. 
bool IsValidBSTUtil(struct Node* root, int min, int max)
{
    // an empty tree is BST as it obeys all the conditions
    if (root==NULL)
        return true;
             
    //return false if this node violates the min/max constraint 
    if (root->key < min || root->key > max)
        return false;
     
    //Check if both subtrees are valid BST's recursively 
    //Update corresponding min , max values
    return  IsValidBSTUtil(root->left, min, root->key-1) && IsValidBSTUtil(root->right, root->key+1, max); 
}

// Function to check if it is a valid binary tree
bool IsValidBST(struct Node* root)
{
    return(IsValidBSTUtil(root, INT_MIN, INT_MAX));
}
 

int main()
{

    int n;
    cout<<"Enter total no.of nodes of the input Tree ( including NULL nodes ) : ";
    cin>>n;

    vector<int>v(n);
    cout<<"Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces"<<endl;
    for(int i=0;i<n;i++)
    {
        cin>>v[i]; //store the input values in a vector
    }

    //create the tree using input node values  
    struct Node* root=createTree(v); 

    //Call the function and print the result
    bool result=IsValidBST(root); 
    if(result)
        cout<<"The given tree is a valid Binary Search Tree";
    else
        cout<<"The given tree is not a valid Binary Search Tree";
      
    return 0; 
}
    
/*
Input:
0 <= node->key < 1000000000
if node is NULL , -1 is entered as it's key

Sample Test Case 1  
Input Binary Tree :                   

               10                                
           /         \                          
         11              12                    
     /       \        /   \               
    5       NULL     6     13             
   / \      /  \    / \   /  \            
  4 NULL  NULL NULL 8  9 10  NULL         


Input Format : 
Example :
Enter total no.of nodes of the input Tree ( including NULL nodes ) : 15
Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces
10 11 12 5 -1 6 13 4 -1 -1 -1 8 9 10 -1

Output Format :
Example : ( Output to the above input example ) 
The given tree is not a valid Binary Search Tree

Sample Test Case 2  
Input Binary Tree :                   

                  12                                
          /               \                          
         9                 17                    
     /       \          /      \               
    8       10         15       18             
   / \      /  \      / \      /  \            
  7 NULL  NULL NULL 14  16 NULL  20         


Input Format : 
Example :
Enter total no.of nodes of the input Tree ( including NULL nodes ) : 15
Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces
12 9 17 8 10 15 18 7 -1 -1 -1 14 16 -1 20

Output Format :
Example : ( Output to the above input example ) 
The given tree is a valid Binary Search Tree

Time/Space Complexity
Time Complexity : O(n) 
   Where n is the no.of nodes 
Space Complexity : O(n) 
   Where n is the no.of nodes
*/


<|start_filename|>Julia/search/binary_search.jl<|end_filename|>
"""Julia program to implement Binary Search algorithm.
Binary Search is a Divide and Conquer strategy based algorithm, where the entire array is divided into two halfs and the
required element is searched for in one of these sections as per the conditions. It is done on sorted arrays.
"""

function binary_search(arr, n, ele)
    low = 1
    high = n
    while high >= low
        mid = low + (high - low) ÷ 2
        # If the mid element is the required element, return that index
        if(arr[mid] == ele)
            return mid
        # ele is greater than mid element then ele would be present in first half of the array
        elseif (arr[mid] > ele)
            high = mid - 1
        #Else if  ele is smaller than mid element then ele would be present in last half of the array
        else
            low = mid + 1
        end
    end
    # If the element is not found return 0
    return 0
end


print("How many numbers are present in the array? ")
n = readline()
n = parse(Int, n)
if (n <= 0)
    println("Array is Empty!!!")
    exit()
end
arr = Int[]
print("Enter the numbers: ")
arr = [parse(Int, num) for num in split(readline())] 
print("Which number do you want to search in the array? ")
ele = readline()
ele = parse(Int, ele)
# Sort the array in ascending order
arr = sort(arr)
res = binary_search(arr, n, ele)
if (res == 0)
    print("The number $ele is not present in the array")
else
    print("The number $ele is present in the array.")
end


"""
Time Complexity - O(log(n)), where 'n' is the size of the array
Space Complexity - O(n)

SAMPLE INPUT AND OUTPUT

SAMPLE I

How many numbers are present in the array? 5 
Enter the numbers: 1 2 3 4 5
Which number do you want to search in the array? 6
The number 6 is not present in the array

SAMPLE II

How many numbers are present in the array? 3
Enter the numbers: 3 1 2
Which number do you want to search in the array? 2
The number 2 is present in the array.

"""


<|start_filename|>C/dp/floyd_warshal.c<|end_filename|>
/*
Floyd-Warshall Algorithm is an algorithm
for finding the shortest path between all the
pairs of vertices in a weighted graph.
This algorithm works for both the directed
and undirected weighted graphs.
But, it does not work for the graphs with negative cycles
*/

#include<stdio.h>
int i, j, k, n, arr[10][10];
//Floyd function
void floyd_Warshall () {
//Add all vertex one by one
	for (k = 0; k < n; k++) {
		//pick all as a source
		for (i = 0; i < n; i++) {
			//pick all as a destination
			for (j = 0; j < n; j++) {
				if ((arr[i][k] * arr[k][j] != 0) && (i != j)) {
					//If vertex k is on the shortest path from
					// i to j, then update the value of arr[i][j]
					if ((arr[i][k] + arr[k][j] < arr[i][j]) || (arr[i][j] == 0)) {
						arr[i][j] = arr[i][k] + arr[k][j];
					}
				}
			}
		}
	}
}
//Main function Began
int main() {
	int i, j;
	//Enter the number of vertex
	printf("enter no of vertices :");
	scanf("%d", &n);
	printf("\n");
//Enter values for array
	for (i = 0; i < n; i++)
		for (j = 0; j < n; j++) {
			printf("arr[%d][%d]:", i, j);
			scanf("%d", &arr[i][j]);
		}
//call Floyd function
	floyd_Warshell();
//OUTPUT
	printf("OUTPUT");
//print the output
	printf (" \n\n Shortest distances are :\n");
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++)
			printf ("%d\t", arr[i][j]);
		printf("\n");
	}
	return 0;
}
//main function ends

/*
Sample Input Output:
enter no of vertices:4

dist[0][0]:0
dist[0][1]:8
dist[0][2]:999
dist[0][3]:1

dist[1][0]:999
dist[1][1]:0
dist[1][2]:1
dist[1][3]:999

dist[2][0]:4
dist[2][1]:999
dist[2][2]:0
dist[2][3]:999

dist[3][0]:999
dist[3][1]:2
dist[3][2]:9
dist[3][3]:0

OUTPUT:
Shortest distances are:
0	3	4	1
5	0	1	6
4	7	0	5
7	2	3	0

Time Complexity:O(N^3)
*/


<|start_filename|>C-Plus-Plus/math/Sieve_Of_Atkins.cpp<|end_filename|>
/*
	Sieve of Atkin is a modern algorithm for finding all prime numbers up to a
	specified integer. Compared with the ancient Sieve of Eratosthenes, which
	marks off multiples of primes, the Sieve of Atkin does some preliminary work
	and then marks off multiples of squares of primes, thus achieving a better 
	theoretical asymptotic complexity.
 	
 	We are going to check the following condition and according to that we
 	decide prime numbers
 	a) a = (4*i*i)+(j*j) has odd number of  
       solutions, i.e., there exist 
       odd number of distinct pairs (i, j)  
       that satisfy the equation and 
        n % 12 = 1 or n % 12 = 5. 
    b) n = (3*i*i)+(j*j) has odd number of  
       solutions and n % 12 = 7 
    c) n = (3*i*i)-(j*j) has odd number of  
       solutions, i > j and n % 12 = 11 
	   
*/


#include<iostream>		//Header file
using namespace std;	//For cin and cout


int Sieve_Of_Atkin(int n) 
{ 
    // Printing 2 and 3 as prime numbers 
    if (n > 2) 
        cout << 2 << " "; 
    if (n > 3) 
        cout << 3 << " "; 
    // Creating a array of boolean type of size n and
	// initialize it with false value    
    bool sieve[n]; 
    for (int i = 0; i < n; i++) 
        sieve[i] = false; 
		
	// Iterating over the numbers
	//If it is prime we make sieve[a]=true  
    for (int i = 1; i * i < n; i++) { 
        for (int j = 1; j * j < n; j++) { 
              
            // Making equations for prime numbers 
            int a = (4 * i * i) + (j * j); 
            if (a <= n && (a % 12 == 1 || a % 12 == 5)) 
                sieve[a] = true; 
  
            a = (3 * i * i) + (j * j); 
            if (a <= n && a % 12 == 7) 
                sieve[a] = true; 
  
            a = (3 * i * i) - (j * j); 
            if (i > j && a <= n && a % 12 == 11) 
                sieve[a] = true; 
        } 
    } 
  
    // Mark all multiples of squares as non-prime 
    for (int k = 5; k * k < n; k++) { 
        if (sieve[k]) { 
            for (int i = k * k; i < n; i += k * k) 
                sieve[i] = false; 
        } 
    } 
  
    // Printing prime numbers greater than 3
    for (int i = 5; i < n; i++) 
        if (sieve[i]) 
            cout << i << " "; 
} 
  
// Main() Function 
int main() 
{ 
    int n;
	cin>>n;					        //Taking input from user
    Sieve_Of_Atkin(n); 		//Calling function
    return 0; 
} 


/*
	Sample input :
 	43
 	Sample output:
 	2 3 5 7 11 13 17 19 23 29 31 37 41
	Time Complexity -O(n/(log(logn)))
	Space Complexity-O(n^0.5)
	
*/



<|start_filename|>C-Plus-Plus/ds/LinkedList.cpp<|end_filename|>
/* A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations, which is a linked list 
consists of nodes where each node contains a data field and a reference(link) to the next node in the list */

#include <iostream>
using namespace std;
int count =0;
class Node{   //To create Node in heap with data and next pointer
public:
    int data;
    Node *next;
};

class LinkedList{     //creates Linked List with help of class Node
    
private:
    Node *first;
    
public:
    LinkedList()     
    {
        first=NULL;
    }
    
    LinkedList(int arr[],int n)  //Takes input as array and its size from main to create Linked List 
    {
        Node *tmp,*last;
        first=new Node;
        first->data = arr[0];  //First element in array is First Node in Linked List
        first->next = NULL;
        last = first;
        for(int i=1;i<n;i++)   //Remaining Elements are followed by first Node
        {
            tmp = new Node;
            tmp->data = arr[i];
            tmp->next=NULL;
            last->next=tmp;
            last=tmp;
        }
   }
 
void display()          // To Display an Linked List
{
    Node *p=first;
    cout << "Nodes in Linked List are: " << endl;
    while(p)
    {
        cout << p->data << " "<< endl;
        p=p->next;
    }
}


int countNodes(Node *p)  //To return total count of Nodes in Linked List
{
    if(p==NULL)
        return 0;
    else
    {
        count++;
         return countNodes(p->next) + 1;
    }
    
}


void InsertNode(int index,int x)  //Takes index and Node's Data to be insterted into Linked List
{
    Node *p=first;
    Node *tmp;
    if(index < 0 || index > countNodes(p))
    {
        return;
    }
    tmp = new Node;
    tmp->data=x;
    if(index==0)
    {
        tmp->next=p;
        first=tmp;
    }
else
    {
    for(int i=0;i<index-1;i++)
    {
        p=p->next;
    }
    tmp->next=p->next;
    p->next=tmp;
    }
}

int DeleteNode(int pos)   //Takes position to delete the corresponding Node from Linked List
{
    Node *p,*q=NULL;
    int x;
    if(pos==1)
    {
        p=first;
        x=p->data;
        first=first->next;
        delete p;
        return x;
    }
    else{
    p=first;
    q=NULL;
    for(int i=0;i<pos-1;i++)
        {
            q=p;
            p=p->next;
        }
    q->next=p->next;
    x=p->data;
    delete p;
    return x;
    }
}
};

int main(){
cout <<"Enter number of elements to be inserted into LinkedList: " << endl;
int num,position,index,Element;
cin >> num;
int arr[num];
for(int i=0;i<num;i++)  // Array of Elements will be inserted into Linked List as separate Node,where each Node contains Data and next pointer which points to next Node
{
    cin >> arr[i];
}
LinkedList LL(arr,num);
LL.display();
cout <<"Enter an Element and its position to insert in LinkedList: " << endl;  //Enter Node data to be inserted into LL with position-1
cin >> Element;
cin >> position;
LL.InsertNode(position,Element);
cout <<"AFter Insertion" << endl;
LL.display();
cout <<"Enter a position to delete from LinkedList: " << endl;
cin >> index;
cout <<"Node " <<LL.DeleteNode(index)<<" Deleted from Linked List" << endl;
return 0;
}


<|start_filename|>C/cryptography/Hill_Cipher.c<|end_filename|>
/* This code is an implementation of Hill Cipher. It
   is a polygraphic substitution cipher. It forms a 
   nxn matrix of key and nx1 matrix(s) of the plaintext
   and then multiplies the two matrices to obtains the
   matrix of ciphertext.*/

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

// Define max-length for message, ciphertext and key
#define MAXLENGTH 100

// Define the size of the n.
#define size 3

/* This function forms the nxn matrix of keyword.
   The value of n can be changed from above macro*/
void get_key_matrix(char* key, int matrix_key[][size]) {

	int count = 0;
	for(int i = 0; i < size; i++) {
		for(int j = 0; j < size; j++) {
			// Converting ascii to decimal
			matrix_key[i][j] = key[count] - 0;
			/* Here, a = 97, b = 98 and so on.
			   We want a = 0, b = 1 and so on.
			   So, we subtract 97.*/
			matrix_key[i][j] -= 97;
			count++;
		}
	}
}

/* This function forms the nx1 matrix of the plaintext.
   Value of n can be changed from the macro defined.*/
void get_plaintext_matrix(char* message, int message_matrix[][1]) {

	int count = 0;
	for(int i = 0; i < size; i++) {
		for(int j = 0; j < 1; j++) {
			// Converting ascii to decimal
			message_matrix[i][j] = message[count] - 0;
			/* As we did above, similarly, we subtract
			   97 from the decimal value to start
			   indexing from 0.*/
			message_matrix[i][j] -= 97;
			count++;
		}
	}
}

/* This function forms the nx1 ciphertext matrix.
   The matrix of decimal is then converted to ascii
   value and combined and then returned.*/
char* get_ciphertext_matrix(char* message, char* keyword, int matrix_cipher[][1]) {

	// Forming the keyword matrix 
	int matrix_key[size][size];
	// Calling the keyord matrix function
	get_key_matrix(keyword, matrix_key);

	// Forming the plaintext matrix
	int message_matrix[size][1];
	// Callin the plaintext matrix function
	get_plaintext_matrix(message, message_matrix);

	/* Initializing the ciphertext matrix values
	   to zero. Otherwise, it would store garbage
	   values.*/
	for(int i = 0; i < size; i++) {
		for(int j = 0; j < 1; j++) {
			matrix_cipher[i][j] = 0;
		}
	}

	/* Multiplying key matrix with plaintext
	   matrix and forming the ciphertext
	   matrix. */
	for(int i = 0; i < size; i++) {
		for(int j = 0; j < 1; j++) {
			for(int k = 0; k < size; k++) {
				matrix_cipher[i][j] += matrix_key[i][k] * message_matrix[k][j];
			}
		}
	}

	/* Taking mod 26 of obtained ciphertext values
	   to ensure they lie within the range [0-25].*/
	for(int i = 0; i < size; i++) {
		for(int j = 0; j < 1; j++) {
			matrix_cipher[i][j] = matrix_cipher[i][j] % 26;
		}
	}

	// This variable is declared to store the ciphertext
	static char encrypted[MAXLENGTH];

	/* Since, we decremented 97 from the decimal values
	   of plaintext and key, we add back 97 to the 
	   ciphertext values, in order to get proper ASCII.*/
	int cnt = 0;
	for(int i = 0; i < size; i++) {
		for(int j = 0; j < 1; j++) {
			encrypted[cnt++] = matrix_cipher[i][j] + 97;
		}
	}

	// Returning the ciphertext
	return encrypted;
}


int main() {

	// Taking plaintext and key as input from user
	char plaintext[MAXLENGTH];
	char keyword[MAXLENGTH];

	printf("\n-----------------------HILL CIPHER--------------------------\n\n");
	printf("The value of plaintext must be same as n(Defined in the macro)\n");

	printf("\nCurrent value of n is: %d\n\n", size);

	printf("Enter a plaintext of size %d: ", size);
	scanf("%s", plaintext);

	// Checking if proper message is provided or not.
	if(strlen(plaintext) != size) {
		printf("Enter a valid message.\n");
		exit(0);
	}

	printf("Enter a key of size %d: ", size*size);
	scanf("%s", keyword);

	// Checking if proper key is provided or not.
	if(strlen(keyword) != size * size) {
		printf("Enter a valid key.\n");
		exit(0);
	}

	// Declaring the ciphertext matrix
	int matrix_cipher[size][1];

	char *encrypted_message;

	// Calling the function to get the encrypted plaintext
	encrypted_message = get_ciphertext_matrix(&plaintext[0], &keyword[0], matrix_cipher);

	printf("Encrypted plaintext is : %s\n", encrypted_message);

	return 0;
}

/* Sample I/O:

a) For n = 3


-----------------------HILL CIPHER--------------------------

The value of plaintext must be same as n(Defined in the macro)

Current value of n is: 3

Enter a plaintext of size 3: ask
Enter a key of size 9: thisiskey
Encrypted plaintext is : yma

b) For n = 4


-----------------------HILL CIPHER--------------------------

The value of plaintext must be same as n(Defined in the macro)

Current value of n is: 4

Enter a plaintext of size 4: mess
Enter a key of size 16: thisisabigkeymsg
Encrypted plaintext is : weio
*/



<|start_filename|>C/ds/maxHeap.c<|end_filename|>
/*
A max heap has the property that the parent is greater than or equal to the child nodes. 
When using a 0-indexed array,
Left child of a node at i is (2 * i + 1)
Right child of a node at i is (2 * i + 2)
Parent is (i - 1) / 2
*/

#include <stdio.h>
#include <stdlib.h>

typedef struct heap{
    int currentSize, capacity;
    int *arr;
}heap;

heap * createHeap(int capacity) {
    heap *h = (heap *)malloc(sizeof(heap));
    h -> arr = (int *)malloc(capacity * sizeof(int));
    h -> currentSize = -1;
    h -> capacity = capacity;
    return h;
}
/* to initialize an empty heap of a given capacity */

void search(heap *h, int key) {
    int index;
    for (index = 0; index <= h -> currentSize; index ++) {
        if (h -> arr[index] == key) {
            printf("Found at position %d!\n", index + 1);
            return;
        }
    }
    printf("Not found!\n");
}
/* to search if a given element is present in the heap or not */

void swap(int arr[10], int index1, int index2) {
    int temp = arr[index1];
    arr[index1] = arr[index2];
    arr[index2] = temp;
}
/* to swap elements at two positions of array */

void upHeapify(heap *h, int index) {
    int parent = (index - 1) / 2;
    if (h -> arr[parent] < h -> arr[index]) {
        swap(h -> arr, parent, index);
        upHeapify(h, parent);
    }
}
/* moving an element up the heap to satisfy the max heap property */

void insert(heap *h, int value) {
    if (h -> currentSize == h -> capacity - 1) {
        printf("Heap is full. Cannot insert\n");
        return;
    }
    h -> arr[ ++ h -> currentSize] = value;
    upHeapify(h, h -> currentSize);
    printf("Inserted!\n");
}
/* inserting an element into the heap */

void downHeapify(heap *h, int index) {
    int lChild = 2 * index + 1, rChild = 2 * index + 2, largest = index;
    if (lChild <= h -> currentSize && h -> arr[lChild] > h -> arr[largest])
        largest = lChild;
    if (rChild <= h -> currentSize && h -> arr[rChild] > h -> arr[largest])
        largest = rChild;
    if (largest != index) {
        swap(h -> arr, largest, index);
        downHeapify(h, largest);
    }
}
/* moving an element down the heap to satisfy the max heap property */

void extract(heap *h) {
    if (h -> currentSize < 0) {
        printf("Heap is empty. Cannot extract!\n");
        return;
    }
    int root = h -> arr[0];
    h -> arr[0] = h -> arr[h -> currentSize --];
    downHeapify(h, 0);
    printf("Extracted number is %d!\n", root);
}
/* to extract the maximum element(i.e the root) of the max heap  */

void insertExtract(heap *h, int value) {
    if (h -> currentSize < 0 || value > h -> arr[0]) {
        printf("Extracted number is %d!\n", value);
        return;
    }
    printf("Extracted number is %d!\n", h -> arr[0]);
    h -> arr[0] = value;
    downHeapify(h, 0);
    
}
/* to insert an element into the heap and then extract the maximum element */

void display(heap *h) {
    for (int index = 0; index <= h -> currentSize; index ++) {
        printf("%d ", h -> arr[index]);
    }
    printf("\n");
}
/* to display the min heap */

int main() {
    int choice, capacity;
    printf("Enter capacity of maxHeap:\n");
    scanf("%d", &capacity);
    heap *h = createHeap(capacity);
    do {
        printf("1. Insert\n2. Extract\n3. Insert and Extract\n4. Display\n5. Search\n6. Exit\nEnter your choice:\n");
        scanf("%d", &choice);
        switch (choice) {
            case 1: { 
                int num;
                printf("Enter number to be inserted:\n");
                scanf("%d", &num);
                insert(h, num);
                break;
            }
            case 2: {
                extract(h);
                break;
            }
            case 3: {
                int num;
                printf("Enter number to be inserted:\n");
                scanf("%d", &num);
                insertExtract(h, num);
                break;
            }
            case 4: {
                printf("The maxHeap is:\n");
                display(h);
                break;
            }
            case 5: {
                int num;
                printf("Enter the number to be searched:\n");
                scanf("%d", &num);
                search(h, num);
                break;
            }
            case 6: { 
                printf("Exiting\n");
                break;
            }
            default: {
                printf("Invalid choice. Exiting\n");
                break;
            }
        }
    } while( choice > 0 && choice <= 5);
}

/*
Sample I/O:
Heap capacity: 10
insert 5
display: 5
insert 8
display: 8 5
insert 11
display: 11 5 8
extract: 11
display: 8 5
search 11: Not found!
insert and extract 15: 15
display: 8 5
exit

Time Complexities:

insert - O(log(n))
extract - O(log(n))
insert extract - O(log(n))
display - O(n)
search - O(n)

Space Complexities:

insert - O(1)
extract - O(1)
insert extract - O(1)
display - O(1)
search - O(1)
*/

<|start_filename|>Java/cp/CountAnagrams.java<|end_filename|>
/**
 * Count Occurrences of Anagrams
 * Java program to find the count of occurrences of anagrams
 * of an entered word, in an entered text (given that
 * length of word <= length of text). Both Strings contain
 * only lower case alphabets. 
 */

import java.io.*;
public class CountAnagrams {
    
    private static int countAnagrams(String text, String word) {

        //Integer arrays to store count of characters in word and text
        int wordCharCount[] = new int[26];
        int textCharCount[] = new int[26];
 
        int len = word.length(); 
        for(int i=0; i<len; i++) {
            wordCharCount[word.charAt(i) - 'a']++;
            
            //To obtain count of each character in first window of text
            //The size of window is the length of word
            textCharCount[text.charAt(i) - 'a']++; 
        }

        //If current window of text and given word are anagrams, difference
        //will be 0. Non-zero difference indicates that the count of atleast
        //one of the 26 characters in not equal in text and word.
        int difference = 0;
        for(int i=0; i<26; i++) {
            difference += Math.abs(wordCharCount[i] - textCharCount[i]); 
        }

        //For first window
        int anagramCount = 0; 
        if(difference == 0)
            anagramCount++;

        //To obtain value of difference for each subsequent window of size len
        for(int i=len; i<text.length(); i++) {

            //Previous value associated with character that has exited window 
            //is subtracted. This character's count is updated and the new value 
            //of difference in added to overall difference.  
            difference -= Math.abs(wordCharCount[text.charAt(i-len)-'a'] - 
                                textCharCount[text.charAt(i-len)-'a']);
            textCharCount[text.charAt(i-len) - 'a']--; 
            difference += Math.abs(wordCharCount[text.charAt(i-len)-'a'] - 
                                textCharCount[text.charAt(i-len)-'a']);

            //Previous value associated with character that has entered the window 
            //is subtracted. This character's count is updated and the new value 
            //of difference in added to overall difference.
            difference -= Math.abs(wordCharCount[text.charAt(i)-'a'] - 
                                textCharCount[text.charAt(i)-'a']);
            textCharCount[text.charAt(i) - 'a']++; 
            difference += Math.abs(wordCharCount[text.charAt(i)-'a'] - 
                                textCharCount[text.charAt(i)-'a']);

            if(difference == 0)
                anagramCount++; 
        }

        return anagramCount; 
    }
    public static void main(String[] args) throws IOException {
        InputStreamReader read = new InputStreamReader(System.in);
	    BufferedReader buf = new BufferedReader(read); 

        //Taking input from user
        System.out.println("Enter the text String: ");
	    String text = buf.readLine().trim(); 
        System.out.println("Enter the word whose anagrams need to be counted: ");
	    String word = buf.readLine().trim(); 

        System.out.println("Number of anagrams: " + countAnagrams(text, word)); 
    }

}

/*
    Time complexity: O(N)
    Space complexity: O(1) (as two arrays of fixed size 26 are being used)

    TEST CASES

    INPUT
    Enter the text String: 
    trfororfideriorofrufrx
    Enter the word whose anagrams need to be counted: 
    for
    OUTPUT
    Number of anagrams: 5

    INPUT
    Enter the text String: 
    timetimetime
    Enter the word whose anagrams need to be counted: 
    time
    OUTPUT
    Number of anagrams: 9

 */


<|start_filename|>C-Plus-Plus/search/Staircase_Search.cpp<|end_filename|>
/*
Search for key in row-wise and column-wise sorted matrix

Staircase Search Method:

In a sorted matrix, consider the top right corner. If we go down then the value increases
and if we go left then the value decreases.

Time Complexity: O(max(n, m))
Auxiliary Space: O(1)
*/

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

void staircase_search(int** a, int n, int m, int key) {

	// int n = sizeof(a) / sizeof(a[0]);
	// int m = sizeof(a[0]) / sizeof(a[0][0]);

	// Start from top right corner
	int i = 0, j = m - 1;

	// While we donot find key
	while (a[i][j] != key) {

		// If curr value is less
		if (a[i][j] < key) {
			// that means array value must increase, for that we have to go down
			i++;
		}

		// If curr value is greater
		if (a[i][j] > key) {
			// that means array value must decrease, for that we have to go down
			j--;
		}
	}

	// If key is found, then print key
	if (a[i][j] == key) {
		cout << i << " " << j;
	} else {
		cout << "Key not found";
	}
}


int main() {

	// Take in input
	int n, m;
	cin >> n >> m;
	int key; cin >> key;

	// Declare 2D Matrix dynamically
	int** a = new int*[n];
	for (int i = 0; i < n; i++) {
		a[i] = new int[m] {0};
	}

	// Take matrix input
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			cin >> a[i][j];
		}
	}

	staircase_search(a, n, m, key);

}

/*
Input:
4 4
16
1 4 8 10
2 5 9 15
6 16 18 20
11 17 19 23

Output:
2 1
*/


<|start_filename|>C/cryptography/PlayFairCipher.c<|end_filename|>
/*
  The Playfair cipher( Playfair square ) encrypts pairs of letters (digraphs),
  instead of single letters as in the simple substitution cipher. The Playfair
  is thus significantly harder to break since the frequency analysis used for 
  simple substitution ciphers does not work with it.
*/

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

//Define size for input and key
#define SIZE 100

//This function will form the 5x5 key Matrix    
void keyTable(char key[],int size2,char keyMatrix[5][5]){
      
     int i,j;
     int c = 0;
     char alph[26] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm','n', 'o','p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
     int index[26];
     
     //initializing the array to 0 as it stores garbage values
     for(int z=0;z<26;z++){
         index[z] = 0;
     }

     int hash[size2]; 
     //marking the alphabets in key
     for(i=0;i<size2;i++){
         if(key[i] != 'j'){
            for(j=0;j<26;j++){
                if(key[i] == alph[j]){
                   index[j] = 2;
                   hash[c] = j;
                   c++;
                }   
            } 
         }   
     } 
     
     //marking alphabetic j
     index[9] = 1;
     i = 0;
     j = 0;

     //adding the marked alphabets  
     for(int k=0;k<size2;k++){
         
         if(index[hash[k]] == 2){
            index[hash[k]] -= 1;
            keyMatrix[i][j] = key[k];
            j++;
            if(j==5){
              i++;
              j=0;
            } 
         }         
     }
     
     //adding the remaining alphabets
     for(int k=0;k<26;k++){
         
         if(index[k] == 0){
            keyMatrix[i][j] = alph[k];
            j++;
            if(j==5){
               i++;
               j=0;
            }
         }
     }

}    

/*this function searches for the characters of the digraph in key matrix 
generated and gives their position*/
int *search(char keyMatrix[5][5],char x,char y){

     static int list[4];

     //replacing j with i   
     if(x == 'j')
         x = 'i';
     else if(y =='j')
         y = 'i';

     //returning the positions of characters through list    
     for(int i=0;i<5;i++){
         for(int j=0;j<5;j++){
             if(keyMatrix[i][j] == x){
                list[0] = i;
                list[1] = j;
             }
             else if(keyMatrix[i][j] == y){
                list[2] = i;
                list[3] = j;
             } 
          }
     }
     return list;        
}    
     
//this function ciphers the plane text      
void cipher(char input[], char keyMatrix[5][5],int size1){
     
     int i = 0;
     int *list;
     //cipher the plain text with the key matrix we built
     while(i<size1){
         list = search(keyMatrix,input[i],input[i+1]);  
         if(list[0] == list[2]){
            input[i]   = keyMatrix[list[0]][(list[1]+1)%5];
            input[i+1] = keyMatrix[list[0]][(list[3]+1)%5];        
         }
         else if(list[1] == list[3]){
            input[i]   = keyMatrix[(list[0]+1)%5][list[1]];
            input[i+1] = keyMatrix[(list[2]+1)%5][list[1]]; 
         }
         else{
            input[i]   = keyMatrix[list[0]][list[3]];
            input[i+1] = keyMatrix[list[2]][list[1]]; 
         }
         i+=2;
     } 

}

//this function will encript the plain-text to cipher in playfail cipher
void playFairCipher(char input[],char key[]){
     
     char keyMatrix[5][5];
     int size1 = strlen(input)-1;
     int size2 = strlen(key)-1;
     
     //we adjust the input plane text to even size
     if(size1%2 != 0 ){
        input[size1++] = 'z';
        input[size1]   = '\0'; 
     }
     
     //generating key table
     keyTable(key,size2,keyMatrix);
     //cipher the plane text
     cipher(input,keyMatrix,size1); 
}

int main(void){

     char input[SIZE];
     printf("Enter the plain-text in small letters :");
     //we take plain text here
     fgets(input,100,stdin);
     printf("Enter the key :");
     char key[SIZE];
     //we take key here
     fgets(key,100,stdin);
     //calling the function to cipher the given plain text 
     playFairCipher(input,key); 

     printf("The Cipher text is :%s\n",input);
     return 0;
}
/*
     Sample I/O :

     Enter the plain-text in small letters :hello
     Enter the key :world
     The Cipher text is :kbekdv
*/


<|start_filename|>Java/Algorithms/Moore_Algorithm.java<|end_filename|>
/*The Boyer–Moore majority vote algorithm is an algorithm for finding the majority of a sequence of elements using linear time and constant space. */


import java.util.*;

public class MajorityVote {

	// naive approach

	public static void check(int arr[]) {
		int count = 0;
		for (int i = 0; i < arr.length - 1; i++) {
			count = 1;
			for (int j = i + 1; j < arr.length; j++) {
				// Counting the number by matching it with other numbers.
				if (arr[j] == arr[i]) {
					count++;
				}
			}
			if (count > arr.length / 2) {
				System.out.println("Number Occuring More than 'n/2'=" + arr[i]);
				System.exit(0);
			}
		}
		System.out.print("NO majority Elements ");
	}

	// using The Boyer–Moore majority vote algorithm
	public static int majority(int arr[], int arrsize) {

		int index = 0, count = 1;
		int i;
		// finding num to check majority
		for (i = 1; i < arrsize; i++) {
			if (arr[index] == arr[i])
				count++;
			else
				count--;
			if (count == 0) {
				index = i;
				count = 1;
			}
		}
		int num = arr[index];
		for (i = 0; i < arrsize; i++)
			if (arr[i] == num)
				count++;
		// checking for majority
		if (count > arrsize / 2)
			return num;
		else
			return -1;
	}

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.println("Enter Number of elements (Eg. 6) : ");
		int element_count = input.nextInt();
		int[] arr = new int[element_count];
		System.out.println("Enter " + element_count + " Numbers:");
		for (int i = 0; i < element_count; i++) {
			// Giving values to array arr
			arr[i] = input.nextInt();
		}

		// Passing array to function
		check(arr);
		// using boyer-moore algorithm
		int result = majority(arr, element_count);
		if (result != -1)
			System.out.println("Majority of a sequence is " + result);

		else
			System.out.println("There is no majority \n");


	}

}


/*Enter Number of elements (Eg. 6) : 
6
Enter 6 Numbers:
5
5
5
5
4
2
Number Occuring More than 'n/2'=5
*/
/*Time Complexity : o(n^2) , Space Complexity : o(1).*/

/*
 * Naive method: 
 * Enter Number of elements : 6 
 * Enter 6 Numbers: 5 5 5 5 4 2
 * Number Occuring More than 'n/2'=5 
 * Time Complexity : o(n^2) , Space Complexity : o(1).
 * 
 * The Boyer–Moore majority vote algorithm: 
 * Enter no of elements:5 
 * Enter elements: 1 1 1 1 2 
 * Majority of arr sequence is 1
 * 
 * Time complexity : O(n) Space complexity: O(1)
 */



<|start_filename|>C-Plus-Plus/heap/heap_implementation.cpp<|end_filename|>
/*
Heap is a binary tree which satisfies two properties:
    1.Structure Property: All levels have maximum number of nodes except possibly the last level. In the last level, all nodes are to the left.
    2.Heap Order Property: (max heap)Key in any node N is greater than or equal to the keys in both children of N.
                           (min heap)Key in any node N is less than or equal to the keys in both children of N.
Representation of heap tree: 
    Sequential representation is good as heap is a complete binary tree. (No wasted array locations)
    We maintain the heap size in a variable. 
    Left child of a node at i is 2i+1 (When using array from index 0)
    Right child of a node at i is 2i+2
    Parent is (i-1)/2

In the following code both max heap and min heap are implemented.
*/
#include<bits/stdc++.h>

using namespace std;
class Maxheap {
  //Pointer to the start of array
  int * heap;
  //For the current size of heap
  int size;
  //The maximum number of nodes it can have
  int capacity;
  public:
    Maxheap(int cap): capacity {
      cap
    }, size {
      0
    } {
      heap = new int[capacity];
    }

  //Returns the index of left child 
  int left_child(int parent) {
    int index_of_left_child = 2 * parent + 1;
    if (index_of_left_child <= size) {
      return index_of_left_child;
    } else {
      return -1;
    }
  }

  //Returns the index of right child 
  int right_child(int parent) {
    int index_of_right_child = 2 * parent + 2;
    if (index_of_right_child <= size) {
      return index_of_right_child;
    } else {
      return -1;
    }
  }

  //Returns the index of parent 
  int parent(int child) {
    return (child - 1) / 2;
  }

  //Method to insert an item into the heap
  void insert_value(int data) {
    if (size == capacity) {
      cout << "Overflow, heap at max capacity" << endl;
      return;
    }
    size++;
    int index = size - 1;
    heap[index] = data;

    //Restoring the max_heap property
    //The new node added must be taken to its correct position based on the heap order property for max heap
    //Move the node up the tree until its less or equal to its parent or it becomes the root node
    while (index > 0 && heap[index] > heap[parent(index)]) {
      swap(heap[index], heap[parent(index)]);
      index = parent(index);
    }
  }

  //Method to delete an item from the heap
  //NOTE: That the element is always deleted from the top of a heap as it gives the maximum element
  int delete_value() {
    if (size == 0) {
      cout << "Underflow, heap is already empty" << endl;
      return -1;
    }
    //Storing the value of the item to be removed
    int max_value = heap[0];
    //Overwriting with the last value
    heap[0] = heap[size - 1];
    //Decreasing size
    size--;
    int index = 0;
    int l, r, largest;
    //Taking the overwritten value to its correct position
    //Move the new node down the tree until it is greater than both of its children
    while (index < size) {
      largest = index;
      l = left_child(index);
      r = right_child(index);
      //Check if the left child is larger than it
      if (l != -1 && heap[l] > heap[index]) {
        largest = l;
      }
      //Check if the right child is also large 
      if (r != -1 && heap[largest] < heap[r]) {
        largest = r;
      }
      //Condition that returns true if the node is larger or equal to both its children
      if (largest == index) break;
      //Move the largest(i.e from left and right child) up
      swap(heap[index], heap[largest]);
      index = largest;
    }
    //Returning the value of deleted item
    return max_value;
  }

  //Level order traversal of heap 
  void print() {
    for (int i = 0; i < size; i++) {
      cout << heap[i] << " ";
    }
    cout << endl;
  }
};

class Minheap {
  int * heap, size, capacity;
  public:
    Minheap(int cap): capacity {
      cap
    }, size {
      0
    } {
      heap = new int[capacity];
    }
  int left_child(int parent) {
    int index_of_left_child = 2 * parent + 1;
    if (index_of_left_child <= size) {
      return index_of_left_child;
    } else {
      return -1;
    }
  }
  int right_child(int parent) {
    int index_of_right_child = 2 * parent + 2;
    if (index_of_right_child <= size) {
      return index_of_right_child;
    } else {
      return -1;
    }
  }
  int parent(int child) {
    return (child - 1) / 2;
  }
  void insert_value(int data) {
    if (size == capacity) {
      cout << "Overflow, heap at max capacity" << endl;
      return;
    }
    size++;
    int index = size - 1;
    heap[index] = data;

    //Restoring the min_heap property
    //Move the node up the tree until it is larger than or equal to its parent node
    while (index > 0 && heap[index] < heap[parent(index)]) {
      swap(heap[index], heap[parent(index)]);
      index = parent(index);
    }
  }

  //Method to delete an item from the heap
  //NOTE: That the element is always deleted from the top of a heap as it gives the minimum element
  int delete_value() {
    if (size == 0) {
      cout << "Underflow, heap is already empty" << endl;
      return -1;
    }
    //Storing the value of the item to be removed
    int min_value = heap[0];
    //Overwriting with the last value
    heap[0] = heap[size - 1];
    //Decreasing size
    size--;
    int index = 0;
    int l, r, smallest;
    //Taking the overwritten value to its correct position
    //Move the node down the tree until it is less than or equal to both its children
    while (index < size) {
      smallest = index;
      l = left_child(index);
      r = right_child(index);
      if (l != -1 && heap[l] < heap[index]) {
        smallest = l;
      }
      if (r != -1 && heap[smallest] > heap[r]) {
        smallest = r;
      }
      if (smallest == index) break;
      swap(heap[index], heap[smallest]);
      index = smallest;
    }
    //Returning the value of deleted item
    return min_value;
  }
  void print() {
    for (int i = 0; i < size; i++) {
      cout << heap[i] << " ";
    }
    cout << endl;
  }
};
int main() {
  int n;
  cout << "Enter the capacity of your heap ";
  cin >> n;
  int choice;
  cout << "Input 1 if you want to use max heap and 2 if min heap: ";
  cin >> choice;
  if (choice == 1) {
    Maxheap my_heap(n);
    int a;
    cout << "Enter the values to be added in heap: ";
    for (int i = 0; i < n; i++) {
      cin >> a;
      my_heap.insert_value(a);
    }
    my_heap.print();
    cout << "Enter 1 to delete from the heap and 2 to exit: ";
    cin >> choice;
    if (choice == 1) {
      my_heap.delete_value();
      cout << "New heap: ";
      my_heap.print();
    }
  } else {
    Minheap my_heap(n);
    int a;
    cout << "Enter the values to be added in heap: ";
    for (int i = 0; i < n; i++) {
      cin >> a;
      my_heap.insert_value(a);
    }
    my_heap.print();
    cout << "Enter 1 to delete from the heap and 2 to exit: ";
    cin >> choice;
    if (choice == 1) {
      my_heap.delete_value();
      cout << "New heap: ";
      my_heap.print();
    }
  }
  return 0;
}
/*

I/O:
Enter the capacity of your heap 6
Input 1 if you want to use max heap and 2 if min heap: 2
Enter the values to be added in heap: 10 15 3 6 1 23
1 3 10 15 6 23
Enter 1 to delete from the heap and 2 to exit: 1
New heap: 3 6 10 15 23

Insertion time Compexity: O(logn) -> Since the height of a binary tree logn we will traverse max logn nodes.
Deletion time Complexity: O(logn) -> Same as insertion

Space Complexity for both: O(1)
*/


<|start_filename|>C-Plus-Plus/cp/check_pangram.cpp<|end_filename|>
/* 
	 A string is a pangram if the string contains all the English alphabet letters.
	 Given a string , the task is to check whether that string is pangram or not.
	 
	 Input: str = “The quick brown fox jumps over the lazy dog”
	 Output: Yes
		
	 Input: str = “We promptly judged antique ivory buckles for the prize”
	 Output: No

*/

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

int pangram(string &str)
{
    //map to store the frequency of each alphabet
    map<char, int> frequency;
    //To count number of alphabets
    int count = 0;
    //If 26 alphabets are not present,pangram is impossible
    if (str.size() < 26)
        return -1;
    else
    {

        for (int i = 0; i < str.size(); i++)
        {
            //Ignore spaces
            if (str[i] == ' ')
                continue;
            //Convert each letter to upper case
            str[i] = toupper(str[i]);
            //If the alphabet is not present in frequency map
            if (!frequency[str[i]])
            {
                //Increase the frequency and the count of alphabets
                frequency[str[i]]++;
                count++;
            }
        }
    }
    //26 means all alphabets are present
    if (count == 26)
        return 1;
    else
        return -1;
}
int main()
{
    cout << "Enter the string:";
    string s;
    //To get the entire string
    getline(cin, s);
    int result = pangram(s);

    if (result == 1)
        cout << "Yes,the string is a pangram";
    else
        cout << "No,the string is not a pangram";

    return 0;
}

/* 
    Input: str = “The quick brown fox jumps over the lazy dog”
    
    Output: Yes
*/

/*

	Time Complexity: O(N), where N is the length of the string.
	Auxiliary Space: O(N),as we have used a map
*/


<|start_filename|>C-Plus-Plus/math/sudoku_solver.cpp<|end_filename|>
/* 
this is a backtracking problem which is used for solving sudoku
in sudoku there should be no repetition of number int same row, same column and same grid which of 3*3 size
*/
#include <bits/stdc++.h>
using namespace std;

// to check whether we can place a particular number in the given cell or not
bool isSafe(int mat[][9], int i, int j, int n, int number){
    /* we will check row and column of a cell whether given number is present or not
     if present then we will return false */
    for(int x=0;x<n;x++){
        if(mat[x][j] == number || mat[i][x] == number){
            return false;
        }
    }

    //sub grid check
    int root = sqrt(n);
    int sx = (i/root)*root;
    int sy = (j/root)*root;
    // iterating the grid
    for(int x=sx;x<sx+root;x++){
        for(int y=sy;y<sy+root;y++){
            if(mat[x][y] == number){
                return false;
            }
        }
    }

    //The number can be placed
    return true;
}

// function to create a sudoku solver
bool sudoku_solver(int mat[][9], int i, int j, int n){
    //base case
    if(i == n){
        // if all the rows are completely filled
        //print the solution
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                cout<<mat[i][j]<<" ";
            }
            cout<<endl;
        }
        return true;
    }

    /*
    if all the columns of a particular row is filled then we will move to next row
    and will start from the 0th column  */
    if(j == n){
       return sudoku_solver(mat,i+1,0,n);
    }
    
    // if the number filled is not 0 then we will skip it move to next column
    if(mat[i][j] != 0){
       return sudoku_solver(mat,i,j+1,n);
    }

    /* recursive case
    fill the current cell with possible options */
    for(int number=1;number<=n;number++){
        if(isSafe(mat,i,j,n,number)){
            // assume that it is correct not at correct position
            mat[i][j] = number;
            bool canBePlaced = sudoku_solver(mat,i,j+1,n);
            if(canBePlaced == true){
                return true;
            }
        }
    }

    //back track here
    mat[i][j] = 0;
    // we were not able to solve this sudoku therefore returned false
    return false;
}

// driver code
int main() {
    int mat[9][9];
    // input size of sudoku board
    int n;
    cin>>n;
    
    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            cin>>mat[i][j];
        }
    }

    //recursive call
    sudoku_solver(mat,0,0,n);
    return 0;
}

/*
Input -
9
5 3 0 0 7 0 0 0 0
6 0 0 1 9 5 0 0 0
0 9 8 0 0 0 0 6 0
8 0 0 0 6 0 0 0 3
4 0 0 8 0 3 0 0 1
7 0 0 0 2 0 0 0 6
0 6 0 0 0 0 2 8 0
0 0 0 4 1 9 0 0 5
0 0 0 0 8 0 0 7 9

Output-
5 3 4 6 7 8 9 1 2
6 7 2 1 9 5 3 4 8
1 9 8 3 4 2 5 6 7
8 5 9 7 6 1 4 2 3
4 2 6 8 5 3 7 9 1
7 1 3 9 2 4 8 5 6
9 6 1 5 3 7 2 8 4
2 8 7 4 1 9 6 3 5
3 4 5 2 8 6 1 7 9

Time-Complexity - O(9^(n*n))
Space-Complexity - O(n*n)
*/


<|start_filename|>Java/Operating-System/banker.java<|end_filename|>
/*
Banker's Algorithm

Banker's Algorithm is a technique used for deadlock avoidance when there are multiple instances of a resource.
The banker's algorithm for deadlock-free resource allocation is one of the basic algorithms in concurrent and distributed systems.
User process may only request one resource at a time. System grants request only if the request will result in a safe state.
A state is considered to be safe if it is possible for all the processes to complete its execution without causing any deadlocks.
An unsafe state is the one in which the processes cannot complete its execution.

The time complexity for n processes and m resources is o(n*n*m).
The space complexity for n processes and m resources is o(n*m).
*/

import java.util.Scanner;

class algorithm {

    void display(int r, int p, int[] avail, int max[][], int need[][], int allocation[][], int res[]) {
        
        //Checking for available resources inline.
        System.out.println("THE MAXIMUM RESOURCES MATRIX IS AS FOLLOWS :");
        System.out.print("   ");
        for (int i = 0; i < r; i++) {
            System.out.print(" " + (i + 1));
        }
        System.out.println(" ");
        System.out.println("_______________________");
        for (int i = 0; i < p; i++) {
            System.out.print("P" + i + "|");
            for (int j = 0; j < r; j++) {
                System.out.print(" " + max[i][j]);
            }
            System.out.println(" ");
        }

        System.out.println(" ");

        System.out.println("THE ALLOCATION MATRIX IS AS FOLLOWS :");
        System.out.print("   ");
        for (int i = 0; i < r; i++) {
            System.out.print(" " + (i + 1));
        }
        System.out.println(" ");
        System.out.println("_______________________");
        for (int i = 0; i < p; i++) {
            System.out.print("P" + i + "|");
            for (int j = 0; j < r; j++) {
                System.out.print(" " + allocation[i][j]);
            }
            System.out.println(" ");
        }
        System.out.println("");


        System.out.print("AVAILABLE ARRAY IS :");
        for (int i = 0; i < r; i++) {
            int sum = 0;
            avail[i] = 0;
            for (int j = 0; j < p; j++) {
                sum = sum + allocation[j][i];
                avail[i] = res[i] - allocation[j][i];
            }
            avail[i] = res[i] - sum;
            System.out.print(avail[i] + "  ");
        }
        System.out.println(" ");
        System.out.println(" ");

        for (int i = 0; i < p; i++) {

            for (int j = 0; j < r; j++) {
                // Need of instance = maxm instance -allocated instance 
                need[i][j] = max[i][j] - allocation[i][j]; 
            }

        }
        System.out.println(" ");
        System.out.println("THE NEED MATRIX IS AS FOLLOWS :");
        System.out.print("   ");
        for (int i = 0; i < r; i++) {
            System.out.print(" " + (i + 1));
        }
        System.out.println(" ");
        System.out.println("_______________________");
        for (int i = 0; i < p; i++) {
            System.out.print("P" + i + "|");
            for (int j = 0; j < r; j++) {
                System.out.print(" " + need[i][j]);
            }
            System.out.println(" ");
        }
    }
    boolean check(int proces[], int avail[], int maxm[][],
        int allot[][], int P, int R, int need[][]) {


        boolean[] finish = new boolean[P];
        
        //for storing the final sequence
        int[] safe = new int[P]; 


        int[] work = new int[R];
        System.out.print("INTIALLY WORK/AVAILABLE     : ");
        for (int i = 0; i < R; i++) {
            work[i] = avail[i];
            System.out.print(work[i] + " ");
        }
        System.out.println(" ");

        // While all processes are not over/system isn't safe run this loop
        int c1 = 0;
        while (c1 < P) {
            boolean found = false;
            for (int p = 0; p < P; p++) {
                //if process is not completed
                if (finish[p] == false) {
                    int j;
                    for (j = 0; j < R; j++)
                        if (need[p][j] > work[j])
                            break;

                    if (j == R) {
                        System.out.print("AFTER EXECUTION OF PROCESS " + p + " : ");
                        for (int k = 0; k < R; k++) {
                            work[k] += allot[p][k];
                            System.out.print(work[k] + " ");
                        }
                        System.out.println("");


                        safe[c1++] = p; 

                        //make finish[i]=true
                        finish[p] = true;

                        found = true;
                    }
                }
            }

            //if process is not safe
            if (found == false) {
                System.out.print("SYSTEM IS NOT IN SAFE STATE");
                return false;
            }
        }
        System.out.println(" ");
        System.out.println("SYSTEM IS IN SAFE STATE");
        System.out.println(" ");
        System.out.println("SAFE SEQUENCE IS : ");
        //to print the sequence
        for (int i = 0; i < P; i++) {
            System.out.print("P" + safe[i]);
            if (i != P - 1)
                System.out.print(" -> ");
        }
        System.out.println(" ");
        return true;
    }
}

// main public class
public class banker 
{
    // Driver code 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int choice = 0;
        int p = 0;
        int r = 0;

        System.out.println("ENTER THE NUMBER OF PROCESSES");
        do {
            p = sc.nextInt();
            if (p < 0) {
                System.out.println("THE VALUE CANNOT BE NEGATIVE. TRY AGAIN");
            }
        } while (p < 0);
        int pro[] = new int[p];

        for (int i1 = 0; i1 < p; i1++) {
            pro[i1] = i1;
        }

        System.out.println(" ");
        System.out.println("ENTER THE TOTAL NUMBER OF RESOURCES");
        do {
            r = sc.nextInt();
            if (r < 0) {
                System.out.println("THE VALUE CANNOT BE NEGATIVE. TRY AGAIN");
            }
        } while (r < 0);
        int res[] = new int[r];
        
        // array defines the maximum demand of each process in a system.
        int max[][] = new int[p][r];
        
        //array about the number of resources of each type currently allocated to each process.
        int allocation[][] = new int[p][r];
        
        int need[][] = new int[p][r];
        //available/work array
        int[] avail = new int[r]; 
        
        //array about how many more resources can be allocated in the future
        int[] req = new int[r];
        
        //create the object
        algorithm al1 = new algorithm(); 

        do {
            System.out.println("PRESS 1 TO ACCEPT DATA");
            System.out.println("PRESS 2 TO DISPLAY THE MATRICES ");
            System.out.println("PRESS 3 TO DISPLAY SEQUENCES ");
            System.out.println("PRESS 4 FOR RESOURCE REQUEST");
            System.out.println("PRESS 0 TO EXIT");
            System.out.println(" ");
            choice = sc.nextInt();
            switch (choice) {
                case 1:
                    System.out.println(" ");

                    for (int i1 = 0; i1 < r; i1++) {
                        System.out.println("ENTER THE TOTAL NUMBER OF INSTANCES FOR RESOURCE " + (i1 + 1) + " ");
                        res[i1] = sc.nextInt();
                    }

                    System.out.println(" ");

                    System.out.println("ENTER THE MATRIX FOR MAXIMUM RESOURCES ");
                    for (int i = 0; i < p; i++) {
                        for (int j = 0; j < r; j++) {
                            max[i][j] = sc.nextInt();
                        }
                    }


                    System.out.println(" ");
                    System.out.println("ENTER THE MATRIX FOR RESOURCES WHICH ARE ALLOCATED");
                    for (int i = 0; i < p; i++) {
                        for (int j = 0; j < r; j++) {
                            allocation[i][j] = sc.nextInt();
                        }
                    }

                    System.out.println("  ");

                    break;

                case 2:
                    al1.display(r, p, avail, max, need, allocation, res);
                    System.out.println("");

                    break;

                case 3:

                    al1.check(pro, avail, max, allocation, p, r, need);
                    System.out.println(" ");

                    break;

                case 4:
                    int allocation1[][] = new int[p][r];
                    int need1[][] = new int[p][r];
                    int[] avail1 = new int[r]; //available/work array

                    int flag = 0;
                    System.out.println("ENTER PROCESS NUMBER");
                    int p1 = sc.nextInt();
                    System.out.println("ENTER RESOURCES REQUESTED BY P" + p1);
                    for (int i = 0; i < r; i++) {
                        req[i] = sc.nextInt();
                    }
                    for (int i = 0; i < r; i++) {
                        //check if available resources are greater than required
                        if (avail[i] < req[i]) 
                        {
                            flag = 1;
                            break;
                            
                        } //check if needed resources are greater than required
                        else if (req[i] > need[p1][i]) 
                        {
                            flag = 1;
                            break;
                        }
                    }
                    if (flag == 1) {
                        System.out.println("THE REQUEST FOR PROCESS P" + p1 + " CANNOT BE GRANTED");
                        System.out.println("  ");
                    } else {
                        allocation1 = allocation;
                        need1 = need;
                        avail1 = avail; //available/work array	

                        for (int i = 0; i < r; i++) {
                            allocation1[p1][i] = allocation1[p1][i] + req[i];
                        }

                        for (int i = 0; i < r; i++) {
                            need1[p1][i] = need1[p1][i] - req[i];
                        }

                        for (int i = 0; i < r; i++) {
                            avail1[i] = avail1[i] - req[i];
                        }

                        al1.check(pro, avail1, max, allocation1, p, r, need1);
                        System.out.println(" ");

                    }
                    System.out.println("  ");
                    break;

                case 0:
                    System.out.println(" ");
                    System.out.println("THANK YOU !");
                    System.out.println();
                    break;
                default:
                    System.out.println("WRONG CHOICE");
                    System.out.println(" ");
                    break;
            }
        } while (choice != 0);

    }
}


<|start_filename|>C-Plus-Plus/cp/matrix's_principal_seconday_diagonal_sum.cpp<|end_filename|>
/*
Given a N * N square matrix. A matrix has two diagonals. One diagonal is principal which starts from the first row, first column
another diagonal is secondary which starts from the first row, last column
Find the sum of it's principal and secondary diagonal elements.
*/

#include <bits/stdc++.h>
using namespace std;
int ar[500][500];

/* From this get_principal_secondary_diagonal_sum() function we will compute matrix's principal,secondary diagonal sum */
int get_principal_secondary_diagonal_sum(int N)
{
    int principal_secondary_diagonal_sum = 0;
    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < N; j++)
        {
            if(i == j)
            {
                /* here principal diagonal element is at cell [1 , 1] , [0 ,0],
                [2 , 2] like this goes on
                that's why condition is i == j
                 */
                principal_secondary_diagonal_sum += ar[i][j];
            }
            else if( (i + j == (N - 1)) and i != j )
            {
                /* here secondary diagonal element is at cell [1 , 4] , [2 ,3],
                [3 , 2] like this goes on
                that's why condition is i + j == ( n - 1) and i != j
                */
                principal_secondary_diagonal_sum += ar[i][j];
            }
        }
    }
    return principal_secondary_diagonal_sum;
}

int main()
{
    cout << "Enter the size of the matrix : \n";
    int N;
    cin >> N;
    cout << "Enter matrix elements :\n";
    for (int i = 0; i < N; i++)
    {
        for(int j = 0; j < N; j++)
        {
            cin >> ar[i][j];
        }

     }
     int principal_secondary_diagonal_sum  = get_principal_secondary_diagonal_sum(N);
     cout << "Sum of Principal and Secondary Diagonal of this matrix is : ";
     cout << principal_secondary_diagonal_sum << endl;
}

/*
Standard Input and Output

Enter the size of the matrix :
4
Enter matrix elements :
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Sum of Principal and Secondary Diagonal of this matrix is : 68

Time Complexity : O( N * N )
Space Complexity : O( 1 )

*/


<|start_filename|>C-Plus-Plus/cp/largest_subarray_of_sum_k.cpp<|end_filename|>
/**
 * Longest Subarray Having Sum k
 * Given an array of integers, find the length of the longest sub-array 
 * having sum equal to the given value k.
 */

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

int LongestSubarraySum(int len, int arr[], int k)
{
    //Variable to store length of longest subarray with sum k
    int length = INT_MIN;
    //2 pointers indicating current window
    int start = 0, end = 0;
    //store cumulative sum as we traverse the array
    long long sum = 0;
    while (end < len) {
        sum = sum + arr[end];
        //If k is greater than sum then increase the size of current window
        if (sum < k)
            end++;
        //Checking if sum equals k then update length as max of window size and length
        //then increase window size
        else if (sum == k) {
            length = max(length, end - start + 1);
            end++;
        }
        //Check if cumulative sum is more than k then remove element
        //at start of current window until it is greater than k
        else if (sum > k) {
            while (sum > k) {
                sum = sum - arr[start];
                start++;
            }
            end++;
        }
    }

    return length;
}

int main()
{
    //Taking input from user
    int len;
    cout << "Enter length of array of integers: ";
    cin >> len;
    int arr[len];
    cout << "Enter array of integers: ";
    for (int i = 0; i < len; i++)
        cin >> arr[i];
    int k;
    cout << "Enter sum: ";
    cin >> k;
    cout << "Length of Longest Subarray having Sum " << k << ": ";
    cout << LongestSubarraySum(len, arr, k);
}

/*
	Test Cases:

    INPUT:
	Enter length of array of integers: 8
	Enter array of integers: 5 4 1 1 1 2 3 1
	Enter sum: 5
	OUTPUT:
    Length of Longest Subarray having Sum 5: 4

	INPUT:
	Enter length of array of integers: 6
    Enter array of integers: -5 8 -14 2 4 12
    Enter sum: -5
	OUTPUT:
	Length of Longest Subarray having Sum -5: 5


	Time complexity: O(N)
	Space complexity: O(1)

 */


<|start_filename|>C/ds/QueueImplementationWithList.c<|end_filename|>
#include <stdio.h>
#include <stdlib.h>
typedef struct Queue
{
    struct Queue *head;
    struct Queue *next;
    int value;
    int size;
}Queue;
/*
 * create empty queue
*/
Queue *create_queue()
{
    Queue *ret = (Queue*) malloc(sizeof(Queue));
    ret->head = ret->next = NULL;
    ret->size = 0;
    return ret;
}
void enqueue(Queue *q, int value)
{
    Queue *cur = q;
    // queue is empty, initialize head
    if( !q->head )
    {
        Queue *head = (Queue*) malloc(sizeof(Queue));

        if( !head )
        {
            perror("create queue");
            exit(-1);
        }
        head->value = value;
        head->next = NULL;
        cur->head = head;
        cur->size++;
    }
    else
    {
        // go until end of queue
        cur = cur->head;
        while( cur->next )
        {
            cur = cur->next;
        }
        // reached end of queue
        Queue *temp = (Queue*) malloc(sizeof(Queue));
        temp->value = value;
        temp->next = NULL;
        // make last node to point to temp - add the link
        cur->next = temp;
        q->size++;      // increase size
    }
    return;
}
int dequeue(Queue *q)
{
    Queue *cur = q->head;
    int ret = cur->value;
    q->size--;
    // advance the head of the queue
    q->head = q->head->next;
    // free memory
    free(cur);
    cur = NULL;
    return ret;
}
void print_queue(Queue *q)
{
    Queue *cur = q->head;
    printf("[");
    while( cur )
    {
        printf(" %d ", cur->value);
        cur = cur->next;
    }
    printf("]\n");
    return;
}
int main()
{
    Queue *q1 = create_queue();
    enqueue(q1, 5);
    enqueue(q1, 9);
    print_queue(q1);
    int d = dequeue(q1);
    printf("d is %d\n", d);
    print_queue(q1);
    enqueue(q1, 45);
    print_queue(q1);
    return 0;
}


<|start_filename|>C-Plus-Plus/dp/number_of_binary_trees.cpp<|end_filename|>
/* 
This program finds the number of binary trees given the length of the preorder sequence = n.
A tree is an acyclic graph . A binary tree is a tree where each node has 0, 1 or 2 children. 
Preorder traversal means traversing a tree in the following order : Root - Left child - Right child.  
    
We use the dynamic programming approach where our root is fixed and the rest of the n-1 nodes
are split as left and right children. Hence, we calculate the number of binary trees possible
while exploring splits varying from 0 to n-1.
    
Time Complexity - O(n^2)
Space Complexity - O(n)
    
Note:- The approach is similar to finding the nth catalan number.
*/

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

typedef long long int lli;

lli PossibleBinaryTrees(int number)
{
    lli *table=(lli *)malloc((number+1)*sizeof(lli));
    
    //Since number of trees that can be formed for n=0/1 is 1
    table[0]=1,table[1]=1;    
    
    //Calculating possible number of binary trees for all i<=n and storing them for future use-Tabulation Method
    for(int loop1=2;loop1<=number;loop1++)                      
    {
        table[loop1]=0;
        
        //We loop over the possible splits from 0 to i-1
        for(int loop2=0;loop2<loop1;loop2++)                       
        {
            table[loop1]+=(table[loop2]*table[loop1-loop2-1]);
        }
    }
    
    lli answer=table[number];
    free(table);
    return answer;
}

//Driver function
int main()                                                      
{
    //Enter length of preorder sequence
    int number;                                                 
    cin>>number;
    cout<<PossibleBinaryTrees(number)<<endl;
    return 0;
}
/* 
Sample input:-
n = 5;
Output = 42;
*/


<|start_filename|>C-Sharp/sort/RadixSort.cs<|end_filename|>
using System;

/*  Radix sort is a sorting technique that sorts the elements by 
    first grouping the individual digits of the same place value. 
    Then, sort the elements according to their increasing/decreasing order.
*/

 class RadixSort{
  static void radixSort(int[] arr){
    int size = arr.Length;
    int max_element = arr[0];
    
    for (int i=1; i<size; i++){  
      if(max_element < arr[i])
        max_element = arr[i];
    }

    for (int x = 1; max_element/x > 0; x *= 10){ 
      countingSort(arr, x); 
      }
  }

 
  static void print_arr(int[] arr){ 
    int size = arr.Length; 
   
    Console.Write("\n"); 
  } 
  
    static void countingSort(int[] arr, int x){   
    int size = arr.Length;    
    int[] new_arr = new int[size];
    
    int[] fr = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

    for(int i = 0; i < size; i++){
      fr[(arr[i]/x)%10]++;
      }

    for (int i = 1; i < 10; i++){ 
      fr[i] += fr[i - 1];     
      }

    for (int i = size - 1; i >= 0; i--){ 
      new_arr[fr[(arr[i]/x)%10] - 1] = arr[i]; 
      fr[(arr[i]/x)%10]--; 
    } 
  
    for (int i = 0; i < size; i++){ 
      arr[i] = new_arr[i]; 
     } 
  }


  public static void Main(string[] args){
    int n = Convert.ToInt32(Console.ReadLine());
    int[] a = new int[n];
   
   int i,j;
    for(i=0; i<n;i++){
        Console.Write("Element {0} : ", i);
        a[i] = Convert.ToInt32(Console.ReadLine());
    }
    Console.Write("Unsorted array: ");
    for (j=0; j<n; j++){
      Console.Write(a[j] + " "); 
    } 
      
    Console.Write("\n");
    
    radixSort(a);
    
    Console.Write("Sorted array: ");
     for (j=0; j<n; j++){
      Console.Write(a[j] + " "); 
      } 
  }
}

/* Input
    6                                                                                         
    Element 0 : 87                                                                            
    Element 1 : 12                                                                            
    Element 2 : 4                                                                             
    Element 3 : 76                                                                            
    Element 4 : 1                                                                             
    Element 5 : 23 
*/

/* Output
    Unsorted array: 87 12 4 76 1 23 
    Sorted array: 1 4 12 23 76 87 
*/

/* Time Complexity = O(d(n+k)) 
        where k= largest element in the array
              n= number of elements in the array
              d = base of numbers(decimal base system =10)
*/




<|start_filename|>C/math/factorial.c<|end_filename|>
// C Program to find the Factorial of a number
#include <stdio.h>

long long unsigned int factorial(int num)
{
    if (num == 0)
        return 1;
    return num * factorial(num - 1);
}

int main()
{
    int num;
    printf("\nEnter the number: ");
    scanf("%d", &num);

    // Factorials are undefined for negative integers
    if (num < 0)
    {
        printf("Factorials are undefined for negative integers");
    }

    // Call the function
    long long unsigned int fact = factorial(num);
    // Print the obtained factorial
    printf("The factorial of the given number is: %lld", fact);
    return 0;
}

/*

Time Complexity- O(num), where 'num' is the given number
Space Complexity- O(1)

SAMPLE INPUT AND OUTPUT

SAMPLE I

Enter the number: 12
The factorial of the given number is: 479001600

*/


<|start_filename|>Java/search/Binary_search.java<|end_filename|>
import java.util.*;

public class Binary_search {
	//binary search algorithm explanation in its readme file in wiki section
	//this can performed recursively also
	//The average and worst case time complexity is O(log n)
	//The space complexity is O(1).
	static int binSearch(int[] a, int l, int h, int key) {
		while (l<= h) {
			int mid = (l + h) / 2;
			if (key == a[mid])
				return mid + 1; //index starts from zero so position has to be incremented by one.
			else if (key < a[mid])
				h = mid - 1;
			else
				l = mid + 1;
		}
		return -1;
	}
	public static void main(String[] args) {
		//to perform binary search the array must be in sorted order
		Scanner sc = new Scanner(System.in);
		System.out.print("Enter the length of the array: ");
		int length = sc.nextInt();
		int arr[] = new int[length];
		System.out.print("Enter array values: ");
		for (int i = 0; i < length; i++) {
			arr[i] = sc.nextInt();
		}
		// to sort the array if not sorted
		Arrays.sort(arr);
		System.out.print("Enter the value whose index needs to be searched: ");
		int value = sc.nextInt();

		int index = binSearch(arr, 0, length - 1, value);
		if (index == -1)
			System.out.println("Element Not found");
		else
			System.out.println("Index of " + value + " is: " + index);
	}
}
/*
Input:
Enter the length of the array: 5
Enter array values: 2 3 4 5 6
Enter the value whose index needs to be searched: 4
Output:
Index of 4 is: 3
*/


<|start_filename|>C/operating_system/bankers.c<|end_filename|>
/*    Some information about Banker's algorithm :-

       *  The Banker’s algorithm is a resource allocation and deadlock avoidance algorithm developed by <NAME>.
       *  The time complexity of the Banker's algorithm as a function of the number n of processes and m of resources is o(n*n*m).
       *
      Let Pbe number of process and R be number of resources.
       *  BOOLEAN function SAFESTATE is -- Determines if current state is safe
        { UNSAFE : boolean;
          AVAILABLE : array[1..R] of INTEGER
          FINISH : array[1..P] of boolean = [false, ..,false];
          I : integer;

        repeat
            UNSAFE = TRUE;
            for I = 1 to P do
                if ((not FINISH[i]) and
                    NEEDi <= WORK) then {
                    WORK = WORK + ALLOCATION_i;
                    FINISH[i] = true;
                    UNSAFE = false;
                    }
                until NOCHANGE;
            return (FINISH == (true, .., true));
       }
*/

#include <stdio.h>

// Calculating the remaining need of the resources for each process.
void CalculateRemainingNeed(int process, int resource, int need[process][resource], int allocated[process][resource], int max[process][resource]){
    int i,j;
    for(i = 0; i < process; ++i){
        for(j = 0; j < resource; ++j){
            need[i][j] = max[i][j] - allocated[i][j];
        }
    }
}
// Checking whether all the processrocess can be executed.
int CheckDeadlock(int process, int resource, int need[process][resource], int avail[], int allocated[process][resource], int finish[], int seq[]){
    int count = 0, i, j, k, unsafe = 1;
    while (count != process){
        unsafe = 1;
        for(i = 0; i < process; ++i){
            // Checking whether particular process is executed or not.
            if (finish[i] == 0){
                for(j = 0; j < resource; ++j){
                    // Checking whether the need of any process is greater than availability.
                    if (need[i][j] > avail[j]){
                        break;
                    }
                }
                // If all the resources are available for any process.
                if (j == resource){
                    for (k = 0; k < resource; ++k)
                        avail[k] = avail[k] + allocated[i][k];
                    finish[i] = 1;
                    seq[count] = i+1;
                    count++;
                    unsafe = 0;
                }
            }
        }
        if (unsafe == 1)
            return unsafe;
    }
}

void DisplaySafeSequence(int seq[], int process){
    int i;
    printf("The safe sequence is:\n");
    for(i = 0; i < process - 1; ++i)
        printf("P%d->", seq[i]);
    printf("P%d\n", seq[process-1]);
}

int main() {

    int process, resource, i, j;

    printf("Enter number of process\n");
    scanf("%d", &process);

    printf("Enter the number of resources\n");
    scanf("%d", &resource);

    int allocated[process][resource], max[process][resource], avail[resource], need[process][resource], finish[process], seq[process];

    printf("Enter the available resources\n");
    for(i = 0; i < resource; ++i){
        scanf("%d", &avail[i]);
    }

    printf("Enter the allocated resources to each process\n");
    for(i = 0; i < process; ++i){
        for(int j = 0; j < resource; ++j){
            scanf("%d", &allocated[i][j]);
        }
    }

    printf("Enter the maximum demand of resources by each process\n");
    for(i = 0; i < process; ++i){
        for(j = 0; j < resource; ++j){
            scanf("%d", &max[i][j]);
        }
    }

    /*
        Finish matrix is used to keep track of the executed process.
        Initializing with value '0' which means no process is executed yet.
    */
    for(i = 0; i < process; ++i){
        finish[i] = 0;
    }

    CalculateRemainingNeed(process, resource, need, allocated, max);

    int unsafe = CheckDeadlock(process, resource, need, avail, allocated, finish, seq);

    // Checking if there is any process which will not able to execute.
    if (unsafe == 1)
        printf("The sequence is unsafe. Deadlock will occur.\n");
    else
        DisplaySafeSequence(seq, process);

    return 0;
}


/*
        OUTPUT
Enter number of process
5

Enter the number of resources
3

Enter the available resources
2 1 0

Enter the allocated resources to each process
1 1 2
2 1 2
4 0 1
0 2 0
1 1 2

Enter the maximum demand of resources by each process
4 3 3
3 2 2
9 0 2
7 5 3
1 1 2

The safe sequence is:
P2->P5->P1->P3->P4

*/


<|start_filename|>Java/cp/NQueens.java<|end_filename|>
/**
N-Queens problem is a famous problem
The paradigm used to solve the problem is backtracking
The problem is to find a way to place n queens on nXn board
such that no queen can kill the other
**/

import java.io.*;
import java.util.*;

public class NQueens {
    
  public static void solve(boolean[][] board, boolean[] cols, 
    boolean[] ndiag, boolean[] rdiag, int row, String asf) {
        
        if(row == board.length) {
            System.out.println(asf+'.');
            return;
        }
        
        for(int col=0; col<board.length; col++) {
            if(cols[col] == false && ndiag[row+col] == false && 
                rdiag[row-col+board.length-1] == false) {
                    // place the queen
            	    // let the column get occpied
            	    // correspondingly ndiag and rdiag
            	    // matrices are populated
                    cols[col] = true;
                    ndiag[row+col] = true;
                    rdiag[row-col+board.length-1] = true;
                    board[row][col] = true;
                    solve(board, cols, ndiag, rdiag, row+1, asf+row+'-'+col+", ");
                    // backtrack
                    // remove all the markings 
                    // made in the above step
                    cols[col] = false;
                    ndiag[row+col] = false;
                    rdiag[row-col+board.length-1] = false;
                    board[row][col] = false;
                }
        }
    }

  public static void main(String[] args) throws Exception {
    Scanner scn = new Scanner(System.in);
    int n = scn.nextInt();
    boolean[][] board = new boolean[n][n];
    
    boolean[] cols = new boolean[n];
    boolean[] ndiag = new boolean[2*n-1];
    boolean[] rdiag = new boolean[2*n-1];
    
    solve(board, cols, ndiag, rdiag, 0, "");
  }

}

/**

Input :
4
Output :
0-1, 1-3, 2-0, 3-2, .
0-2, 1-0, 2-3, 3-1, .

Space Complexity : O(n^2)
Time Complexity : upperbounded by O(n^n)

**/





<|start_filename|>C-Plus-Plus/graphs/kahns_algorithm.cpp<|end_filename|>
/*
The algorithm gives us a topological sort for the given directed graph. If the graph is cyclic it returns as no topological sort for the graph is possible.

Steps:

1: Firstly compute in-degree (number of incoming edges) for each of the vertex present in the DAG and initialize the count of visited nodes as 0.

2: Pick all the vertices with in-degree as 0 and add them into a queue.

3: Remove a vertex from the queue and then increment count of visited nodes by 1.
Decrease in-degree by 1 for all its neighboring nodes.
If in-degree of any neighboring node is reduced to zero, then add that node to the queue.

4: Repeat 3 until the queue is empty.

5: If count of visited nodes is not equal to the number of nodes in the graph then the topological sort is not possible for the given graph.
*/

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

void kahn_topological_sort(vector <int> adj[], int n){
    //Array for keeping a track for indegree of all nodes
    int in_degree[n]; 
    memset(in_degree,0,sizeof(in_degree));
    queue <int> q; 
    //Computing in degree of each node
    for(int i=0;i<n;i++){
        for(auto s: adj[i]){
            in_degree[s]++;
        }
    }
    //Pushing nodes with in degree zero into the queue
    for(int i=0;i<n;i++){
        if(!in_degree[i]){
            q.push(i);
        }
    }
    int count_of_visited_nodes{};
    //This vector will store the order
    vector <int> topological_order; 
    while(!q.empty()){
        //Storing the front i.e. the first node of the queue in curr
        int curr = q.front();
        //Pushing the node curr into the order
        topological_order.push_back(curr);
        //Poping that node from the queue
        q.pop();
        //Traversing to all adjacents of the curr node and decreasing there indegree by one
        for(auto s: adj[curr]){
            in_degree[s]--;
            //If any node's indegree becomes zero pushing it into the queue
            if(!in_degree[s]) q.push(s);
        }
        //increasing the count of visited nodes
        count_of_visited_nodes++;
    }
    if(count_of_visited_nodes!=n){
        cout<<"No topological sort possible, there exists a cycle"<<endl;
    }
    else{
        cout<<"Topological Order:"<<endl;
        for(auto s:topological_order){
            cout<<s<<" ";
        }cout<<endl;
    }
}
int main(){
    int n,m; cin>>n>>m;
    vector <int> adj[n];
    int a,b;
    for(int i=0;i<m;i++){
        cin>>a>>b;
        adj[a].push_back(b);
    }
    kahn_topological_sort(adj,n);
    return 0;
}
/*
Test cases:

1.
Input:->
5 7
0 1
0 2
0 3
1 3
1 4
4 3
Output:->
Topological Order:
0 1 2 4 3

Time complexity: O(n+m) //Order of Sum of number of edges and vertices

Auxillary Space: O(n)   //Order of number of vertices

*/


<|start_filename|>Go/search/Jump_Search/JumpSearch.go<|end_filename|>
/* Jump search is a searching algorithm for sorted arrays. In this algorithm,
we jump ahead by a fixed number of steps each time, instead of traversing the
whole array. Suppose array is of size 10, and jump is 3, then, we check array[0],
array[3], array[6], array[9]. We get an interval in which we are searching for
is present. We then traverse the interval lineally to get the exact index of the
element. The optimal jump size of sqrt(size of the array). This can be easily proved.

REMEMBER : If the array is not sorted, jump search won't work.*/

package main

import (
	"fmt"
	"math"
)

/* This is the function which implements the jump search algorithm.
The input to the function is the sorted array, the element which we
are looking for and the size of the sorted array.*/
func search(array []int, element, n int) int {

	//Size to jump
	var jump int = int(math.Sqrt(float64(n)))

	initial := 0

	/*Ensures that value of jump does not cross the 
	size of the array. And also checks if the value
	at that jump is less than element or not.*/
	for jump < n && array[jump] <= element {

		/*This keeps track of the lower bound of the
		interval in which element could be present*/
		initial = jump

		//Everytime we increase jump by sqrt(size of array)
		jump = jump + int(math.Sqrt(float64(n)))

		/*If jump exceeds the size of the array, then we
		set jump as the last index  of array + 1*/
		if(jump >= n) {
			jump = n
		}
	}

	/*As the while loop ends, we are sure that the element, if
	present in the array is present between index initial and jump.
	We linearlly travere that interval to look for the element*/
	for i := initial; i <= jump - 1; i++ {

		//If we find the element, we return the index in the array
		if(array[i] == element) {
			return i
		} else {
			continue
		}
	}
	//We reuturn -1 if element is not found in the array
	return -1
}

func main() {

	// Take length of array as input from the user
	fmt.Print("Enter the size of the array: ")
	var n int
	fmt.Scan(&n)

	// Take elements of array as input from the user
	fmt.Print("Enter ", n, " numbers in increasing order followed by spaces : ")
	array := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&array[i])
	}

	// Take element to search as input from the user
	fmt.Print("Enter the element to search: ")
	var element int
	fmt.Scan(&element)

	// Call search function to find the index
	var index int = search(array, element, n)

	/* If index is -1, the element is not present
	Else print index of element in the array*/
	if(index == -1) {
		fmt.Print("\nThe element ", element, " is not present in the array.\n")
	} else {
		fmt.Print("\nThe element ", element, " is present at ", index, " index in the array.\n");
	}
}

/* Sample I/O:

a)

Enter the size of the array: 6
Enter 6 numbers in increasing order followed by spaces : -3 -1 3 5 6 7
Enter the element to search: 5

The element 5 is present at 3 index in the array.

b)

Enter the size of the array: 6
Enter 6 numbers in increasing order followed by spaces : -2 -1 4 6 8 10
Enter the element to search: 5

The element 5 is not present in the array.

*/


<|start_filename|>Julia/math/magic_number.jl<|end_filename|>
"""Julia program to check if a number is a Magic Number or not
A number is said to be a magic number if the recursive sum of its digits is 1.
    For Example Let's Consider
      19, 1 + 9 = 10
      10, 1 + 0 = 1
      = 1 , Hence 19 is a Maigc Number
"""


function sum_of_digits(n)
    sum = 0
    while(n>0)
        rem = n % 10
        sum = sum + rem
        n = n ÷ 10
    end
    return sum
end

function check_magic_num(n)
    while(n > 9)
        n = sum_of_digits(n)
    end
    if(n == 1)
        return true
    else
        return false
    end
end



print("Enter the number: ")
n = readline()
n = parse(Int, n)
res = check_magic_num(abs(n))
if res
    println("The given number $n is a Magic Number.")
else
    println("The given number $n is not a Magic Number.")
end


"""
Time Complexity: O(log(n)), where 'n' is the given number
Space Complexity: O(1)

SAMPLE INPUT AND OUTPUT

SAMPLE 1
Enter the number: 23
The given number 23 is not a Magic Number.

SAMPLE 2
Enter the number: 1729
The given number 1729 is a Magic Number..

"""


<|start_filename|>C-Plus-Plus/stack/maximum_size_of_balanced_bracket_sequence.cpp<|end_filename|>
/*
Given a sequence of brackets as a string, find maximum possible length of balanced bracket sequence.
string consists only two characters , one is '(' another is ')'
can be solved this with the help of stack data structure.
*/

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

int balanced_bracket_sequence(string s, int string_size)
{
    int max_possible_balanced_bracket_sequence = 0;
    stack < char > st;
    for(int i = 0 ; i < string_size; i++)
    {
        /* Here if the current character of string is ' ( ' we will push it to stack
          and if the current character of string is ' ) ' and
          stack is not empty we will pop from the top of the stack
          increment the max_possible_balanced_bracket_sequence by 2
          every time.
        */
        if(s[i] == '(' )
        {
            st.push(s[i]);
        }
        else if(s[i]==')')
        {
            if(!st.empty())
            {
                if(st.top()=='(')
                {
                    st.pop();
                    max_possible_balanced_bracket_sequence += 2;
                }
            }
        }
    }
    return max_possible_balanced_bracket_sequence;
}

int main()
{
    cout << "Enter the string : \n";
    string s;
    cin >> s;
    int string_size = (int)s.size();
    int max_balanced_bracket_sequence = balanced_bracket_sequence(s, string_size);
    cout << "Maximum possible length of balanced bracket sequence is : \n";
    cout << max_balanced_bracket_sequence << endl;
}

/*
Standard Input and Output

Enter the string :
((()())

Maximum possible length of balanced bracket sequence is :
6

Time Complexity : O(N)
Space Complexity : O(N)

*/


<|start_filename|>C-Plus-Plus/math/Convert_decimal_to_binary.cpp<|end_filename|>
//C++ Program to convert a positive decimal number into its equivalent binary number

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

//Function to convert a positive decimal number into a binary number

long long convertDecimalToBinary(int n) {
	long long binaryNumber = 0;
	int remainder, i = 1;

	while (n != 0) {
		remainder = n % 2;
		n /= 2;
		binaryNumber += remainder * i;
		i *= 10;
	}
	return binaryNumber;
}

//Driver function
int main() {
	int decimal;
	//Prompts user for input
	cout << "Enter a decimal number to be converted into binary: ";
	cin >> decimal;

	//Display the resultant binary number
	cout << "Binary number: " << convertDecimalToBinary(decimal) << "\n";

	return 0;
}

/*
Input:
Enter a decimal number to be converted into binary: 13
Output:
Binary number: 1101

Input:
Enter a decimal number to be converted into binary: 57
Output:
Binary number: 111001

Input:
Enter a decimal number to be converted into binary: 100
Output:
Binary number: 1100100

Time complexity: O(N)
Space complexity: O(1)
*/


<|start_filename|>JavaScript/search/JumpSearch.js<|end_filename|>
/*

Jump search is a searching algorithm which works similarly to binary search i.e. it works on sorted array.
Idea - Check fewer elements by jumping a certain number of steps.
Ex., suppose length of array is 9, then jump search will be jumped by √9 i.e 3 steps.
Time Complexity : O(√n)

*/

// Prompt node package for taking user input
const prompt = require("prompt-sync")({ sigint: true });

function jumpSearch(number) {
  // Number of steps to jump
  let jump = Math.floor(Math.sqrt(array.length));
  let start, end;

  start = 0;
  end = jump;

  // Loop to get the range in which 'number' resides
  while (array[end] <= number && end < array.length) {
    // Upgrade step range
    start = end;
    end = end + jump;

    // if end is greater than array of length
    if (end > array.length - 1) {
      end = array.length;
    }
  }

  // Start looking through the range
  for (let i = start; i <= end - 1; i++) {
    if (array[i] === number) {
      return console.log("Found", array[i]);
    }
  }

  return console.log("Not found");
}

/* Workflow of user input */

// Take array length as input
let arrayLength = +prompt("Enter array length - ");
// Check whether the entered value is number or not

if (isNaN(arrayLength)) return console.log("Only numbers are allowed");

// Globally declared array 
let array = [];

// Take array items
for (let i = 1; i <= arrayLength; i++) {
  array.push(+prompt(`Enter ${i} element - `));
  
  // Check whether the entered value is number or not 
  if (array.includes(NaN)) return console.log("Only numbers are allowed");
}

console.log("Your array - ", array);

// Sort the given array ( Jump Search works for sorted array only )
array.sort((a, b) => {
  return a - b;
});

// Ask the key/number to search in provided array
let key = +prompt("Enter number to search - ");
if (isNaN(key)) return console.log("It should be a number");

// Call the algorithm
jumpSearch(key);

/*

Sample i/o

> node JumpSearch

Enter array length - 5
Enter 1 element - 23
Enter 2 element - 45
Enter 3 element - 87
Enter 4 element - 12
Enter 5 element - 54
Your array -  [ 23, 45, 87, 12, 54 ]
Enter number to search - 54
Found 54

Enter number to search - 14
Not Found

*/



<|start_filename|>C/other/Palindrome.c<|end_filename|>
/*
C Program to check whether a number is Palindrome or not
An integer is a palindrome if the reverse of that number is equal to the original number.
Example of Palindromes are 11,44,101,121,
*/
#include <stdio.h>

int reverse_num(int);
int main()
{
	int n, rev;
	printf("\n Enter a number:");
	scanf("%d", &n);
	rev = reverse_num(n);
	if (rev == n)
	{
		printf("\n %d is a palindrome", n);
	}
	else
	{
		printf("\n %d is not a palindrome", n);
	}
	return 0;
}
int reverse_num(int num)
{
	int rev = 0;
	int rem;
	while (num > 0)
	{
		rem = num % 10;
		rev = rev *10 + rem;
		num = num / 10;
	}
	return rev;
}

/*
Sample Output
Enter a number: 121
121 is a palindrome

Complexities
Time Complexity: O(n)
Space Complexity: O(1)
*/



<|start_filename|>Java/cp/N_Queens_Problem_Efficient.java<|end_filename|>

/* Java program to solve N Queen Problem
using backtracking in an Optimization Method*/
import java.util.*;

class nQueens
{
    static int N;
    //ldia : Left Diagonal to store negative indices
    static int []ldia = new int[30];
    //rdia : Right Diagonal queen placed in right diagonal or not(row+column)
    static int []rdia = new int[30];
    //col :  column array
    static int []col = new int[30];

    //An Effective Funtion to print Solution
    static void printSolution(int onBoard[][])
    {
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < N; j++)
                System.out.printf(" %d ", onBoard[i][j]);
            System.out.printf("\n");
        }
    }

    /* By this Utility Function, Consider using column 
    and try placing this queen in all rows one by one and
    check if queen can be placed or not. If Queen can be
    placed on Board then we can check left diagonal and 
    Right diagonal. If Queen placed dosen't match the 
    rules, then remove Queen on that position.*/
    static boolean solveUtil(int onBoard[][], int colo)
    {
        //BaseCase : If all Queens Placed
        if (colo >= N)
            return true;

        for (int i = 0; i < N; i++) {
            if ((ldia[i - colo + N - 1] != 1 &&
                    rdia[i + colo] != 1) && col[i] != 1) {

                onBoard[i][colo] = 1;
                ldia[i - colo + N - 1] =
                        rdia[i + colo] = col[i] = 1;

                if (solveUtil(onBoard, colo + 1))
                    return true;

                onBoard[i][colo] = 0; // BACKTRACK
                ldia[i - colo + N - 1] =
                        rdia[i + colo] = col[i] = 0;
            }
        }
        return false;
    }
    /* This function returns false if queens
    cannot be placed, otherwise, return true and
    prints placement of queens in the form of 1s.
    */
    static boolean solBoard()
    {
        Scanner sc = new Scanner(System.in);
        N = sc.nextInt();
        int onBoard[][] = new int[N][N];

        if (solveUtil(onBoard, 0) == false)
        {
            System.out.printf("Solution does not exist");
            return false;
        }
        printSolution(onBoard);
        return true;
    }
    public static void main(String[] args)
    {
        solBoard();
    }
}

/*
Input : N = 4;
Output : 0  0  1  0
         1  0  0  0
         0  0  0  1
         0  1  0  0
 Input : N = 5
         1  0  0  0  0
         0  0  0  1  0
         0  1  0  0  0
         0  0  0  0  1
         0  0  1  0  0
 */


<|start_filename|>C-Plus-Plus/graphs/Check_for_bipartite_graph.cpp<|end_filename|>
/*
Bipartite Graph Check
----------------------
Problem:
Divide all vertices of the graph in two sets such that
all the edges of the graph are from set1 to set2

Similar to 2 coloring problem

Algorithm:
1) If graph is a tree, then YES Bipartite.
2) If it is not a tree(=> cycle is present)
	Odd length cycle => NOT Bipartite
	Even length cycle => YES Bipartite

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

// Helper function to run dfs from src node
bool dfs_helper(vector<int> graph[], int src, int visited[], int parentOf[], int color) {

	// Mark the current node
	visited[src] = color;

	// Visit all the neighbours of src
	for (int nbr : graph[src]) {
		// If neighbour has not been visited yet
		if (!visited[nbr]) {
			// Mark src to be the parent of src
			parentOf[nbr] = src;
			// Instantiate dfs call at nbr
			bool oddLenCycleFound = dfs_helper(graph, nbr, visited, parentOf, 3 - color);
			// If odd length cycle is found at nbr, then immediately return false
			if (oddLenCycleFound) return 0;
		} else {
			// nbr potentially contributes to a cycle
			if (parentOf[src] == nbr) {
				// Not a cycle
			} else {
				// Yes a cycle
				// nbrs of src should not have same color
				if (visited[nbr] == color) return 0;
			}

		}
	}
	return true;
}

bool isBipartite(vector<int> graph[], int n) {

	// Keeps track of visited nodes
	int visited[n] = {0};
	// 0 -> Not visited
	// 1,2 -> Visited and color is 1,2

	// Stores parent of each node
	int parentOf[n];
	for (int i = 0; i < n; i++) {
		parentOf[i] = i; // Initially each node is a parent of itself
	}

	bool ans = dfs_helper(graph, 0, visited, parentOf, 1);

	// Print colour of each node
	for (int i = 0; i < n; i++) {
		cout << i << " color=" << visited[i] << endl;
	}

	return ans;
}

int main() {
	// n : Number of vertices
	// m : Number of edges
	int n, m;
	cin >> n >> m;

	// Ajacency List : graph[i] stores all the neighbours of i
	vector<int> graph[n];

	for (int i = 0; i < m; i++) {
		int x, y; cin >> x >> y;

		graph[x].push_back(y);
		graph[y].push_back(x);
	}

	cout << isBipartite(graph, n);
}

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

Output:
0 color=1
1 color=2
2 color=1
3 color=2
4 color=1
0

*/


<|start_filename|>C-Plus-Plus/other/Max_in_BitonicArray.cpp<|end_filename|>
/*
Find the maximum element in Bitonic array
==========================================
A bitonic array is an array of integers which is initially
increasing and then decreasing.
An efficient solution to find the maximum element 
in bitonic array is by using binary search.
Given an array of integers which is initially increasing
and then decreasing, find the maximum value in the array.
*/

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

/* This function is used to find maximum 
element in bitonic array
*/
int findMax(int arr[],int low,int high){
	/* Base Case: Only one element is present in arr[low..high]*/
   if (low == high) 
     return arr[low]; 
     
    /* If there are two elements and first is greater then 
      the first element is maximum */
   if ((high == low + 1) && arr[low] >= arr[high]) 
      return arr[low];
	  
	/* If there are two elements and second is greater then 
      the second element is maximum */
   if ((high == low + 1) && arr[low] < arr[high]) 
      return arr[high];
	  
	int mid = (low + high)/2;   /*low + (high - low)/2;*/
	/* If we reach a point where arr[mid] is greater than both of 
     its adjacent elements arr[mid-1] and arr[mid+1], then arr[mid] 
     is the maximum element*/
   if ( arr[mid] > arr[mid + 1] && arr[mid] > arr[mid - 1]) 
      return arr[mid]; 
  
    /* If arr[mid] is greater than the next element and smaller than the previous  
    element then maximum lies on left side of mid */
   if (arr[mid] > arr[mid + 1] && arr[mid] < arr[mid - 1]) 
      return findMax(arr, low, mid-1); 
   else /* when arr[mid] is greater than arr[mid-1] and smaller than arr[mid+1] */
      return findMax(arr, mid + 1, high);   
}


//Drivers' Code
int main()
{
	int size;
   cout<<"Enter the size of the Array:";
	cin>>size;
	int arr[size]; //declaring the array 
	cout<<"Enter the elements of the Array:";
	for(int i=0;i<size;i++)
	  cin>>arr[i];
	cout<<"The maximum element is: "<<findMax(arr,0,size-1)<<endl;
	return 0;
}
/*

    Time Complexity: O(Logn)
    Auxilary Space  Complexity:O(1)

    Testcase '1':
    Enter the size of the Array:11
    Enter the elements of the Array:8 10 20 80 100 200 400 500 3 2 1
    The maximum element is: 500

    Testcase '2':
    Corner case (No decreasing part)
    Enter the size of the Array:5
    Enter the elements of the Array:10 20 30 40 50
    The maximum element is: 50

    Testcase '3':
    Corner case (No increasing part)
    Enter the size of the Array:5
    Enter the elements of the Array:120 100 80 20 0
    The maximum element is: 120
*/



<|start_filename|>C-Plus-Plus/other/subsets_iterative.cpp<|end_filename|>
#include<bits/stdc++.h>

using namespace std;
void generate_subsets(int arr[], int n) {
    /*
    Number of possible subsets are 2^n
    If n=2, then:
    00 01 10 11 , four sets
    00 Indicates that both 0 and 1 index are not set hence empty
    01 Indicating that first index is unset and zeroth index is set
    */
    for (int i = 0; i < pow(2, n); i++) {
        //For checking set bits in the binary pattern and then printing the corresponding element
        for (int j = 0; j < n; j++) {
            if (i & (1 << j)) {
                cout << arr[j] << " ";
            }
        }
        cout << endl;
    }
}
int main() {
    int n;
    cin >> n;
    int arr[n];
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }
    generate_subsets(arr, n);
}
/*
Input:
3
1 2 3 

Output:
1 
2 
1 2 
3 
1 3 
2 3 
1 2 3

Time complexity: O(2^n)
Space complexity: O(1)
*/


<|start_filename|>C/cp/first_missing_positive_integer.c<|end_filename|>
#include <stdio.h>
#include <stdlib.h>

int main(){
    int n;
    printf("Enter the value of n: ");
    scanf("%d\n",&n);
    printf("Enter the array:\n");
    int *arr = (int*)malloc(n * sizeof(int));
    for (int i = 1; i <= n; ++i)
    {
        scanf("%d", &arr[i]);
    }
    if (arr == NULL) { 
        printf("Memory not allocated.\n"); 
        return 0;
    } 
    else {
        for (int i = 1; i <= n; i++) {
            if (arr[i] <= 0 || arr[i] > n) 
                continue; 

            int x = arr[i]; 
            while (arr[x] != x) { 
                int next_ele = arr[x]; 
                arr[x] = x; 
                x = next_ele;
                if (x <= 0 || x > n) 
                    break; 
            } 
        }
        int ans = n + 1;
        for (int i = 1; i <= n; i++) { 
            if (arr[i] != i) { 
                ans = i;
                break;
            } 
        }
        printf("%d", ans);
    } 
    
    return 0;
}

/*
Time Complexity: O(N)
Space Complexity: O(1)
OUTPUT
Enter the value of n: 4
Enter the array:
3 4 -1 1
2
*/


<|start_filename|>Java/cp/MaximumSumSubarray.java<|end_filename|>
/**
 * Maximum Sum Subarray of Size K
 * Java program to find the maximum sum of a subarray of fixed size K, 
 * given an array of integers, using the 'Sliding Window Technique'. 
 */

import java.util.*; 
public class MaximumSumSubarray {
    
    public static int maximumSum(int[] numArray, int K) {
        int currentSum = 0; 

        //Calculating sum for first window of size K
        for(int i=0; i<K; i++) 
            currentSum += numArray[i]; 

        //Storing maximum sum till current window
        int maxSum = currentSum; 

        //Finding sum of all possible K-sized windows, one by one
        int subtractIndex = 0; 
        for(int i=K; i<numArray.length; i++) {
            currentSum += numArray[i] - numArray[subtractIndex]; 
            subtractIndex++; 
            maxSum = Math.max(maxSum, currentSum); 
        }
        return maxSum; 
    }
    
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in); 

        //Taking input from user
        System.out.println("Enter length of array and size of window: "); 
        int length = scan.nextInt(); 
        int K = scan.nextInt(); 
        int numArray[] = new int[length]; 
        System.out.println("Enter array elements: "); 
        for(int i=0; i<length; i++) {
            numArray[i] = scan.nextInt(); 
        }

        if(K > length || K <= 0)
            System.out.println("Invalid input"); 
        else {
            System.out.println("Maximum sum of a subarray of size " + K + ":"); 
            System.out.println(maximumSum(numArray, K));
        }
    }

}

/*
    Time complexity: O(N)
    Space complexity: O(1)

    TEST CASES

    INPUT
    Enter length of array and size of window: 
    10 3
    Enter array elements: 
    1 7 -2 4 5 2 1 6 11 -4
    OUTPUT
    Maximum sum of a subarray of size 3:
    18

    INPUT
    Enter length of array and size of window: 
    8 4
    Enter array elements:
    2 4 0 1 5 2 9 3
    OUTPUT
    Maximum sum of a subarray of size 4:
    19

 */


<|start_filename|>JavaScript/ds/StackLinkedList.js<|end_filename|>
/*

A stack is a data structure that follows the Last in, First out principle (i.e.​ the last added elements are removed first).
Generally, a stack is implemented using an array but a linked list approach can be used. Below is the implementation of a stack using a linked list ( Singly Linked List ).

In this program, the user can provide a choice to perform operations on a stack. It is created using an ES6 class syntax. 
prompt & colors are node packages for taking user input and displaying text in different colors respectively. 

*/

const prompt = require("prompt-sync")({ sigint: true });
const colors = require("colors");

// Setting the Color schema
colors.setTheme({
  display: "green",
  insert: "white",
  delete: "red",
  leave: "yellow",
  end: "rainbow",
  wrong: "america",
});

// Creating the node class to create nodes
class Node {
  constructor(value, next = null) {
    this.value = value;
    this.next = next;
  }
}

// Creating a Stack class to perform operations
class Stack {
  constructor() {
    this.top = null;
    this.bottom = null;
    this.length = 0;
  }

  // Push element into the stack
  push(value) {
    const newNode = new Node(value);
    if (this.length === 0) {
      this.top = newNode;
      this.bottom = newNode;
      this.length++;

      return this;
    }

    const holdingPointer = this.top;
    this.top = newNode;
    this.top.next = holdingPointer;
    this.length++;
    return this;
  }

  // Get topmost element of stack
  peek() {
    if (this.length === 0) return console.log("Nothing to look for");
    return console.log(this.top.value);
  }

  // Check whether the stack is empty or not
  isEmpty() {
    if (this.length === 0) return console.log("Yes, it's Empty here");
    return console.log("There is something inside, not void for sure");
  }

  // Pop element form the stack
  pop() {
    if (!this.top) return console.log("Nothing to pop");
    let pop = this.top.value;

    if (this.top === this.bottom) {
      this.bottom = null;
      this.top = null;
      this.length--;
      return console.log("Popped out", pop);
    }

    this.top = this.top.next;
    this.length--;
    return console.log("Popped out", pop);
  }

  // Reverse the stack
  reverse() {
    if (!this.top.next) {
      return this.top;
    }

    let top = this.top;
    this.bottom = this.top;
    let nextNode = top.next;

    while (nextNode) {
      const temp = nextNode.next;
      nextNode.next = top;
      top = nextNode;
      nextNode = temp;
    }

    this.top.next = null;
    this.top = top;

    return this;
  }

  // Display all the elements of stack
  printStackElements() {
    let currentNode = this.top;
    let data = [];

    while (currentNode) {
      data.push(currentNode.value);
      currentNode = currentNode.next;
    }

    return console.log("Stack Elements", data);
  }
}

// Instantiating the Stack class
const myStack = new Stack();

let choice = 0;
let value;

// Asking user input for performing operations on Stack
do {
  console.log("\nWelcome to the Stack Linked List Show");
  console.log("Follow the instructions to get in the show");
  console.log("0. To exit without doing anything".yellow);
  console.log("1. Display the stack".display);
  console.log("2. Push element into the stack".insert);
  console.log("3. Get top element of the stack".display);
  console.log("4. Check whether the stack in empty or not".insert);
  console.log("5. Pop element from the stack".delete);
  console.log("6. Reverse the stack".display);

  choice = +prompt("Enter your choice - ");

  switch (choice) {
    case 0:
      console.log("Hmm, matter of choice!\n".rainbow);
      return;

    case 1:
      myStack.printStackElements();
      break;

    case 2:
      value = prompt("Enter element to push into the stack - ");
      myStack.push(value);
      myStack.printStackElements();
      break;

    case 3:
      myStack.peek();
      break;

    case 4:
      myStack.isEmpty();
      break;

    case 5:
      myStack.pop();
      myStack.printStackElements();
      break;
    
    case 6:
      if (myStack.length === 0) {
        console.log("Stack is empty");
      } else {
        myStack.reverse();
        myStack.printStackElements();
      }
  
      break;

    default:
      console.log("You know this is wrong, Bbye!\n".wrong);
      return;
  }
} while (choice !== 0);

// Sample I/O of the above program -

/*

> node StackLinkedList

Welcome to the Stack Linked List Show
Follow the instructions to get in the show
0. To exit without doing anything
1. Display the stack
2. Push element in stack
3. Get top element of stack
4. Check whether stack in empty or not
5. Pop element from stack
6. Reverse the stack
Enter your choice - 1
Stack Elements []

Welcome to the Stack Linked List Show
Follow the instructions to get in the show
0. To exit without doing anything
1. Display the stack
2. Push element in stack
3. Get top element of stack
4. Check whether stack in empty or not
5. Pop element from stack
6. Reverse the stack
Enter your choice - 2
Enter element to push into the stack - Google
Stack Elements [ 'Google' ]

Welcome to the Stack Linked List Show
Follow the instructions to get in the show
0. To exit without doing anything
1. Display the stack
2. Push element in stack
3. Get top element of stack
4. Check whether stack in empty or not
5. Pop element from stack
6. Reverse the stack
Enter your choice - 2
Enter element to push into the stack - YouTube
Stack Elements [ 'Google', 'YouTube' ]

Welcome to the Stack Linked List Show
Follow the instructions to get in the show
0. To exit without doing anything
1. Display the stack
2. Push element in stack
3. Get top element of stack
4. Check whether stack in empty or not
5. Pop element from stack
6. Reverse the stack
Enter your choice - 6
Stack Elements [ 'YouTube', 'Google' ]

*/




<|start_filename|>C/cp/maxSubArraySum.c<|end_filename|>
#include <stdio.h>
#include <stdlib.h>
#define MAX(a,b) (((a)>(b))?(a):(b))

int main(void) {
    
	// Accepting an array 
	int size;
	printf("Enter the size of the array ");
	scanf ("%d", &size);
	
	printf("Enter elements of array \n");
	int arr[size];
	for (int index = 0; index < size; index++ ){
	    scanf("%d", &arr[index]);
	}
	
	//KADANE'S ALGORITHM
	int max_sum  = arr[0];
	int curr_max = arr[0];
	for (int index = 1; index < size; index++ ){
	    curr_max = MAX(arr[index], arr[index] + curr_max);
	    max_sum = MAX(curr_max, max_sum);
	}
	
	printf("Maximum sum of subarray is %d \n", max_sum);
	
	return 0;
}

/*
TIME COMPLEXITY : O(n) where n is number of elements in array
SPACE COMPLEXITY : O(1) as no new space is allocated
TEST CASE 

INPUT
Enter number of elemets in array 4
Enter elemets of array  2 -3 4 6 

OUTPUT
Maximum sum of subarray is 10 


INPUT
Enter number of elemets in array 4
Enter elemets of array  2 3 4 6 

OUTPUT
Maximum sum of subarray is 15 
*/



<|start_filename|>C/ds/StackImplementationWithLinkedList.c<|end_filename|>
/*
A stack is an Abstract Data Type (ADT), commonly used in most programming languages.This feature makes it LIFO data structure.
LIFO stands for Last-in-first-out. Here, the element which is placed (inserted or added) last, is accessed first.

The Basic operation in Stack are:
1.push() − Pushing (storing) an element on the stack.
2.pop() − Removing (accessing) an element from the stack.
3.peek() − get the top data element of the stack, without removing it.
4.display() - used to display the elements
*/

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

struct node
{
    int data;
    struct node *link;
};

struct node *top = NULL;
void push();
void pop();
void display();

void push()
{
    struct node *temp;
    temp = (struct node *)malloc(sizeof(struct node));
    printf("\n Enter node data:");
    scanf("%d", &temp->data);
    temp->link = top;
    top = temp;
}

void pop()
{
    struct node *temp;
    if (top == NULL)
        printf("No element");
    else
    {
        temp = top;
        printf("The deleted element is %d", temp->data);
        top = top->link;
        temp->link = NULL;
        free(temp);
    }
}

void display()
{
    struct node *temp;
    if (top == NULL)
        printf("\n Stack is empty");
    else
    {
        temp = top;
        printf("\nData is");
        while (temp != NULL)
        {
            printf("%d ", temp->data);
            temp = temp->link;
        }
    }
}

void main()
{
    int choice;
    do
    {
        printf("\n*****Menu*****\n");
	printf("\n1.Push\n2.Pop\n3.Display\n4.Exit\n"); 
        printf("Enter your choice:"); 
        scanf("%d", &choice);
	switch (choice)
	{
		case 1:
			push();
			break;
		case 2:
			pop();
			break;
		case 3:
			display();
			break;
		case 4:
			exit(0);
		default:
			printf("Invalid choice");
	}
	}
        while (choice < 5);
        getchar();
}

/*
*****MENU****** 
1.Push
2.Pop 
3.Display 
4.Exit 
Enter your choice 1 
Enter node data 23

*****MENU****** 
1.Push
2.Pop 
3.Display 
4.Exit
Enter your choice 1 
Enter node data 24

*****MENU****** 
1.Push
2.Pop 
3.Display 
4.Exit
Enter your choice 2
The deleted element is 24

*****MENU****** 
1.Push
2.Pop 
3.Display 
4.Exit
Enter your choice 
1
Enter node data 25

*****MENU****** 
1.Push
2.Pop 
3.Display 
4.Exit
Enter your choice 3 
Data is 23 25

Time complexity : O(1)
Space Complexity: O(n)
*/


<|start_filename|>Java/ds/Stack.java<|end_filename|>
import java.util.*;
public class Stack
{
  static Node top;
  class Node
  {
	public int data;
	public Node next;
	Node(int data)
	{
		this.data=data;
	}
  }
  void push(int data)
  {
	Node ptr = new Node(data);
	if(top==null)
	{
		top=ptr;
		ptr.next=null;
                System.out.println(data+" is successfully added to the stack");
	}
	else 
	{
		Node ctr=top;
		ptr.next=ctr;
		top = ptr;
		System.out.println(data+" is successfully added to the stack");
	}
  }
  boolean isEmpty()
  {
	if(top==null) 
		return true;
	return false;
  }
  void peek()
  {     if(!isEmpty())
	  System.out.println(top.data);
        else 
          System.out.println("Stack is empty");
  }
  void count()
  {
	  int count = 0;
	  Node ptr = top;
	  while(ptr!=null)
	  {
		  count++;
		  ptr = ptr.next;
	  }
	  System.out.println("The stack has "+count+" elements"); 
  }
  void pop()
  {
	Node ctr=top;int data;
	if(ctr==null)
	{
		System.out.println("Stack is empty");
		return ;
	}
	else if(ctr!=null && ctr.next==null)
	{       data = top.data;
		top = null;
	}
	else 	
	{       data = top.data;
		top = top.next;
	}
	  System.out.println(data+" is successfully removed from the stack");
  }
  void display()
  {   if (isEmpty())
        {
	    System.out.println("The stack is empty");
        }
      else 
      { System.out.println("The stack is ");
	Node ctr=top;
	while(ctr!=null)
	{
		System.out.print(ctr.data+" ");
		ctr=ctr.next;
	}
	System.out.println();
  }
  }
  public static void main(String[] args)
  {
	Stack st=new Stack();
	Scanner sc=new Scanner(System.in);
	System.out.println("Stack");
	int choice; boolean f=true;
	while(f) 
	{
		System.out.println("Enter 1 to input data, 2 to delete data from stack, 3 to peek data from stack,4 to count the number of elements in the stack, 5 to display all elements in the stack and 6 to exit");
		choice=sc.nextInt();
		switch(choice) 
		{
		 case 1: System.out.println("Enter data to enter into stack");
		         int data = sc.nextInt();
		         st.push(data);
		         break;
		 case 2: st.pop();
			 break;
		 case 3: st.peek();	
		         break;
		 case 4: st.count();
			 break;
		 case 5: st.display();
			 break;
		 case 6: f=false;
	                 break;
	        default: System.out.println("Enter Valid Input");
	                 break;
		}
	}
  }

}

/*
Stack
Enter 1 to input data, 2 to delete data from stack, 3 to peek data from stack,4 to count the number of elements in the stack, 5 to display all elements in the stack and 6 to exit
1
Enter data to enter into stack
2
2 is successfully added to the stack
Enter 1 to input data, 2 to delete data from stack, 3 to peek data from stack,4 to count the number of elements in the stack, 5 to display all elements in the stack and 6 to exit
2
2 is successfully removed from the stack
Enter 1 to input data, 2 to delete data from stack, 3 to peek data from stack,4 to count the number of elements in the stack, 5 to display all elements in the stack and 6 to exit
1
Enter data to enter into stack
3
3 is successfully added to the stack
Enter 1 to input data, 2 to delete data from stack, 3 to peek data from stack,4 to count the number of elements in the stack, 5 to display all elements in the stack and 6 to exit
3
3
Enter 1 to input data, 2 to delete data from stack, 3 to peek data from stack,4 to count the number of elements in the stack, 5 to display all elements in the stack and 6 to exit
4
The stack has 1 elements
Enter 1 to input data, 2 to delete data from stack, 3 to peek data from stack,4 to count the number of elements in the stack, 5 to display all elements in the stack and 6 to exit
5
The stack is 
3 
Enter 1 to input data, 2 to delete data from stack, 3 to peek data from stack,4 to count the number of elements in the stack, 5 to display all elements in the stack and 6 to exit
6
*/


<|start_filename|>Java/other/OnePlustoWhole.java<|end_filename|>
/*
One plus to whole

For a given array arr[] of decimal digits, all of which are non-negative numbers.
The digits are stored such that the most significant is at the head of the list, 
and each element of the array contaians single digit only.
It is assumed that none of the numbers have its most significant digit equal to 0.
Your task is to increment the interger so formed by one and return it.
*/

import java.util.*;

public class OnePlustoWhole
{
    //function to return the incremented integer
    public int[] onePlus(int arr[], int size)
    {
        for(int i=size-1; i>=0; i--)
        {
            //if element of the array are somethig less than 9 no carray
            if(arr[i]<9)
            {
                arr[i]++;
                return arr;
            }
            //else if array element is 9 then we crearw new array
            //with one extra digit to keep carry
            arr[i]=0;
        }

        int[] num=new int[size+1];
        num[0]=1;
        
        return num;
    }

    //DRIVER METHOD
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);

        //size of array
        System.out.println("Enter the number of elements of array: ");
        int size = sc.nextInt();

        int []arr = new int[size];
        //array elements
        System.out.println("Enter the elements for array: ");
        for (int i = 0; i < size; i++) {
            arr[i] = sc.nextInt();
        }

        System.out.println("The incremented number is: ");
        int[] res=new OnePlustoWhole().onePlus(arr, size);
        for(int i=0; i<res.length; i++)
        {
            System.out.print(res[i]+" ");
        }
    }
}

/*
EXAMPLE:-

Input--
Enter the number of elements of array: 5
Enter the elements for array: [1, 2, 2, 5, 6]
Output--
The incremented number is: [1, 2, 2, 5, 7]

TIME COMPLEXCITY --> O(N)
SPACE COMPLEXITY --> O(N)
*/


<|start_filename|>Kotlin/search/StairCaseSearch.kt<|end_filename|>
// Kotlin program to implement Staircase Search using Iterative Approach

import java.util.Scanner

fun main(args: Array <String>) {

    val input = Scanner(System.`in`)

    val noOfRows = input.nextInt()
    val noOfColumns = input.nextInt()

    val matrix = ArrayList <ArrayList <Int>> ()
    for(row in 0 until noOfRows) {
        var rows = ArrayList <Int> ()
        for(column in 0 until noOfColumns) {
            var element = input.nextInt()
            rows.add(element)
        }
        matrix.add(rows)
    }

    val key = input.nextInt()
    stairCaseSearch(matrix , key)
}

fun stairCaseSearch(matrix: ArrayList<ArrayList<Int>>, key: Int) {

    var noOfRows = matrix.size
    var noOfColumns = matrix[0].size
    var row = 0
    var column = noOfColumns - 1
    var isKeyPresent = false

    while(row <= noOfRows - 1 && column >= 0) {

        // If key is equal to the current element, print the indices values and break
        if(matrix[row][column] == key) {
            isKeyPresent = true
            println("Key: $key is present at Row: ${row + 1} and Column: ${column + 1}")
            break
        }

        // If current element is greater than key, then since it is column sorted matrix, the
        // previous column would have smaller element than the current column
        else if(matrix[row][column] > key) {
            column--
        }

        // If the current element is smaller than key, then since it is row sorted matrix, the
        // next row would have greater element than the current row
        else {
            row++
        }
    }

    // If the element is not present in the matrix
    if(!isKeyPresent)
        println("Key: $key is not present in the matrix")
}

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

/* Sample Test Cases:
Test - 1:
    Input
        3 4
        1 2  3  4
        5 6  7  8
        9 10 11 12
        11

    Output
        Key: 11 is present at Row: 3 and Column: 3

Test - 2:
    Input
        2 1
        10
        20
        -10
    Output
        Key: -10 is not present in the matrix
 */



<|start_filename|>C-Plus-Plus/cp/maximum_of_all_subarray_of_size_k.cpp<|end_filename|>
/**
 * Maximum of All Subarrays of Size k
 * Cpp program to find the maximum integer in each subarray of 
 * fixed size k, given an array of integers, using the 'Sliding 
 * Window Technique'. 
 */

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

void MaximumEachSubarray(int len, int arr[], int k)
{
    //Deque stores indices of useful elements for each window.
    //These elments are sorted in decreasing order, so that for each
    //window, maximum element is at the front.
    deque<int> maxElement;
    vector<int> ans;
    //Edge case
    //If len is smaller than k, push maximum element into the answer
    if (k > len) {
        ans.push_back(*max_element(arr, arr + len));
    }
    //Two pointer one pointing to start and other to the end of current window
    int start = 0, end = 0;
    //The same process is repeated over all windows of length k.
    while (end < len) {
        //For any element, all elements smaller than it and to its left in
        //the window are useless as they cannot be the maximum for that
        //window. Hence, we remove them from rear of deque.
        while (maxElement.size() > 0 && maxElement.back() < arr[end])
            maxElement.pop_back();
        //Adding newest element to rear of deque
        maxElement.push_back(arr[end]);
        //If window size is not reached,increment end pointer
        if (end - start + 1 < k)
            end++;
        else if (end - start + 1 == k) { //Adding front element to ans
            //If front element equals 1st element
            //of current window, we remove it from deque
            ans.push_back(maxElement.front());
            if (maxElement.front() == arr[start])
                maxElement.pop_front();
            //slide the window
            start++;
            end++;
        }
    }
    cout << "Array of maximum integers in all k-sized subarrays: ";
    for (int i = 0; i < ans.size(); i++)
        cout << ans[i] << " ";
}

int main()
{
    //Taking input from user
    int len;
    cout << "Enter length of array of integers: ";
    cin >> len;
    int arr[len];
    cout << "Enter array of integers: ";
    for (int i = 0; i < len; i++)
        cin >> arr[i];
    int k;
    cout << "Enter size of window: ";
    cin >> k;
    MaximumEachSubarray(len, arr, k);
    return 0;
}

/*
	Test cases:

	INPUT:-
	Enter length of array of integers: 8
    Enter array of integers: 12 3 -7 8 -15 39 15 20
	Enter size of window: 3
	OUTPUT:-
	Array of maximum integers in all k-sized subarrays: 12 8 8 39 39 39

	INPUT:-
	Enter length of array of integers: 4
	Enter array of integers: 3 2 1 5
	Enter size of window: 3
	OUTPUT:-
	Array of maximum integers in all k-sized subarrays: 3 5

	Time complexity: O(N)
	Space complexity: O(k)

*/


<|start_filename|>Java/graphs/LevelOrderTraversalInQueue.java<|end_filename|>
// Iterative Queue based Java program to do level order traversal 
// of Binary Tree 

package practice;

/* importing the inbuilt java classes required for the program */
import java.util.LinkedList;
import java.util.Queue;

/* Class to represent Tree node */
public class Node 
{	
	 int data;
	 Node right,left;
	 
	 public Node(int item) 
	 {
		 data=item;
		 right=left=null;
	 }
}

/* Class to print Level Order Traversal */
public class LevelOrderTraversalInQueue 
{	
	Node root;
	
	/* Given a binary tree. Print its nodes in level order 
    using array for implementing queue  */
	public void printLevelOrder()
	{  Queue<Node> q=new LinkedList<Node>();
	   q.add(root);
       while(!q.isEmpty())
       {
    	  /* poll() removes the present head.*/ 
    	  Node temp=q.poll();
		  System.out.print(temp.data+" ");
		  
		  /*Enqueue left child */
		  if (!((temp.left)==null))
		     q.add(temp.left);
		  
		  /*Enqueue right child */
		  if (!((temp.right)==null))
		     q.add(temp.right);
	   }
	}
    
	public static void main(String args[])  
    { 
        /* creating a binary tree and entering  
         the nodes */
        LevelOrderTraversalInQueue tree_level = new LevelOrderTraversalInQueue(); 
        tree_level.root = new Node(1); 
        tree_level.root.left = new Node(2); 
        tree_level.root.right = new Node(3); 
        tree_level.root.left.left = new Node(4); 
        tree_level.root.left.right = new Node(5); 
  
        System.out.println("Level order traversal of binary tree is - "); 
        tree_level.printLevelOrder(); 
    } 
} 

/*Output is
  Level order traversal of binary tree is - 
  1 2 3 4 5 
*/


<|start_filename|>C/math/automorphic_no.c<|end_filename|>
/*
C program to check whether the number is automorphic or not.
Automorphic number is a number whose square ends with the original number itself
*/
#include <stdio.h>

int automorphic_num(int);
int main()
{
	int n, l;
	printf("Enter the number to check:\n");
	scanf("%d", &n);
	l = automorphic_num(n);
	if (l == n)
		printf("\nAUTOMORPHIC NUMBER !");
	else
		printf("\nNOT AUTOMORPHIC NUMBER !");
	return 0;
}

// Function to check if the number is automorphic or not
int automorphic_num(int n)
{
	int s, temp, l;
	temp = n;
	s = n * n;
	int flag = 1;
	while (n != 0)
	{
		flag = flag * 10;
		n = n / 10;
	}

	l = s % flag;
	return l;
}

/*
Sample Input-Output:1
Enter the number to check:
7
NOT AUTOMORPHIC NUMBER !

Sample Input-Output:2
Enter the number to check:
5
AUTOMORPHIC NUMBER !

Time Complexity: O(n)
*/



<|start_filename|>C-Plus-Plus/cp/product_of_array_except_itself.cpp<|end_filename|>
/*
Given a vector, return a vector
where each element is equal to the product of all the elements
of except that particular element.
*/

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

vector < int > get_Product_Except_Self(vector < int > &ar)
{
        /* take a vector Product_ExceptSelf where each element is 1 */
        vector < int > Product_ExceptSelf( ar.size(), 1);
        int x = 1;
        for(int i = 1; i < ar.size() ; i++)
        {
            Product_ExceptSelf[i] = Product_ExceptSelf[i-1] * ar[i-1];
        }
        for(int i = Product_ExceptSelf.size() - 1 ; i >= 1 ; i--)
        {
            /* here we keep multiplied x with ar[i]
            and then multiply Product_ExceptSelf[i-1]
            with current x value */
            x *= ar[i];
            Product_ExceptSelf[i-1] *= x;
        }
        return Product_ExceptSelf;
}

int main()
{
    cout << "Enter the size of the vector : \n";
    int N; 
    cin >> N;
    vector < int > ar(N , 0);
    cout << "Enter vector elements :\n";
    for (int i = 0; i < N; i++) 
    {
	cin >> ar[i];
    }
    vector < int > Product_Except_Self = get_Product_Except_Self(ar);
    cout << "The New vector is :\n";
    for(auto i : Product_Except_Self)
    {
        cout << i << ' ';
    }
    cout << endl;
}

/*
Standard Input and Output

1.
Enter the size of the vector :
6
Enter vector elements :
4 53 23 9 3 2
The New vector is :
65826 4968 11448 29256 87768 131652

2.
Enter the size of the vector :
5
Enter vector elements :
0 0 0 3 5
The New vector is :
0 0 0 0 0

Time Complexity : O( N )
Space Complexity : O( N )

*/


<|start_filename|>C-Plus-Plus/math/automorphic_number.cpp<|end_filename|>
/**
 * Given a number and you need to check if a number is Automorphic or not. 
 * A number is called Automorphic if the square of the number ends
 * with the number itself.
 * Input:
 * First line of input contains a number of integer data type.
 * Output:
 * A single line telling whether a number is Automorphic or not.
 *
*/

#include <bits/stdc++.h>

using namespace std;

int Check_Automorphic(int n)
{
    int square, temp, remainder, no_digits = 0;
    temp = n;
    square = n * n;
    int flag = 10;

    while (n != 0)
    {
        n = n / 10;
        no_digits++;
    }

    flag = pow(10, no_digits);
    remainder = square % flag;

    if (remainder == temp)
        return 1;
    else
        return 0;
}

int main()
{

    long long int num;
    cout << "Enter the number: " << endl;
    cin >> num;

    int result = Check_Automorphic(num);

    if (result == 1)
        cout << num << " is a Automorphic number. " << endl;

    else
        cout << num << " is not a Automorphic number. " << endl;
}

/*
 * Example:
 * Input:
 * 3
 * Output:
 * 3 is not a Automorphic number.
 * 
 * Input:
 * 25
 * Output:
 * 25 is a Automorphic number.
*/
/*
*Time complexity : O(n) 
*Space complexity : O(1)
*/


<|start_filename|>C-Plus-Plus/ds/heap_sort.cpp<|end_filename|>
#include<iostream>
using namespace std;

void adjust(int a[] , int n ,int i){
    while(2*i+1<=n){
        int j = 2*i+1;
        if(j+1<=n && a[j+1]>a[j])
            j = j+1;
        if(a[i] >= a[j])
            break;
        else{
            int temp = a[i];
            a[i] = a[j];
            a[j] = temp;
            i = j;
        }
    }
}
void heapsort(int a[] , int n){
    for(int i = n/2 - 1;i>=0 ;i--){  //using this for loop for converting it into max heap
        adjust(a,n-1,i);
    }
    cout<<"the max heap is "<<endl;
    for(int i = 0;i<n;i++){    //printing the max heap elements
        cout<<a[i]<<" ";
    }
    cout<<endl;

    while(n>0){           //using this while for given no of elements
        int t = 0;
        t = a[0];            //first swapping of first and last element and then again converting to heap 
        a[0] = a[n-1];
        a[n-1]=t;
        n--;
        adjust(a,n-1,0);
    }


}


int main(){
    int n;
    cin>>n;
    int a[n];
    cout<<"Enter the elements in heap"<<endl;        //accepting the elements in heap
    for(int i=0;i<n;i++){         //heap with index starting from 0
        cin>>a[i];
    }
    heapsort(a,n);            //calling heapsort to sort and convert it into max heap too 
    cout<<"Sorted array is using heapsort is"<<endl;
    for(int i = 0;i<n;i++){
        cout<<a[i]<<" ";
    }
    cout<<endl;

}


/*
OUTPUT :- 
10                                                                                                                
Enter the elements in heap                                                                                        
13                                                                                                                
1                                                                                                                 
2                                                                                                                 
3
4                                                                                                                 
4                                                                                                                 
5
6                                                                                                                 
7
8                                                                                                                 
the max heap is                                                                                                   
13 8 5 7 4 4 2 6 3 1                                                                                              
Sorted array is using heapsort is                                                                                 
1 2 3 4 4 5 6 7 8 13    
*/


<|start_filename|>C-Plus-Plus/dp/Coin_Change_Problem.cpp<|end_filename|>
/*Given a value V, if we want to make change for V cents, and we have infinite supply of each of C = { C1, C2, .. , Cm} valued coins, what is the minimum number of
coins to make the change?
Examples:

Input: coins[] = {25, 10, 5}, V = 30
Output: Minimum 2 coins required
We can use one coin of 25 cents and one of 5 cents 

Input: coins[] = {9, 6, 5, 1}, V = 11
Output: Minimum 2 coins required
We can use one coin of 6 cents and 1 coin of 5 cents */

#include <bits/stdc++.h>

using namespace std;

int main()
{
	int n, coin[100], tot, i, j;
	cout << "Enter number of coins" << endl;
	cin >> n;
	cout << "Enter denominations of coins" << endl;
	for(i = 0; i < n; i++){
		cin >> coin[i];
	}
	cout << "Enter value" << endl;
	cin >> tot;
	int dp[tot + 1] = {0};
	for(i = 1; i <= tot; i++)
	{
		int num = INT_MAX;
		for(j = 0; j < n; j++)
		{
			if(coin[j] <= i)
			num = min(num, dp[i - coin[j]] + 1);    /*bottom-down approach*/
		}
		dp[i] = num;
	}
	cout << dp[tot];
	return 0;
}


<|start_filename|>C-Plus-Plus/Bit--Manipulation/sort_integers_by_their_number_of_set_bits.cpp<|end_filename|>
// C++ program to sort integers by the number of set bits present in their binary equivalence
/*
Given an integer array of numbers, We have to sort these integers in the ascending order by the 
number of set bits(1's) present in their binary equivalence. In case two integers have equal 
number of set bits we have to sort them in ascending order of magnitude.
*/

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

/* We modify the compare method to sort the numbers w.r.t their number of set bits */
static bool compare(const int &a, const int &b)
{
    /* count stores the number of set bits
        and temp variables hold the values of a and b temporarily */
    int count_a_1 = 0, count_b_1 = 0, temp_a = a, temp_b = b;
    // Count number of set bits in a
    while (temp_a)
    {
        temp_a = temp_a & (temp_a - 1);
        count_a_1++;
    }
    // Count number of set bits in b
    while (temp_b)
    {
        temp_b = temp_b & (temp_b - 1);
        count_b_1++;
    }

    // If their counts are equal, check their magnitude.
    if (count_a_1 == count_b_1)
        return a < b;
    return count_a_1 < count_b_1;
}

int main()
{
    int n, ele;
    cout << "How many numbers do you want to sort w.r.t the number of set bits? ";
    cin >> n;
    if (n == 0)
    {
        cout << "There are no numbers to sort!!";
        return 0;
    }
    vector<int> arr;
    cout << "Enter the numbers:";
    for (int i = 0; i < n; i++)
    {
        cin >> ele;
        arr.push_back(ele);
    }
    // Call the sort method, with our modified compare method
    sort(arr.begin(), arr.end(), compare);
    cout << "\nThe sorted array is: ";
    for (int i = 0; i < n; i++)
    {
        cout << arr[i] << " ";
    }

    return 0;
}

/*

Time Complexity: O(logn)
Space Complexity: O(n)

SAMPLE INPUT AND OUTPUT

How many numbers do you want to sort w.r.t the number of set bits? 5
Enter the numbers: 13 2 9 34 22 

The sorted array is: 2 9 34 13 22  

*/


<|start_filename|>Java/cryptography/VigenereCipher.java<|end_filename|>
/* Below code is an implementation of Vigenere Cipher in Java.
It is a form of substitution cipher. Given a plaintext and a key.
If the length of key is smaller than that of plaintext, then we 
repeat the contents of the key in a circular fashion till both of
their lengths is same. Plaintext and key are converted to number 
[0-25] and then each character of plaintext is shifted by character
present at the same index in the key to form the encrypted message.*/

import java.util.*;
import java.lang.*;

public class VigenereCipher {

	/*This method generates the key if the length of key
	is shorter than the length of the plaintext.*/
	static String generateKey(String key, int size) {

		int i = 0;
		/*In a circular fashion, we add the contents of
		the key from front to the end, till the length of
		the key becomes equal to the length of the plaintext.*/
		while(i < size) {
			if(i == size) {
				i = 0;
			}
			if(key.length() == size) {
				break;
			}
			key += key.charAt(i);
			i = i + 1;
		}
		// Return the final key to be used
		return key;
	}

	// This method generates the cipher text
	static String generateCipher(String plaintext, String key) {
		
		/* Calling the above function to ensure that the length
		of the key is same as length of the plaintext*/
		String keyUpdated = generateKey(key, plaintext.length());
		String ciphertext = new String("");

		// Shifting the plaintext to generate the ciphertext
		for(int i = 0; i < plaintext.length(); i++) {
			int temp = 0;
			temp = (plaintext.charAt(i) - 97) + (keyUpdated.charAt(i) - 97);
			temp = temp % 26;
			temp = temp + 97;
			ciphertext += (char) temp;
		}
		// Returns the ciphertext
		return ciphertext;
	}

	/* This method formats the ciphertext according to the plaintext.
	From the encrypt function above, we send plaintext in lowercase.
	So, the ciphertext we get is also in all lowercase. Here, we format
	the ciphertext so that wherever there is capital letter in the plaintext,
	same follows in the ciphertext.*/
	static String format(String plaintext, String ciphertext) {

		String finalencrypted = new String("");

		/* Check wherever the plaintext is capital and
		then capitalize that character in the ciphertext*/
		for(int i = 0; i < plaintext.length(); i++) {
			if(Character.isUpperCase(plaintext.charAt(i))) {
				finalencrypted += Character.toUpperCase(ciphertext.charAt(i));
			}
			else {
				finalencrypted += ciphertext.charAt(i);
			}
		}
		// Return the final formatted ciphertext
		return finalencrypted;
	}

	public static void main(String[] args) {
		
		Scanner scan = new Scanner(System.in);

		// Taking plaintext as input from the user
		System.out.print("Enter a plaintext to encrypt: ");
		String plaintext = scan.nextLine();

		// Taking key as input from the user
		System.out.print("Enter a key to encrypt      : ");
		String key = scan.nextLine();

		scan.close();

		// Generating and formatting the ciphertext
		String ciphertext = generateCipher(plaintext.toLowerCase(), key.toLowerCase());
		String encrypted = format(plaintext, ciphertext);

		// Printing the ciphertext
		System.out.println("Encrypted plaintext is      : " + encrypted);
	}
}

/* Sample I/O:
	Enter a plaintext to encrypt: HelloWorld
	Enter a key to encrypt      : Mercury 
	Encrypted plaintext is      : TicniNmdpu
*/



<|start_filename|>Java/other/SetBitsInInteger.java<|end_filename|>
import java.util.Scanner;

/*
Calculating the set bits(number of 1's in binary form) of an integer
*/

public class SetBitsInInteger
{
    private static Scanner sc  =new Scanner(System.in);
    public static void main(String[] args) {
        
        //asking the user for input and storing the input in int variable n
        System.out.println("Kindly enter the number: ");
        int n= sc.nextInt();

        //converting the entered input(integer) into binary and storing it in string variable binary
        String binary = Integer.toBinaryString(n);
        
        //printing the binary form of the integer
        System.out.println("Binary form: "+binary);

        //we store the number of 1's in count variable
        int count=0;

        //now we iterate through the string and check for the presence of 1's
        for(int i=0;i<binary.length();i++)
        {
            //comparing each character present in the string to '1'
            if(binary.charAt(i)=='1'){
                count++;
            }
        }
        System.out.println(count);
    }
}

/*
Sample Outputs:

Kindly enter the number: 
3
Binary form: 11
2


Kindly enter the number:
2
Binary form: 10
1


Kindly enter the number: 
16
Binary form: 10000
1


Kindly enter the number: 
-12
Binary form: 11111111111111111111111111110100
29

*/


<|start_filename|>C-Plus-Plus/cp/next_greater_element.cpp<|end_filename|>
/* This algorithm will print the next greater element for all the indices in an array using stacks.
The procedure is to store the index of the next greater element in an answer array. Incase, there is no next greater element,
-1 will be stored.*/

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

//Function to print the next greater element
void next_greater(int arr[],int n)
{
   int ans[n]; //declaring an answer array
   for(int i=0;i<n;i++)
   ans[i]=-1;  //marking all the indices with -1 initially

   stack<int> s;
   s.push(0);  //pushing the zeroth index of arr
   
   //iterating through the rest of indices of arr
   for(int i=1;i<n;i++)
   {
       /*If the stack is not empty and the value at cuurent index (arr[i]) is greater than value at s.top(),
        then next greater element for arr[s.top()] will be arr[i]. Once the next greater element for a particular
        index is found, then tha particular index can be popped out*/
     while(s.empty()==false && arr[i]>arr[s.top()]) 
     {                                              
        ans[s.top()]=i;
        s.pop();
     }
    s.push(i); //pushing the current index so that it can be compared with the values to its right in further iterations
   }
   
   //printing the final answer
   for(int i=0;i<n;i++)
   {
     if(ans[i]==-1) //if the value of ans[i] remains -1, it means there is no next greater element for it
     cout<<"-1 ";
     else
     cout<<arr[ans[i]]<<" ";
   }
   return;
}

//Driver Code
int main()
{
 int n;
 cin>>n;
 int arr[n];
 for(int i=0;i<n;i++)
 cin>>arr[i];
 next_greater(arr,n);
 return 0;
}

/* Time Complexity : o(n)
   Space Complexity: O(n)
   Sample Input    : 4
                      4 5 2 25
   Sample Output   : 5 25 25 -1 */


<|start_filename|>Java/cp/DutchFlag.java<|end_filename|>
import java.util.*;
public class DutchFlag {
    private static void dutchNationalFlag(int[] array, int size){
        int start = 0 , mid = 0;
        int end = size-1;

        while(mid < end){
            switch(array[mid]){
                case 0:
                    swap(array,start,mid);
                    start++;
                    mid++;
                    break;
                case 1:
                    mid++;
                    break;
                case 2:
                    swap(array,mid,end);
                    end--;
                    break;
            }
        }
    }
    private static void swap(int[] array, int i, int j){
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int size = sc.nextInt();
        int[] array = new int[size];
        //Input Array:

        for(int i = 0; i < size; i++){
            array[i] = sc.nextInt();
        }

        dutchNationalFlag(array,size);
        //Output
        System.out.println("Sorted Array : ");

        for(int i = 0; i < size; i++){
            System.out.print(array[i]+" ");
        }
    }
}
//Sample output : 
// 8 ->size
// 0 1 2 2 1 1 0 0 -> input array
//Output : s
// Sorted Array : 
// 0 0 0 1 1 1 2 2

<|start_filename|>C-Plus-Plus/cp/ZeroSum.cpp<|end_filename|>
/**
Given an array of integers,
find the largest continuous subarray 
with sum zero
**/

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

vector<int> lszero(vector<int> &A) {
    int start = -1, end = -1, m = 0, l = 0;
    unordered_map<int, int> umap;
    int sum = 0, n = A.size();
    for(int i=0; i<n; i++) {
        sum += A[i];
        if(sum == 0) {
            start = 0;
            end = i;
            m = i+1;
        } else {
            if(umap.find(sum) != umap.end()) {
                l = i-umap[sum];
                if(l > m) {
                    m = l;
                    start = umap[sum]+1;
                    end = i;
                } 
            } else 
                umap[sum] = i;
        }
    }
    
    if(start == -1)
        return vector<int> (0);
    
    vector<int> res(m);
    for(int i=start; i<=end; i++)
        res[i-start] = A[i];
    return res;
}

int main() {
    int n;
    cin >> n;
    vector<int> arr(n);
    for(int i = 0; i < n; i++)
        cin >> arr[i];
    vector<int> ans = lszero(arr);
    cout << "The longest subarray with sum zer is : \n";
    for(int i = 0; i < ans.size(); i++)
        cout << ans[i] << ' ';
    cout << '\n';
    return 0;
}

/**

Input :
5
1 2 -2 4 -4
Output:
The longest subarray with sum zer is : 
2 -2 4 -4 

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

**/

<|start_filename|>Java/sort/BucketSort.java<|end_filename|>
import java.util.*;

class BucketSort {

    private static void bucketSort(float[] arr, int k) {
        if (arr.length < 2)
            return;
        
        // getting upper limit for dividing numbers in buckets
        int length = arr.length;
        float max_val = arr[0];
        for (int i = 1; i<length; i++) {
            max_val = Math.max(max_val, arr[i]);
        }
        max_val += 1;

        //making bucket list and adding buckets in it
        ArrayList<ArrayList<Float>> bucketList = new ArrayList<ArrayList<Float>>();
        for (int i=0; i<k; i++) {
            bucketList.add(new ArrayList<Float>());
        }

        //dividing numbers in different buckets
        for (int i=0; i<length; i++) {
            int bucketIndex = (int) ((arr[i] * k) / max_val);
            bucketList.get(bucketIndex).add(arr[i]);
        }

        // sorting each bucket one by one
        for (int i=0; i<k; i++) {
            Collections.sort(bucketList.get(i));
        }

        //joining buckets
        int pos = 0;
        for (int i=0; i<k; i++) {
            for (int j=0; j<bucketList.get(i).size(); j++) {
                arr[pos] = bucketList.get(i).get(j);
                pos += 1;
            }
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        //taking input array
        System.out.println("Enter size of array:");
        int size = sc.nextInt();
        float arr[] = new float[size];
        System.out.println("Enter array elements:");
        for (int i=0; i<size; i++) {
            arr[i] = sc.nextFloat();
        }
        System.out.println("Enter number of buckets:");
        int bucketNum = sc.nextInt();

        // before sorting
        System.out.println("Array before bucket sort:");
        for (int i=0; i<arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();

        bucketSort(arr, bucketNum);

        // after sorting
        System.out.println("Array after Bucket sort:");
        for (int i=0; i<arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        sc.close();
    }
}
/*
Sample input/output:-

Enter size of array:
10
Enter array elements:
88
26
77
49
91
62
33
85
99
11
Enter number of buckets:
5
Array before bucket sort:
88.0 26.0 77.0 49.0 91.0 62.0 33.0 85.0 99.0 11.0 
Array after Bucket sort:
11.0 26.0 33.0 49.0 62.0 77.0 85.0 88.0 91.0 99.0
*/


<|start_filename|>JavaScript/math/ArmstrongNumbers.js<|end_filename|>
//program for an armstrong number or not

//first we take input for the number
let number = "153"
    //window.prompt("enter a positive no");
    //then we calculate the no of digits 
let n = number.length
console.log(n)
    //we store our number in a temporary variable
let temp = number
    //variable for summing up the digits raised to the total no of digits
let sum = 0


while (temp > 0) {

    //extracting the last digit
    let rem = temp % 10;

    //summation
    sum += parseInt(rem ** n);

    // removing last digit from the number
    // convert float into integer
    temp = parseInt(temp / 10);
}

//checking for armstrong no.
if (sum == number) {
    console.log(`${number} is an Armstrong number`);
} else {
    console.log(`${number} is not an Armstrong number.`);
}

<|start_filename|>Java/cp/Subarray.java<|end_filename|>
/* Find Subarray of an array with given sum in O(n) time.

Input :
arr[]={1,4,20,3,10,5} ; sum=33
Output :
Sum found between indexes 2 and 4
 * 
 */
// to find Subarray of an array with given sum in O(n) time
import java.util.*;
class Subarray {
    public static void findsubarray(List < Integer > arr, int sum) {
        int startindex = 0, endindex = 0, tempsum = 0;
        boolean flag = true;
        while (tempsum != sum) {
            if (tempsum < sum) {
                tempsum += arr.get(endindex);
                endindex += 1;
            } else if (tempsum > sum) {
                tempsum -= arr.get(startindex);
                startindex += 1;
            }
            if (endindex == arr.size()) {
                flag = false;
                tempsum = sum;
            }

        }
        if (flag)
            System.out.println("Sum found between indexes " + startindex + " and " + (endindex - 1));
        else
            System.out.println(" No such subarray found");
    }
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        List < Integer > arr = new ArrayList < > ();
        System.out.print("Enter sum : ");
        int sum = sc.nextInt();
        System.out.println("Enter elements of array");
        while (sc.hasNextInt())
            arr.add(sc.nextInt());
        //System.out.println(arr);
        findsubarray(arr, sum);

    }
}

/* Sample Input and Output : 
 * Enter sum : 33
Enter elements of array
1 4 20 3 10 5
Sum found between indexes 2 and 4
Enter sum : 33
Enter elements of array
1 4 20 3 20 5
No such subarray found

Time Complexity : O(n)
Space Complexity : O(1)
 */


<|start_filename|>C-Plus-Plus/cp/infix_to_postfix.cpp<|end_filename|>
// Author: <NAME>

/*
   C++ code for Conversion of infix expression to post fix expression.
*/

#include <bits/stdc++.h>

using namespace std;

//Function declarations

// Function to convert Infix expression to postfix
string InfixToPostfix(string expression);

// Function to verify whether an operator has higher precedence over other
int HasHigherPrecedence(char operator1, char operator2);

// Function to verify whether a character is operator symbol or not.
bool IsOperator(char C);

// Function to verify whether a character is alphanumeric chanaracter
//(letter or numeric digit) or not.
bool IsOperand(char C);

// Function to check whether a char is an opening parenthesis i.e '(' or '{' or '['
bool IsOpeningParentheses(char C);

// Function to check whether a char is an closing parenthesis i.e ')' or '}' or ']'
bool IsClosingParentheses(char C);

int main()
{
	string expression;
	cout<<"Enter Infix Expression \n";
	getline(cin,expression);
	string postfix = InfixToPostfix(expression);
	cout<<"Output = "<<postfix<<"\n";
}

// Function to evaluate Postfix expression and return output
string InfixToPostfix(string expression)
{
	// Declaring a Stack from Standard template library in C++.
	stack<char> S;
	string postfix = ""; // Initialize postfix as empty string.
	for(int i = 0;i< expression.length();i++) {

		// Scanning each character from left.
		// If character is a delimiter, move on.
		if(expression[i] == ' ' || expression[i] == ',') continue;

		// Else if character is an operand then just append it in res string
		else if(IsOperand(expression[i]))
		{
			postfix +=expression[i];
		}

		//If character is operator, check for Higher precedence operator in Stack top
		//till first opening bracket and pop all such operators
		//Finally push the current operator on the Stack
		else if(IsOperator(expression[i]))
		{
			while(!S.empty() && !IsOpeningParentheses(S.top())
            		&& HasHigherPrecedence(S.top(),expression[i]))
			{
				postfix+= S.top();
				S.pop();
			}
			S.push(expression[i]);
		}

		//If opening Parentheses simply push it on the Stack
		else if(IsOpeningParentheses(expression[i]))
		{
			S.push(expression[i]);
		}

        //If Closing Parentheses then pop all the operators and append to res string
        // until Stack top is opening Parentheses and finally one extra pop for Opening Parentheses
		else if(IsClosingParentheses(expression[i]))
		{
			while(!S.empty() && !IsOpeningParentheses(S.top())) {
				postfix += S.top();
				S.pop();
			}
			S.pop();
		}
	}

    //Finally pop and append all operators till Stack is not empty
	while(!S.empty()) {
		postfix += S.top();
		S.pop();
	}

	return postfix;
}

// Function to verify whether a character is english letter or numeric digit.
// We are assuming in this solution that operand will be a single character
bool IsOperand(char C)
{
	if(C >= '0' && C <= '9') return true;
	if(C >= 'a' && C <= 'z') return true;
	if(C >= 'A' && C <= 'Z') return true;
	return false;
}

// Function to verify whether a character is operator symbol or not.
bool IsOperator(char C)
{
	if(C == '+' || C == '-' || C == '*' || C == '/' || C== '^')
		return true;

	return false;
}

bool IsOpeningParentheses(char C)
{
    if(C == '(' || C == '{' || C=='[')
        return true ;
    return false;
}

bool IsClosingParentheses(char C)
{
    if(C == ')' || C == '}' || C==']')
        return true ;
    return false;
}
// Function to verify whether an operator is right associative or not.
int IsRightAssociative(char op)
{
	if(op == '^') return true;
	return false;
}

// Function to get weight of an operator. An operator with higher weight will have higher precedence.
int GetOperatorWeight(char op)
{
	int weight = -1;
	switch(op)
	{
	case '+':
	case '-':
		weight = 1;
		break ;
	case '*':
	case '/':
		weight = 2;
		break ;
	case '^':
		weight = 3;
		break ;
	}
	return weight;
}

// Function to perform an operation and return output.
int HasHigherPrecedence(char op1, char op2)
{
	int op1Weight = GetOperatorWeight(op1);
	int op2Weight = GetOperatorWeight(op2);

	// If operators have equal precedence, return true if they are left associative.
	// return false, if right associative.
	// if operator is left-associative, left one should be given priority.
	if(op1Weight == op2Weight)
	{
		if(IsRightAssociative(op1)) return false;
		else return true;
	}
	return op1Weight > op2Weight ?  true: false;
}


/*
        Sample input and its output:-
	Input = a+b*c-(d/e+f*g*h)
	Output = abc*+de/fg*h*+-
*/


<|start_filename|>Go/cryptography/Caesar_Cipher/Caesar_Cipher.go<|end_filename|>
/* This code is an implementation of caesar cipher. Here the 
plaintext is shifted by a fixed amount. The shift is chosen by
the user. Each alphabet of plaintext is then converted to decimal,
shifted, and then again converted back to ascii to form the 
ciphertext. Here the input plaintext must be all in lowercase*/

package main

import (
	"fmt"
	"bufio"
	"os"
)

// This is the encryption function
func caesar(plaintext string, shift int) string {

	/* Updating the plaintext by replacing all
	the spaces with underscores.*/
	var message string
	for j:= 0; j < len(plaintext); j++ {
		if(string(plaintext[j]) == " ") {
			message += string("_")
		} else {
			message += string(plaintext[j])
		}
	}

	// Cipher text string
	var cipher string
	// Iterating through each alphabet of plaintext
	for i:=0; i < len(message); i++ {
		/* Shift the alphabets of plaintext. If it is
		an underscore, add a space in ciphertext*/
		if(string(message[i]) != "_") {
			var temp int = (int(plaintext[i]) + shift - 97) % 26
			temp = temp + 97
			cipher += string(temp)
		} else {
			cipher += " "
		}
	}
	// Return the ciphertext
	return cipher
}

func main() {

	// Taking plaintext as input from the user
	fmt.Print("Enter a plaintext: ")
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	plaintext := scanner.Text()

	// Taking the shift amount as input from user
	var shift int
	fmt.Print("Enter the shift  : ")
	fmt.Scan(&shift)

	// Calling the encryption function, print the ciphertext
	var ciphertext string = caesar(plaintext, shift)
	fmt.Print("\nEncrypted plaintext is: ", ciphertext, "\n")
}

/* Sample I/O:

Enter a plaintext: this is a ciphertext
Enter the shift  : 7

Encrypted plaintext is: aopz pz h jpwolyalea

*/



<|start_filename|>Java/ds/PriorityQueueEg.java<|end_filename|>
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Scanner;

/*Priority Queue data structure is a special queue in which the elements are present not as per FIFO order 
 *but as per the natural elements or any xyz comparator used during queue creation.
*/

public class PriorityQueueEg {
    
    private static Scanner sc = new Scanner(System.in);

    public static void printingthequeue(PriorityQueue<String> queue) {
        Iterator iterator = queue.iterator();  
        while(iterator.hasNext())
        { 
            System.out.print(iterator.next() + " ");  
        }  
    }

    public static void main(String args[])
    {  
        System.out.println("Kindly enter the number of strings in the queue: ");
        int n = sc.nextInt();

        PriorityQueue<String> queue = new PriorityQueue<String>();  
        
        //taking n strings as input from the user
        for(int i=0;i<n;i++)
        {
            System.out.println("Kindly enter the "+i+"'th element");
            queue.add(sc.next());
        }

        //print the head of the PriorityQueue
        System.out.println("PriorityQueue Head : "+ queue.element());  
        
        //Define the iterator for PriorityQueue and print its elements 
        System.out.println("\nPriorityQueue : "); 

        //to print the queue, using Iterator
        printingthequeue(queue);
    }

}

/*
Output:

Kindly enter the number of strings in the queue:                                                                                              
3                                                                                                                                             
Kindly enter the 0'th element                                                                                                                 
ram                                                                                                                                           
Kindly enter the 1'th element                                                                                                                 
seeta                                                                                                                                         
Kindly enter the 2'th element                                                                                                                 
geeta                                                                                                                                         
PriorityQueue Head : geeta                                                                                                                    
PriorityQueue :                                                                                                                               
geeta seeta ram   

*/



<|start_filename|>C/ds/List_deletenode_func.c<|end_filename|>
/*
 * Definition of a  singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

// Below is the function to delete node

#include <stdio.h>
#include <stdlib.h>

struct node
{
    int data;
    struct node *next;
};

struct node *newNode(int data)
{
    struct node *n = (struct node *)malloc(sizeof(struct node *));
    n->data = data;
    n->next = NULL;
    return n;
}

void deleteNode(struct node *ref)
{
    while (ref->next != NULL)
    {
        ref->data = ref->next->data; //NODE TO BE DELETE POINTER GIVEN
        ref = ref->next;
    }
    free(ref);
}

void main()
{
    struct node *n = newNode(1);
    n->next = newNode(2);
    n->next->next = newNode(3);
    n->next->next->next = newNode(4);
    n->next->next->next->next = newNode(5);
    n->next->next->next->next->next = newNode(6);

    deleteNode(n->next->next->next); // deletion node is  4

    while (n->next != NULL)
    {
        printf("%d\n", n->data);
        n = n->next;
    }
}

/* OUTPUT
1 2 3 4 5 NULL
1 2 3 5 NULL
Time Complexity: O(1)
Space complexity: O(n)
*/


<|start_filename|>Java/cp/Staircase_problem.java<|end_filename|>
/*This program finds the total number of possible combinations that can be used to
climb statirs . EG : for 3 stairs ,combination and output will be 1,1,1 , 1,2 , 2,1 i.e 3 . */
import java.util.Scanner;

class Staircase_problem{
    public static void main(String args[]){
        int count_stairs=0;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter total number of Stairs:"); 
        count_stairs = input.nextInt();
        Staircase_problem sp = new Staircase_problem();
        int final_steps = sp.possibilities_count(count_stairs); 
        System.out.println("Total Number of possible Combinations = "+final_steps);
    }

    int possibilities_count(int a){
        int result = a;
        /*Using Recursion to find the total number of stairs as f(a) = f(a-1) + a(a-2) 
        where f(a) is the final result */
        if(result <= 1){
            result =  1;
        }else{
            result = possibilities_count(a-1) + possibilities_count(a-2);
        }
        return result;
    }
}
/* Output 
Enter total number of Stairs:
4
Total Number of possible Combinations = 5
*/
// Time Complexity : O(2^n)
// Space Complexity :O(1)
// Created by <NAME> on 16-12-2020 on WoC


<|start_filename|>Dart/search/BinarySearch.dart<|end_filename|>
/**
Function to search for a given element in a list using binary search algorithm.
For this algorithm we need a sorted list. After getting the list, we compare
the value of the element to be searched with the middle value and then search
for it either in the half before the middle element or after it. This way our
search area gets reduced by half.
 */
import 'dart:io';

//function which runs the binary search algorithm
int binarySearch(List arr, int num) {
  // initial bounds of array
  int low = 0;
  int high = arr.length - 1;

  while (low <= high) {
    // find middle position of the bounds
    int mid = (low + high) ~/ 2;
    // if num is found, return index
    if (arr[mid] == num) {
      return mid;
    }
    // if num > mid, that means it might be in the 2nd half of the list
    // so we increase the lower bound by 1 to get into that half
    else if (arr[mid] < num) {
      low++;
    }
    // else if num < mid, we try for first half by decreasing upper bound
    else {
      high--;
    }
  }
  // return invalid index to show that element is not in the list
  return -1;
}

// main function, entry point of program
void main() {
  print("Enter the size of list:");
  int size = int.parse(stdin.readLineSync()!);
  List arr = [];
  print("Enter the sorted list:");
  for (int i = 0; i < size; i++) {
    arr.add(int.parse(stdin.readLineSync()!));
  }
  print("Enter the number to be searched:");
  int num = int.parse(stdin.readLineSync()!);
  // sorting
  int result = binarySearch(arr, num);
  if (result != -1) {
    print("$num found at position: ${result + 1}");
  } else {
    print("$num not found in the list.");
  }
}

/**
Enter the size of list:
6
Enter the sorted list:
12
25
32
47
56
68
Enter the number to be searched:
47
47 found at position: 4

Time complexity: O(log n)
Space complexity: O(1)
 */


<|start_filename|>Java/cp/StockSpan.java<|end_filename|>
/*

Stock Span Problem
===================
You are given the price of a stock for N consecutive days and are required to find the span
of stock's price on ith day. The span of a stock's price on a given day i, is the maximum
consecutive days before the (i+1)th day, for which the stock's price is less than equal to that on
the ith day.

*/

import java.util.*;

public class StockSpan {
	public static void main(String args[]) {
		// Input number of days
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int[] price = new int[n];
		int[] span = new int[n];

		// Input price for n days
		for (int i = 0; i < n; i++)
			price[i] = sc.nextInt();

		// Stack for keeping track of span of largest element till now
		Stack<Integer> s = new Stack<Integer>();
		// Push first element in the stack
		s.push(0);
		// Span for first day will always be 1
		span[0] = 1;

		// Looping through rest of the days
		for (int i = 1; i < n; i++) {

			// While we have elements in the stack and currPrice is greater than equal to topPrice
			// keeping popping out elements and update the currSpan
			while (s.empty() == false && price[s.peek()] <= price[i])
				// Pop out the topmost element as its price was less than currPrice
				s.pop();

			// Calculate the span for the current day
			span[i] = (s.empty()) ? i + 1 : i - s.peek();
			// Push curr element into the stack
			s.push(i);
		}

		// Print ans
		for (int i = 0; i < n; i++)
			System.out.print(span[i] + " ");
		System.out.println();
	}
}


/*

Input :
5
30 35 40 38 35
Output :
1 2 3 1 1

Application: Stack data structure
Time Complexity: O(n)
Space Complexity: O(n)

*/




<|start_filename|>Go/dp/coin_change/coin_change_problem.go<|end_filename|>
// Given a value N, if we want to make change for N cents,
// and we have infinite supply of each of S = { S1, S2, .. , Sm}
// valued coins, how many ways can we make the change?
// The order of coins doesn’t matter.

package main

import "fmt"

// function to count coins
func countCoins(coins []int, numberOfCoin, value int) int {
	// creating 2d slice
	dp := make([][]int, value+1)
	for itr := 0; itr <= value; itr++ {
		dp[itr] = make([]int, numberOfCoin)
	}

	// value if n = 0
	for i := 0; i < numberOfCoin; i++ {
		dp[0][i] = 1
	}

	// bottom up manner
	for i := 1; i < value+1; i++ {
		for j := 0; j < numberOfCoin; j++ {

			var x int
			if i-coins[j] >= 0 {
				x = dp[i-coins[j]][j]
			} else {
				x = 0
			}

			var y int
			if j >= 1 {
				y = dp[i][j-1]
			} else {
				y = 0
			}

			dp[i][j] = x + y
		}
	}
	return dp[value][numberOfCoin-1]
}

func main() {
	fmt.Print("Enter the number of coins : ")
	var numberOfCoin int
	fmt.Scan(&numberOfCoin)

	fmt.Print("Enter the value of coins : ")
	coins := make([]int, numberOfCoin)
	for itr := 0; itr < numberOfCoin; itr++ {
		fmt.Scan(&coins[itr])
	}

	fmt.Print("Enter the amount : ")
	var value int
	fmt.Scan(&value)

	count := countCoins(coins, numberOfCoin, value)

	fmt.Println("Number of coins : ", count)
}

// Time complexity : O(numberOfCoin * value)
// Space complexity : O(numberOfCoin * value)

// TEST CASE 1:
// Enter the number of coins : 3
// Enter the value of coins : 1 2 3
// Enter the amount : 4
// Number of coins :  4

// TEST CASE 2:
// Enter the number of coins : 4
// Enter the value of coins : 2 5 3 6
// Enter the amount : 10
// Number of coins :  5


<|start_filename|>C-Plus-Plus/graphs/detect_cycle.cpp<|end_filename|>
#include<bits/stdc++.h>
#define Graph unordered_map<int, vector<int>>
#define vb vector<bool>
using namespace std;

bool dfs (int curr, vb visited, Graph graph) {
  if(!visited[curr]) {

    visited[curr] = true;
    for(int i=0; i < graph[curr].size(); i++)
      return dfs(graph[curr][i], visited, graph);

  } else
    return true;
}

bool detectCycle(int edges, Graph graph) {

  vb visited(edges, false);

  for(auto it : graph) {
    visited[it.first] = true;
    int sz = it.second.size();

    for(int i=0; i<sz; i++) {
        // do dfs and check for visited is once againg visiting or not
        if(dfs( it.second[i], visited, graph))
          return true;
    }
    visited[it.first] = false;
  }

  // dfs checked for all vertices and there we found no Cycle
    return false;
}

int main() {
  std::cout << "Enter total number of edges in your graph : ";

  freopen("input.txt","r",stdin);
  freopen("output.txt","w",stdout);

  int edges;
  cin>>edges;

// data structure used for creation of graph
  Graph graph;

// creation of graph
int traversegde = edges;
  while (traversegde--) {
    int x;
    int y;
    cin >> x >> y;
    graph[x].push_back(y);
  }

  detectCycle( edges, graph )
  ? std::cout << "Yes there is Cycle in graph" << '\n'
  : std::cout << "No there isn't any Cycle in graph" << '\n';

  return 0;
}


<|start_filename|>C/math/Binary_Exponentiation.c<|end_filename|>
// C Program to find Binary Exponent Iteratively and Recursively.

#include <stdio.h>

// Iterative function to calculate exponent.

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

// Recursive function to calculate exponent.

int binExpo_recurse(int a, int b)
{
    if (b == 0)
    {
        return 1;
    }
    int res = binExpo_recurse(a, b / 2);
    if (b % 2)
    {
        return res * res * a;
    }
    else
    {
        return res * res;
    }
}

// Main function

int main()
{
    int a, b;

    scanf("%d%d", &a, &b);

    if (a == 0 && b == 0)
    {
        printf("Math Error");
    }
    else if (b < 0)
    {
        printf("Exponent must be Positive");
    }
    else
    {
        int resIterate = binExpo_iterate(a, b);
        int resRecurse = binExpo_recurse(a, b);

        printf("%d", resIterate);
        printf("%d", resRecurse);
    }
}


<|start_filename|>Java/dp/Kadane_Algorithm.java<|end_filename|>
import java.util.*;
 class abc
{   static long findMaxSumArray(long arr[],int x)
    {   long currentSum=0,maxSum=0;int i;
        
        for(i=0;i<x;i++)
        {currentSum+=arr[i];
            if(currentSum<0)
            currentSum=0;
        maxSum=Math.max(currentSum,maxSum);}
        
       
        return maxSum;
    }
    public static void main()
    {
        Scanner sc=new Scanner(System.in);
        int i,j,k,l,m,n;
        n=sc.nextInt();long sum=0,maxSum=0;
        long a[]=new long[n];
        for(i=0;i<n;i++)
        a[i]=sc.nextLong();
        
        sum=findMaxSumArray(a,n);
        System.out.println(sum);
    }
}
/* Input/Output-
5
4 2 -3 -1 8
10 */


<|start_filename|>C-Sharp/sort/MergeSort.cs<|end_filename|>
﻿// Implementation of MergeSort a comparison-based sorting algorithm. It works on the principle of Divide and Conquer.

using System;

namespace MergeSortAlgorithm
{
    class Merge_Sort
    {
        //The merge step to sort the elements
        private static void Merge(int[] arr, int[] temp, int leftStart, int mid, int rightEnd)
        {
            int left = leftStart, right = mid + 1, index = left;
            //Compare Elments from arr portion and sort them in temproray array temp
            while (left < mid + 1 && right <= rightEnd)
            {
                if (arr[right] < arr[left])
                {
                    temp[index] = arr[right++];
                }
                else
                {
                    temp[index] = arr[left++];
                }
                index++;
            }
            // if the arr porion sorted but i didn't reach the last element place the rest in temp 
            for (; left <= mid; left++)
                temp[index++] = arr[left];
            // if the arr porion sorted but j didn't reach the last element place the rest in temp 
            for (; right <= rightEnd; right++)
                temp[index++] = arr[right];
            //Place the sorted elements from temp into arr
            for (left = leftStart; left <= rightEnd; left++)
                arr[left] = temp[left];
        }
        // recursive part in merge sort to break the array into smaller portions
        private static void MergeSort(int[] arr, int[] temp, int leftStart, int rightEnd)
        {
            if (leftStart < rightEnd)
            {
                int mid = leftStart + (rightEnd - leftStart) / 2;
                MergeSort(arr, temp, leftStart, mid);
                MergeSort(arr, temp, mid + 1, rightEnd);
                Merge(arr, temp, leftStart, mid, rightEnd);
            }

        }
        //Limit the number of parameters
        public static void MergeSort(int[] arr)
        {
            MergeSort(arr, new int[arr.Length], 0, arr.Length - 1);

        }
        static void Main(string[] args)
        {
            Console.Write("Enter array size: ");
            int n = Convert.ToInt32(Console.ReadLine());
            int[] arr = new int[n];
            Console.WriteLine("Enter array Elements: ");
            for(int i = 0; i<n; i++)
            {
                arr[i] = Convert.ToInt32(Console.ReadLine());
            }
            MergeSort(arr);
            foreach (var i in arr)
            {
                Console.Write(i + " ");
            }
        }
    }
}
/*
Sample Input


Enter array size: 8
Enter arry elements : 
23
21
12
34
2
5
7
10

input array : 23 21 12 34 2 5 7 10

merge sorted arry output: 2 5 7 10 12 21 23 34

Complexity:
Merge sort takes time complexity of O(nlogn) and space complexity of O(n)
 
 */


<|start_filename|>C/cryptography/Vernam_Cipher.c<|end_filename|>
/*In Vernam cipher(also known as the One-Time Pad), the length of the plaintext, ciphertext, and key is the same.
  Below is an implementation of Vernam cipher in the C language.*/

/*Basically, here the ith letter of the cipher text is fomred by shifting the ith letter of the plaintext with 
 * the ith letter of key.
 * */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

//This defines the maximum length of the string in which we want to perform encrypt and decrypt operations.
#define LENGTH_MAX 100 

// This is the decrypt function which takes ciphertext and key as input
char *decrypt(char *ciphertext, char *key) { 

	static char decrypted[LENGTH_MAX];

	for(int i = 0; i < strlen(key); i++) {

		//Convert the character to ASCII
		int ct = ciphertext[i] - 0;

		ct -= 65;
		//We number alphabets as A-0, B-1, ..... , Z-25. So, 
		//We shift the obtained ASCII value by 65.	

		//We perform similar steps for the key.
		int k = key[i] - 0;
		k -= 65;
		
		//The plaintext is obtained by shifting the ciphertext backwards by the key
		int pt = ct - k;
		
		//If the value goes below 0, we add 26 to it, as number of cycle doesn't matter
		//Since, at last we take mod by 26.	
		while(pt < 0) {
			pt += 26;
		}

		pt = pt % 26;
		
		//We add back 65 to convert it back to ASCII and then to char
		pt += 65;

		char plaintext = pt;

		decrypted[i] = plaintext;
	}
	//Return the decrypted message	
	return decrypted;	
}

// This is the encrypt function which takes plaintext and key as input
char* encrypt(char *plaintext, char *key) { 

	static char encrypted[LENGTH_MAX];

	for(int i = 0; i < strlen(key); i++) {
	
		//Convert the character to ASCII
		int pt = plaintext[i] - 0;

		//We number alphabets as A-0, B-1, ..... , Z-25. So, 
		//We shift the obtained ASCII value by 65.
		pt -= 65;

		//We perform similar steps for the key.
		int k = key[i] - 0;
		k -= 65;

		//The ciphertext is obtained by shifting the ciphertext backwards by the key
		int cipher = pt + k;
		cipher = cipher %  26;

		//We add back 65 to convert it back to ASCII and then to char
		cipher += 65;

		char enc = cipher;

		encrypted[i] = enc;
	}

	//Return the decrypted message
	return encrypted;               
}

int main() {
	
	//while true
	while(1) {

	//Ask user for input on what he wants to perform
	printf("\nVERNAM CIPHER\n");

	printf("\n1. Encrypt a plaintext\n");

	printf("2. Decrypt a ciphertext\n");

	printf("3. Exit\n\n");
	
	printf("Enter your choice - ");

	int choice;
	
	//Take choice of user
	scanf("%d", &choice);
	
	//If user has chosen to exit
	if(choice == 3) 
		exit(0);
	
	//If the user has chosen to encrypt
	else if(choice == 1) {
		
		char message[LENGTH_MAX];
		
		printf("Enter the plaintext you want to encrypt         - ");
		
		//Take the plaintext message as input from the user
		scanf("%s", message);

		int len_plaintext = strlen(message);

		// Converts all characters to upper case to maintain unity
		for (int i = 0; message[i] != '\0'; i++) { 
			
			if(message[i] >= 'a' && message[i] <= 'z') {
      			
				message[i] -= 32;
   			}
		}

		char key[LENGTH_MAX];

		printf("Enter the key of the same size as the plaintext - ");

		scanf("%s", key);

		int len_key = strlen(key);

		// Checks if the length of the key is equal to that of plaintext or not
		// If not then prompts user for entering another key
		while(len_key != len_plaintext) { 
						  		
			printf("\nPlease enter a key whose length is same as that of the plaintext.\n");
			printf("Key - ");
			scanf("%s", key);
			len_key = strlen(key);
		}

		// Converts all characters to upper case to maintain unity
		for(int i = 0; key[i] != '\0'; i++) {

			if(key[i] >= 'a' && key[i] <= 'z') {
				key[i] -= 32;
			}
		}
		
		//Print the encrypted text
		printf("\nThe encrypted text is %s\n", encrypt(&message[0], &key[0]));
	
	}
	
	//If the user has chosen to decrypt
	else if(choice == 2) {
		
		char ciphertext[LENGTH_MAX];

		printf("Enter the ciphertext you want to decrypt         - ");
		
		//Take ciphertext as input from user
		scanf("%s", ciphertext);

		int len_ciphertext = strlen(ciphertext);

		// Converts all characters to upper case to maintain unity
		for (int i = 0; ciphertext[i] != '\0'; i++) {

   			if(ciphertext[i] >= 'a' && ciphertext[i] <= 'z') {
	
				ciphertext[i] -= 32;
   			}
		}

		char key[LENGTH_MAX];

		printf("Enter the key of the same size as the ciphertext - ");

		scanf("%s", key);

		int len_key = strlen(key);

		// Checks if the length of the key is equal to that of ciphertext or not
		// If not then prompts user for entering another key
		while(len_key != len_ciphertext) {

			printf("\nPlease enter a key whose length is same as that of the ciphertext.\n");
			printf("Key - ");
			scanf("%s", key);
			len_key = strlen(key);
		}

		// Converts all characters to upper case to maintain unity
		for(int i = 0; key[i] != '\0'; i++) {

			if(key[i] >= 'a' && key[i] <= 'z') {
			
				key[i] -= 32;
			}
		}

		printf("\nThe decrypted text is %s\n", decrypt(&ciphertext[0], &key[0]));
	
	}

	else {
		printf("\nPlease enter a valid choice.\n");
	}

	}

	return 0;
}

/*Test Case - 

VERNAM CIPHER

1. Encrypt a plaintext
2. Decrypt a ciphertext
3. Exit

Enter your choice - 1
Enter the plaintext you want to encrypt         - thisisatestcase
Enter the key of the same size as the plaintext - thisisthereqkey

The encrypted text is MOQKQKTAIJXSKWC

VERNAM CIPHER

1. Encrypt a plaintext
2. Decrypt a ciphertext
3. Exit

Enter your choice - 2
Enter the ciphertext you want to decrypt         - moqkqktaijxskwc
Enter the key of the same size as the ciphertext - thisisthereqkey

The decrypted text is THISISATESTCASE

VERNAM CIPHER

1. Encrypt a plaintext
2. Decrypt a ciphertext
3. Exit

Enter your choice - 4

Please enter a valid choice.

VERNAM CIPHER

1. Encrypt a plaintext
2. Decrypt a ciphertext
3. Exit

Enter your choice - 3
 *
 * */





<|start_filename|>JavaScript/ds/Parenthesis_Checker.js<|end_filename|>
function checkclosingParen(lastParen, currParen) {
  return (
    (lastParen === "(" && currParen === ")") ||
    (lastParen === "[" && currParen === "]") ||
    (lastParen === "{" && currParen === "}")
  );
}

function BalancedParen(parenString) {
  let pseudoStack = []; // Using Array(object) as stack therefore named as pseudoStack
  for (let i = 0; i < parenString.length; i++) {
    if (
      parenString[i] == "(" ||
      parenString[i] == "[" ||
      parenString[i] == "{"
    ) {
      pseudoStack.push(parenString[i]);
    } else {
      if (pseudoStack.length === 0) return "Unbalanced";
      else if (
        checkclosingParen(pseudoStack[pseudoStack.length - 1], parenString[i])
      )
        pseudoStack.pop();
      else return "Unbalanced";
    }
  }
  if (pseudoStack.length === 0) return "Balanced";
  else return "Unbalanced";
}

let parenString1 = "[]{}()";
let parenString2 = "[{}()]";
let parenString3 = "[{()}]";
let parenString4 = "][(){";
let parenString5 = "[{]}";

console.log(BalancedParen(parenString1)); // Balanced
console.log(BalancedParen(parenString2)); // Balanced
console.log(BalancedParen(parenString3)); // Balanced
console.log(BalancedParen(parenString4)); // Unbalanced
console.log(BalancedParen(parenString5)); // Unbalanced


<|start_filename|>Java/cp/Sort_2D_Array.java<|end_filename|>
import java.util.*;
class Sort_2D_Array {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of rows and columns");
        int m = sc.nextInt();
        int n = sc.nextInt();
        int arr[][] = new int[m][n];
        System.out.println("Enter the elements of the array");
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                arr[i][j] = sc.nextInt();

        System.out.println("Enter the column to be sorted");
        int k = sc.nextInt();
        sort(arr, k, m);

    }

    public static void sort(int[][] arr, int col, int row) {
        int max = 0, ind = -1;
        for (int j = 0; j < row - 1; j++) {
            max = arr[j][col];
            ind = -1;
            for (int i = (j + 1); i < row; i++) {
                if (arr[i][col] > max) {
                    max = arr[i][col];
                    ind = i;
                }
            }

            if (ind != -1) {
                for (int k = 0; k <= col; k++) {
                    int temp = arr[j][k];
                    arr[j][k] = arr[ind][k];
                    arr[ind][k] = temp;
                }
            }
        }
        for (int[] x : arr) {
            for (int y : x) {
                System.out.print(y + "        ");
            }
            System.out.println();
        }

    }
}
/*
Enter number of rows and columns
4
4
Enter the elements of the array
39 27 11 42
10 93 91 90
54 78 56 89
24 64 20 65
Enter the column to be sorted
3
10        93        91        90
54        78        56        89
24        64        20        65
39        27        11        42

Space Complexity : O(1)
Time Complexity : O(m^2)
 */


<|start_filename|>C/graphs/Adjacency_List.c<|end_filename|>
/* ADJACENCY LIST FOR REPRESENTING DIRECTED GRAPH
    It is a method of representing a digraph using 2 linked lists
        1. Node list
        2. Edge list corresponding to each node
    Edges arising from a node are stored in edge list of each node
*/

#include <stdio.h>
#include <stdlib.h>

/* Declare a structure for representing digraph with data and 2 links
 * link represents the edge between the parent node and next node (edge list)
 * pnext point to the next node from which new edges arise(node list)
 * g points to the graph
*/
typedef struct AdjacencyList
{
    int data;
    struct AdjacencyList *link, *pnext;
} AdjacencyList;
AdjacencyList *g;

//to insert into the graph
void insert_to_graph(AdjacencyList *g, int parent, int value)
{
    //ptr points to the first node in the graph
    AdjacencyList *ptr = g->link, *p;
    //Check if the graph is empty
    if (g->link == NULL)
    {
        //Allocate memory for ptr to store the value of parent node
        ptr = malloc(sizeof(AdjacencyList));
        ptr->data = parent;
        ptr->pnext = NULL;
        ptr->link = NULL;
        // Set ptr as first node
        g->link = ptr;
    }
    else
    {
        //Search for parent in the node list
        while (ptr != NULL && ptr->data != parent)
        {
            p = ptr;
            ptr = ptr->pnext;
        }
        //If parent is not found in the node list insert as last node
        if (ptr == NULL)
        {
            ptr = malloc(sizeof(AdjacencyList));
            ptr->data = parent;
            ptr->pnext = NULL;
            ptr->link = NULL;
            p->pnext = ptr;
        }
    }
    //Allocate memory for node to insert value in the edge list of parent node
    AdjacencyList *node;
    node = (AdjacencyList *)malloc(sizeof(AdjacencyList));
    node->data = value;
    node->link = NULL;
    node->pnext = NULL;
    //Traverse till the end of the edge list
    while (ptr->link != NULL)
        ptr = ptr->link;
    //Insert value as the last node in the edge list
    ptr->link = node;
}

//To delete a node from the graph
void delete_from_graph(AdjacencyList *g, int value)
{
    //Set flag as 0 assuming value is not present in the graph
    int flag = 0;
    //If the graph is not empty
    if (g->link != NULL)
    {
        //ptr points to first node
        AdjacencyList *ptr = g->link, *p, *pre;
        //If the first node in the node list is value
        if (ptr->data == value)
        {
            //Delete the node and make the next node in node list as first node
            g->link = ptr->pnext;
            //value is present in the graph
            flag = 1;
        }
        //If value is not the first node
        else
        {
            //Traverse the node list till value is found
            while (ptr->pnext != NULL && ptr->data != value)
            {
                p = ptr;
                ptr = ptr->pnext;
            }
            //If value is found
            if (ptr->data == value)
            {
                //delete value node from the node list and rearrange pnext
                p->pnext = ptr->pnext;
                //value is present in the graph
                flag = 1;
            }
        }
        //ptr points to first node in the node list
        ptr = g->link;
        //Traverse till the end of the node list
        while (ptr != NULL)
        {
            //p is set as ptr
            p = ptr;
            //traverse the edge list of p till value is found
            while (p->link && p->data != value)
            {
                pre = p;
                p = p->link;
            }
            // If value is found in the edge list of p
            if (p->data == value)
            {
                //delete the edge between value and p
                pre->link = p->link;
                //value is present in the graph
                flag = 1;
            }
            //move to the next node in node list
            ptr = ptr->pnext;
        }
    }
    //If flag is 0 value in not present in the graph
    if (flag == 0)
        printf("Node %d does not exist !\n", value);
}

//to print the graph
void print_graph(AdjacencyList *g)
{
    //Check if graph is empty
    if (g->link == NULL)
        printf("Graph Empty !\n");
    else
    {
        //ptr points to first node in the node list
        AdjacencyList *ptr = g->link, *p;
        //Traverse the node list
        while (ptr)
        {
            //print node p
            p = ptr;
            printf("%d ->", ptr->data);
            //traverse the edge list of p and print all the nodes
            while (p->link)
            {
                printf(" %d", p->link->data);
                p = p->link;
            }
            printf("\n");
            ptr = ptr->pnext;
        }
    }
}

int main()
{
    AdjacencyList *g = (AdjacencyList *)malloc(sizeof(AdjacencyList) * 10);
    g->link = NULL;
    //menu driven program to insert, delete and print graph according to choice
    while (1)
    {
        int choice;
        scanf("%d", &choice);
        switch (choice)
        {
        case 1:
        {
            int parent, value;
            scanf("%d %d", &parent, &value);
            insert_to_graph(g, parent, value);
        }
        break;

        case 2:
        {
            int value;
            scanf("%d", &value);
            delete_from_graph(g, value);
        }
        break;

        case 3:
        {
            print_graph(g);
        }
        break;

        case 4:
        {
            return 0;
        }
        }
    }

    return 0;
}

/*
    Sample input 
        1
        2 3
        1
        3 4
        1
        1 5
        1
        2 4
        3
        4
    Sample output
        2 -> 3 4
        3 -> 4
        1 -> 5
*/

/*
    TIME COMPLEXITY
        Insertion - O(n)
        Deletion - O(n^2)
        Print graph - O(n^2)
    Total time complexity of the program - O(n^2)
    SPACE COMPLEXITY- O(n)
*/


<|start_filename|>Java/dp/FlightOfStairs.java<|end_filename|>
/*Problem link: https://binarysearch.com/problems/A-Flight-of-Stairs-Sequel

Problem Statement:
You are given positive integers n and k and you are currently at stair 0 and want to climb to stair n. 
You can either climb 1, 2, or 3 stairs at a time, but you can only climb 3 stairs at most k times.
Return the number of ways to climb to the nth stair.
*/

import java.util.Scanner;

public class FlightOfStairs{

    public static int ans(int[][] memo, int n, int k) {

        /*base conditions*/
        if (n == 0)
            return 1;
        else if (n < 0)
            return 0;
        else if (memo[n][k] != 0)
            return memo[n][k];

        /*recursive calls for 1 step and 2 steps respectively*/
        memo[n][k] = ans(memo, n - 1, k) + ans(memo, n - 2, k);

        /*recursive call for 3 steps only if k satisfies*/
        if (k > 0)
            memo[n][k] += ans(memo, n - 3, k - 1);

       /*returning memoized answer*/
        return memo[n][k];

    }
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the value of n");
        int n = sc.nextInt();
        System.out.println("Enter the value of k");
        int k = sc.nextInt();

        /*array to initiate memoization*/
        int[][] memo = new int[n+1][k+1];

        /*passing arguments to the function and displaying answer*/
        System.out.println("The answer is: "+ans(memo, n, k));
        sc.close();
    }
}

/*
Sample Input :
Enter the value of n
4
Enter the value of k
1
Output :
The answer is: 7
*/

/*
Time complexity: O(n*k) 
Space complexity: O(n*k)
 */


<|start_filename|>C/ds/bellman_ford.c<|end_filename|>
#include <stdio.h>
#include <math.h>
//Bellman Ford Function
int Bellman_Ford(int k, int *A, int *B, int n)
{
    int i, j;
    for (i = 0; i < n; i++)
    {
        *(B + (k + 1) * n + i) = *(B + k * n + i);
        for (j = 0; j < n; j++)
        {
            if (*(B + (k + 1) * n + i) > *(B + k * n + j) + *(A + *(B + j) * n + *(B + i)))
                *(B + (k + 1) * n + i) = *(B + k * n + j) + *(A + *(B + j) * n + *(B + i));
        }
    }
    if (k < n)
        Bellman_Ford(k + 1, A, B, n);
}
//Main Function Began
int main()
{
    int n, i, j, k, a;
    printf("Please enter the number of vertices:");
    scanf("%d", &n);
    int A[n][n], B[n + 2][n];
    printf("\nEnter the value of Adjacency Matrix:\n");
    for (i = 0; i < n; i++)
    {
        printf("\n");
        for (j = 0; j < n; j++)
        {
            scanf("%d", &A[i][j]);
        }
    }
    printf("\nEnter the Source vertex number:");
    scanf("%d", &a);

    /*Calculation for the first vertex*/
    B[0][0] = a - 1;
    B[1][0] = 0;
    for (j = 1; j < n; j++)
    {
        if (j > a - 1)
            B[0][j] = j;
        else
            B[0][j] = j - 1;
    }
    for (j = 1; j < n; j++)
        B[1][j] = 99;
    //calling bellman function
    Bellman_Ford(1, A, B, n);
    //check for negative cycle
    for (i = 0; i < n; i++)
    {
        if (B[n + 1][i] != B[n][i])
        {
            printf("\n Negative edge-cycle Present");
            return 0;
        }
    }
    //print the output
    printf("\n\tOUTPUT:\n");
    for (i = 1; i < n; i++)
        printf("\nWeight of vertex no.%d is %d", B[0][i] + 1, B[n + 1][i]);
}
//main ends here

/* Sample Input Output
Please enter the number of vertices: 5
Enter the value of Adjacency Matrix:
0
3
8
99
-4

99
0
99
1
7

99
4
0
99
99

2
99
5
0
99

99
99
99
6
0

Enter the Source vertex number: 1

OUTPUT:
Weight of vertex no.2 is 3
Weight of vertex no.3 is 7
Weight of vertex no.4 is 2
Weight of vertex no.5 is -4

Time Complexity : O(V*E)
where V is noumber of vertices and E is no. of edges in the graph.
*/


<|start_filename|>Java/cp/Paint_Fence.java<|end_filename|>
/*
___Paint Fence Algorithm___
Problem:
Given a fence with n posts and k colors
Find out the number of ways of painting the fence
such that at most 2 adjacent posts have the same color.
Input:
n : number of posts
k : number of colors
Output:
result: number of ways of painting
        considering the condition above
*/

import java.util.*;

public class Paint_Fence{

    //function uses permutation logic to output number of possible ways of painting

    public int paint_fence(int n,int k){
        if(n<2 | k<(n/2)){
            return -1;
        }
        int[] same = new int[n-1];
        int[] diff = new int[n-1];
        int[] total = new int[n-1];
        same[0]=k;
        diff[0]=k*(k-1);
        total[0]=k*k;
        for(int i=1;i<(n-1);++i){
            same[i]=diff[i-1];
            diff[i]=total[i-1]*(k-1);
            total[i]=diff[i]+same[i];
        }
        return total[n-2];
    }
    public static void main(String[] args){
        int n,k;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter n,Number of Posts");
        n=input.nextInt();
        System.out.println("Enter k,Number of Colors");
        k=input.nextInt();
        Paint_Fence obj = new Paint_Fence();
        int result = obj.paint_fence(n,k);
        if(result==-1){
            System.out.println("Painting is not possible following the condition");
        }
        else{
            System.out.println("Number of Possiblities: "+result);
        }
        input.close();
    }
}

/*Sample Input/Output
Enter n,Number of Posts
3
Enter k,Number of Colors
5
Number of Possiblities: 120

Enter n,Number of Posts
10
Enter k,Number of Colors
4
Painting is not possible following the condition

Enter n,Number of Posts
5
Enter k,Number of Colors
3
Number of Possiblities: 180

Time Complexity  O(n)
Space Complexity O(n) 
*/


<|start_filename|>C-Plus-Plus/other/max_possible_subsequence.cpp<|end_filename|>
/*
Given two words and a string.
By using two words , Count How many different subsequence's can be created through the string.
Two subsequence's are considered to be different if they start or end
at different positions in the string.
*/

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

//From this get_count_max_possible_subsequence() function we will count max different subsequence's can be created
int get_count_max_possible_subsequence(string word1, string word2, string text)
{
    int size_of_text = text.size();
    int size_of_word1 = word1.size();
    int size_of_word2 = word2.size();
    int count_max_possible_subsequence = 0;
    int count1 = 0;
    for(int i = 0; i < size_of_text; i++)
    {
        /* here we will check if string s1 is first word or not
        if yes we will increment the count1
         */
        string s1 = text.substr(i , size_of_word1);
        if(s1 == word1)
            count1++;
        string s2 = text.substr(i , size_of_word2);
        if(s2 == word2)
        {
            /* here we will check if string s2 is second word or not
            if yes we will increment the count_max_possible_subsequence
            with current count1 value
            */
            count_max_possible_subsequence += count1;
        }
    }
    return count_max_possible_subsequence;
}

int main()
{
    string text, word1, word2;
	
    cout << "Enter the two words : \n";
    cin >> word1 >> word2;
    cout << "Enter the string : \n";
    cin >> text;
	
    int count_max_possible_subsequence = get_count_max_possible_subsequence(word1, word2, text);
	
    cout << "Maximum possible subsequence can be created is : ";
    cout << count_max_possible_subsequence << endl;
}

/*
Standard Input and Output

Enter the two words :
KICK
START
Enter the string :
KICKXKICKXSTARTXKICKXSTART
Maximum possible subsequence can be created is : 5

Time Complexity : O( N )
Space Complexity : O( N )

*/


<|start_filename|>C-Plus-Plus/graphs/BellmanFord.cpp<|end_filename|>
/*
Bellman Ford algorithm can handle negative weights which dijkstra couldn't.
However it cannot handle negative cycles and have more complexity than Dijkstra.
*/

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

struct Edge { 
  int src, dest, weight; 
}; 

struct Graph { 
  int V, E; 
  struct Edge* edge; 
}; 
  
struct Graph* createGraph(int V, int E) 
{ 
  struct Graph* graph = new Graph; 
  graph->V = V; 
  graph->E = E; 
  graph->edge = new Edge[E]; 
  return graph; 
} 

void showDist(int dist[], int n) 
{ 
  cout<<"Vertex Distance from Source"<<endl; 
  for (int i = 0; i < n; ++i) 
    cout<<i<<"  "<<dist[i]<<endl; 
} 

void bellmanFord(struct Graph* graph, int src){
  int V = graph->V; 
  int E = graph->E; 
  int dist[V];

  for (int i = 0; i < V; i++) 
    dist[i] = INT_MAX; 
  dist[src] = 0;

  for(int i=0;i<V-1;i++){
    for (int j = 0; j < E; j++){
      int u = graph->edge[j].src; 
      int v = graph->edge[j].dest; 
      int w = graph->edge[j].weight; 
      if (dist[u] != INT_MAX && dist[u] + w < dist[v]) 
        dist[v] = dist[u] + w;
    }
  }

  for (int i = 0; i < E; i++) { 
    int u = graph->edge[i].src; 
    int v = graph->edge[i].dest; 
    int weight = graph->edge[i].weight; 
    if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) { 
      cout<<"Graph contains negative weight cycle, hence the shortest distance is not gauranteed"<<endl; 
      return; 
    } 
  } 
  showDist(dist,V);
}

int main(){
  int n,m;
  cin>>n>>m;
  struct Graph* graph = createGraph(n, m);
    
  for(int i=0;i<m;i++){
    int u,v,w;
    cin>>u>>v>>w;
    graph->edge[i].src = u-1; 
    graph->edge[i].dest = v-1; 
    graph->edge[i].weight = w;
  }

  bellmanFord(graph,0);
  return 0;
}

/*
Input:
First line contains two space separated integers,(N,M) 
N- no of vertices, M- no of edges.
Then M lines follow, each line has 3 space separated integers ui ,vi ,wi which denotes edge from vertex ui to vi with weight wi.
Find shortest distance from vertex 1 to all other vertices.

TEST CASE
5 5
1 2 5
1 3 2
3 4 1
1 4 6
3 5 5

OUTPUT
Vertex Distance from Source
0  0
1  5
2  2
3  3
4  7

Time- complexity: O(VE)
If there are 'n' vertices, then there can be n(n-1)/2 edges thus the worst case time complexity is O(n^3).

Space Complexity: O(V)
*/


<|start_filename|>Java/cryptography/vernamCipher.java<|end_filename|>
/*In Vernam cipher, also known as the One-Time Pad, the length
  of the plaintext, ciphertext, and key is the same. Below is
  an implementation of Vernam cipher in Java. Here the ith letter
  of the cipher text is fomred by shifting the numerical value of
  ith letter of the plaintext by the numerical value ofith letter
  of key. The conversion here is a-0, b-1, c-2, ...., z-25.*/

import java.util.*;
import java.lang.*;

public class vernamCipher {

	/* This method takes a string as input and converts
	   each character in the string to its respective
	   numerical value and returns it.*/
	static int[] asciiToDec(String str) {

		int[] decimal = new int[str.length()];

		for(int i = 0; i < str.length(); i++) {

			/* We first convert the character to its
			 decimal and then shift it by 97 as, a-97,
			 b-98, and so on. So to change the indexing
			 and start from 0, we subtract the value by 97.*/
			decimal[i] = str.charAt(i);
			decimal[i] = decimal[i] - 97;
		}

		return decimal;
	}

	/* This method is the encryption method. It takes 
	   plaintext and key as the input.*/
	static String encrypt(String plaintext, String key) {

		String ciphertext = new String("");

		/* Converting both plaintext and key to their
		   respective numerical values.*/
		int[] plaintextArray = asciiToDec(plaintext);
		int[] keyArray = asciiToDec(key);

		int[] ciphertextArray = new int[keyArray.length];

		/* Forming the ciphertext by shifting each value of
		plaintext by the value present at same index of the key*/
		for(int i = 0; i < keyArray.length; i++) {
			ciphertextArray[i] = (plaintextArray[i] + keyArray[i]) % 26;

			//Shifting the values by 97, to get proper ascii values.
			ciphertextArray[i] += 97;
		}

		/* Converting the decimal values to respective ascii
		values and forming the ciphertext string.*/
		for(int i = 0; i < ciphertextArray.length; i++) {
			ciphertext += (char)ciphertextArray[i];
		}

		return ciphertext;
	}

	/* This method formats the ciphertext according to the plaintext.
	From the encrypt function above, we send plaintext in lowercase.
	So, the ciphertext we get is also in all lowercase. Here, we format
	the ciphertext so that wherever there is capital letter in the plaintext,
	same follows in the ciphertext.*/
	static String format(String plaintext, String ciphertext) {

		String finalencrypted = new String("");

		/* Check wherever the plaintext is capital and
		then capitalize that character in the ciphertext*/
		for(int i = 0; i < plaintext.length(); i++) {
			if(Character.isUpperCase(plaintext.charAt(i))) {
				finalencrypted += Character.toUpperCase(ciphertext.charAt(i));
			}
			else {
				finalencrypted += ciphertext.charAt(i);
			}
		}
		return finalencrypted;
	}

	public static void main(String[] args) {

		Scanner scan = new Scanner(System.in);

		// Take plaintext and key as input from the user.
		System.out.print("Enter a plaintext to encrypt: ");
		String plaintext = scan.nextLine();

		System.out.print("Enter a key of same size    : ");
		String key = scan.nextLine();

		/*If the length of key is not equal to the
		length of the plaintext, then terminate.*/
		if(plaintext.length() != key.length()) {
			System.out.println("Invalid input.");
			System.exit(0);
		}
		scan.close();

		// Call the methods and print the encrypted message.
		String encryptedplaintext = encrypt(plaintext.toLowerCase(), key.toLowerCase());
		String encrypted = format(plaintext, encryptedplaintext);

		System.out.println("Encrypted plaintext is      : " + encrypted);
	}
}

/* Sample I/O:
a)	Enter a plaintext to encrypt: ThisIsAMessage
	Enter a key of same size    : MercuryisHottt
	Encrypted plaintext is      : FlzuCjYUwzgtzx

b)	Enter a plaintext to encrypt: MessageTooBIg
	Enter a key of same size    : KeynotMatch
	Invalid input.
*/



<|start_filename|>C/sort/InsertionSort.c<|end_filename|>
/*INSERTION SORT
The array is virtually split into a sorted and an unsorted part. 
Values from the unsorted part are picked and placed at the correct position in the sorted part.
*/
#include <stdio.h>

void insertion_sort(int[], int);
int main()
{
	int arraySize, index, temp, key;
	printf("Enter the size of the array:");
	scanf("%d", &arraySize);
	int arr[arraySize];	// declaring array by - 'arr'
	printf("Enter the elements to sort:");
	for (index = 0; index < arraySize; index++)
	{
		scanf("%d", &arr[index]);
	}

	insertion_sort(arr, arraySize);
	printf("Sorted Array:");
	for (index = 0; index < arraySize; index++)
	{
		printf("%d ", arr[index]);
	}

	return 0;
}

// Function to sort the array using insertion sort method
void insertion_sort(int arr[], int arraySize)
{
	int index, key, temp;
	for (index = 1; index < arraySize; index++)
	{
		key = arr[index];	// the key stores the value at the index position
		temp = index - 1;
		while (temp >= 0 && arr[temp] > key)
		{
			arr[temp + 1] = arr[temp];
			temp--;
		}

		arr[temp + 1] = key;
	}
}

/*
Sample Output
Enter the size of the array:6
Enter the elements to sort:17 8 9 0 2
Sorted Arrray:0 2 8 9 17

Complexities
Time Complexity:O(n^2)
Space Complexity:O(1)
*/



<|start_filename|>C/math/lowest_prime_factor_of_number.c<|end_filename|>
/*
Given a number. find it's lowest prime factor.
we have to get the lowest factor of that number and
that lowest factor has to be a prime number.
*/

#include <stdio.h>

// From this chech_prime function we will whether a number is prime or not
int check_prime(int number)
{
    /* check whether number is prime or not */
    int i = 0;
    for(i = 3; i * i <= number; i += 2)
    {
        if(number % i == 0)
        {
            return 0;
        }
    }
    return 1;
}

// From this function we will get lowest prime factor of a number
int get_lowest_prime_factor(int number)
{
    int get_factor = 0, i = 0;
    /*
    loop runs till sqrt( number )
    for not getting precision errors
    use i * i <= number
    */
    for(i = 3 ; i * i <= number; i += 2)
    {
        if(number % i == 0)
        {
            get_factor = 1;
            int prime = check_prime(i);
            if(prime)
            {
                /* that means the number is lowest prime factor */
                return i;
            }
        }
    }
    if(!get_factor)
    {
        /*
        that means the number itself it's lowest prime factor.
        Ex : 17
        so we can return the number.
        */
        return number;
    }
}

int main()
{
    printf("Enter the number : \n");
    int number;
    scanf("%d", &number);
    /*
    if the number is even, we can say that the lowest prime factor
    is 2 for any even number.
    because 2 is prime and it's a factor of
    every even number.
    */
    if(number % 2 == 0)
    {
        printf("Lowest prime factor for this number is : 2\n");
    }
    else if(number % 2)
    {
        int lowest_prime_factor = get_lowest_prime_factor(number);
        printf("Lowest prime factor for this number is : \n");
        printf("%d\n" , lowest_prime_factor);
    }
}

/*
Standard Input and Output
1. Even number
Enter the number :
435346
Lowest prime factor for this number is : 2
2. Odd Number
Enter the number :
35345
Lowest prime factor for this number is :
5
3. Odd Prime Number :
Enter the number :
23
Lowest prime factor for this number is :
23
Time Complexity : O(sqrt (N) )
Space Complexity : O( 1 )

*/


<|start_filename|>C-Plus-Plus/other/sudoku_solver.cpp<|end_filename|>
// SudokuSolver
//Given a partially filled 9ï¿½9 2D array ï¿½grid[9][9]ï¿½, the goal is to assign digits (from 1 to 9) to the empty cells so that every row, column, and subgrid of size 3ï¿½3 contains exactly one instance of the digits from 1 to 9.
#include <bits/stdc++.h>
using namespace std;

bool isSafeToPut(int **mat, int i, int j, int n, int number)
{
    // Check the rows and cols
    for (int k = 0; k < n; k++)
    {
        if (mat[k][j] == number)
        {
            return false;
        }
    }

    for (int k = 0; k < n; k++)
    {
        if (mat[i][k] == number)
        {
            return false;
        }
    }

    n = sqrt(n);
    int starti = (i / n) * n;
    int startj = (j / n) * n;

    for (int k = starti; k < starti + n; k++)
    {
        for (int l = startj; l < startj + n; l++)
        {
            if (mat[k][l] == number)
            {
                return false;
            }
        }
    }
    return true;
}

bool SudokuSolver(int **mat, int i, int j, int n)
{
    if (i == n)
    {
        // Print the sudoku
        cout << endl;
        cout << "Solved Sudoku:" << endl;
        for (int k = 0; k < n; k++)
        {
            for (int l = 0; l < n; l++)
            {
                cout << mat[k][l] << " ";
            }
            cout << endl;
        }
        cout << endl;
        return true;
    }
    if (j == n)
    {
        return SudokuSolver(mat, i + 1, 0, n);
    }
    if (mat[i][j] != 0)
    {
        return SudokuSolver(mat, i, j + 1, n);
    }
    for (int number = 1; number <= n; number++)
    {
        if (isSafeToPut(mat, i, j, n, number))
        {
            mat[i][j] = number;
            bool t = SudokuSolver(mat, i, j + 1, n);
            if (t)
            {
                return true;
            }
            mat[i][j] = 0;
        }
    }
    return false;
}

int main()
{
    int n;
    cout << "Enter size of square matrix: ";
    cin >> n;

    int **mat = new int *[n];

    //pointer initialization
    for (int i = 0; i < n; i++)
    {
        mat[i] = new int[n];
    }
    cout << "Enter elements and type 0 for empty cells: " << endl;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            cin >> mat[i][j];
        }
    }
    SudokuSolver(mat, 0, 0, n);

    return 0;
}

/*
Sample input/output:
Enter size of square matrix: 9
Enter elements and type 0 for empty cells:
3 0 6 5 0 8 4 0 0
5 2 0 0 0 0 0 0 0
0 8 7 0 0 0 0 3 1
0 0 3 0 1 0 0 8 0
9 0 0 8 6 3 0 0 5
0 5 0 0 9 0 6 0 0
1 3 0 0 0 0 2 5 0
0 0 0 0 0 0 0 7 4
0 0 5 2 0 6 3 0 0

Solved Sudoku:
3 1 6 5 7 8 4 9 2 
5 2 9 1 3 4 7 6 8 
4 8 7 6 2 9 5 3 1 
2 6 3 4 1 5 9 8 7
9 7 4 8 6 3 1 2 5
8 5 1 7 9 2 6 4 3
1 3 8 9 4 7 2 5 6
6 9 2 3 5 1 8 7 4
7 4 5 2 8 6 3 1 9

Time complexity: O(9^(n*n))
Space Complexity: O(n*n)
*/


<|start_filename|>Kotlin/search/LinearSearch.kt<|end_filename|>
/*Linear search algorithm is an algorithm which checks if an element is present in the given list by comparing it with every element in the list.
  Linear search is the simplest search algorithm;it is a special case of brute-force search and in worst-case, cost is proportional to the number
  of elements in the list. Hence name is Linear search.This is a linear search algorithm in Kotlin.*/

//we need to import util as we are using the scanner object 
import java.util.*

fun linearsearch(array:IntArray,number:Int){
   
   var i = 0 
   //we iterate through the array
   for( index in array.indices ){ 
      if( array[index] == number){
         //print the number and at what index it is present
         println("we have ${number} at index : ${index}")
         i++
      }
   }  
   //Print this message if the element is not found in the array/List
   if(i==0){
      print("The number given is not there in the given List")
   }  
}     
      
fun main(){
   
   val scan = Scanner(System.`in`)
   print("Enter the number of elements :")
   //Taking input from user
   val array = IntArray(scan.nextInt())
   print("Enter the elements :")
   for(element in array.indices){
     array[element] = scan.nextInt()
   } 
   print("Enter the number you want to search for :")
   val number = scan.nextInt()
   scan.close()
   //calling linearsearch function
   linearsearch(array,number)
}
/*
   We can compile and run this code with the commands as:
   $kotlinc LinearSearch.kt -include-runtime -d LinearSearch.jar
   $java -jar LinearSearch.jar
   
   Sample I/O :
   
   Enter the number of elements :4
   Enter the elements :1 2 2 4
   Enter the number you want to search for :2
   we have 2 at index : 1
   we have 2 at index : 2
*/


<|start_filename|>Java/math/Big_Integer_Factorial.java<|end_filename|>
/*BigInteger class is used for mathematical operation which involves very big integer calculations that are outside the limit of all available primitive data types. For example factorial of 100 contains 158 digits in it so we can't store it in any primitive data type available*/
import java.math.*;
import java.util.*;
class Big_Integer_Factorial {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number to find the factorial of");
        int n = sc.nextInt();
        System.out.println(" The factorial of " + n + " is : " + factorial(n));
    }
    public static BigInteger factorial(int n) {
        BigInteger fact = new BigInteger(Integer.toString(n));
        for (int i = 1; i < n; i++)
            fact = fact.multiply(BigInteger.valueOf(i));
        return fact;

    }

}
/* Sample Input and Output : 
 * Enter the number to find the factorial of
32
 The factorial of 32 is : 263130836933693530167218012160000000
Time Complexity : O(n)
Space Complexity : O(1)
 */

<|start_filename|>C-Plus-Plus/heap/K_Closest_Points_to_Origin.cpp<|end_filename|>
/*
K Closest Points to Origin
=================================

Problem Statement:
Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k,
Print the k closest points to the origin i.e (0, 0).
The distance between two points on the X-Y plane is the Euclidean distance (i.e, √(x1 - x2)^2 + (y1 - y2)^2).

Concept:
For all the pairs in the points array we calculate the eucledian distance between that point and the origin.
We store a pair of the point and the eucledian distance in a Min-Heap.
We use a Min-Heap because we need first K closest point i.e points with minimum distance from the origin.
At the end we print first K points from the Min-Heap.
*/

#include <iostream>
#include <queue>
#include <vector>
#include <math.h>
using namespace std;
// made a user defined pair which would be of the form {distance, coordinate}
using user_defined_pair = pair<long long, vector<int>>; 

// calculate eucledian distance between point and (0, 0)
long long eucledian_distance(vector<int> coordinates) 
{
    int x = coordinates[0];
    int y = coordinates[1];
    return sqrt(x * x + y * y);
}

vector<vector<int>> kClosest(vector<vector<int>> points, int k)
{
    // syntax to create a min_heap
    priority_queue<user_defined_pair, vector<user_defined_pair>, greater<user_defined_pair>> min_heap; 
    vector<vector<int>> result;

    for (auto coordinates : points)
    {
        float distance = eucledian_distance(coordinates);
        user_defined_pair distance_coordinate_pair = {distance, coordinates};
        // push a pair of {distance, coordinate} in min_heap
        min_heap.push(distance_coordinate_pair); 
    }

    while (k != 0)
    {
        user_defined_pair distance_coordinate_pair = min_heap.top();
        // add first k coodinates in result vector
        result.push_back(distance_coordinate_pair.second); 
        min_heap.pop();
        k--;
    }

    return result;
}

int main()
{
    vector<vector<int>> points;
    vector<vector<int>> result;
    int k;
    int rows;
    int x;
    int y;

    cin >> rows;

    for (int i = 0; i < rows; i++)
    {
        vector<int> coordinate;
        cin >> x;
        cin >> y;
        coordinate.push_back(x);
        coordinate.push_back(y);
        points.push_back(coordinate);
    }

    cin >> k;

    result = kClosest(points, k);

    for (auto pair : result)
    {
        for (auto coordinate : pair)
        {
            cout << coordinate << " ";
        }
        cout << endl;
    }
}

/*
Time Complexity: O(NlogK)
Space Complexity: O(N)

Input:
points = [[1,3],[-2,2]]
k = 1

Output:
[[-2, 2]]

Explanation:
Eucledian Distance between [1,3] and origin i.e [0, 0] is sqrt(10).
Eucledian Distance between [-2,2] and origin i.e [0, 0] is sqrt(8).
As sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].

Input 2: 
points = [[3,3],[5,-1],[-2,4]]
k = 2

Output:
[[3,3],[-2,4]]
*/


<|start_filename|>Java/search/TernarySearch.java<|end_filename|>
import java.util.*;
public class Main
{  
   // Recursive Approach
  static int ternarySearchRecursive (int arr[], int f, int left, int right)
  {
    if (left <= right)
      {
	int mid1 = left + (right - left) / 3;
	int mid2 = right - (right - left) / 3;
	if (arr[mid1] == f)
	  return mid1 + 1;
	else if (arr[mid2] == f)
	  return mid2 + 1;
	else if (f < arr[mid1])
	    return ternarySearchRecursive (arr, f, left, mid1 - 1);
	else if (f > arr[mid2])
	    return ternarySearchRecursive (arr, f, mid2 + 1, right);
	else

	    return ternarySearchRecursive (arr, f, mid1 + 1, mid2 - 1);
      }
    return -1;
  }
    // Iterative Approach
 static int ternarySearch(int arr[], int f, int left, int right)
    {  int found = -1;
        while(left <= right)
        {
          int mid1 = left + (right - left) / 3;
	int mid2 = right - (right - left) / 3;
            if(arr[mid1] == f)
                return mid1 + 1;
            else if(arr[mid2] == f)
                return mid2 + 1;
            else if(f < arr[mid1])
             right = mid1 - 1;
            else if(f > arr[mid2])
               left = mid2 + 1;
            else 
              {
                  left = mid2 + 1;
                  right = mid2 - 1;
              }
            
        } 
        return found;
       
    }
    

  public static void main (String[]args)
  {
    Scanner sc = new Scanner (System.in);
    int i, n, left, right, f = -1, element;
    System.out.println ("Enter length of array");
    n = sc.nextInt ();
    System.out.println ("Enter  array elements");
    int arr[] = new int[n];
    for (i = 0; i < n; i++)
      arr[i] = sc.nextInt ();
    System.out.println ("Enter element to be searched");
    element = sc.nextInt ();

    Arrays.sort (arr);
    left = 0;
    right = n - 1;

    f = ternarySearch(arr, element, left, right);
    if (f != -1)
      System.out.println ("Element found at " + (f));
    else
      System.out.println ("Element not found");
  }
}

/*
Time Complexity -  O(log3(N))

Sample I/O :

Input :  
Enter length of array
4
Enter  array elements
1 2 3 4
Enter element to be searched
4

Output :
Element found at 4 
*/


<|start_filename|>C-Plus-Plus/math/double_factorial.cpp<|end_filename|>
//double factorial  of a number n (denoted by n!!) is the product of all the integers from 1 up to n that have the same parity(odd or even) as n.

//algorithm to find the double factorial of a number n in O(n) time complexity and O(1) space complexity

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

int Recursive(int num)   //recursive approach
{
    if (num == 0 || num == 1) 
        {
            return 1;
        }
    return num * Recursive(num - 2);
}

int Iterative(int num)   // Iterative approach
{
    int ans = 1;
    for (int i = num; i >= 0; i = i - 2) 
    {
        if (i == 0 || i == 1) 
        {
            return ans;
        } 
        else 
        {
            ans *= i;
        }
    }
    return ans;
}

int main() {
    //taking input from the user
    int num;
    cout << "Please Enter a number\n";
    cin >> num;
    cout << "Which way would you like to use?\n";
    cout << "1. Iterative\n";
    cout << "2. Recursive\n";
    int way;
    cin >> way;
    if (way == 1)
    {
        cout << Iterative(num) << endl;
    }
    else if (way == 2)
    {
        cout << Recursive(num) << endl;
    }
    else
    {
        cout << "Invalid choice" << endl;
    }    
    
    
    return 0;
}

/*
  Sample input/output
  Enter the number:
  13
  Which way would you like to use?
  1 Iterative
  2 Recursive
  
  Output  = 135135
 */


<|start_filename|>JavaScript/sort/BubbleSort.js<|end_filename|>
/**
 * time complexity O(n*n) - space complexity O(1)
 */

function BubbleSort(arr) {
  for (let i = 0; i < arr.length; i++) {
    // outer loop
    let isSwapped = false; //  create a boolean to keep track of whether or not there was a successful comparison made
    for (let j = 0; j < arr.length - 1; j++) {
      // inner loop
      if (arr[j] > arr[j + 1]) {
        // check if the current value is greater than next value
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; // Swap the current value and next value
        isSwapped = true; // Set swap variable to true
      }
    }
    if (!isSwapped) {
      // if there's no swap, the arr is fully sorted and can exit there, we break.
      break;
    }
  }

  return arr; // return the sorted array
}

console.log(BubbleSort([4, 2, 1, 3]));
// output should be => [1, 2, 3, 4]

console.log(BubbleSort([-4, 18, 2, 0, 6]));
// output should be => [-4, 0, 2, 6, 18]


<|start_filename|>Go/math/Fibonacci/fibonacci.go<|end_filename|>
/*
   This is a simple program written in go language.
   This program takes in a number as an input an 
   returns the Fnth term in the fibonacci sequence.

   Here the base case is Fo =1 and F1 =1
   Formula goes as : Fn = Fn-1 + Fn-2

*/

package main

import (

  "fmt"

)

/* This function takes the given number and 
   returns the fibonacci number*/
func fibonacci(n int) int{

   // base case as Fo =1 and F1 =1
   if(n == 0 || n == 1){

        return n

    }else {

        // Fn = Fn-1 + Fn-2
        return fibonacci(n-1) + fibonacci(n-2)

    }

}

//driver function
func main() {

   var number int
   fmt.Print("Enter the number :")
   //taking the input from here
   fmt.Scan(&number)

   var res int
   res = 0

   /* calling the fibonacci functuion to return 
      the value and printing it out*/
   res = fibonacci(number)
   fmt.Print("The number is : ",res)

}

/*
   Sample I/O :

   a) Base Case :   

   Enter the number :0
   The number is : 0 

   Enter the number :1
   The number is : 1   

   b) At random number n : 

   Output-1:

   Enter the number :20
   The number is : 6765      

   Output-2:

   Enter the number :40
   The number is : 102334155   

*/



<|start_filename|>C-Plus-Plus/other/addTwoLinkedLists.cpp<|end_filename|>
/* 
Add two numbers in a Linked list

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order,
and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.

*/

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

//Definition for singly-linked list.
class node {
    public:
        int value;
        node* next;
        node(int input) {
            value = input;
            next = NULL;
        }
};
//function to add the element in linked list
void Insertion(node *&head, int input)
{
    node *new_link = new node(input);
    if (head == NULL)
    {
        head = new_link;
        return;
    }
    node *temp = head;
    while (temp->next != NULL)
    {
        temp = temp->next;
    }
    temp->next = new_link;
}
// function to add calculate the sum of two non-empty linked lists which will return the answer as reversed.
node* AddTwoNumbers(node* list1,node* list2){
    // initialize a list to store the result.
    node* answer_list = NULL;
    // Two temporary pointers of 'type' node pointing to list 1 and 2 respectively.
    node *pointer1 = list1;        
    node *pointer2 = list2;
    // to store the carry obtain if the sum exceeds 9.
    int carry = 0; 
    while (pointer1 != NULL || pointer2 != NULL)
    {
        // a temporary variable 'x' to store the value at the current node of list1
        int x = (pointer1 != NULL) ? pointer1->value : 0; 
        // a temporary variable 'y' to store the value at the current node of list2
        int y = (pointer2 != NULL) ? pointer2->value : 0; 
        // calculating sum of the respective nodes
        int sum = carry + x + y;
        // calculating the carry
        carry = sum / 10;
        // storing the sum obtained in the answerList;
        Insertion(answer_list,(sum % 10)); 
        if (pointer1 != NULL)
            pointer1 = pointer1->next;
        if (pointer2 != NULL)
            pointer2 = pointer2->next;
    }
    if (carry > 0)
        Insertion(answer_list,carry); 
    return answer_list;
}
node* ReverseTheList(node* &head){
    node* prev_ptr = NULL;
    node* current_ptr = head;
    node* next_ptr;
    while(current_ptr != NULL)
    {
        next_ptr = current_ptr -> next;
        current_ptr -> next = prev_ptr;
        prev_ptr = current_ptr;
        current_ptr = next_ptr;
    }
    return prev_ptr;
}
// main function
int main()
{
    int testCases;
    cout << "Enter the number of testcases: ";
    cin >> testCases;

    while (testCases--)
    {
        // intialization of the input list1
        node* input1 = NULL;
        // intialization of the input list1
        node* input2 = NULL; 
        int number1;
        cout << "Enter the size of the linked list 1: "<<endl;
        cin >> number1;
        int number2;
        cout << "Enter the size of the linked list 2: "<<endl; 
        cin>>number2;
        cout<<"Enter the elements of linked list 1: "<<endl;
        while(number1--)
        {
            int temp;
            cin>>temp;
            Insertion(input1, temp);
        }
        cout << "Enter the elements of linked list 2: " << endl;
        while(number2--){
            int temp;
            cin>>temp;
            Insertion(input2,temp);
        }
        node* ans = AddTwoNumbers(input1, input2);
        ans = ReverseTheList(ans);
        cout<<"The resulting sum of the two lists is: "<<endl;
        while(ans != NULL)
        {
            cout<<ans->value<<"";
            ans = ans->next;
        }
        cout<<endl;
    }

    return 0;
}

/*

FOR EXAMPLE:--

Example 1:
Input:-
Enter the number of testcases: 3
Enter the size of the linked list 1: 
7
Enter the size of the linked list 2: 
4
Enter the elements of linked list 1: 
9 9 9 9 9 9 9
Enter the elements of linked list 2: 
9 9 9 9
The resulting sum of the two lists is: 
10009998
Enter the size of the linked list 1: 
3
Enter the size of the linked list 2: 
3
Enter the elements of linked list 1: 
2 4 3
Enter the elements of linked list 2: 
5 6 4
The resulting sum of the two lists is: 
807
Enter the size of the linked list 1: 
1
Enter the size of the linked list 2: 
1
Enter the elements of linked list 1: 
0
Enter the elements of linked list 2: 
0
The resulting sum of the two lists is: 
0


SPACE COMPLEXITY = O(max(m,n))(where m and n are the sizes of the list1 and list2 respectively)
TIME COMPLEXITY = O(max(m,n))

*/



<|start_filename|>JavaScript/Algorithms/RussianPeasant.js<|end_filename|>
/*
In this algorithm we keep halving one number and doubling the 2nd one.
While halving, if we get an odd number, we add the 2nd doubled number to the result.
This goes on until the halving makes the first reach 0
It is also known as the Ancient Egyptian Multiplication, used by scribes to do multiplication
without using the multiplication table.
 */

const findProduct = (num1, num2) => {
  if (typeof num1 != "number" || typeof num2 != "number") {
    return "N/A";
  }

  let result = 0;

  // running the loop as long as 2nd number is greater than 0
  while (num2 > 0) {
    // if 2nd becomes odd, we add whatever value of num1
    // we have to result
    if ((num2 & 1) !== 0) {
      result += num1;
    }

    // double first and halve the second
    num1 = num1 << 1;
    num2 = num2 >> 1;
  }

  return result;
};

var product1 = findProduct(1328, 596);
var product2 = findProduct("hello", 96);
console.log("Product 1:" + product1);
console.log("Product 2:" + product2);

/*
Output for above sample input:
Product 1:791488
Product 2:N/A
Time complexity = O(1)
*/


<|start_filename|>C-Plus-Plus/other/Find_kth_Element_of_two_sorted_array.cpp<|end_filename|>
/* Find kth Element of two sorted array.

  Given two sorted arrays of size m and n respectively,
  your task is to finding the element that would be
  at the k’th position of the final sorted array.

  Examples 1 : 

  Input 1 : Array 1 - 2 3 6 7 9
            Array 2 - 1 4 8 10
            k = 5

  Output 1 : 6

  Explanation: The final sorted array would be -
               1, 2, 3, 4, 6, 7, 8, 9, 10
               The 5th element of this array is 6.


  Examples 2 : 
    
  Input 2 : Array 1 - 100 112 256 349 770
            Array 2 - 72 86 113 119 265 445 892
            k = 7

  Output 2 : 256

  Explanation: Final sorted array is -
               72, 86, 100, 112, 113, 119, 256, 265, 349, 445, 770, 892
               The 7th element of this array is 256.

  Algorithm :-

  1) All two arrays are push into the vector.
  2) Then, sort the vector
  3) After Print the vector of (k - 1) index Element.

*/

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


// Function to find kth element of two sorted array
int solve()
{
    // Input m = size of arr1.
    // Input n = size of arr2.
    int m,n;
    cin>>m>>n;

    int arr1[m],arr2[n];

    // Input Elements in array 1
    for (int i = 0; i < m; ++i)
    {
        cin>>arr1[i];
    }

    // Input Elements in array 2
    for (int i = 0; i < n; ++i)
    {
        cin>>arr2[i];
    }

    int k;
    cin>>k;

    // Create a Vector and push arr1 and
    // arr2 elements in a vector

    vector<int> v;
    for (int i = 0; i < m; ++i)
    {
        v.push_back(arr1[i]);
    }

    for (int i = 0; i < n; ++i)
    {
        v.push_back(arr2[i]);
    }

    // Sort the Vector
    sort(v.begin(),v.end());

    // return v[k - 1] value
    return v[k - 1];

}

int main()
{
    // Input the test cases.
    int t;
    cin>>t;
    while(t--)
    {
        int k = solve();
        cout<<"kth Element is : "<<k<<endl;
    }
    return 0;
}

/*
Test cases :

    Input :

        2
        5 4
        2 3 6 7 9
        1 4 8 10
        5
        5 7
        100 112 256 349 770
        72 86 113 119 265 445 892
        7

    Output :

        kth Element is : 6
        kth Element is : 256


    Time complexity: O(nlogn)
    Space Complexity: O(n)
*/


<|start_filename|>Java/cryptography/ModifiedCaesarCipher.java<|end_filename|>
import java.util.Scanner;

/**
 * <h1>Modified Caesar Cipher</h1>
 * <p>
 * To Implement Modified Version of Caesar Cipher
 * </p>
 * <b>Description</b>
 * <p>
 * class ModifiedCaesarCipher is used to encrypt plainText to cipherText using Modified Caesar Algorithm and decrypt
 * cipherText to plainText using the respective algorithm, in Modified Caesar Cipher the encryption takes place by
 * increasing or decreasing the key-value to the character based on its index number from A-Z series, instead of just
 * increasing the key to the character which was done in Caesar Cipher, which provides more enhancement in security and
 * decreases the chances of attack.
 * </p>
 * <b>Requirements</b>
 * <p>
 * A string plain text and an integer key are required for encryption and for decryption the cipher text which is
 * calculated from the given key and the key itself.
 * </p>
 * 
 * <b>Reference for understanding the algorithm</b>
 * <a href="https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.402.8295&rep=rep1&type=pdf"> Modified CaesarCipher
 * for Better Security Enhancement </a>
 * 
 */
public class ModifiedCaesarCipher
{
    /**
     * <p>
     * This is a public method used to encrypt plainText using integer key using Modified Caesar Cipher algorithm.
     * </p>
     * <b>Process</b>
     * <ul>
     * <li>a string plain text and integer key are taken as input</li>
     * <li>iteratively each character of plain text is encrypted
     * <ul>
     * <li>The character index of the current character is calculated, if the character is whitespace then it is not
     * calculated</li>
     * <li>If the character index is even then the character value is incremented by the key-value, else decremented</li>
     * <li>If the sum of the character value and key-value extends or descends within the letter group range (A-Z,a-z,0-9),
     * then the values are circulated and encrypted unless and until their encrypted value comes it the range.</li>
     * <li>The encrypted value is returned</li>
     * </ul>
     * </li>
     * </ul>
     * 
     * @param plainText This is a String parameter to encrypt method, this signifies plain text which is passed.
     * @param key       This is an Integer parameter to encrypt method, this signifies key which is passed to encrypt
     *                  plainText.
     * 
     * @return String This returns the cipherText.
     */
    public String encrypt(String plainText, Integer key)
    {
        /*
         * StringBuilder is used because, it makes a mutable sequence of characters, due to appending of each encrypted
         * character in cipherText, if we use String then it could cause creation of many immutable objects, so to make the code
         * more efficient, StringBuilder is used.
         */
        StringBuilder cipherText = new StringBuilder("");
        
        // Iterating through each character in plainText
        for (int i = 0; i < plainText.length(); i++)
        {
            // Checking for the character index and storing its value in variable 'characterIndex'
            Integer characterIndex = 0;
            // Withing range a-z
            if (plainText.charAt(i) >= 'a' && plainText.charAt(i) <= 'z')
            {
                characterIndex = plainText.charAt(i) - 'a';
            }
            // Withing range A-Z
            else if (plainText.charAt(i) >= 'A' && plainText.charAt(i) <= 'Z')
            {
                characterIndex = plainText.charAt(i) - 'A';
            }
            // Withing range 0-9
            else if (plainText.charAt(i) >= '0' && plainText.charAt(i) <= '9')
            {
                characterIndex = plainText.charAt(i) - '0' + 1;
            }
            // Special Characters
            else
            {
                cipherText.append(plainText.charAt(i));
                continue;
            }
            
            /*
             * If there's an occurrence of whitespace observed in the plainText then it is passed as it is to the cipherText without
             * encrypting it.
             */
            if (plainText.charAt(i) == ' ')
            {
                cipherText.append(' ');
                continue;
            }
            
            int encryptedChar = plainText.charAt(i);
            
            // If the value characterIndex is even then the value of the character is incremented
            if (characterIndex % 2 == 0)
            {
                encryptedChar += key;
            }
            // If the value characterIndex is odd then the value of the character is decremented
            else
            {
                encryptedChar -= key;
            }
            
            /*
             * Flag used to know that if the encrypted character is withing its group range or not
             * 
             * exit = false signifies that the character is within the range
             * 
             * exit = true signifies that the character was not within its range and needs one more iteration for circulation
             */
            boolean exit = false;
            do
            {
                if (plainText.charAt(i) >= 'a' && plainText.charAt(i) <= 'z')
                {
                    exit = false;
                    if (encryptedChar < 'a' || encryptedChar > 'z')
                    {
                        if (encryptedChar < 'a')
                        {
                            encryptedChar += ('z' - 'a' + 1);
                        }
                        else if (encryptedChar > 'z')
                        {
                            encryptedChar -= ('z' - 'a' + 1);
                        }
                        exit = true;
                    }
                }
                else if (plainText.charAt(i) >= 'A' && plainText.charAt(i) <= 'Z')
                {
                    exit = false;
                    if (encryptedChar < 'A' || encryptedChar > 'Z')
                    {
                        if (encryptedChar < 'A')
                        {
                            encryptedChar += ('Z' - 'A' + 1);
                        }
                        else if (encryptedChar > 'Z')
                        {
                            encryptedChar -= ('Z' - 'A' + 1);
                        }
                        exit = true;
                    }
                }
                else if (plainText.charAt(i) >= '0' && plainText.charAt(i) <= '9')
                {
                    exit = false;
                    
                    if (encryptedChar < '0' || encryptedChar > '9')
                    {
                        if (encryptedChar < '0')
                        {
                            encryptedChar += ('9' - '0' + 1);
                        }
                        else if (encryptedChar > '9')
                        {
                            encryptedChar -= ('9' - '0' + 1);
                        }
                        exit = true;
                    }
                }
            }
            while (exit);
            
            /*
             * At the end of for loop(which was used to iterate through each character in plainText), the encrypted character
             * 'encryptedChar' is appended to cipherText
             */
            cipherText.append((char) encryptedChar);
        }
        
        // cipher text is retured
        return cipherText.toString();
    }
    
    /**
     * <p>
     * This is a public method used to decrypt cipherText using integer key using Modified Caesar Cipher algorithm.
     * </p>
     * <b>Process</b>
     * <ul>
     * <li>a string cipher text and integer key are taken as input</li>
     * <li>iteratively each character of cipher text is decrypted
     * <ul>
     * <li>The character index of the current character is calculated, if the character is whitespace then it is not
     * calculated</li>
     * <li>If the key is even then
     * <ul>
     * <li>If the character index is even then the character value is decremented by the key-value</li>
     * <li>If the character index is odd then the character value is incremented by the key-value</li>
     * </ul>
     * </li>
     * <li>If the key is odd then
     * <ul>
     * <li>If the character index is even then the character value is incremented by the key-value</li>
     * <li>If the character index is odd then the character value is decremented by the key-value</li>
     * </ul>
     * </li>
     * <li>If the sum of the character value and key-value extends or descends within the letter group range (A-Z,a-z,0-9),
     * then the values are circulated and decrepted unless and until their decrypted value comes it the range.</li>
     * <li>The decrypted value is returned</li>
     * </ul>
     * </li>
     * </ul>
     * 
     * @param cipherText This is a String parameter to decrypt method, this signifies cipher text which is passed.
     * @param key        This is an Integer parameter to decrypt method, this signifies key which is passed to decrypt
     *                   cipherText.
     * 
     * @return String This returns the plainText.
     */
    public String decrypt(String cipherText, Integer key)
    {
        /*
         * StringBuilder is used because, it makes a mutable sequence of characters, due to appending of each decrypted
         * character in plainText, if we use String then it could cause creation of many immutable objects, so to make the code
         * more efficient, StringBuilder is used.
         */
        StringBuilder plainText = new StringBuilder("");
        
        // Iterating through each character in cipherText
        for (int i = 0; i < cipherText.length(); i++)
        {
            // Checking for the character index and storing its value in variable 'characterIndex'
            Integer characterIndex = 0;
            
            // Withing range a-z
            if (cipherText.charAt(i) >= 'a' && cipherText.charAt(i) <= 'z')
            {
                characterIndex = cipherText.charAt(i) - 'a';
            }
            // Withing range A-Z
            else if (cipherText.charAt(i) >= 'A' && cipherText.charAt(i) <= 'Z')
            {
                characterIndex = cipherText.charAt(i) - 'A';
            }
            // Withing range 0-9
            else if (cipherText.charAt(i) >= '0' && cipherText.charAt(i) <= '9')
            {
                characterIndex = cipherText.charAt(i) - '0' + 1;
            }
            // Special Characters
            else
            {
                plainText.append(cipherText.charAt(i));
                continue;
            }
            
            /*
             * If there's an occurrence of whitespace observed in the cipherText then it is passed as it is to the plainText without
             * decrypting it.
             */
            if (cipherText.charAt(i) == ' ')
            {
                plainText.append(' ');
                continue;
            }
            
            int decryptedChar = cipherText.charAt(i);
            
            /*
             * AND logic is used to determine increment or decrement in the cipherText
             * 
             * 0 X 1 = 0
             * 
             * 1 X 0 = 0
             * 
             * 1 X 1 = 1
             * 
             * 0 X 0 = 0
             * 
             * Where 0 determines odd number and 1 determines even in this case
             */
            // If the value key is even
            if (key % 2 == 0)
            {
                // If the value characterIndex is even then the value of the character is decremented
                if (characterIndex % 2 == 0)
                {
                    decryptedChar -= key;
                }
                // If the value characterIndex is odd then the value of the character is incremented
                else
                {
                    decryptedChar += key;
                }
            }
            // If the value key is odd
            else
            {
                // If the value characterIndex is even then the value of the character is incremented
                if (characterIndex % 2 == 0)
                {
                    decryptedChar += key;
                }
                // If the value characterIndex is odd then the value of the character is decremented
                else
                {
                    decryptedChar -= key;
                }
            }
            
            /*
             * Flag used to know that if the decrypted character is withing its group range or not
             * 
             * exit = false signifies that the character is within the range
             * 
             * exit = true signifies that the character was not within its range and needs one more iteration for circulation
             */
            boolean exit = false;
            
            do
            {
                if (cipherText.charAt(i) >= 'a' && cipherText.charAt(i) <= 'z')
                {
                    exit = false;
                    if (decryptedChar < 'a' || decryptedChar > 'z')
                    {
                        if (decryptedChar < 'a')
                        {
                            decryptedChar += ('z' - 'a' + 1);
                        }
                        else if (decryptedChar > 'z')
                        {
                            decryptedChar -= ('z' - 'a' + 1);
                        }
                        exit = true;
                    }
                }
                else if (cipherText.charAt(i) >= 'A' && cipherText.charAt(i) <= 'Z')
                {
                    exit = false;
                    if (decryptedChar < 'A' || decryptedChar > 'Z')
                    {
                        if (decryptedChar < 'A')
                        {
                            decryptedChar += ('Z' - 'A' + 1);
                        }
                        else if (decryptedChar > 'Z')
                        {
                            decryptedChar -= ('Z' - 'A' + 1);
                        }
                        exit = true;
                    }
                }
                else if (cipherText.charAt(i) >= '0' && cipherText.charAt(i) <= '9')
                {
                    exit = false;
                    
                    if (decryptedChar < '0' || decryptedChar > '9')
                    {
                        if (decryptedChar < '0')
                        {
                            decryptedChar += ('9' - '0' + 1);
                        }
                        else if (decryptedChar > '9')
                        {
                            decryptedChar -= ('9' - '0' + 1);
                        }
                        exit = true;
                    }
                }
            }
            while (exit);
            
            /*
             * At the end of for loop(which was used to iterate through each character in cipherText), the decrypted character
             * 'decryptedChar' is appended to plainText
             */
            plainText.append((char) decryptedChar);
        }
        
        // plain text is retured
        return plainText.toString();
    }
    
    /**
     * This is the main method which makes use of the following methods:
     * <ul>
     * <li>encrypt</li>
     * <li>decrypt</li>
     * </ul>
     * 
     * And uses the following objects of types:
     * <ul>
     * <li>java.util.Scanner</li>
     * <li>java.lang.Integer</li>
     * <li>ModifiedCaesarCipher</li>
     * </ul>
     * 
     * @param args not used
     */
    public static void main(String[] args)
    {
        Integer              key;                                              // Created an object of Integer class for storing key to be entered by the user
        String               plainText;                                        // Create an object of String class for storing plain text to be entered by the user
        Scanner              scan                 = new Scanner(System.in);    // Created an object of Scanner class for asking for user input.
        ModifiedCaesarCipher modifiedCaeserCipher = new ModifiedCaesarCipher();// Created an object of ModifiedCaesarCipher for accessing it's method for encryption and decryption
        
        // Asking user to enter plain text
        System.out.println("Please Enter Plain Text:");
        plainText = scan.nextLine();
        
        // Asking user to enter integer key
        System.out.println("Please Enter Key:");
        key = scan.nextInt();
        
        // Accessing method 'encrypt' of ModifiedCaesarCipher class to encrypt plainText by key
        String cipherText = modifiedCaeserCipher.encrypt(plainText, key);
        
        // Printing cipher text
        System.out.println("Cipher Text: " + cipherText);
        
        // Accessing method 'decrypt' of ModifiedCaesarCipher class to decrypt cipherText by key
        String decryptedText = modifiedCaeserCipher.decrypt(cipherText, key);
        
        // Printing decrypted text
        System.out.println("Decrypted Text: " + decryptedText);
        
        // Closing the Scanner object scan
        scan.close();
    }
}

/*
 * OUTPUT:
 * 
 * Please Enter Plain Text:
 * 
 * Attack Alice's troops at 5:00 PM today
 * 
 * Please Enter Key:
 * 
 * 3
 * 
 * Cipher Text: Dqqdfn Dilfh'v qorrmv dq 8:77 MP qradb
 * 
 * Decrypted Text: Attack Alice's troops at 5:00 PM today
 */

<|start_filename|>C/math/Euler's_Totient_function.c<|end_filename|>
/*
Euler's totient function, also known as phi-function ϕ(n), counts the
numberof integers between 1 and n inclusive, which are coprime to n.
*/
#include <stdio.h>

void Euler_Totient(int, int[]);
int main()
{
	int n, phi[100];
	printf("Enter an integer: ");
	scanf("%d", &n);
	Euler_Totient(n, phi);
	printf("\nThe euler totient function for all integers from 1 to %d is:\n", n);
	for (int i = 1; i <= n; ++i)
	{
		printf("%d: %d\n", i, phi[i]);
	}

	return 0;
}

// Function whuch counts number of integers between 1 to n which are co-prime to n
void Euler_Totient(int n, int phi[])
{
	int temp = n;
	//This gives euler totient function for N
	// Time Complexity: O(N*root(N))
	int ans = n;
	for (int i = 2; i <= n; ++i)
	{
		if (n % i == 0)
		{
			ans = ans - ans / i;
			while (n % i == 0)
				n /= i;
		}
	}

	if (n > 1)
	{
		ans = ans - ans / n;
	}

	n = temp;
	printf("\nThe euler totient function for %d is: %d", n, ans);

	//This gives euler totient function from 1 to N
	// Time Complexity: O(N loglogN) - same as Sieve of Eratosthenes
	for (int i = 0; i <= n; ++i)
	{
		phi[i] = i;
	}

	for (int i = 2; i <= n; ++i)
	{
		if (phi[i] == i)
		{
			for (int j = i; j <= n; j += i)
			{
				phi[j] = phi[j] - phi[j] / i;
			}
		}
	}
}

/*
Time Complexity: O(N loglogN)

OUTPUT
Enter an integer: 10
The euler totient function for 10 is: 4
The euler totient function for all integers from 1 to 10 is:
1: 1
2: 1
3: 2
4: 2
5: 4
6: 2
7: 6
8: 4
9: 6
10: 4

-----
(1,3,7,9) are coprime to 10
*/



<|start_filename|>C-Plus-Plus/ds/detectionOfCycle_likedList.cpp<|end_filename|>
/*Below is the code which is used to find whether a cycle is present in a linked list.
It uses 2 pointer slow and fast(which travels at speed twice that of slow).
If they meet at any position while traversing the linked list then a cycle is
present otherwise cycle is not present */
#include <bits/stdc++.h>
using namespace std;

class node{
public:
    int data;
    node* next;
    node(int d){
        data = d;
        next = NULL;
    }
};

void insertAtHead(node* &head,int d){
    if(head==NULL){
        head = new node(d);
        return;
    }
    node* n = new node(d);
    n->next = head;
    head = n;
    return;
}

void insertAtTail(node* &head,int d){
    if(head==NULL){
        insertAtHead(head,d);
        return;
    }
    node* tail = head;
    while(tail->next!=NULL){
        tail=tail->next;
    }
    tail->next = new node(d);
    return;
}

void makeCycle(node* &head,int pos){
    node* temp = head;
    node* startNode;

    int count = 1;
    while(temp->next != NULL){
         if(count == pos){
             startNode = temp;
         }
         temp = temp->next;
         count++;
    }
    temp->next = startNode;
}

bool detectCycle(node* head){
    node* slow = head;
    node* fast = head;
    while(fast!=NULL and fast->next!=NULL){
        fast = fast->next->next;
        slow = slow->next;
        if(fast==slow){
            return true;
        }
    }
    return false;
}

int main()
{
    node* head = NULL;
    int n;
    cout<<"Enter the number of nodes:"<<endl;
    cin>>n;
    for(int i=0;i<n;i++){
       int x;
       cin>>x;
       insertAtTail(head,x);
    }
    int pos;
    cout<<"Enter the position where you want to make a cycle:"<<endl;
    cin>>pos;

    //cycle is created at position pos
    makeCycle(head,pos);

    //detect a cycle
    if(detectCycle(head)){
       cout<<"Cycle is present"<<endl;
    }
    else{
       cout<<"Cycle is not present"<<endl;
    }
    return 0;
}

/*
SAMPLE INPUT
7
1 2 3 4 5 6 7
3
SAMPLE OUTPUT
Enter the number of nodes:
Enter the position where you want to make a cycle:
Cycle is present

Time Complexity  O(N)
Space Complexity O(1)
*/



<|start_filename|>Java/graphs/TopologicalSort.java<|end_filename|>
/**
Topological sort is linear ordering of vertices
in a directed acyclic graph (DAG). This algorithm is useful in 
solving many other applications on DAG
**/

import java.io.*; 
import java.util.*;

public class TopologicalSort {
	private static void dfs_visit(ArrayList<ArrayList<Integer> > graph, int src, Stack<Integer> s, boolean[] visit) {
		visit[src] = true;
		for(int i = 0; i < graph.get(src).size(); i++)
			if(visit[graph.get(src).get(i)] == false)
			    dfs_visit(graph, graph.get(src).get(i), s, visit);
	    s.push(new Integer(src));
	}

	private static void dfs(ArrayList<ArrayList<Integer> > graph, int v, Stack<Integer> s) {
		boolean[] visit = new boolean[v];
		for(int i = 0; i < v; i++)
			if(visit[i] == false)
				dfs_visit(graph, i, s, visit);
	}

	private static void topological_sort(ArrayList<ArrayList<Integer> > graph, int v) {
		Stack<Integer> s = new Stack<Integer>();
		dfs(graph, v, s);
		while(s.empty() == false)
			System.out.print(s.pop() + " ");
		System.out.println();
	}

	public static void main(String[] args) {
		int v, e, a, b;
		// all vertices are labelled from 0 to v-1
		Scanner sc= new Scanner(System.in);
		v = sc.nextInt();
		e = sc.nextInt();
		ArrayList<ArrayList<Integer> > graph = new ArrayList<ArrayList<Integer> >(v);
		for (int i = 0; i < v; i++) 
            graph.add(new ArrayList<Integer>());
		// all directed edges
		for(int i = 0; i < e; i++) {
			a = sc.nextInt();
			b = sc.nextInt();
			// edge a -> b
			graph.get(a).add(b);
		} 
		topological_sort(graph, v);
	}
}

/**
Input :
6 8
0 3
0 4
0 5
1 5
1 0
2 1
3 4
4 5
Output :
2 1 0 3 4 5
Time Complexity : O(v+e)
Space Complexity : O(v)
**/



<|start_filename|>C/ds/Merging_two_Linked_List.c<|end_filename|>
/*

This program is about merging two Linked list. Here the user is going to enter
values of first and second linked list.
It will merge the two linked lists into one linked list by comparing the each
and every node values and convert into one linked list.

*/
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *next;
} *first = NULL, *second = NULL, *third = NULL;

void Create(int Array1[], int size) {
    int i;
    struct Node *temp, *last;
    first = (struct Node *)malloc(sizeof(struct Node));
    first->data = Array1[0];
    first->next = NULL;
    last = first;
    for (i = 1; i < size; i++) {
        temp = (struct Node *)malloc(sizeof(struct Node));
        temp->data = Array1[i];
        temp->next = NULL;
        last->next = temp;
        last = temp;
    }
}

void Create2(int Array2[], int size) {
    int i;
    struct Node *temp, *last;
    second = (struct Node *)malloc(sizeof(struct Node));
    second->data = Array2[0];
    second->next = NULL;
    last = second;
    for (i = 1; i < size; i++) {
        temp = (struct Node *)malloc(sizeof(struct Node));
        temp->data = Array2[i];
        temp->next = NULL;
        last->next = temp;
        last = temp;
    }
}

void Display(struct Node *p) {
    while (p != NULL) {
        printf("%d ", p->data);
        p = p->next;
    }
    printf("\n");
}

void Merge(struct Node *p, struct Node *q) {
    struct Node *last;
    /*Merging the two linkedlists and making it as third linkedlist
    if the condition satisfies*/
    if (p->data < q->data) {
        third = last = p;
        p = p->next;
        third->next = NULL;
    } else {
          third = last = q;
          q = q->next;
          third->next = NULL;
    }
    while (p && q) {
        if (p->data < q->data) {
            last->next = p;
            last = p;
            p = p->next;
            last->next = NULL;
      } else {
            last->next = q;
            last = q;
            q = q->next;
            last->next = NULL;
      }
  }
  /* Checking whether any node is left in the first and second linkedlist
  if so merging those nodes as well. */
  if (p)
      last->next = p;
  if (q)
      last->next = q;
}

int main() {
    int *Array1, *Array2;
    int size;
    printf("Enter the size of the array: \n");
    scanf("%d", &size);
    Array1 = (int *)malloc(size * sizeof(int));
    Array2 = (int *)malloc(size * sizeof(int));
    printf("Enter first LL Elements: \n");
    for (int i = 0; i < size; i++) {
        scanf("%d", &Array1[i]);
    }
    Create(Array1, size);
    printf("Enter second LL Elements: \n");
    for (int i = 0; i < size; i++) {
        scanf("%d", &Array2[i]);
    }
    Create2(Array2, size);
    Merge(first, second);
    Display(third);
    return 0;
}

// Output:-
/*
Enter the size of the array:
5
Enter first LL Elements:
2
4
7
8
9
Enter second LL Elements:
1
2
3
4
5

1 2 2 3 4 4 5 7 8 9

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

*/


<|start_filename|>Java/cryptography/KeyWord.java<|end_filename|>
/*Keyword cipher is a form of monoalphabetic substitution, where a keyword is used as the key. Now
  a encryption is formed of alphabets from [a-z] such that the first part of encrption contains 
  unique letters of the keyword and the rest are the remaining alphabets from [a-z]. That is,
  until the keyword is used up, whereupon the rest of the ciphertext letters are used in alphabetical 
  order, excluding those already used in the key.*/

import java.util.*;

public class KeyWord{
   
   //This function builds the encoder based on the key given as input
   static String encoder(char[] key){
       
        String str = "";
        int[] array = new int[26];

        for(int k=0;k<26;k++){
            array[k] = 0;  
        }
        
        //Iterating the key and building the encoder
        for(int i=0;i<key.length;i++){
          if(key[i] != ' '){
            if(array[key[i]-97] == 0){
                 str += key[i];
                 array[key[i]-97] = 1;                     
            }
          }
        }
         
        //Adding the remaining alphabetics
        for(int i=0;i<26;i++){
          if(array[i] == 0){
             array[i] = 1;
             str += (char)(i+97);
          }
        }
        
        return str;
   }
  
   //We cipher the text in this function
   static void cipher(String plaintext,String keyencoder){

        String output="";
        char space = ' ';
        char[] message = plaintext.toCharArray();        
       
        /*for every letter in the plaintext we replace it with
          the corresponding letter in the encoded string we use*/  
        for(int i=0;i<message.length;i++){
          if(message[i] == space)
             //adding the space if input has one
             output += message[i];
          else 
             output += keyencoder.charAt(message[i]-97);
        } 
        
        //printing the cipher text 
        System.out.println("The cipher text is :"+output); 
   }

   public static void main(String []args){
       
        String plaintext,key;
        
        Scanner scan = new Scanner(System.in);
        //We take plaintext and key here 
        System.out.print("Enter the Plaintext :");
        plaintext = scan.nextLine();
        
        System.out.print("Enter the key :");
        key = scan.nextLine(); 
        scan.close();

        //we call this function to cipher the plaintext
        cipher(plaintext,encoder(key.toCharArray()));
   }

}
/*
   Simple I/O :
   
   Enter the Plaintext :hello world
   Enter the key :asdf
   The cipher text is :gbkkn wnqkf    
*/



<|start_filename|>C-Plus-Plus/dp/dijsktra.cpp<|end_filename|>
#include<bits/stdc++.h>
using namespace std;
//Function to find the minimum vertex
int findMinVertex(int* distance, bool visited[], int n) {
	//Initialize min value
	int minVertex = -1;
	for (int i = 0; i < n; i++) {
		if (!visited[i] && (minVertex == -1 || distance[i] < distance[minVertex])) {
			minVertex = i;
		}
	}
	return minVertex;
}

//Dijkstra function
void dijkstra(int** edges, int n) {
	//hold the shortest distance from src to i
	int* distance = new int[n];
	//check if it is visited or not?
	bool* visited = new bool[n];
	for (int i = 0; i < n; i++) {
		//Initialize all distances as INFINITE and visited[] as false
		distance[i] = INT_MAX;
		visited[i] = false;
	}
	distance[0] = 0;
	//Now pick all corrosponding vertex and explore them
	for (int i = 0; i < n - 1; i++) {
		//finding min vertex i,e minimum then source
		int minVertex = findMinVertex(distance, visited, n);
		visited[minVertex] = true;
		//Now check its Neighbour
		for (int j = 0; j < n; j++ ) {
			if (edges[minVertex][j] != 0 && !visited[j]) {
				int dist = distance[minVertex] + edges[minVertex][j];
				if (dist < distance[j]) {
					distance[j] = dist;
				}
			}
		}
	}
	//print the constructed distance array
	cout << "Vertex\tDistance from Source\n";
	for (int i = 0; i < n - 1; i++) {
		cout << i << "          " << distance[i] << endl;
	}
}

//Main function
int main() {
	//Take input from user
	cout << "Enter value for node and edge -";
	int n, e;
	cin >> n >> e;
	int** edges = new int*[n];
	for (int i = 0; i < n; i++) {
		edges[i] = new int[n];
		for (int j = 0; j < n; j++) {
			edges[i][j] = 0;
		}
	}
	cout << "Enter value for Adjacency Matrix -";
	for (int i = 0; i < e; i++) {
		int f, s, weight;
		cin >> f >> s >> weight;
		edges[f][s] = weight;
		edges[s][f] = weight;
	}
	//Calling  Disjkstra function
	cout << endl;
	dijkstra(edges, n);
}

/*
Sample Input Output

Enter value for node and edge -
5 6
Enter value for Adjacency Matrix -
0 1 4
0 2 8
1 3 5
1 2 2
2 3 5
2 4 9

Vertex	Distance from Source
0          0
1          4
2          6
3          9

Time Complexity -O(N^2)
*/


<|start_filename|>C-Plus-Plus/ds/Double_Ended_Queue.cpp<|end_filename|>
/*  DOUBLE ENDED QUEUE
    Double ended queue or dequeue is a special type of queue
    wherein elements can be inserted or deleted from both ends
    i.e front and rear
*/

#include <bits/stdc++.h>
using namespace std;
//Declare dequeue with an array arr, front and rear as members
typedef struct
{
    int arr[10];
    int front, rear;
} dequeue;
dequeue dq;

//to insert an element to the front of double ended queue
void enqueue_front(int n)
{
    //If dequeue is not full
    if ((dq.rear + 1) % 10 != dq.front)
    {
        //If dequeue is empty insert as first element
        if (dq.front == -1)
        {
            dq.front = 0;
            dq.rear = 0;
        }
        //decrement front in circular manner and insert
        else
            dq.front = (dq.front + 9) % 10;
        dq.arr[dq.front] = n;
    }
}

//to insert an element to the rear of double ended queue
void enqueue_rear(int n)
{
    if ((dq.rear + 1) % 10 != dq.front)
    {
        if (dq.rear == -1)
        {
            dq.front = 0;
            dq.rear = 0;
        }
        //increment rear in circular manner and insert
        else
            dq.rear = (dq.rear + 1) % 10;
        dq.arr[dq.rear] = n;
    }
}

//to delete an element and return it from the front of dequeue
int delete_front()
{
    int item;
    //If dequeue is empty
    if (dq.front == -1)
        return -1;
    else
    {
        item = dq.arr[dq.front];
        //if there is only one element
        if (dq.front == dq.rear)
        {
            dq.front = -1;
            dq.rear = -1;
        }
        else
            dq.front = (dq.front + 1) % 10;
    }
    return item;
}

//to delete an element and return it from the rear of dequeue
int delete_rear()
{
    int item;
    if (dq.rear == -1)
        return -1;
    else
    {
        item = dq.arr[dq.rear];
        if (dq.front == dq.rear)
        {
            dq.front = -1;
            dq.rear = -1;
        }
        else
            dq.rear = (dq.rear + 9)%10;
    }
    return item;
}

//to display the double ended queue from front to rear
void display()
{
    //If dequeue is not empty
    if (dq.front!=-1){
        if (dq.front <= dq.rear)
        {
            for (int i = dq.front; i <= dq.rear; i++)
                printf("%d ", dq.arr[i]);
        }
        else
        {
            for (int i = dq.front; i <= 9; i++)
                printf("%d ", dq.arr[i]);
            for (int i = 0; i <= dq.rear; i++)
                printf("%d ", dq.arr[i]);
        }
        printf("\n");
    }
    else
        printf("Empty Dequeue!");
}

//driver code
int main()
{
    int q, t, n;
    printf("1. Insert at front\n2. Insert at rear\n3. Delete from front\n");
    printf("4. Delete from rear\n5. Display Dequeue\n");
    //input no of queries
    printf("\nEnter the number of queries: ");
    scanf("%d", &q);
    dq.front = -1;
    dq.rear = -1;

    //menu driven program to insert,delete or display dequeue
    while (q--)
    {
        printf("Enter a choice: ");
        scanf("%d", &t);
        switch (t)
        {
        case 1:
            printf("Enter the value to be inserted: ");
            scanf("%d", &n);
            enqueue_front(n);
            break;
        case 2:
            printf("Enter the value to be inserted: ");
            scanf("%d", &n);
            enqueue_rear(n);
            break;
        case 3:
            printf("Enter the value to be deleted: ");
            printf("%d\n", delete_front());
            break;
        case 4:
            printf("Enter the value to be deleted: ");
            printf("%d\n", delete_rear());
            break;
        case 5:
            display();
            break;
        }
    }
    return 0;
}
/*
    Sample Input/Output:
    1. Insert at front
    2. Insert at rear
    3. Delete from front
    4. Delete from rear
    5. Display Dequeue

    Enter the number of queries: 5
    Enter a choice: 1
    Enter the value to be inserted: 3
    Enter a choice: 2
    Enter the value to be inserted: 1
    Enter a choice: 1
    Enter the value to be inserted: 5
    Enter a choice: 1
    Enter the value to be inserted: 4
    Enter a choice: 5
    4 5 3 1
*/
/*
    Time Complexity of insertion and deletion operations: O(1)
    Time Complexity of display function : O(n)
    Time complexity of random access by index : O(1)
    Space complexity: O(1)
*/


<|start_filename|>JavaScript/search/ExponentialSearch.js<|end_filename|>
/*

Exponential search is aka doubling or galloping search works on same concept as of Binary Search i.e for a sorted array.
Algorithm - To find the specific range ( with power of 2 ) & then using binary search technique to find location of search key.

Time Complexity - a) Best Case : O(1) b) Worst Case : O(logi)

*/

// Prompt node package for taking user input
const prompt = require("prompt-sync")({ sigint: true });

function exponentialSearch(key) {
  // return it the key is first element of the array
  if (array[0] === key) {
    return console.log("Found", array[0]);
  }

  // Find range by increasing the power(2) i.e. jumping by 2^i for every iteration
  let i = 1; // as 2^0 = 1
  while (i < array.length && array[i] <= key) i *= 2;

  // Pass the range to binary search
  return binarySearch(i / 2, Math.min(i, array.length), key);
}

// Binary search to find the key in specified range
function binarySearch(start, end, key) {
  if (start <= end) {
    // Find mid of given range
    let mid = Math.floor(start + (end - start) / 2);
    if (array[mid] === key) return console.log("Found", array[mid]);

    // Recursively call binary search by changing start/end points of range
    if (array[mid] > key) {
      return binarySearch(start, mid - 1, key);
    } else {
      return binarySearch(mid + 1, end, key);
    }
  } else {
    return console.log("Not found");
  }
}

/* Workflow of user input */

// Take array length as input
let arrayLength = +prompt("Enter array length - ");

// Check whether the entered value is number or not
if (isNaN(arrayLength)) return console.log("Only numbers are allowed");

// Globally declared array
let array = [];

// Take array items
for (let i = 1; i <= arrayLength; i++) {
  array.push(+prompt(`Enter ${i} element - `));

  // Check whether the entered value is number or not
  if (array.includes(NaN)) return console.log("Only numbers are allowed");
}

console.log("Your array - ", array);

// Sort the given array ( Exponential Search works for sorted array only )
array.sort((a, b) => {
  return a - b;
});

// Ask the key/number to search in provided array
let key = +prompt("Enter number to search - ");
if (isNaN(key)) return console.log("It should be a number");

// Call the algorithm
exponentialSearch(key);

/*

Sample i/o

> node ExponentialSearch

Enter array length - 5
Enter 1 element - 84
Enter 2 element - 56
Enter 3 element - 78
Enter 4 element - 98
Enter 5 element - 63
Your array -  [ 84, 56, 78, 98, 63 ]
Enter number to search - 12
Not Found

Enter number to search 98
Found 98

*/



<|start_filename|>Julia/math/mystery_number.jl<|end_filename|>
""" Julia program to Check if a number is a Mystery Number or Not.

A mystery number is that number which can be expressed as a sum of two 
numbers and those two numbers must be the reverse of each other
"""


function reverse(n)
    rev = 0
    while n > 0
        rev = rev * 10
        rev = rev + (n % 10);
        n = n ÷ 10
    end
    return rev
end


function check_mystery_num(n)
    # Let us iterate from 1 upto n/2, to check if there is any pair, such that thier
    # sum equals the given number and check if the pair are reverse of each other 
    temp = n ÷ 2
    for i in 1:(temp)
        if (reverse(i) == (n - i))
            return true
        end
    end
    return false
end


print("Enter the number: ")
num = readline()
num = parse(Int, num)
res = check_mystery_num(num)
if res
    println("The given number $num is a Mystery Number.")
else
    println("The given number $num is not a Mystery Number.")
end

"""
Time Complexity: O(n*log(n)), where 'n' is the given number
Space Complexity: O(1)

SAMPLE INPUT AND OUTPUT

SAMPLE 1
Enter the number: 43234
The given number 43234 is a Mystery Number.

SAMPLE 2
Enter the number: 1234
The given number 1234 is not a Mystery Number.

"""


<|start_filename|>C/other/recursion_string.c<|end_filename|>
#include <stdio.h>
#include <string.h>
int find_occ(char main_str[100], char sub_str[100], int main_len, int sub_len);
int main()
{
    char word[100], sub[100];
    scanf("%s%s", word, sub);
    int len_word, len_sub, occ; //find length of both strings
    len_word = strlen(word);
    len_sub = strlen(sub);
    if (len_word = 0 || len_sub == 0 || len_word < len_sub) //if either string is empty or length of substring is greater than the main string
        printf("Enter valid strings.");
    else
    {
        occ = find_occ(word, sub, len_word, len_sub);
        printf("Number of occurences of %s in %s: %d", sub, word, occ);
    }
    return 0;
}
int find_occ(char main_str[100], char sub_str[100], int main_len, int sub_len)
{
    int occ = 0, len_m; //loop variables and variable to store occurence
    for (len_m = 0; len_m <= (main_len - sub_len); len_m++)
    {
        int len_s;
        for (len_s = 0; len_s < sub_len; len_s++)
        {
            if (main_str[len_m + len_s] != sub_str[len_s])
                break;
        }
        if (len_s == sub_len)
        {
            occ++;
            len_s = 0;
        }
    }
    return occ;
}

/*
Time Complexity: O(len_word*len_sub)
Space Complexity: O(len_word)

Sample Input:
abcchifjrnccdnrr
cc
Output:
Number of occurences of cc in abcchifjrnccdnrr: 2
*/


<|start_filename|>Java/cp/target_sum_triplets.java<|end_filename|>
import java.util.*;

class target_sum_triplets {
    
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in); // input
        int n = sc.nextInt(); //  array size

        int arr[] = new int[n];

        for (int i = 0; i < n; i++){
            arr[i] = sc.nextInt();// array elements
        }

        int target = sc.nextInt(); // target sum

        Arrays.sort(arr);

        for (int j = 0; j < n - 1; j++) {
            int start = j + 1;
            int end = n - 1;

            while (start < end) {

                if (arr[j] + arr[start] + arr[end] == target) {
                    System.out.println(arr[j] + ", " + arr[start] + " and " + arr[end]); // output 
                    start++;
                    end--;
                } else if (arr[j] + arr[start] + arr[end] < target)
                    start++;

                else
                    end--;
            }
        }
    }
}

/* Sample Input Output ->
Input
9
5 7 9 1 2 4 6 8 3
10

Output
1, 2 and 7
1, 3 and 6
1, 4 and 5
2, 3 and 5 

Complexity Analysis

Time Complexity - O(n^2)
Space Complexity - O(1) */


<|start_filename|>C/math/sum_of_digits.c<|end_filename|>
// C Program to find the Sum of Digits of a given number
#include <stdio.h>

int sum_of_digits(int num)
{
    int S = 0;
    while (num != 0)
    {
        // Extracting the digits from the number
        int rem = num % 10;
        S += rem;
        // Removing the extracted digit
        num = num / 10;
    }
    return S;
}

int main()
{
    int num, sum;
    printf("\nEnter the number: ");
    scanf("%d", &num);

    // If the number is negative, convert it into positive
    if (num < 0)
    {
        num = num * -1;
    }

    // Call the function
    sum = sum_of_digits(num);
    // Print the obtained sum
    printf("The sum of the digits of the given number is: %d", sum);
    return 0;
}

/*

Time Complexity- O(log(num)), where 'num' is the given num
Space Complexity- O(1)

SAMPLE INPUT AND OUTPUT

SAMPLE 1

Enter the number: 1231
The sum of the digits of the given number is: 7
*/


<|start_filename|>Java/sort/ShellSort.java<|end_filename|>
import java.util.Scanner;

/*
*Shell Sort is a very efficient sorting algorithm based on insertion sort technique.
*
*Shell Sort is more effective than insertion sort as
*sometimes in Insertion Sorting, we shift a large block to insert an item at the right place
*as per the sorting order,
*which can be avoided by using the Shell Sort algorithm.
*
*In Shell Sort, the sorting is done at certain intervals/gaps and everytime, this gap is reduced.
*This way, Shell Sort becomes nearly twice as fast as Insertion Sort.
*/

public class ShellSort {
	int shellsort(int arr[], int n) {
		//here n is the size of the array
		//initially gap = n/2
		for (int gap = n / 2; gap > 0; gap = gap / 2) {
			for (int i = gap; i < n; i++) {
				//decreasing the gap
				int k = arr[i];
				int j = i;

				while (j >= gap && arr[j - gap] > k) {
					arr[j] = arr[j - gap];
					j = j - gap;
				}
				arr[j] = k;
			}
		}
		return 0;
	}

	private static Scanner sc = new Scanner(System.in);

	public static void main(String args[]) {
		//we store the number of elements in n
		System.out.println("Kindly enter the number of elements: ");
		int n = sc.nextInt();

		//declaring an array of n elements
		int array[] = new int[n];

		//taking the input from the user
		for (int i = 0; i < n; i++) {
			System.out.print("\n" + i + "'th element : ");
			array[i] = sc.nextInt();
		}

		System.out.println("\nArray before sorting");
		for (int j = 0; j < n; j++)
			System.out.print(array[j] + " ");


		//creating an object of shellsort class so that the methods inside shellsort class can be used
		ShellSort object = new ShellSort();
		object.shellsort(array, n);

		System.out.println("\nArray after sorting");
		for (int k = 0; k < n; k++)
			System.out.print(array[k] + " ");

	}
}

/*
Output:

Kindly enter the number of elements: 5

0'th element : 1
1'th element : 2
2'th element : 5
3'th element : 3
4'th element : 0
Array before sorting
1 2 5 3 0
Array after sorting
0 1 2 3 5
*/



<|start_filename|>C-Plus-Plus/cp/check_T_prime.cpp<|end_filename|>
/**
 * Given a number and you need to check if a number is T-prime or not. 
 * A number is called T-prime if it has exactly three factors.
 * Input:
 * First line of input contains a number of integer data type.
 * Output:
 * A single line telling whether a number is T-prime or not.
 *
*/

#include <bits/stdc++.h>

using namespace std;

int Check_T_Prime(int n)
{
    if (n <= 3)
    {
        return 0;
    }
    else
    {
        long long int square_root = sqrt(n);
        int perfect_square_prime = 0, i;

        //to check if number is perfect square or not.
        if (square_root * square_root == n)
        {
            for (i = 2; i <= sqrt(square_root); i++)
            {
                
                /* If the square root of the 
                user input number (num) is prime then it's T-prime otherwise it's not.
                Because for T-prime number should have 3 factors(one the number itself)
                and other 2 from square root as it prime number.  
                */
                if (square_root % i == 0)
                {
                    perfect_square_prime = 1;
                    break;
                }
            }
            if (perfect_square_prime == 0)
                return 1;
            else
                return 0;
        }
        else
            return 0;
    }
}

int main()
{

    long long int num;
    cout << "Enter the number: " << endl;
    cin >> num;

    int result = Check_T_Prime(num);

    if (result == 1)
        cout << num << " is T-prime. " << endl;
    else
        cout << num << " is not T-prime. " << endl;
}

/*
 * Example:
 * Input:
 * 3
 * Output:
 * 3 is not T-prime.
 * 
 * Input:
 * 49
 * Output:
 * 49 is T-prime;
*/

/*
*Time complexity : O(sqrt(n)) 
*Space complexity : O(1)
*/


<|start_filename|>C-Plus-Plus/dp/wildcard_matching.cpp<|end_filename|>
/**

Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where:

'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).

**/

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

bool isMatch(string s, string p) {

    int rows = p.length()+1, cols = s.length()+1;
    // dp table 
    bool dp[rows][cols];
    dp[0][0] = true;
    
    for(int i = 1; i < cols; i++)
        dp[0][i] = false;
    for(int i = 1; i < rows; i++)
        dp[i][0] = dp[i-1][0] && (p[i-1] == '*');
    
    // populating the dp table
    for(int row = 1; row < rows; row++)
        for(int col = 1; col < cols; col++)
            if(p[row-1] == '*')
                dp[row][col] = dp[row-1][col] || dp[row-1][col-1] || dp[row][col-1];
            else
                dp[row][col] = (dp[row-1][col-1] && ((p[row-1] == s[col-1]) || (p[row-1] == '?')));
    
    return dp[rows-1][cols-1];
}

int main() {
    string str, pattern;
    cin >> str >> pattern;
    cout << (isMatch(str, pattern) ? "Pattern matches the given string\n" : "Pattern does not match the given string\n");
}

/**

Input :
aa *
Output :
Pattern matches the given string

Time Complexity : O(mn)
Space Complexity : O(mn)

where m is length of the string
and n is length of the pattern

**/

<|start_filename|>C-Plus-Plus/search/sublist_Search.cpp<|end_filename|>
/*
SUBLIST SEARCH
    to search if a given sublist is present in a mainList using LinkedList.
*/

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

//A linkedlist Node
typedef struct Node{
	int data;
	struct Node* next;
}Node;


Node* getNode(int data){
	Node* n = new Node;
	n->data = data;
	n->next = NULL;
	return n;
}

//returns true if the given sublist is found in MainList.
bool searchSublist(Node* mainList,Node* subList){
	Node *main = mainList, *sub = subList;
	//if both the lists are empty, return true.
	if(main == NULL && sub == NULL)
		return true;
	//if one list is empty and other is not return false
	else if(main == NULL ||(main != NULL && sub == NULL))
		return false;
	
	while(mainList != NULL){
		main = mainList;
		//searching for the sublist in mainlist.
		while(sub != NULL){
			if(main == NULL)
				return false;
			else if(main->data == sub->data){
				main = main->next;
				sub = sub->next;
			}else
				break;
		}

		//if the sub list is completely found in Main list, succesful search.
		if(sub == NULL)
			return true;
		sub = subList;
		mainList = mainList->next;
	}
	return false;
}

Node* insertToList(Node* head,int data){
	if(head == NULL){
		head = getNode(data);
	}else{
		Node *ptr = head;
		while(ptr->next != NULL){
			ptr = ptr->next;
		}
		ptr->next = getNode(data);
	}
	return head;
}

int main(){
	Node *mainHead = NULL,*subHead = NULL;
	int data,sizeMainlist,sizeSublist;
	//Input MainList in which search is to be done
	cout<<"Enter number of elements in Main List: ";
	cin>>sizeMainlist;
	cout<<"Enter Main List: ";
	for(int i=0;i<sizeMainlist;i++){
		cin>>data;
		mainHead = insertToList(mainHead,data);
	}
	//Input sublist which is to searched for
	cout<<"Enter number of elements in Sub List: ";
	cin>>sizeSublist;
	cout<<"Enter Sub List: ";
	for(int i=0;i<sizeSublist;i++){
		cin>>data;
		subHead = insertToList(subHead,data);
	}

	//Printing the search result
	if(searchSublist(mainHead,subHead))
		cout<<"SEARCH SUCCESSFUL";
	else
		cout<<"SEARCH UNSUCCESSFUL";
	return 0;
}


/*
Time Complexity: O(sizeMainlist * sizeSublist)

CASE 1:
MAIN: 1 2 3 4 5 6 7 8
SUB: 2 3 4
Expected Output: SEARCH SUCCESSFUL

CASE 1:
MAIN: 1 44 3 13 12 6 19 8
SUB: 13 12 12
Expected Output: SEARCH UNSUCCESSFUL

*/



<|start_filename|>Kotlin/sort/InsertionSort/src/InsertionSort.kt<|end_filename|>
fun insertionSort(array: MutableList<Int>) : List<Int> {
    // go from the 2nd item in the list till the last item
    for (i in 1 until array.size){
        // store the value
        val value = array[i]
        // store the index of the value
        var temp = i

        /*
        for every new_value below the index of the value
        if the new_value is greater than the value

        if the value is not greater than the loop will end
        */
        while ((array[temp - 1] > value) and (temp >= 0)) {
            // put new_value one index above the current value
            array[temp] = array[temp - 1]
            // decrease the temporary index
            temp -= 1
        }
        /*
            when the loop has ended we know that the value at index
            less then current temp is lesser than current value so
            replace value at temp and close the loop
        */

        array[temp] = value
    }
    return array
}

fun main() {
    print("Enter the number of items to sort - ")
    val lengthOfList = readLine()!!.toInt()

    val list = MutableList(lengthOfList) { 0 }
    list.withIndex().forEach {
        print("Enter value ${it.index + 1} - ")
        list[it.index] = readLine()!!.toInt()
    }
    println("unsorted list is $list")

    val sorted = insertionSort(list.toMutableList());
    println("sorted list is $sorted")
}


<|start_filename|>C-Plus-Plus/sort/three_way_merge_sort.cpp<|end_filename|>
// C++ program to implement Three Way Merge Sort

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


// Merge the three sections in ascending order
void merge(int arr[], int beg, int midA, int midB, int end, int temp[])  
{  
    int i, j, k, l;
    i = beg;
    j = midA; 
    k = midB; 
    l = beg;  
  
    // Find the smallest element among the three sections 
    while ((i < midA) && (j < midB) && (k < end))  
    {  
        if(arr[i] < arr[j]) 
        { 
            if(arr[i] < arr[k]) 
            { 
                temp[l++] = arr[i++]; 
            } 
            else
            { 
                temp[l++] = arr[k++]; 
            } 
        } 
        else
        { 
            if(arr[j] < arr[k]) 
            { 
                temp[l++] = arr[j++]; 
            } 
            else
            { 
                temp[l++] = arr[k++]; 
            } 
        } 
    }  
  
    /*
    Now any two arrays would have remaining values that are yet to be merged,
    We have to identify those two arrays and merge the elements.  
    */
 
    while ((i < midA) && (j < midB))  
    {  
        if(arr[i] < arr[j]) 
        { 
            temp[l++] = arr[i++]; 
        } 
        else
        { 
            temp[l++] = arr[j++]; 
        } 
    }  
  
   
    while ((j < midB) && (k < end))  
    {  
        if(arr[j] < arr[k]) 
        { 
            temp[l++] = arr[j++]; 
        } 
        else
        { 
            temp[l++] = arr[k++]; 
        }  
    }  
  
    while ((i < midA) && (k < end))  
    {  
        if(arr[i] < arr[k]) 
        { 
            temp[l++] = arr[i++]; 
        } 
        else
        { 
            temp[l++] = arr[k++]; 
        }  
    }  
  
  /*
    Now a single array would have remaining values that are yet to be merged,
    We have identify that array and copy its remaining elements.  
  */
    
    while (i < midA)  
        temp[l++] = arr[i++];  
  
    while (j < midB)  
        temp[l++] = arr[j++];  
        
    while (k < end)  
        temp[l++] = arr[k++];  
}  



void three_way_merge_sort(int arr[], int beg, int end, int temp[])  
{  
    //If the array contains only a single element, then return  
    if (end - beg < 2)  
        return;  
  
    // Split the array into three parts
    int midA = beg + ((end - beg) / 3);  
    int midB = beg + 2 * ((end - beg) / 3) + 1;  
    
    three_way_merge_sort(temp, beg, midA, arr);  
    three_way_merge_sort(temp, midA, midB, arr);  
    three_way_merge_sort(temp, midB, end, arr);  
  
    // Merge the sorted arrays  
    merge(temp, beg, midA, midB, end, arr);  
}

int main()
{
    int n;
    cout<<"\nHow many numbers do you want to sort? ";
    cin>>n;
    int arr[n];

    if (n <= 0)
    {
        cout<<"There are no numbers to sort!!!";
        return 0;
    }
    // Input the numbers to sort
    cout<<"Enter the numbers: ";
    for (int i = 0; i < n; i++)
        cin>>arr[i];
    
    // creating a temporary array 
    int temp[n];  
  
    // Copy the elements of the temporary elements into the new array  
    for (int i = 0; i < n; i++)  
        temp[i] = arr[i];  
  
    //Call the sort function 
    three_way_merge_sort(temp, 0, n, arr);  

    cout<<"The numbers in sorted order is: ";
    // Print the sorted array
    for (int i = 0; i < n; i++)
        cout<<temp[i]<<" ";
    cout<<endl;

    return 0;
}

/*

Time Complexity: O(n*logn)
Space Complexity: O(n)

SAMPLE INPUT AND OUTPUT

SAMPLE 1
How many numbers do you want to sort? 5
Enter the numbers: 1 3 5 2 4
The numbers in sorted order is:  1  2  3  4  5

SAMPLE 2
How many numbers do you want to sort? 0
There are no numbers to sort!!!

*/


<|start_filename|>C-Plus-Plus/graphs/EdmondKarp.cpp<|end_filename|>
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<ll> vl;
#define pb push_back

#define loop(x,n) for(ll x = 0; x < n; ++x)

 
ll capacity[100][100];
vl adj[100];

ll bfs(ll s, ll t, vl& parent) {
    fill(parent.begin(), parent.end(), -1);
    parent[s] = -2;
    queue<pair<int, int>> q;
    ll inf=INT_MAX;
    q.push({s, inf});

    while (!q.empty()) {
        ll cur = q.front().first;
        ll flow = q.front().second;
        q.pop();

        for (ll next : adj[cur]) {
            if (parent[next] == -1 && capacity[cur][next]) {
                parent[next] = cur;
                ll new_flow = min(flow, capacity[cur][next]);
                if (next == t)
                    return new_flow;
                q.push({next, new_flow});
            }
        }
    }

    return 0;
}

ll maxflow(ll s, ll t, ll n) {
    ll flow = 0;
    vl parent(n);
    ll new_flow;

    while (new_flow = bfs(s, t, parent)) {
        flow += new_flow;
        ll cur = t;
        while (cur != s) {
            ll prev = parent[cur];
            capacity[prev][cur] -= new_flow;
            capacity[cur][prev] += new_flow;
            cur = prev;
        }
    }

    return flow;
}



int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
    ll n,e;
      cout<<"enter the number of nodes and edges\n"; 
    cin>>n>>e; 
    
    ll source, sink,u,v,w;
     cout<<"enter the source and sink\n";
    cin>>source>>sink;

   loop(i,e){
      cin>>u>>v>>w;
      capacity[u][v] = w;
      adj[u].pb(v);
      adj[v].pb(u);
   }
     
   cout<<"Max Flow: "<<maxflow(source,sink,n);
	
	return 0;
}

/*
Input:
First line contains two space separated integers,(n,e) 
n- no of vertices, e- no of edges.
Then 2 space separated integers source and sink ie, starting and ending point.
Then e lines follow, each line has 3 space separated integers u ,v, w which denotes edge from vertex u to v with capcity w.


TEST CASE
6 10
0 5
0 1 16
0 2 13
1 2 10
2 1 4
1 3 12
3 2 9
2 4 14
4 3 7
4 5 4
3 5 20

OUTPUT
Max Flow: 23

Time- complexity: O(n*e*e)

Space Complexity: O(n+e)
*/


<|start_filename|>Java/sort/SelectionSort.java<|end_filename|>
import java.util.*;
 class SelectionSort
{
	public static void main(String[] args) {
		int indexI,arrayLength,indexJ,temp=0,minElementIndex=0;
		Scanner sc=new Scanner(System.in);
		System.out.println("Enter size of array");
		arrayLength=sc.nextInt();
		int array[]=new int[arrayLength];
		System.out.println("Enter Elements of array");
		for(indexI=0;indexI<arrayLength;indexI++)
		array[indexI]=sc.nextInt();
		for(indexI=0;indexI<arrayLength;indexI++)
		{   
		    minElementIndex=indexI;
		    for(indexJ=indexI+1;indexJ<=arrayLength-1;indexJ++)
		    {
		        if(array[minElementIndex]>array[indexJ])
		        minElementIndex=indexJ;
		      }
		        
		        temp=array[indexI];
		        array[indexI]=array[minElementIndex];
		        array[minElementIndex]=temp;
		      }
		  
		  for(indexI=0;indexI<arrayLength;indexI++)
		    System.out.println(array[indexI]);
		}
		}


<|start_filename|>C/other/Number_of_duplicates_using_Binary_search.c<|end_filename|>
/* To print the occurrence of the given number in the list/array using Binary Search Technique */

#include <stdio.h>
int Binary_search_algo_for__finding_occurrence(int* , int , int , int);
int Partition(int* , int , int);
int Quick_sort(int* , int , int);

int Binary_search_algo_for__finding_occurrence(int array[], int sizeOf_array, int number, int found)
{
    int start = 0, end = sizeOf_array - 1;

// initializing value
    int value = -1;

    while (start <= end)
    {
        int middle = (start + end) / 2;

        /*** CASE : number equals middle element ***/
        if (number == array[middle]) // if both are equal then we update the 'value'
        {
            value = middle;
            if (found) { // searching in left side
                end = middle - 1;
            }
            else { // searching in right side
                start = middle + 1;
            }
        }

        /*** CASE : number less than middle element ***/
        else if (number < array[middle])
        {
            end = middle - 1;
        }

        /*** CASE : number greater than middle element (last case) ***/
        else
        {
            start = middle + 1;
        }
    }
    return value;
}

int Partition(int array[], int lower_bound, int upper_bound)
{
    int pivot , start , end , t;
    pivot = array[lower_bound];
    start = lower_bound ;
    end = upper_bound ;

    while (start < end)
    {
        while (array[start] <= pivot)
        {
            start++;
        }
        while (array[end] > pivot)
        {
            end--;
        }
        if (start < end)
        {   //swap
            t = array[start];
            array[start] = array[end];
            array[end] = t;
        }
    }
    //if the condition is not followed then we replace the 'end' with 'pivot' element and return end
    //swap
    t =  array[lower_bound];
    array[lower_bound] = array[end];
    array[end] = t ;

    return end ;
}

int Quick_sort(int array[] , int lower_bound , int  upper_bound)
{
    int temp ;

    if (lower_bound < upper_bound)
    {
        temp = Partition(array , lower_bound , upper_bound );// as partition function would return end index which would be used further
        Quick_sort(array , lower_bound , temp - 1);
        Quick_sort(array , temp + 1, upper_bound);
    }
}

int main()
{
//declaring the size of array
    int sizeOf_array;
    printf("The size of array is:\n");
    scanf("%d", &sizeOf_array);

// defining the array
    int array[sizeOf_array];
    printf("Please input the elements in array:\n");

// storing elements in array
    for (int i = 0 ; i < sizeOf_array; i++) {
        scanf("%d", &array[i]);
    }
    printf("\n");

    int number; // we would input the number whose occurrence must be returned.
    printf("The number whose occurrence must be found : ");
    scanf("%d", &number);

// we would sort the array using Quick_sort
    int lower_bound = 0 , upper_bound = sizeOf_array - 1;

    Quick_sort(array , lower_bound , upper_bound);

// now we have sorted the array

// we pass 1 for the first occurrence of the number
    int first_occurrence_of_number = Binary_search_algo_for__finding_occurrence(array, sizeOf_array, number, 1);

// we pass 0 for the first occurrence of the number
    int last_occurrence_of_number = Binary_search_algo_for__finding_occurrence(array, sizeOf_array, number, 0);

// now we would subtract the first & last occurrence to get the total occurrences of the number
    int total_occurrences_of_number = last_occurrence_of_number - first_occurrence_of_number + 1;

    if (first_occurrence_of_number != -1) {
        printf("The number: %d occurs %d times in the given array.", number, total_occurrences_of_number);
    }
    else {
        printf("Error! The number is not present in the array.");
    }

    return 0;
}

/*
Sample Test Case

Input
5
1 4 2 3 4
4

Output
Occurrence of '4' : 2

*/

<|start_filename|>Java/Operating-System/allocate.java<|end_filename|>

/*
- A page replacement algorithm looks at the limited information about accesses to the pages provided by hardware and tries to guess which pages should be replaced.
- The simplest page-replacement algorithm is a FIFO algorithm. The first-in, first-out (FIFO) page replacement algorithm is a low-overhead algorithm that requires little bookkeeping on the part of the operating system.
- In the Least Recently Used (LRU) page replacement policy, the page that is used least recently will be replaced.
- Optimal Page Replacement algorithm is the best page replacement algorithm as it gives the least number of page faults.

*/
import java.util.*;

class node {
    int d;
    node next;
    //constructor of node class
    node() 
    {
        d = 0;
        next = null;
    }
}
class queue {
    node front;
    node rear;
	
    //default constructor
    queue() 
    {
        front = null;
        rear = null;
    }
    //returns 1 if queue is empty
    public int isEmpty() 
    {
        if (front == null) {
            return 1;
        } else return 0;
    }
    //adds an element of type node in queue
    public void enq(node temp) 
    {
	//if queue is empty
        if (front == null) 
        {
            rear = temp;
            front = temp;
        } else {
            rear.next = temp;
            rear = temp;
        }
    }
    //deletes an element of type node from the queue
    public node deq() 
    {
        node x = new node();
        if (isEmpty() == 0) {
            if (front == rear) {
                x = front;
                front = null;
                rear = null;
            } else {
                x = front;
                front = front.next;
            }
        } else {
            System.out.println("Queue is empty.");
        }
        return x;
    }
}

class page {
    int arr[];
    int pf;
    int ph;
    int pno;
    page() {
        arr = new int[5];
        pf = 0;
        ph = 0;
        pno = 0;
    }
}

class pagerep {
    page p[];
    String input;
    queue q;
    int frame;
    int number;
    int arrlru[];
    int arropt[];

    pagerep() {
        input = "";
        q = new queue();
        frame = 0;
        number = 0;
    }

    public void accept() {
        Scanner Sc = new Scanner(System.in);
        System.out.println("ENTER THE REFERENCE STRING");
        input = Sc.nextLine();
        String ref[] = input.split(" ");
        number = ref.length;

        System.out.println("ENTER THE NUMBER OF FRAMES ");
        frame = Sc.nextInt();

        p = new page[number];
        for (int i = 0; i < number; i++) {
            p[i] = new page();
            p[i].pno = Integer.parseInt(ref[i]);
        }
    }

    public void display_ref() {
        System.out.println("REFERENCE STRING IS  " + input);
        System.out.println();
    }

    public void fcfsalgo() {
        int i = 0, j = 0;
        node ptr;
        int pfc = 0, phc = 0;

        for (i = 0; i < frame; i++) {
            node temp = new node();
            temp.d = p[i].pno;
            q.enq(temp);
            for (ptr = q.front, j = 0; j < frame; j++) {
                if (ptr != null) {
                    p[i].arr[j] = ptr.d;
                    ptr = ptr.next;
                } else {
                    p[i].arr[j] = -1;
                }
            }
            pfc++;
            p[i].pf = pfc;
            p[i].ph = phc;
        }

        while (i < number) {
            int flag = 0;
            for (int k = 0; k < frame; k++) {
                p[i].arr[k] = p[i - 1].arr[k];
            }
            for (j = 0; j < frame; j++) {
                if (p[i - 1].arr[j] == p[i].pno) {
                    flag = 1;
                    p[i].pf = pfc;
                    phc++;
                    p[i].ph = phc;
                }
            }
            if (flag == 0) {
                node temp = q.deq();
                for (j = 0; j < frame; j++) {
                    if (p[i].arr[j] == temp.d) {
                        p[i].arr[j] = p[i].pno;
                        pfc++;
                        p[i].pf = pfc;
                        p[i].ph = phc;
                        break;
                    }
                }
                temp.d = p[i].pno;
                temp.next = null;
                q.enq(temp);
            }
            i++;
        }
    }

    public void lru1() {
        int i = 0;
        int j = 0;
        int pfcnt = 0;
        int phcnt = 0;
        arrlru = new int[frame];
        for (i = 0; i < frame; i++) {
            arrlru[i] = i;
            for (j = 0; j <= i; j++) {
                p[i].arr[j] = p[arrlru[j]].pno;
            }
            while (j < frame) {
                p[i].arr[j] = -1;
                j++;
            }
            pfcnt++;
            p[i].pf = pfcnt;
            p[i].ph = phcnt;
        }

        while (i < number) {

            int flag = 0;
            for (int k = 0; k < frame; k++) {
                p[i].arr[k] = p[i - 1].arr[k];
            }
            for (j = 0; j < frame; j++) {
                if (p[i - 1].arr[j] == p[i].pno) {
                    flag = 1;
                    break;
                }
            }
            if (flag == 1) {
                for (j = 0; j < frame; j++) {
                    if (p[arrlru[j]].pno == p[i].pno) {
                        arrlru[j] = i;
                    }
                }
                p[i].pf = pfcnt;
                phcnt++;
                p[i].ph = phcnt;
            } else {
                int min = 999;
                int pos = 0;
                for (j = 0; j < frame; j++) {
                    if (arrlru[j] < min) {
                        min = arrlru[j];
                        pos = j;
                    }
                }
                for (j = 0; j < frame; j++) {
                    if (p[min].pno == p[i].arr[j]) {
                        p[i].arr[j] = p[i].pno;
                        break;
                    }
                }
                arrlru[pos] = i;
                pfcnt++;
                p[i].pf = pfcnt;
                p[i].ph = phcnt;
            }
            i++;
        }
    }

    public void optimal1() {
        int i = 0;
        int j = 0;
        int pfcnt = 0;
        int phcnt = 0;
        int flag = 0;
        node ptr;
        arropt = new int[frame];
        queue oq = new queue();

        for (i = 0; i < frame; i++) {
            int t = p[i].pno;
            for (j = i + 1; j < number; j++) {
                if (p[j].pno == t) {
                    flag = 1;
                    arropt[i] = j;
                    break;
                }
            }
            if (flag == 0) {
                node temp = new node();
                temp.d = t;
                oq.enq(temp);
                arropt[i] = 999;
            }
            ptr = q.front;
            for (j = 0; j <= i; j++) {
                if (arropt[j] != 999) {
                    p[i].arr[j] = p[arropt[j]].pno;
                } else {
                    p[i].arr[j] = ptr.d;
                    ptr = ptr.next;
                }
            }
            while (j < frame) {
                p[i].arr[j] = -1;
                j++;
            }
            pfcnt++;
            p[i].pf = pfcnt;
            p[i].ph = phcnt;
        }

        while (i < number) {

            flag = 0;
            for (int k = 0; k < frame; k++) {
                p[i].arr[k] = p[i - 1].arr[k];
            }
            for (j = 0; j < frame; j++) {
                if (arropt[j] == i) {
                    flag = 1;
                    break;
                }
            }
            if (flag == 1) {
                flag = 0;
                for (int k = i + 1; k < number; k++) {
                    if (p[k].pno == p[i].pno) {
                        flag = 1;
                        arropt[j] = k;
                        break;
                    }
                }
                if (flag == 0) {
                    node temp = new node();
                    temp.d = p[i].pno;
                    oq.enq(temp);
                    arropt[j] = 999;
                }
                p[i].pf = pfcnt;
                phcnt++;
                p[i].ph = phcnt;
            } else {
                int max = 0;
                int pos = 0;
                for (j = 0; j < frame; j++) {
                    if (arropt[j] > max) {
                        max = arropt[j];
                        pos = j;
                    }
                }
                if (max != 999) {
                    for (j = 0; j < frame; j++) {
                        if (p[max].pno == p[i].arr[j]) {
                            p[i].arr[j] = p[i].pno;
                            break;
                        }
                    }
                } else {
                    node temp = oq.deq();
                    for (j = 0; j < frame; j++) {
                        if (temp.d == p[i].arr[j]) {
                            p[i].arr[j] = p[i].pno;
                            break;
                        }
                    }
                }
                flag = 0;
                for (int k = i + 1; k < number; k++) {
                    if (p[k].pno == p[i].pno) {
                        flag = 1;
                        arropt[pos] = k;
                        break;
                    }
                }
                if (flag == 0) {
                    node temp = new node();
                    temp.d = p[i].pno;
                    oq.enq(temp);
                    arropt[pos] = 999;
                }
                pfcnt++;
                p[i].pf = pfcnt;
                p[i].ph = phcnt;
            }
            i++;
        }

    }
	
    //DISPLAY THE MATRIX
    void dis() 
    {
        System.out.println("\t\t ");
        System.out.println();
        System.out.print("RF\t  ");
        for (int i = 0; i < number; i++) {
            System.out.print(p[i].pno + "\t");
        }
        System.out.println();
        System.out.println();
        for (int i = 0; i < frame; i++) {
            System.out.print("Frame" + i + " \t");
            for (int j = 0; j < number; j++) {
                System.out.print(p[j].arr[i] + "\t");
            }
            System.out.println();
        }
        System.out.println();
        System.out.print("PF\t  ");
        for (int j = 0; j < number; j++) {
            System.out.print(p[j].pf + "\t");
        }
        System.out.println();
        System.out.println("\t\t ");
        System.out.println("THE NUMBER PAGE FAULT IS/ARE  " + p[number - 1].pf);
        System.out.println("THE NUMBER PAGE HIT IS/ ARE " + p[number - 1].ph);
        System.out.println(" ");
    }
}


public class allocate {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner Sc = new Scanner(System.in);

        pagerep sh = new pagerep();

        int choice = 0;
        do {
            System.out.println("---------------------------------------------------------------------------------------------------");
            System.out.println("  ");
            System.out.println("PRESS 0 TO EXIT");
            System.out.println("PRESS 1 TO ACCEPT STRING");
            System.out.println("PRESS 2 TO DISPLAY STRING");
            System.out.println("PRESS 3 FOR FCFS");
            System.out.println("PRESS 4 FOR LRU");
            System.out.println("PRESS 5 FOR OPTIMAL");
            System.out.println("PLEASE ENTER YOUR CHOICE ");
            choice = Sc.nextInt();
            System.out.println("--------------------------------------------------------------------------------------------------");
            switch (choice) {
                case 1:
	            //accepting the reference string
                    sh.accept(); 
                    break;

                case 2:
	            //display of reference string
                    sh.display_ref(); 
                    break;

                case 3:
                    //first come first serve algorithm
                    sh.fcfsalgo(); 
                    sh.dis();
                    break;

                case 4:
	            //least recently used algorithm
                    sh.lru1(); 
                    sh.dis();
                    break;

                case 5:
	            //optimal algorithm
                    sh.optimal1();
                    sh.dis();
                    break;

            }
        } while (choice != 0);
    }

}


/*
---------------------------------------------------------------------------------------------------
PRESS 0 TO EXIT
PRESS 1 TO ACCEPT STRING
PRESS 2 TO DISPLAY STRING
PRESS 3 FOR FCFS
PRESS 4 FOR LRU
PRESS 5 FOR OPTIMAL
PLEASE ENTER YOUR CHOICE 
1
--------------------------------------------------------------------------------------------------
ENTER THE REFERENCE STRING
1 2 3 4 5 1 2 5 3 2 1 5
ENTER THE NUMBER OF FRAMES 
3
---------------------------------------------------------------------------------------------------
  
PRESS 0 TO EXIT
PRESS 1 TO ACCEPT STRING
PRESS 2 TO DISPLAY STRING
PRESS 3 FOR FCFS
PRESS 4 FOR LRU
PRESS 5 FOR OPTIMAL
PLEASE ENTER YOUR CHOICE 
2
--------------------------------------------------------------------------------------------------
REFERENCE STRING IS  1 2 3 4 5 1 2 5 3 2 1 5
---------------------------------------------------------------------------------------------------
  
PRESS 0 TO EXIT
PRESS 1 TO ACCEPT STRING
PRESS 2 TO DISPLAY STRING
PRESS 3 FOR FCFS
PRESS 4 FOR LRU
PRESS 5 FOR OPTIMAL
PLEASE ENTER YOUR CHOICE 
3
--------------------------------------------------------------------------------------------------
		 
RF	  1	2	3	4	5	1	2	5	3	2	1	5	
Frame0 	1	1	1	4	4	4	2	2	2	2	2	2	
Frame1 	-1	2	2	2	5	5	5	5	3	3	3	3	
Frame2 	-1	-1	3	3	3	1	1	1	1	1	1	5	
PF	  1	2	3	4	5	6	7	7	8	8	8	9	
		 
THE NUMBER PAGE FAULT IS/ARE  9
THE NUMBER PAGE HIT IS/ ARE 3
 
---------------------------------------------------------------------------------------------------
  
PRESS 0 TO EXIT
PRESS 1 TO ACCEPT STRING
PRESS 2 TO DISPLAY STRING
PRESS 3 FOR FCFS
PRESS 4 FOR LRU
PRESS 5 FOR OPTIMAL
PLEASE ENTER YOUR CHOICE 
4
--------------------------------------------------------------------------------------------------
		 
RF	  1	2	3	4	5	1	2	5	3	2	1	5	
Frame0 	1	1	1	4	4	4	2	2	2	2	2	2	
Frame1 	-1	2	2	2	5	5	5	5	5	5	1	1	
Frame2 	-1	-1	3	3	3	1	1	1	3	3	3	5	
PF	  1	2	3	4	5	6	7	7	8	8	9	10	
		 
THE NUMBER PAGE FAULT IS/ARE  10
THE NUMBER PAGE HIT IS/ ARE 2
 
---------------------------------------------------------------------------------------------------
  
PRESS 0 TO EXIT
PRESS 1 TO ACCEPT STRING
PRESS 2 TO DISPLAY STRING
PRESS 3 FOR FCFS
PRESS 4 FOR LRU
PRESS 5 FOR OPTIMAL
PLEASE ENTER YOUR CHOICE 
5
--------------------------------------------------------------------------------------------------
		 
RF	  1	2	3	4	5	1	2	5	3	2	1	5	
Frame0 	1	1	1	1	1	1	1	1	1	1	1	1	
Frame1 	-1	2	2	2	2	2	2	2	2	2	2	2	
Frame2 	-1	-1	3	4	5	5	5	5	3	3	3	5	
PF	  1	2	3	4	5	5	5	5	6	6	6	7	
		 
THE NUMBER PAGE FAULT IS/ARE  7
THE NUMBER PAGE HIT IS/ ARE 5
 
---------------------------------------------------------------------------------------------------
  
PRESS 0 TO EXIT
PRESS 1 TO ACCEPT STRING
PRESS 2 TO DISPLAY STRING
PRESS 3 FOR FCFS
PRESS 4 FOR LRU
PRESS 5 FOR OPTIMAL
PLEASE ENTER YOUR CHOICE 
*/


<|start_filename|>C-Plus-Plus/other/Calculate_max_sum_of_k_consecutive_elements.cpp<|end_filename|>
/*
Given an array of N elements and a value K (K <= N) , calculate maximum summation of K consecutive elements in the array.
We can solve this problem by using Sliding Window Technique. This technique will allow us to solve this problem in O(N)
*/

#include <bits/stdc++.h>
using namespace std;
int ar[100009];

int max_sum_by_sliding_window(int ar[] , int N , int K)
{
    int sum = 0;
    if(N == K)
    {
        // max_sum will be the sum of all elements of array.
        for(int i = 0; i < N; i++)
            sum += ar[i];
        return sum;
    }
    if(N > K)
    {
        // calculate sum of first window of size K
        int max_sum = 0, win_sum = 0;
        for(int i = 0; i < K; i++)
            max_sum += ar[i];

        /*calculate sum of remaining windows
         by removing elements from first window simultaneously add elements to current window */
        win_sum = max_sum;
        for(int i = K; i < N; i++)
        {
            win_sum += (ar[i] - ar[i - K]);
            if(win_sum > max_sum)
            {
                max_sum = win_sum;
            }
        }
        return max_sum;
      }
}

int main()
{
	int N, K;
	cout << "Input array size and value\n";
	cin >> N >> K;
	for(int i = 0; i < N; i++)
    {
        cin >> ar[i];
    }
    int solve = max_sum_by_sliding_window(ar, N , K);
    cout << "maximum summation of K consecutive elements in the array is " << solve << endl;

}
/*

Standard Input and Output
1. if N == K
Input array size and value
5 5
1 2 3 4 5
maximum summation of K consecutive elements in the array is 15
2. if N > K
Input array size and value
5 3
5 2 -1 0 3
maximum summation of K consecutive elements in the array is 6
Time Complexity : O(N)
Space Complexity : O(1)

*/


<|start_filename|>Java/math/Segmented_Sieve.java<|end_filename|>
/*
  Segmented sieve is used to print prime number in a given range(l,r).
*/

import java.util.ArrayList;
import java.util.Scanner;

public class Segmented_Sieve {

	public static int MAX=1000000;
	public static boolean prime[]=new boolean[MAX+1];
	
//	Basic sieve returning a list of primes number less than or equal to MAX
	public static ArrayList<Integer> sieve() {
		
//		Marking all number as true initailly
		for(int i=0;i<=MAX;i++) {
			prime[i]=true;
		}
		
//	0 and 1 are not prime , so marking them as false		
		prime[0]=prime[1]=false;
		
		for(int i=2;i*i<=MAX;i++) {
//			If the given number is prime
			if(prime[i]==true) {
//				Marking all its multiple as false
				for(int j=i*i;j<=MAX;j+=i) {
					prime[j]=false;
				}
			}
		}
		
		ArrayList<Integer> primeList=new ArrayList<Integer>();
		
		for(int i=0;i<=MAX;i++){
			if(prime[i]==true) {
				primeList.add(i);
			}
		}
		
		return primeList;
	}
	
//	Printing prime number in the given range l to r
	public static void printPrimeInRange(long l,long r,ArrayList<Integer> primeList) {
		
		boolean array[]=new boolean[(int)(r-l+1)];
		
		for(int i=0;i<=(r-l);i++) {
			array[i]=true;
		}
		
		for(int i=0;i<primeList.size()&&(long)primeList.get(i)*primeList.get(i)<=r;i++) {
			
			int currentPrime=primeList.get(i);
			
//			Finding nearest number greater than or equal to l  which is divisible by currentPrimeNumber
			int baseValue=(int)(l/currentPrime)*currentPrime;
			
			if(baseValue<l) {
				baseValue+=currentPrime;
			}
			
			for(int j=baseValue;j<=r;j+=currentPrime) {
				array[(int)(j-l)]=false;
			}
			if(baseValue==currentPrime) {
				array[(int)(baseValue-l)]=true;
			}
		}
		
		for(int i=0;i<=(r-l);i++) {
			if(array[i]==true) {
				System.out.print((i+l)+" ");
			}
		}
	}
	
	public static void main(String[] args) {
		
		Scanner sc=new Scanner(System.in);
		
		System.out.println("Enter lower limit : ");
		long l=sc.nextLong();
		
		System.out.println("Enter upper limit  :");
		long r=sc.nextLong();
		
		ArrayList<Integer> primeList=sieve();
		
		System.out.println("Prime Number in range " + l + " to "+ r +" are : ");
		printPrimeInRange(l, r, primeList);
		
		
		
	}

}


<|start_filename|>C-Plus-Plus/math/neon_number.cpp<|end_filename|>
/*
	A neon number is a number where :- 
	the sum of digits of square of the number is equal to the number. 
	The task is to check and print neon numbers in a range given by the user.
*/

#include <bits/stdc++.h>
using namespace std;
//Function that prints the sum of digits of a number
int sum_of_digits(int y)
{
    int s = 0,v;
    while (y != 0)
    {
        v=y%10;
        s = s + v;
        y = y / 10;
    }
    return s;
}
bool Neon(int n)
{
    int sq = pow(n,2);
    int result = sum_of_digits(sq);
    //If sum of digits become equal to the number
    if (result == n)
        return true;
    else
        return false;
}

int main()
{
    cout << "Enter the range:";
    int a, b;
    cin >> a >> b;

    // Printing Neon Numbers according to the range
    cout<<"Neon numbers in between "<<a<<" to "<<b<<" are : ";
    for (int i = a; i <= b; i++)
        if (Neon(i) == true)
            cout << i << " ";
}
/*
   Input: Enter the range:1 10000
   Output: Neon numbers in between 1 to 10000 are : 1 9
*/
/*
   Time Complexity:O(nlogn) //where n is the range of a to b.
   Space Complexity:O(1)
*/


<|start_filename|>Dart/maths/Areas2D.dart<|end_filename|>
import 'dart:io';

// Area of a Square
double square(double a) {
  return a * a;
}

// Area of a Reactangle
double rectangle(double l, double b) {
    return l * b;
}

// Area of a Circle
double circle(double r, [double PI = 3.14]) {
    return PI * r * r;
}

// Area of a Triangle
double triangle(double b, double h) {
    return b * h/2.0;
}

// Area of a Parallelogram
double parallelogram(double b, double h) {
    return b * h;
}

// Area of a Trapezium

double trapezium(double a, double b, double h) {
    return (a+b)*h/2.0;
}

void main() {
  print("Enter side of square:");
  double squareSide = double.parse(stdin.readLineSync()!);
	print(square(squareSide));

  print("Enter length of rectangle:");
  double rectL = double.parse(stdin.readLineSync()!);
  print("Enter breadth of rectangle:");
  double rectB = double.parse(stdin.readLineSync()!);
  print(rectangle(rectL, rectB));

  print("Enter radius of circle:");
  double rad = double.parse(stdin.readLineSync()!);
  print(circle(rad));

  print("Enter base of triangle:");
  double triB = double.parse(stdin.readLineSync()!);
  print("Enter height of triangle:");
  double triH = double.parse(stdin.readLineSync()!);
  print(triangle(triB, triH));

  print("Enter base of parallelogram:");
  double paraB = double.parse(stdin.readLineSync()!);
  print("Enter height of parallelogram:");
  double paraH = double.parse(stdin.readLineSync()!);
  print(parallelogram(paraB, paraH));

  print("Enter length of 1st parallel side of trapezium:");
  double a = double.parse(stdin.readLineSync()!);
  print("Enter length of 2nd parallel side of trapezium:");
  double b = double.parse(stdin.readLineSync()!);
  print("Enter height of trapezium:");
  double h = double.parse(stdin.readLineSync()!);
  print(trapezium(a, b, h));
}
/**
Time complexity = O(n)
Space complexity = O(n)
Sample input/output:-
Enter side of square:
2.0
4.0
Enter length of rectangle:
4.1
Enter breadth of rectangle:
2.3
9.429999999999998
Enter radius of circle:
3.0
28.259999999999998
Enter base of triangle:
3.0
Enter height of triangle:
2.0
3.0
Enter base of parallelogram:
4.5
Enter height of parallelogram:
2.0
9.0
Enter length of 1st parallel side of trapezium:
1.5
Enter length of 2nd parallel side of trapezium:
4.5
Enter height of trapezium:
6.0
18.0
 */


<|start_filename|>Java/Algorithms/Min_Max_Algorithm_implementation.java<|end_filename|>
/*
    The MinMax Algorithm is used to find the maximum and minimum element of an Array 
    in less no of comparisons(3*(n/2) - 2 comparisons) as compared to the Brute Force method.
    It uses a Divide N Conquer algorithmic approach(recursively dividing the array) to find minimum 
    and maximum elements 
*/

import java.util.Scanner;

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

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the size of array:-");
        
        int n = sc.nextInt();
        int arr[] = new int[n];
        
        System.out.println("Enter elements of array");
        
        for(int i = 0; i<n; i++){
            arr[i] = sc.nextInt();
        }
        
        //Least index of an array/subarrays
        int low = 0; 
        //Highest index of an array/subarrays
        int high = n - 1; 
        
        int output[] = MinMax(arr, low, high);
        System.out.println("Output:");
        System.out.println(String.format("Min: %d Max: %d", output[0], output[1]));
    }

    /* 
        Function that returns minimum and maximum out of 2 elements.
        It returns an array with first element as minimum and second element as maximum out of 2 elements.
    */ 

    public static int[] min_max_of_2_elements(int x, int y){
        int min_max[] = new int[2];
        if(x < y){
            min_max[0] = x;
            min_max[1] = y;
        }
        else{
            min_max[0] = y;
            min_max[1] = x;
        }
        return min_max;
    }

    public static int[] MinMax(int arr[], int low, int high){
        
        // If after dividing array, we have one element left or two elements then return min or max of those elements
        if(low == high || high == low + 1){
            return min_max_of_2_elements(arr[low], arr[high]);
        }

        // Else dividing array recursively into smaller parts.
        else{ 
            int mid = low + ((high - low) / 2);
            int arr1[] = MinMax(arr, low, mid);
            int arr2[] = MinMax(arr, mid+1, high);

            // Returning an array with first element as the min element and second element as max of two elements
            return new int[]{min_max_of_2_elements(arr1[0], arr2[0])[0], min_max_of_2_elements(arr1[1], arr2[1])[1]};
        }
    }
}

/*
    Time Complexity:- O(N)
    Space Complexity:- O(1)
*/

/*
Sample Case:
Enter the size of array:-
8
Enter elements of array:
8 7 3 12 6 4 2 11
Output:
Min: 2 Max: 12
*/


<|start_filename|>C-Plus-Plus/dp/unbounded_knapsack.cpp<|end_filename|>
/**
 * Finding the maximum value of the items that can be popacked into the knapsack if it is possible to take one item multiple times
 * DYNAMIC PROGRAMMING
 * Time Complexity O(n^2) 
 **/

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

int unboundedKnap(int w[], int v[], int W, int n)
{
    //table
    int t[n + 1][W + 1];

    /*Base conditions
    If the number of items in the knapsack is zero, then the value of the items taht can be packed is zero
    If the weight of the knapsack is zero, then the value of the items taht can be packed into the knapsack will be zero too*/
    for (int i = 0; i < n + 1; i++)
    {
        for (int j = 0; j < W + 1; j++)
        {
            if (i == 0 || j == 0)
                t[i][j] = 0;
        }
    }

    /*-->If the weight of the ith item is less than the weight of the knapsack, then we can either include the item or exclude it depending upon which will maximise the value
      -->If included then we can include it again
      -->If not included once then it is not included again
      -->If the weight is greater than the weight of the knapsack then we cannot include it into the knapsack at any time
    */

    for (int i = 1; i < n + 1; i++)
    {
        for (int j = 1; j < W + 1; j++)
        {
            if (w[i - 1] <= j)
                t[i][j] = max(v[i - 1] + t[i][j - w[i - 1]], t[i - 1][j]);
            if (w[i - 1] > j)
                t[i][j] = t[i - 1][j];
        }
    }
    return t[n][W];
}

//Driver code
int main()
{
    int W;
    cin >> W;
    int n;
    cin >> n;
    int v[n], w[n];
    for (int i = 0; i < n; i++)
        cin >> w[i] >> v[i];
    cout << unboundedKnap(w, v, W, n) << "\n";
}

/*
 * EXAMPLE
 * INPUT 
 * W=10
 * n=5
 * w[n] = 2 4 6 7 8
 * v[n] = 10 20 30 40 100
 * OUTPUT- 100
 */



<|start_filename|>Java/ds/MiddleOfLinkedList.java<|end_filename|>
//Java program to find middle of LinkedList

/*Possible Approaches: 
i) Traverse List: Traverse list to find it's length, then scan list to locate n/2 node from the beginning.
ii) Two - Pointer Approach: It is the efficient approach (only one scan). Use 2 pointers. Move one at twice the speed of second. 
When first pointer reaches the end of list, second pointer will point the middle node of the LinkedList.					   		
*/
import java.util.*;
public class MiddleOfLinkedList {
	Node head;
    	static class Node {
		int data;
		Node next;
			Node(int data) {
            			this.data = data;
			}
    		}
 
    public void addToTheLast(Node node) {
 
        if (head == null) {
            head = node;
        }
	else {
            Node temp = head;
            while (temp.next != null)
                temp = temp.next;
		temp.next = node;
        }
    }
 
    public void printList() {
        Node temp = head;
        while (temp != null) {
            System.out.format("%d ", temp.data);
            temp = temp.next;
        }
        System.out.println();
    }
 
    // This function will find middle element in linkedlist
    public Node findMiddleNode(Node head){
    	Node pointer1, pointer2;       
    	pointer1 = pointer2 = head;	 
    	int i = 0;
    	while(pointer1.next != null){
    		if(i == 0){
    			pointer1 = pointer1.next;
    			i=1;
    		}
    		else if(i == 1){
    			pointer1 = pointer1.next  
    			pointer2 = pointer2.next;
    			i=0;
    		}
    	}	
    	return pointer2; 
    }
    	
    //Main Method
    public static void main(String[] args) {
        MiddleOfLinkedList list = new MiddleOfLinkedList();
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the size of Linked List:");
        int n = sc.nextInt();
        System.out.println("Enter the data of Linked List:");
        int num = sc.nextInt();
        Node head = new Node(num);
        list.addToTheLast(head);
        Node tail = head;
        for(int i=0; i<n-1; i++){
            num = sc.nextInt();
            tail.next = new Node(num);
            tail = tail.next;
        }
        list.printList();
        Node middle = list.findMiddleNode(head);
        System.out.println("Middle node is: "+ middle.data);
    }
}

/*OUTPUT
  Enter the size of Linked List:
  5
  Enter the data of Linked List:
  1 2 3 4 5
  1 2 3 4 5 
  Middle node is: 3
  
  Time Complexity: O(n) 
  Space Complexity: O(1)
 */


<|start_filename|>Java/other/FirstNonRepeatingChar.java<|end_filename|>
import java.util.*;

public class FirstNonRepeatingChar {

    private static int firstNonRepeating(String str) {
        int len = str.length();
        int result = Integer.MAX_VALUE;
        HashMap<Character, CountIndex> countEachChar
            = new HashMap<Character, CountIndex>(len);
        
        for (int i = 0; i < len; i++) {
            if (countEachChar.containsKey(str.charAt(i))) {
                // if the character already exists in the hashmap,
                // we increment the counter for it by one
                countEachChar.get(str.charAt(i)).incrementCount();
            } else {
                // if first occurrence, then create an entry for it
                countEachChar.put(str.charAt(i), new CountIndex(i));
            }
        }

        for (Map.Entry<Character, CountIndex> entry : countEachChar.entrySet()) 
        {
            // checking all entries for repetition. If all repeating,
            // then Integer.MAX_VALUE is returned
            int c = entry.getValue().count; 
            int ind = entry.getValue().index; 
            if(c == 1 && ind < result) 
            { 
                result = ind; 
            } 
        } 
        return result;
    }
    
    public static void main(String[] args) {
        // taking String input
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a string:");
        String str = sc.nextLine();
        sc.close();

        int result = firstNonRepeating(str);

        System.out.println(result == Integer.MAX_VALUE
            ? "Either all characters repeat atleast once or String is empty"
            : "First non-repeating char:" + str.charAt(result) + " at index " + result);
    }
}

class CountIndex { 
    int count, index; 
  
    // constructor for first occurrence 
    public CountIndex(int index) 
    { 
        this.count = 1; 
        this.index = index; 
    } 
  
    // method for updating count 
    public void incrementCount() 
    { 
        this.count++; 
    } 
}
/**
 * Sample input/output:
 * Enter a string:
 * aabcdb
 * First non-repeating char:c at index 3
 * 
 * Enter a string:
 * lovetocode
 * First non-repeating char:l at index 0
 * 
 * Time complexity: O(n)
 * Since we need to go through the whole string at least once
 * Space complexity: O(n)
 * Space used for storing the String hashmap for keeping a track of frequency
 */


<|start_filename|>C-Plus-Plus/cp/Activity_Selection.cpp<|end_filename|>
/**
You are given n activities (from 0 to n-1) with their start and finish times.
Select the maximum number of activities that can be performed by a single person, 
assuming that a person can only work on a single activity at a time.

Input Format
The first line consists of an integer T, the number of test cases.
 For each test case, the first line consists of an integer N, the number of activities. 
 Then the next N lines contain two integers m and n, the start and end time of each activity.

Output Format
For each test case find the maximum number of activities that you can do.

Sample Input
1 
3
10 20
12 15
20 30

Sample Output
2

Explanation
Person can only do 0th and 2nd activities.
**/
#include<bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<utility>

using namespace std;

bool compare(pair<int,int> a,pair <int ,int> b)         //made compare function for sorting
{
	return a.second<b.second;
}

int main() 
{
	int testcases;
	
	cout<<"Enter no. of Testcases:";                      //no.of test cases to be tested
	cin>>testcases;

	while(testcases--)
	{
		int num,count;                                     //counter for answer
		count=1;                                           // Initialize count with 1
		
		cout<<"Enter no. of Activities:";
		cin>>num;
		
		pair<int,int>* arr = new pair<int,int>[num];      //An dynamic Array of Pairs
        
		cout<<"Enter activities:"<<endl;
		for(int i=0;i<num;i++)
		{
			cin>>arr[i].first>>arr[i].second;
		}

		sort(arr,arr+num,compare);                        // Inbuilt Sorting Function taking compare function as a parameter 

		int prev=0;

		for(int curr=1;curr<num;curr++)
		{
			if(arr[prev].second<=arr[curr].first)
			{
				count++;
				prev=curr;
			}
		}
		
        cout<<"Person can do only "<<count<<" activities at a time"<<endl;    //Result
		delete[] arr;  
	}
	return 0;
}


<|start_filename|>Java/math/countDigits/iterative.java<|end_filename|>
/*Iterative:*/
import java.util.Scanner;

public class CountDigits {

	public static void countdigit(int n) {
	        int count=0;
		while(n!=0){
                count=count+1;
                n=n/10;
              }
             System.out.println(count);   

	}
	
	public static void main(String[] args) {

		Scanner sc=new Scanner(System.in);
		
		System.out.print("Enter a number : ");
		int n=sc.nextInt();
		
		System.out.println("Number of digits in a number are : ");
		countdigit(n);
				
	}
/*	
 	Sample Input : 
	Enter a number : 24567
 	
	Sample Output : 5
	 	
*/


<|start_filename|>C-Plus-Plus/cp/Two_Pointers_Method.cpp<|end_filename|>
// Given a sorted array A, size of N ( N elements) and a target value X, find if there exists any pair of elements in the Array such that their total sum is equal to X.

/*
we can solve this by using Two pointers Method and thus time complexity will be O(N).
Two pointers Method is a method where one pointer starts from beginning and other from the end and they proceed towards each other simultaneously

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

int ar[100009];

bool Pair_exist_by_Two_Pointer_Method(int ar[], int N, int X)
{
    int i = 0, j = N - 1, cur_sum = 0;
    while(i < j)
    {
        cur_sum = ar[i] + ar[j];
        if(cur_sum == X)
        {
            return true;
        }
        else if(cur_sum < X)
        {
            i++;
        }
        else if (cur_sum > X )
        {
            j--;
        }
    }
    return false;
}


int main()
{
	int N, X;
	cout << "Input array size and target value\n";
	cin >> N >> X;
	for(int i = 0; i < N; i++)
    {
        cin >> ar[i];
    }
    bool solve = Pair_exist_by_Two_Pointer_Method(ar , N , X);
    if(solve)
        cout << "Pair found and their total sum is equal to target value\n";
    else
        cout << "Pair doesn't exist in the array\n";
}
/*

Standard Input and Output

Input array size and target value
6 70
10 20 35 50 75 80
Pair found and their total sum is equal to target value

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

*/


<|start_filename|>C/cp/Lexicographic_rank.c<|end_filename|>
// To find the rank of a string among all its lexicographically sorted permutations.
#include <stdio.h>
#include <string.h>

int lexicographic_rank(char*);
int fact(int);
int smallerright(char *, int);
int main()
{
	char string[100];
	printf("Enter the string:");
	scanf("%s", string);
	printf("Lexicographic Rank of the string=%d", lexicographic_rank(string));
}

// Function to calculate the rank of the string
int lexicographic_rank(char *string)
{
	int length = strlen(string);
	int total_permutation = fact(length);
	int i = 0;
	int rank = 1;
	int countsmallright;
	while (*(string + i) != '\0')
	{
		total_permutation = total_permutation / (length - i);
		countsmallright = smallerright(string, i);
		rank = rank + (countsmallright *total_permutation);
		i++;
	}

	return rank;
}

// Function to check if the element on the right side is smaller than the index ith element
int smallerright(char *string, int index)
{
	int i = index;
	int count = 0;
	while (*(string + i) != '\0')
	{
		if (*(string + i)<*(string + index))
		{
			count = count + 1;
		}
		i++;
	}

	return count;
}

// To calculate factorial of a number using recursion
int fact(int num)
{
	if (num == 0)
		return 1;
	else
		return (num* fact(num - 1));
}

/*
Sample Output
Enter the string:rohan
Lexicographic Rank of the string=117

Complexities
Time Complexity:O(n^2)
Space Complexity:O(n)
*/



<|start_filename|>C-Sharp/math/Armstrong_Number.cs<|end_filename|>
// Armstrong Number
using System;
public class Armstrong // Class Declaration
{
  public static void Main(string[] args) {
    int number, r, sum = 0, temp;
    Console.Write("Enter the Number to check whether it is an Armstrong Number or Not = ");
    number = int.Parse(Console.ReadLine()); // Getting Number From User    
    temp = number;
    while (number > 0) {
      r = number % 10;
      sum = sum + (r * r * r);
      number = number / 10;
    }
    // Checking if the number is Armstrong number or not
    if (temp == sum) Console.Write("{0} Is an Armstrong Number.", temp);
    else Console.Write("{0} Is Not an Armstrong Number.", temp);

  }
}

/*
Input:
Enter the Number to check whether it is an Armstrong Number or Not = 153
Output:
153 Is an Armstrong Number.

Input:
Enter the Number to check whether it is an Armstrong Number or Not = 788
Output:
788 Is Not an Armstrong Number.

Time Complexity: O(log(n))
Space Complexity: O(1)
*/


<|start_filename|>Go/cryptography/Affine_Substitution_Cipher/affinecipher.go<|end_filename|>
/*
    This is a simple program in golang to cipher the given plain text
    using Affine Substitution Method. The Affine cipher is a type of
    monoalphabetic substitution cipher, wherein each letter in an alphabet 
    is mapped to its numeric equivalent, encrypted using a simple mathematical 
    function, and converted back to a letter. 

    Formula : y = ( a*x +b ) % 26
    
    Here a = 17
         b = 20 

    Note : Here a should be chosen to be relatively prime to m  
*/

package main

import (

  "fmt"
  "unicode"
  "bufio"
  "os"
  "strings"

)

//Global Variables
var plaintext string
var ciphertext string

/* We use this list of alphabets to check what letter we have
   in plaintext*/
var list string = "abcdefghijklmnopqrstuvwxyz"
var a int = 17
var b int = 20
var cipherer string
var output string

// Using this function we build the cipherer
func buildcipherer() {
     var res int
     for i:=0;i<26;i++ {
         res = (a*i + b)%26
         cipherer += string(list[res])
     }
}

/*
 This function formats the given ciphertext according to
 the orginal plaintext recieved from the user as input.
 In the monoalphabeticcipher function below, we converet
 the given plaintext into lowercase for our cinvinence of 
 checking. So, the ciphertext we get is also in all 
 lowercase. Here, we format the ciphertext so that wherever
 there is capital letter in the plaintext, same follows 
 in the ciphertext.*/
func format(temp string) {

    /* Checking if the given letter in plaintext is capital 
       or not and changint it to capttal if it was*/
    for i:=0; i < len(temp); i++ {
       if (unicode.IsUpper (rune(temp[i]) ) ) {
           output += strings.ToUpper(string(ciphertext[i]))
       }else {
          output += string(ciphertext[i])
       }
    }
}

/* This is the function where we cipher the plaintext using 
   the cipherer into small letters */
func monoaplhabeticcipher() {

      // Converting the plaintext to small letters
      plaintext = strings.ToLower(plaintext)

      var temporary string
      /* Here we replace all the space charecter with underscore
         for out convinence*/
      for k:=0;k<len(plaintext);k++ {
          if(string(plaintext[k]) == " ") {
		temporary += string("_")
          }else {
		temporary += string(plaintext[k])
          }
      }

      plaintext = temporary

      /* If the inputted plaintext had space we give sapce in
         the cipher text also */
      for i:=0 ;i < len(plaintext); i++ {
          if(string(plaintext[i]) == "_") {
                ciphertext += " "
          }else {
                /* We replace the letter with corresponding letter 
                   from the cipherer */
                for j:=0 ; j<26 ; j++ {
                     if( string(plaintext[i]) == string(list[j]) ) {
                          ciphertext += string(cipherer[j])
                     }
                }
          }
      }
}

// driver function
func main () {

     // Taking the plaintext as input from user
     fmt.Print("Enter the plaintext : ")
     scanner := bufio.NewScanner(os.Stdin)
     scanner.Scan()

     plaintext = scanner.Text()

     // copy of plaintext
     temp := plaintext

     // building the cipherer
     buildcipherer()

     /* calling the monoaplhabetic cipher function
        to encrypt the input string leaving pit 
        the space in to small letters*/
     monoaplhabeticcipher()

     /* calling the format function to format the 
        calculated cipher text in accorfing to the 
        plaintext format */
     format(temp)

     // Printing the cipher text out
     fmt.Print("The cipher text is : ",output)

}

/*

     Sample I/O :

     a) All small letters :

     Enter the plaintext : hello world
     The cipher text is : jkzzy eyxzt 

     b) All Capital letters :

     Enter the plaintext : HELLO WORLD
     The cipher text is : JKZZY EYXZT

     c) Mix of small and capital letters :  
 
     Enter the plaintext : Hello World
     The cipher text is : Jkzzy Eyxzt  

*/


<|start_filename|>C-Plus-Plus/math/mystery_number.cpp<|end_filename|>
// C++ program to Check if a number is a Mystery Number or Not.
/*
A mystery number is that number which can be expressed as a sum of two 
numbers and those two numbers must be the reverse of each other
*/
#include <bits/stdc++.h>
using namespace std;

// Helper function to reverse a number.
int reverse(int n)
{
    int rev = 0;
    for (; n > 0; n /= 10)
    {
        rev = rev * 10;
        rev = rev + (n % 10);
    }
    return rev;
}

bool check_mystery_num(int n)
{
    /* Let us iterate from 1 upto n/2, to check if there is any pair, such that thier
       sum equals the given number and check if the pair are reverse of each other  */
    for (int i = 1; i <= n / 2; i++)
    {
        if (reverse(i) == n - i)
        {
            return true;
        }
    }
    return false;
}

int main()
{
    int n;
    cout << "Enter the number: ";
    cin >> n;
    bool res = check_mystery_num(n);
    if (res)
    {
        cout << "The given number " << n << " is a Mystery Number.";
    }
    else
    {
        cout << "The given number " << n << " is not a Mystery Number.";
    }
    return 0;
}

/*
Time Complexity: O(n*log(n)), where 'n' is the given number
Space Complexity: O(1)

SAMPLE INPUT AND OUTPUT

SAMPLE 1
Enter the number: 43234
The given number 43234 is a Mystery Number.

SAMPLE 2
Enter the number: 1234
The given number 1234 is not a Mystery Number.
*/


<|start_filename|>C-Plus-Plus/math/reorderedPowerOf2.cpp<|end_filename|>
/* Problem Statement:
Starting with a positive integer N, we reorder the digits in any order (including the original order) such that the leading digit is not zero.
The task is to return true if and only if we can do this in a way such that the resulting number is a power of 2.

Constraints:
1 <= N <= 10^9
*/

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

bool reorderedPowerOf2(int N) {
    string num = to_string(N);
    int n = num.size();
    int base = 1, x = 1;
    unordered_map<int, vector<int>> powers2; //size of string, powers of 2 of that length

    while(x <= n) {
        powers2[x].push_back(base);
        base *= 2;
        x = to_string(base).size();
    }

    vector<int> countDigits(10, 0); //stores freq of digits of string num
    for(int i = 0; i < n; i++) {
        countDigits[num[i] - '0']++;
    }

    for(auto power : powers2[n]) {
        string x = to_string(power);
        int nx = x.size();
        vector<int> countDigitsx (10, 0);
        for(int i = 0; i < nx; i++) {
            countDigitsx[x[i] - '0']++;
        }

        bool f = 1;
        for(int i = 0; i < 10; i++) {
            if(countDigitsx[i] != countDigits[i]){
                f = 0;
                break;
            }
        }
        if(f == 1) {
            return true;
        }
    }
    return false;
}

int main() {
    int n;
    cin >> n;
    reorderedPowerOf2(n) == 1 ? cout << "true" : cout << "false";
    return 0;
}

/*Examples:
1.  Input: 10
    Output : false
2.  Input: 46
    Output: true
*/


<|start_filename|>C-Plus-Plus/math/check_palindrome.cpp<|end_filename|>
// C++ program to check if a number is a palindrome or not
#include <bits/stdc++.h>
using namespace std;

int main()
{
    int num, temp, rev = 0;
    cout << "Enter the number:  ";
    cin >> num;
    temp = num;
    /*To check if a number is palindrome, we reverse the number
    and then compare it with the given number */
    while (temp)
    {
        int rem = temp % 10;
        rev = rev * 10 + rem;
        temp = temp / 10;
    }
    if (rev == num)
    {
        cout << "The given number is a palindrome number";
    }
    else
    {
        cout << "The given number is not a palindrome number";
    }
    return 0;
}

/*
Time Complexity: O(log(num)), where 'num' is the given number
Space Complexity: O(1)

SAMPLE INPUT AND OUTPUT

SAMPLE 1

Enter the number:  14321
The given number is not a palindrome number

SAMPLE 2

Enter the number:  43234
The given number is a palindrome number

*/


<|start_filename|>Java/math/countDigits/recursive.java<|end_filename|>
/*Recursive:*/
import java.util.Scanner;

public class CountDigits {

	public static int countdigit(int n) {
	        if(n==0){
                   return 0;
                }
                return 1 + countdigit(n/10);  

	}
	
	public static void main(String[] args) {

		Scanner sc=new Scanner(System.in);
		
		System.out.print("Enter a number : ");
		int n=sc.nextInt();
		
		System.out.println("Number of digits in a number are : ");
		System.out.println(countdigit(n));
				
	}
/*	
 	Sample Input : 
	Enter a number : 24567
 	
	Sample Output : 5
	 	
*/


<|start_filename|>C-Plus-Plus/other/Find_Kth_smallest_element_in_sorted_Matrix.cpp<|end_filename|>
/*  Find Kth smallest element in a row-wise and column-wise sorted Matrix. */

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

/* Function to find kth smallest element in the matrix */
int solve()
{
    /* Input row = size of row.
       Input col = size of column. */
    int row,col;
    cin >> row >> col;

    /* Input elements in matrix. */
    int a[row][col];
    for (int i = 0; i < row; ++i)
    {
        for (int j = 0; j < col; ++j)
        {
            cin >> a[i][j];
        }
    }    
    
    /* Input k */
    int k;
    cin >> k;

    /* Define a min-heap priority queue */
    priority_queue<int, vector<int>> pq;

    for (int i = 0; i < row; ++i)
    {
        for (int j = 0; j < col; ++j)
        { 
            /* Add the elements in first row of matrix */
            if(pq.size() < k)
            {
                pq.push(a[i][j]);
            }
            else
            {
                /* Pop an element and store the element.
                   Add the element lying in matrix into priority queue. */
                if(a[i][j] < pq.top())
                {
                   pq.pop();
                   pq.push(a[i][j]);
                }
            }
        }
    }
    /* Return last element value store in priority queue. */
    return pq.top();
}

int main()
{
    int k = solve();
        cout << "kth Smallest Element is : " << k << endl;
    return 0;
}

/*
Test cases :
    
    Input 1 :

        4 4
        10 20 30 40
        15 25 35 45
        24 29 37 48
        32 33 39 50
        3

    Output 1 :

        kth Smallest Element is : 20

    Input 2 :

        4 4
        10 20 30 40
        15 25 35 45
        24 29 37 48
        32 33 39 50
        7

    Output 2 :

        kth Smallest Element is : 30
    
    Time complexity: O(r*c)
    Space Complexity: O(1)
*/


<|start_filename|>Go/math/armstrong_number/armstrong_number.go<|end_filename|>
// Golang Program to check whether a given number is an Armstrong number or not

/*
  In recreational number theory, an Armstrong number (also known as narcissistic number)
  is a number that is equal to the sum of its own digits, each raised to the power of
  the total number of digits.
  For example, in the case of 3 digit numbers,
  153 is an Armstrong number as 153 = 1*1*1 + 5*5*5 + 3*3*3
*/

package main

import (
	"fmt"
	"strconv"
)

func main() {
	// taking an 'n' digit number as input
	var number int
	fmt.Print("\n Enter a number : ")
	fmt.Scan(&number)
	// displaying results after calling isArmstrong()
	if isArmstrong(number) {
		fmt.Printf(" %d is an Armstrong number", number)
	} else {
		fmt.Printf(" %d is NOT an Armstrong number", number)
	}
}

// function to check whether a number is Armstrong or not
func isArmstrong(number int) bool {
	sum := 0
	digit := 0
	copyNum := number
	/* getting the number of digits of the integer by
	   converting it to a string and finding its length */
	numberOfDigits := len(strconv.Itoa(number))
	for {
		// discarding negative integers
		if copyNum <= 0 {
			break
		}
		temp := 1
		// extracting last digit
		digit = copyNum % 10
		// raising it to the power of number of digits
		for i := 0; i < numberOfDigits; i++ {
			temp = temp * digit
		}
		// storing the resulting number in sum
		sum += temp
		copyNum = copyNum / 10
	}
	// returning true if the number is equal to sum
	return number == sum
}

/*
	Time Complexity = O(log(n))
	Space Complexity = O(1)

	Sample inputs and outputs:

	i/o 1 -
	 Enter a number: 153
	 153 is an Armstrong number.

	i/o 1 -
	 Enter a number: 369
	 369 is NOT an Armstrong number.

	i/o 3 -
	 Enter a number: 370
	 370 is an Armstrong number.
*/


<|start_filename|>C/search/Interpolation.c<|end_filename|>
// C Program for Interpolation search algorithm
#include <stdio.h>
//Array size must be less tha MAX
#define MAX 100
/* Interpolation search function begin ::
	Search for key element in array.
	If key present in a[0..n-1],
	then it return the index of that key element
	else return -1
*/
int interpolation_search(int a[], int low, int high, int key)
{
	int mid;
	while (low <= high && key >= a[low] && key <= a[high])  {

		if (low == high) {
			if (a[low] == key) return low;
			return -1;
		}
		//Finding the value of position
		mid = low + ((key - a[low]) / (a[high] - a[low])) * (high - low);
		// Condition of target found
		if (key == a[mid])
			return mid + 1;
		// If key is greater then
		// key must be in upper part
		if (key < a[mid])
			high = mid - 1;
		// If key is smaller then
		// key must be in lower part
		else
			low = mid + 1;
	}
	return -1;
}
/* End of interpolation_search() */
/* The main() begins */
int main()
{
	int a[MAX];
	int i, num;
	int key, pos;
	printf("\nEnter the size of array (num < %d) :", MAX);
	scanf("%d", &num);
	//Interpolation search work best for uniform array
	printf("Enter %d Elements of array  :\n", num);
	for (i = 0; i < num; i++)
		scanf("%d", &a[i]);
	printf("\nEnter the value to be Search : ");
	scanf("%d", &key);
	//Display the user inputs of element and searched key
	printf("\nELEMENTS ARE : \n ");
	for (i = 0; i < num; i++)
		printf("%d\t", a[i]);
	printf("\nElement to be search is : %d", key);
	pos = interpolation_search(&a[0], 0, num - 1, key);
	//Check if the elemnet found in an array or not!
	printf("\n\nOutput -->\n");
	if (pos == -1)
		printf("\nElement %d not found\n", key);
	else
		printf("\nElement %d found at position %d\n", key, pos);
	return 0;
}
/* The main() end */
/*Sample Input Output of above code
Enter the size of array (num < 100) : 5
Enter 5 Elements of array  :
1
2
3
4
5
Enter the value to be Search : 4
ELEMENTS ARE :
1    2    3    4    5
Element to be search is : 4


Output -->
Element 4 found at position 4.
*/


<|start_filename|>C-Plus-Plus/cp/ARRAYSUB.cpp<|end_filename|>
// Given an array and an integer k, find the maximum for each and every contiguous subarray of size k.
// https://www.spoj.com/problems/ARRAYSUB/

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

int main() {
	//Taking Input From The User.
	int n;
	cout << "Enter The value of N:\n";
	cin >> n; //Size of Array
	int array[n];
	cout << "Enter the elements of array:\n";
	for (int i = 0; i < n; ++i) {
		cin >> array[i];
	}
	int k;
	cout << "Enter the value of k:\n";
	cin >> k; //Size Of The Sliding Window

	deque<int> d(k);//Created data Structure Deque Of Size k
	cout << "Maximum Numbers in sliding window of size " << k << " are:\n";
	for (int i = 0; i < n; i++) {
		if (i >= k) {
			cout << array[d.front()] << " ";
			//Checking whether a given number is in sliding window or not.
			//If it is not then pop the front element.
			while (!d.empty() && d.front() <= i - k) {
				d.pop_front();
			}
		}
		//If the given number is greater than number at last then we pop it.
		while (!d.empty() && array[i] >= array[d.back()]) {
			d.pop_back();
		}
		d.push_back(i);
	}
	cout << array[d.front()];
}

/*
Time Complexity : O(N*Log2(N))
Sample I/O:
INPUT :
Enter The value of N:
9
Enter the elements of array:
1 2 3 1 4 5 2 3 6
Enter the value of k:
3

OUTPUT:
Maximum Numbers in sliding window of size 3 are:
3 3 4 5 5 5 6
*/


<|start_filename|>JavaScript/Algorithms/BoyerMooreAlgorithm.js<|end_filename|>
    /*
     *   An arrow function with 1 parameter and returns a value.
     *   @param {Array} arrayOfCandidates contains a list of candidates
     *   @return {number} majority candidate value selected by the algorithm
     *   
     *   This function determines the candidate who has the 
     *   the majority number of votes, this algorithm was proposed by <NAME>. 
     */
    const selectCandidate = (arrayOfCandidates) => {

        var majorityVotes = 1; //contains the vote number of the candidate
        var majorityCandidate = arrayOfCandidates[0]; //contains current majority candidate

        for (var i = 1; i < arrayOfCandidates.length; i++) //Iterates through the list of candidates
        {

            /*
             * checks whether the current candidate value is 
             * same as of it's preceding one
             */
            if (majorityCandidate == arrayOfCandidates[i]) {
                majorityVotes++;
            } else {
                majorityVotes--;
            }

            /*
             * If majorityVotes deduct to 0 then a new candidate 
             * is assigned and the value of majorityVotes reset to 1
             */
            if (majorityVotes <= 0) {
                majorityVotes = 1; //Resetting value of majorityVotes
                majorityCandidate = arrayOfCandidates[i]; //Assigning new candidate
            }
        }
        return majorityCandidate; //Returns MajorityCandidate selected by the algorithm
    }

    /*
     *  An arrow function with 2 parameters and returns a value
     *  @param {Array} arrayOfCandidates contains a list of candidates
     *  @param {number} selectedCandidate the selected candidate by the Boyer Moore's Algorithm
     *  @return {boolean} verifies and returns that the given candidate is Majority Candidate or not
     * 
     * This function verifies that the given candidate selected is a valid candidate 
     * and satisfies the need of having votes greater than 50% of the length of the list.
     */
    const validateSelectedCandidate = (arrayOfCandidates, selectedCandidate) => {

        var countOfSelectedCandidate = 0; //counts number of seats earned of the candidate

        //Iterates through the list of candidates
        arrayOfCandidates.forEach(candidate => {

            /*
             *   If the selected candidate by the algorithm has the value equal
             *   to the current element value than the countOfSelectedCandida
             *   is incremented by 1
             */
            if (selectedCandidate == candidate) {
                countOfSelectedCandidate++;
            }
        });
        /*
         *  Verifies that the total count of the candidate 
         *  is greater than 50% of the total length of the list
         * 
         *  returning true signifies that the selected candidate is a legit candidate and has majority votes
         *  returning false signifies that the selected candidate is not a legit candidate and no majority candidate is detected in the list
         */
        if (countOfSelectedCandidate > (arrayOfCandidates.length / 2)) {
            return true;
        }
        return false;
    };

    /*
     *  An arrow function with 1 parameter and no return value
     *  @param {Array} listOfCandidates contains a list of candidates 
     * 
     *  This function acts as the main entry point for the execution flow
     */
    const main = (listOfCandidates) => {
        var selectedCandidate = selectCandidate(listOfCandidates); //Fetches value of the selected candidate
        var result = validateSelectedCandidate(listOfCandidates, selectedCandidate); //Passes the candidate for verification and gets the result
        if (result) {
            console.log(selectedCandidate + " Has The Majority Number Of Votes")
        } else {
            console.log("No Majority Candidate Detected")
        }
    }

    //Declaration of list of candidates
    var listOfCandidates = new Array(3, 3, 3, 3, 1, 1, 1, 3, 2);
    //Calls main function for starting execution process
    main(listOfCandidates);

    //Output : 3 Has The Majority Number Of Votes


<|start_filename|>C/ds/paranchecker.c<|end_filename|>
/*
Given a string of parenthesis check if parenthesis occurred in pair
Example:
Input: s="({})"
Output: yes
Input: s="[{(}])"
Output: yes
Input: s="(((}"
Output: no
*/

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int check(char *a){
    int a1 = 0,a2 = 0 , b1= 0, b2=0,c1=0,c2=0;
    for(int i=0;i<strlen(a) ; i++){
        if(a[i]=='{')
            a1++;
        else if(a[i]=='}')
            a2++;
        else if(a[i]=='(')
            b1++;
        else if(a[i]==')')
            b2++;
        else if(a[i] =='[')
            c1++;
        else if(a[i]==']')
            c2++;
    }
    if(a1==a2 && c1==c2 && b1==b2)             //we are checking if opening and closing brackets are same then it is true 
        return 1;
    else 
        return 0;
}
int main() {
char a[1001];
    int n,valid;

     scanf("%s",a); //accepting input
         valid = check(a);        //if function returns 1 then it is true
         if(valid==1)
             printf("yes\n");
    else                //else it is false
        printf("no\n");
    return 0;
}


<|start_filename|>C-Plus-Plus/cp/1st_negative_no_in_every_window_of_size_k.cpp<|end_filename|>
/**
 *  First Negative Integer in Every Window of Size K
 *  Cpp program to find first negative integer in each subarray
 *  of fixed size k, given an array of integers, using the 'Sliding
 *  Window Technique'. In case there is no negative integer in selected
 *  window, print 0.
 */

#include <bits/stdc++.h>

using namespace std;

/* function to find the first negative 
 integer in every window of size k*/
void printFirstNegativeInteger(int len, int k, int arr[])
{
    //A dynamic Array to store negative integers for current window of size k.
    vector<int> list;
    //Dynamic array to store 1st negative of each window
    vector<int> ans;
    int start = 0, end = 0;
    while (end < len) {
        //Add current element at the back of list if it is a negative integer
        if (arr[end] < 0)
            list.push_back(arr[end]);
        //When window size less than k, increase the size of window
        if (end - start + 1 < k)
            end++;
        //On reaching window size
        else if (end - start + 1 == k) { //If list is empty then the window does not have negative integer
            if (list.size() == 0)
                ans.push_back(0);
            else { //Else is not empty then element at the front
                //of list is the first negative integer of previous window
                ans.push_back(list.front());
                // Remove the elements which are out of this window
                if (arr[start] == list.front())
                    list.erase(list.begin());
            }
            //slide the window
            start++;
            end++;
        }
    }
    //Print the first negative integer of each window
    for (int i = 0; i < ans.size(); i++)
        cout << ans[i] << " ";
    cout << endl;
}

int main()
{
    //taking input from user
    int len;
    cout << "Enter the length of array of integers: ";
    cin >> len;
    int arr[len];
    cout << "Enter array of integers: ";
    for (int i = 0; i < len; i++)
        cin >> arr[i];
    int k;
    cout << "Enter size of window: ";
    cin >> k;
    printFirstNegativeInteger(len, k, arr);
    return 0;
}

/*
    Test cases:

    INPUT:-
    Enter the length of array of integers: 8
    Enter array of integers: 12 3 -7 8 -15 39 15 20
    Enter size of window: 3
    OUTPUT:-
    -7 -7 -7 -15 -15 0

    INPUT:-
    Enter length of array of integers: 9
    Enter array of integers: -1 2 0 3 -2 -1 -2 10 8
    Enter size of window: 5
    OUTPUT:-
    -1 -2 -2 -2 -2

    Time complexity: O(N)
    Space complexity: O(k)

*/


<|start_filename|>Java/cp/RectArea.java<|end_filename|>
/* Given n non-negative integers representing the histogram's bar height where 
the width of each bar is 1, find the area of largest rectangle in the histogram */

import java.util.*;
import java.lang.*;
import java.io.*;

class RectArea {
    private static int largestRectangleArea(int[] array) {
        int n = array.length;
        Stack<Integer> s = new Stack<Integer>();
        int[] left_nearest_small = new int[n];
        int[] right_nearest_small = new int[n];
        for(int i = 0; i < n; i++) {
            while(!s.isEmpty() && array[s.peek()] >= array[i])
                s.pop();
            left_nearest_small[i] = (s.isEmpty() ? -1 : s.peek());
            s.push(i);
        }
        s = new Stack<Integer>();
        for(int i = n-1; i >= 0; i--) {
            while(!s.isEmpty() && array[s.peek()] >= array[i])
                s.pop();
            right_nearest_small[i] = (s.isEmpty() ? n : s.peek());
            s.push(i);
        }
        int area = 0;
        // find area for each possible bar being the maximum heighted bar in the considered bars
        for(int i = 0; i < n; i++)
            area = Math.max(area, (right_nearest_small[i]-left_nearest_small[i]-1)*array[i]);
        return area;
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] array = new int[n];
        // take input
        for(int i = 0; i < n; i++)
            array[i] = sc.nextInt();
        System.out.println(largestRectangleArea(array));
    }
}


/**

Input:
6
2 1 5 6 2 3
Output:
10
TimeComplexity : O(n)
SpaceComplexity : O(n)

**/




<|start_filename|>C-Plus-Plus/cp/Sort_Color.cpp<|end_filename|>
/*
Given an array nums with n objects colored red, white, or blue,
sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.

Example 1:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Example 2:
Input: nums = [2,0,1]
Output: [0,1,2]

Example 3:
Input: nums = [0]
Output: [0]

Example 4:
Input: nums = [1]
Output: [1]

Constraints:

n == nums.length
1 <= n <= 300
nums[i] is 0, 1, or 2.

link to the problem: https://leetcode.com/problems/sort-colors/
*/

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

class Sort_Col {
	int n;
	int a[MAX];
  public:
	void sort_colors(int a[]) {
		int lo = 0;
		int hi = n - 1;
		int mid = 0;

		// Iterate till all the elements
		// are sorted
		while (mid <= hi) {
			switch (a[mid]) {

			// If the element is 0
			case 0:
				swap(a[lo++], a[mid++]);
				break;

			// If the element is 1 .
			case 1:
				mid++;
				break;

			// If the element is 2
			case 2:
				swap(a[mid], a[hi--]);
				break;
			}
		}
	}

	void set_data() {
		cout << "Enter number of elements: " << endl;
		cin >> n;
		cout << "Input Numbers:" << endl;

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

	void display() {
		sort_colors(a);

		cout << "[";
		for (int i = 0; i < n; i++) {
			cout << a[i] << "  ";
		}
		cout << "]";
	}

};

int main() {
	Sort_Col sc;
	sc.set_data();
	sc.display();
	return 0;
}


/*
Complexity Analysis:
Time Complexity: O(n) as only one traversal of the array is needed.
Space Complexity: O(1) as no extra space is required.

Example 1:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Example 2:
Input: nums = [2,0,1]
Output: [0,1,2]

Example 3:
Input: nums = [0]
Output: [0]

Example 4:
Input: nums = [1]
Output: [1]
*/


<|start_filename|>C/dp/Fibonacci.c<|end_filename|>
//C program to calculate the nth fibonacci term using DP memoization
#include<stdio.h>

//Global array storing the nth term index wise,the size can be changed as per use.
int f[1000];
 
//Fibonnaci function 
int fibonacci(int n)
{
  //Fibonnaci series:
  //f[0]=0 and f[1]=1
  //base condition:
  if(n<=1)
  {
    f[n]=n;
    return n;
  }
  //Recursive function:
  //f[n]=f[n-1]+f[n-2]
  else{

    if(f[n-2]==-1)

      f[n-2]=fibonacci(n-2);

    if(f[n-1]==-1)

      f[n-1]=fibonacci(n-1);

    return f[n-1]+f[n-2];
  }
}
 
//Main Function 
int main()
{
  
    int i, n;
    printf("Enter the number the indexing starts from 1\n");
    scanf("%d",&n);
    if(n<=0)
    printf("Wrong Input\n");
    else
    {
	    for(i=0;i<n;i++)
	      f[i]=-1;
	    fibonacci(n);
	 
	    printf("The nth fibonacci term is: %d",f[n-1]);
    }
    
    return 0;
}
/* Author : <NAME> (@chandansahuji)
contributing as a part of hackinCodes 2020

Sample Input:
enter the number
n=5

sample output:
The nth fibonacci term is:3

Time Complexity-O(n)
Space Complexity-O(n)
*/



<|start_filename|>Java/other/SudokuSolver.java<|end_filename|>
import java.util.Scanner;

public class SudokuSolver {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter elements of unsolved sudoku. Type 0 for empty cells:");
        int[][] sudokuArr = new int[9][9];
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                sudokuArr[i][j] = scanner.nextInt();
            }
        }
        scanner.close();

        if (solveSudoku(sudokuArr)) {
            System.out.println("Solved sudoku:");
            for (int i = 0; i < 9; i++) {
                for (int j = 0; j < 9; j++) {
                    System.out.print(sudokuArr[i][j]+ ", ");
                }
                System.out.println();
            }
        } else {
            System.out.println("Unsolvable");
        }
    }

    private static boolean solveSudoku(int[][] sudokuArr) {
        int row = -1, col = -1;
        boolean isEmpty = true;

        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                if (sudokuArr[i][j] == 0) {
                    row = i;
                    col = j;

                    // we still have some remaining
                    // missing values in Sudoku
                    isEmpty = false;
                    break;
                }
            }
            if (!isEmpty) {
                break;
            }
        }

        if (isEmpty) {
            return true;
        }

        for (int i = 1; i <= 9; i++) {
            if (isSafe(sudokuArr, row, col, i)) {
                sudokuArr[row][col] = i;
                if (solveSudoku(sudokuArr)) {
                    return true;
                }
                else {
                    sudokuArr[row][col] = 0;
                }
            }
        }

        return false;
    }

    private static boolean isSafe(int[][] sudokuArr, int row, int col, int i) {
        for (int d = 0; d < 9; d++) {
            if (sudokuArr[row][d] == i) {
                return false;
            }
        }

        for (int r = 0; r < 9; r++) {
            if (sudokuArr[r][col] == i) {
                return false;
            }
        }

        int rowStart = row - (row % 3);
        int colStart = col - (col % 3);
        for (int r = rowStart; r < rowStart + 3; r++) {
            for (int d = colStart; d < colStart + 3; d++) {
                if (sudokuArr[r][d] == i) {
                    return false;
                }
            }
        }

        return true;
    }
}

/*
* Sample input/output:
* Enter elements of unsolved sudoku. Type 0 for empty cells:
* 3 0 6 5 0 8 4 0 0
* 5 2 0 0 0 0 0 0 0
* 0 8 7 0 0 0 0 3 1
* 0 0 3 0 1 0 0 8 0
* 9 0 0 8 6 3 0 0 5
* 0 5 0 0 9 0 6 0 0
* 1 3 0 0 0 0 2 5 0
* 0 0 0 0 0 0 0 7 4
* 0 0 5 2 0 6 3 0 0
* Solved sudoku:
* 3, 1, 6, 5, 7, 8, 4, 9, 2,
* 5, 2, 9, 1, 3, 4, 7, 6, 8,
* 4, 8, 7, 6, 2, 9, 5, 3, 1,
* 2, 6, 3, 4, 1, 5, 9, 8, 7,
* 9, 7, 4, 8, 6, 3, 1, 2, 5,
* 8, 5, 1, 7, 9, 2, 6, 4, 3,
* 1, 3, 8, 9, 4, 7, 2, 5, 6,
* 6, 9, 2, 3, 5, 1, 8, 7, 4,
* 7, 4, 5, 2, 8, 6, 3, 1, 9,
*
* Time complexity: O(9^(n*n))
* Space Complexity: O(n*n)
*/


<|start_filename|>C-Plus-Plus/graphs/Vertical_order_print_of_binary_tree.cpp<|end_filename|>
/*
Vertical order print of binary tree
====================================
Given a binary tree, print it in vertical manner
eg:
           1
        /    \
       2      3
      / \   /   \
     4   5  6   7
               /  \
              8   9
Vertical Print:
4
2
1 5 6
3 8
7
9

Time Complexity: O(n)
Space Complexity: O(n)
*/
#include <iostream>
#include<map>
#include <vector>
using namespace std;

// Node class
class node {
public:
	int data;
	node *left = NULL;
	node *right = NULL;

	node(int d) {
		data = d;
	}
};

// builds tree for pre-order input
node* buildTree() {
	int d; cin >> d;

	//  Base Case
	if (d == -1) {
		return NULL;
	}

	node *root = new node(d);
	root->left = buildTree();
	root->right = buildTree();
	return root;
}

// Recursive function to mark position of nodes
void markNodes(node* root, int pos, map<int, vector<int>> &mp) {

	if (root == NULL) {
		return;
	}

	mp[pos].push_back(root->data);
	markNodes(root->left, pos - 1, mp);
	markNodes(root->right, pos + 1, mp);
}

// prints vertical order
void verticalPrint(node* root) {
	map<int, vector<int>> mp;
	markNodes(root, 0, mp);

	for (auto it : mp) {
		for (auto x : it.second) {
			cout << x << " ";
		} cout << endl;
	}

}

// Driver code
int main() {

	node *root = buildTree();
	verticalPrint(root);
}

/*
Sample Input:
8 10 1 -1 -1 6 9 -1 -1 7 -1 -1 3 -1 14 -1 13 -1 -1

Sample Output:
1
10 9
8 6
7 3
14
13
*/

<|start_filename|>C/other/UniqueNumberIII.c<|end_filename|>
#include<stdio.h>

main()
{
    int n;
    printf("Enter number of elements: ");
    scanf("%d",&n);
    int arr[n], i;
    printf("\nEnter %d elements: ", n);
    for(i = 0 ;i < n ;i++)
    {
        scanf("\n%d",&arr[i]);
    }
    int one = 0;
    int two = 0;
    int n_t, x;
    for(i = 0; i < n; i++)
    {
        x = arr[i];
        two |=one & x;
        one ^= x;
        n_t  =~(one & two);
        one &= n_t;
        two &= n_t;
    }
    printf("\nThe number that occurs only once is %d \n", one);
}

/*
Time complexity: O(n)
Space complexity: O(n)

Example 1:
Sample input:
Enter number of elements: 7
Enter 7 elements: 6
2
5
2
2
6
6
Output: The number that occurs only once is 5

Example 2:
Sample Input:
Enter number of elements: 4
Enter 4 elements: 3
3
1
3
Output: The number that occurs only once is 1
*/


<|start_filename|>C-Plus-Plus/ds/Floor_of_a_number_in_BST.cpp<|end_filename|>
/*
Introduction 
Given a Binary Search Tree ,Find the Floor value of the given number in the BST
Floor value of a given number is the element existing in BST with value less than or equal to the given number

Argument/Return Type
Input of total no.of nodes is taken
Input of key values of nodes of tree are taken
*/

#include <bits/stdc++.h> 
using namespace std;
//Define a Global variable and keep updating it
int Floor;

//Define Node as structure
struct Node 
{
    int key;
    Node* left;
    Node* right;
};
 
// Function to create a node with 'value' as the data stored in it. 
// Both the children of this new Node are initially null.
struct Node* newNode(int value)
{
    Node* n = new Node;
    n->key = value;
    n->left = NULL;
    n->right = NULL;
    return n;
}

// Function to insert a node with given value to the root
struct Node* insert(struct Node* root,int element) 
{
    //If the root is NULL , create a node with given element and assign it to root
    //else if the root itself is the node with given data , return 
    //else recursively insert it in one of the subtrees accordingly
    if(root==NULL)
        root = newNode(element);
    else if(root->key < element)
        root->right = insert(root->right,element);
    else if(root->key > element)
        root->left = insert(root->left,element);
    
    return root;
}

//Function to update Floor value of the given number
void UpdateFloor(struct Node* root,int value)
{
   //If root is a NULL node , return
   if(root==NULL)
     return ;
 
   if(root->key > value)
    {
      //if root key > given value , 
      // recursively search for a floor value in left subtree
       UpdateFloor(root->left,value);
    }
   else if(root->key < value)
   {
       //if root key < given value , 
       //update the floor value and 
       //search for a greater value in right subtree recursively
       Floor=max(Floor,root->key);
       UpdateFloor(root->right,value);
   }
   else
   {
      // if root key = given value , 
      // update the Floor
      Floor = value;
   }
    
   return;
} 

// Driver code
int main()
{
    int n;
    cout<<"Enter total no.of nodes of the input Tree ( including NULL nodes ) : ";
    cin>>n;

    //create a null node  and initialise it as a NULL node
    struct Node* root;
    root=NULL;
    
    cout<<"Enter value of each node of the Tree , with head as the first value ( if a node is NULL , enter -1 ) with spaces"<<endl;
    for(int i=0;i<n;i++)
    {
        int data;
        cin>>data; 
        //take input of data of each node and insert it in the root
        root = insert(root,data);
    }

    cout<<"Enter a number : ";
    int value;
    cin>>value;

    //Initialise floor variable as -1
    Floor=-1;

    //Call the function and print the result
    UpdateFloor(root,value);
    if(Floor!=-1)
      cout<<"Hence the Floor of given value in the BST is : "<<Floor;
    else
     cout<<"There is no node with the value less than given value in the given Tree";
    
    return 0; 
}
    
/*
Input:
0 <= node->key < 1000000000
While entering node values of the tree , 
value of the head of the tree should be enetered first

Sample Test Case 1  
Input Binary Tree 1:                    
            11                                                             
          /     \                                             
         2      20                                      
        / \    /  \                           
       1   5 NULL 25                                

Input Format : 
Example :
Enter total no.of nodes of the input Tree ( including NULL nodes ) : 6
Enter value of each node of the Tree , with head as the first value ( if a node is NULL , enter -1 ) with spaces
11 2 20 1 5 25
Enter a number : 8

Output Format :
Example : ( Output to the above input example ) 
Hence the Floor of given value in the BST is : 5

Time/Space Complexity
Time Complexity : O(n) 
   Where n is the no.of nodes ofthe tree
Space Complexity : O(1) 
*/


<|start_filename|>JavaScript/Backtracking/N-Queens.js<|end_filename|>
/* The n-queens puzzle is the problem of placing n queens 
on an n x n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle. */


/* Function to get the number of way N queens can be placed on a NxN chess board */
const totalNQueens = (n) => {
    
    /* Helper Function */
    const getTotalWays = (board, row, col, n) => {

        /* Base case when we filled each and every row */
        if(row == n){
            return true;
        }
        
        /* Checking every column in a particular row */
        for(let i=col; i<n; i++){

            /* Checking if a queen is already placed in that particular spot */
            if(!board[row][i]){
                /* Placing a queen in that spot */
                board[row][i] = true;

                /* Checking the validity of our move and continuing to place queens in the next row */
                if(validMove(board, row, i, n) && getTotalWays(board, row+1, 0, n)){
                    /* Incrementing our answer if n queens are placed on the chessboard */
                    ans++;
                }

                /* Removing the queen in that spot to get a different combination */
                board[row][i] = false;
            }
        }

        /* Returning false if we cannot place any queens in that row */
        return false;
    }
            

    /* Function to check the validity of our move */
    const validMove = (board, row, col, n) => {
        return validCol(board, row, col, n) &&
            validRow(board, row, col, n) && 
            validRightUpperDiagonal(board, row, col, n) && 
            validRightLowerDiagonal(board, row, col, n) && 
            validLeftUpperDiagonal(board, row, col) && 
            validLeftLowerDiagonal(board, row, col, n)
    }
            

    /* Function to check if no two queens can kill each other in their respective columns */
    const validCol = (board, row, col, n) => {
        let count = 0;
        for(let i=0; i<n; i++){
            if(board[i][col]){
                count++;
            }
            if(count > 1){
                return false;
            }
        }
        return true;
    }
            
    /* Function to check if no two queens can kill each other in their respective row */
    const validRow = (board, row, col, n) => {
        let count = 0;
        for(let i=0; i<n; i++){
            if(board[row][i]){
                count++;
            }
            if(count > 1){
                return false;
            }
        }
        return true;
    }
            
    /* Function to check if no two queens can kill each other in their respective right upper diagonal */
    const validRightUpperDiagonal = (board, row, col, n) => {
        let r = row-1;
        let c = col+1;
        let count = 0;
        while(r>=0 && c<n){
            if(board[r][c]){
                count++;
            }
            if(count > 0){
                return false;
            }
            r--;
            c++;
        }
        
        return true;
    }
    
    /* Function to check if no two queens can kill each other in their respective right lower diagonal */
    const validRightLowerDiagonal = (board, row, col, n) => {
        let r = row+1;
        let c = col+1;
        let count = 0;
        while(r<n && c<n){
            if(board[r][c]){
                count++;
            }
            if(count > 0){
                return false;
            }
            r++;
            c++;
        }
            
        return true;
    }
            
    /* Function to check if no two queens can kill each other in their respective left upper diagonal */
    const validLeftUpperDiagonal = (board, row, col) => {
        let r = row-1;
        let c = col-1;
        let count = 0;
        while(r>=0 && c>=0){
            if(board[r][c]){
                count++;
            }
            if(count > 0){
                return false;
            }
            r--;
            c--;
        }
            
        return true;   
    }
            
    /* Function to check if no two queens can kill each other in their respective left lower diagonal */
    const validLeftLowerDiagonal = (board, row, col, n) => {
        let r = row+1;
        let c = col-1;
        let count = 0;
        while(r<n && c>=0){
            if(board[r][c]){
                count++;
            }
            if(count > 0){
                return false;
            }
            r++;
            c--;
        }
            
        return true;   
    }

    const createRow = ()=>{
        return new Array(n).fill(false);
    }
    

    /* Creating an empty board */
    let board = new Array(n).fill(null).map(createRow);

    let ans = 0;

    /* Gets the total number of way N Queens can be placed */
    getTotalWays(board, 0, 0, n);
    
    /* Returning the answer */
    return ans;
};

/* Printing the answer for 10x10 chessboard -> Ans = 724 ways */
console.log(`${totalNQueens(10)} ways`);


/*Example 1

Input :
4

Output :
2

Explanation :
There are only two possible ways to place 4 Queens on a 4x4 chessboard

Example 2

Input :
10

Output :
724

Explanation :
There are 724 possible ways to place 10 Queens on a 10x10 chessboard


Time Complexity : O(N^N)
Space Complexity : O(NxN)
*/



<|start_filename|>Java/cp/Jump_Game.java<|end_filename|>
/*
  Jump Game :
      We need to find the minimum number of jumps to reach the end of the array starting from the first
      element of the array, jumps value would be (-1) if we are not able to reach the end of the array

  Example : array = {2,3,0,1,4,1,1,2,0,3,5}
            minimum jumps = 5  {2 to 3, 3 to 4, 4 to 2, 2 to 3, 3 to 5}

  Explanation : (Greedy Solution)

   1. We will check if array's length is equal to or less than 1 or not
          i.e  if array's length is equal to 1 then we have only one element in the
          array and it is already at the end and program will return 0

   2. Now, we will check if the first element of array is 0 or not,
          i.e if it is 0 then we can't make any jump and program will return -1

   3. Now, we will use the for loop from i = 1 till array's length when (i == array.length - 1)
      this is true then we have reached the end and we will return jumps

   4. (i + array[i]) is the number of steps we take from the current position and we will compare it with
      max_Jump_Reach and then we will use Math.max which will compare both and return the maximum and assigns
      it to the max_Jump_Reach again

   5. We have used checks-- so that we can iterate the for loop till the checks == 0 and find the maximum
      value for max_Jump_Reach and afterwards we will update checks by (max_Jump_Reach - i)
 */
import java.util.Scanner;

public class JumpGame {
	// jumpGame method
	public static int jumpGame(int array[]) {

		//Initializing max_Jump_Reach, checks, jumps
		int max_Jump_Reach = array[0];
		int checks = array[0];
		int jumps = 1;

		// If array has only 1 element then it is already at last element so return 0
		if (array.length <= 1) {
			return 0;
		}
		// If first element is 0 then we can't jump to any other element in the array
		if (array[0] == 0) {
			return -1;
		}
		// Traverse array
		for (int i = 1; i < array.length; i++) {

			// Check if we reached last element or not
			if (i == array.length - 1) {
				return jumps;
			}
			// Update max_Jump_Reach
			max_Jump_Reach = Math.max(max_Jump_Reach, i + array[i]);

			checks--;

			if (checks == 0) {
				jumps++;
				if (i >= max_Jump_Reach) {
					return -1;
				}
				// Initialize checks again
				checks = max_Jump_Reach - i;
			}
		}
		return -1;
	}

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

		Scanner sc = new Scanner(System.in);
		// Number of elements we want to put in array
		int number = sc.nextInt();
		int[] array = new int[number];

		// Putting values in array using for loop
		for(int i = 0 ; i < array.length ; i++) {
			array[i] = sc.nextInt();
		}
		// Initializing the value returned by jumpGame method to jumps
		int jumps = JumpGame.jumpGame(array);

		System.out.println("minimum number of Jumps required : "+jumps);
	}
}
/*
- Test Cases :
   1.  Input : 7
               2 1 3 4 1 2 3
      Output : minimum number of Jumps required : 3

   2.  Input : 4
               1 0 0 3
      Output : minimum number of Jumps required : -1

   3.  Input : 1
               0
      Output : minimum number of Jumps required : 0

- Complexity Analysis :
    * Time Complexity : O(n)
		  We are using only one for loop, so it iterates maximum 'n' times while traversing for loop

    * Space Complexity : O(n)
		 Auxiliary space : O(1)  +  input space : O(n)
*/


<|start_filename|>C-Plus-Plus/other/Fast_fibonacci_last_digit.cpp<|end_filename|>
// C++ Program to calculate last digit number of fibonacci series

#include <iostream>
using namespace std;

// Constraints for this function is 0≤𝑛≤10^7.

int get_fibonacci_last_digit(long long n) {
	int first = 0; // first integer of fibonacci series
	int second = 1; // second integer of fibonacci series

	int result;

	for (int i = 2; i <= n; i++) {
		result = (first + second) % 10; // storing the remainder in result instead of whole fibonacci series
		first = second;
		second = result;
	}

	return result;
}

// Below algorithm is taken from Geeksforgeeks

// Finds nth fibonacci number
long long int  fib(long long int f[], long long int n) {
	// 0th and 1st number of
	// the series are 0 and 1
	f[0] = 0;
	f[1] = 1;

	// Add the previous 2 numbers
	// in the series and store
	// last digit of result
	for (long long int i = 2; i <= n; i++)
		f[i] = (f[i - 1] + f[i - 2]) % 10;

	return f[n];
}

// Returns last digit of n'th Fibonacci Number
int findLastDigit(int n) {
	long long int f[60] = {0};

	// Precomputing units digit of
	// first 60 Fibonacci numbers
	fib(f, 60);

	return f[n % 60];
}


int main() {
	int number;
	cin >> number;
	//int result = get_fibonacci_last_digit(number);
	int result = findLastDigit(number);
	cout << result << '\n';

	return 0;
}

/*
Sample I/O:
Input:
200
Output:
5

Time Complexity: O(1) for findLastDigit() and O(n) for get_fibonacci_last_digit()
Space Complexity : O(1) for findLastDigit() and O(n) for get_fibonacci_last_digit()

*/


<|start_filename|>C-Plus-Plus/cp/Lexicographyically_largest_palindrome_subsequence.cpp<|end_filename|>
/* C++ Program to find lexicographically largest palindrome subsequence 
In this Program only input line contains a non-empty string S consisting of lowercase English letters only. Its length does not exceed 10.
Here, Characters in the strings are compared according to their ASCII codes and the one with largest ASCII code is lexicographically largest. 
And output contain frequency and all the reoccurrence of that character in string S in a single line.
*/     
#include<iostream>
#include<string>
using namespace std;

void Lexicographically_largest_palindrome_subsequence(string String) {
    string  assign, maxAscii;
    int i, j, counter, maxFrequency;
    //initialising maxAscii with character "a"                                
    maxAscii = "a";                         
    maxFrequency = 0;                     
    for(j = 0; j < String.size(); j++) {
        //initialising c with 0         
        counter = 0;                             
        for(i = 0; i < String.size(); i++) {
            //assigning value of element with index 'i' to a           
            assign = String[i];
            //this is for getting the lexicographically largest element (the one with largest ascii value)                  
            if(assign >= maxAscii)                       
            	maxAscii = assign;                     
        }
    }   
    for(i = 0; i < String.size(); i++) {
        assign = String[i];                           
        if(assign == maxAscii) {
            //increament c when we find our lexicographically largest character in string more than one time                  
            counter++;
            //for finding maximum frequency of character                              
            if(counter > maxFrequency) 
                maxFrequency = counter;                    
        } 
    }
    cout << maxFrequency << " ";
    for(i = 0; i < maxFrequency; i++) {  
        //printing subsequence of lexicographically largest character as output                        
        cout << maxAscii; 
    }
    return ;
}
int main() {
    string inputString;
    //getting user input as string        
    cin >> inputString;
    //calling function to perform the task
    Lexicographically_largest_palindrome_subsequence(inputString);
    return 0;
}

/* SAMPLE
Testcase 1
INPUT   startling
OUTPUT  2 tt
Testcase 2
INPUT   mississippi
OUTPUT  4 ssss
Testcase 3
INPUT   sausage
OUTPUT  1 u   
Time Complexity is O(n^2)   where n is length of string
Space Complexity is O(1)   */



<|start_filename|>C-Plus-Plus/dp/fibonacci_top_down.cpp<|end_filename|>
#include <iostream>
using namespace std;

//Recursion+Memoization
int fib(int n,int dp[]){
	//base case
	if(n == 0 || n == 1) return n;
	//Recursive
	//Look Up
	if(dp[n] != 0) return dp[n];

	int ans;
	ans = fib(n-1,dp)+fib(n-2,dp);
	return dp[n] = ans;
}


int main() {
 int n;
 cin>>n;
 int dp[n+1]={0};
 cout<<"output :"<<fib(n,dp)<<endl;

return 0;
}

/*
sample input output
input: 10
output: 55
*/

/*
Space O(n)
Time O(n)
*/


<|start_filename|>C/sort/mergesort_in_O(1)_space_complexity.c<|end_filename|>
// algorithm for merging two sorted array in O(1) space complexity and in
// Nlog(N) + Mlog(M) time complexity
#include <stdio.h>
#include <stdlib.h>
int i, j;

void swap(int &x, int &y)    // swapping the elements
{ 
    int temp = x; 
    x = y; 
    y = temp; 
} 

void mergesort(int a[], int b[], int n, int m) {
  int min = min(n, m);
  for (i = 0; i < min; i++)  // we are swapping the elements of both the array
    // which should be there in the result
  {
    if (a[n - i - 1] > b[i]) 
    {
       swap(a[n - i - 1], b[i]);   
    }
  }
  // sorting the first array
  int x = n;
  int round1 = x / 2 + x % 2;
  while (round1 > 0 && x > 1) {
    for (int i = 1; i + round1 <= n; i++)  // Comparing elements in the first array
      if (a[i - 1] > a[i + round1 - 1])
      {
        swap(a[i - 1], a[i + round1 - 1]);
      }

    x = round1;
    round1 = x / 2 + x % 2;
  }
  // Sorting  the second array
  int y = m;
  int round2 = y / 2 + y % 2;
  while (round2 > 0 && y > 1) {
    for (i = 1; i + round2 <= m; i++)  // Comparing elements in the second array
      if (b[i - 1] > b[i + round2 - 1]) 
      {
        swap(b[i - 1], b[i + round2 - 1]);
      }

    y = round2;
    round2 = y / 2 + y % 2;
  }
}

void print(int a[], int b[], int n, int m) {
  for (i = 1; i <= n;
       i++)  // printing the elements of the first and second array
    printf("%d ", a[i - 1]);
  for (i = 1; i <= m; i++) printf("%d ", b[i - 1]);
}

int main() {
  int n, m;
  printf(
    "please enter the number of elements for the first array\n");  // taking
  // input
  // from the
  // user
  scanf("%d ", &n);
  printf("please enter the number of elements for the second array\n");
  scanf("%d ", &m);
  int capacity = 100;
  int used = 0;
  int *a = (int *)malloc(sizeof(int) * capacity);
  int *b = (int *)malloc(sizeof(int) * capacity);

  printf("please enter the elements of the first array\n");
  for (i = 1; i <= n; i++) {
    scanf("%d", &a[i - 1]);
    if (used == capacity) {
      capacity *= 2;
      a = (int *)realloc(a, sizeof(int) * capacity);
    }
    a[used] = a[i - 1];
    used++;
  }

  printf("please enter the elements of the second array\n");
  for (i = 1; i <= m; i++) {
    scanf("%d", &b[i - 1]);
    if (used == capacity) {
      capacity *= 2;
      b = (int *)realloc(b, sizeof(int) * capacity);
    }
    b[used] = b[i - 1];
    used++;
  }
  mergesort(a, b, n, m);
  print(a, b, n, m);
  return 0;
}

/*
Sample input/output
Enter size of first array:
6
Enter size of second array:
5
Enter array elements:
1 5 7 9 13 17
Enter array elements:
4 6 10 13 15
output
1 4 5 6 7 9 10 13 13 15 17
*/


<|start_filename|>C-Plus-Plus/cp/Topological_sort.cpp<|end_filename|>
/*
Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering
of vertices such that for every directed edge uv, vertex u comes before v in
the ordering. Topological Sorting for a graph is not possible if the graph is
not a DAG.
*/

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

vector<vector<int>> adjList;
stack<int> s;
bool *visited;

// Number of Test Cases (Vertices)
int n;

void createGraph()
{
    int x, y;
    adjList.resize(n);

    for (int j = 0; j < n; j++)
    {
        cin >> x >> y;
        adjList[x].push_back(y);
    }
}

void topoSortFun(int i)
{
    visited[i] = true;
    for (int j = 0; j < adjList[i].size(); j++)
    {
        int key = adjList[i][j];
        if (!visited[key])
            topoSortFun(key);
    }
    s.push(i);
}

void topoSort()
{
    memset(visited, false, sizeof(visited));

    for (int i = 0; i < n; i++)
    {
        if (!visited[i])
            topoSortFun(i);
    }
}
void display()
{
    for (int i = 0; i < n; i++)
    {
        cout << s.top() << " ";
        s.pop();
    }
}
int main()
{
    cin >> n;
    visited = new bool[n];
    createGraph();
    topoSort();
    display();
}

/*
    Test Case:

    Input 1 :
    6
    5 2 
    5 0 
    4 0 
    4 1 
    2 3 
    3 1 

    Output 1 :
    5 4 2 3 1 0 

    Input 2 :
    6
    4 2
    5 1
    4 0
    3 1
    1 3
    3 2

    Output 2 : 
    5 4 1 3 2 0 

    Time Complexity: O(V + E) – where V is the number of vertices and E is the number of edges.

    Space Complexity: O(V)
*/


<|start_filename|>Go/math/Ugly_Number/uglynumber.go<|end_filename|>
/*
   This is a simple program in go language to check
   if a given number is an ugly number or not.
   
   An Ugly number is a number whose only prime factors
   are 2, 3 or 5.

   Note : 1 is taken as base case and is considered
          as an ugly number
*/

package main

import (

  "fmt"

)

/* This function repeatedly divides a give number
    till its divisible by the second number*/
func divisible(x,y int) int {

     var r int
     r = x % y

     for r == 0 {

         x = x/y
         r = x % y

     }

     return x
}

/* This is the function where we check if a given 
   number is an ugly number or not*/
func uglynumber(n int) int{

    // these are the base cases
    if(n == 1 || n==2 || n==3 || n==5 ) {

       return 1

    }

    // checking divisibility by 2 and its multiples
    n = divisible(n,2)
    if(n == 1) {
        return 1
    }

    // checking divisibility by 3 and its multiples
    n = divisible(n,3)
    if(n == 1) {
        return 1
    }

    // checking divisibility by 5 and its multiples
    n = divisible(n,5)
    if(n == 1) {
        return 1
     }

    // if its not divisible by either of them
    return 0

}

// driver function
func main() {

    var number int
    fmt.Print("Enter the number you want to check for :")
    // taking the number as input from user
    fmt.Scan(&number)

    // validating the input
    if (number <= 0){

        fmt.Print("Enter a valid number!")

    }else {

        var checker int
        checker = 0

        checker = uglynumber(number)

        // checking if the number is ugly number or not
        if( checker == 1 ){

             fmt.Print("The given number is a ugly number!")

        }else {

             fmt.Print("The given number is not an ugly number")

        }

    }

}

/*
    Sample I/O :

    a) Is Ugly Number :

    Enter the number you want to check for :300
    The given number is a ugly number!      

    b) Is not an Ugly Number :      
    
    Enter the number you want to check for :56
    The given number is not an ugly number 

    c) Invalid Input : 

    Enter the number you want to check for :0
    Enter a valid number! 

*/



<|start_filename|>Java/cp/KMP_Algorithm.java<|end_filename|>
/**
 * This program implements the Knuth–Morris–Pratt string-searching algorithm which searches
 * for occurrences of a "word" W within a main "text string" S by employing the observation
 * that when a mismatch occurs, the word itself embodies sufficient information to determine 
 * where the next match could begin, thus bypassing re-examination of previously matched 
 * characters.
 *
 * For more information visit: https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm
 *
 *
 * Time Complexity: O(n+m)                n -> Length of Text String
 * Space Complexity: O(m)                 m -> Length of Pattern String
 * 
 * 
 * Sample Input :- 
 *    	Text String - "aabaacaadaabaaba"
 *    	Pattern String - "aaba"
 *   
 * Expected Output :-
 *		Pattern found at index: 0
 *		Pattern found at index: 9
 *		Pattern found at index: 12
 */

import java.util.Scanner;

public class KMP_Algorithm {
	
	// To compute the longest prefix suffix array 
	static int[] computeLPS(String patt)
	{
		// length of pattern String
		int len = patt.length();
		
		int i, j;
		int[] lps = new int[len];
		
		// LPS of length 1 String is always 0
		lps[0] = 0;
		
		i = 1;
		j = 0;
		while(i < len)
		{
			if(patt.charAt(i) == patt.charAt(j))
			{
				lps[i] = j + 1;
				i++;
				j++;
			}
			else
			{
				if(j == 0)
				{
					lps[i] = 0;
					i++;
				}
				else
				{
					j = lps[j - 1];					
				}
			}
		}
		
		return lps;
	}
	
	// Prints all starting index of pattern in text string 
	static void KMPSearch(String txt, String patt)
	{
		int[] lps = computeLPS(patt);
		int i, j;
		int txt_len, patt_len;
		
		// Length of text string
		txt_len = txt.length();
		
		// Length of pattern string
		patt_len = patt.length();
		
		i = j = 0;
		while(i < txt_len)
		{
			if(patt.charAt(j) == txt.charAt(i))
			{
				i++;
				j++;
			}
			else
			{
				if(j == 0)
					i++;
				else
					j = lps[j-1]; 
			}
			
			if(j == patt_len)
			{
				// Printing the staring index of pattern in text string
				System.out.println("Pattern found at index: " + (i - j));
				j = lps[j-1];
			}
		}
	}
	
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		String patt = "", txt = "";
		
		// Dynamic Input
		System.out.print("Enter Text String: ");
		txt = sc.nextLine();
		System.out.print("Enter Pattern String: ");
		patt = sc.nextLine();
		sc.close();
		
		KMPSearch(txt, patt);
	}
}


<|start_filename|>C-Plus-Plus/other/Phone_keypad.cpp<|end_filename|>
/*
Given an integer n, using phone keypad find out and print all the possible strings that can be made using digits of input n.
*/
#include<bits/stdc++.h>
using namespace std;

void printKeypad_rec(int num, string output){
    string index[8] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    if(num == 0){
        cout << output <<endl;
        return;
    }
    
    int rem = num%10;
    int first = num/10;
    if(rem == 7 || rem == 9){
        printKeypad_rec(first, index[rem - 2][0] + output);
		printKeypad_rec(first, index[rem - 2][1] + output);
        printKeypad_rec(first, index[rem - 2][2] + output);
        printKeypad_rec(first, index[rem - 2][3] + output);
    }
    else{
        printKeypad_rec(first, index[rem - 2][0] + output);
		printKeypad_rec(first, index[rem - 2][1] + output);
        printKeypad_rec(first, index[rem - 2][2] + output);
    }
}

void printKeypad(int num){
    /*
    Given an integer number print all the possible combinations of the keypad. You do not need to return anything just print them.
    */
    
    string output = "";
    printKeypad_rec(num, output);
}

int main(){
    	int num;
	cout<<"Enter the integer for which you want the combinations of keypad: ";
	//take input of integer
    	cin >> num;
	cout<<"All the combinations of the keypad for given input integer are: "<<endl;
    	printKeypad(num);
	//prints all the combinations of the keypad for given input integer
    	return 0;
}



/*
Sample input: 
Enter the integer for which you want the combinations of keypad: 32
Sample output:
All the combinations of the keypad for given input integer are: 
da
ea
fa
db
eb
fb
dc
ec
fc

Time complexity: O(4^n)
Space complexity: O(1)
*/


<|start_filename|>C-Plus-Plus/math/Print_Palindrome_Partitions.cpp<|end_filename|>
/*
This problem is solved using backtracking.
It will print all possible Palindromes in the string
*/
#include <bits/stdc++.h>
using namespace std;

/*To check whether a given string is Palindrome or not*/
int isPalindrome(string& word)
{
    int n = word.length() - 1;
    for (int i = 0; i < n; i++) {
        if (word[i] != word[n]) {
            return false;
        }
        n--;
    }
    return true;
}

// Prototype of PalindromeUtil
void printPalindrome(string str, int n, string result);

// Prints all possible Palindromes of given string
void Palindrome(string str)
{
    // Last argument is word
    printPalindrome(str, str.size(), "");
}

/* Result store the current word with spaces
 between words */
void printPalindrome(string str, int n, string result)
{
    //Process all words one by one
    for (int i = 1; i <= n; i++) {
        // Extract substring from 0 to i in word
        string word = str.substr(0, i);

        /* If dictionary conatins this word, then
         we check for remaining string. Otherwise
         we ignore this word (there is no else for
         this if) and try next */
        if (isPalindrome(word)) {
            // If no more elements are there, print it
            if (i == n) {
                // Add this element to previous word
                result += word;
                cout << result << endl;
                return;
            }
            printPalindrome(str.substr(i, n - i), n - i, result + word + " , ");
        }
    }
}

int main()
{
    // Function call
    string str;
    cin >> str;
    Palindrome(str);

    return 0;
}
/*
Input - abaaba
Output -
a , b , a , a , b , a
a , b , a , aba
a , b , aa , b , a
a , baab , a
aba , a , b , a
aba , aba
abaaba

Time Complexity - O(n^n)
Space Complexity - O(n*n)
*/


<|start_filename|>Java/math/Matrix_Transpose.java<|end_filename|>
/*
* Matrix is the Two-Dimensional Model
* Matrix is the combination of rows and columns,here the rows are n & columns are m
* size = n x m
* Transpose of the matrix is swapping of the rows and columns in the given matrix
* Following code gives the output of the transpose of the matrix
*/

import java.util.Scanner;

public class Matrix_Transpose 
{
	//Function for the transpose
	public static void transpose(int[][] a,int[][] b, int n , int m) 
	{
		int i=0, j=0;
		
	    	for(i=0;i<m;i++)
    		{
	    		for(j=0;j<n;j++)
	    		{
				//Each element of the transpose is assigned
				b[i][j]=a[j][i]; 
	    		}
    		}
	}
	
	public static void main(String[] args) 
	{
		//To read inputs from the users Scanner is used
		Scanner sc = new Scanner(System.in);
		//To read number of rows required in the matrix as per user 
		System.out.println("Enter number of rows:");
		int n = sc.nextInt(); 
		//To read number of columns required in the matrix as per user 
		System.out.println("Enter number of columns:");
		int m = sc.nextInt(); 
		int i=0,j=0;
		//Assigning the memory to the 2-D array according to given matrix size
		int[][] a = new int[n][m];
		int[][] b = new int[m][n]; 
		System.out.println("Enter matrix elements:");
	    	for(i=0;i<n;i++)
		{
			for(j=0;j<m;j++)
			{
			        //Taking user inputs(elements) of the matrix
				a[i][j]=sc.nextInt();
			}

			System.out.println();
		}
	    
	     	System.out.println("Given Matrix elements are:");
	    	for(i=0;i<n;i++)
		{
			for(j=0;j<m;j++)
			{
				System.out.print(a[i][j]+" ");
			}

			System.out.println();
		}
	   	transpose(a, b , n , m);
	        System.out.println("Transpose of Matrix:");
	        for(i=0;i<m;i++)
	   	{
		   	for(j=0;j<n;j++)
		   	{
		   		//Printing the elements of the matrix after transpose calculation
		   		System.out.print(b[i][j]+" ");
		   	}
		   	System.out.println();
	   	}
	}
}
	
/*
Sample Input:

Enter number of rows:
2
Enter number of columns:
3
Enter matrix elements:
10 20 30 40 50 60

Sample Output:

Given Matrix elements are:
10 20 30 
40 50 60 

Transpose of Matrix:
10 40 
20 50 
30 60 

Explanation:
*Inputs, rows are 2 and columns are 3 
* On the next line all the elements of the matrix have been entered
10 20 30 40 50 60
* Then, the code gives output for the transpose.
 
 
 Time Complexity : theta(nm) where, n = number of rows & m = number of columns
 Space Complexity : Transpose matrix requires extra memory space, theta(nm)
 
*/


<|start_filename|>Java/cp/Shortest_Dist.java<|end_filename|>

// Given a list of words and two words word1 and word2, find the shortest distance between those two words from the list.

import java.util.*;
class Shortest_Dist {
    static List < String > arr;
    public static void main(String args[]) {
        int t = 0;

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the list of words " + "\n" + "Words = ");
        arr = new ArrayList <> ();

        arr.add(sc.nextLine());
        while (sc.hasNext()) {
            arr.add(sc.nextLine());
            if (sc.hasNextInt()) {
                t = sc.nextInt();
                break;
            }

        }

        List < String > wd = new ArrayList(arr);
        while (t > 0) {
            System.out.println("Enter the words between which the shortest distance is to be calculated");
            String wd1 = sc.next();
            String wd2 = sc.next();
            System.out.println(" The shortest Distance between " + wd1 + " and " + wd2 + " is : " + shortest_dist(wd, wd1, wd2));
            //List<> wd is being allocation with elements of Collection arr
            wd = new ArrayList(arr);

            t--;
        }

    }
    public static int shortest_dist(List < String > wd, String wd1, String wd2) {
        int dist = -1;
        List < String > wdcopy = new ArrayList(wd);
        //list <> ind1. List <> ind2, for storing indexes of wd1, wd2 in List <> wd
        List < Integer > ind1 = new ArrayList <> ();
        List < Integer > ind2 = new ArrayList <> ();

        while (wd.contains(wd1)) {
            ind1.add(wd.indexOf(wd1));
            //
            wd.add(wd.indexOf(wd1), "0");
            wd.remove(wd.indexOf(wd1));

        }

        while (wdcopy.contains(wd2)) {
            ind2.add(wdcopy.indexOf(wd2));

            wdcopy.add(wdcopy.indexOf(wd2), "0");
            wdcopy.remove(wdcopy.indexOf(wd2));
        }

        for (int i = 0; i < ind1.size(); i++) {
            for (int j = 0; j < ind2.size(); j++) {
                //calculating distance between the indexes
                int d = (int) Math.abs(ind1.get(i) - ind2.get(j));
                if (dist == -1)
                    dist = d;
                else if ((dist != -1) && (d < dist))
                    dist = d;
            }
        }
        return dist;

    }
}

/*
Sample Input And Output :
Enter the list of words
Words =
practice
makes
perfect
coding
makes
2
Enter the words between which the shortest distance is to be calculated
practice
coding
The shortest Distance between practice and coding is : 3
Enter the words between which the shortest distance is to be calculated
coding
makes
The shortest Distance between coding and makes is : 1

Timple Complexity : O(n)
Space Complexity : O(1)
*/


<|start_filename|>Java/cp/Distinct_Element.java<|end_filename|>
import java.util.*;

class Distinct_Element {
    static void FindDistinct(int arr[], int size, int k) {
        // using set for storing the distinct elements.
        Set<Integer> elements = new HashSet<Integer>();
        for (int i = 0; i <= size - k; i++) {
            for (int j = 0; j < k; j++) {
                elements.add(arr[i + j]);
            }
            System.out.println(elements.size());
            elements.clear();
        }

    }

    public static void main(String arg[]) {
        Scanner sc = new Scanner(System.in);
        int len, k;
        System.out.println("Enter the length of array and window size");
        len = sc.nextInt();
        k = sc.nextInt();
        int arr[] = new int[len];
        System.out.println("Enter the array elements");

        for (int i = 0; i < len; i++)
            arr[i] = sc.nextInt();
        System.out.println("Distinct elements are:");
        FindDistinct(arr, len, k);
    }
}

/*
output:
Enter the length of array and window size: 4 2
Enter the array elements: 10 10 20 30
Distinct elements are: 1 2 2
Time complexity : O(K^2)
space complexity : O(size)
*/


<|start_filename|>Java/ds/DetectLoopLL.java<|end_filename|>
import java.util.*;
import java.io.*;
import java.lang.*;
//nodes of Linked list
class Node
{
    int data;
    Node next;
    Node(int x)
    {
        data = x;
        next = null;
    }
}
public class DetectLoopLL
{
    public static void makeLoop(Node head, Node tail, int x){
        if (x == 0) return;
        Node curr = head;
        for(int i=1; i<x; i++)
            curr = curr.next;
        tail.next = curr;
    }
    // } Driver Code Start
    public static void main (String[] args){
        Scanner sc = new Scanner(System.in);
        //size of linked list
        System.out.println("Enter the size of Linked List:");
        int n = sc.nextInt();
         System.out.println("Enter the data of Linked List:");
        //Input for the Linked list
        int num = sc.nextInt();
        Node head = new Node(num);
        Node tail = head;
        //Linked List created
        for(int i=0; i<n-1; i++)
        {
            num = sc.nextInt();
            tail.next = new Node(num);
            tail = tail.next;
        }
        //Position to check loop exists or not
         System.out.println("Enter the Position to check:");
        int pos = sc.nextInt();
        makeLoop(head, tail, pos);
        //Object of Solution class
        Solution x = new Solution();
        //True if loop exits otherwise False
        System.out.println("\tOUTPUT");
        System.out.println("-----------------");
        if( x.detectLoop(head) )
            System.out.println("TRUE");
        else
            System.out.println("FALSE");
    }
}
//  Driver Code Ends
//Solution class to check detect the loop
class Solution {
    public static boolean detectLoop(Node head){
        if(head==null||head.next==null)
            return false;
        Node slow = head;
        Node fast = head;
        while(fast != null && fast.next != null) {
            
            slow = slow.next;
            fast = fast.next.next;
            //there exists a loop if and only if 
            //both fast and slow pointer 
            //point to a same one during traversal
            if(slow==fast)
                return true;
        }
        //otherwise return false
        return false;
    }
}
//Sample Input OUTPUT
/*Enter the size of Linked List:
4
Enter the data of Linked List:
1 8 3 4
Enter the Position to check:
0
    OUTPUT
-----------------
FALSE

Time complexity: O(n).
Auxiliary Space:O(1).
*/


<|start_filename|>C-Plus-Plus/cp/Combination_Sum.cpp<|end_filename|>
/* C++ Code for Combination Sum Problem.
Problem Statement:
Given an array of integers and a target value, the unique combination of values in array should sum up to the target value. 
The same number can be chosen multiple times.

For Example:
Input: array = [4,2,8,6], target = 8
Output: [2,2,2,2], [4,4], [2,6], [8], [2,2,4]

Constraints:
1. The array should have distinct elements.
2. 1 <= target <= 500
3. 1 <= arr.size() <= 50
4. 1 <= arr[i] <= 200
*/
#include<bits/stdc++.h>
using namespace std;

void combinationSum(vector<int> &arr, int target, vector<vector<int>> &ans, vector<int> &combn, int beg)
{
    if(!target) {
        ans.push_back(combn);
        return;
    } 
    for(int i=beg; i!=arr.size() && target >= arr[i]; ++i) {
        combn.push_back(arr[i]);
        combinationSum(arr, target-arr[i], ans, combn, i);
        combn.pop_back();
    }
}
int main() {
    int n; 
    cout << "\nEnter Array Size: "; cin >> n;

    vector<int> arr (n);
    cout << "\nEnter Array Elements: ";
    for(int i=0; i<n; ++i)
        cin >> arr[i];

    int target;
    cout << "\nEnter Target Sum: "; cin >> target;
    //Sorting the array
    sort(arr.begin(), arr.end());
    vector<vector<int> > ans;
    vector<int> combination;
    combinationSum(arr, target, ans, combination, 0);
    for(int i=0; i<ans.size(); ++i) {
        if(ans[i].size() > 0) {
            cout << "\n[";
            for(int j=0; j<ans[i].size(); ++j) 
                if(j == ans[i].size() - 1) cout << ans[i][j]; 
                else cout << ans[i][j] << ", ";
            cout << "]";
        }
    }
    return 0;
}
/* Sample Input
Enter Array Size: 4
Enter Array Elements: 1 2 3 4
Enter Target Sum: 10

Output:
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 2]
[1, 1, 1, 1, 1, 1, 1, 3]
[1, 1, 1, 1, 1, 1, 2, 2]
[1, 1, 1, 1, 1, 1, 4]
[1, 1, 1, 1, 1, 2, 3]
[1, 1, 1, 1, 2, 2, 2]
[1, 1, 1, 1, 2, 4]
[1, 1, 1, 1, 3, 3]
[1, 1, 1, 2, 2, 3]
[1, 1, 1, 3, 4]
[1, 1, 2, 2, 2, 2]
[1, 1, 2, 2, 4]
[1, 1, 2, 3, 3]
[1, 2, 2, 2, 3]
[1, 2, 3, 4]
[1, 3, 3, 3]
[2, 2, 2, 2, 2]
[2, 2, 2, 4]
[2, 2, 3, 3]
[2, 4, 4]
[3, 3, 4]
*/


<|start_filename|>C-Plus-Plus/dp/JobSchedulingWithMaxProfit.cpp<|end_filename|>
/*
Query : Job Scheduling with Maximum Profit (using Recursion)

Task:
We are given X number of Jobs and their starting time, end time, and profit value of accomplishing them.
We have to find the maximum profit of any subset of them such that there is no overlapping 
between the time durations of the jobs.

Input is three arrays: BeginTime , EndTime , Profit
Output is an integer of Maximum profit of subset of Jobs

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

/*Defining class for jobs 
The attributes of jobs as the 
members of the class namely:
 	a)begin: starting time of the job
 	a)end : ending time of the job
 	c)profit: profit you gain by completing that job
*/
class Jobs
{
	public:
		int begin, end, profit; 
	
};

/*Sorting the activities according to their 
ending times to get the correct ordering of 
the jobs
*/
static bool sort_Order(Jobs job1, Jobs job2)
{
	return (job1.end < job2.end);
}

/*
Recursive solution for optimizing the maximum 
profits for jobs without overlapping the job duration
 Here job[]: Array of jobs
	  job_curr : Current job
*/

int Optimal_profit_Rec(Jobs job[], int job_curr)
{
	if(job_curr < 0)
		return 0;
	if (job_curr == 1) 
		return job[job_curr-1].profit;

	int include,exclude;
	
	/*a) to include the current job:
	 We need to find the last job(nearest_job) that
	 doesn't overalp with current job(job_curr).
	 we can find that using linear search.
	  Then we will recursively find the result for all jobs till that job(nearest_job) and
		add profit of current job(job_curr) to the output.
	*/
	int nearest_job=-1;
	int job_idx;       // to iterate the jobs
	job_idx = job_curr - 1;
	
	while (job_idx>=0)
	{
		if (job[job_idx].end <= job[job_curr-1].begin){
			nearest_job=job_idx; // This is the last non-overlapping job
			break;
		}
		job_idx--;
	}
	
	
	//Including the job , hence adding the profit to the result
	include= job[job_curr-1].profit;
	
	if(nearest_job != -1)
	include = include + Optimal_profit_Rec(job, nearest_job+1);
	
	//b) exclude the job
	exclude = Optimal_profit_Rec(job, job_curr-1);

	// Return maximum profit from two available options
	return max(include , exclude );
}

/*main body*/
int main()
{
	
	int N;
	cout << "Enter the number of Jobs:";
	cin >> N;

	Jobs job[N];

	cout << "Enter the credentials of Jobs in the order BeginTime , EndTime , Profit:\n";

	for(int job_ind=0 ; job_ind<N ; job_ind++)
	{
		cout << "For Job #" << (job_ind+1) << endl;

		cout<<"Enter The begin Time:";
		cin >> job[job_ind].begin;

		cout<<"Enter The end Time:";
		cin >> job[job_ind].end;

		cout<<"Enter The Profit value:";
		cin >> job[job_ind].profit;


	}

	// Sort the jobs according to their ending time
	sort(job, job+N, sort_Order);
	
	cout << "The maximum profit for the optimal job selection is:" << Optimal_profit_Rec(job, N);
	return 0;
}

/*
	COMPLEXITY:
	Since it is a recursive solution
	 Time Complexity -> O(N*2^N)  
	 Space Complexity -> occupies space in call stack	

Sample Test Cases :

Example #1:
Input: startTime = [1,1], endTime = [5,6], profit = [12,17]
Output: 17
Explanation: 
We can choose the job with maximum profit i.e. second job .
Thus the output is 17

Example #2:
Input: startTime = [2,7], endTime = [7,12], profit = [2,8]
Output: 10
Explanation: 
We can complete both the jobs with maximum profit= 
				profit by first job + profit by second job
as their time ranges does not clash with each other
Thus the output is 10

*/


<|start_filename|>C/cp/Maximum_Container_with_water.c<|end_filename|>
// C code for maximum water Container

#include<stdio.h>
int maxArea(int[], int);

// function to find the maximum Area
int maxArea(int A[], int length) {
  int start = 0;
  int end = length - 1;
  int area = 0;
  int min;
  while (start < end) {
    // Calculating the max area 
    if (A[start] < A[end]) {
      min = A[start];
    } else {
      min = A[end];
    }
    int t = end - start;
    if (area < (min * t)) {
      area = min * t;
    }

    if (A[start] < A[end])
      start += 1;

    else
      end -= 1;
  }
  return area;

}
//driver code to check above function
int main() {
  int size1, size2; 
  printf("Input-->");
  printf("Enter the a size : \n");
  scanf("%d", & size1);
  printf("Enter the b size :\n");
  scanf("%d", & size2);
  int a[size1],b[size2];
  printf("Enter the elements of a container :\n");
  for (int i = 0; i < size1; i++) {
    scanf("%d", & a[i]);
  }
  printf("Enter the elements of b container\n");
  for (int i = 0; i < size2; i++) {
    scanf("%d", & b[i]);
  }
  int A = maxArea(a, size1);
  int B = maxArea(b, size2);
  printf("Output-->\n");
  if (A > B) {
    printf("Container a contain more water i.e %d\n", A);
  } else {
    printf("Container b contain more water i.e %d\n", B);
  }
  return 0;
}

/*
 Input-->
 Enter the a size : 4
 Enter the b size : 5
 Enter the elements of a container :
 1 5 4 3
 Enter the elements of b container :
 3 2 1 4 5
 Output-->
 Container b contain more water i.e 12

 Time Compelxity: O(n).
 As only one traversal of the array is required, so time complexity is O(n) where n is size of array.
 Space Complexity: O(1).
 No extra space is required, so space complexity is constant
*/


<|start_filename|>C/ds/StackImplementationWithArray.c<|end_filename|>
/*
A stack is an Abstract Data Type (ADT), commonly used in most programming languages.This feature makes it LIFO data structure. LIFO stands for Last-in-first-out. Here, the element which is placed (inserted or added) last, is accessed first.
The Basic operation in Stack are:
1.push() − Pushing (storing) an element on the stack.
2.pop() − Removing (accessing) an element from the stack.
3.peek() − get the top data element of the stack, without removing it.
4.display() - used to display the elements
*/

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define SIZE 10

void push(int);
void pop();
void peek();
void display();

int stack[SIZE], top = -1;

void main()
{
	int s;
        printf("Enter the array size: ");
        scanf("%d", &s);
        int a[s];
	int value, choice;
	while (1)
	{
		printf("\n\n*****MENU *****\n");
		printf("1. Push\n2. Pop\n3. Display\n4. Peek\n5. Exit");
		printf("\nEnter your choice: ");
		scanf("%d", &choice);
		switch (choice)
		{
			case 1:
				printf("Enter the value to be insert: ");
				scanf("%d", &value);
				push(value);
				break;
			case 2:
				pop();
				break;
			case 3:
				display();
				break;
			case 4:
				peek();
				break;
			case 5:
				exit(0);
			default:
				printf("\nWrong selection!!! Try again!!!");
		}
	}
}
void push(int value)
{
	if (top == SIZE - 1)
		printf("\nStack is Full!!! Insertion is not possible!!!");
	else
	{
		top++;
		stack[top] = value;
		printf("\nInsertion success!!!");
	}
}
void pop()
{
	if (top == -1)
		printf("\nStack is Empty!!! Deletion is not possible!!!");
	else
	{
		printf("\nDeleted Element : %d", stack[top]);
		top--;
	}
}
void display()
{
	if (top == -1)
		printf("\nStack is Empty!!!");
	else
	{
		int i;
		printf("\nStack elements are:\n");
		for (i = top; i >= 0; i--)
			printf("%d\n", stack[i]);
	}
}
void peek()
{
	if (top == -1)
		printf("\nstack is empty!!!");
	else
	{
		printf("\nTop element of stack is %d", stack[top]);
	}
}

/*
Enter the array size: 10
***** MENU *****
1.	Push
2.	Pop
3.	Display
4.	peek
5.	exit
Enter your choice: 1
Enter the value to be insert: 45 
Insertion Success!!!

***** MENU *****
1.	Push
2.	Pop
3.	Display
4.	peek
5.	exit
Enter your choice: 1
Enter the value to be insert: 20 
Insertion Success!!!

***** MENU *****
1.	Push
2.	Pop
3.	Display
4.	peek
5.	exit
Enter your choice: 3 
Stack elements are: 45 20

***** MENU *****
1.	Push
2.	Pop
3.	Display
4.	peek
5.	exit
Enter your choice: 4
Top element of Stack is: 20

***** MENU *****
1.	Push
2.	Pop
3.	Display
4.	peek
5.	exit
Enter your choice: 2 
Deleted Element : 20

***** MENU *****
1.	Push
2.	Pop
3.	Display
4.	peek
5.	exit
Enter your choice: 3 
Stack elements are: 45

Time complexity : O(1)
Space Complexity: O(n)
*/


<|start_filename|>C-Plus-Plus/graphs/right_view_of_tree.cpp<|end_filename|>
/*
  This program will print Right view of tree by 
  using the concept of level order traversal  
  with some modification
    
*/
#include <bits/stdc++.h>

using namespace std;

struct node {
  node(int x): data(x), left_child(NULL),
    right_child(NULL) {}
  int data;
  node * left_child;
  node * right_child;
};

class bin_tree {
  node * root;
  int n = 0;
  public:
    // constructor of tree
    bin_tree() {
      root = NULL;
      n = 0;
    }
  void insert_data(int x) {
    //incrase number of element
    n++;
    //if tree is empty
    if (!root) {
      node * tnode = new node(x);
      root = tnode;
    }
    //if tree if not empty
    else {
      node * temp = root;
      while (1) {
        //if data to be inserted is less then the
        //data of current node
        if (x < temp -> data) {
          //if left child of current node is not 
          //present we simple add new node with 
          //the data to be inserted
          if (!temp -> left_child) {
            node * tnode = new node(x);
            temp -> left_child = tnode;
            break;
          }
          //else we change the current node 
          //pointer with pointer of left child 
          //node pointer
          else
            temp = temp -> left_child;
        }
        //if data to be inserted is grater then 
        //or equal to the data of current node
        else {
          //if right child of current node is not
          //present we simple add new node with 
          //the data to be inserted
          if (!temp -> right_child) {
            node * tnode = new node(x);
            temp -> right_child = tnode;
            break;
          }
          //else we change the current node 
          //pointer with pointer of left child 
          //node pointer
          else
            temp = temp -> right_child;
        }
      }
    }
  }
  int size() {
    return n;
  }

  void right_view_of_tree();
};

void bin_tree::right_view_of_tree() {
  int enterptr = 0, exitptr = 0;
  node * a[this -> size()];

  if (this -> root)
    a[enterptr++] = this -> root;

  while (enterptr != exitptr) {
    // number of nodes at current level 
    int cn = enterptr - exitptr;

    // Print the righ  most element at the level 
    cout << a[exitptr] -> data << " ";

    // Traverse all nodes of current level  
    for (int i = 1; i <= cn; i++) {
      // Add Rightchild node
      if (a[exitptr] -> right_child)
        a[enterptr++] = a[exitptr] -> right_child;

      // Add leftchild node
      if (a[exitptr] -> left_child)
        a[enterptr++] = a[exitptr] -> left_child;
      // Move to next node
      exitptr++;
    }
  }
}

int main() {
  bin_tree t;
  int n;
  cout << "Enter number of elements in tree: ";
  cin >> n;
  cout << "Enter elements to insert in  tree: ";
  while (n--) {
    int k;
    cin >> k;
    t.insert_data(k);
  }
  cout << "\nRight View of tree:";
  t.right_view_of_tree();
  return 0;
}

/* 
   
    Sample case 1
    Enter number of elements in tree: 8
    Enter elements to insert in  tree: 50 40 60 
    55 30 56 70 45
    Right View of tree : 50 60 70 56
         50                         
      /     \
     /       \
    40        60                    
   /   \     /   \
  /     \   /     \
30    45  55      70                
            \
             \
             56                    
             
.......................................................................
 Sample case 2
    Enter number of elements in tree: 10
    Enter elements to insert in  tree: 50 40 30 
    45 60 55 54 70 42 43
    Right View of tree : 50 60 70 54 43 
            50     
       /         \
      /           \
     /             \
    40             60                    
   /   \         /     \
  /     \       /       \
30    45       55       70                
     /        /        
    /        /          
   42        54        
     \
      \
       43
Time Complexity: O(n) 
Space Complexity: O(n)
        
*/


<|start_filename|>Go/math/Palindrome/palindrome.go<|end_filename|>
package main

import (
	"fmt"
	"bufio"
	"os"
)

// This function checks if string is a palindrome
func palindrome_check(str string) int {
	// Iterate till the middle of the string
	for i:=0; i < len(str) / 2; i++ {
		/* Check if character at beginning index of the
		string matches the end of the string at same index*/
		if(string(str[i]) != string(str[len(str) - 1 - i])) {
			// If it does not then return -1
			return -1
		}
	}
	// If everything matches then return 1
	return 1
}

func main() {

	// Take string as input from the user
	fmt.Print("Enter a string to check if it is a palindrome: ")

	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	line := scanner.Text()

	// Calling the function to check
	var result int = palindrome_check(line)

	/* If the string is a palindrome.
	Else the string is not a palindrome*/
	if(result == 1) {
		fmt.Print("\nThe entered string is a palindrome.\n")
	} else {
		fmt.Print("\nThe entered string is not a palindrome.\n")
	}
}

/* Sample I/O:

Enter a string to check if it is a palindrome: check kcehc

The entered string is a palindrome.

Time Complexity - O(n)
Space Complexity - O(1)
*/



<|start_filename|>Java/search/Interpolation_search.java<|end_filename|>
import java.util.Scanner;
// JAVA Implementation of recursive Interpolation Search

public class InterpolationSearch {
  int findEleByInterSearching(int arr[], int low, int high, int key) {
    if (high >= low && key >= arr[low] && key <= arr[high]) {
      //if value of high and low ae same
      if (low == high) {
        // value of key compared with element at index low
        if (arr[low] == key) return low;
        else return - 1;
      }
      //determining the position of the key element in an array
      int pos = low + (((high - low) / (arr[high] - arr[low])) * (key - arr[low]));
      // value of key compared with element at index low
      if (arr[pos] == key) return pos;
      /* If element key  is smaller than pos value
                    then it can only be present in left subarray */
      if (arr[pos] > key) return findEleByInterSearching(arr, low, pos - 1, key);
      /* Else the element key  can only be present 
                   in right subarray */
      if (arr[pos] < key) return findEleByInterSearching(arr, pos + 1, high, key);
    }
    return - 1;
  }
  // Driver method to test above 
  public static void main(String args[]) {
    InterpolationSearch s = new InterpolationSearch();
    Scanner sc = new Scanner(System. in );
    System.out.println("Input :");
    System.out.println("Enter the size of array: ");
    int size = sc.nextInt();
    sc.nextLine();
    int sortedarr[] = new int[size];
    System.out.println("Enter the elements of array:");
    for (int index = 0; index < size; index++) {
      sortedarr[index] = sc.nextInt();
    }
    System.out.println("Enter the element to be searched:");
    int searchKey = sc.nextInt();
    int position = s.findEleByInterSearching(sortedarr, 0, size - 1, searchKey);
    System.out.println("Output :");
    if (position == -1) System.out.println("Element not found");
    else System.out.println("Element found at index " + position);
  }
}
/*
   Input :
   Enter the size of array:
   4
   Enter the elements of an array:
   1 3 5 7
   Enter the element to be search:
   5
   Output :
   Element found at index 2
 */
/* 
  Time Complexity: If elements are uniformly distributed, then O (log log n)). In worst case it can take upto O(n).
  Auxiliary Space: O(1)
*/

<|start_filename|>C/dp/EditDistanceDP.c<|end_filename|>
/*
A Dynamic Programming based C program to find minimum 
number operations to convert string1 to string2
*/

#include <stdio.h>
#include <string.h>
	// Utility function to find the minimum of three numbers 
int mincount(int count1, int count2, int count3)
{
	if (count1 <= count2 && count1 <= count3)
		return count1;
	else if (count2 <= count1 && count2 <= count3)
		return count2;
	else
		return count3;
}
int editDistDP(char str1[], char str2[], int str1Len, int str2Len)
{
	// Create a table to store results of subproblems 
	int dp[str1Len + 1][str2Len + 1];
	// Fill d[][] in bottom up manner 
	for (int indexstr1 = 0; indexstr1 <= str1Len; indexstr1++)
	{
		for (int indexstr2 = 0; indexstr2 <= str2Len; indexstr2++)
		{ /*If first string is empty, only option is to 
			   insert all characters of second string */
			if (indexstr1 == 0)
				// Min. operations = indexstr2
				dp[indexstr1][indexstr2] = indexstr2;
			/* If second string is empty, only option is to 
			    remove all characters of second string */
			else if (indexstr2 == 0)
				dp[indexstr1][indexstr2] = indexstr1;	// Min. operations = loop
			/*If last characters are same, ignore last char 
			   and recur for remaining string */
			else if (str1[indexstr1 - 1] == str2[indexstr2 - 1])
				dp[indexstr1][indexstr2] = dp[indexstr1 - 1][indexstr2 - 1];
			/*If the last character is different, consider all 
			  possibilities and find the minimum */
			else
				dp[indexstr1][indexstr2] = 1 + mincount(dp[indexstr1][indexstr2 - 1],	// Insert 
					dp[indexstr1 - 1][indexstr2],	// Remove 
					dp[indexstr1 - 1][indexstr2 - 1]);	// Replace 
		}
	}
	return dp[str1Len][str2Len];
}
// Driver program 
int main()
{
	char string1[20];
	char string2[20];
	int n;
	printf("\n Input: ");
	printf("\n Enter the first string:");
	gets(string1);
	printf("\n Enter the second string:");
	gets(string2);
	n = editDistDP(string1, string2, strlen(string1), strlen(string2));
	printf("\n Output:");
	printf(" %d\n ", n);
	return 0;
}
// The main() end here
/*
Input:
Enter the first string: "sunday"
Enter the second string: "saturday"
Output: 3 
*/
/*
Time Complexity : O(mn)
Space Complexity : O(mn)
*/



<|start_filename|>Julia/math/sum_of_digits.jl<|end_filename|>
# Julia program to Find the Sum of Digits of a Number 

# Extracting Each digits
function sum_of_digits(num)
    sum = 0
    while(num != 0)
        sum = sum + (num % 10)
        num = num ÷ 10
    end
    return sum
end

print("Enter the number: ")
num = readline()
num = parse(Int, num)
sum = sum_of_digits(abs(num))
println("The sum of digits of the given number is $sum.")

"""
Time Complexity: O(log(num)), where 'num' is the length of the given number
Space Complexity: O(1)

SAMPLE INPUT AND OUTPUT

SAMPLE 1
Enter the number: -12
The sum of digits of the given number is 3.

SAMPLE 2
Enter the number: 43258
The sum of digits of the given number is 22.

"""


<|start_filename|>C-Plus-Plus/cp/integertobinarystring.cpp<|end_filename|>
#include<bits/stdc++.h>

using namespace std;

typedef long long int ll;

string decimalToBinary(ll n) 
{      
    string s = bitset<64> (n).to_string();  // stl to convert integer tobinary and convert into string 
      
    //Finding the first occurance of "1" 
    //to strip off the leading zeroes. 
    const auto loc1 = s.find('1'); 
      
    if(loc1 != string::npos) 
        return s.substr(loc1); 
      
    return "0"; 
} 


int main() {
    
    int n;
    cout<<"Enter a number: ";
    cin>>n;
    cout<<"binary string of given number is :"<< decimalToBinary(n);

    return 0;
}


<|start_filename|>C-Plus-Plus/cryptography/Modified_Caeser_Cipher.cpp<|end_filename|>
#include<bits/stdc++.h>
using namespace std;

/* Encrypts the plain text message into a cipher text 
by simply replacing each letter of a given text by 
some places down the alphabet. */
string encode(string plain, int shift) {
	
	string encrypt = "";
	int length = plain.length();
	for(int i = 0;i < length; ++i) {
		if(plain[i] <= 91) {
			//uppercase letter
			encrypt += char((plain[i] - 65 + shift)%26 + 65);
		} else if(plain[i] > 97) {
			//lowercase letter
			encrypt += char((plain[i] - 97 + shift)%26 + 97);
		}
	}

	return encrypt;
}

int main() {
	
	string plain,encrypt;
	int shift;
	cout<<"Enter the plain text: ";
	cin>>plain;
	
	cout<<"Enter the integer key to shift: ";
	cin>>shift;
	
	encrypt = encode(plain,shift);
	cout<<"Cipher Text: "<<encrypt<<endl;
	
}

/*
Example:
Text : TESSERACTCODING
Shift: 4
Cipher: XIWWIVEGXGSHMRK

Text : NEOALGO
Shift: 2
Cipher: PGQCNIQ

Time Complexity: O(n)
Space Complexity: O(n)
*/

<|start_filename|>Go/ds/stack/stack_using_queue/stack_using_queue.go<|end_filename|>
/*
	==============================================================
			Implementing QUEUE using STACK data structure
	==============================================================
	stack can be implemented using two queues

	 1 -> By making push() operation costly :
		This method insert new entered element in the pushQueue,
		so that pop() operation just dequeue from pushQueue. To put the element at top of pushQueue, popQueue is used.

	  2 -> By making pop() operation costly :
		In this method, in push() operation, the new element is entered at the top of pushQueue.
		In pop() operation, all the elements of pushQueue are dequeued and enqueued to popQueue and top of popQueue is returned.
		finally all the elements of popQueue dequeued and enqueued to pushQueue again

	  This program uses second way

*/

package main

import (
	"fmt"
)

// CAPACITY of every Stack and Queue in this program
const CAPACITY int = 10

// QUEUE user-definded data type to hold the variables for our queue data structure
type QUEUE struct {
	front int
	back  int
	array [CAPACITY]int
}

func (queue *QUEUE) initQueue() {
	queue.front = -1
	queue.back = -1
}

// isEmpty(): checks if the both front and back are less than 0 it means Queue is empty
func (queue *QUEUE) isEmpty() bool {
	if queue.front < 0 && queue.back < 0 {
		return true
	}
	return false
}

// iFull(): checks if the back of Queue is greater or equals to last index of array,
// if so it will return true otherwise false
func (queue *QUEUE) isFull() bool {
	if queue.back >= CAPACITY-1 {
		return true
	}
	return false
}

// enQueue(): it first checks if there is space available for new element,
// if available it will just insert the value to end of the Queue
func (queue *QUEUE) enQueue(value int) {
	if queue.isFull() {
		fmt.Println("Queue is full")
	} else {
		if queue.front < 0 {
			queue.front++
		}
		queue.back++
		queue.array[queue.back] = value
	}
}

// pop(): this will delete the value from the front of the Queue
func (queue *QUEUE) deQueue() int {
	var data int
	if queue.isEmpty() {
		fmt.Println("Queue is empty")
	} else {
		data = queue.array[queue.front]
		queue.front++
		if queue.front > queue.back {
			queue.initQueue()
		}
	}
	return data
}

// printQueue(): if queue is not empty then it will simply print the element
func (queue *QUEUE) printQueue() {
	for i := queue.front; i <= queue.back; i++ {
		fmt.Printf("%d ", queue.array[i])
	}
}

// STACK user-defined data type will use for implementing stack using queue
type STACK struct {
	top       int
	pushQueue QUEUE
	popQueue  QUEUE
}

func (stack *STACK) initStack() {
	stack.top = -1
	stack.pushQueue.initQueue()
	stack.popQueue.initQueue()
}

// length(): if the stack is empty it will show 0 element,
// otherwise it will show the number of current element presents in stack
func (stack *STACK) length() {
	if stack.isEmpty() {
		fmt.Println("The current length of Stack is 0")
	} else {
		fmt.Printf("The current length of Stack is %d\n", stack.top+1)
	}
}

// isEmpty(): this checks if stack is empty or not
func (stack *STACK) isEmpty() bool {
	if stack.top < 0 {
		return true
	}
	return false
}

// isFull(): this checks if stack is full or not
func (stack *STACK) isFull() bool {
	if stack.top >= CAPACITY-1 {
		return true
	}
	return false
}

// push(): if there is space for new element it will simply insert the element to pushQueue
func (stack *STACK) push() {
	var data int
	if stack.isFull() {
		fmt.Println("Stack is full")
	} else {
		stack.top++
		fmt.Println("enter the value: ")
		fmt.Scanf("%d", &data)
		stack.pushQueue.enQueue(data)
		fmt.Println("value pushed succesfully at the top of the Stack")
	}
}

// pop(): if stack is not empty then first it will remove all the element from pushQueue
// and insert them in popQueue and return the poped element by removing popQueue's first element
// and finally it will again insert all the element of popQueue to pushQueue by removing them
func (stack *STACK) pop() {
	var data int
	if stack.isEmpty() {
		fmt.Println("Stack is empty")
	} else {
		for i := 0; i <= stack.top; i++ {
			stack.popQueue.enQueue(stack.pushQueue.deQueue())
		}
		data = stack.popQueue.deQueue()
		stack.top--
		for i := 0; i <= stack.top; i++ {
			stack.pushQueue.enQueue(stack.popQueue.deQueue())
		}
		fmt.Printf("Succesfully poped element %d from the top of the Stack\n", data)
	}
}

// printStack(): if stack is not empty it will print the elements of pushQueue
func (stack *STACK) printStack() {
	if stack.isEmpty() {
		fmt.Println("Stack is empty")
	} else {
		fmt.Println("Current state of Stack is")
		stack.pushQueue.printQueue()
		fmt.Print("\n")
	}
}

func main() {
	var stack STACK
	stack.initStack() // initalizing stack for first time
	var choice int
	var isContinue bool = true
	fmt.Println("Please enter option")
	for isContinue {
		fmt.Println("1 -> push element\n2 -> pop element\n3 -> print Stack\n4 -> print length\n5 -> exit program")
		fmt.Scanf("%d", &choice)

		switch choice {
		case 1:
			stack.push()
			break
		case 2:
			stack.pop()
			break
		case 3:
			stack.printStack()
			break
		case 4:
			stack.length()
			break
		case 5:
			isContinue = false
			break
		default:
			fmt.Println("Please enter correct option")
			break
		}
	}
}

/*
	input/output sample :

	Please enter option
	1 -> push element
	2 -> pop element
	3 -> print Stack
	4 -> print length
	5 -> exit program
	1
	enter the value:
	4
	value pushed succesfully at the top of the Stack
	1 -> push element
	2 -> pop element
	3 -> print Stack
	4 -> print length
	5 -> exit program
	1
	enter the value:
	5
	value pushed succesfully at the top of the Stack
	1 -> push element
	2 -> pop element
	3 -> print Stack
	4 -> print length
	5 -> exit program
	1
	enter the value:
	6
	value pushed succesfully at the top of the Stack
	1 -> push element
	2 -> pop element
	3 -> print Stack
	4 -> print length
	5 -> exit program
	3
	Current state of Stack is
	4 5 6
	1 -> push element
	2 -> pop element
	3 -> print Stack
	4 -> print length
	5 -> exit program
	4
	The current length of Stack is 3
	1 -> push element
	2 -> pop element
	3 -> print Stack
	4 -> print length
	5 -> exit program
	2
	Succesfully poped element 4 from the top of the Stack
	1 -> push element
	2 -> pop element
	3 -> print Stack
	4 -> print length
	5 -> exit program
	2
	Succesfully poped element 5 from the top of the Stack
	1 -> push element
	2 -> pop element
	3 -> print Stack
	4 -> print length
	5 -> exit program
	3
	Current state of Stack is
	6
	1 -> push element
	2 -> pop element
	3 -> print Stack
	4 -> print length
	5 -> exit program
	4
	The current length of Stack is 1

*/


<|start_filename|>C/cp/Stock_Span.c<|end_filename|>
// Stock Span Problem
// Given a list of prices of a stock for N number of days, find stock span for each day.
// link to problem:  https://practice.geeksforgeeks.org/problems/stock-span-problem/

#include<stdio.h>
#define MAXSIZE 50

int stack[MAXSIZE];
int top = -1;

int isempty() {
	if (top == -1)
		return 1;
	else
		return 0;
}

int isfull() {
	if (top == MAXSIZE)
		return 1;
	else
		return 0;
}

int peek() {
	return stack[top];
}

int pop() {
	int data;
	if (!isempty()) {
		data = stack[top];
		top = top - 1;
		return data;
	} else {
		printf("Stack is empty.\n");
	}
}

void push(int data) {
	if (!isfull()) {
		top = top + 1;
		stack[top] = data;
	} else {
		printf("Stack is full.\n");
	}
}

void calcSpan(int arr[], int days) {
	int i, span[days];

	if (days == 0)
		return;
	// initialization
	span[0] = 1;
	push(0);
	for (i = 1; i < days; i++) {
		// checking if previous stock prize is less
		while (!isempty() && arr[i] > arr[peek()])
			pop();
		// updating the span value
		if (isempty()) {
			span[i] = i + 1;
		} else {
			span[i] = i - peek();
		}
		push(i);
	}
	// printing the span
	for (i = 0; i < days; i++)
		printf("%d  ", span[i]);

	printf("\n");
}

int main() {
	int n;
	printf("Enter the no. of days: \n");
	scanf("%d", &n);
	printf("Enter the stock prizes: \n");
	int arr[n];
	for (int i = 0; i < n; i++)
		scanf("%d", &arr[i]);

	calcSpan(arr, n);
	return 0;
}

/*
 Input:
 Enter the no. of days:
 5
 Enter the stock prizes:
 30 20 40 50 60
 Output:
 1  1  3  4  5

 Time complexity: O(n)
 Space complexity: O(n)
 */


<|start_filename|>C-Plus-Plus/dp/shortest_uncommon_subseq.cpp<|end_filename|>
/*
A string of length n has 2^n different possible subsequences.
A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous.
*/

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

#define MAX 1005

// Returns length of shortest common subsequence
int shortestSeq(char *S, char *T) {
	int m = strlen(S), n = strlen(T);

	// declaring 2D array of m + 1 rows and
	// n + 1 columns dynamically
	int dp[m + 1][n + 1];

	// T string is empty
	for (int i = 0; i <= m; i++)
		dp[i][0] = 1;

	// S string is empty
	for (int i = 0; i <= n; i++)
		dp[0][i] = MAX;

	for (int i = 1; i <= m; i++) {
		for (int j = 1; j <= n; j++) {
			char ch = S[i - 1];
			int k;
			for (k = j - 1; k >= 0; k--)
				if (T[k] == ch)
					break;

			// char not present in T
			if (k == -1)
				dp[i][j] = 1;
			else
				dp[i][j] = min(dp[i - 1][j], dp[i - 1][k] + 1);
		}
	}

	int ans = dp[m][n];
	if (ans >= MAX)
		ans = -1;

	return ans;
}

int main() {
	char S[100];
	char T[100];
	cout << "Enter first string\n";
	cin >> S;
	cout << "Enter second string\n";
	cin >> T;
	cout << "Length of shortest subsequence is : " << shortestSeq(S, T) << endl;
}

/*
Example:

Input:
S = “babab”
T = “babba”
Output:
Length of shortest subsequence is : 3
The subsequence “aab” of length 3 is present in S but not in T.

Time complexity: O(mn^2)
Space Complexity: O(mn)
*/


<|start_filename|>C-Plus-Plus/ds/ThreadedBinaryTree.cpp<|end_filename|>
/*
DESCRIPTION -
Threaded binary tree are used to make faster inorder traversal without using stack or recursion.
It stores the inorder successor, if the right node is empty.
And stores the inorder predecessor if left node is empty.
- There are functions to add, delete and search for an element.
- Also the inorder for the tree. 
*/
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <math.h>
#define COUNT 10
using namespace std;

typedef struct Node
{
	int data;
	// 1 for address of child, 0 address of parent
	int leftflag, rightflag;
	struct Node *left, *right;

}

Node;
void add(Node **p, int v)
{
	Node *newnode = (Node*) malloc(sizeof(Node));
	newnode->data = v;
	// by default both the flags will be 0
	newnode->leftflag = 0;
	newnode->rightflag = 0;
	// if its the root node it will have no inorder predecessor or successor
	if (*p == NULL)
	{
		newnode->left = NULL;
		newnode->right = NULL;
		*p = newnode;
	}
	else
	{
		Node *temp = *p;
		// This loop will find the inorder predecessor or successor
		while (1)
		{
			if (temp->data > v && temp->leftflag == 1)
				temp = temp->left;
			else if (temp->data < v && temp->rightflag == 1)
				temp = temp->right;
			else
				break;
		}

		// temp is now the inorder predecessor or successor
		// This will update the new node that is created with the links to its inorder predecessor or successor
		if (temp->data < v)
		{
			newnode->right = temp->right;
			// points at the child
			temp->right = newnode;
			temp->rightflag = 1;
			// points at the parent
			newnode->left = temp;
		}
		else
		{
			newnode->left = temp->left;
			// points at the child
			temp->left = newnode;
			temp->leftflag = 1;
			// points at the parent
			newnode->right = temp;
		}
	}
}

void inorder(Node *p)
{
	while (1)
	{
		// goes to left most
		while (p->leftflag)
			p = p->left;
		cout << p->data << " ";
		// right flag must be 0 so that it goes to the parent and not the child
		while (!p->rightflag)
		{
			p = p->right;
			if (p == NULL)
				return;
			cout << p->data << " ";
		}

		p = p->right;
	}
}

// returns 1 if present else 0
int TBTsearch(Node *p, int value)
{
	while (1)
	{
		// left flag must be 1 to make sure it goes to the child and not the parent
		if (p->data > value && p->leftflag)
		{
			p = p->left;
		}

		// right flag must be 1 to make sure it goes to the child and not the parent
		else if (p->data < value && p->rightflag)
		{
			p = p->right;
		}
		else
		{
			// the element has been found or reached the end and value is not found so does not exist in the tree 
			break;
		}
	}

	if (p->data == value)
	{
		return 1;
	}

	return 0;
}

int main()
{
	/*
	This is how the tree will look like
	- means the flag values for that node is 1

	                    -50-
	                   /   \
	                 40    -70-
	                      /    \
	                     60    80

	*/
	Node *root = NULL;
	int option, element;
	cout << "MENU\n\nEnter 1. Insert an element\nEnter 2. Inorder of the tree\nEnter 3. Search for an element\nEnter 4. Exit\n";

	while (option != 4)
	{
		cout << "\nEnter your option: ";
		cin >> option;

		if (option == 1)
		{
			cout << "Enter the element you want to insert: ";
			cin >> element;
			add(&root, element);
			cout << element << " has been inserted into the tree.\n";
		}
		else if (option == 2)
		{
			inorder(root);
			cout << endl;
		}
		else if (option == 3)
		{
			cout << "Enter the element you want to search: ";
			cin >> element;
			cout << TBTsearch(root, element) << endl;
		}
		else if (option != 4)
		{
			cout << "Enter a valid number!\n";
		}
	}

	cout << "Exiting.... ";
	return 0;
}

// Contributed by <NAME>


<|start_filename|>C-Plus-Plus/dp/max_sum_rectangle.cpp<|end_filename|>
#include <bits/stdc++.h>
using namespace std;

int kadane(int* arr, int n){
    int curr_sum = 0, best_sum = 0;
    int flag = -1;
    for(int i = 0; i < n; i++){
        curr_sum += arr[i];
        if(best_sum < curr_sum){
            best_sum = curr_sum;
            flag = 0;
        }
        if(curr_sum < 0)
            curr_sum = 0;
    }
    if(flag != -1)
    	return best_sum;
    best_sum = INT_MIN;
    for(int i = 0; i < n; i++){
        best_sum = max(arr[i], best_sum);
    }
    return best_sum;
}

int maxSumRect(int** input, int row, int col){
    int maxSum = INT_MIN,sum;
    for(int l = 0; l < col; l++){
        int* arr = new int[row];
        fill(arr, arr+row, 0);
        for(int r = l; r < col; r++){
            for(int i = 0; i < row; i++){
                arr[i] += input[i][r];
            }
            sum = kadane(arr, row);
            maxSum = max(maxSum, sum);
        }
        delete[] arr;
    }
    return maxSum;
}

int main()
{
    int row,col;
    cout << "Enter no. of rows and columns: " << endl;
    cin >> row >> col;
    cout << "Enter matrix elements: " << endl;
    int** input = new int*[row];
    for(int i = 0; i < row; i++){
        input[i] = new int[col];
        for(int j = 0; j < col; j++){
            cin >> input[i][j];
        }
    }
    
    cout << "Maximum Sum is: " << maxSumRect(input, row, col) << endl;
    
    for(int i = 0; i < row; i++){
        delete[] input[i];
    }
    delete[] input;
    return 0;
}

/*
Sample input/output:
Enter no. of rows and columns:                                                                                                
4 5                                                                                                                           
Enter matrix elements:                                                                                                        
1 2 -1 -4 -20                                                                                                                 
-8 -3 4 2 1                                                                                                                   
3 8 10 1 3                                                                                                                    
-4 -1 1 7 -6                                                                                                                  
Maximum Sum is: 29  

Time Complexity: O(cols^2 * rows) 
Space Compleity: O(rows)
*/



<|start_filename|>Java/cp/BalancedParenthesis.java<|end_filename|>
/*

Check for balanced parenthesis
==============================
Given an expression containing parenthesis, check if it is well-formed or balanced.
Example of balanced parenthesis are: (), ((())), (a+b), (a/b)*(b/a)

*/

import java.util.*; 
import java.io.*;

public class BalancedParenthesis {
	private static boolean isBalanced(String str) {
		// Size of the string
		int n = str.length();

		// Stack to store open parenthesis
		Stack<Integer> s = new Stack<Integer>();
		// Open parenthesis -> 1

		// Loop through characters in the string
		for (int i = 0; i < n; i++) {
			// Open parenthesis is always pushed into the stack
			if (str.charAt(i) == '(') {
				s.push(1);
			} else if (str.charAt(i) == ')') {
				// Closed parenthesis encountered must be balanced by an open parenthesis already
				// present in the stack
				if (!s.empty())
					// Stack contains open parenthesis, one of which has been balanced
					// Pop one parenthesis out
					s.pop();
				else
					// Stack contains no open parenthesis. So closed parenthesis cannot be balanced
					return false;
			}
		}

		// Check if we have open parenthesis remaining
		return (s.size() == 0);
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String str = sc.nextLine();
		System.out.println((isBalanced(str) ? "YES" : "NO"));
	} 
}

/*

Input:
((a+b)+(c-d+f))
Output:
YES

Application: Stack data structure
Time Complexity: O(n)
Space Complexity: O(n)

*/



<|start_filename|>C/dp/houseRobber.c<|end_filename|>
#include <stdio.h>
#include <stdlib.h>

int rob(int num[], int n) {
    if (n == 0) return 0;
    int *d = (int *)calloc(n + 2, sizeof(int));
    int i;
    d[0] = d[1] = 0; 
    for (i = 2; i < n + 2; i++) {
        if (d[i - 2] + num[i - 2] > d[i - 1]) {
            d[i] = d[i - 2] + num[i - 2];
        }
        else {
            d[i] = d[i - 1];
        }
    }
    return d[n + 1];
}

int main() {
    int num;
    printf("Enter number of houses: ");
    scanf("%d",&num);
    int money[num];
    printf("\nEnter money in each house: ");
    for(int i=0;i<num;i++)
    {
           scanf("%d",&money[i]);
    }
    printf("\nTotal amount that can be robbed: %d", rob(money, num));

    return 0;
}

/*
Time Complexity: n(log(n))
Space Complexity: n
Sample input: 
Enter number of houses: 4
Enter money in each house: 1 2 3 1 
Total amount that can be robbed: 4
*/


<|start_filename|>C/cp/Array_Mirror_Inverse.c<|end_filename|>
#include <stdio.h>
#include <stdbool.h>

bool array_mirror_inverse(int[], int);
int main()
{
	int n;
	bool f;
	printf("Enter the size of the array:");
	scanf("%d", &n);
	int arr[n];
	printf("Enter the elements:");
	for (int i = 0; i < n; ++i)
	{
		scanf("%d", &arr[i]);
	}

	f = array_mirror_inverse(arr, n);
	if (f)
		printf("The given array is mirror-inverse");
	else
		printf("The given array is not the mirror-inverse");
}

// Boolean Function which return if the array is mirror-inverse or not
bool array_mirror_inverse(int arr[], int n)
{
	bool f = true;
	for (int i = 0; i < n; ++i)
	{
		if (arr[arr[i]] != i)
		{
			f = false;
		}
	}

	return f;
}

/*
Time Complexity: O(N)

Sample Output
Enter the size of the array:5
Enter the elements:1 0 2 4 3
The given array is mirror-inverse
*/



<|start_filename|>C-Plus-Plus/cp/EvenPairSum.cpp<|end_filename|>
/*
Two positive integers A and B are given. Find the number of pairs 
of positive integers (X,Y) such that 1=X=A, 1=Y=B and X+Y is even.
Input
The first line of the input contains a single integer T denoting the
number of test cases.The description of T test cases follows.
The first and only line of each test case contains two space-separated 
integers A and B.
Output
For each test case, print a single line containing one integer-the number
of valid pairs.
*/
#include<iostream>
#include<algorithm>
using namespace std;

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    //t=test case
    int t; 
    cin>>t;
    while(t--)
         {
	    long long c,d;
	    long long ans=0;
	    cin>>c>>d;
	    long long a=min(c,d);
	    long long b=max(c,d);
	    if(a%2==0)
	    {
	        if(b%2==0)
	        {
	            ans=2*(a/2)*(b/2);
	            cout<<ans<<endl;
	            continue;
	        }
	        else
	        {
	            long long x=(a/2)*(b/2),y=(a/2)*((b/2)+1);
	            cout<<x+y<<endl;
	            continue;
	            
	        }
	    }
	    else
	    {
	       if(b%2==0)
	        {
	            long long x=(a/2)*(b/2),y=((a/2)+1)*(b/2);
	            cout<<x+y<<endl;
	            continue;
	        }
	        else
	        {
	            
	            long long x=(a/2)*(b/2),y=((a/2)+1)*((b/2)+1);
	            cout<<x+y<<endl;
	            continue;
	        } 
	    }	    
	}
	
	return 0;
}
/*
Example Input
4
1 1
2 3
4 6
8 9
Example Output
1
3
12
36

time complexity- O(t)
//t is no. of test cases
*/


<|start_filename|>Java/math/AsciiOfString.java<|end_filename|>
/*
AIM :: Take a string form the user.
	   Consider each individual character and print the corresponding ASCII code of that character.
*/
import java.util.Scanner;

public class AsciiOfString {

    public static void main(String[] args) {

        //taking user input of string
        System.out.print("Enter the string :: ");
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();

        // printing all the characters with their ASCII code
        for (int i = 0; i < str.length(); i++)
            System.out.println(str.charAt(i) + " = " + (int) str.charAt(i));
    }
}

/*
TEST CASE

Enter the string :: ANAND
A = 65
N = 78
A = 65
N = 78
D = 68

TIME COMPLEXITY  :: O(n)
SPACE COMPLEXITY :: O(1)

 */



<|start_filename|>C/ds/Double_Ended_Queue.c<|end_filename|>
/*  DOUBLE ENDED QUEUE
    Double ended queue or dequeue is a special type of queue 
    wherein elements can be inserted or deleted from both ends
    i.e front and rear
*/

#include <stdio.h>
//Declare dequeue with an array arr, front and rear as members
typedef struct
{
    int arr[10];
    int front, rear;
} dequeue;
dequeue dq;

//to insert an element to the front of double ended queue
void enqueue_front(int n)
{
    //If dequeue is not full
    if ((dq.rear + 1) % 10 != dq.front)
    {
        //If dequeue is empty insert as first element
        if (dq.front == -1)
        {
            dq.front = 0;
            dq.rear = 0;
        }
        //decrement front in circular manner and insert
        else
            dq.front = (dq.front + 9) % 10;
        dq.arr[dq.front] = n;
    }
}

//to insert an element to the rear of double ended queue
void enqueue_rear(int n)
{
    if ((dq.rear + 1) % 10 != dq.front)
    {
        if (dq.rear == -1)
        {
            dq.front = 0;
            dq.rear = 0;
        }
        //increment rear in circular manner and insert
        else
            dq.rear = (dq.rear + 1) % 10;
        dq.arr[dq.rear] = n;
    }
}

//to delete an element and return it from the front of dequeue
int delete_front()
{
    int item;
    //If dequeue is empty
    if (dq.front == -1)
        return -1;
    else
    {
        item = dq.arr[dq.front];
        //if there is only one element
        if (dq.front == dq.rear)
        {
            dq.front = -1;
            dq.rear = -1;
        }
        else
            dq.front = (dq.front + 1) % 10;
    }
    return item;
}

//to delete an element and return it from the rear of dequeue
int delete_rear()
{
    int item;
    if (dq.rear == -1)
        return -1;
    else
    {
        item = dq.arr[dq.rear];
        if (dq.front == dq.rear)
        {
            dq.front = -1;
            dq.rear = -1;
        }
        else
            dq.rear = (dq.rear + 9)%10;
    }
    return item;
}

//to display the double ended queue from front to rear
void display()
{
    if (dq.front <= dq.rear)
    {
        for (int i = dq.front; i <= dq.rear; i++)
            printf("%d ", dq.arr[i]);
    }
    else
    {
        for (int i = dq.front; i <= 9; i++)
            printf("%d ", dq.arr[i]);
        for (int i = 0; i <= dq.rear; i++)
            printf("%d ", dq.arr[i]);
    }
    printf("\n");
}

//driver code
int main()
{
    int q, t, n;
    //input no of queries
    scanf("%d", &q);
    dq.front = -1;
    dq.rear = -1;

    //menu driven program to insert,delete or display dequeue
    while (q--)
    {
        scanf("%d", &t);
        switch (t)
        {
        case 1:
            scanf("%d", &n);
            enqueue_front(n);
            break;
        case 2:
            scanf("%d", &n);
            enqueue_rear(n);
            break;
        case 3:
            printf("%d\n", delete_front());
            break;
        case 4:
            printf("%d\n", delete_rear());
            break;
        case 5:
            display();
            break;
        }
    }
    return 0;
}
/* 
    Sample Input:
    7
    1
    2
    2
    1
    1
    3
    1
    4
    2
    5
    3
    5
    Sample Output:
    4
    3 2 1 5
*/
/*
    Time Complexity of insertion and deletion operations: O(1)
    Time Complexity of display function : O(n)
    Time complexity of random access by index : O(1)
    Space complexity: O(1)
*/


<|start_filename|>C-Plus-Plus/other/distinct_subsets_of_set.cpp<|end_filename|>
/*Finding all distinct subsets of a given set using BitMasking Approach
Examples:

Input:  S = {1, 2, 2}
Output:  {}, {1}, {2}, {1, 2}, {2, 2}, {1, 2, 2}

Explanation:
The total subsets of given set are -
{}, {1}, {2}, {2}, {1, 2}, {1, 2}, {2, 2}, {1, 2, 2}
Here {2} and {1, 2} are repeated twice so they are considered only once in the output*/


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

vector<string> split(const string &s, char ch)
{
    vector<string> elems;
    stringstream ss(s);
    string item;
    while (getline(ss, item, ch))
        elems.push_back(item);

    return elems;
}

// Function to find all subsets of given set(repeated subset is considered only once)
int printPowerSet(vector<int> arr, int n)
{
    vector<string> list;

    for (int i = 0; i < (int) pow(2, n); i++)
    {
        string subset = "";
        for (int j = 0; j < n; j++)
        {
            // Check if jth bit in the i is set. If the bit is set, we consider jth element from set
            if ((i & (1 << j)) != 0)
                subset += to_string(arr[j]) + "|";
        }

        // if subset is encountered for the first time, If we use set<string>, we can directly insert
        if (find(list.begin(), list.end(), subset) == list.end())
            list.push_back(subset);
    }

    for (string subset : list)
    {
        // split the subset and print its elements
        vector<string> a = split(subset, '|');
        for (string str: a)
            cout << str << " ";
        cout << endl;
    }
}

int main()
{
    vector<int> arr;
    int n = arr.size();

    printPowerSet(arr, n);

    return 0;
}

/*Input: 10 12 12
Output:
10
12
10 12
12 12
10 12 12 */

/*Time complexity
For every index, we make 2 recursion calls and there are n elements so total time complexity is O(2^n).

Space complexity
There are 2^n-1 subsets and for every subset, we need O(n) space on average so total space complexity is O(2^n * n). */

<|start_filename|>C-Sharp/sort/BubbleSort.cs<|end_filename|>
﻿public class BubbleSort
{
    public static void Sort(int[] array)
    {
        for (int i = 0; i < array.Length - 1; i++)
        {
            bool noSwap = true;

            for (int j = 0; j < array.Length - i - 1; j++)
            {
                if (array[j] > array[j + 1])
                {
                    (array[j], array[j + 1]) = (array[j + 1], array[j]);
                    noSwap = false;
                }
            }

            // if there is no swap done we stop the algo
            if (noSwap)
            {
                break;
            }
        }
    }
}



<|start_filename|>C/search/Fibonacci_Search.c<|end_filename|>
// C program implementation for Fibonacci Search 

// Worst case time complexity: Θ(logn)
// Average case time complexity: Θ(log n)
// Best case time complexity: Θ(1)
// Space complexity: Θ(1)


#include <stdio.h>
#include <string.h>
 
int Fibonacci_Search(int a[], int n, long x)
{ 
    int index = 0, position, k;
    static int n_1= -1, n_2 = -1;
    
    // Precomputed Fibonacci numbers from F_0 up to F_46.
    static int fib[]={0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 98,
    1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811,
    514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817,
    39088169, 63245986, 102334155, 165580141};
    if (n_2 != n)
    { 
        k = 0;
        while (fib[k] < n)
            k++;
        n_1 = k;
        n_2 = n;
    }
    else
        k = n_1;
    while (k > 0)
    {
        position = index + fib[--k];
        if ((position >= n) || (x < a[position]));
        else if (x > a[position])
        {
            index = position + 1;
            k--;
        }
        else {
            return position;
        }
    }
    return -1;
}
void main()
{
    int no_element=0;
    printf("Enter the no of element in the array: "); 
        scanf("%d", &no_element);
    int arr[no_element];

    // taking input 
    printf("Enter the array: \n"); 
    for(int z=0; z < no_element; z++){
        scanf("%d", &arr[z]);
    }
    int num;
    printf("Enter an element to search: ");
    scanf("%d", &num);

    (Fibonacci_Search(arr, 10, num) == -1) ? printf("Element NOT found!! ") :
    printf("Element is at index : %d", Fibonacci_Search(arr, 10, num));
 
}
/*
____Example-1____
Enter the no of element in the array: 5                                                                                            
Enter the array:                                                                                                                   
30                                                                                                                                 
20                                                                                                                                 
28                                                                                                                                 
55                                                                                                                                 
62                                                                                                                                 
Enter an element to search: 28                                                                                                     
Element is at index : 2

____Example-2____
Enter the no of element in the array: 6                                                                                            
Enter the array:                                                                                                                   
48                                                                                                                                 
56                                                                                                                                 
24                                                                                                                                 
16                                                                                                                                 
36                                                                                                                                 
66                                                                                                                                 
Enter an element to search: 22                                                                                                     
Element NOT found!!
*/

<|start_filename|>Java/cp/CheckForSubSequence.java<|end_filename|>
import java.util.*;
public class CheckForSubSequence
{
    public boolean CheckForSubSequenceFunc(String st1, String st2){
	    char[] ch1 = st1.toCharArray();
	    char[] ch2 = st2.toCharArray();
	    int count2=0, count1=0;
	    for(count2=0; count2<ch2.length && count1<ch1.length; count2++){
	        if(Character.compare(ch1[count1], ch2[count2]) == 0) count1++;
	    }
	    return (count1 == ch1.length);
    }
	public static void main(String[] args) {
	    Scanner sc = new Scanner(System.in);
	    System.out.print("Enter first string: ");
	    String st1 = sc.next();
	    System.out.print("Enter second string: ");
	    String st2 = sc.next();
	    CheckForSubSequence cfs = new CheckForSubSequence();
	    if(cfs.CheckForSubSequenceFunc(st1, st2)) System.out.print(st1+" is a subsequence of "+st2);
	    else System.out.print(st1+" is a not subsequence of "+st2);
	}
}

/*Sample input and output

# 1
Enter first string: pogy
Enter second string: appology
pogy is a subsequence of appology

# 2
Enter first string: race
Enter second string: horse
race is a not subsequence of horse

Complexities
time: O(n)
space: O(n)*/

<|start_filename|>C-Plus-Plus/cryptography/Shamir_Secret_Sharing.cpp<|end_filename|>
/* Shamir's Secret Sharing algorithm:
 * Generates a specified number of shares
 * where putting together a fixed number of
 * a subset of those shares reveals an encoded
 * secret value.
 */

#include<iostream>
#include<vector>
#include<map>
#include<random>
#include<type_traits>
using namespace std;

// Chosen RNG engine: mersenne twister
mt19937 rng;
// Global seed for chosen RNG engine
mt19937::result_type seed_val;

/* Initialise chosen RNG with seed value that is
 * entropy taken from system's entropy source
 * (generally /dev/urandom on Linux).
 */
void rng_init() {
    random_device rand_dev;
    seed_val = rand_dev();
    rng.seed(seed_val);
}

/* Populate a vector with specified number
 * of random natural numbers generated by chosen RNG.
 */
vector<unsigned> gen_rand_uints(unsigned num) {
    rng_init();

    // Use random values from a uniform distribution
    uniform_int_distribution<unsigned> uint_dist;
    vector<unsigned> rand_ints;
    for (unsigned i = 0; i < num; i++) {
        rand_ints.push_back(uint_dist(rng));
    }

    return rand_ints;
}

/* Generate a map from share number to share value for
 * Shamir's Secret Sharing algorithm, using the specified
 * secret natural number that is to be protected.
 *
 * The shares are a set of points which map from values of
 * x to values of f(x), where f(x) is a polynomial of
 * degree (min_shares - 1), and f(0) = secret.
 */
map<unsigned, unsigned> sss_gen_shares(unsigned min_shares, unsigned max_shares, unsigned secret) {
    vector<unsigned> poly_coeffs = gen_rand_uints(min_shares - 1);
    map<unsigned, unsigned> shares;
    for (unsigned x = 1; x <= max_shares; x++) {
        unsigned y = secret; // f(0)
        for (unsigned i = 1; i <= poly_coeffs.size(); i++) {
            unsigned term = poly_coeffs[i] * unsigned(pow(x, i));
            y += term;
        }
        shares[x] = y;
    }

    return shares;
}

/* Recover the secret encoded by Shamir's Secret Sharing
 * algorithm given a map of share number to share value.
 * The secret is given by f(0), which can be calculated
 * using any (min_shares - 1) points out of the total
 * (max_shares) points available.
 *
 * Taking min_shares = k, max_shares = n,
 * f(0) is calculated from (x_1, y_1), (x_2, y_2), ..., (x_k, y_k)
 * by using Lagrange polynomials to find the constant term given by
 * sum{i=0 to k-1} (y_i * (product{j=0 to k-1, i != j} (x_j/(x_j - x_i))))
 */
unsigned sss_recover_secret(const map<unsigned, unsigned>& shares) {
    double sum_of_terms = 0.0;
    for (auto i : shares) {
        unsigned temp_numerator = 1;
        int temp_denominator = 1; // int, since negative values possible
        for (auto j : shares) {
            if (i != j) {
                unsigned x_i = i.first;
                unsigned x_j = j.first;
                temp_numerator *= x_j;
                temp_denominator *= x_j - x_i;
            }
        }
        unsigned y_i = i.second;
        double term = double(y_i * temp_numerator) / temp_denominator;
        sum_of_terms += term;
    }
    unsigned secret = round(sum_of_terms);

    return secret;
}

int main() {
    unsigned min_shares;

    /* Less than 3 shares is impractical for security purposes,
     * since the constant term of the polynomial can then
     * be easily calculated.
     */
    do {
        cout << "Enter minimum number of shares to unlock secret (at least three): ";
        cin >> min_shares;
    } while (min_shares < 3);

    unsigned max_shares;
    do {
        cout << "Enter total number of shares to generate (not less than the minimum): ";
        cin >> max_shares;
    } while (max_shares < min_shares);

    unsigned secret;
    /* Beyond 1E9, the recovered secret key comes out incorrect as
     * calculation of the polynomial points overflow silently
     */
    do {
        cout << "Enter secret number (a natural number): ";
        cin >> secret;
    } while(secret >= 1E9);

    auto shares = sss_gen_shares(min_shares, max_shares, secret);
    cout << endl;
    cout << "Secret_shares (share number, share value):" << endl;
    for (auto share : shares) {
        cout << "(" << share.first << ", " << share.second << ")" << endl;
    }

    cout << endl;
    cout << "Enter any " << min_shares << " shares:" << endl;
    map<unsigned, unsigned> input_shares;
    for (unsigned i = 1; i <= min_shares; i++) {
        cout << "For input number " << i << ":" << endl;

        unsigned temp_x;
        cout << "    Share number: ";
        cin >> temp_x;

        unsigned temp_y;
        cout << "    Share value: ";
        cin >> temp_y;

        input_shares[temp_x] = temp_y;
    }
    auto recovered_secret = sss_recover_secret(input_shares);
    cout << endl;
    cout << "Recovered secret: " << recovered_secret << endl;
}

/* Example session:
Enter minimum number of shares to unlock secret (at least three): 4
Enter total number of shares to generate (not less than the minimum): 7
Enter secret number (a natural number): 123456789

Secret_shares (share number, share value):
(1, 3351437161)
(2, 1499306213)
(3, 3156998537)
(4, 4029546837)
(5, 4116951113)
(6, 3419211365)
(7, 1936327593)

Enter any 4 shares:
For input number 1:
    Share number: 7
    Share value: 1936327593
For input number 2:
    Share number: 2
    Share value: 1499306213
For input number 3:
    Share number: 3
    Share value: 3156998537
For input number 4:
    Share number: 1
    Share value: 3351437161

Recovered secret: 123456789
 */

/* For total number of shares = n
 * and minimum number of shares = k,
 * generation of shares has
 * Time Complexity = O(n),
 * and recovery of secret value has
 * Time Complexity = O(k^2).
 *
 * Overall program has
 * Space Complexity = O(k).
 */


<|start_filename|>C-Plus-Plus/cp/Reverse_Words_in_String.cpp<|end_filename|>
/**
 * @author omkarlanghe
 * Given a String of length S, reverse the whole string without reversing the individual words in it.
 * Words are separated by dots.
 * 
 * Input:
 * The first line contains T denoting the number of testcases. 
 * T testcases follow. Each case contains a string S containing characters.
 * 
 * Output:
 * For each test case, in a new line, output a single line containing the reversed String.
 * 
 * Example:
 * Input:
 * 2
 * i.like.this.program.very.much
 * pqr.mno
 * 
 * Output:
 * much.very.program.this.like.i
 * mno.pqr
*/
#include <iostream>
#include <stack>

int main() {
    int t;
    std::cout << "Enter test cases : " << std::endl;
    std::cin >> t;
    while (t--) {
        std::stack<std::string> str_stack;
        std::string str, stack_string;

        std::cout << "Enter the string : " << std::endl;
        std::cin >> str;

        for (int i = 0 ; i < str.size() ; i++) {
            if (str[i] != '.') {
                stack_string += str[i];
            } else {
                str_stack.push(stack_string);
                str_stack.push(".");
                stack_string = "";
            }
        }
        str_stack.push(stack_string);
        str = "";
        while (!str_stack.empty()) {
            str += str_stack.top();
            str_stack.pop();
        }
        std::cout << str << std::endl;
    }
    return (0);
}


<|start_filename|>C-Plus-Plus/dp/pascal's_triangle.cpp<|end_filename|>
/*
Given the number of rows , print the pascal's triangle having that many rows.
*/
#include <bits/stdc++.h>
using namespace std;
int main()
{
    long int n;
    cout << "Enter the number of rows" << endl;
    cin >> n; // Enter the number of rows in the triangle
    long int dp[n][n];
    cout << "The Pascal's Triangle is : " << endl;
    for (int row = 0; row < n; row++)
    {
        for (int i = 0; i <= row; i++)
        {
            if (row == i || i == 0)
                dp[row][i] = 1; //Initialize first and last element of ach row with 1
            else
                dp[row][i] = dp[row - 1][i - 1] + dp[row - 1][i]; //Other values are sum of values just above and left of above
            cout << dp[row][i] << " ";
        }
        cout << endl;
    }
    return 0;
}
/*<NAME>
   Time Complexity - O(n^2)
   Space Complexity - O(n^2) auxiliary space
   Sample Input -
   Enter the number of rows
   4 
   Sample Output -
   The Pascal's Triangle is :  
       1
      1 1
     1 2 1
    1 3 3 1 */

<|start_filename|>C/ds/FenwickTree.c<|end_filename|>
**Fenwick Tree**

#include <stdio.h>

int FWtree[100] = {0};
int SIZE;

int get_sum(int i)
{
	int sum = FWtree[i];
	while(i)
	{
		i -= (i & (-i));
		sum += FWtree[i];
	}
	return sum;
}

void add(int i, int value)
{
	while(i < SIZE)
	{
		FWtree[i] += value;
		i += (i & (-i));
	}
}

void init_fw_tree(int my_array[], int start, int end)
{
	SIZE = end-start+2;
	for(int i = 1; i <= end-start+2; i++)
	{
		add(i, my_array[ start+i-1 ]);
	}
}

int main()
{
	int my_array[] = {1, 3, 2, 4, 5 ,9, 6, 5 ,0, 3, 4, 3, 2, 2};
	init_fw_tree(my_array, 0, 13);

	//get sum of all the numbers in the array
	printf("Sum of all  numbers in the array is = %d\n",get_sum(14));
	
	// update 5th index with value 9
	add(5,9);
	printf("New sum after updating 5th index with value 8 is = %d\n",get_sum(14));

	return 0;
}



<|start_filename|>Java/cp/Factorial_large_numbers.java<|end_filename|>
import java.util.*;
public class Factorial_large_numbers
{
    public static int len = 0;
    public static int[] Factorial(int n, int[] arr, int[] str2){
        int temp = 0, carry = 0, i=0;
        for(i=0; i<len; i++){
            temp = str2[i]*n + carry;
            carry = temp/10;
            arr[i] = temp%10;
        }
        while(carry!=0){
            arr[i] = carry%10;
            carry = carry/10;
            len+=1;
            i+=1;
        }
        return arr;
    }
	public static void main(String[] args) {
	    Scanner sc = new Scanner(System.in);
	    System.out.print("Enter number : ");
	    int num = sc.nextInt();
	    String str = String.valueOf(num);
	    len = str.length();
	    int[] arr = new int[300];
	    int[] str2 = new int[300];
	    int i=0, temp=num;
	    for(i=0; i<len; i++){
	        str2[i] = temp%10;
	        temp=temp/10;
	    }
	    for(int j=1; j<num; j++){
    	    str2 = Factorial(j, arr, str2);
	    }
	    System.out.print("Factorial of "+num+" = ");
        for(i=len-1; i>=0; i--){
            System.out.print(str2[i]);
        }
	}
}

/*
Sample input and output
Enter number : 10
Factorial of 10 = 3628800

Complexities
time: O(n^2)
space: O(n)
*/

<|start_filename|>C-Plus-Plus/cp/Array_Right_Rotate.cpp<|end_filename|>
/**
 * copyright 2020 @author omkarlanghe
 * 
 * @file
 * Given an unsorted array arr[] of size N, rotate it by D elements (clockwise).
 * Input:
 * 
 * The first line of the input contains T denoting the number of testcases. First line of each test case contains two space separated elements, N denoting the size of the array and an integer D denoting the number size of the rotation.
 * Subsequent line will be the N space separated array elements.
 * 
 * Output:
 * For each testcase, in a new line, output the rotated array.
 * 
 * Example:
 * Input:
 * 
 * 2                        where 2 is the total number of test cases.
 * 5 2                      where 5 is the size of array and 2 is the rotation factor for test case 1.
 * 1 2 3 4 5                space seperated integers represting elements of an array for test case 1.
 * 10 3                     where 10 is the size of array and 3 is the rotation factor for test case 2.
 * 1 2 5 3 4 6 7 8 9 10     space seperated integers represting elements of an array for test case 2.
 * 
 * Output:
 * 4 5 1 2 3
 * 8 9 10 1 2 3 4 5 6 7
 * 
 * Timecomplexity: O(n) where n is the size of an array.
*/
#include <iostream>
#include <vector>

void right_rotate_array(std::vector<int> *, int, int);
void rotate_by_one_element(std::vector<int> *, int);

/**
 * Function which performs array rotation by one element based on its given rotation factor.
*/
void right_rotate_array(std::vector<int> *arr, int size, int rotation_factor) {
    for (int i = 0 ; i < rotation_factor ; i++) {
        rotate_by_one_element(arr, size);
    }
}

/**
 * Function which shifts array elements by one position to its right.
*/
void rotate_by_one_element(std::vector<int> *arr, int size) {
    int temp = (*arr)[size - 1];
    for (int i = (size - 2) ; i >= 0 ; i--) {
        (*arr)[i+1] = (*arr)[i];
    }
    (*arr)[0] = temp;
}

/** Main function */
int main() {
    int t, size, rotate_factor, input;
    std::cout << "Enter testcases to test : " << std::endl;
    std::cin >> t;

    while (t--) {
        std::cout << "Enter size of an array : " << std::endl;
        std::cin >> size;
        std::cout << "Enter rotation factor to rotate : " << std::endl;
        std::cin >> rotate_factor;
        std::vector<int> ivec;
        std::vector<int> *v = &ivec;

        std::cout << "Enter the elements in an array : " << std::endl;
        for (int i = 0 ; i < size ; i++) {
            std::cin >> input;
            ivec.push_back(input);
        }

        right_rotate_array(v, size, rotate_factor);

        std::cout << "Array after right rotation : " << std::endl;

        for (int i = 0 ; i < size ; i++) {
            std::cout << ivec[i] << " ";
        }
        std::cout << std::endl;
    }
    return 0;
}


<|start_filename|>Java/cryptography/HomophonicCipher.java<|end_filename|>
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

/**
 * <h1>Homophonic Cipher</h1>
 * <p>
 * To Implement Homophonic Cipher
 * </p>
 * 
 * <b>Description</b>
 * <p>
 * Homophonic Cipher is a substitution cipher, it replaces each letter with a varity of substitues, it is very similar
 * to Monoalphabetic cipher, the key difference between Homophonic cipher and Monoalphabetic cipher is that, in
 * Monoalphabetic cipher there is a constant replacement of character to another character whereas in Homophonic cipher
 * we have a set of characters which we can substitute.
 * </p>
 */
public class HomophonicCipher
{
    // Character Mapping table for Homophonic Cipher
    private static HashMap<Character, List<Character>> homophonicSequence;
    
    /**
     * <p>
     * This is a public method which is used to initialize homophonicSequence with character mapping.
     * </p>
     */
    public void initializeHomophonicSequence()
    {
        // Initializing homophonicSequence
        homophonicSequence = new HashMap<Character, List<Character>>();
        
        // Character Mapping for letter 'A'
        List<Character> aCharacterList = new ArrayList<Character>();
        aCharacterList.add('D');
        aCharacterList.add('9');
        HomophonicCipher.homophonicSequence.put('A', aCharacterList);
        
        // Character Mapping for letter 'B'
        List<Character> bCharacterList = new ArrayList<Character>();
        bCharacterList.add('X');
        HomophonicCipher.homophonicSequence.put('B', bCharacterList);
        
        // Character Mapping for letter 'C'
        List<Character> cCharacterList = new ArrayList<Character>();
        cCharacterList.add('S');
        HomophonicCipher.homophonicSequence.put('C', cCharacterList);
        
        // Character Mapping for letter 'D'
        List<Character> dCharacterList = new ArrayList<Character>();
        dCharacterList.add('F');
        HomophonicCipher.homophonicSequence.put('D', dCharacterList);
        
        // Character Mapping for letter 'E'
        List<Character> eCharacterList = new ArrayList<Character>();
        eCharacterList.add('Z');
        eCharacterList.add('7');
        eCharacterList.add('2');
        eCharacterList.add('1');
        HomophonicCipher.homophonicSequence.put('E', eCharacterList);
        
        // Character Mapping for letter 'F'
        List<Character> fCharacterList = new ArrayList<Character>();
        fCharacterList.add('E');
        HomophonicCipher.homophonicSequence.put('F', fCharacterList);
        
        // Character Mapping for letter 'G'
        List<Character> gCharacterList = new ArrayList<Character>();
        gCharacterList.add('H');
        HomophonicCipher.homophonicSequence.put('G', gCharacterList);
        
        // Character Mapping for letter 'H'
        List<Character> hCharacterList = new ArrayList<Character>();
        hCharacterList.add('C');
        HomophonicCipher.homophonicSequence.put('H', hCharacterList);
        
        // Character Mapping for letter 'I'
        List<Character> iCharacterList = new ArrayList<Character>();
        iCharacterList.add('V');
        iCharacterList.add('3');
        HomophonicCipher.homophonicSequence.put('I', iCharacterList);
        
        // Character Mapping for letter 'J'
        List<Character> jCharacterList = new ArrayList<Character>();
        jCharacterList.add('I');
        HomophonicCipher.homophonicSequence.put('J', jCharacterList);
        
        // Character Mapping for letter 'K'
        List<Character> kCharacterList = new ArrayList<Character>();
        kCharacterList.add('T');
        HomophonicCipher.homophonicSequence.put('K', kCharacterList);
        
        // Character Mapping for letter 'L'
        List<Character> lCharacterList = new ArrayList<Character>();
        lCharacterList.add('P');
        HomophonicCipher.homophonicSequence.put('L', lCharacterList);
        
        // Character Mapping for letter 'M'
        List<Character> mCharacterList = new ArrayList<Character>();
        mCharacterList.add('G');
        HomophonicCipher.homophonicSequence.put('M', mCharacterList);
        
        // Character Mapping for letter 'N'
        List<Character> nCharacterList = new ArrayList<Character>();
        nCharacterList.add('A');
        nCharacterList.add('5');
        HomophonicCipher.homophonicSequence.put('N', nCharacterList);
        
        // Character Mapping for letter 'O'
        List<Character> oCharacterList = new ArrayList<Character>();
        oCharacterList.add('Q');
        oCharacterList.add('0');
        HomophonicCipher.homophonicSequence.put('O', oCharacterList);
        
        // Character Mapping for letter 'P'
        List<Character> pCharacterList = new ArrayList<Character>();
        pCharacterList.add('L');
        HomophonicCipher.homophonicSequence.put('P', pCharacterList);
        
        // Character Mapping for letter 'Q'
        List<Character> qCharacterList = new ArrayList<Character>();
        qCharacterList.add('K');
        HomophonicCipher.homophonicSequence.put('Q', qCharacterList);
        
        // Character Mapping for letter 'R'
        List<Character> rCharacterList = new ArrayList<Character>();
        rCharacterList.add('J');
        HomophonicCipher.homophonicSequence.put('R', rCharacterList);
        
        // Character Mapping for letter 'S'
        List<Character> sCharacterList = new ArrayList<Character>();
        sCharacterList.add('R');
        sCharacterList.add('4');
        HomophonicCipher.homophonicSequence.put('S', sCharacterList);
        
        // Character Mapping for letter 'T'
        List<Character> tCharacterList = new ArrayList<Character>();
        tCharacterList.add('U');
        tCharacterList.add('6');
        HomophonicCipher.homophonicSequence.put('T', tCharacterList);
        
        // Character Mapping for letter 'U'
        List<Character> uCharacterList = new ArrayList<Character>();
        uCharacterList.add('O');
        HomophonicCipher.homophonicSequence.put('U', uCharacterList);
        
        // Character Mapping for letter 'V'
        List<Character> vCharacterList = new ArrayList<Character>();
        vCharacterList.add('W');
        HomophonicCipher.homophonicSequence.put('V', vCharacterList);
        
        // Character Mapping for letter 'W'
        List<Character> wCharacterList = new ArrayList<Character>();
        wCharacterList.add('M');
        HomophonicCipher.homophonicSequence.put('W', wCharacterList);
        
        // Character Mapping for letter 'X'
        List<Character> xCharacterList = new ArrayList<Character>();
        xCharacterList.add('Y');
        HomophonicCipher.homophonicSequence.put('X', xCharacterList);
        
        // Character Mapping for letter 'Y'
        List<Character> yCharacterList = new ArrayList<Character>();
        yCharacterList.add('B');
        HomophonicCipher.homophonicSequence.put('Y', yCharacterList);
        
        // Character Mapping for letter 'Z'
        List<Character> zCharacterList = new ArrayList<Character>();
        zCharacterList.add('N');
        HomophonicCipher.homophonicSequence.put('Z', zCharacterList);
    }
    
    /**
     * <p>
     * This is a public method which is used to encrypt plain text using Homophonic Substitution Cipher method
     * </p>
     * 
     * @param plainText This is a String parameter to encrypt method, this signifies plain text which is passed.
     * 
     * @return String This returns the cipherText.
     */
    public String encrypt(String plainText)
    {
        StringBuilder cipherText = new StringBuilder("");// used to store cipher text
        
        // Iterates through plainText
        for (int i = 0; i < plainText.length(); i++)
        {
            // Gets List of mapping characters to the current character
            List<Character> characterList = HomophonicCipher.homophonicSequence.get(plainText.charAt(i));
            // If character mapping is found
            if (characterList != null)
            {
                // Random character index is picked from the set of characters
                Integer indexToUse = new Random().nextInt(characterList.size());
                // character selected by random is appended to cipherText
                cipherText.append(characterList.get(indexToUse));
            }
            // If character mapping is not found
            else
            {
                // Without encryption plainText character will be appended to cipherText
                cipherText.append(plainText.charAt(i));
            }
        }
        // cipher text is retured
        return cipherText.toString();
        
    }
    
    /**
     * This is the main method which makes use of the following methods:
     * <ul>
     * <li>encrypt</li>
     * </ul>
     * 
     * And uses the following objects of types:
     * <ul>
     * <li>java.util.Scanner</li>
     * <li>HomophonicCipher</li>
     * </ul>
     * 
     * @param args not used
     */
    public static void main(String[] args)
    {
        String           plainText;                                 // Create an object of String class for storing plain text to be entered by the user
        Scanner          scan             = new Scanner(System.in); // Created an object of Scanner class for asking for user input.
        HomophonicCipher homophonicCipher = new HomophonicCipher(); // Created an object of HomophonicCipher for accessing it's method for encryption
        
        // Initializing homophonicCipher
        homophonicCipher.initializeHomophonicSequence();
        
        // Asking user to enter plain text
        System.out.println("Please Enter Plain Text:");
        plainText = scan.nextLine();
        
        // Accessing method 'encrypt' of HomophonicCipher class to encrypt plainText
        String cipherText = homophonicCipher.encrypt(plainText.toUpperCase());
        // Printing cipher text
        System.out.println("Cipher Text: " + cipherText);
        
        // Closing the Scanner object scan
        scan.close();
    }
}
/*
 * Please Enter Plain Text:
 * 
 * Attack Alice's troops at 5:00 PM today
 * 
 * Cipher Text: DU6DST 9PVS2'4 6J0QLR 9U 5:00 LG UQFDB
 */

<|start_filename|>C-Plus-Plus/other/count_of_set_bit_using_lookup_tech.cpp<|end_filename|>
/*A CPP implementation of count of set bits in an integer using a LookUp 
table technique - <NAME> */
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int main()
{
    int arr[] = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4}; // An array containg count of set bits from 0 - 15

    long long int number, count = 0;
    cout << "Enter the Integer value : ";
    cin >> number; // Input

    while (number != 0)
    {
        count += arr[number & 0xF];
        number >>= 4;
    }
    cout << "Number of set bits in the given integer are : " << count;
    return 0;
}

/* Time Complexity : Worst case - O((logn)/k)
                     Best case  - O(1)
Space Complexity : k - bit approach - O(2^k) 
where n is the given integer and k is the number of bits in each nibble
4 - bit - form :
                    0 - 0000
                    1 - 0001
                    2 - 0010
                    .... 
Sample Input - 9 (1001)
Sample Output - 2 
Sample Input - 124(0111 1100)
Sample Output - 5  --> 3 in upper nibble ,2 in lower nibble*/

<|start_filename|>C-Plus-Plus/sort/wave_sort.cpp<|end_filename|>
/* Problem statement :
Given an unsorted array. Sort the array in such a way that the array looks like a wave array.
For example, if the given sequence arr has n elements then the sorted wave array looks like -
arr[0] >= arr[1] and arr[1] <= arr[2]
arr[2] >= arr[3] and arr[3] <= arr[4]
arr[4] >= arr[5] and arr[5] <= arr[6] And so on
For example, the given array : arr = { 4, 3, 5, 2, 3, 1, 2 } 
The above figure is a visual representation of the given arr and you can see we can express ‘arr’ in a waveform array because 
4>3 and 3<5 
5>2 and 2<3
3>1 and 1<2
And it follows the condition of wave array */

#include <bits/stdc++.h>
using namespace std;
vector<int> wave_sort(vector<int> &v, int n)
{
	for (int i = 0; i < n; i += 2)
	{
		/*If the current element is lesser in value than the previous and is not the first.
		then the values are swapped */
		if (v[i] < v[i - 1] and i != 0)
		{
			swap(v[i], v[i - 1]);
		}

		/*If the current element is lesser in value than the next and is not the last.
		then the values are swapped */
		if (v[i] < v[i + 1] and i != n - 1)
		{
			swap(v[i], v[i + 1]);
		}
	}

	return v;
}

int main()
{
	int n;
	vector<int> v;
	cin >> n;

	for (int i = 0; i < n; i++)
	{
		int temp;
		cin >> temp;
		v.push_back(temp);
	}
	wave_sort(v, n);
	
	//Printing the final vector
	for (int i = 0; i < n; i++)
	{
		cout << v[i] << " ";
	}

	return 0;
}

/* Example 1:
Input[] : {20 80 40 35 10 15 70}
Output[] : {80 20 40 10 35 15 70}

Example 2:
Input[] = {12 20 45 60 5}
Output[] : {20 12 60 5 45}

Time Complexity: O(n) */


<|start_filename|>Go/cryptography/Burrows_Wheeler_Transform/Burrows_Wheeler_Transform.go<|end_filename|>
/* Below is an implementation of Burrows Wheeler Transform in Go. It restructures
the given plaintext to forms the ciphertext. It first forms all possible cyclic
rotations of the plaintext, and then sorts the rotations lexicographically. Then,
ciphertext is formed by taking the last character of each rotation sorted in
lexicographical order. This code is implemented keeping in mind that characters
in the plaintext are all unique.*/

package main

import (
	"fmt"
	"os"
)

// Define the size of the n (Globally)
var n int = 4

// This function generates all cyclic rotations of given plaintext
func gen_rotations(plaintext string, combinations [][]string) {

	var indx int = 0
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			combinations[i][j] = string(plaintext[(indx + j) % n])
		}
		indx += 1;
	}
}

// This function sorts the above rotations lexicographically.
func sort(plaintext string, combinations [][]string, arr []int) {

	// Calling the generate function to generate all rotations
	gen_rotations(plaintext, combinations)

	var count int = 0

	for k := 0; k < n; k++ {

		// Iterate through the first column
		for i := 0; i < 1; i++ {
			/* Character { is lexicograqphically greater than
			[A-Z] and [a-z]. So, we use it here as a maximum.*/
			var min string = "{"
			var indx int

			// Iterate though first element of each row
			for j := 0; j < n; j++ {
				if(combinations[j][i] < min) {
					// Find the minimum
					min = combinations[j][i]
					// Store its index
					indx = j
				}
			}
			// Add the index to the array
			arr[count] = indx
			count += 1
			// Replace the minimum with {
			combinations[indx][i] = "{"
		}
	}
}

// This is the encrpytion function
func encrypt(plaintext string, combinations [][]string) string {

	var arr = make([]int, n)

	// Calling the sort function to get the sorted order
	sort(plaintext, combinations, arr)

	var encrypted string

	// Adding last element of sorted rotation to the encrypted text
	for i := 0; i < n; i++ {
		encrypted += combinations[arr[i]][n - 1]
	}
	// Returning the encrypted message
	return encrypted
}

func main() {

	fmt.Print("----------Burrows Wheeler Transform----------\n")
	fmt.Print("\nCurrent value of n is: ", n, "\n\n")

	// Taking plaintext as input from user
	fmt.Print("Enter a plaintext of size ", n, ": ")
	var plaintext string
	fmt.Scan(&plaintext)

	// Check if size of plaintext is equal global var n
	if(len(plaintext) != n) {
		fmt.Print("Invalid message entered.\n")
		os.Exit(0)
	}

	// Decalring matrix to store the rotations
	var combinations = make([][]string, n)
	for i := range combinations {
		combinations[i] = make([]string, n)
	}

	// Calling the encrypted fuction and printing ciphertext
	var encrypted string = encrypt(plaintext, combinations)
	fmt.Print("\nEncrypted plaintext is: ", encrypted, "\n")
}

/* Sample I/O:

a)
----------Burrows Wheeler Transform----------

Current value of n is: 10

Enter a plaintext of size 10: ThisISBurr

Encrypted plaintext is: SsIrThuriB

b)
----------Burrows Wheeler Transform----------

Current value of n is: 4

Enter a plaintext of size 4: hell

Encrypted plaintext is: hlel

*/


<|start_filename|>Java/other/FirstMissingPositiveNumber.java<|end_filename|>
import java.util.*;

public class FirstMissingPositiveNumber {

    private static void swap(int arr[], int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    private static int findMissingPositive(int arr[]) {
        // we firstly separate the positive numbers from negative numbers
        int j = 0, i;
        // j is for counting non-positive integers
        for (i = 0; i < arr.length; i++) {
            if (arr[i] <= 0) {
                swap(arr, i, j);
                j += 1;
            }
        }

        // getting array for only positive numbers in arr2
        int arr2[] = new int[arr.length - j];
        i = j;
        j = 0;
        for (; i < arr.length; i++) {
            arr2[j] = arr[i];
            j += 1;
        }

        // marking the number visited by its negative
        // for only those that don't go beyond length of the
        // array of positive numbers
        for (i = 0; i < arr2.length; i++) {
            int checkNum = Math.abs(arr2[i]);
            if (checkNum - 1 < arr2.length && arr2[checkNum - 1] > 0) {
                arr2[checkNum - 1] = -arr2[checkNum - 1];
            }
        }

        for (i = 0; i < arr2.length; i++) {
            if (arr2[i] > 0) {
                return i + 1;
            }
        }
        return arr2.length + 1;
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        //taking input array
        System.out.println("Enter size of array:");
        int size = sc.nextInt();
        int arr[] = new int[size];
        System.out.println("Enter array elements:");
        for (int i=0; i<size; i++) {
            arr[i] = sc.nextInt();
        }
        sc.close();

        int missingNum = findMissingPositive(arr);

        System.out.println("Lowest missing positive integer in the array is:" + missingNum);
    }
}
/**
 * Sample input/output:
 * Enter size of array:
 * 8
 * Enter array elements:
 * 1
 * -1
 * -5
 * -3
 * 3
 * 4
 * 2
 * 8
 * Lowest missing positive integer in the array is:5
 * 
 * Time complexity: O(n)
 * Space complexity: O(1)
 */


<|start_filename|>Java/cp/Rabin_Karp.java<|end_filename|>
/*
Rabin–Karp algorithm or Karp–Rabin algorithm is a string-searching algorithm that uses hashing to find an exact match of a pattern string in a text. 
It uses a rolling hash to quickly filter out positions of the text that cannot match the pattern, and then checks for a match at the remaining positions.
*/
import java.util.*;
class  Main
{
    public static void main( String[] args )
 {
   String actualText , patternToBeSearched;
   Scanner sc=new Scanner(System.in);
   System.out.println( "Enter actual text" ) ;
   actualText = sc.nextLine();
   System.out.println( "Enter pattern to be searched" );
   patternToBeSearched = sc.nextLine();
   int indexI , indexJ , locationIndex = -1 , count = 0;
   long sumOfCharactersOfTempString = 0 ,sumOfCharactersOfPatternToBeSearched = 0;
   for( indexI = 0; indexI < patternToBeSearched.length() ; indexI++ )
   {
       sumOfCharactersOfPatternToBeSearched = sumOfCharactersOfPatternToBeSearched + (long) (patternToBeSearched.charAt(indexI) * Math.pow(127,patternToBeSearched.length()-1-indexI) );
   }
   for( indexI = 0; indexI <= actualText.length() - patternToBeSearched.length(); indexI++ )
   {
       sumOfCharactersOfTempString = 0; indexJ = indexI;
       for( count = 0; count < patternToBeSearched.length(); count++ )
        {   
            sumOfCharactersOfTempString = sumOfCharactersOfTempString + (long)( actualText.charAt(indexJ) * Math.pow(127,patternToBeSearched.length()-1-count) );
            indexJ++;
        }
        if( sumOfCharactersOfTempString == sumOfCharactersOfPatternToBeSearched)
        locationIndex = indexI;
         
    }
    if(locationIndex != -1)
    System.out.println( "Pattern found at index " + locationIndex );
    else
    System.out.println( "Pattern not found" );
    }
}


<|start_filename|>Julia/sort/selection_sort.jl<|end_filename|>
# Julia program to implement Selection sort

function selection_sort(arr, n)
    for i in 1:n
        # Let the first element in this iteration be the minimum value
        min = i
        # Find the least element in the concerned part of the array
        for j in (i + 1):n
            if arr[min] > arr[j]
                min = j
            end
        end
        # Swap the least element with the beginning of the concerned part of the array
        arr[i], arr[min] = arr[min], arr[i]
    end
end



print("How many numbers do you want to sort? ")
n = readline()
n = parse(Int, n)
if (n <= 0)
    println("No numbers to sort!!!")
    exit()
end
arr = Int[]
print("Enter the numbers: ")
arr = [parse(Int, num) for num in split(readline())]
selection_sort(arr, n)
print("The numbers in sorted order is ")
print(arr)



"""
Time Complexity - O(n^2), where 'n' is the size of the array
Space Complexity - O(n)

SAMPLE INPUT AND OUTPUT

SAMPLE I
How many numbers do you want to sort? 5
Enter the numbers: 4 2 5 1 3
The numbers in sorted order is [1, 2, 3, 4, 5]

"""


<|start_filename|>C-Plus-Plus/search/TernarySearch.cpp<|end_filename|>
#include <bits/stdc++.h> 
using namespace std; 

//Recursive Approach: Time Complexity Is O(log3(N))
int ternarySearchRecursion(int l, int r, int key, int ar[]) 
{ 
	if (r >= l) { 
		// Find the mid1 and mid2 
		int mid1 = l + (r - l) / 3; 
		int mid2 = r - (r - l) / 3;
		
		// Check if key is present at any mid
		if (ar[mid1] == key) { 
			return mid1; 
		} 
		if (ar[mid2] == key) { 
			return mid2; 
		} 
		// Since key is not present at mid, 
        	// check in which region it is present 
	        // then repeat the Search operation 
	        // in that region 
		if (key < ar[mid1]) { 
			 // The key lies in between l and mid1 
			return ternarySearchRecursion(l, mid1 - 1, key, ar); 
		} 
		else if (key > ar[mid2]) { 
			// The key lies in between mid2 and r 
			return ternarySearchRecursion(mid2 + 1, r, key, ar); 
		} 
		else {
       	                // The key lies in between mid1 and mid2 
			return ternarySearchRecursion(mid1 + 1, mid2 - 1, key, ar); 
		} 
	} 
	// Key not found 
	return -1; 
} 

//Iterative Approach: Time Complexity Is O(log3(N))
int ternarySearchIterative(int l, int r, int key, int ar[])   
{ 
    while (r >= l) { 
	// Find the mid1 and mid2 
        int mid1 = l + (r - l) / 3; 
        int mid2 = r - (r - l) / 3; 
	 // Check if key is present at any mid
        if (ar[mid1] == key) { 
            return mid1; 
        } 
        if (ar[mid2] == key) { 
            return mid2; 
        } 
	// Since key is not present at mid, 
        // check in which region it is present 
        // then repeat the Search operation 
        // in that region 
        if (key < ar[mid1]) { 
	    // The key lies in between l and mid1 
            r = mid1 - 1; 
        } 
        else if (key > ar[mid2]) { 
	    // The key lies in between mid2 and r 
            l = mid2 + 1; 
        } 
        else { 
	    // The key lies in between mid1 and mid2 
            l = mid1 + 1; 
            r = mid2 - 1; 
        } 
    } 
    // Key not found 
    return -1; 
} 
int main() 
{ 
	int left, right, index, key; 	
	cout<<"Enter Number Of Elements in the array:\n";
	cin>>right;// length of array 
	int ar[right];
	cout<<"Enter The Elements In Array:\n";
	for(int i=0;i<right;i++){
	    cin>>ar[i];
	}
	left = 0;// Starting index 
	cout<<"Enter The Element To Be Searched:\n";
	cin>>key;// Key to be searched in the array 
	index = ternarySearchIterative(left, right, key, ar);// Search the key using Iterative Ternary Search
	cout << "Iterative Approach : Index of " << key << " is " << index << endl; 
	index = ternarySearchRecursion(left, right, key, ar); // Search the key using Recursive Ternary Search 
	cout << "Recursive Approach : Index of " << key << " is " << index << endl; 
} 
'''
Time Complexity : O(log3(N))
Sample I/O:
INPUT : 
Enter Number Of Elements in the array:
9
Enter The Elements In Array:
1 2 3 4 5 6 7 8 9 
Enter The Element To Be Searched:
5

OUTPUT : 
Iterative Approach : Index of 5 is 4
Recursive Approach : Index of 5 is 4
'''


<|start_filename|>C-Plus-Plus/other/SortColors-DutchNationalFlag.cpp<|end_filename|>
/*                  
PROBLEM STATEMENT- https://leetcode.com/problems/sort-colors/

Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
In simpler words sort an array containing 0,1,2.

Solve the problem with a one-pass algorithm using only O(1) constant space?

The bruteforce approach - Sort the vector in nlogn time

                                ************************DUTCH_NATIONAL_FLAG ALGORITHM***********************************
 */

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

void sortColors(vector<int> nums) {
        int n=nums.size();
        int low=0,med=0,high=n-1;
        int temp;
        while(med<=high){ 
            if(nums[med]==0){
                temp=nums[med];
                nums[med]=nums[low];
                nums[low]=temp;
                low++;
                med++;
            }
            else if(nums[med]==1){
                med++;
            }
            else{
                temp=nums[med];
                nums[med]=nums[high];
                nums[high]=temp;
                high--;
            }
        }
        for(int i=0;i<n;i++){
          cout<<nums[i]<<" ";
        }
    }

    int main(){
      vector<int >nums;
      int n,input;
      cin>>n;
      for(int i=0;i<n;i++){
          cin>>input;
          nums.push_back(input);
      }
      sortColors(nums);
    }

/*TEST CASE-
Input:
n=6
nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Input:
n=3
nums = [2,0,1]
Output: [0,1,2]

COMPLEXITY ANALYSIS-
      Time= O(N)
      space=O(1)
*/


<|start_filename|>C-Plus-Plus/ds/Stack_using_Array.cpp<|end_filename|>
/*
Implement the basic functionality of stack using Array Data structure
@author: Rishikeshrajrxl
@created: 17/08/2020
*/

#include <iostream>
using namespace std;

void Push();             //Function declaration
void Peek();           
void Pop();
void Is_Empty();
void Is_Full();
void Display();
void count();
int stack_size,top=0,stack[100];         

int main()              //Main() starts
{
int ch;
cout<<"ENTER THE STACK SIZE : ";     //taking stack size initally from the user.
cin>>stack_size;
cout<< "\n\n\t Implement the basic functionality of stack"<<endl;         //Displaying the Features in a tabular manner         
cout<<"\t **************************************************"<<endl;
do
{
cout<<"\t 1) Push\t \t 2) Pop "<<endl; 
cout<<"\t 3) Peek\t \t 4) Is_Empty"<<endl;
cout<<"\t 5) Is_Full\t \t 6) Display"<<endl;
cout<<"\t 7) count\t \t 8) Exit"<<endl;
cout<<"\t ***************************************************\nENTER YOUR CHOICE : ";
cin >>ch;
  switch(ch)
  {
    case 1:
    Push();
    break;

    case 2:
    Pop();
    break;

    case 3:
    Peek();
    break;

    case 4:
    Is_Empty();
    break;

    case 5:
    Is_Full();
    break;

    case 6:
    Display();
    break;

    case 7:
    count();
    break;
    
    case 8:
    exit(0);
    break;
    
    default:
    cout<<"Invalid Input. Please enter the Number between 1 to 8 \n"<<endl;
  }
}while(ch!=0);
    return 0;
}                       // Main() Ends
//--------------------------------------------------------------------------
void Push()             //Insertion at the top 
{
    int ele;
    if(top==stack_size){
        cout<<"Stack is Full."<<endl;
    }
    else{
        cout<<"ENTER THE ELEMENT :";
        cin>>ele;
        top+=1;
        stack[top]=ele;
        cout<<"Pushed Successfully"<<endl;
    }
}
//---------------------------------------------------------------------------
void Pop()                //deletion from the top
{
    if(top==0){
        cout<<"Stack is Empty"<<endl;
    }
    else{
        top=top-1;
        cout<<"Poped Successfully"<<endl;
    }
}
//---------------------------------------------------------------------------
void Peek()             //returns the value of the top
{
    if(top==0){
        cout<<"Stack is Empty"<<endl;
    }
    else{
        cout<<"Peek value is : "<<stack[top]<<endl;
    }
}
//-----------------------------------------------------------------------------
void Is_Full()          //returns Yes if Full, else No
{
    if(top==stack_size){
        cout<<"Yes"<<endl;
    }
    else{
        cout<<"No"<<endl;
    }
}
//-----------------------------------------------------------------------------
void Is_Empty()           //returns Yes if Empty, else No
{
    if(top==0){
        cout<<"Yes"<<endl;
    }
    else{
        cout<<"No"<<endl;
    }
}
//------------------------------------------------------------------------------

void Display()           //returns all the value inside the Stack
{
    cout<<"ELEMENT IN THE STACK : ";
    for(int i=top;i>0;i--)
    {
        cout<<stack[i]<<" ";
    }
    cout<<"\n";
}
//-------------------------------------------------------------------------------
void count()        //returns the length of stack 
{
    cout<<"Length of Stack : "<<top<<endl;
}


<|start_filename|>C-Plus-Plus/ds/CircularLinkedList.c<|end_filename|>
#include<stdio.h>
#include<conio.h>

void insertAtBeginning(int);
void insertAtEnd(int);
void insertAtAfter(int,int);
void deleteBeginning();
void deleteEnd();
void deleteSpecific(int);
void display();

struct Node
{
   int data;
   struct Node *next;
}*head = NULL;

void main()
{
   int choice1, choice2, value, location;
   clrscr();
   while(1)
   {
      printf("\n*********** MENU *************\n");
      printf("1. Insert\n2. Delete\n3. Display\n4. Exit\nEnter your choice: ");
      scanf("%d",&choice1);
      switch()
      {
         case 1: printf("Enter the value to be inserted: ");
         		 scanf("%d",&value);
                 while(1)
                 {
                 	printf("\nSelect from the following Inserting options\n");
                 	printf("1. At Beginning\n2. At End\n3. After a Node\n4. Cancel\nEnter your choice: ");
                    scanf("%d",&choice2);
                    switch(choice2)
                    {
                       case 1: 	insertAtBeginning(value);
                       		break;
                       case 2: 	insertAtEnd(value);
                       		break;
                       case 3: 	printf("Enter the location after which you want to insert: ");
                       		scanf("%d",&location);
                       		insertAfter(value,location);
                       		break;
                       case 4: 	goto EndSwitch;
                       default: printf("\nPlease select correct Inserting option!!!\n");
                    }
                 }
         case 2: while(1)
                 {
                 	printf("\nSelect from the following Deleting options\n");
                 	printf("1. At Beginning\n2. At End\n3. Specific Node\n4. Cancel\nEnter your choice: ");
                    scanf("%d",&choice2);
                    switch(choice2)
                    {
                       case 1: 	deleteBeginning();
                       		break;
                       case 2: 	deleteEnd();
                       		break;
                       case 3: 	printf("Enter the Node value to be deleted: ");
                       		scanf("%d",&location);
                       		deleteSpecic(location);
                       		break;
                       case 4:	goto EndSwitch;
                       default: printf("\nPlease select correct Deleting option!!!\n");
                    }
                 }
                 EndSwitch: break;
         case 3: display();
         	 break;
         case 4: exit(0);
         default: printf("\nPlease select correct option!!!");
      }
   }
}

void insertAtBeginning(int value)
{
    struct Node *newNode;
    newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode -> data = value;
    if(head == NULL)
    {
       head = newNode;
       newNode -> next = head;
    }
    else
    {
       struct Node *temp = head;
       while(temp -> next != head)
          temp = temp -> next;
       newNode -> next = head;
       head = newNode;
       temp -> next = head;
    }
    printf("\nInsertion success!!!");
}
void insertAtEnd(int value)
{
   struct Node *newNode;
   newNode = (struct Node*)malloc(sizeof(struct Node));
   newNode -> data = value;
   if(head == NULL)
   {
      head = newNode;
      newNode -> next = head;
   }
   else
   {
      struct Node *temp = head;
      while(temp -> next != head)
         temp = temp -> next;
      temp -> next = newNode;
      newNode -> next = head;
   }
   printf("\nInsertion success!!!");   
}
void insertAfter(int value, int location)
{
   struct Node *newNode;
   newNode = (struct Node*)malloc(sizeof(struct Node));
   newNode -> data = value;
   if(head == NULL)
   {      
      head = newNode;
      newNode -> next = head;
   }
   else
   {
      struct Node *temp = head;
      while(temp -> data != location)
      {
         if(temp -> next == head)
         {
            printf("Given node is not found in the list!!!");
            goto EndFunction;
         }
         else
         {
            temp = temp -> next;
         }
      }
      newNode -> next = temp -> next;
      temp -> next = newNode;
      printf("\nInsertion success!!!");
   }
   EndFunction:
}
void deleteBeginning()
{
   if(head == NULL)
      printf("List is Empty!!! Deletion not possible!!!");
   else
   {
      struct Node *temp = head;
      if(temp -> next == head)
      {
         head = NULL;
         free(temp);
      }
      else{
         head = head -> next;
         free(temp);
      }
      printf("\nDeletion success!!!");
   }
}
void deleteEnd()
{
   if(head == NULL)
      printf("List is Empty!!! Deletion not possible!!!");
   else
   {
      struct Node *temp1 = head, temp2;
      if(temp1 -> next == head)
      {
         head = NULL;
         free(temp1);
      }
      else{
         while(temp1 -> next != head){
            temp2 = temp1;
            temp1 = temp1 -> next;
         }
         temp2 -> next = head;
         free(temp1);
      }
      printf("\nDeletion success!!!");
   }
}
void deleteSpecific(int delValue)
{
   if(head == NULL)
      printf("List is Empty!!! Deletion not possible!!!");
   else
   {
      struct Node *temp1 = head, temp2;
      while(temp1 -> data != delValue)
      {
         if(temp1 -> next == head)
         {
            printf("\nGiven node is not found in the list!!!");
            goto FuctionEnd;
         }
         else
         {
            temp2 = temp1;
            temp1 = temp1 -> next;
         }
      }
      if(temp1 -> next == head){
         head = NULL;
         free(temp1);
      }
      else{
         if(temp1 == head)
         {
            temp2 = head;
            while(temp2 -> next != head)
               temp2 = temp2 -> next;
            head = head -> next;
            temp2 -> next = head;
            free(temp1);
         }
         else
         {
            if(temp1 -> next == head)
            {
               temp2 -> next = head;
            }
            else
            {
               temp2 -> next = temp1 -> next;
            }   
            free(temp1);
         }
      }
      printf("\nDeletion success!!!");
   }
   FuctionEnd:
}
void display()
{
   if(head == NULL)
      printf("\nList is Empty!!!");
   else
   {
      struct Node *temp = head;
      printf("\nList elements are: \n");
      while(temp -> next != head)
      {
         printf("%d ---> ",temp -> data);
      }
      printf("%d ---> %d", temp -> data, head -> data);
   }
}

<|start_filename|>C-Plus-Plus/cp/find_single _occuring_element.cpp<|end_filename|>
/*
 Given an array of N elements, where each element occurs twice except one.
 we can found that element with the help of Bitwise XOR operator.
 Bitwise operations are best because they perform the operation in least possible time.
*/

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

int single_occurs_element(int ar[], int N) {
	int x = 0;
	for (int i = 0; i < N; i++) {
		/*  we know how bitwise xor works that is
		bitwise xor of a number with itself is 0.
		bitwise xor of a number with 0 is number itself.
		so the single element will be in the x finally.
		*/
		x ^= ar[i];

	}
	return x;
}

int main() {
	cout << "Enter the size of the array : \n";
	int N;
	cin >> N;
	int ar[N + 1];
	cout << "Enter array elements :\n";
	for (int i = 0; i < N; i++) {
		cin >> ar[i];
	}
	int single_element = single_occurs_element(ar, N);
	cout << "Single occurring element in the array is : \n";
	cout << single_element << endl;

}

/*
Standard Input and Output

Enter the size of the array :
9
Enter array elements :
1 2 3 4 1 2 3 5 4

Single occurring element in the array is :
5

Time Complexity : O(N)
Space Complexity : O(1)
*/


<|start_filename|>C-Plus-Plus/math/Extended_Euclidean_Algorithm.cpp<|end_filename|>
#include <iostream>
#include <tuple>

using namespace std;

int gcd (int a, int b, int &x, int &y) 
{
	//base case
	if (a == 0) 
  {
		x = 0; y = 1;
		return b;
	}
	int x1, y1;
	int d = gcd (b % a, a, x1, y1);
	x = y1 - (b / a) * x1;
	y = x1;
	return d;
}

// Iterative version of Extended Euclidean algorithm

int gcd_iterative(int a, int b, int& x, int& y) {
    x = 1, y = 0;
    int x1 = 0, y1 = 1, a1 = a, b1 = b;
    while (b1) {
        int q = a1 / b1;
        tie(x, x1) = make_tuple(x1, x - q * x1);
        tie(y, y1) = make_tuple(y1, y - q * y1);
        tie(a1, b1) = make_tuple(b1, a1 - q * b1);
    }
    return a1;
}

int main()
{
    int x = 0, y = 0, a, b;
    cout<<"Enter the numbers whose GCD is to be found:"<<endl;
    cin>>a>>b;
	
    cout<<"GCD of "<<a<<" and "<<b<<" is:"<<endl;
    cout<<gcd(a, b, x, y)<<endl;
    cout<<"GCD (iterative method) is : "<<endl;
    cout<<gcd_iterative(a,b,x,y)<<endl;
    return 0;
}

/*
Input:
Enter the numbers whose GCD is to be found:
36
60

Output:
GCD of 36 and 60 is:
12
GCD (iterative method) is : 
12

Time Complexity: O(Log min(a, b))
Space Complexity: O(1)
*/


<|start_filename|>Julia/math/armstrong_number.jl<|end_filename|>
""" Julia program to Check if a number is an Armstrong Number or not.
An armstrong number is a number such that the sum of its digits each 
raised to the power of the number of digits.
"""

function check_armstrong(num)
    temp = num
    sum = 0
    cnt = floor(log10(num) + 1)
    while (temp > 0)
        rem = temp % 10
        sum = sum + (rem ^ cnt)
        temp = temp ÷ 10;
    end
    if(num == sum)
        return true
    else
        return false
    end
end


print("Enter the number: ")
num = readline()
num = parse(Int, num)
if(num < 0)
    println("The given number $num is not a Armstrong Number.")
    exit()
end
res = check_armstrong(num)
if res
    println("The given number $num is a Armstrong Number.")
else
    println("The given number $num is not a Armstrong Number.")
end


"""
Time Complexity: O(log(num)), where 'num' is the given number
Space Complexity: O(1)

SAMPLE INPUT AND OUTPUT

SAMPLE 1
Enter the number: 371
The given number 371 is a Armstrong Number.

SAMPLE 2
Enter the number: 1234
The given number 1234 is not a Armstrong Number.

"""


<|start_filename|>C/cryptography/railFenceCipher.c<|end_filename|>
/* The rail fence cipher (also called a zigzag cipher) is a form of transposition cipher.
   It derives its name from the way in which it is encoded. Given a plain-text message and a numeric key, it cipher the
   given text using Rail Fence algorithm(here key == 2). 
*/

#include<stdio.h>
#include<string.h>
  
void cipher(char input[100],int size){
   
  int i = 0;
  int count;
  char string [2][size]; 
  //This is where we cipher the text and store in the 2D array
    while( i < size ) {
    
         for ( count = 0 ; count < 2 ; count++ ) {
              string[count][i] = input[i];
              i++;
         }
    
    }
    //we store the plain text after cipher in this char array 
    char output[size];
    int k = 0;
    int b;
    //Concatenating all the charecters we stored row wise
    while( k < size ) {
  
         for( int a = 0 ; a < 2 ; a++ ) {
              b = a;       
              while( b < size ) { 
                  output[k] = string[a][b];
                  k++;
                  b = b+2;
    
              }
  
         }
  
    }
    printf( "Cipher :" );
    //Printing the cipher after the concatenation
    for( int c = 0; c < size ; c++ ) {
  
         if( output[c] != '\n' )  
             printf("%c", output[c] );
    
    }
}


int main( void ) {
  
  char input[100];
  printf( "Enter your plain text here :" );
  //we take the input here
  fgets( input , 100 , stdin );  
  int size = strlen( input );
    
  cipher(input,size);
  return 0;
} 
/*
 Sample I/O : 
   
 Enter your plain text here :Hello World
 Cipher :HloWrdel ol

 Time complexity  : O(n)  
 Space complexity : O(n)
 */


<|start_filename|>Julia/sort/bubble_sort.jl<|end_filename|>
"""Julia program to implement Bubble Sort
In Bubble Sort we compare the adjacent elements and swap them such that the greater
element among them comes in the right-side. After each iteration, one smallest element
goes towars the end of the array.
"""

function bubble_sort(arr, n)
    # Iterate the entire array
    for i in 1:n
        # Iterate till the concerned part only.
        for j in 1:(n-i)
            # Swap adjacent elements if they are in wrong order
            if(arr[j] > arr[j+1])
                arr[j], arr[j+1] = arr[j+1], arr[j]
            end
        end
    end
end
            

print("How many numbers do you want to sort? ")
n = readline()
n = parse(Int64, n)
if (n <= 0)
    println("No numbers to sort!!!")
    exit()
end
arr = Int[]
print("Enter the numbers: ")
arr = [parse(Int, num) for num in split(readline())]
bubble_sort(arr, n)
print("The numbers in sorted order is ")
print(arr)



"""
Time Complexity - O(n^2), where 'n' is the size of the array
Space Complexity - O(n)

SAMPLE INPUT AND OUTPUT

SAMPLE I
How many numbers do you want to sort? 5
Enter the numbers: 4 2 5 1 3
The numbers in sorted order is [1, 2, 3, 4, 5]

"""


<|start_filename|>C-Plus-Plus/other/majority_vote_algorithm.cpp<|end_filename|>
// The Boyer–Moore majority vote algorithm in C++
// This algorithm finds a majority element, if there is one: i.e, an element that occurs repeatedly for more than half of the elements of the input.

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

// To find majority element
int majority(int arr[], int arrsize) {
	int index = 0, count = 1;
	// finding num to check majority
	for (int i = 1; i < arrsize; i++) {
		if (arr[index] == arr[i])
			count++;
		else
			count--;
		if (count == 0) {
			index = i;
			count = 1;
		}
	}
	int num = arr[index];
	for (int i = 0; i < arrsize; i++)
		if (arr[i] == num)
			count++;
	// checking for majority
	if (count > arrsize / 2)
		return num;
	else
		return -1;
}

int main() {
	int n;
	cout << "Enter no of elements:";
	cin >> n;
	cout << "\nEnter elements: ";
	int arr[n];
	for (int i = 0; i < n; i++)
		cin >> arr[i];
	int result = majority(arr, n);
	if (result != -1)
		cout << "Majority of a sequence is " << result << endl;
	else
		cout << "There is no majority \n";
	return 0;
}

/*input/output:
 Enter no of elements:5
 Enter elements: 1 1 1 1 2
 Majority of arr sequence is 1

 Enter no of elements:5
 Enter elements: 1 2 3 2 4
 There is no Majority.

 Time complexity : O(n)
 Space complexity: O(1)
 */


<|start_filename|>C/cp/SudukoSolver.c<|end_filename|>
/**
A backtracking algorithm to solve 9X9 suduko
0's in the input are treated empty cells
Assumption : Given configuration is correct
**/

#include <stdio.h>
#include <stdbool.h>

#define N 9

void display(int board[N][N]){
  for(int i = 0; i < N; i++){
    for(int j = 0; j < N; j++){
      printf("%d ", board[i][j]);
    }
    printf("\n");
  }
}

// backtracking soln
bool solve(int board[N][N], int i, int j, 
  bool rows[N][N], bool cols[N][N], bool boxes[N][3][3]) {
    
    if(i == 9)
      return true;
      
    if(board[i][j] == 0) {
        
      for(int k=0; k<9; k++) {
          
        if(rows[k][i] == false && cols[k][j] == false
          && boxes[k][i/3][j/3] == false) {
            board[i][j] = k+1;
            rows[k][i] = true;
            cols[k][j] = true;
            boxes[k][i/3][j/3] = true;
              
            if(solve(board, i+j/8, (j+1)%9, rows, cols, boxes))
              return true;
              
            board[i][j] = 0;
            rows[k][i] = false;
            cols[k][j] = false;
            boxes[k][i/3][j/3] = false;
          }
      }
      
      return false;
    } else
      return solve(board, i+j/8, (j+1)%9, rows, cols, boxes);
  }

void solveSudoku(int board[N][N], int x, int y) {
  // write yopur code here
  bool rows[N][N], cols[N][N], boxes[9][3][3];

  // intialization
  for(int i=0; i<N; i++)
    for(int j=0; j<N; j++) {
      rows[i][j] = false;
      cols[i][j] = false;
    }

  // intialization
  for(int i=0; i<N; i++)
    for(int j=0; j<3; j++)
      for(int k=0; k<3; k++)
        boxes[i][j][k] = false;
  
  for(int i=0; i<9; i++)
    for(int j=0; j<9; j++)
      if(board[i][j] != 0) {
        int num = board[i][j]-1;
        rows[num][i] = true;
        cols[num][j] = true;
        boxes[num][i/3][j/3] = true;
      }
      
  solve(board,0,0,rows,cols,boxes);
  display(board);
}

int main() {
  int arr[N][N];

  // taking input
  for (int i = 0; i < 9; i++)
    for (int j = 0; j < 9; j++)
      scanf(" %d", &arr[i][j]);

  solveSudoku(arr, 0, 0);
  return 0;
}

/**
Input :
3 0 6 5 0 8 4 0 0
5 2 0 0 0 0 0 0 0
0 8 7 0 0 0 0 3 1
0 0 3 0 1 0 0 8 0
9 0 0 8 6 3 0 0 5
0 5 0 0 9 0 6 0 0
1 3 0 0 0 0 2 5 0
0 0 0 0 0 0 0 7 4
0 0 5 2 0 6 3 0 0
Output :
3 1 6 5 7 8 4 9 2 
5 2 9 1 3 4 7 6 8 
4 8 7 6 2 9 5 3 1 
2 6 3 4 1 5 9 8 7 
9 7 4 8 6 3 1 2 5 
8 5 1 7 9 2 6 4 3 
1 3 8 9 4 7 2 5 6 
6 9 2 3 5 1 8 7 4 
7 4 5 2 8 6 3 1 9 
Space Complexity : O(1)
Time Complexity : O(1)
The size of input is fixed, so the complexity does not change
**/

<|start_filename|>JavaScript/sort/insertion_sort.js<|end_filename|>
/*
What is Insertion Sort?
Insertion sort is a method of sorting an array by dividing the array into a 'sorted' portion and 'unsorted' portion. Then we compare the unsorted item to see if it is larger than the previous element, if not we insert the new item. Basically we are looking from left to right and sorting as we go.

Let's start building our insertionSort function.

-----------------------------------------------------------------------------------
|                ALGORITHM                                                         |
|        Step 1 − If it is the first element, it is already sorted. return 1;              |
|        Step 2 − Pick next element                                                        |
|        Step 3 − Compare with all elements in the sorted sub-list                         |
|        Step 4 − Shift all the elements in the sorted sub-list that is greater than the   |
|                 value to be sorted                                                       |
|        Step 5 − Insert the value                                                         |
|        Step 6 − Repeat until list is sorted                                              |
|                                                                                  |
-----------------------------------------------------------------------------------


*/

const insertionSort = (arr) => {
  const len = arr.length;
  for (let i = 0; i < len; i++) {
    let el = arr[i];
    let j;

    for (j = i - 1; j >= 0 && arr[j] > el; j--) {
      arr[j + 1] = arr[j];
    }
    arr[j + 1] = el;
  }
  return arr;
};

console.log(insertionSort([1, 3, 4, 1, 2]));


<|start_filename|>Java/cryptography/SimpleColumnarTranspositionWithMultipleRoundsCipher.java<|end_filename|>
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.ListIterator;
import java.util.Scanner;

/**
 * <h1>Columnar</h1>
 * <p>
 * Columnar class acts as a custom Data Structure which consits of a List of Characters.
 * </p>
 */
class Columnar
{
    List<Character> characterList;
}

/**
 * <h1>Simple Columnar Transposition Cipher With Multiple Rounds</h1>
 * <p>
 * To Implement Simple Columnar Transposition Cipher With Multiple Rounds
 * </p>
 * <b>Description</b>
 * <p>
 * class SimpleColumnarTranspositionWithMultipleRoundsCipher is used to encrypt plainText to cipherText using Columnar
 * Transposition and decrypt cipherText to plainText using the respective algorithm, Simple Columnar Transposition is a
 * variation of Transposition technique just like Rail Fence Cipher
 * </p>
 * <b>Requirements</b>
 * <p>
 * A string plain text and a string key are required for encryption and for decryption the cipher text which is
 * calculated from the given key and the key itself.
 * </p>
 */
public class SimpleColumnarTranspositionWithMultipleRoundsCipher
{
    /**
     * <p>
     * This is a private method used to validate the key provided by the user.
     * </p>
     * <b>Validation Scheme</b>
     * <p>
     * There must be NO occurance of repetative characters in a string, occurance of repetative characters can lead to
     * malfunctioning of the code and algorithm leading to mismatched output.
     * </p>
     * <p>
     * Thou same letters with different cases(UpperCase and LowerCase) can be accepted.
     * </p>
     * <p>
     * Example: AaZ can be a valid key, but AAZ will not be considered as a valid key.
     * </p>
     * 
     * @param key This is a String parameter to validateKey method, this signifies key which is passed to perform encryption
     *            and decryption.
     * 
     * @return Boolean Tells whether the key entred is a valid key or not
     */
    private Boolean validateKey(String key)
    {
        for (int i = 0; i < key.length() - 1; i++)
        {
            for (int j = i + 1; j < key.length(); j++)
            {
                // An occurance of same character in key found.
                if (key.charAt(i) == key.charAt(j))
                {
                    return false;
                }
            }
        }
        // No occurance of same character in key found.
        return true;
    }
    
    /**
     * <p>
     * This is a public method which is used to encrypt plain text using Simple Columnar Transposition With Multiple Rounds
     * technique.
     * </p>
     *
     * <b>Process</b>
     * <ul>
     * <li>The plain text is placed row-wise in the columnar table</li>
     * <li>According to the ascending order of the characters in key, its particular column is fetched and appended in
     * cipher text</li>
     * <li>This process is repeated numberOfRounds times, after first round the plain text becomes the cipher text
     * PLAIN_TEXT(n)=CIPHER_TEXT(n-1)</li>
     * </ul>
     * 
     * @param plainText      This is a String parameter to encrypt method, this signifies plain text which is passed.
     * @param key            This is a String parameter to encrypt method, this signifies key which is passed to encrypt
     *                       plainText.
     * @param numberOfRounds This is an Integer parameter to encrypt method, this signifies total number of rounds needed to
     *                       be performed
     * 
     * @return String This returns the cipherText.
     */
    String encrypt(String plainText, String key, Integer numberOfRounds)
    {
        StringBuilder cipherText = new StringBuilder("");// used to store cipher text
        
        // Iterates until i reaches numberOfRound
        for (int numberOfRound = 1; numberOfRound <= numberOfRounds; numberOfRound++)
        {
            cipherText = new StringBuilder("");// Re-initializing cipherText
            
            Columnar[] columnars   = new Columnar[key.length()];// used to store plainText in columnar sequence given by algorithm
            Integer    columnIndex = 0;                         // used to store current column index of columnars
            
            // Initializing columnars
            for (int i = 0; i < key.length(); i++)
            {
                columnars[i] = new Columnar();
                columnars[i].characterList = new ArrayList<Character>();
            }
            
            // Iterates through plainText and stores its characters in a columnar sequence given by the algorithm
            for (int i = 0; i < plainText.length(); i++)
            {
                // It the value of columnIndex reaches to its peak then it is reassigned its value to 0, to start from a new row
                if (columnIndex == key.length())
                {
                    columnIndex = 0;
                }
                
                // Adds plainText character to columnars
                columnars[columnIndex].characterList.add(plainText.charAt(i));
                
                // Incrementes the value of columnIndex by 1
                columnIndex++;
            }
            
            // sorts the characters in key in ascending order and stores it in sortedKey
            char[] keyArray = key.toCharArray();
            Arrays.sort(keyArray);
            String sortedKey = new String(keyArray);
            
            // Iterates through the columnars
            for (int i = 0; i < key.length(); i++)
            {
                char                    currentChar             = sortedKey.charAt(i);               // used to store the current character in sorted key
                int                     indexOfCurrentCharInKey = key.indexOf(currentChar);          // used to store the index of currentChar in key
                Columnar                columnar                = columnars[indexOfCurrentCharInKey];// used to get Columnar at position indexOfCurrentCharInKey
                List<Character>         characterList           = columnar.characterList;            // used to store the List of Characters in columnar
                ListIterator<Character> characterListIterator   = characterList.listIterator();      // used as an iterator for characterList
                
                // Iterates through characterList
                while (characterListIterator.hasNext())
                {
                    // Appends plainText characters which were stored in columnars column wise
                    cipherText.append(characterListIterator.next());
                }
            }
            // PLAIN_TEXT(n)=CIPHER_TEXT(n-1)
            plainText = cipherText.toString();
        }
        
        // cipher text is retured
        return cipherText.toString();
    }
    
    /**
     * <p>
     * This is a public method which is used to decrypt cipher text using Simple Columnar Transposition With Multiple Rounds
     * technique.
     * </p>
     *
     * <b>Process</b>
     * <ul>
     * <li>As the length of cipher text and plain text is the same, we first create a placeholder columnar for getting an
     * idea of the size of each column</li>
     * <li>Arranging cipherText characters in columnar according to the size of the column</li>
     * <li>Iterating through columnar row-wise and appending each character in plain text</li>
     * <li>This process is repeated numberOfRounds times, after first round the cipher text becomes the plain text
     * CIPHER_TEXT(n)=PLAIN_TEXT(n-1)</li>
     * </ul>
     * </ul>
     * 
     * @param cipherText     This is a String parameter to decrypt method, this signifies cipher text which is passed.
     * @param key            This is a String parameter to decrypt method, this signifies key which is passed to decrypt
     *                       cipherText.
     * @param numberOfRounds This is an Integer parameter to encrypt method, this signifies total number of rounds needed to
     *                       be performed
     * 
     * @return String This returns the plainText.
     */
    String decrypt(String cipherText, String key, Integer numberOfRounds)
    {
        StringBuilder plainText = new StringBuilder("");
        
        for (int numberOfRound = 1; numberOfRound <= numberOfRounds; numberOfRound++)
        {
            plainText = new StringBuilder("");// used to store plain text
            
            Columnar[] columnars             = new Columnar[key.length()];// used to store columnar
            Columnar[] columnarsForPlacement = new Columnar[key.length()];// used as a placeholder/template for columnars
            Integer    columnIndex           = 0;                         // used to store column index in columnars
            Integer    indexForCharacter     = 0;                         // used to store index of character in cipherText
            
            // sorts the characters in key in ascending order and stores it in sortedKey
            char[] keyArray = key.toCharArray();
            Arrays.sort(keyArray);
            String sortedKey = new String(keyArray);
            
            // Initializing columnars and columnarsForPlacement
            for (int i = 0; i < key.length(); i++)
            {
                columnars[i] = new Columnar();
                columnars[i].characterList = new ArrayList<Character>();
                columnarsForPlacement[i] = new Columnar();
                columnarsForPlacement[i].characterList = new ArrayList<Character>();
            }
            
            // Creating a placeholder for getting an idea of size of column
            for (int i = 0; i < cipherText.length(); i++)
            {
                if (columnIndex == key.length())
                {
                    columnIndex = 0;
                }
                columnarsForPlacement[columnIndex].characterList.add('*');
                columnIndex++;
            }
            
            // Arranges cipherText characters according to the columnar algorithm sequence
            for (int i = 0; i < key.length(); i++)
            {
                Character               currentKeyCharacter   = sortedKey.charAt(i);                    // used to store current character in sorted key
                Integer                 indexForColumnar      = key.indexOf(currentKeyCharacter);       // used to store index of currentKeyCharacter in key
                Columnar                columnarPlaceholder   = columnarsForPlacement[indexForColumnar];// used to store Columnar at position indexForColumnar
                List<Character>         characterList         = columnarPlaceholder.characterList;      // used to store List of Characters in columnarsForPlacement
                ListIterator<Character> characterListIterator = characterList.listIterator();           // used as an iterator for characterList
                // Iterates through characterList
                while (characterListIterator.hasNext())
                {
                    // Adds a character in cipherText at indexForCharacter to characterList
                    columnars[indexForColumnar].characterList.add(cipherText.charAt(indexForCharacter));
                    // Iterates over to the next element in characterListIterator
                    characterListIterator.next();
                    // Incrementes the value of indexForCharacter by 1
                    indexForCharacter++;
                }
            }
            
            // Keeps a counter of key index
            Integer keyIndex = 0;
            
            // Iterates through cipherText
            for (int i = 0; i < cipherText.length(); i++)
            {
                // If keyIndex reaches its maximum possible limit(length of key) then it is assigned 0
                if (keyIndex >= key.length())
                {
                    keyIndex = 0;
                }
                
                Columnar        columnar      = columnars[keyIndex];   // used to store Columnar of columnars at index keyIndex
                List<Character> characterList = columnar.characterList;// used to store List of Characters in columnar
                
                if (!characterList.isEmpty())
                {
                    // appends characters at 0th position to plainText
                    plainText.append(characterList.get(0));
                    // removes the 0th character in characterList which makes it self iterative and saves space
                    characterList.remove(0);
                }
                
                // Increments keyIndex by 1
                keyIndex++;
            }
            // CIPHER_TEXT(n)=PLAIN_TEXT(n-1)
            cipherText = plainText.toString();
        }
        // plain text is retured
        return plainText.toString();
    }
    
    /**
     * This is the main method which makes use of the following methods:
     * <ul>
     * <li>encrypt</li>
     * <li>decrypt</li>
     * </ul>
     * 
     * And uses the following objects of types:
     * <ul>
     * <li>java.util.Scanner</li>
     * <li>SimpleColumnarTranspositionWithMultipleRoundsCipher</li>
     * </ul>
     * 
     * @param args not used
     */
    public static void main(String[] args)
    {
        
        String                                              key;                                                // Created an object of String class for storing key to be entered
                                                                                                                // by the user
        String                                              plainText;                                          // Create an object of String class for storing plain text to be
                                                                                                                // entered by the user
        Integer                                             numberOfRounds;                                     // Creates an object of Integer class for storing number of rounds
                                                                                                                // needed to be performed
        Scanner                                             scan = new Scanner(System.in);                      // Created an object of Scanner class for asking for user input.
        SimpleColumnarTranspositionWithMultipleRoundsCipher simpleColumnarTranspositionWithMultipleRoundsCipher;// Created an object of
                                                                                                                // SimpleColumnarTranspositionWithMultipleRoundsCipher for
                                                                                                                // accessing it's method for encryption and decryption
        simpleColumnarTranspositionWithMultipleRoundsCipher = new SimpleColumnarTranspositionWithMultipleRoundsCipher();
        
        // Asking user to enter plain text
        System.out.println("Please Enter Plain Text:");
        plainText = scan.nextLine();
        
        // Asking user to enter String key
        System.out.println("Please Enter Key:");
        key = scan.next();
        
        // Asking user to enter number of rounds needed to be performed
        System.out.println("Please Enter Number Of Rounds:");
        numberOfRounds = scan.nextInt();
        
        // Checks if the key entered is valid or not
        Boolean keyValidationStatus = simpleColumnarTranspositionWithMultipleRoundsCipher.validateKey(key);
        
        // If the key entered by the user is valid
        if (keyValidationStatus)
        {
            // Accessing method 'encrypt' of SimpleColumnarTranspositionWithMultipleRoundsCipher class to encrypt plainText by key
            // and numberOfRounds
            String cipherText = simpleColumnarTranspositionWithMultipleRoundsCipher.encrypt(plainText, key, numberOfRounds);
            // Printing cipher text
            System.out.println("Cipher Text: " + cipherText);
            
            // Accessing method 'decrypt' of SimpleColumnarTranspositionWithMultipleRoundsCipher class to decrypt cipherText by key
            // and numberOfRounds
            String decryptedText = simpleColumnarTranspositionWithMultipleRoundsCipher.decrypt(cipherText, key, numberOfRounds);
            // Printing decrypted text
            System.out.println("Decrypted Text: " + decryptedText);
        }
        // If the key entered by the user is not valid
        else
        {
            // Printing error message
            System.out.println("An Occurance of repetative characters in key is found, please enter unique characters");
        }
        
        // Closing the Scanner object scan
        scan.close();
    }
}
/*
 * Please Enter Plain Text:
 * 
 * Attack Alice's troops at 5:00 PM today
 * 
 * Please Enter Key:
 * 
 * ATCK13pa
 * 
 * Please Enter Number Of Rounds:
 * 
 * 3
 * 
 * Cipher Text: ac0tpkdlMAatA 0aciys5 o rP:'tesot to
 * 
 * Decrypted Text: Attack Alice's troops at 5:00 PM today
 */

<|start_filename|>Java/other/Palindrome.java<|end_filename|>
import java.util.*;

/*
A program to check whether a string is palindrome or not.
A plaindrome string is a string which is same to its reverse.
eg. 1234321, radar etc.
Time Complexity = O(n/2) //represents the number of operations to be performed by an algorithm to complete its task
Space Complexity = O(n) //represents the total space needed by the algorithm
*/

public class Palindrome {

    private static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) {

        //the string entered by the user is stored in string_1
        System.out.println("Kindly enter the string: ");
        String string_1 = sc.nextLine();

        //to check if the string is palindrome or not
        Boolean check = ispalindrome(string_1);

        if(check==true)
            System.out.println(string_1+" is a palindrome.");
        else
            System.out.println(string_1+" is not a palindrome.");
    }

    //method to check if the string is a palindrome or not
    //method returns true if the string is a palindrome else it returns false
    private static boolean ispalindrome(String string_1) 
    {
        //storing the last index of the string in n
        int n =string_1.length() - 1;
        //comparing the characters of the string
        //first to the end and so on
        for (int i = 0; i < (n) / 2; i++) 
        {
           if (string_1.charAt(i) != string_1.charAt(n-i)) 
               return false;
        }
        return true; 
    }
}

/*
Output:

Kindly enter the string: 
1234321
1234321 is a palindrome.

Kindly enter the string: 
radar
radar is a palindrome.

Kindly enter the string: 
lol
lol is a palindrome.

Kindly enter the string: 
good
good is not a palindrome.

*/



<|start_filename|>C-Plus-Plus/cryptography/VernamCipher.cpp<|end_filename|>
/* Vernam Cipher

Vernam Cipher is a symmetric key cryptographic algorithm and is one of the transposition technique that converts plain text into ciphertext.
In this algorithm the size of the key and plain text must be same. */


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

string encrypt(string plain,string key){
  string enc="";
  int n=key.length();
  for(int i=0;i<n;i++){
    int y = plain[i]+key[i]-130;
    if(y>=26) {
      y = y-26;
    }
    enc+=char(y+65);
  }
  return enc;
}

string decrypt(string enc,string key){
  string dec="";
  int n=enc.length();
  for(int i=0;i<n;i++){
    if(enc[i]>=key[i]){
      dec+=char(enc[i]-key[i]+65);
    }
    else{
      dec+=char(enc[i]-key[i]+91);  
    }
  }
  return dec;
}

int main(){
  string plain,encrypted,decrypted,key;
  cout<<"USE UPPERCASE LETTERS"<<endl;
  cout<<"Enter the Key: ";
  cin>>key;
  transform(key.begin(), key.end(), key.begin(), ::toupper);

  cout<<"\nEnter the plain text of same size as that of key: ";
  cin>>plain;
  transform(plain.begin(), plain.end(), plain.begin(), ::toupper);
	
  int n=key.length();
  if(plain.length()<key.length()){
    cout<<"Invalid";
    return 0;
  }
	
  encrypted = encrypt(plain,key);
  cout<<"\nCipher text: "<<encrypted<<endl;
	
  decrypted = decrypt(encrypted,key);
  cout<<"Decrypted text: "<<decrypted<<endl;	
}


/* Output
USE UPPERCASE LETTERS
Enter the Key: TESSERACTCODING

Enter the plain text of same size as that of key: OPENSOURCESTART

Cipher text: HTWFWFUTVGGWIEZ
Decrypted text: OPENSOURCESTART */


<|start_filename|>C-Plus-Plus/search/Unbounded_Binary_Search.cpp<|end_filename|>
/*
Given a function ‘int f(unsigned int x)’ which takes a non-negative integer ‘x’ 
as input and returns an integer as output. The function is monotonically increasing 
with respect to value of x, i.e., the value of f(x+1) is greater than f(x) for every 
input x. Find the value ‘n’ where f() becomes positive for the first time.
Since f() is monotonically increasing, values of f(n+1), f(n+2),… must be positive and 
values of f(n-2), f(n-3), .. must be negative.
*/
#include<bits/stdc++.h> 
using namespace std; 

int binarySearch(int low, int high); 

// Let's take an example function 
// f(x) = x^2 - 10*x - 20 
int function(int x) 
{ 
	return (x*x - 10*x - 20);
} 

int findFirstPositive() 
{ 
	if (function(0) > 0) 
		return 0; 

	int i = 1; 
	while (function(i) <= 0) 
		i = i*2; 

	return binarySearch(i/2, i); 
} 

int binarySearch(int low, int high) 
{ 
	if (high >= low) 
	{ 
		int mid = low + (high - low)/2;

		if (function(mid) > 0 && (mid == low || function(mid-1) <= 0)) 
			return mid; 

		if (function(mid) <= 0) 
			return binarySearch((mid + 1), high); 
		else 
			return binarySearch(low, (mid -1)); 
	} 
	return -1; 
} 
/* Driver code */
int main() 
{ 
	cout<<"The value n where function() becomes positive first is "<< findFirstPositive(); 
	return 0; 
} 
/*
SAMPLE OUTPUT:

Input : x^2 - 10*x - 20
Output : The value n where function() becomes positive first is 12

Time Conplexity:O(log n)
Space Complexity:O(1)
*/



<|start_filename|>Java/other/RecursionCount.java<|end_filename|>
import java.util.Scanner;

public class RecursionCount {

    public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter first string:");
        String str1 = scanner.nextLine();
        System.out.println("Enter second string:");
        String str2 = scanner.nextLine();
        scanner.close();

        System.out.println("Number of occurrences of \"" + str2 + "\" in \"" + str1 + "\":" + countSubstring(str1, str2));
    }

    static int countSubstring(String str1, String str2) {
        // recursive function
        if(str1.contains(str2)) {
            return 1 + countSubstring(str1.replaceFirst(str2, ""), str2);
        } else {
            return 0;
        }
    }
}
/*
* Sample input/output:
* Enter first string:
* abcdabc
* Enter second string:
* abc
* Number of occurrences of "abc" in "abcdabc":2
*
* Time complexity: O(n)
*/


<|start_filename|>Java/other/LastDigitFibonacci.java<|end_filename|>
//Java Code to find the last digit of nth fibonacci number

import java.io.* ;
import java.util.* ;

public class LastDigitFibonacci {

  public static void main(String[] args) {

    //dynamic input
    Scanner sc = new Scanner(System. in );
    System.out.println("Input:\n");
    System.out.println("Enter the value of N\n");
    //long used to hold large value of N
    long N = sc.nextLong();
    //On observing,we can find the repitition of last digit after 60
    //precomputed an array of size 60 and stored fibonacci respectively
    int f[] = new int[60];
    f[0] = 0;   //setting value of Oth index of f[] to 0
    f[1] = 1;   //setting value of 1th index of f[] to 1
    for (int i = 2; i < 60; i++) {
      //adding the previous and next previous elements mod 10 and storing it in present index
      //thus the last digit after adding is stored in f[i] 
      f[i] = (f[i - 2] + f[i - 1]) % 10;
    }
    System.out.println("Output:\n");
    System.out.println("The last digit of " + N + "th fibonaci is " + f[(int)(N % 60L)]);

  }
}

/*
  Input:
  Enter the value of N 
  67
  Output:
  The last digit of 67th fibonacci is 3
  
  Time Complexity: O(1)
  Space Complexity:O(1)
*/


<|start_filename|>C-Plus-Plus/ds/Maximum_Width_BinaryTree.cpp<|end_filename|>
// C++ Program to find Maximum Width of Binary Tree

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

struct Node
{
    int data;
    Node* left;
    Node* right;
};

// function to create a new Tree Node
Node* newNode(int val)
{
    Node* temp = new Node;
    temp->data = val;
    temp->left = NULL;
    temp->right = NULL;
    
    return temp;
}

// Function to Build Tree
Node* buildTree(string str)
{   
    // Corner Case
    if(str.length() == 0 || str[0] == 'N')
            return NULL;
    
    // Creating vector of strings from input 
    // string after spliting by space
    vector<string> v;
    istringstream iss(str);
    for(string str; iss >> str; )
        v.push_back(str);
        
    // Create the root of the tree
    Node* root = newNode(stoi(v[0]));
        
    // Push the root to the queue
    queue<Node*> queue;
    queue.push(root);
        
    // Starting from the second element
    int i = 1;
    while(!queue.empty() && i < v.size()) {
        
        // Get and remove the front of the queue
        Node* currNode = queue.front();
        queue.pop();
            
        // Get the current node's value from the string
        string currVal = v[i];
            
        // If the left child is not null
        if(currVal != "N") {
         
            // Create the left child for the current node
            currNode->left = newNode(stoi(currVal));
                
            // Push it to the queue
            queue.push(currNode->left);
        }
            
        // For the right child
        i++;
        if(i >= v.size())
            break;
        currVal = v[i];
            
        // If the right child is not null
        if(currVal != "N") {
                
            // Create the right child for the current node
            currNode->right = newNode(stoi(currVal));
                
            // Push it to the queue
            queue.push(currNode->right);
        }
        i++;
    }
    
    return root;
}

/* Function to get the maximum width of a binary tree*/
// follows level order traversal
int getMaxWidth(Node* root)
{
    
   int i,count,res=0;
   
    if(root == NULL) // If root is NULL
    return 0;
    
     //Create queue of nodes
    queue<Node*>q;  
    // Pushing root in queue
    q.push(root);   
    
    while(q.empty()==false)
    { 
        // Count size of queue
        count=q.size();
        
        // Calculate maximum width
        res=max(res,count);  
        
        for(i=0;i<count;i++) 
        {
            // Get and remove the front of the queue
            Node *curr = q.front();
            q.pop();
            
            // If the left child is not null
            if(curr->left!=NULL)
            {
             // Push it to the queue
              q.push(curr->left);
            }
            
            // If the right child is not null
            if(curr->right!=NULL)
            {
             // Push it to the queue
              q.push(curr->right);
            }
        }
   }

   return res;
}

int main()
{
        string s;
        getline(cin, s);
        Node* root = buildTree(s);
        // maximum width
        cout << getMaxWidth(root);
   
    return 0;
}

/* Test Cases
  
Input: 1 2 3 4 5 6 7
Output: 4

Input: 1 2 3 N N 4 6 N 5 N N 7 N
Output: 2

Time Complexity:  O(N) where N is the total number of nodes in the tree.
Space Complexity: O(w) where w is the maximum width of the tree.

*/


<|start_filename|>Java/sort/OptimizedBubbleSort.java<|end_filename|>
/**
 * Optimized Bubble Sort Algorithm
 *
 * In optimized version of bubble sort algorithm we keep track of an extra variable inside the
 * inner loop to check if there was even a single swap if in an iteration of outer loop no elements
 * were swapped in inner loop this means that array is sorted and any extra running of outer loop is
 * redundant.
 *
 * @author [<NAME>](https://github.com/Lakhan-Nad)
 */

import java.util.Scanner;

public class OptimizedBubbleSort {
  /**
   * A main function to test the algorithm
   * 
   * Example Input: 2, 11, 5, -1, 0, 10, 20, 2, 8, 56, -34
   * Ouput: -34, -1, 0, 2, 2, 5, 8, 10, 11, 20, 56
   *
   * @param args the input arguments
   */
  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter size of array: ");
    int n = scan.nextInt();
    int[] array = new int[n];
    System.out.println("Enter elements of array");
    for(int i = 0; i < n; i++){
      array[i] = scan.nextInt();
    }
    bubbleSort(array);
    for (int i = 0; i < n; i++) {
      System.out.print(array[i] + " ");
    }
  }

  /**
   * Implementation of optimized bubble sort
   *
   * @param arr the array to sort
   */
  public static void bubbleSort(int[] arr) {
    /* extra variable to see maintain if swap was done */
    boolean swapped;
    int n = arr.length;
    for (int i = 0; i < n - 1; i++) {
      /* At start of outer loop make it false */
      swapped = false;
      for (int j = 0; j < n - i - 1; j++) {
        if (arr[j] > arr[j + 1]) {
          swap(arr, j, j + 1);
          /* Even if a single swap occurs during inside loop make it true */
          swapped = true;
        }
      }
      /* If no swap occurred this variable is false and we can end our iterations */
      if (!swapped) {
        break;
      }
    }
  }

  /**
   * A utility to swap elements
   *
   * @param array the array whose elements need to be swapped
   * @param i first index to swap
   * @param j second index to swap
   */
  public static void swap(int[] array, int i, int j) {
    int temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
}


<|start_filename|>Java/sort/CombSort_implementation.java<|end_filename|>
/*
    Comb Sort is a relatively simple sorting algorithm. It is an improvement over Bubble sort
    by using gap of size more than 1. The gap starts with a large value and starts shrinking by
    1.3 in every iteration until it reaches the value 1.
    You can check out more about this Sorting Algorithm here:- https://en.wikipedia.org/wiki/Comb_sort
*/

import java.util.Scanner;

public class CombSort_implementation {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the size of the array:- ");
        int n = input.nextInt();

        int arr[] = new int[n];
        System.out.println("Enter the elements of the array:- ");
        
        for(int i =0; i<n; i++){
            arr[i] = input.nextInt();
        }

        comb_sort(arr);

        System.out.println("\nSorted Array is:- ");
        for(int i = 0; i<n; i++){
            System.out.print(arr[i] + " ");
        }
    }

    //Method to swap two elements of an Array
    public static void swap_elements_in_array(int idx_1, int idx_2, int arr[]){
        int temp;
        temp = arr[idx_1];
        arr[idx_1] = arr[idx_2];
        arr[idx_2] = temp;
    }

    public static void comb_sort(int arr[]){
        int gap = arr.length;
        //A flag is use to check whether the elements of the array in a gap are sorted or not.
        boolean flag = true;
        while(gap != 1 || flag){
            //Dividing size of gap in every iteration by 1.3
            gap = (int)Math.floor(gap/1.3);
            if(gap < 1){
                gap = 1;
            }
            flag = false;

            for(int i = 0; i <= arr.length-gap-1; i++){
                if(arr[i] > arr[i+gap]){
                    swap_elements_in_array(i, i+gap, arr);
                    flag = true;
                }
            }
        }
    }
}

/*
    Time Complexity:- Best Case - O(n*logn)
                      Average Case:- O(n^2/2^P) where P is no of increments
                      Worst Case:- O(n^2) like Bubble Sort
    
    Space Complexity:- O(1)
*/

/*
    Sample Testcase:-
    Enter the size of array:-
    6
    Enter the elements of the array:-
    12 3 5 23 17 10
    Sorted Array is:-
    3 5 10 12 17 23
*/

<|start_filename|>C-Plus-Plus/graphs/inorder-traversal.cpp<|end_filename|>
/*
*   Author: <NAME>
*   Date: 27/06/2020
*   Summary: Inorder traversal of a tree;
*/

#include <iostream>
using namespace std;


/*
*   Create structure of a node
*/
struct node 
{ 
    int data; 
    struct node *left, *right; 
}; 
   
/*
*   A utility function to create a new node
*/
struct node *newNode(int item) 
{ 
    struct node *temp = new node; 
    temp->data = item; 
    temp->left = temp->right = NULL; 
    return temp; 
};

/*
*   Add a new node in the tree
*/
struct node * insert(struct node *root, int element)
{
    if(root == NULL)
        return newNode(element);
    if(root->data > element)
        root->left = insert(root->left, element);
    else if (root->data < element)
        root->right = insert(root->right, element); 
    return root;
}

/*
*   Make inorder traverse of the tree
*/
void inorder(struct node *root)
{
    if(root == NULL)
        return; 
    inorder(root->left);
    cout <<root->data << " ";
    inorder(root->right);
}


/*
*   Entry point of the application
*/
int main()
{
    struct node *root = NULL;
    root = insert(root, 50);
    insert(root, 40);
    insert(root, 26);
    insert(root, 35);
    insert(root, 67);
    insert(root, 89);
    insert(root, 1);

   
    inorder(root);
    return 0;
}

<|start_filename|>Java/cp/LongestSubstringDistinctChar.java<|end_filename|>
/**
 * Longest Substring with K Distinct Characters
 * Given a string, print the longest possible substring that 
 * has exactly K unique characters. 
 */

import java.io.*;
public class LongestSubstringDistinctChar {

    static final int CHAR_COUNT = 26;

    public static String findLongestSubstring(String str, int K) {

        String result = ""; 
        int distinct = 0; //Counter for number of distinct letters encountered

        int charCount[] = new int[CHAR_COUNT]; //Array maintains current count of each letter

        //Variable len stores length of longest valid substring, while start and end
        //are limits of the current window (substring) being considered 
        int len = 0, start=0; 
        for(int end=0; end<str.length();) {

            //Updating count of distinct characters
            if(charCount[str.charAt(end) - 'a'] == 0) 
                distinct++; 

            //Updating count of current letter
            charCount[str.charAt(end) - 'a']++; 
            end++;

            if(distinct == K) {
                if((end-start) > len) {
                    len = end-start; 
                    result = str.substring(start, end); 
                }
            } else if(distinct > K) {

                //If number of distinct characters exceeds K, we shorten the 
                //substring by removing characters from the front
                while(distinct > K && start<end) {
                    if(charCount[str.charAt(start) - 'a'] == 1) {
                        distinct--; 
                    }
                    charCount[str.charAt(start) - 'a']--; 
                    start++;
                }
                if(distinct == K) {
                    if((end-start) > len) {
                        len = end-start; 
                        result = str.substring(start, end); 
                    }
                }

            }
        }

        //In absence of any valid substring, "-1" is returned
        return (len==0)? "-1": result;
    }
    
    public static void main(String[] args) throws IOException {
        InputStreamReader read = new InputStreamReader(System.in);
	    BufferedReader buf = new BufferedReader(read); 

        //Taking input from user
        System.out.println("Enter a String of lower case alphabets: ");
        String str = buf.readLine().trim();  
        System.out.println("Enter number of distinct characters: ");
	    int K = Integer.parseInt(buf.readLine()); 
	    
        //Printing output
        System.out.println("Longest substring with " + K + " distinct characters: "); 
        System.out.println(findLongestSubstring(str, K)); 
    }

}

/*
    Time complexity: O(N)
    Space complexity: O(CHAR_COUNT) (as there are 26 lower case English 
    alphabets, here, CHAR_COUNT = 26)

    TEST CASES

    INPUT
    Enter a String of lower case alphabets:
    abckefcaxyzzxxo
    Enter number of distinct characters: 
    3
    OUTPUT
    Longest substring with 3 distinct characters: 
    xyzzxx

    INPUT
    Enter a String of lower case alphabets:
    kkkkrrrr
    Enter number of distinct characters: 
    4
    OUTPUT
    Longest substring with 4 distinct characters: 
    -1

 */


<|start_filename|>C-Plus-Plus/math/number_of_divisors.cpp<|end_filename|>
/*
Given a Number. Find it's Number of Divisors.

The Number can be big such as 10^6 to 10^9
So, If we do this in O(N) we will get Time Limit Exceeded [TLE]
Better Approach is run a loop till sqrt(Number)
Example square root of 10^9 is 31622 (approx), so iteration optimized a lot.
*/

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

// this get_number_of_divisors will count the number of divisors of the number
int get_number_of_divisors(int Number)
{
    int number_of_divisors = 0;
    int limit = (int) sqrt(Number);
    for(int i = 1; i < limit; i++)
    {
        if(Number % i == 0)
        {
            /* Here i is a divisor of that number
            ( Number / i ) is also a divisor
            */
            number_of_divisors += 2;
        }
    }

    if(Number % limit == 0)
    {
        if(limit * limit == Number)
        {
            //means perfect square number
            number_of_divisors++;
        }
        else
        {
            number_of_divisors += 2;
        }
    }
    return number_of_divisors;
}

int main()
{
    cout << "Enter the number : \n";
    int Number;
    cin >> Number;
    int number_of_divisors = get_number_of_divisors(Number);
    cout << "Number of Divisors of this Number is : ";
    cout << number_of_divisors << endl;
}

/*
Standard Input and Output

Enter the number :
1000000000
Number of Divisors of this Number is : 100

Enter the number :
4567323
Number of Divisors of this Number is : 16

Time Complexity : O( sqrt(N) )
Space Complexity : O( 1 )

*/


<|start_filename|>Java/cp/Count_The_Reversals.java<|end_filename|>
//Given a string S consisting only of opening and closing curly brackets '{' and '}' find out the minimum number of reversals required to make a balanced expression.
//
//        Input
//        The first line of input contains an integer T, denoting the number of test cases. Then T test cases
//        follow. The first line of each test case contains a string S consisting only of { and }.
//
//        Output
//        Print out minimum reversals required to make S balanced. If it cannot be balanced, then print -1.
//
//        Constraints
//        1 <= T <= 100
//        0 <= |S| <= 50
//
//        Examples
//        Input
//        4
//        }{{}}{{{
//        {{}}}}
//        {{}{{{}{{}}{{
//        {{{{}}}}
//
//        Output
//        3
//        1
//        -1
//        0

import java.util.Scanner;
import java.util.Stack;

public class Count_the_Reversals {
    public static void main(String[] args) {
        Stack ss=new Stack();
        System.out.println(ss.size());

        Scanner s=new Scanner(System.in);
        int t=s.nextInt();
        while (t-->0){
            Stack<Character> stack=new Stack<>();
            String str=s.next();
            if (str.length()%2!=0){
                System.out.println(-1);
            }
            else {
                for (int i = 0; i <str.length() ; i++) {
                    if(str.charAt(i)=='{'){
                        stack.push(str.charAt(i));


                    }
                    else {
                        if(!stack.isEmpty()&&stack.peek()=='{'){
                            stack.pop();
                        }
                        else {
                            stack.push(str.charAt(i));
                        }
                    }

                }
                int m=stack.size();
                int n = 0;
                while (!stack.empty() && stack.peek() == '{')
                {
                    stack.pop();
                    n++;
                }
                System.out.println(m/2+n%2);
            }

        }
    }
}


<|start_filename|>C-Plus-Plus/ds/Circular_Queue.cpp<|end_filename|>
/*
This is a code of circular queue data structure. It is a linear data structure, which obeys the principal
 of First in First Out(FIFO). Circular queue data structure is a updated version of linear queue data structure,
 which have some advantages over linear queue. The following code shows the implementation of circular queue data structure,
 in a very clean and understandable way.
*/

#include<iostream>
#include<stdlib.h>

// Defining max size of the queue as 5

#define max 5

using namespace std;

// Writing a class where all the basic functions of the circular queue presides

class CircularQueue
{
    /*
    Defining all the variables as public variables.
    (It is not necessory of define the variables as public,you can define the variables as private also)*/       
    public:
    int front;
    int rear;
    int arr[max];

    // Initializing a default constructor of the class
    CircularQueue(){
    front = -1;
    rear = -1;
        for(int i = 0; i < max; i++){
            arr[i] = 0;
        }
    }

    // Defining the isFull function to check whether the queue is full or not
    bool isFull(){
        if ((rear + 1) % max == front)
            return true;
        else
            return false;
    }

    // Defining the isEmpty function to check whether the queue is empty or not
    bool isEmpty(){
        if (front == -1 && rear == -1)
            return true;
        else
            return false;
    }

    // Defining the enqueue function, to insert an item in the queue
    void enqueue(int item){
        if(isFull())
        {
            cout << "Queue is full" << endl;
        }
        else if (isEmpty()){
            front=rear=0;
            arr[rear] = item;
        }
        else {
            rear = (rear + 1) % 5;
            arr[rear] = item;
        }

    }

    // Defining the dequeue function, to delete item from the queue
    int dequeue(){
        int x = 0;       
        if(front == rear){
          x = arr[front];
          front = rear = -1;
          return x;
        }
        else
        {
            x = arr[front];
            arr[front] = 0;
            front = (front + 1) % 5;
            return x;
        }
    }

    // Defing display function to display the whole queue
    void display(){
            for (int i = 0; i < 5; i++)
            {
                cout << arr[i] <<endl;
            }   
    }
};

// Testing the above functions:
int main()
{
    // Declaring an object to the class
    CircularQueue Q1;
    
    // A menu driven program to check all the defined functions in the class
    while (1)
    {
        cout << "1. Insert an element in the queue - enqueue" << endl;
        cout << "2. Delete element from the queue - Dequeue" << endl;
        cout << "3. Display items in the queue" << endl;
        cout << "4. To check whether the queue is empty or not" << endl;
        cout << "5. To check whether the queue is full or not" << endl;
        cout << "6. Exit" << endl;
        cout << "Enter your choice" << endl;
        int n;

        cin >> n;

        switch(n){
            case 1:
                int item;
                cout << "Enter the item" << endl;
                cin >> item;
                Q1.enqueue(item);
                break;

            case 2:
                if(!Q1.isEmpty()){
                    cout << "The dequeued value is: " << Q1.dequeue() << endl;
                }
                else{
                    cout << "The queue is empty" << endl;
                }

                break;

            case 3:
                cout << "The Queue is" << endl;
                Q1.display();
                break; 

            case 4:
                if(Q1.isEmpty()){
                    cout<<"Queue is Empty"<<endl;
                }
                else{
                    cout<<"Queue is not Empty"<<endl;
                }

            break;

            case 5:
                if(Q1.isFull()){                    
                    cout<<"Queue is Full"<<endl;
                }
                else{
                    cout<<"Queue is not Full"<<endl;
                }
            break;         

            case 6:
                exit(1);  

            default:
                cout << "Choose the options correctly";
                break;        
        }
    } 
    return 0;
}

/*
  Sample Input/Output:
  
  1. Insert an element in the queue - enqueue
  2. Delete element from the queue - Dequeue
  3. Display items in the queue
  4. To check whether the queue is empty or not
  5. To check whether the queue is full or not
  6. Exit
  Enter your choice
  1
  Enter the item
  10
  1. Insert an element in the queue - enqueue
  2. Delete element from the queue - Dequeue
  3. Display items in the queue
  4. To check whether the queue is empty or not
  5. To check whether the queue is full or not
  6. Exit
  Enter your choice
  1
  Enter the item
  20
  1. Insert an element in the queue - enqueue
  2. Delete element from the queue - Dequeue
  3. Display items in the queue
  4. To check whether the queue is empty or not
  5. To check whether the queue is full or not
  6. Exit
  Enter your choice
  3
  The Queue is
  10
  20
  0
  0
  0
  1. Insert an element in the queue - enqueue
  2. Delete element from the queue - Dequeue
  3. Display items in the queue
  4. To check whether the queue is empty or not
  5. To check whether the queue is full or not
  6. Exit
  Enter your choice
  2
  The dequeued value is: 10
  1. Insert an element in the queue - enqueue
  2. Delete element from the queue - Dequeue
  3. Display items in the queue
  4. To check whether the queue is empty or not
  5. To check whether the queue is full or not
  6. Exit
  Enter your choice
  2
  The dequeued value is: 20
  1. Insert an element in the queue - enqueue
  2. Delete element from the queue - Dequeue
  3. Display items in the queue
  4. To check whether the queue is empty or not
  5. To check whether the queue is full or not
  6. Exit
  Enter your choice
  4
  Queue is Empty
  1. Insert an element in the queue - enqueue
  2. Delete element from the queue - Dequeue
  3. Display items in the queue
  4. To check whether the queue is empty or not
  5. To check whether the queue is full or not
  6. Exit
  Enter your choice
  5
  Queue is not Full
  1. Insert an element in the queue - enqueue
  2. Delete element from the queue - Dequeue
  3. Display items in the queue
  4. To check whether the queue is empty or not
  5. To check whether the queue is full or not
  6. Exit
  Enter your choice
  6 
*/
/*
 The time complexities of different operations in a circular queue data structure are:-
  1) The time complexity of enqueue operation is O(1), that is constant time.
  2) The time complexity of dequeue operation is O(1), that is constant time. 
  3) The time complexity for checking whether the queue is empty of full is O(1), that is constant time.
  4) The time complexity of display function is O(n), where n is the number of Elements in the queue.
*/


<|start_filename|>C-Plus-Plus/math/decimal_to_hexadecimal.cpp<|end_filename|>
#include<bits/stdc++.h>
using namespace std;

//CONVERSION OF DECIMAL NUMBER TO HEXADECIMAL NUMBER
void decimal_to_hexadecimal(int n)
{
  int i=0;
  string ans="";
  int last_digit=0;
  char x;
  while(n)
  {
    last_digit=n%16;
    n=n/16;
    /*  Condition checking :
        If digit greater than 9, X will be alphabet
        Else X will be a number  */
    if(last_digit>9)
       x=last_digit+'A'-10;
    else
      x=last_digit+'0';
    ans[i]=x;
    i++;
  }
  //Loop for printing reverse String
  cout<<"\n The Required Hexadecimal Number is::";
  for(int k=i-1;k>=0;k--)
    cout<<ans[k];
}
int main()
{
  int decimal;
  cout<<"\n ENTER THE DECIMAL NUMBER::";
  cin>>decimal;
  decimal_to_hexadecimal(decimal);
  return 0;
}

/* Testcases:

  INPUT-
  ENTER THE DECIMAL NUMBER::463
  OUTPUT-
  The Required Hexadecimal Number is::1CF

  INPUT-
  ENTER THE DECIMAL NUMBER::100
  OUTPUT-
  The Required Hexadecimal Number is::64

  INPUT-
  ENTER THE DECIMAL NUMBER::516042
  OUTPUT-
  The Required Hexadecimal Number is::7DFCA

  Time Complexity- O(n);
  Space Complexity- O(1);

*/


<|start_filename|>C-Plus-Plus/cp/Binary_Tree_to_Doubly_Linked_List.cpp<|end_filename|>
/*
This code gets the values of binary tree from the user and then convert the binary tree to doubly linked list.
The formed Doubly linked list will have elements in the same order as that of inorder traversal of binary tree. 
*/

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

struct TreeNode{
	int value;
	TreeNode* left = NULL;
	TreeNode* right = NULL;
};

TreeNode* newNode(int n){
	TreeNode* t = new TreeNode;
	t->value = n;
	t->left = NULL;
	t->right = NULL;
}

//This function inserts node into the binary tree
TreeNode* insert(TreeNode* t, queue<TreeNode* > &q, int v){		
	TreeNode* temp = newNode(v);
	if(v==-1){
		temp = NULL;
	}
	if(t==NULL){
		t = temp;
	}
	else if(q.front()->left==NULL){
		q.front()->left = temp;
	}
	else{
		q.front()->right = temp;
		q.pop();
	}
	q.push(temp);
	return t;
}

//This function converts given vector into Binary Tree
TreeNode* make_tree(vector<int> v){		
	queue<TreeNode* > q;
	TreeNode* t = NULL;
	for(int i=0;i<v.size();i++){
		t = insert(t,q,v[i]);
	}
	return t;
}

//This function prints all the elements of doubly linked list
void print_elements(TreeNode* &T){		
	TreeNode* temp = T;
	cout<<"The elements of doubly linked list are: ";
	while(temp!=NULL){
		cout<<temp->value<<" ";
		temp = temp->right;
	}
}

//This function converts Binary tree to doubly linked list
void to_dll(TreeNode* T, TreeNode* &temp){		
	if(T==NULL){
		return;
	}
	to_dll(T->right,temp);
	T->right = temp;
	
	if(temp!=NULL){
		temp->left = T;
	}
	temp = T;
	to_dll(T->left,temp);
}

void to_doubly_linked_list(TreeNode* T){		
	TreeNode* h = NULL;
	to_dll(T,h);
	print_elements(h);
}

int main(){
	cout<<"Enter number of nodes of binary tree: "<<endl;
	int node;		//number of nodes of binary tree
	cin>>node;
	
	cout<<"Enter the values of nodes level by level and enter -1 if node is NULL: "<<endl;
	vector<int> binary_tree_values;
	
	while(node){		//asking user for elements of Binary tree
		int node_value;
		cin>>node_value;
		binary_tree_values.push_back(node_value);
		node--;
	}
	
	cout<<"Making binary tree from the vector..."<<endl;
	TreeNode* T = make_tree(binary_tree_values);
	
	cout<<"Converting Binary tree to doubly linked list..."<<endl;
	to_doubly_linked_list(T);
	
	return 0;
}

/*
Time Complexity : O(N)
Space Complexity : O(N)

Here if we give following binary tree as input:
    5
   / \
  6   8
 / \ / \
3  4 9  2 
i.e,

if input is -

Enter number of nodes of binary tree: 
7
Enter the values of nodes level by level and enter -1 if node is NULL:
5 6 8 3 4 9 2

The output will be -

Making binary tree from the vector...
Converting Binary tree to doubly linked list...
The elements of doubly linked list are: 3 6 4 5 9 8 2
*/



<|start_filename|>C-Plus-Plus/cp/min_cost_to_generate_n_cells.cpp<|end_filename|>
/*Problem Statement: 
There's a scientist is interested in budding of cells. He has one container which initially contains only a single cell. 
Now he wants n number of cells in his container. 
So he can change the number of cells in container in 3 different ways -:

1.Double the number of cells present in the container.

2.Increase the number of cells in the container by 1.

3.Decrease the number of cells in the container by 1.

Now, all the above operations have different costs associated with them x,y,z respectively for above operations. 
Help him in finding the minimum cost to generate n cells in the container starting from one cell. */

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

int costToGenerate(int n, int x, int y, int z)
{
    int dp[100];
    dp[0] = 0;
    dp[1] = 0;

    for (int i = 2; i <= n; i++)
    {
        if (i % 2 == 0)
        {
            dp[i] = min(dp[i / 2] + x, dp[i - 1] + y);
        }
        else
        {
            /*Here, an odd number cannot be reached by doubling an odd number,
            therefore, we increase it by 1  and then use case 1*/
            dp[i] = min(dp[i - 1] + y, dp[i + 1 / 2] + x + z);
        }
    }

    return dp[n];
}

int main()
{
    int x, n, y, z;
    cin >> n >> x >> y >> z;
    int dp[100];
    cout << costToGenerate(n, x, y, z) << endl;
    return 0;
}

/*Example: 
1)Input: 5 2 1 3
Output: 4
2)Input: 7 4 2 3
Output: 10
Time Complexity: O(n)
Space Complexity: O(n) */


<|start_filename|>C-Plus-Plus/cp/Unique_prime_factors.cpp<|end_filename|>
/* This is a use of Sieve of Eratosthenes algorithm.
In this We can find all unique prime factor of any number n.For example if n is 12 then output will be 2,3
In this first we store all prime factor of numbers till n and then print prime factors of n. */

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

void unique_prime(int n){
  int arr[n+1];
  memset(arr , 1 , n+1);
  //first find all prime factors till n by sieves method 
  for(int i = 2 ; i <= sqrt(n) ; i++) {
    if(arr[i]==0){
      continue;
    } 
      for(int j = i*i ; j <=n ; j += i){
        arr[j] = 0;
      
    }
  }
  //now check which prime number are factor of n
  cout<<"All unique prime factors of "<<n<<" are: ";
  for(int i=2; i<=n; i++){  
    if(arr[i] == 0 && n%i == 0 ) {
      cout << i <<"  ";
    }
  }
}

int main() {
  int num;
  cout<<"Enter the number: ";
  cin >> num;
  unique_prime(num);
}

/* Sample Input
   Enter the number: 5446
   Sample output
   All Unique prime factors of 5446 are: 2  7  389 
*/
/* Time complaxity : O(n + n(log(logn)))
   Space Complaxity : O(n)
*/


<|start_filename|>C-Plus-Plus/graphs/Bidirectional_search_using_BFS_in_undirected_graph.cpp<|end_filename|>
/*
Bidirectional search is an algorithm in which we find the Smallest Path from the source to the
target vertex of a graph.
In this algorithm, we perform the search operation from two sides, i,e. from the source
vertex(Forward Search) and the target vertex(Backward Search) simultaneously.
It divides the graph into two smaller sub-graphs, one starting at the source
vertex and other at the target vertex.
As the searching operation proceeds, the two graphs grow and the search terminates when two graphs
intersect.
To perform the searching operation, we implement Breadth-first search on both source vertex and
target vertex.

Bidirectional search is faster in many cases as compared to normal one-directional search as it
dramatically reduces the amount of required exploration.
*/

typedef long long int ll;
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
#define mod 1000000007

void bfs(queue<int>& q, vector<bool>& visited, vector<int>& parent, vector<int> graph[])
{
    int current = q.front();
    q.pop();

    for (auto i : graph[current])
    {

        // If adjacent vertex is not visited earlier
        // mark it visited by assigning true value
        if (!visited[i])
        {
            // set current as parent of this vertex
            parent[i] = current;
            
            // Mark this vertex visited
            visited[i] = true;
            
            // Push to the end of queue
            q.push(i);
        }
    }
}

// Print the path from source to target
void printShortestPath(vector<int>& parentF, vector<int>& parentB, int sv, int tv, int inode)
{
    vector<int> path;
    path.push_back(inode);
    int i = inode;
    while (i != sv)
    {
        path.push_back(parentF[i]);
        i = parentF[i];
    }
    reverse(path.begin(), path.end());
    i = inode;
    while (i != tv)
    {
        path.push_back(parentB[i]);
        i = parentB[i];
    }

    for (auto x : path)
        cout << x << " ";
    cout << endl;
}

// Helper Method for bidirectional searching
int bidirectional_search_helper(int sv, int tv, vector<int> graph[], int n, vector<bool>& visitedF,
    vector<bool>& visitedB, vector<int>& parentF, vector<int>& parentB)
{
    // queue for front and backward search
    queue<int> qF, qB;

    qF.push(sv);
    visitedF[sv] = true;

    qB.push(tv);
    visitedB[tv] = true;

    // parent of source is set to -1
    parentF[sv] = -1;

    // parent of target is set to -1
    parentB[tv] = -1;

    while (!qF.empty() && !qB.empty())
    {

        // Forward Breadth first search
        bfs(qF, visitedF, parentF, graph);

        // Backward Breadth first search
        bfs(qB, visitedB, parentB, graph);

        // checks for intersecting vertex
        int inode = -1;
        int i, flag = 0;
        for (i = 0; i < n; i++)
        {
            if (visitedF[i] && visitedB[i])
            {
                flag = 1;
                break;
            }
        }
        if (flag == 1)
            inode = i;

        // If intersecting vertex is found
        // that means there exist a path
        if (inode != -1)
            return inode;
    }
    return -1;
}

// Method for bidirectional searching
void bidirectional_search(int vertices, vector<int> graph[], int sv, int tv)
{
    // visited array for forward search
    vector<bool> visitedF(vertices, false);

    // visited array for backward search
    vector<bool> visitedB(vertices, false);

    // parent array for forward search
    vector<int> parentF(vertices);

    // parent array for backward search
    vector<int> parentB(vertices);

    int intersection_node = bidirectional_search_helper(
        sv, tv, graph, vertices, visitedF, visitedB, parentF, parentB);

    // If intersection node does not exist then the path between the source vertex and target vertex
    // doesn't exist
    if (intersection_node == -1)
    {
        cout << "Path between " << sv << " and " << tv << " does not exists" << endl;
    }
    else
    {
        cout << "Path exist between " << sv << " and " << tv << endl;
        cout << "Intersection at: " << intersection_node << endl;
        printShortestPath(parentF, parentB, sv, tv, intersection_node);
    }
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int vertices, edges;
    cin >> vertices >> edges;

    vector<int> graph[vertices];

    for (int i = 0; i < edges; i++)
    {
        int a, b;
        cin >> a >> b;
        graph[a].push_back(b);
        graph[b].push_back(a);
    }
    // source vertex
    int sv;
    // target vertex
    int tv;

    cin >> sv >> tv;

    bidirectional_search(vertices, graph, sv, tv);

    return 0;
}

/*
Example:

input:
15 14
0 4
1 4
2 5
3 5
4 6
5 6
6 7
7 8
8 9
8 10
9 11
9 12
10 13
10 14
3 10

output:
Path exist between 3 and 10
Intersection at: 7
3 5 6 7 8 10

Time Complexity : O(bd/2)
Space Complexity : O(bd/2)

{ b = branching factor of tree
  d = distance of goal vertex from source }
*/



<|start_filename|>Java/Operating-System/CPU_Scheduling_SJF.java<|end_filename|>
/*
-Shortest Job First (SJF) is an algorithm in which the process having the smallest execution time is chosen for the next execution. 
-This scheduling method can be preemptive or non-preemptive. It significantly reduces the average waiting time for other processes 
awaiting execution. 
-It can improve process throughput by making sure that shorter jobs are executed first, hence possibly have a short turnaround time.
*/

import java.util.Scanner;

class sjf
{
    int arrival_time;
    int finish_time=0;
    int turnaround_time;
    int waiting_time;
    int burst_time;
    int id;
    public sjf(int B_T,int id)			//Parameterized constructor
    {
        arrival_time=0;
        burst_time=B_T;
    }
}

class process_sjf
{
    sjf process[]=new sjf[30];				//Array of objects
    Scanner sc=new Scanner(System.in);
   
    int burst_time;
    int id;
    int num;

    public void create()			
    {
    System.out.println("Enter number of processes: ");
    num=sc.nextInt();
    for(int i=0;i<num;i++)
    {

        System.out.println("Enter the process id: ");
        id=sc.nextInt();
        System.out.println("Enter the burst time: ");
        burst_time=sc.nextInt();
        process[i]=new sjf(burst_time,id);
    }
    }
   
    public void sorting()					//Bubble sort
    {
        int i,j;
        sjf temp;
        for(i=0;i<num-1;i++)
        {
            for(j=0;j<num-i-1;j++)
            {
                if(process[j].burst_time > process[j+1].burst_time)
                {
                    temp=process[j];
                    process[j]=process[j+1];
                    process[j+1]=temp;
                }
   
            }
        }
       
    }
   
    public void calc()			
    {
        int i;   
        sorting();
        process[0].finish_time=process[0].burst_time;
        System.out.println(process[0].finish_time);
        for(i=1;i<num;i++)          //Completion time
        {
            process[i].finish_time=process[i-1].finish_time+process[i].burst_time;		//Finish time calculation
        }
       
        for(i=1;i<num;i++)         //Turnaround time
        {
            process[i].turnaround_time=process[i].finish_time-0;					//Turnaround time calculation
        }
        for(i=1;i<num;i++)        //Wating time
        {
            process[i].waiting_time=process[i].turnaround_time-process[i].burst_time;		//Waiting time calculation
        }
       
 
    }

    public void display()			
    {
    	int i=0;
    	int j=0;
    	int k=0;
    	sjf temp;
    	float avg_tt=0;
        float avg_wt=0;
           calc();
           for(i=0;i<num-1;i++)
           {
                k=i;
               for(j=i+1;j<num;j++)
               {
                   if(process[j].id<process[k].id)
                   {
                       k=j;
                   }
               }
              
                  if(k!=i)
                   {
                       temp=process[i];
                       process[i]=process[k];
                       process[k]=temp;
                   }
           }
       System.out.println("Process"+"\t\t"+"Arrival time"+"\t\t"+"Burst time"+"\t\t"+"Finish time"+"\t\t"+"Turnaround time"+"\t\t"+"Waiting time");
 
           for( i=0 ; i<num ; i++)
           {
               System.out.println("P"+process[i].id+"\t\t\t"+"0"+"\t\t\t"+process[i].burst_time+"\t\t\t"+process[i].finish_time+"\t\t\t"+process[i].turnaround_time+"\t\t\t"+process[i].waiting_time);
               avg_tt=avg_tt+process[i].turnaround_time;
               avg_wt=avg_wt+process[i].waiting_time;
           }
          
           avg_tt=avg_tt/num;				//Average turnaround time
           avg_wt=avg_wt/num;				//Average waiting time
          
           System.out.println("\nAverage Turn Around time="+avg_tt+"ms");
           System.out.println("Average Waiting time="+avg_wt+"ms");
    }
}

public class CPU_Scheduling_SJF{
    public static void main(String[] args)
    {
        process_sjf p=new process_sjf();
        p.create();
        p.display();
       
    }

}

/*
Enter number of processes: 
5
Enter the process id: 
1
Enter the burst time: 
22
Enter the process id: 
2
Enter the burst time: 
8
Enter the process id: 
3
Enter the burst time: 
20
Enter the process id: 
4
Enter the burst time: 
10
Enter the process id: 
5
Enter the burst time: 
4

Gantt chart:
P5		P2		P4		P3		P1

Process		Arrival time		Burst time		Finish time		Turnaround time		Waiting time
P1			0			22			64			64			42
P2			0			8			12			12			4
P3			0			20			42			42			22
P4			0			10			22			22			12
P5			0			4			4			0			0

Average Turn Around time=28.0ms
Average Waiting time=16.0ms
*/

<|start_filename|>C-Plus-Plus/Bit--Manipulation/reverse_bits.cpp<|end_filename|>
// C++ program to reverse the bits of a number

/*
Given an integer, reverse its bits in its binary equivalent and 
print the new number obtained in its decimal form
*/

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

/*
The code first stores the lsb of the given number in a variable and then left shifts
the given number and gives this number to the lsb of the answer variable and then right
shifts it
*/
int reverse_bits(int n)
{

    int rev = 0, rem;

    // Traverse while there exist bits for the given number
    while (n)
    {
        // Shift the bit of the reversed(answer) number to the right
        rev = rev << 1;
        //Stores the temporary lsb of the given number
        rem = n & 1;
        //Set the lsb of the answer variable with the stored value
        rev = rem | rev;
        //Drops the already processed lsb of the given number
        n = n >> 1;
    }
    return rev;
}

int main()
{
    int n, ans;
    cout << "\nEnter the number? ";
    cin >> n;

    //Call the function
    ans = reverse_bits(n);
    cout << "The bits-reversed number is: " << ans << endl;
    return 0;
}

/*

Time Complexity: O(n)
Space Complexity: O(1)

SAMPLE INPUT AND OUTPUT

Enter the number? 39
The bits-reversed number is: 57

*/


<|start_filename|>Java/dp/Make_string_palindrome_using_DP.java<|end_filename|>
/*
    Given a String, find the minimum number of characters that need to be deleted to make the 
    resultant String a Palindrome and also print these characters.
*/
/*
    Basic Idea to solve this problem:- We find the Longest Common Subsequence of given string and its reverse. The resultant 
    sequence is now just matched with the original string and the missing characters will be the ones that need to be deleted
    from the original string to make it a palindrome.
*/

import java.util.*;

public class Make_string_palindrome_using_DP {
    //Function to calculate maximum out of 2 nos
    public static int maximum(int a, int b){
        return (a>=b) ? a : b;
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the string:- ");
        
        String s1 = sc.nextLine();

        StringBuilder s = new StringBuilder();
        s.append(s1);
        s.reverse();
        String s2 = s.toString();

        longest_common_subsequence(s1, s2);
    }

    public static void longest_common_subsequence(String s1, String s2){
        //Cost Matrix for finding the Longest Common Subsequence for Original string and its reverse
        int cost[][];
        cost = new int[s1.length() + 1][s2.length()+1];

        //Recurrence Relation for LCS:- 
        // if str1[i-1] == str2[j-1] -> cost[i][j] = 1 + cost[i-1][j-1]
        // else -> max(cost[i-1][j], cost[i][j-1)

        for (int i = 0; i<=s1.length(); i++) {
            for (int j = 0; j<=s2.length(); j++) {
                if(i == 0 || j == 0){
                    cost[i][j] = 0;
                }
                else if(s1.charAt(i-1) == s2.charAt(j-1)){
                    cost[i][j] = 1 + cost[i-1][j-1];
                }
                else {
                    cost[i][j] = maximum(cost[i-1][j], cost[i][j-1]);
                }
            }
        }

        System.out.println("\nLongest length Matrix for two subsequences:- ");
        
        for (int i = 0; i <= s1.length(); i++) {
            for (int j = 0; j <=s2.length(); j++) {
                System.out.print(cost[i][j] + "\t");
            }
            System.out.println();
        }
        System.out.println("\n");
        // Getting the LCS by backtracking the Cost matrix
        String s = extracting_longest_subsequence_using_backtracking(cost, s1, s2).toString();
        print_chars_to_be_removed_for_palindrome(s, s1);
    }

    public static void print_chars_to_be_removed_for_palindrome(String lcs, String original_str){
        int count = 0;
        System.out.print("Characters to be delted:- ");
        for(int i = 0; i<original_str.length(); i++){
            if(lcs.contains("" + original_str.charAt(i))){
                continue;
            }
            else{
                System.out.print(original_str.charAt(i) + " ");
                count++;
            }
        }
        System.out.println("\nMinimum no of characters to be deleted:- " + count);
    }

    public static StringBuilder extracting_longest_subsequence_using_backtracking(int c[][], String s1, String s2){
        String output_str = new String("");
        StringBuilder output = new StringBuilder();
        int i = s1.length();
        int j = s2.length(); 
        //If while traversing the characters at i and j are same then go back diagonally 
        //else find max from (i-1, j) and (i, j-1) and traverse to that position just like how we did while filling the matrix
        //and when the characters of the two strings were not same. 
        while(i > 0 && j > 0){
            if(s1.charAt(i-1) == s2.charAt(j-1)){
                output_str = output_str + "" + s1.charAt(i-1);
                i -= 1;
                j -= 1;
            }
            else if(c[i-1][j] > c[i][j-1]){
                i -= 1;
            }
            else{
                j -= 1;
            }
        }
        output.append(output_str);
        output.reverse();
        return output;
    }
}
/*
    Time Complexity:- O(n*m) where 'n' is length of String 1 and 'm' is the length of String 2
    Space Complexity:- O(n*m) since we are creating the Cost matrix
*/

/*
Sample Testcase: 
Enter the string:- 
NITIXN

Output:-
Longest length Matrix for two subsequences:- 
0       0       0       0       0       0       0       
0       1       1       1       1       1       1       
0       1       1       2       2       2       2       
0       1       1       2       3       3       3       
0       1       1       2       3       4       4       
0       1       2       2       3       4       4       
0       1       2       2       3       4       5       


Characters to be delted:- X
Minimum no of characters to be deleted:- 1
*/

<|start_filename|>Java/cp/Identical_Words.java<|end_filename|>
/*
- Identical_Words :
    We will give 3 Strings as input and we will check if it is possible to make
    second_string and third_string equivalent to first_string by re-arranging characters of
    second_string and third_string any number of times

- Example :
     Input : words ordws rsdow
    Output : They are Identical

- Approach :
  1. After taking the 3-input Strings we will check if their lengths are equal or not, if not then
     they are not equivalent

  2. We will use string_sort method to sort the string by converting it to character array and then
     using Arrays.sort() method

  3. After all 3 Strings sorted we will check if they are equal or not, if equal then "They are Identical"
     and if not then "They are not Identical"
*/

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

public class Identical_Words {
	//string_sort method
	public static String string_sort(String s) {
		//converting string to char array
		char char_Array[] = s.toCharArray();
		//sorting char array
		Arrays.sort(char_Array);
		//converting char array back to String
		String sorted_string = new String(char_Array);
		return sorted_string;
	}
	//main method
	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		//Enter 3 Strings as input
		System.out.print("Enter Strings : ");
		String first_string = sc.next();
		String second_string = sc.next();
		String third_string = sc.next();

		// Checking if length of all Strings are equal or not
		if(first_string.length() == second_string.length() && first_string.length() == third_string.length()) {

			String s1 = Identical_Words.string_sort(first_string);
			String s2 = Identical_Words.string_sort(second_string);
			String s3 = Identical_Words.string_sort(third_string);
			//Checking if Strings are equal or not
			if(s1.equals(s2) && s1.equals(s3)) {
				//if this condition satisfies then print "They are Identical"
				System.out.println("They are Identical");
			}else {
				//else print "They are not Identical"
				System.out.println("They are not Identical");
			}
		}else {
			System.out.println("They are not Identical");
		}
	}
}
/*
- Test Cases :
      Input : Enter Strings : identical inticalde lacitdeni
     Output : They are Identical

- Complexity Analysis :
  * Time Complexity : O(nlog(n))
        As we are using Arrays.sort()

  * Space Complexity : O(n)
        Auxiliary space : O(n)  +  input space : O(1)
*/
  


<|start_filename|>C-Plus-Plus/ds/Circular_LinkedList.cpp<|end_filename|>
#include <bits/stdc++.h>
using namespace std;

class node
{
public:
    int data;
    node *next;
    //constructor
    node(int d)
    {
        data = d;
        next = NULL;
    }
};

//Function to insert in circular LinkedList
void insert(node *&head, int data) //pass by referance
{
    node *n = new node(data);
    n->next = head; //creating a new node
    node *temp = head;
    if (temp != NULL)
    {
        while (temp->next != head)
        {
            temp = temp->next;
        }
        temp->next = n;
    }

    //self loop for single node
    else
    {
        n->next = n;
    }
    head = n;
}

//Creating a function to get the node to be deleted
node *getnode(node *head, int data) //pass ny value
{
    node *temp = head;
    while (temp->next != head)
    {
        if (temp->data == data)
        {
            return temp;
        }
        temp = temp->next;
    }
    if (temp->data == data)
    {
        return temp;
    }
    return NULL;
}

//Creating the delete function
void del(node *head, int data)
{
    node *del = getnode(head, data);

    if (del == NULL)
    {
        return;
    }

    if (head == del)
    {
        head = head->next;
    }

    node *temp = head;

    while (temp->next != del)
    {
        temp = temp->next;
    }
    temp->next = del->next;
    delete del;
}

//function to print circular linkedlist
void print(node *head)
{
    node *temp = head;
    while (temp->next != head)
    {
        cout << temp->data << " -> ";
        temp = temp->next;
    }
    cout << temp->data << endl; //for last node
}

int main()
{
    node *head = NULL;
    cout << "Insertion in circular linkedlist" << endl;
    int arr[100], arr2[100];
    int n, n2;
    cout << "enter the number of elements" << endl;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cout << "enter element number " << i << "-" << endl;
        cin >> arr[i];
        insert(head, arr[i]);
    }
    cout << "Elements inserted" << endl;
    print(head);

    cout << "enter the number of elements you want to delete" << endl;
    cin >> n2;
    for (int j = n2 - 1 + 1; j > 0; j--)
    {
        cout << "enter position of number " << endl;
        cin >> arr2[j];
        del(head, arr[j + 1]);
    }

    print(head);

    return 0;
}

/*
OUTPUT
Insertion in circular linkedlist
enter the number of elements
6
enter element number 0-
1
enter element number 1-
2
enter element number 2-
3
enter element number 3-
4
enter element number 4-
5
enter element number 5-
6
Elements inserted
6 -> 5 -> 4 -> 3 -> 2 -> 1
enter the number of elements you want to delete
2
enter position of number 
2
enter position of number 
3
6 -> 5 -> 2 -> 1
*/


<|start_filename|>C-Plus-Plus/cp/weird algorithm.cpp<|end_filename|>
/*****

Consider an algorithm that takes as input a positive integer n. If n is even, the algorithm divides it by two, and if n is odd, the algorithm multiplies it by three and adds one. The algorithm repeats this, until n is one. For example, the sequence for n=3 is as follows:
3→10→5→16→8→4→2→1

Your task is to simulate the execution of the algorithm for a given value of n.

Input

The only input line contains an integer n.

Output

Print a line that contains all values of n during the algorithm.

Example :
Input:
3

Output:
3 10 5 16 8 4 2 1

*****/


#include<iostream>
using namespace std;
 
int main(){
    long long n;
    cin>>n;
    while(true)
    {
        cout << n << " "; 
        // breaking here coz finally we have to reach here
        if (n == 1) break; 
        // main condition that if n is even then change it to its half otherwise multiply by 3 and add 1
        if (n%2 == 0) n /= 2;    
        else n = n*3+1;
    }
    cout << "\n";               
    return 0;
}



/***

Time complexity of this program O(n)

Input:
3

Output:
3 10 5 16 8 4 2 1

*****/


<|start_filename|>Java/math/Quadratic_Equation.java<|end_filename|>
/* 
Problem: Solving Quadratic equations in Java-
A program that prints all real solutions to quadratic equation ax^2+bx+c=0, if discriminant is negative displays a message "roots are imaginary". 
*/
import java.util.*;
import java.io.*;

public class Quadratic_Equation {
  public static void quadraticroots()
  {
    // value a, b, and c
    double a, b, c;
    double root1, root2;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter coefficients of the equation:");
    System.out.print("Enter a: ");
    a = sc.nextDouble();
    System.out.println();
    System.out.print("Enter b: ");
    b = sc.nextDouble();
    System.out.println();
    System.out.print("Enter c: ");
    c = sc.nextDouble();
    System.out.println();
    // If a is 0, then equation is not quadratic, but linear
    if (a == 0) {
        System.out.println("Its a linear equation,Not a quadratic equation!");
        return;
      }
    // calculate the discriminant (b^2 - 4ac)
    double discriminant = b * b - 4 * a * c;
    // discriminant is greater than 0, real and distinct roots
    if (discriminant > 0) {
        root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
        root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
        System.out.println("Roots are real and distinct");
        System.out.format("root1 = %.2f and root2 = %.2f", root1, root2);
      }
    // discriminant is equal to 0, real and equal roots
    else if (discriminant == 0) {
        root1 = root2 = -b / (2 * a);
        System.out.println("Equal roots");
        System.out.format("root1 = root2 = %.2f;", root1);
      }
    // discriminant is less than zero, imaginary roots
    else {
        double real = -b / (2 * a);
        double imaginary = Math.sqrt(-discriminant) / (2 * a);
        System.out.println("Imaginary roots!");
        System.out.format("root1 = %.2f+%.2fi", real, imaginary);
        System.out.format("\nroot2 = %.2f-%.2fi", real, imaginary);
      }
  }
  public static void main(String[] args) {
    quadraticroots();
  }
}

/*
Sample Test Cases:

Test case 1:
Enter coefficients of the equation:
Enter a: 1

Enter b: -4

Enter c: 0

Roots are real and distinct
root1 = 4.00 and root2 = 0.00

Test case 2:
Enter coefficients of the equation:
Enter a: 7.2

Enter b: 5

Enter c: 9

Imaginary roots!
root1 = -0.35+1.06i
root2 = -0.35-1.06i

Test case 3:
Enter coefficients of the equation:
Enter a: 1

Enter b: -2

Enter c: 1

Equal roots
root1 = root2 = 1.00;

Time Complexity: O(1)
Space Complexity: O(1)
*/


<|start_filename|>C-Plus-Plus/dp/maximum_sum_increasing_subsequence.cpp<|end_filename|>
// C++ program to implement Maximum Sum Increasing Subsequence
/*
In this problem, given an array we have to find the maximum sum an increasing subsequence of that array can make.
This problem is a slight modification to the Longest Increasing subsequence problem.
The problem can be solved using Dynamic Programming
*/
#include <bits/stdc++.h>
using namespace std;

int max_sum_increasing_subsequence(int arr[], int n)
{
    int dp[n], max_sum = 0;

    /* Initialize the dp array with the array values, as the maximum sum 
       at each point is atleast as the value at that point         */
    for (int i = 0; i < n; i++)
        dp[i] = arr[i];

    // Now Lets Fill the dp array in Bottom-Up manner
    /* Compare Each i'th element to its previous elements from 0 to i-1, 
       If arr[i] > arr[j], then it qualifies for increasing subsequence and
       If dp[i] < dp[j] + arr[i], then that subsequence sum qualifies for being the maximum one */
    for (int i = 1; i < n; i++)
        for (int j = 0; j < i; j++)
            if (arr[i] > arr[j] && dp[i] < dp[j] + arr[i])
                dp[i] = dp[j] + arr[i];

    //Now Find the maximum element in the 'dp' array
    max_sum = *max_element(arr, arr + n);

    return max_sum;
}

int main()
{
    int n, max_sum;
    cout << "\nWhat is the length of the array? ";
    cin >> n;
    int arr[n];
    cout << "Enter the numbers: ";
    for (int i = 0; i < n; i++)
    {
        cin >> arr[i];
    }
    max_sum = max_sum_increasing_subsequence(arr, n);

    cout << "The maximum sum of an increasing subsequence of the given array is " << max_sum;
    return 0;
}

/*
Time Complexity: O(num ^ 2), where 'num' is the size of the given array
Space Complexity: O(num)

SAMPLE INPUT AND OUTPUT

SAMPLE 1

What is the length of the array? 10
Enter the numbers: 23 14 5 84 24 222 321 43 123 432 
The maximum sum of an increasing subsequence of the given array is 1082

SAMPLE 2

What is the length of the array? 5
Enter the numbers: 5 4 3 2 1
The maximum sum of an increasing subsequence of the given array is 5
*/


<|start_filename|>C/sort/HeapSort.c<|end_filename|>
/* 
Heap Sort 
Heap Sort is treated as the best sorting technique in the category of selection sorting .
It uses a heap tree as an underlying data structure to soer an array of elements
This is an inplace sorting algorithm as it does not require any extra storage space other 
than the input storage list. This algorithm requires 3 basic steps 
Create heap : Create the initial heap tree with n elements stored in the array A
Remove max : Select the value in the root node and swap with the value in the i'th 
location
Rebuild heap : Rebuild the heap for elements A[1,2,3,..., i - 1]
The first operation is done once , the second and third are done n times 
*/
#include <stdio.h>
#include <stdlib.h>

/* removeMax function is to remove the maximum element, 
which is at the root of the Max heap */

void removeMax(int *b, int n)
{
    int temp = b[n];
    b[n] = b[1];
    b[1] = temp;
}

/* swap function swaps the position of the given two numbers
in the sequence */

void swap(int *b, int a, int c)
{
    int temp = b[a];
    b[a] = b[c];
    b[c] = temp;
}

/* 
reBuildHeap function rebuilds the heap from which the root element was 
removed.
*/

void reBuildHeap(int *b, int i)
{
    if (i == 1)
    {
        return;
    }
    int j = 1;
    int flag = 1;
    while (flag == 1)
    {
        int left = 2 * j, right = (2 * j) + 1;
        if (right <= i)
        {
            if (b[j] <= b[left] && b[left] >= b[right])
            {
                swap(b, left, j);
                j = left;
            }
            else
            {
                if (b[j] <= b[right] && b[right] >= b[left])
                {
                    swap(b, right, j);
                    j = right;
                }
                else
                {
                    flag = 0;
                }
            }
        }
        else
        {
            if (left <= i)
            {
                if (b[j] <= b[left])
                {
                    swap(b, left, j);
                    j = left;
                }
                else
                {
                    flag = 0;
                }
            }
            else
            {
                flag = 0;
            }
        }
    }
}

/*
createHeap function creates a MAX heap from the given sequence of numbers
*/

int *createHeap(int *ar, int n)
{
    int i = 1;
    int *b = (int *)malloc(sizeof(int) * (n + 1));
    while (i <= n)
    {
        int x = ar[i];
        b[i] = x;
        int j = i;
        while (j > 1)
        {
            if (b[j] > b[j / 2])
            {
                int temp = b[j];
                b[j] = b[j / 2];
                b[j / 2] = temp;
                j = j / 2;
            }
            else
            {
                j = 1;
            }
        }
        i++;
    }
    return b;
}

/*
heap_sort function sort the given array of digits 
*/

void heap_sort(int *ar, int n)
{
    int *b = createHeap(ar, n);
    for (int i = n; i > 1; i--)
    {
        removeMax(b, i);
        reBuildHeap(b, i - 1);
    }
    for (int i = 1; i <= n; i++)
    {
        ar[i] = b[i];
    }
}

int main()
{
    int n;
    printf("Enter the number of elements to sort\n");
    scanf("%d", &n);
    int *ar = (int *)malloc(sizeof(int) * (n + 2));
    printf("Enter the elements to sort\n");
    for (int i = 1; i < n + 1; i++)
        scanf("%d", &ar[i]);

    heap_sort(ar, n);
    printf("The sorted list :\n");
    for (int i = 1; i < n + 1; i++)
        printf("%d ", ar[i]);
    return 0;
}

/*
Sample I/O :
Enter the number of elements to sort
5
Enter the number of elements to sort
4 3 2 5 1
The sorted list :
1 2 3 4 5

Time Complexity : O(n log n)
Space Complexity : O(1) 
*/


<|start_filename|>C-Plus-Plus/dp/Rectangle_cutting.cpp<|end_filename|>
/*
Given an a×b rectangle, your task is to cut it into squares. On each move you can select a rectangle and cut it into two
rectangles in such a way that all side lengths remain integers. What is the minimum possible number of moves?

Input

The only input line has two integers a and b.

Output

Print one integer: the minimum number of moves.

Constraints

1≤a,b≤500

Example

Input:
3 5

Output:
3

*/

/*
                                APPROACH
            ----------------------------------------------------
            We will make all the horizontal cuts and try to find 
            after which move we have to make minimum moves to make 
            all squares,
            Similarly,
            We do the same with vertical moves,
            We will divide the recetanle in two parts and add the 
            result for both parts and find minimum among all moves
            which will be our ans.

*/
#include <iostream>
using namespace std;
int dp[501][501]; //declaring dp array for memorization.
int cutting(int a,int b)
{
    //if side lengths are equal then no move required.
    if(a==b)
    return 0;
    //for a by 1 or 1 by b rectangle we have to make a-1 and b-1 cuts respectively.
    if(a==1 || b==1)
    return max(a,b)-1;

    //if the result is stored already return it.
    if(dp[a][b]!=-1)
    return dp[a][b];

    int ans=INT_MAX;
    
    //recursivly making cuts.
    //loop to make all the horizontal cuts
    /*
        iterate upto a/2 only wwwww
    */
    for(int i=1;i<=a/2;i++)
    {
        //making every position move and taking the minimum out of it.
        ans=min(ans,cutting(i,b)+cutting(a-i,b));
    }
    
    //loop to make all the vertical cuts
    for(int i=1;i<=b/2;i++)
    {
        //making every position move and taking the minimum out of it.
        ans=min(ans,cutting(a,i)+cutting(a,b-i));
    }
    return dp[a][b]=1+ans; //this 1 corressponds to one of the minimum move we have done above.
}
int cutting_iterative(int a,int b)
{
    int dp[a+1][b+1];

    //These 2 loops are for base case.
    for(int i=1;i<=a;i++)
    dp[i][1]=i-1;
    for(int i=1;i<=b;i++)
    dp[1][i]=i-1;
    for(int i=2;i<a+1;i++)
    {
        for(int j=2;j<b+1;j++)
        {
            if(i==j)
            dp[i][j]=0;
            else
            {
                int ans=INT_MAX;
                for(int k=1;k<=i/2;k++)
                ans=min(ans,dp[k][j]+dp[i-k][j]);
                for(int k=1;k<=j/2;k++)
                ans=min(ans,dp[i][k]+dp[i][j-k]);
                dp[i][j]=1+ans;
            }
        }
    }
    return dp[a][b];
}   
int main(){
    int a,b;
    cin>>a>>b;
    for(int i=0;i<=a;i++) for(int j=0;j<=b;j++) dp[i][j]=-1; //initialising the DP Array for Memorization.
    cout<<cutting(a,b)<<endl;//call to the function to find the answer using memorization.
    cout<<cutting_iterative(a,b)<<endl;//call to function to find the answer using iteration.
    return 0;
}

<|start_filename|>Julia/search/jump_search.jl<|end_filename|>
"""Julia program to implement Jump Search algorithm.
Jump Search is a searching algorithm similar to binary search, where a sorted array is searched. 
In this algorithm, only fewer comparisons are done, by jumping ahead some elements while traversal
"""


function jump_search(arr, num, ele)

    # Size by which the traversing index should be jumped is calculated.
    jump = floor(Int, sqrt(num))
    step = jump
    temp = 1
    
    """ The entire sorted array is divided into blocks of sqrt(n) size and the block just after which the
        required element is present is being identified. and the previous block starting index is stored in temp""" 
    while (arr[min(step, num)] < ele)
        temp = step
        step = step + jump
        if (temp >= num)
            return false
        end
    end

    # The identified block, is searched via linea search for the required element.
    while (arr[temp] < ele)
        temp = temp + 1
        if (arr[temp] == ele)
            return true
        end
        # Check if the end of the array or end of the block is reached 
        if (temp == min(step, num))
            return false
        end
    end
    if (arr[temp] == ele)
        return true
    else
        return false
    end
end


print("How many numbers are present in the array? ")
n = readline()
n = parse(Int, n)
if (n <= 0)
    println("Array is Empty!!!")
    exit()
end
arr = Int[]
print("Enter the numbers: ")
arr = [parse(Int, num) for num in split(readline())] 
print("Which number do you want to search in the array? ")
ele = readline()
ele = parse(Int, ele)
# Sort the array in ascending order
arr = sort(arr)
res = jump_search(arr, n, ele)
if (res == 0)
    print("The number $ele is not present in the array")
else
    print("The number $ele is present in the array.")
end



"""
Time Complexity - O(n^(0.5)), where 'n' is the size of the array
Space Complexity - O(n)

SAMPLE INPUT AND OUTPUT

SAMPLE I

How many numbers are present in the array? 5 
Enter the numbers: 1 2 3 4 5
Which number do you want to search in the array? 6
The number 6 is not present in the array

SAMPLE II

How many numbers are present in the array? 3
Enter the numbers: 3 1 2
Which number do you want to search in the array? 2
The number 2 is present in the array.

"""


<|start_filename|>Julia/cp/Prime_factorization.jl<|end_filename|>
#= Given a number n, print its prime factorization. We could do it 
normal way which will be having time complexity of O (sqrt(N)) 
but we will be using Sieve to lessen the time complexity
We will make a sieve to get all the prime numbers and then get the 
prime factorization of the number using that.=#

## Function

function PrimeFactor(n)
    a = zeros(Int64, n)
    for i = 2:n
        a[i] = i
    end
    for i = 2:n
        if (a[i] == i)
            for j = (i*i):i:n
                if (a[j] == j)
                    a[j] = i
                end
            end
        end
    end
    while (n != 1)
        println(a[n])
        n = div(n, a[n])
    end
end

## Input

n = readline()
n = parse(Int64, n)

#Calling the function

PrimeFactor(n)

#=
Sample Test case
Input:
    n = 495
Output:
    3 3 5 11

Time Complexity: O( log N )
=#

<|start_filename|>C/ds/doubly_linked_list.c<|end_filename|>
#include <stdio.h>
#include <malloc.h>

/*
Code Description :
Doubly linked list is a type of linked list in which each node
has a data part and two pointer part. The first pointer points 
to the previous node in the list and the second pointer points 
to the next node in the list.

In the code below we have created the structure of doubly linked list.
We have also provided options to the user to choose among the opearations.

As per the option selected, respective switch-case will execute and function 
will be called. Brief description of each function is also provided below.
*/

struct node
{
    int info;
    struct node *prev,*next;
};

struct node *start = NULL;

//Function Declarations
void insertstart();
void insertlast();
void insertafter(struct node *);
struct node* find ();
void insertat();
void deletefirst();
void deletelast();
void deleteafter();
void viewlist();


int main()
{
    int choice;
    char ans = 'Y';
    
    while(ans == 'Y' || ans == 'y')
    {
        printf("\n\n Operations on doubly linked list");
        printf("\n----------------------------------");
        printf("\n 1- To view the list.");
        printf("\n 2- Insertion of element at starting.");
        printf("\n 3- Insertion of element at end.");
        printf("\n 4- Insertion of element at any position by providing previous element.");
        printf("\n 5- Insertion of element at any position by providing index.");
        printf("\n 6- Deletion of the first element.");
        printf("\n 7- Deletion of the last element.");
        printf("\n 8- Delete an element from any position.");
        printf("\n 9- To exit.");
        printf("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
        printf("\nEnter your choice : ");
        scanf("%d" , &choice);

        switch(choice)
        {
        case 1:
                viewlist();
                break;
        case 2:
                insertstart();
                break;
        case 3:
                insertlast();
                break;
        case 4:
                insertafter(find());
                break;
        case 5:
                insertat();
                break;
        case 6:
                deletefirst();
                break;
        case 7:
                deletelast();
                break;
        case 8:
                deleteafter();
                break;
        case 9:
        		printf("\nExiting :\n");
                return 0;
                break;
        default:
            printf("\nIncorrect Choice!\n");
            break;
        }
        printf("\nYOU WANT TO CONTINUE (Y/N) : ");
        scanf(" %c", &ans);
    }
    return 0;
}

/*
To insert a node at the starting of the Doubly linked list,
create a new node and make it point by the start pointer.
*/

void insertstart()
{
    int data;
    struct node *temp;
    temp = (struct node*) malloc (sizeof(struct node));
    printf("\nEnter the element : ");
    scanf("%d" , &data);
    temp->info = data;
    temp->prev = NULL;
    temp->next = start;
    start = temp;
}

/*
To insert a node at the end of the Doubly linked list,
create a new node and make it pointed by the previously last node.
*/

void insertlast()
{
    int data;
    struct node *temp , *trav;
    temp = (struct node*) malloc (sizeof(struct node));
    printf("\nEnter the element : ");
    scanf("%d" , &data);
    temp->info = data;
    temp->next = NULL;
    trav = start;
    if(start == NULL)
    {
        temp->prev = NULL;
        start = temp;
    }
    else
    {
        while(trav->next != NULL)
            trav = trav->next;
        temp->prev = trav;
        trav->next = temp;
    }
}

/*
To insert a node at a specific position of the Doubly linked list,
create a new node, traverse the list till the desired position,
make the new node pointed by the previous node. 
Also make the new node point to the previou's next node.
*/

void insertafter(struct node *ptr)
{
    int data;
    struct node *temp;
    temp = (struct node*) malloc (sizeof(struct node));
    if(ptr == NULL)
        printf("\nThe list is empty.\n");
    else
    {
         printf("\nEnter the element : ");
         scanf("%d" , &data);
         temp->info = data;
         temp->prev = ptr;
         temp->next = ptr->next;
         ptr->next->prev = temp;
         ptr->next = temp;
    }
}


struct node* find ()
{
    int data;
    struct node *temp;
    if(start == NULL)
        return NULL;
    else
    {
        printf("\nEnter the element after which you want the insertion : ");
        scanf("%d" , &data);
        temp = start;
        while(temp != NULL)
        {
            if(temp->info == data)
                return temp;
            else
                temp = temp->next;
        }
        return NULL;
    }
}

void insertat()
{
    int data , pos , i=1;
    struct node *temp , *newnode;
    newnode = malloc(sizeof(struct node));
    printf("\nEnter the index/position : ");
    scanf("%d" , &pos);
    printf("\nEnter the element : ");
    scanf("%d" , &data);
    newnode->info = data;
    temp = start;
    if(start == NULL)
    {
        start = newnode;
        newnode->prev = NULL;
        newnode->next = NULL;
    }
    else
    {
        while(i < pos-1)
        {
            temp = temp->next;
            i++;
        }
        newnode->next = temp->next;
        newnode->prev = temp;
        temp->next = newnode;
        temp->next->prev = newnode;
    }

}

/*
To delete the first node, make start ointer point to the next node.
*/

void deletefirst()
{
    struct node *temp;
    if(start == NULL)
        printf("\nThe list is empty.\n");
    else
    {
        temp = start;
        start = start->next;
        start->prev = NULL;
        free(temp);
    }
}

/*
To delete the last node, traverse till second last node;
and make it point to NULL.
*/

void deletelast()
{
    struct node *temp;
    if(start == NULL)
        printf("\nThe list is empty.\n");
    else
    {
        temp = start;
        while(temp->next != NULL)
            temp = temp->next;
        if(start->next == NULL)
            start = NULL;
        else
        {
            temp->prev->next = NULL;
            free(temp);
        }
    }
}

/*
To delete a specific node, traverse till that node (lets say current),
use an extra pointer to point its previous node,
now make the previous node point to current node's next node.
*/


void deleteafter()
{
    int pos , i=1;
    struct node *temp , *position;
    temp = start;
    if(start == NULL)
        printf("\nThe list is empty.\n");
    else
    {
        printf("\nEnter the index : ");
        scanf("%d",&pos);
        while(i < pos-1)
        {
            temp = temp->next;
            i++;
        }
        position = temp->next;
        position->next->prev = temp;
        temp->next = position->next;

        free(position);
    }
}

/*
To view the list, use a pointer and make it point to start,
now print the node's data part and make it point to next node. 
Repeat both the steps until the pointer points to NULL.
*/

void viewlist()
{
    if(start == NULL)
        printf("\nThe list is empty.\n");
    else
    {
        struct node *temp;
        temp = start;
        printf("\nThe list is : ");
        while(temp != NULL)
        {
            printf("%d  " , temp->info);
            temp = temp->next;
        }
    }
}

/*Sample Input/Output of this program-

 Operations on doubly linked list
----------------------------------
 1- To view the list.
 2- Insertion of element at starting.
 3- Insertion of element at end.
 4- Insertion of element at any position by providing previous element.
 5- Insertion of element at any position by providing index.
 6- Deletion of the first element.
 7- Deletion of the last element.
 8- Delete an element from any position.
 9- To exit.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Enter your choice : 2

Enter the element : 10

YOU WANT TO CONTINUE (Y/N) : y


 Operations on doubly linked list
----------------------------------
 1- To view the list.
 2- Insertion of element at starting.
 3- Insertion of element at end.
 4- Insertion of element at any position by providing previous element.
 5- Insertion of element at any position by providing index.
 6- Deletion of the first element.
 7- Deletion of the last element.
 8- Delete an element from any position.
 9- To exit.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Enter your choice : 3

Enter the element : 20

YOU WANT TO CONTINUE (Y/N) : y


 Operations on doubly linked list
----------------------------------
 1- To view the list.
 2- Insertion of element at starting.
 3- Insertion of element at end.
 4- Insertion of element at any position by providing previous element.
 5- Insertion of element at any position by providing index.
 6- Deletion of the first element.
 7- Deletion of the last element.
 8- Delete an element from any position.
 9- To exit.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Enter your choice : 4

Enter the element after which you want the insertion : 10

Enter the element : 15

YOU WANT TO CONTINUE (Y/N) : y


 Operations on doubly linked list
----------------------------------
 1- To view the list.
 2- Insertion of element at starting.
 3- Insertion of element at end.
 4- Insertion of element at any position by providing previous element.
 5- Insertion of element at any position by providing index.
 6- Deletion of the first element.
 7- Deletion of the last element.
 8- Delete an element from any position.
 9- To exit.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Enter your choice : 1

The list is : 10  15  20
YOU WANT TO CONTINUE (Y/N) : y


 Operations on doubly linked list
----------------------------------
 1- To view the list.
 2- Insertion of element at starting.
 3- Insertion of element at end.
 4- Insertion of element at any position by providing previous element.
 5- Insertion of element at any position by providing index.
 6- Deletion of the first element.
 7- Deletion of the last element.
 8- Delete an element from any position.
 9- To exit.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Enter your choice : 6

YOU WANT TO CONTINUE (Y/N) : y


 Operations on doubly linked list
----------------------------------
 1- To view the list.
 2- Insertion of element at starting.
 3- Insertion of element at end.
 4- Insertion of element at any position by providing previous element.
 5- Insertion of element at any position by providing index.
 6- Deletion of the first element.
 7- Deletion of the last element.
 8- Delete an element from any position.
 9- To exit.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Enter your choice : 7

YOU WANT TO CONTINUE (Y/N) : y


 Operations on doubly linked list
----------------------------------
 1- To view the list.
 2- Insertion of element at starting.
 3- Insertion of element at end.
 4- Insertion of element at any position by providing previous element.
 5- Insertion of element at any position by providing index.
 6- Deletion of the first element.
 7- Deletion of the last element.
 8- Delete an element from any position.
 9- To exit.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Enter your choice : 1

The list is : 15
YOU WANT TO CONTINUE (Y/N) : n

Process returned 0 (0x0)   execution time : 50.165 s
Press any key to continue.

*/



<|start_filename|>Java/cp/LongestSubstringNoRepeatingChar.java<|end_filename|>
/**
 * Length of Longest Substring Without Repeating Characters
 * Given a string, print the longest possible substring that has 
 * no repeating characters, i.e., all its characters are distinct. 
 * Consider a String contains upper and lower case alphabets.
 */

import java.io.*; 
public class LongestSubstringNoRepeatingChar {

    //Function returns true only if each character's count 
    //is <= 1, i.e., substring is valid
    static boolean isDistinct(int[] charCount) {
        for(int i=0; i<52; i++) {
            if(charCount[i] > 1)
                return false; 
        }
        return true; 
    }

    public static int findLongestSubstring(String str) {

        int charCount[] = new int[52]; //Maintains count of each alphabet

        //Variable len stores length of longest valid substring, while start and end
        //are limits of the current window (substring) being considered 
        int len = 0, start=0;
        for(int end=0; end<str.length(); ) {
            char ch = str.charAt(end); 

            if(ch >= 'a' && ch <= 'z') //Lower-case letter
                charCount[ch - 'a']++; 
            else //Upper-case letter
                charCount[ch - 'A' + 26]++;
            end++;

            if(isDistinct(charCount)) {
                len = Math.max(len, end-start);
                continue; 
            }

            //If there are repeating characters, we shorten substring by removing
            //characters from start, till we get a distinct substring.
            while(!isDistinct(charCount)) {
                ch = str.charAt(start); 
                if(ch >= 'a' && ch <= 'z')
                    charCount[ch - 'a']--; 
                else
                    charCount[ch - 'A' + 26]--;
                start++; 
            }
            len = Math.max(len, end-start); 
        }
        return len;
    }
    
    public static void main(String[] args) throws IOException{
        InputStreamReader read = new InputStreamReader(System.in);
	    BufferedReader buf = new BufferedReader(read); 

        //Taking input from user
        System.out.println("Enter a String of alphabets: ");
        String str = buf.readLine().trim();  

        System.out.println("Length of longest substring with no repeating" +
                        " characters: " + findLongestSubstring(str)); 
    }

}

/*
    Time complexity: O(Length of String)
    Space complexity: O(52) (total number of lower and upper case alphabets)

    TEST CASES

    INPUT
    Enter a String of alphabets: 
    pqrsqptrot
    OUTPUT
    Length of longest substring with no repeating characters: 6

    INPUT
    Enter a String of alphabets: 
    trialAndErroR
    OUTPUT
    Length of longest substring with no repeating characters: 9

 */


<|start_filename|>C-Plus-Plus/cp/first_non_repeating_character.cpp<|end_filename|>
/*Problem statement :
Print the first non repeating character in a running stream of characters, 
that is the characters will input continuously until a '.'
is encountered you need to keep printing the first non repeating character. */

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

void first_non_repeating(queue<char> q, int frequency[])
{
        while (!q.empty())
        {
            int index = q.front() - 'a';
            //If character already exists more than once, then pop
            if (frequency[index] > 1)
            {
                q.pop();
            }
            else
            {
                cout << q.front() << endl;
                break;
            }
        }

        if (q.empty())
        {
            cout << "-1" << endl;
        }
}

int main()
{
    queue<char> q;
    int frequency[27] = { 0 };

    char ch;
    cin >> ch;
    while (ch != '.')
    {
        q.push(ch);
        frequency[ch - 'a']++;
        first_non_repeating(q,frequency);
        cin >> ch;
    }

    return 0;
}
/*
Example :
1)Input = a a b c c .
Output = a -1 b b b
2)Input: s d d g .
Output: s s s s 
Time Complexity : O(n) 
Space Complexity : O(1) */



<|start_filename|>C-Plus-Plus/cp/search_insert_position.cpp<|end_filename|>
/*
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
*/

#include <iostream>
using namespace std;

int search_insert_position(int arr[], int n, int target) {
	int l = 0, r = n - 1;
	int mid;
	while (l <= r) {
		mid = l + ((r - l) / 2);
		if (target > arr[mid])
			l = mid + 1;
		else if (target < arr[mid])
			r = mid - 1;
		else
			return mid;
	}
	return l;
}

int main() {
	int n;
	cin >> n;
	int arr[n];
	for (int i = 0; i < n; i++)
		cin >> arr[i];
	int target;
	cin >> target;
	int ans = search_insert_position(arr, n, target);
	cout << ans;
	return 0;
}


/*
TIME COMPLEXITY:- O(log2n)
SPACE COMPLEXITY:- O(n)

OUTPUT:-
5
2 3 4 5 6
4
2
*/


<|start_filename|>Java/ds/QueueandStack.java<|end_filename|>
//Qs class for implementing queue using two stack with costly dequeue() 
import java.util.Scanner;
class QueueUsingStack {
	int s1[];			//First stack
	int s2[];			//Second stack
	int size;			//size of queue
	int topS1;			//To maintain top of stack 1
	int topS2;			//To maintain top of stack 2
	int count;  		//To count number of items in queue
	public QueueUsingStack(int s)
	{
		topS1 = 0;
		topS2 = 0;
		count = 0;
		size = s;
		s1 = new int[size];
		s2 = new int[size];
	}
	public void pushS1(int d)	  //Function to push an item of stack 1
	{
		s1[topS1] = d;
		topS1++;
	}
	public int popS1()	         //Function to pop an item of stack 1
	{
		topS1--;
		int temp = s1[topS1];
		return temp;
	}
	public void pushS2(int d)	 //Function to push an item of stack 2
	{
		s2[topS2] = d;
		topS2++;
	}
	public int popS2()			//Function to pop an item of stack 1
	{
		topS2--;
		int temp = s2[topS2];
		return temp;
	}
	public boolean isFull(int c) 	//Function to check whether queue is full or not
	{
		return (c == size);
	}
	public boolean isEmpty(int c)	//Function to check whether queue is empty or not
	{
		return (c == 0);
	}
	
	public void enqueue(int d)		// Function to enqueue an item to the queue
	{
		if(isFull(count))
		{
			System.out.println("Queue is full");
			System.exit(0);
		}
		else {
			pushS1(d);
			count++;
		}
	}
	public int dequeue()		//Function to deQueue an item from queue
	{
		int temp,i,dq;
		if(isEmpty(count))
		{
			System.out.println("Queue is empty");
			System.exit(0);
		}

		//push all the items in stack 2
		for(i=0;i<count;i++)
		{
			temp = popS1();
			pushS2(temp);
		}
		dq = popS2();
		count--;

		//After poping push all the items of stack 2 back into stack 1
		for(i=0;i<count;i++)
		{
			temp = popS2();
			pushS1(temp);
		}
		return dq;
	}
	public void display()
	{
		int i;
		for(i=0;i<count;i++)
		{
			System.out.print(s1[i]+" ");
		}
	}
}

//Sq class to implement a stack using two queue with costly push()
class StackUsingQueue {
	int q1[];		//First queue
	int q2[];		//Second queue
	int front1;		//To maintain front of queue 1
	int front2;		//To maintain front of queue 2
	int rear1;		//To maintain rear of queue 1
	int rear2;		////To maintain rear of queue 2
	int size;		//size of stack
	int count;		//to count number of items in stack
	public StackUsingQueue(int s)
	{
		size = s;
		q1 = new int[size];
		q2 = new int[size];
	}
	public void enqueue1(int d)			//Function to enqueue an item from queue 1
	{
		q1[rear1] = d;
		rear1 = (rear1+1)%size;
	}
	public int dequeue1()				//Function to dequeue an item from queue 1
	{
		int temp = q1[front1];
		front1 = (front1+1)%size;
		return temp;
	}
	public void enqueue2(int d)			//Function to enqueue an item from queue 2
	{
		q2[rear2] = d;
		rear2 = (rear2+1)%size;
	}
	public int dequeue2()				//Function to dequeue an item from queue 2
	{
		int temp = q2[front2];
		front2 = (front2+1)%size;
		return temp;
	}
	public boolean isFull(int c)		//Function to check whether stack is full or not
	{
		return (c == size);
	}
	public boolean isEmpty(int c)		//Function to check whether stack is empty or not
	{
		return (c == 0);
	}
	public void push(int d)				//Function to push an item into a stack
	{
		int i,temp;
		if(isFull(count))
		{
			System.out.println("Stack is full");
			System.exit(0);
		}
		enqueue2(d);
		for(i=0;i<count;i++)
		{
			temp = dequeue1();
			enqueue2(temp);
		}
		count++;

		//Swap the name of two queues
		int q[] = new int[q1.length];
		q = q1;
		q1 = q2;
		q2 = q;
	}
	public int pop()					//Function to pop an item from a stack
	{
		int temp;
		if(isEmpty(count))
		{
			System.out.println("Stack is empty");
			System.exit(0);
		}
		temp = dequeue1();
		count--;
		return temp;
	}
	public void display(int k)
	{
		int i;
		for(i=k;i<count+k;i++)
		{
			System.out.print(q1[i]+" ");
		}
	}
}

//QueueandStack class with main function to operate Qs and Sq class
public class QueueandStack {
	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter 1 for implementing Queue using Stack");
		System.out.println("Enter 2 for implementing Stack using Queue");
		int n = sc.nextInt(); 
		if(n == 1)  	//For implementing queue using stack
		{
			System.out.println("Enter the size of Queue");
			int s = sc.nextInt();
			QueueUsingStack obq = new QueueUsingStack(s);
			System.out.println("Enter 1 for Enqueue");
			System.out.println("Enter 2 for Dequeue");
			System.out.println("Enter 3 to display Queue");
			System.out.println("Enter 4 to exit");
			while(true)
			{
				int ch = sc.nextInt();
				switch(ch) 
				{
					case 1:
						System.out.println("Enter the number to enqueue");
						int d = sc.nextInt();
						obq.enqueue(d);
						System.out.println("Number enqueued successfully");
						break;
					case 2:
						int temp = obq.dequeue();
						System.out.println(temp+" is dequeued");
						break;
					case 3:
						obq.display();
						break;
					case 4:
						System.exit(0);
				}
			}
		}
		else			//For implementing stack using queue
		{
			int k = 0;
			System.out.println("Enter the size of Stack");
			int s = sc.nextInt();
			StackUsingQueue obs = new StackUsingQueue(s);
			System.out.println("Enter 1 for Push");
			System.out.println("Enter 2 for Pop");
			System.out.println("Enter 3 to display Stack");
			System.out.println("Enter 4 to exit");
			while(true)
			{
				int ch = sc.nextInt();
				switch(ch) 
				{
					case 1:
						System.out.println("Enter the number to Push");
						int d = sc.nextInt();
						obs.push(d);
						System.out.println("Number pushed successfully");
						break;
					case 2:
						int temp = obs.pop();
						k++;
						System.out.println(temp+" is poped");
						break;
					case 3:
						obs.display(k);
						break;
					case 4:
						System.exit(0);
				}
			}
		}
	}
}



/*Output:

--------------------------------------------
Output of implementing Queue using Stack
--------------------------------------------

Enter 1 for implementing Queue using Stack
Enter 2 for implementing Stack using Queue
1
Enter the size of Queue
3
Enter 1 for Enqueue
Enter 2 for Dequeue
Enter 3 to display Queue
Enter 4 to exit
1
Enter the number to enqueue
1
Number enqueued successfully
1
Enter the number to enqueue
2
Number enqueued successfully
1
Enter the number to enqueue
3
Number enqueued successfully
2
1 is dequeued
3
2 3 

--------------------------------------------
Output of implementing Stack using Queue
--------------------------------------------

Enter 1 for implementing Queue using Stack
Enter 2 for implementing Stack using Queue
2
Enter the size of Stack
3
Enter 1 for Push
Enter 2 for Pop
Enter 3 to display Stack
Enter 4 to exit
1
Enter the number to Push
1
Number pushed successfully
1
Enter the number to Push
2
Number pushed successfully
1
Enter the number to Push
3
Number pushed successfully
2
3 is poped
3
2 1 
 */


<|start_filename|>C-Plus-Plus/other/Kth_smallest_element.cpp<|end_filename|>
/* Q Kth smallest element 

Given an array a[] and a number K where K is smaller than size of array, 
the task is to find the Kth smallest element in the given array.
It is given that all array elements are distinct. */


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

//find the kth samllest Element
void kthSmallestElement(int arr[], int size, int k){

    priority_queue <int> maxHeap;
    
    for(int i = 0; i < size; i++){
        maxHeap.push(arr[i]);
        
        if(maxHeap.size() > k){
            maxHeap.pop();
        }
    }
    cout<< "Kth smallest element in the array is: "<< maxHeap.top();
}

int main()
{
    int size, k;
     
    cout << "Enter the size of an Array : ";
    cin >> size;

    cout << "Enter the value of k : ";
    cin>> k;

    cout<< "Enter the elements of the array: " << endl;

    int arr[size];
    

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

    kthSmallestElement(arr, size, k);  
    
    return 0;
}

/*
Input 
Enter the size of an Array : 7                                                                                                                
Enter the value of k : 3                                                                                                                      
Enter the elements of the array:                                                                                                              
7 5 9 8 4 6 10      

Output
Kth smallest element in the array is: 6 

Space complexity => O(k)
Time complexity => O(nlogk)
*/

<|start_filename|>Java/cp/ReverseString.java<|end_filename|>

/* Program to reverse a string */

import java.io.*;
import java.util.*;
 
// Main class

class Program {
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);

        // Accepting input from user

        System.out.println("Enter string");
        String str = sc.nextLine();

        // revoking the function reverse

        reverse(str);
        
    }

    // Method for reversing the string

    static void reverse(String s){

        // Reversing the string by extracting each element from the end of the string and storing in a variable result

        String result = "";
        for (int i = s.length() - 1; i >= 0; i--)
            result += s.charAt(i);

        // Printing the reversed string

        System.out.println(result);
       
    }

}

/* Time Complexity is O(n)
   Space Complexity is O(n)
   
   Input :
   Hello World
   
   Output :
   dlroW olleH
*/


<|start_filename|>C-Plus-Plus/ds/Reverse_linked_list.cpp<|end_filename|>
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
    int data;
    Node* next;
    Node(int data)
    {
        this -> data = data;
        this -> next = NULL;
    }
};
/* 
The helper class for the basic utility 
functions used in Linked List algorithms

1 - length - to return length of the Linked List
2 - print_ll - print the linked list to the output console
3 - take_input - take input from the user, terminated by -1
4 - Node* copy=NULL;
*/
class helper
{
public:
    int length(Node* head)
    {
        Node* temp = head;
        int count = 0;
        while(temp != NULL)
        {
            temp = temp -> next;
            count++;
        }
        return count;
    }
    void print_ll(Node* head)
    {
        Node *temp=head;
        while(temp != NULL)
        {
            cout << temp -> data <<"--> ";
            temp= temp -> next;
        }
        cout<<"NULL"<<endl;
    }
    Node* take_input()
    {
        cout<<"Enter data to enter into the linked list and add -1 at the end of link list : ";
        int data;
        cin >> data;
        Node* head = NULL;
        Node* tail = NULL;
        if(data==-1)
            cout<<"Link List is Empty please try again.";
        while(data != -1)
        {
            Node* n = new Node(data);
            if(head==NULL)
            {
                head = n;
                tail = n;            
            }
            else
            {
                tail -> next = n;
                tail = tail -> next;
            }
            cin >> data;
        }
        return head;
    }
    Node *copy(Node *ref)
    {
        if(ref==NULL) return ref;
        Node *temp=(Node *)malloc(sizeof(Node));
        temp->data=ref->data;
        temp->next=copy(ref->next);
        return temp;
    }
};

/// The main algorithmic solution class
class solution
{
public:    
     /// Recursive approach
     Node* reverse_linked_recursive(Node* head)
     {
         /// if head or it's next pointer are null
         if(head == NULL || head -> next == NULL)
         {
             return head;
         }
         /// getting small output using recursion
         Node* small_head = reverse_linked_recursive(head -> next);
         head -> next = NULL;         
         /// Traversing to the end node
         Node* temp = small_head;
         while(temp -> next != NULL)
         {
            temp = temp -> next;
         }        
         /// Putting the head pointer at the next of end node
         temp -> next = head;
         head = small_head;
         return head;
     }
     /// The iterative approach
     Node* reverse_linked_iterative(Node* head)
     {
         /// if head or it's next pointer are null
         if(head == NULL || head -> next == NULL)
         {
             return head;
         }      
         /*
          getting three pointers,
          
          prev = to store the previous pointer
          temp = auxiliary storage (Node pointer)
          curr = current pointer
         
         */      
         Node* prev = NULL;
         Node *temp;
         Node  *curr = head;
         while(curr)
         {
             temp = curr -> next;
             curr -> next = prev;
             prev = curr;
             curr = temp;
         }
         head=prev;
         return head;
     }    
};
int main()
{
    helper help_object;
    solution sol;
    Node* head = help_object.take_input();
    //clone of head pointer
    Node *copy=help_object.copy(head);
    Node* head2 = sol.reverse_linked_recursive(head);
    Node* head3 = sol.reverse_linked_iterative(copy);
    help_object.print_ll(head2);
    help_object.print_ll(head3);
    return 0;
}

/*Sample Input Output
Enter Data to enter into linked list and add -1 at the end of the list :
1
2
3
4
5
-1
Output in both approach :
5 -> 4 -> 3 -> 2 -> 1 -> NULL
5 -> 4 -> 3 -> 2 -> 1 -> NULL
*/


<|start_filename|>C-Plus-Plus/math/Tower_Of_Hanoi.cpp<|end_filename|>
/*
The Tower of Hanoi is a very famous mathematical problem. You have three rods and n disks. Initially all the n disks are stacked on one rod.
The task is to take all those disks from one rod to some other rod following these rules:
1) Only one disk can be moved among the towers at any given time.
2) There can be no disk mounted on top of a smaller disk.
3) Only the "top" disk can be removed.
4) A disk can be moved only if it is the stack's uppermost disk.
    
Program will print the source and destination to transfer each disks for all the steps in chronological order.
*/

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

void tower_of_hanoi(int n, char from_rod, char aux_rod, char to_rod)
{
	/*
		This function takes the number of disks and the names of the rods.
		The Idea is to shift one disk from the source to the destination.
		BUT,if there is already mutiple disk on the source then call the same function to put the extra disk on an auxiliary rod.
		AND,if there is already mutiple disk on the destination then call the same function to put the extra disk on an auxiliary rod.
	*/

	if (n == 1)
		cout << "Move a rod from the top of " << from_rod << " to the top of " << to_rod << '\n';
	else
	{
		tower_of_hanoi(n - 1, from_rod, to_rod, aux_rod);
		tower_of_hanoi(1, from_rod, aux_rod, to_rod);
		tower_of_hanoi(n - 1, aux_rod, from_rod, to_rod);
	}
}

int main()
{

	int n;
	cin >> n;	// Number of disks			
	tower_of_hanoi(n, 'A', 'B', 'C');

	return 0;
}

/* 
 Test Case :
 ******************************************************************
 Input : 2

 Output :
    Move a rod from the top of A to the top of B
    Move a rod from the top of A to the top of C
    Move a rod from the top of B to the top of C
*******************************************************************
 Input : 3
 
 Output : 
	Move a rod from the top of A to the top of C
	Move a rod from the top of A to the top of B
	Move a rod from the top of C to the top of B
	Move a rod from the top of A to the top of C
	Move a rod from the top of B to the top of A
	Move a rod from the top of B to the top of C
	Move a rod from the top of A to the top of C
********************************************************************

 Time Complexity: O(2^n)
 Space Complexity: O(n)
*/


<|start_filename|>C-Plus-Plus/ds/priorityQ_array.cpp<|end_filename|>
/******************************************************************************
Author - @Suvraneel 
        <NAME>

* Implementation of a dynamic, menu-driven Priority Queue using arrays in C++ *
******************************************************************************/

#include <iostream>
using namespace std;

//define queue's max capacity here 
#define capacity 1000
//global variable
int size = -1; 

// defines a structure for each element entered
struct item { 
    int priority;
	int data;
}priorityQ[capacity];

//function to check if queue is empty
bool isEmpty(){
    return (size == -1);
}

//function to check if queue is at capacity
bool isFull(){
    return (size == capacity-1);
}

//function to insert an element into queue
void push(int data, int priority) 
{ 
    // Increment in size
	size += 1; 
	// Insert the element 
    priorityQ[size].priority = priority;
	priorityQ[size].data = data;
    cout << "(" << priorityQ[size].data << ") " << "with priority: " << priorityQ[size].priority << " was enqueued"  << endl;
}

//function to print the entire queue in order of input entered by user
void printQ(){
    cout << "Priority\t" << "Data" << endl;
    for (int i = 0; i <= size; i++)
        cout << priorityQ[i].priority << "\t---->\t" << "(" << priorityQ[i].data << ")" << endl;    
}

// returns highest priority element without deleting it from queue
int peek() 
{
    //Initialising j (index for priority-Q)
    //objective of j is to keep track of the top priority element as of yet
    int j = -1;
    /*
    Set an element with minimum possible priority (i.e, INT_MIN) so that any value will replace the elephant
    *reference to "Elephants in Cairo" problem : 
    A piece of data that matches the search criteria purposefully inserted at the end of a search space, in order to make sure the search algorithm terminates; it is a humorous example of a sentinel value.
    */
	int elephant = INT_MIN; 

	// Check for the element with highest priority (=>definitely not the hypothetical INT_MIN)
	for (int i = 0; i <= size; i++) { 
        if (priorityQ[i].priority > elephant) { 
            //Set that element as highest priority as of yet
			elephant = priorityQ[i].priority;
            //Set j as current index
			j = i; 
		}
		// Priority Tie-breaker : highest data 
		else if (priorityQ[i].priority == elephant && priorityQ[i].data < priorityQ[j].data && j > -1) { 
			elephant = priorityQ[i].priority; 
			j = i; 
		}
	} 
	// Return index
	return j;
}

// Function to remove the element with the highest priority 
void pop() 
{ 
    //To pop the highest priority element, we use peek function
	//peek returns the top priority element when called... the one to be dequeued
	int deQ = peek();
    cout << "(" << priorityQ[deQ].data << ")" << " with priority: " << priorityQ[deQ].priority << " was dequeued";
	// Simply keep shifting all the elements by a slot towards deQ, hence replacing it
	for (int i = deQ; i < size; i++) { 
		priorityQ[i] = priorityQ[i + 1]; 
	}

	// Leads to decrement in size
	size -= 1; 
}

// Main Driver Code (menu-driven)
int main() 
{ 
    //main method
    int choice, entry, priority;
    cout << "1 - Enqueue an element..." << endl;
    cout << "2 - Dequeue an element..." << endl;
    cout << "3 - Display the top priority element" << endl;
    cout << "4 - Display number of elements in queue" << endl;
    cout << "5 - Display current queue" << endl;
    cout << "6 - Exit" << endl;

    while(1)
    {
        cout << endl << "Enter choice:\t";
        cin >> choice;
        switch(choice)
        {
            case 1:
                if (!isFull())
                {
                    cout << "Enter element to enqueue & its priority:";
                    cin >> entry >> priority;
                    push(entry, priority); 
                }
                else cout << "Queue Full";
                break;

            case 2:
                //provided queue isn't empty
                if (!isEmpty())
                    pop();
                break;

            case 3:{    
                int max_prior = peek(); 
                cout << "Element with maximum priority in queue: \n(" << priorityQ[max_prior].data << ") with priority: " << priorityQ[max_prior].priority << endl;
                break;
            }

            case 4:
                cout << "No. of elements in queue currently\t:" << size+1 << endl;
                break;

            case 5:
                printQ();
                break;

            case 6:
                cout << "Program terminated successfully.";
                exit(0);
        }
    }

	return 0; 
}

/*
Time Complexity:
    Enqueue : O(1)
    Peek : O(n)
    Dequeue : O(1) + O(n) for seek = O(n)

Space Complexity: O(n) for array

Sample Run Output:
1 - Enqueue an element...
2 - Dequeue an element...
3 - Display the top priority element
4 - Display number of elements in queue
5 - Display current queue
6 - Exit

Enter choice:   1
Enter element to enqueue & its priority:10 1
(10) with priority: 1 was enqueued

Enter choice:   1
Enter element to enqueue & its priority:20 2
(20) with priority: 2 was enqueued

Enter choice:   1
Enter element to enqueue & its priority:100 5
(100) with priority: 5 was enqueued

Enter choice:   1
Enter element to enqueue & its priority:50 3
(50) with priority: 3 was enqueued

Enter choice:   1
Enter element to enqueue & its priority:75 4
(75) with priority: 4 was enqueued

Enter choice:   5
Priority        Data
1       ---->   (10)
2       ---->   (20)
5       ---->   (100)
3       ---->   (50)
4       ---->   (75)

Enter choice:   4
No. of elements in queue currently      :5

Enter choice:   2
(100) with priority: 5 was dequeued
Enter choice:   4
No. of elements in queue currently      :4

Enter choice:   5
Priority        Data
1       ---->   (10)
2       ---->   (20)
3       ---->   (50)
4       ---->   (75)

Enter choice:   3
Element with maximum priority in queue: 
(75) with priority: 4

Enter choice:   6
Program terminated successfully.
*/



<|start_filename|>C/ds/removeDuplicate.c<|end_filename|>
/*
 A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. It is a 
collection of nodes.Nodes consists of 2 parts data part and address part. Address part contains the address of the next or the 
successor node. In this program, duplicate elements present in sorted linked list is removed. 
*/

#include <stdio.h>
#include <stdlib.h>

struct Node
{
  int data;
  struct Node *next;
}*first=NULL,*second=NULL,*third=NULL;


void Display(struct Node *p)
{
    while(p!=NULL)
    {
        printf("%d ",p->data);
        p=p->next;
    }
}

void create(int A[],int n)
{
    int i;
    struct Node *t,*last;
    first=(struct Node *)malloc(sizeof(struct Node));
    first->data=A[0];
    first->next=NULL;
    last=first;

    for(i=1;i<n;i++)
    {
        t=(struct Node*)malloc(sizeof(struct Node));
        t->data=A[i];
        t->next=NULL;
        last->next=t;
        last=t;
    }
}

void removeDuplicate(struct Node *p)
{
    struct Node *q=p->next;

    while(q!=NULL)
    {
        if(p->data!=q->data)
        {
                p=q;
                q=q->next;
        }
        else
        {
            p->next=q->next;
            free(q);
            q=p->next;
        }
    }
}

int main()
{
    int A[]={10,20,20,40,50,50,50,60};
    clrscr();
    printf("Sorted list with no duplicate elements is : ");
    create(A,8);
    removeDuplicate(first);
    Display(first);
    getch();
    return 0;
}

/*
SAMPLE INPUT OUTPUT
 int A[]={10,20,20,40,50,50,50,60}
 output:
 Sorted list with no duplicate elements is : 10 20 40 50 60
  
  Time Complexity: O(n) 
  where n is the number of nodes in the given linked list

  Space Complexity: O(n) 
  where n is the number of nodes in the given linked list
  
  */




<|start_filename|>Java/ds/heapmain.java<|end_filename|>
/*
 * Implementation of heap.
 * A Heap is a special Tree-based data structure in which the tree is a complete binary tree. 
 * A tree is said to be complete if all its levels, except possibly the deepest, are complete. 
 * A heap has many applications, including the most efficient implementation of priority queues, which are useful in many applications. 
 * In the worst case, the time complexity of inserting a node in a heap would be O(logN).
 * The delete operation has a time complexity relative to the height of the tree, or O(log n).
 * Heapsort is a comparison-based sorting algorithm. Heaps are often implemented in an array rather than a linked list. 
   Overall time complexity of Heap Sort is O(nLogn).
 */

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

class heap //max-heap
{
	private static final int d = 2;
	private int[] arr1;
	private int heapSize;
    //This will initialize our heap with default size.
	 
	public heap(int capacity) {
		heapSize = 0;
		arr1 = new int[capacity + 1];
		Arrays.fill(arr1, -1);

	}

	//This will check if the heap is empty or not 
	public boolean isEmpty() {
		return heapSize == 0;
	}

	//to check if heap is full or not
	public boolean isFull() {
		return heapSize == arr1.length;
	}

	private int parent(int i) {
		return (i - 1) / d;
	}

	private int kthChild(int i, int k) {
		return d * i + k;
	}

	//This will insert new element in to heap Complexity: O(log N) As worst case scenario, we need to traverse till the root
	public void insert(int x) {
		if (isFull())
			throw new NoSuchElementException("Heap is full, No space to insert new element");
		arr1[heapSize++] = x;
		heapifyUp(heapSize - 1);
	}

//This will delete element at index x 
	public int delete(int x) 
{
		if (isEmpty())
			throw new NoSuchElementException("Heap is empty, No element to delete");
		int key = arr1[x];
		arr1[x] = arr1[heapSize - 1];
		heapSize--;
		heapifyDown(x);
		return key;
	}
	
  // This method used to maintain the heap property while inserting an element.
	 private void heapifyUp(int i) 
	 {
		int temp = arr1[i];
		while (i > 0 && temp > arr1[parent(i)]) {
			arr1[i] = arr1[parent(i)];
			i = parent(i);
		}
		arr1[i] = temp;
	}

	// This method used to maintain the heap property while deleting an element.
     private void heapifyDown(int i) 
     {
		int child;
		int temp = arr1[i];
		while (kthChild(i, 1) < heapSize) {
			child = maxChild(i);
			if (temp < arr1[child]) {
				arr1[i] = arr1[child];
			} else
				break;
			i = child;
		}
		arr1[i] = temp;
	}

	private int maxChild(int i) {
		int leftChild = kthChild(i, 1);
		int rightChild = kthChild(i, 2);
		return arr1[leftChild] > arr1[rightChild] ? leftChild : rightChild;
	}
  //This method used to print all element of the heap
	public void printHeap() 
	 
	{
		
		for (int i = 0; i < heapSize; i++)
			System.out.print(arr1[i] + " ");
		System.out.println();
	}
	
	void heapify(int arr[], int n, int i) 
	{
		   int temp;
		   int largest = i;
		   int l = 2 * i + 1;
		   int r = 2 * i + 2;
		   if (l < n && arr[l] > arr[largest])
		      largest = l;
		   if (r < n && arr[r] > arr[largest])
		      largest = r;
		   if (largest != i) {
		      temp = arr[i];
		      arr[i] = arr[largest];
		      arr[largest] = temp;
		      heapify(arr, n, largest);
		   }
		}
		void heapSort(int arr[], int n) {
		   int temp;
		   for (int i = n / 2 - 1; i >= 0; i--)
		      heapify(arr, n, i);
		   for (int i = n - 1; i >= 0; i--) {
		      temp = arr[0];
		      arr[0] = arr[i];
		      arr[i] = temp;
		      heapify(arr, i, 0);
		   }
		}
	 void sort1()
	 {
		 heapSort(arr1, heapSize);
	 }
    
}
public class heapmain {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner s1 = new Scanner(System.in);
		int choice = 0;
		int a1 = 0;
		System.out.println("ENTER THE SIZE OF HEAP");
		a1=s1.nextInt();
		System.out.println(" ");
		heap a = new heap(a1);
		int yn = 0;
		do {
			System.out.println("PRESS 1 TO CREATE ");
			System.out.println("PRESS 2 TO ADD ");
			System.out.println("PRESS 3 TO DELETE ");
			System.out.println("PRESS 4 TO DISPLAY");
			System.out.println("PRESS 5 TO SORT");
			System.out.println("PRESS 0 TO EXIT");
			System.out.println("  ");
			choice = s1.nextInt();
			switch (choice) {
			case 1:
				do {
					System.out.println("ENTER THE NUMBER TO BE ADDED");
					int k = 0;
					k = s1.nextInt();
					a.insert(k);
					System.out.println("DO YOU WANT TO CONTINUE?(1=YES /2=N0)");
					yn = s1.nextInt();
				} while (yn != 2);
				break;
			case 2:
				System.out.println("ENTER THE  NEW NUMBER TO BE ADDED");
				int k = 0;
				k = s1.nextInt();
				a.insert(k);
				System.out.print("NEW HEAP = ");
				a.printHeap();
				System.out.println(" ");
				break;
			case 3:
				System.out.println("ENTER THE INDEX OF THE NUMBER TO BE DELETED");
				int q0 = 0;
				q0 = s1.nextInt();
				a.delete(q0);
				System.out.print("NEW HEAP = ");
				a.printHeap();
				System.out.println(" ");
				break;
			case 4:
				System.out.print("HEAP = ");
				a.printHeap();
				System.out.println(" ");
				break;
			case 5:
				System.out.print("SORTED HEAP = ");
				a.sort1();
				a.printHeap();
				System.out.println(" ");
				break;

			}

		} while (choice != 0);

	}

}



/*
OUTPUT :

ENTER THE SIZE OF HEAP
20
PRESS 1 TO CREATE 
PRESS 2 TO ADD 
PRESS 3 TO DELETE 
PRESS 4 TO DISPLAY
PRESS 5 TO SORT
PRESS 0 TO EXIT
  
1
ENTER THE NUMBER TO BE ADDED
17
DO YOU WANT TO CONTINUE?(1=YES /2=N0)
1
ENTER THE NUMBER TO BE ADDED
25
DO YOU WANT TO CONTINUE?(1=YES /2=N0)
1
ENTER THE NUMBER TO BE ADDED
3
DO YOU WANT TO CONTINUE?(1=YES /2=N0)
1
ENTER THE NUMBER TO BE ADDED
1
DO YOU WANT TO CONTINUE?(1=YES /2=N0)
1
ENTER THE NUMBER TO BE ADDED
0
DO YOU WANT TO CONTINUE?(1=YES /2=N0)
1
ENTER THE NUMBER TO BE ADDED
1008
DO YOU WANT TO CONTINUE?(1=YES /2=N0)
2
PRESS 1 TO CREATE 
PRESS 2 TO ADD 
PRESS 3 TO DELETE 
PRESS 4 TO DISPLAY
PRESS 5 TO SORT
PRESS 0 TO EXIT
  
4
HEAP = 1008 17 25 1 0 3 
 
PRESS 1 TO CREATE 
PRESS 2 TO ADD 
PRESS 3 TO DELETE 
PRESS 4 TO DISPLAY
PRESS 5 TO SORT
PRESS 0 TO EXIT
  
2
ENTER THE  NEW NUMBER TO BE ADDED
45
NEW HEAP = 1008 17 45 1 0 3 25 
PRESS 1 TO CREATE 
PRESS 2 TO ADD 
PRESS 3 TO DELETE 
PRESS 4 TO DISPLAY
PRESS 5 TO SORT
PRESS 0 TO EXIT
  
2
ENTER THE  NEW NUMBER TO BE ADDED
58
NEW HEAP = 1008 58 45 17 0 3 25 1 
PRESS 1 TO CREATE 
PRESS 2 TO ADD 
PRESS 3 TO DELETE 
PRESS 4 TO DISPLAY
PRESS 5 TO SORT
PRESS 0 TO EXIT
  
3
ENTER THE INDEX OF THE NUMBER TO BE DELETED
0
NEW HEAP = 58 17 45 1 0 3 25 
 
PRESS 1 TO CREATE 
PRESS 2 TO ADD 
PRESS 3 TO DELETE 
PRESS 4 TO DISPLAY
PRESS 5 TO SORT
PRESS 0 TO EXIT
  
5
SORTED HEAP = 0 1 3 17 25 45 58 
 
PRESS 1 TO CREATE 
PRESS 2 TO ADD 
PRESS 3 TO DELETE 
PRESS 4 TO DISPLAY
PRESS 5 TO SORT
PRESS 0 TO EXIT
  
0
*/


<|start_filename|>JavaScript/search/ternary_search.js<|end_filename|>
/*
*   Author: <NAME>
*   Date: 28/10/2020
*/

// Search an element in an array using Ternary Search algorithm (iterative)
// Prerequisite: Sorted array should be passed
function ternary_search_iterative(leftIndex, rightIndex, key, array) {
    // If left index is greater than right index then the key cannot be searched. 
    while(rightIndex >= leftIndex) {

        // Find two mid values
        let mid1 = leftIndex + ((rightIndex - leftIndex) / 3);
        let mid2 = rightIndex - ((rightIndex - leftIndex) / 3);

        // If the key is in one of the mid values, return its index
        if(key == array[mid1])
            return mid1;
        else if(key == array[mid2])
            return mid2;

        // Check which part of the array the key is present
        // and update the leftIndex and rightIndex values accordingly
        if(key < array[mid1]) {
            rightIndex = mid1 - 1;  // key lies in the region between leftIndex and mid1
        }
        else if(key > array[mid2]) {
            leftIndex = mid2 + 1;   // key lies in the region between mid2 and rightIndex
        }
        else {
            leftIndex = mid1 + 1;
            rightIndex = mid2 - 1;
        }
    }

    // The key does not exist
    return -1;
}

// Search an element in an array using Ternary Search algorithm (recursive)
// Prerequisite: Sorted array should be passed
function ternary_search_recursive(leftIndex, rightIndex, key, array) {
    if(rightIndex >= leftIndex) {
        // Find the two mid values
        let mid1 = leftIndex + ((rightIndex - leftIndex) / 3);
        let mid2 = rightIndex - ((rightIndex - leftIndex) / 3);

        // If the key is in one of the mid values, return its index
        if(key == array[mid1])
            return mid1;
        else if(key == array[mid2])
            return mid2;

        // Check which part of the array the key is present
        // and recall the function using updated values accordingly
        if(key < array[mid1]) {
            return ternary_search_recursive(leftIndex, mid1 - 1, key, array);
        }
        else if(key > array[mid2]) {
            return ternary_search_recursive(mid2 + 1, rightIndex, key, array);
        }
        else {
            return ternary_search_recursive(mid1 + 1, mid2 - 1, key, array);
        }
    }

    // The key doesn't exists
    return -1;
}

/*
*   @Test
*/
function test() {
    var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

    // Iterative tests
    var target = 15;
    console.log(ternary_search_iterative(0, array.length, target, array)); // Output: -1

    target = 5
    console.log(ternary_search_iterative(0, array.length, target, array)); // Output: 4

    // Recursive tests
    target = 20;
    console.log(ternary_search_recursive(0, array.length, target, array)); // Output: -1

    target = 4
    console.log(ternary_search_recursive(0, array.length, target, array)); // Output: 3
}

// Entry point of the application for testing purpose
test();


<|start_filename|>C/ds/reverseWordsOfString.c<|end_filename|>
/*
Reversing individual words of a string using stacks
Algorithm/Approach:
We iterate through the string character-by-character.
If the current character is not a space, or not a newline character or not a null character,
we push it into the stack
Otherwise, we pop the elements from the stack until it's empty. 
(Because a space or newline or null character marks the end of a word.)
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

typedef struct stack {
    int capacity, top;
    char* arr;
}stack;
/* creating a structure to implement stack */

int isEmpty(stack* s) {
    return s->top == -1;
}
/* to check if the stack is empty */

int isFull(stack* s) {
    return s->top == s->capacity - 1;
}
/* to check if the stack is full */

stack* createStack(int size) {
    struct stack* s = (struct stack*)malloc(sizeof(struct stack));
    s->capacity = size;
    s->arr = (char*)malloc(size * sizeof(char));
    s->top = -1;
    return s;
}

void push(stack* s, char data) {
    s->arr[++s->top] = data;
}
/* push a given element into the stack */

char pop(stack* s) {
    return s->arr[s->top--];
}
/* to pop the top element from stack */

void reverseWords(char sentence[100], int length) {
    stack* s = createStack(length);
    for (int i = 0; i < length; i++) {
        char letter = sentence[i];
        if ((!isspace(letter)) && (letter != '\n') && (letter != '\0')) {
            push(s, letter);
            /* anything other than an alphabet or number indicates that a word has ended */
        }
        else {
            while (!(isEmpty(s))) {
                printf("%c", pop(s));
            }
            printf("%c", letter);
        }
    }
}

int main() {
    int size, i = 0;
    char sentence[100];
    printf("Enter a sentence:\n");
    fgets(sentence, 100, stdin);
    printf("The sentence after reversing individual words is:\n");
    reverseWords(sentence, strlen(sentence));
    /* calling the reverseWords function */
    return 0;
}

/*
Sample I/O:
Enter a sentence:
Get me food
The sentence after reversing individual words is:
teG em doof
*/

/*
Time complexity = O(n) [since each pop or push takes O(1) times]
Space Complexity = O(n)
*/

<|start_filename|>C/sort/comb.c<|end_filename|>

/*

COMB SORT :

Comb Sort is mainly an improvement over Bubble Sort. Bubble sort always compares adjacent values.
So all inversions are removed one by one. Comb Sort improves on Bubble Sort by using gap of size
more than 1. The gap starts with a large value and shrinks by a factor of 1.3 in every iteration
until it reaches the value 1. Thus Comb Sort removes more than one inversion counts with one swap
and performs better than Bubble Sort.
*/



#include <stdio.h>

void comb_sort(int *ar, int n){

    //gap variable gives gap between the values to compare
    int gap = n;
    int q,w;
    
    while(gap>1){
        //updating the gap variable
        gap = gap/1.3;
        if(gap<1){
            gap = 1;
        }
        q=0;w=q+gap;
        while(w<n){
            if(ar[q]>ar[w]){
		        //swap values
                int temp = ar[q];
                ar[q] = ar[w];
                ar[w] = temp;
            }
            w++;q++;
        }
    }
}

int main()
{
    int n;
    int *ar;
    printf("Enter the limit : ");

    //Input the number of elements to be sorted
    scanf("%d",&n);

    //Dynamically allocate memory for the array
    ar = (int*)malloc(n * sizeof(int));

    //Input numbers to be sorted
    for(int i=0;i<n;i++){
        scanf("%d",&ar[i]);
    }
    
    printf("Unsorted array : \n");

    //Print the unsorted array
    for(int i=0;i<n;i++){
        printf("%d ",ar[i]);
    }
    printf("\n\n");
    
    //Execute the comb sort function
    comb_sort(ar, n);
    
    printf("Sorted array : \n");

    //Print the sorted array
    for(int i=0;i<n;i++){
        printf("%d ",ar[i]);
    }
    
    return 0;
}

/*
CASE 1:
input = [1, 8, 7, 61, 5, 4, 11];
EXPECTED: [1,4,5,7,8,11,61]

CASE 2:
input = [1,8,3,9,10,10,2,4];
EXPECTED: [1,2,3,4,8,9,10,10]

    Time Complexity - O(n log n) for the best case.
                      O(n^2/2^p) (p is a number of increment) for average case.
                      O(n^2) for the worst case.
    Space Complexity - O(1)

*/



<|start_filename|>Go/math/areas/3D/Areas3D.go<|end_filename|>
package main

import (
	"fmt"
	"math"
)

// Surface area of a Cone

func cone(r, l float64) float64 {
	return (math.Pi * r * r) + (math.Pi * r * l)
}

// Surface area of a Cube

func cube(a float64) float64 {
	return 6.0 * a * a
}

// Surface area of a Cuboid

func cuboid(a, b, c float64) float64 {
	return 2.0 * ((a * b) + (b * c) + (c * a))
}

// Surface area of a Cylinder

func cylinder(r, h float64) float64 {
	return (2.0 * (math.Pi * r * r)) + (r * h)
}

// Surface area of a Pyramid

func pyramid(l, b, h float64) float64 {
	return (l * b) + (l * math.Sqrt((b/2.0*b/2.0)+(h*h))) + (b * math.Sqrt((l/2.0*l/2.0)+(h*h)))
}

// Surface area of a Rectangular Prism

func rectangular_prism(l, b, h float64) float64 {
	return 2.0 * (l*b + l*h + b*h)
}

// Surface area of a Sphere

func sphere(r float64) float64 {
	return 4.0 * math.Pi * r * r
}

// Surface area of a Hemisphere

func hemisphere(r float64) float64 {
	return (2.0 * math.Pi * r * r) + (math.Pi * r * r)
}

func main() {
	fmt.Println(cone(3.0, 5.0))
	fmt.Println(cube(4.0))
	fmt.Println(cuboid(4.0, 6.0, 2.5))
	fmt.Println(cylinder(3.5, 5.0))
	fmt.Println(pyramid(4.0, 7.0, 5.5))
	fmt.Println(rectangular_prism(4.0, 3.5, 6.5))
	fmt.Println(sphere(4.0))
	fmt.Println(hemisphere(4.5))
}

// Time Complexity - O(1)
// Space Complexity - O(1)


<|start_filename|>C/sort/three_way_merge_sort.c<|end_filename|>
// C program to implement Three Way Merge Sort
#include <stdio.h>

// Time Complexity: O(n*logn)
// Space Complexity: O(n)


// Merge the three sections in ascending order
void merge(int arr[], int beg, int midA, int midB, int end, int temp[])  
{  
    int i, j, k, l;
    i = beg;
    j = midA; 
    k = midB; 
    l = beg;  
  
    // Find the smallest element among the three sections 
    while ((i < midA) && (j < midB) && (k < end))  
    {  
        if(arr[i] < arr[j]) 
        { 
            if(arr[i] < arr[k]) 
            { 
                temp[l++] = arr[i++]; 
            } 
            else
            { 
                temp[l++] = arr[k++]; 
            } 
        } 
        else
        { 
            if(arr[j] < arr[k]) 
            { 
                temp[l++] = arr[j++]; 
            } 
            else
            { 
                temp[l++] = arr[k++]; 
            } 
        } 
    }  
  
    /*
    Now any two arrays would have remaining values that are yet to be merged,
    We have to identify those two arrays and merge the elements.  
    */
 
    while ((i < midA) && (j < midB))  
    {  
        if(arr[i] < arr[j]) 
        { 
            temp[l++] = arr[i++]; 
        } 
        else
        { 
            temp[l++] = arr[j++]; 
        } 
    }  
  
   
    while ((j < midB) && (k < end))  
    {  
        if(arr[j] < arr[k]) 
        { 
            temp[l++] = arr[j++]; 
        } 
        else
        { 
            temp[l++] = arr[k++]; 
        }  
    }  
  
    while ((i < midA) && (k < end))  
    {  
        if(arr[i] < arr[k]) 
        { 
            temp[l++] = arr[i++]; 
        } 
        else
        { 
            temp[l++] = arr[k++]; 
        }  
    }  
  
  /*
    Now a single array would have remaining values that are yet to be merged,
    We have identify that array and copy its remaining elements.  
  */
    
    while (i < midA)  
        temp[l++] = arr[i++];  
  
    while (j < midB)  
        temp[l++] = arr[j++];  
        
    while (k < end)  
        temp[l++] = arr[k++];  
}  



void three_way_merge_sort(int arr[], int beg, int end, int temp[])  
{  
    //If the array contains only a single element, then return  
    if (end - beg < 2)  
        return;  
  
    // Split the array into three parts
    int midA = beg + ((end - beg) / 3);  
    int midB = beg + 2 * ((end - beg) / 3) + 1;  
    
    three_way_merge_sort(temp, beg, midA, arr);  
    three_way_merge_sort(temp, midA, midB, arr);  
    three_way_merge_sort(temp, midB, end, arr);  
  
    // Merge the sorted arrays  
    merge(temp, beg, midA, midB, end, arr);  
}

int main()
{
    int n;
    printf("\nHow many numbers do you want to sort? ");
    scanf("%d",&n);
    int arr[n];

    if (n <= 0)
    {
        printf("There are no numbers to sort!!!");
        return 0;
    }
    // Input the numbers to sort
    printf("Enter the numbers: ");
    for (int i = 0; i < n; i++)
        scanf("%d",&arr[i]);
    
    // creating a temporary array 
    int temp[n];  
  
    // Copy the elements of the temporary elements into the new array  
    for (int i = 0; i < n; i++)  
        temp[i] = arr[i];  
  
    //Call the sort function 
    three_way_merge_sort(temp, 0, n, arr);  

    printf("The numbers in sorted order is: ");
    // Print the sorted array
    for (int i = 0; i < n; i++)
        printf(" %d ", temp[i]);
    printf("\n");

    return 0;
}

/*
SAMPLE INPUT AND OUTPUT

SAMPLE 1
How many numbers do you want to sort? 5
Enter the numbers: 1 3 5 2 4
The numbers in sorted order is:  1  2  3  4  5

SAMPLE 2
How many numbers do you want to sort? 0
There are no numbers to sort!!!
*/


<|start_filename|>Java/math/SumOfDigit.java<|end_filename|>
/* Java Program to calculate the sum of digits of a number */

import java.util.Scanner;
public class SumOfDigit {

	/* Function to calculate the sum of digits */
	static int getSum(int n) {
		int temp = n;
		int sum = 0;

		while(temp > 0)
		{
			// Extracting the last digit of given number
			int lastDigit = temp % 10;
			// Adding the extracted last digit to sum
			sum += lastDigit;
			//Removing the last digit of the given number
			temp /= 10;	
		}
		  return sum;
	}
	
	public static void main(String[] args)
	{
		System.out.println("Enter the number for which you want to calculate the sum of digits:");
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int x = getSum(n);
		System.out.println("Sum of the digits of "+n+" is "+x+".");
	}
}
/*
Sample Input and Output

Example 1:
Input:
Enter the number for which you want to calculate the sum of digits:
745
Output : Sum of the digits of 745 is 16.
Explanation : Sum of digits of the number 745 = (7+4+5) = 16

Example 2:
Input:
Enter the number for which you want to calculate the sum of digits:
8674
Output: Sum of the digits of 8674 is 25.
Explanation: Sum of digits of the number 8674 = (8+6+7+4) = 25

Space Complexity :O(1)
Time Complexity : O(logn)
*/


<|start_filename|>C/dp/Max_Sub_SquareMatrixwithAll_1s.c<|end_filename|>
// C code for Maximum size square sub-matrix with all 1's 
#include<stdio.h>

int main() {

  int r_size, c_size, mat[r_size][c_size], MaxSub[r_size][c_size];
  printf("Input --> \n");
  printf("Enter the row-size :\n");
  scanf("%d", & r_size);
  printf("Enter the column-size :\n");
  scanf("%d", & c_size);
  printf("Enter the elements of matrix  :\n");
  for (int i = 0; i < r_size; i++) {
    for (int j = 0; j < c_size; j++) {
      scanf("%d", & mat[i][j]);
    }
  }
  /* Set first column of MaxSub[][]*/
  for (int i = 0; i < r_size; i++)
    MaxSub[i][0] = mat[i][0];
  /* Set first row of MaxSub[][]*/
  for (int j = 0; j < c_size; j++)
    MaxSub[0][j] = mat[0][j];

  /* Construct other entries of MaxSub[][]*/
  for (int i = 1; i < r_size; i++) {
    for (int j = 1; j < c_size; j++) {
      if (mat[i][j] == 1) {
        int m;
        /* To get minimum of three values */
        m = MaxSub[i][j - 1];
        if (m > MaxSub[i - 1][j])
          m = MaxSub[i - 1][j];
        if (m > MaxSub[i - 1][j - 1])
          m = MaxSub[i - 1][j - 1];

        MaxSub[i][j] = m + 1;
      } else
        MaxSub[i][j] = 0;
    }
  }
  /* Find the maximum entry, and indexes of maximum entry  
      in MaxSub[][] */
  int max_of_subMat = MaxSub[0][0], max_i = 0, max_j = 0;
  for (int i = 0; i < r_size; i++) {
    for (int j = 0; j < c_size; j++) {
      if (max_of_subMat < MaxSub[i][j]) {
        max_of_subMat = MaxSub[i][j];
        max_i = i;
        max_j = j;
      }
    }
  }
  printf("Output -->\n");
  printf("Maximum square sub-matrix is: \n");
  int size = 0;
  for (int i = max_i; i > max_i - max_of_subMat; i--) {
    for (int j = max_j; j > max_j - max_of_subMat; j--) {
      printf("%d ", mat[i][j]);

    }
    printf("\n");
    size++;
  }
  printf("Size of max SubSquareMatrix : ");
  printf("%d", size);
  return 0;
}

/*
 Input -->

 Enter the row-size : 3
 Enter the column-size : 4
 Enter the elemnts of matrix :
 1 0 1 1 
 0 1 1 1
 0 0 1 1

 Output -->
 Maximum square sub-matrix is: 
 1 1 
 1 1 
 Size of max SubSquareMatrix : 2
 Time Complexity: O(m*n) where m is number of rows and n is number of columns in the given matrix.
 Auxiliary Space: O(m*n) where m is number of rows and n is number of columns in the given matrix.
*/


<|start_filename|>Java/other/InfixtoPrefix.java<|end_filename|>
/**
 * Infix to Prefix Expression
 * 
 * Algorithm Used:
 * First the given infix expression is reversed.
 * By reversing, every '(' becomes ')' and vice versa.
 * Then, we obtain the postfix of the reversed expression.
 * Now, we reverse this postfix expression to obtain the Prefix expression.
 * 
 * Author: iamvs-2002
 */

import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
import java.util.Stack;

public class InfixtoPrefix 
{
    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Kindly enter the infix expression: ");
        String infix = sc.nextLine();

        InfixtoPrefix x = new InfixtoPrefix();
        String prefix = x.infixtoprefix(infix);
        
        System.out.println("Prefix Expression: "+prefix);
    }

    static int priority(char c)
    {
        /**
         * '+' and '-' have priority=1
         * '*' and '/' have priority=2
         * '^' has priority=3
         */
        switch (c)
        {
            case '+':
                return 1;
            case '-':
                return 1;
            case '*':
                return 2;
            case '/':
                return 2;
            case '^':
                return 3;
            default:
                return -1;
        }
    }

    private String infixtoprefix(String expression)
    {
        //initially an empty string
        String result = "";

        //reversing the given infix expression
        char[] array = new char[expression.length()];
        for (int j = expression.length()-1; j >=0 ; j--) { 
            array[expression.length()-j-1] = expression.charAt(j);
        }

        Stack<Character> stack = new Stack<>();

        int i=0;
        for (i = 0; i < array.length; i++) 
        {
            if (array[i] == '(')
            {
                array[i] = ')';
                i++;
            }
            else if (array[i] == ')')
            {
                array[i] = '(';
                i++;
            }
        }

        String infix = '(' + String.valueOf(array) + ')';

        for (i = 0; i < infix.length() ; i++) 
        {
            char c = infix.charAt(i);
            //check if char is operator or operand
            if(priority(c)>0)
            {
                //if the topmost operator in the stack has a priority greater than c
                //pop it and add to result string
                //else push it into the stack
                while(stack.isEmpty()==false && (priority(stack.peek())>priority(c) || (priority(stack.peek())>=priority(c) && c=='^')))
                {
                    result = result + stack.pop();
                }
                stack.push(c);
            }
            else if(c==')')
            {
                //if character is ending bracket ')'
                //pop from stack, until '(' is found
                while(stack.peek()!='(')
                {
                    result = result + stack.peek();
                    stack.pop();
                }
                //removing '(' from stack
                char x = stack.pop();
            }
            else if(c=='(')
            {
                //character is starting bracket '('
                stack.push(c);
            }
            else
            {
                //if the character is an operand, add it to the result string
                result = result + c;
            }
        }
        //the result string is now a postfix expression
        //reversing the string to obtain the prefix expression.
        //converting the final result string to a char array
        char[] arr = new char[result.length()];
        for (i = result.length()-1; i >=0 ; i--) { 
            arr[result.length()-i-1] = result.charAt(i);
        }
        return String.valueOf(arr);
    }
}
/**
 * Sample Outputs:
 * 
 * Kindly enter the infix expression:
 * A+B*C
 * Prefix Expression: +A*BC
 * 
 * Kindly enter the infix expression: 
 * x+y*z/w+u
 * Prefix Expression: ++x/*yzwu
 * 
 * Kindly enter the infix expression: 
 * A * B + C / D
 * Prefix Expression: +*A  B / C  D
 * 
 * Time Complexity: O(n^2)
 * Space Complexity: O(n)
 */


<|start_filename|>C-Plus-Plus/cp/Josephus.cpp<|end_filename|>
/**
Josephus problem is a famous problem.
In each iteration we kill the every kth
person in a circular arrangement of n persons.
Find the person who is alive at the end.
0-based indexing
link to the problem : https://en.wikipedia.org/wiki/Josephus_problem
**/

#include <iostream>
using namespace std;

int solution(int n, int k) {
	if (n == 1)
		return 0;
	return (k + solution(n - 1, k)) % n;
}

int main() {
	int people, gap;
	cin >> people >> gap;
	cout << solution(people, gap) << '\n';
	return 0;
}

/**
Input :
4 2
Output :
0

Time Complexity : O(n)
Space Complexity : O(1)
**/


<|start_filename|>C-Plus-Plus/ds/queue.cpp<|end_filename|>
//Implementation of all the basic functionality of queue using array.

#include<iostream>
using namespace std;
class QueueUsingArray
{
    int *data;
    int nextindex;    //Index where the element should be inserted
    int firstindex;    //Index where top value is stored
    int size;    //The no. of elements present in queue
    int capacity;   //The total size of queue
public:
    QueueUsingArray(int num)
    {
        data = new int[num];
        nextindex = 0;      //indexing start from 0
        firstindex = -1;    //firstindex is initialised by -1 because till now we don't have any element as top .
        size = 0;
        capacity = num;
    }
    int getSize()     //Return the number of elements present in queue
    {
        return size;
    }
    bool isEmpty()     //Indicate whether the queue is empty or not
    {
        return size == 0;
    }
    void enqueue()     //function to insert an element at the rear of the queue
    {
        int element;
        cout<<"Enter the Element to be inserted in queue  ";
        cin>>element;
        if(size == capacity)
        {
            cout<<"Queue is Full !"<<endl;
            return;
        }
        data[nextindex]=element;
        nextindex = (nextindex+1)% capacity;
        if(firstindex == -1)
        {
            firstindex = 0;
        }
        size++;    //increament the size when a new  element is inserted
    }
    int front()     //Return the top value of queue
    {
        if(isEmpty())
        {
            cout<<"Queue is Empty!"<<endl;
            return 0;
        }
        return data[firstindex];

    }
    int dequeue()     //function to delete an element from the front of the queue
    {
        if(isEmpty())
        {
            cout<<"Queue is Empty!"<<endl;
            return 0;
        }
        int ans = data[firstindex];
        firstindex = (firstindex+1)% capacity;    //modify the firstindex value to top value index
        size--;
        cout<<"Deletion is successfull !"<<endl;
        return ans;
    }
};
int main()
{
    int num;
    cout<<"Enter the no. of element to be inserted in queue :";
    cin>>num;
    QueueUsingArray q(num);    // Create a queue of capacity num

    int choice;
    do
    {
        cout<<"\n0.Exit\n1.Insertion of Element\n2.Deletion of Element\n3.Display top value of queue\n4.Size of queue\n5.Is Empty"<<endl;
        cin>>choice;
        switch(choice)
        {
         case 0:
            choice = 0;
            cout<<"Exit Function is Successfull !"<<endl;
            break;        
        case 1:
            q.enqueue();
            cout<<"Insertion is successfull !"<<endl;
            break;
        case 2:
            cout << "Pop  value from the queue : "<<q.dequeue() << endl;
            break;
        case 3:
            cout << "Top value of queue : "<<q.front() << endl;
            cout<<"Displaying top value function of queue is Successfull !"<<endl;
            break;
        case 4:
            cout << "Total element in the queue : "<<q.getSize() << endl;
            cout<<"Size function is Successfull !"<<endl;
            break;
        case 5:
            cout << "Isempty "<<q.isEmpty() << endl;
            cout<<"IsEmpty function is Successfull !"<<endl;
            break;
        default:
            cout<<"\nEnter a valid choice!!";
        }
    }
    while(choice != 0);
}


<|start_filename|>Java/dp/Coin_Change.java<|end_filename|>
import java.io.*; 
import java.util.*;

public class demo{                                              
    public static  Integer change(Integer amount, Integer[] coins) {        //Bottomup dp
         if (amount == 0) return 1;                                         //base case if no coin is selected,then there can be one way only ie. not selecting any coin
        
        int[][] dp = new int[coins.length + 1][amount + 1];                 //dp[i][j] represents the amount of coin combinations within first i coins to get j amount
        for (int i = 0; i <= coins.length; i++) dp[i][0] = 1;
        
        for (int i = 1; i <= coins.length; i++) {
            for (int j = 1; j <= amount; j++) {
                if (coins[i - 1] > j) {
                    dp[i][j] = dp[i - 1][j];                               //dp[i - 1][j] Not selecting the i th coin , let the other coins form j
                } else {
                    dp[i][j] = dp[i][j - coins[i - 1]] + dp[i - 1][j];     //dp[i][j - coins[i - 1]] select i th coin one or multiple times to form j, we take using i th coin into consideration every time
                }
            }
        }
        return dp[coins.length][amount];
    }
 
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);

        Integer n = sc.nextInt();

        ArrayList<Integer> li = new ArrayList<Integer>(); 
        while(true){
            System.out.println("Please enter coin value: ");  //enter coin values
            li.add(sc.nextInt());
            System.out.println("Do you want to add more yes/no?");
            String answer = sc.next(); 

            if (answer.equals("no")){
                break;
            }
        }
        Integer arr[] = new Integer[li.size()]; //converting arraylist to array
        arr = li.toArray(arr);

        System.out.println(change(n,arr));
    }
}


/*
Sample Test Case
Input:
N = 4
S = {1,2,3}

Explanation
there are four solutions: {1,1,1,1},{1,1,2},{2,2},{1,3}

Output
4

Input
N = 10
S = {2, 5, 3, 6}

Explanation
there are five solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}

Output
5
*/


<|start_filename|>Go/cryptography/Monoalphabetic_Cipher/monoalphabeticcipher.go<|end_filename|>
/*
   Monoalphabetic substitution cipher basically replaces
   each letter of a plaintext by another letter or symbol,
   depending only on the letter. The same plaintext letter
   is always replaced by the same ciphertext letter and 
   the same letter can be replaced by letter itself.
   
   Example if a is there we replace it with B to Z .....so on.

   Here in this particular case we use the cipherer as a => z
   b => y .... so on. The user can change depending upon his/her
   requirment

*/

package main

import (

  "fmt"
  "unicode"
  "bufio"
  "os"
  "strings"

)

//Global Variables
var plaintext string
var ciphertext string

/* We use this list of alphabets to check what letter we have
   in plaintext*/
var list string = "abcdefghijklmnopqrstuvwxyz"

/* We use this list of alphabets as the corresponding cipher  
   letters for corresponding input letters in plaintext */
var cipherer string = "zyxwvutsrqpomnlkjihgfedcba"

var output string

/*
 This function formats the given ciphertext according to
 the orginal plaintext recieved from the user as input.
 In the monoalphabeticcipher function below, we converet
 the given plaintext into lowercase for our cinvinence of 
 checking. So, the ciphertext we get is also in all 
 lowercase. Here, we format the ciphertext so that wherever
 there is capital letter in the plaintext, same follows 
 in the ciphertext.*/
func format(temp string) {


    /* Checking if the given letter in plaintext is capital 
       or not and changint it to capttal if it was*/
    for i:=0; i < len(temp); i++ {

       if (unicode.IsUpper (rune(temp[i]) ) ) {

           output += strings.ToUpper(string(ciphertext[i]))

       }else {

          output += string(ciphertext[i])

       }

    }

}

/* This is the function where we cipher the plaintext using 
   the cipherer into small letters */
func monoaplhabeticcipher() {

      // Converting the plaintext to small letters
      plaintext = strings.ToLower(plaintext)

      var temporary string
      /* Here we replace all the space charecter with underscore
         for out convinence*/
      for k:=0;k<len(plaintext);k++ {

          if(string(plaintext[k]) == " ") {

		temporary += string("_")

          }else {

		temporary += string(plaintext[k])

          }
      }

      plaintext = temporary

      /* If the inputted plaintext had space we give sapce in
         the cipher text also */
      for i:=0 ;i < len(plaintext); i++ {

          if(string(plaintext[i]) == "_") {

                ciphertext += " "

          }else {
                /* We replace the letter with corresponding letter 
                   from the cipherer */
                for j:=0 ; j<26 ; j++ {

                     if( string(plaintext[i]) == string(list[j]) ) {

                          ciphertext += string(cipherer[j])

                     }

                }

          }

      }

}

// driver function
func main () {

     // Taking the plaintext as input from user
     fmt.Print("Enter the plaintext : ")
     scanner := bufio.NewScanner(os.Stdin)
     scanner.Scan()

     plaintext = scanner.Text()

     // copy of plaintext
     temp := plaintext

     /* calling the monoaplhabetic cipher function
        to encrypt the input string leaving out 
        the space in to small letters*/
     monoaplhabeticcipher()

     /* calling the format function to format the 
        calculated cipher text in accorfing to the 
        plaintext format */
     format(temp)

     // Printing the cipher text out
     fmt.Print("The cipher text is : ",output)

}

/*

     Sample I/O :

     a) All small letters :

     Enter the plaintext : hello world
     The cipher text is : svool dliow 

     b) All Capital letters :

     Enter the plaintext : HELLO WORLD
     The cipher text is : SVOOL DLIOW

     c) Mix of small and capital letters :  
 
     Enter the plaintext : Hello World
     The cipher text is : Svool Dliow

*/



<|start_filename|>C-Plus-Plus/cp/Container_with_most_water.cpp<|end_filename|>
class Container_with_most_Water {
public:
    int calculate(int i, int j, int x1, int x2){
        int part1 = min(x1,x2);
        return part1 * abs(j - i);
    }
    
    int maxArea(vector<int>& height) {
        int max = 0;
        int i = 0;    // left pointer
        int j = height.size() - 1;    // right pointer
        
        while (i < j){
            int curr = calculate(i,j, height[i], height[j]);
            if (curr > max) max = curr;
            if (height[i] < height[j]) i++;     
            else j--;
        }
        return max;  // Returning maxarea
    }
};

/*
TIME COMPLEXITY
2 POINTER APPROACH USED
O(N) where n is the size of the array

TEST CASE

INPUT
[1,8,6,2,5,4,8,3,7]
OUTPUT
49
*/




<|start_filename|>Julia/math/catalan_number.jl<|end_filename|>
# Julian program to Find the n'th Catalan number
# To know more about Catalan Numbers Visit Here : https://en.wikipedia.org/wiki/Catalan_number


function find_catalan(n)
    if (n == 0 || n == 1)
        return 1
    end

    # DP Table 
    cat = [0 for i in 1:(n + 1)]

    # Initialize the first to values
    cat[1] = 1
    cat[2] = 1
    for i in 3:(n + 1)
        for j in 1:(i - 1)
            cat[i] = cat[i] +  (cat[j] * cat[i - j])
        end
    end
    return cat[n + 1]
end

print("Enter the number: ")
num = readline()
num = parse(Int, num)
catalan_number = find_catalan(abs(num))
println("The $num'th catalan number is $catalan_number.")

"""
Time Complexity: O(num^2), where 'num' is the given number
Space Complexity: O(num)

SAMPLE INPUT AND OUTPUT

SAMPLE 1
Enter the number: 12
The 12'th catalan number is 208012.

SAMPLE 2
Enter the number: 2
The 2'th catalan number is 2.

"""


<|start_filename|>Java/cp/Reverse_words_in_String.java<|end_filename|>
    /*
    Given a string, we need to reverse it without reversing any word in it.
    We can reverse each word of a string.
    In other words, Reverse text without reversing individual word in a String.
    */
    import java.util.Scanner;

    public class Reverse_String 
    {
    /*
    This is an constructor called from main function
    */
    public Reverse_String(String in[],int n)
    {
         System.out.println(); 
        
	   for (int i = n - 1; i >= 0; i--) 
           {
               System.out.print(in[i] + " ");
           }
    }
    public static void main(String[] args) 
    {

       Scanner scan = new Scanner(System.in);
       System.out.println("Please Enter the number of words your String have....");
       int n = scan.nextInt();
       String in[] = new String[n];
       System.out.println("Please enter your String here...");
           for (int i = 0; i <= n-1; i++) 
	   {
              in[i] = scan.next();
           }
       Reverse_String r1=new Reverse_String(in,n);
    }
    }   
    /*
    Time complexity is O(n-1)
    Space complexity is O(1)
    Input :
    Please Enter the number of words your String have....
    6
    Please enter your String here...
    i like this program very much
    Output:
    much very program this like i
    */


<|start_filename|>C-Plus-Plus/cp/count_occurences_of_anagrams.cpp<|end_filename|>
/**
 * Count Occurences of Anagrams
 * Cpp Program to find the count of anagrams
 * of an entered word, in an entered text (given that 
 * length of word <= length of text).
 */

#include<bits/stdc++.h>

using namespace std;

//function to count no. of occurences of anagram
int countAnagrams(string text, string word) {
  //To keep count of anagrams
  int anagramCount = 0;
  int lenOfText = text.length();
  int lenOfWord = word.length();
  //Map to store frequency of each character in word
  map < char, int > wordCharCount;
  for (int i = 0; i < lenOfWord; i++)
    wordCharCount[word[i]]++;
  //To count number of distict character
  int count = wordCharCount.size();
  //To denote 2 pointers one pointing to start of window and other to the end
  int start = 0, end = 0;
  //To obtain value of difference for each subsequent window of size lenOfWord
  while (end < lenOfText) {

    wordCharCount[text[end]]--;
    //if occurence of any character reduces to zero then decrease count of distinct character
    if (wordCharCount[text[end]] == 0)
      count--;
    //Window size less than lenOfWord then increase the window size
    if (end - start + 1 < lenOfWord)
      end++;
    //on reaching the window size ,if number of distinct characters equals zero then increment count of anagram
    else if (end - start + 1 == lenOfWord) {
      if (count == 0)
        anagramCount++;
      //compute if character is present in map
      //add last character of current window
      if (wordCharCount.find(text[start]) != wordCharCount.end())
        wordCharCount[text[start]]++;
      //check if only one occurence of a character is present then
      //increment the count for distict characters
      if (wordCharCount[text[start]] == 1)
        count++;
      //slide the window
      start++;
      end++;
    }
  }
  return anagramCount;
}

int main() {
  //take input from user
  string text, word;
  cout << "Enter the text string: ";
  cin >> text;
  cout << "Enter the word whose anagrams need to be counted: ";
  cin >> word;
  cout << "Number of Anagrams: " << countAnagrams(text, word);
}

/*
	Test Cases:

	Input 1:
	Enter the text string: xforfxorffxdofrf
    Enter the word whose anagrams need to be counted: ffor
	Output 1:
	Number of Anagrams: 3

	Input 2:
	Enter the text string:  aabaabaa
    Enter the word whose anagrams need to be counted: aaba
	Output 2:
	Number of Anagrams: 3

	Time complexity: O(N)
	Space complexity: O(1)

*/


<|start_filename|>C-Plus-Plus/ds/Ascending_priority_queue.cpp<|end_filename|>
/*
AIM :: TO IMPLEMENT ASCENDING PRIORITY QUEUE


                    WHAT IS ASCENDING PRIORITY QUEUE ?
 In ascending order priority queue, a lower priority number is given as a higher priority in a priority. 
 For example, we take the numbers from 1 to 5 arranged in an ascending order like 1,2,3,4,5; therefore, 
 the smallest number, i.e., 1 is given as the highest priority in a priority queue.

*/

#include <iostream>
using namespace std;

//Prototypes
void enq(int *, int &, int &, int); // for insertion
void deq(int *, int &, int &, int); // for deletion
void display(int *, int, int);      // for display

int q_full(int, int);  // for checking queue is full or not
int q_empty(int, int); // for checking queue is empty or not

int main()
{
    int size = 100, choice;
    int Q[size];

    //initially front and rear will be at -1
    int front = -1; // deletion will be done from front end
    int rear = -1;  // insertion will be done from rear end

    cout << "\t\t\nASCENDING PRIORITY QUEUE" << endl;

    while (true)
    {
        cout << "\n1. ENQ\n2. DEQ\n3. DISPLAY\n4. EXIT" << endl;
        cout << "Enter your choice :: ";
        cin >> choice;

        switch (choice)
        {
        case 1:
            enq(Q, front, rear, size);
            break;

        case 2:
            deq(Q, front, rear, size);
            break;

        case 3:
            display(Q, front, rear);
            break;

        case 4:
            cout << "\nexiting..." << endl;
            exit(0);
            break;

        default:
            cout << "\nInvalid choice :(" << endl;
            break;
        }
    }
    return 0;
}

void enq(int Q[], int &front, int &rear, int size)
{
    int data, temp;

    if (q_full(front, size))
        cout << "QUEUE OVERFLOW" << endl;
    else
    {
        cout << "Enter the data :: ";
        cin >> data;

        if (front == -1) // means inserting for first time
            front++;

        //find the appropriate place for the data given by the user
        for (temp = rear; temp >= 0 && data < Q[temp]; temp--)
            Q[temp + 1] = Q[temp];

        Q[temp + 1] = data; // insert data at it's right place
        rear++;

        display(Q, front, rear);
    }
}

void deq(int Q[], int &front, int &rear, int size)
{
    if (q_empty(front, rear))
        cout << "\nQUEUE UNDERFLOW";
    else
    {
        //storing data which is to be deleted
        int data = Q[front];

        //if front and rear is equal means there was only one element left
        if (front == rear)
            front = rear = -1; // reset front and rear
        else
            front++;

        display(Q, front, rear);
    }
}

void display(int Q[], int front, int rear)
{
    if (q_empty(front, rear))
        cout << "\nQUEUE IS EMPTY :(" << endl;
    else
    {
        cout << "\nQUEUE :: ";
        for (int i = front; i <= rear; i++)
            cout << Q[i] << "    ";
        cout << '\n';
    }
}

int q_full(int rear, int size)
{
    if (rear >= size)
        return 1;

    return 0;
}

int q_empty(int front, int rear)
{
    if (front == -1 || front > rear)
        return 1;

    return 0;
}

/*
TEST CASE

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 1
Enter the data :: 10

QUEUE :: 10

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 1
Enter the data :: 5

QUEUE :: 5    10

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 1
Enter the data :: 15

QUEUE :: 5    10    15

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 1
Enter the data :: 1

QUEUE :: 1    5    10    15

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 2

QUEUE :: 5    10    15

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 2

QUEUE :: 10    15

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 2

QUEUE :: 15

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 2

QUEUE IS EMPTY :(

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 4

exiting...


TIME COMPLEXITY 
    INSERTION O(n)
    DELETION O(1)
*/


<|start_filename|>Go/cryptography/Keyword_Cipher/Keyword_Cipher.go<|end_filename|>
/*Below is an implementation of keyword cipher in Go. It is a form of
monoalphabetic substitution. A encryption is formed of alphabets from
[a-z] such that the first part of encrption contains unique letters of
the keyword and the rest are the remaining alphabets from [a-z]. That is,
until the keyword is used up, whereupon the rest of the ciphertext letters
are used in alphabetical order, excluding those already used in the key.*/

package main

import (
	"fmt"
	"unicode"
	"bufio"
	"os"
	"strings"
)

// This function generates the pad using the keyword
func padgen(key string) string {

	pad := [26]string{}
	count := 0
	i := 0

	for i < len(key) {

		// Ignoring the spaces in the given keyword
		if(string(key[i]) == " ") {
			i = i + 1
			continue
		}

		// Checking keyword alphabet-wise
		missing := 0
		for j := 0; j < len(key); j++ {
			if(string(key[i]) != string(pad[j])) {
				missing += 1
			}
		}

		// Adding the unique words of key to pad
		if(missing == len(key)) {
			pad[count] = string(key[i])
			count += 1
		}
		i = i + 1
	}
	// Till here we get the first half of the pad

	// Declaring ciphertext string
	var enc string
	var alphabet string = "abcdefghijklmnopqrstuvwxyz"

	i = 0
	// This while loop forms the remaining pad
	for i < 26 {

		not_present := 0
		for j := 0; j < 26; j++ {
			if(string(alphabet[i]) != string(pad[j])) {
				not_present += 1
			}
		}

		/* Whatever alphabets from [a-z] are not present
		in the pad till now, add them to the pad.*/
		if(not_present == 26) {
			pad[count] = string(alphabet[i])
			count = count + 1
		}
		i += 1
	}

	for i := 0; i < len(pad); i++ {
		if(pad[i] != " ") {
			enc += pad[i]
		}
	}

	// Return the length 26 pad
	return enc
}

// This is the encryption function
func encryption(plaintext, key string) string {

	// Generate the pad using the above function
	var pad string = padgen(strings.ToLower(key))
	var alphabet string = "abcdefghijklmnopqrstuvwxyz"

	// Replace all sapces in plaintext with underscores
	var message string
	for j := 0; j < len(plaintext); j++ {
		if(string(plaintext[j]) == " ") {
			message += string("_")
		} else {
			message += string(plaintext[j])
		}
	}

	// Declare the encrypted string
	var encrypted string

	for i := 0; i < len(plaintext); i++ {

		/*If the message has space, add space to the
		encrypted message at the same index.*/
		if(string(message[i]) == "_") {
			encrypted += " "
		} else {
			/*else replace it with the corresponding
			position in the pad*/
			index := 0
			for j := 0; j < len(alphabet); j++ {
				if(string(message[i]) == string(alphabet[j])) {
					index = j
				}
			}
			encrypted += string(pad[index])
		}
	}

	// Return the encrypted message
	return encrypted
}

/* This method formats the ciphertext according to
the plaintext. From the encrypt function above, we
send plaintext in lowercase. So, the ciphertext we
get is also in all lowercase. Here, we format the
ciphertext so that wherever there is capital letter
in the plaintext, same follows in the ciphertext.*/
func format(plaintext, ciphertext string) string {

	var enc string

	/* Check wherever the plaintext is capital and
	then capitalize that character in the ciphertext*/
	for i := 0; i < len(plaintext); i++ {
		if(unicode.IsUpper(rune(plaintext[i]))) {
			enc += strings.ToUpper(string(ciphertext[i]))
		} else {
			enc += string(ciphertext[i])
		}
	}

	// Return the final formatted ciphertext
	return enc
}

func main() {

	// Take plaintext as input from the user
	fmt.Print("Enter the plaintext  : ")
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	plaintext := scanner.Text()

	// Taking keyword as input from the user
	fmt.Print("Enter the keyword    : ")
	scanner.Scan()
	key := scanner.Text()

	// Calling the encrypt function and formatting the ciphertext
	var ciphertext string = encryption(strings.ToLower(plaintext), strings.ToLower(key))
	var encrypted string = format(plaintext, ciphertext)

	// Printing the ciphertext
	fmt.Print("\nThe encrypted text is: ", encrypted, "\n")
}

/* Sample I/O:

Enter the plaintext  : This Is A Secret
Enter the keyword    : Mercury

The encrypted text is: Qbdp Dp M Purouq

*/


<|start_filename|>JavaScript/search/InterpolationSearch.js<|end_filename|>
/*

Interpolation search is a searching algorithm which works similarly to binary search i.e. it works on sorted array.
Interpolation search finds a particular item by computing the probe position.

If the middle item is greater than the item, then the probe position is again calculated in the sub-array to the right of the middle item.
Otherwise, the item is searched in the subarray to the left of the middle item.

Time Complexity - Ο(log (log n))

*/

// Prompt node package for taking user input
const prompt = require("prompt-sync")({ sigint: true });

function interpolationSearch(key) {
  let lowIndex = 0;
  let mid = -1;
  let highIndex = array.length - 1;

  // Check if key lies in the lowerBound & upperBound of array
  while (
    lowIndex <= highIndex &&
    key >= array[lowIndex] &&
    key <= array[highIndex]
  ) {

    // Check if array contains only one element
    if (array.length === 1) {
      if (key === array[lowIndex]) return console.log("Found", array[lowIndex]);
      return console.log("Not Found");
    }

    // Calculate the mid position ( or Probe )
    mid =
      lowIndex +
      Math.floor(
        ((highIndex - lowIndex) / (array[highIndex] - array[lowIndex])) *
          (key - array[lowIndex])
      );

    // Check whether the key is found, if not then update the range i.e lowerBound & upperBound
    if (array[mid] === key) {
      return console.log("Found", array[mid]);
    } else {
      if (array[mid] < key) {
        lowIndex = mid + 1;
      } else if (array[mid] > key) {
        highIndex = mid - 1;
      }
    }
  }

  return console.log("Not Found");
}

/* Workflow of user input */

// Take array length as input
let arrayLength = +prompt("Enter array length - ");

// Check whether the entered value is number or not
if (isNaN(arrayLength)) return console.log("Only numbers are allowed");

// Globally declared array
let array = [];

// Take array items
for (let i = 1; i <= arrayLength; i++) {
  array.push(+prompt(`Enter ${i} element - `));

  // Check whether the entered value is number or not
  if (array.includes(NaN)) return console.log("Only numbers are allowed");
}

console.log("Your array - ", array);

// Sort the given array ( Interpolation Search works for sorted array only )
array.sort((a, b) => {
  return a - b;
});

// Ask the key/number to search in provided array
let key = +prompt("Enter number to search - ");
if (isNaN(key)) return console.log("It should be a number");

// Call the algorithm
interpolationSearch(key);

/*

Sample i/o

> node InterpolationSearch

Enter array length - 5
Enter 1 element - 34
Enter 2 element - 56
Enter 3 element - 78
Enter 4 element - 98
Enter 5 element - 23
Your array -  [ 34, 56, 78, 98, 23 ]
Enter number to search - 12
Not Found

Enter number to search 56
Found 56

*/




<|start_filename|>Java/sort/BeadSort.java<|end_filename|>
import java.util.*;
class sorting
{
    public static void main()
    {
        Scanner sc=new Scanner(System.in);
        int indexI,indexJ,arrayLength,temp,indexK;
        System.out.println("Enter the length of array");
        arrayLength=sc.nextInt();
        int array[]=new int[arrayLength];
        System.out.println("Enter array elements");
        for(indexI=0;indexI<arrayLength;indexI++)
        array[indexI]=sc.nextInt();
        indexI=0;indexJ=1;
        while(indexI<arrayLength-2)
        {    indexJ=indexI+1;
             while(array[indexI]<=array[indexJ])
            {   if(indexI==arrayLength-2)
                break;
                indexI++;
                indexJ=indexI+1;
            }
            if(array[indexI]>array[indexJ])
            {
                temp=array[indexJ];
                array[indexJ]=array[indexI];
                array[indexI]=temp;
                indexI=0;
                continue;
            }
        }
        for(indexI=0;indexI<arrayLength;indexI++)
        System.out.println(array[indexI]+" ");
    }
    
} 

/*
Input :
Enter the length of array
5
Enter array elements
1
2
3
1
1

Output :
1 
1 
1 
2 
3 */


<|start_filename|>C/ds/detectLoopLL.c<|end_filename|>
/*
Detecting a loop/cycle in a linked list.
Algorithm/Approach:
We use two pointers- slow and fast pointers to traverse the linked list.
If there is a loop in the linked list, then we will never encounter a NULL pointer. 
Also, since we are using a slow and a fast pointer, these two pointers will point the same node at one oint of time.
This indicates a loop/cycle in linked list.
*/

#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int data;
    struct Node *next;
} Node;
Node *head;

Node * newNode(int val) {
    Node *new_node = (Node *)malloc(sizeof(Node ));
    new_node -> data = val;
    new_node -> next = NULL;
    return new_node;
}

void insertNode(int value) {
    /* inserting a new node */
    Node *new_node = newNode(value);
    if (!head) {
        head = new_node;
    }
    else {
        new_node -> next = head;
        head = new_node;
    }
}

int detectLoop(Node *head) {
    Node *fastPtr, *slowPtr;
    /* using two pointer */
    slowPtr = fastPtr = head;
    do {
        slowPtr = slowPtr -> next;
        fastPtr = fastPtr -> next;
        fastPtr = fastPtr ? fastPtr -> next : fastPtr;
    } while (fastPtr && slowPtr && fastPtr != slowPtr);
    return slowPtr == fastPtr;
}

void display() {
    Node *p = head;
    while (p) {
        printf("%d ", p -> data);
        p = p -> next;
    }
    printf("\n");
}

int main() {
    int size, val;
    printf("Enter the size of linked list:\n");
    scanf("%d", &size);
    printf("Enter the elements of the linked list:\n");
    for (int i = 0; i < size; i ++) {
        scanf("%d", &val);
        insertNode(val);
    }
    
    /* before introducing a loop */
    if (detectLoop(head)) {
        printf("A loop has been detected in the linked list!\n");
    }
    else {
        printf("No loop detected in the linked list!\n");
    }

    /* after introducing a loop */
    head -> next -> next = head;
    if (detectLoop(head)) {
        printf("A loop has been detected in the linked list!\n");
    }
    else {
        printf("No loop detected in the linked list!\n");
    }
    
    return 0;
}

/*

Sample I/O:
Enter the size of linked list:
5
Enter the elements of the linked list:
1
2
3
4
5
No loop detected in the linked list!
A loop has been detected in the linked list!

Time Complexity: O(n)
Space complexity: O(1)

*/


<|start_filename|>JavaScript/cp/CountAnagrams.js<|end_filename|>
/*  Given two strings word and text, return the number of 
substrings where text contains any anagram of word. */


/* Function to count the number of anagrams */
const countAnagrams = (word, text) => {
    let alpha = new Array(26);

    for(let i = 0; i<alpha.length; i++){
        alpha[i] = 0;
    }

    /* Calculating the frequency of each character in the given word */
    for(let c in word){
        alpha[word.charCodeAt(c)-97]++;
    }

    let window = [];
    let ans = 0;

    /* Checking the occurrences of anagrams of the given word*/
    for(let i=0; i<text.length; i++){
        let c = text.charCodeAt(i);

        /* Adding the current character to the window if the word contains it*/
        if(alpha[c-97] > 0){
            /* Subtracting the given word as we have added it to the window */
            alpha[c-97]--;
            window.push(i);
        }else{

            /* Decrementing the window until it is feasible to accommodate the current character */
            while(window.length > 0 && alpha[c-97] <= 0){
                alpha[text.charCodeAt(window.shift()) - 97]++;
            }

            /* Adding the current character to the window if the word contains it */
            if(alpha[c-97] > 0){
                alpha[c-97]--;
                window.push(i);
            }
        }

        /* Increasing the answer if the window size = word size */
        if(window.length == word.length){
            ans++;
            /* Removing the first character of the window */
            alpha[text.charCodeAt(window.shift()) - 97]++;
        }
    }

    return ans;
}


console.log("Enter the word to be found and the text in which the word needs to be searched");

/* List stores the word and the text */
let list = readline()
    .split(" ")
    .map((element) => element);

/* Only two elements are present in the list, the first one 
represents the word to be searched and the second one 
represents the text in which the word is searched in  */
console.log("Number of substrings which contains the anagram ", list[0], " in ", list[1], " is ", countAnagrams(list[0], list[1]));

/* 
Example 1:

Input:

ab aab

Output:

Number of substrings which contains the anagram ab in aab is 1

Time Complexity: O(N)
Space Complexity: O(K)
*/



<|start_filename|>C-Plus-Plus/graphs/Kosaraju_Algorithm.cpp<|end_filename|>
//Implementation of Kosaraju's Algorithm to find out the strongly connected components (SCCs) in a graph.

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

class Graph {
  list<int> *l;
  list<int> *rl;
  int V;
  vector<int> order;
  int vis[1000], comp[1000];

public:

  Graph(int V) {
    this->V = V;
    l = new list<int>[V];
    rl = new list<int>[V];

  }

  void addEdge(int x, int y) {
    l[x].push_back(y);
    rl[y].push_back(x);
  }

  void dfs(int cur) {
    vis[cur] = 1;
    for (auto x : l[cur]) {
      if (!vis[x]) {
        dfs(x);
      }
    }
    order.push_back(cur);
  }

  void dfs_reverse(int cur, int col) {
    vis[cur] = 1;
    comp[cur] = col;
    for (auto x : rl[cur]) {
      if (!vis[x]) {
        dfs_reverse(x, col);
      }
    }

  }

  //for finding the strongly connected components
  void solve() {
    memset(vis, 0, V);
    for (int i = 0; i < V; i++) {
      if (!vis[i]) {
        dfs(i);
      }
    }
    for (int i = 0; i < V; i++) {
      vis[i] = 0;
    }
    int col = 1;
    for (int i = V - 1; i >= 0; i--) {
      if (!vis[order[i]]) {
        dfs_reverse(order[i], col);
        col++;
      }

    }

    for (int i = 0; i < V; i++) {
      cout << i + 1 << ": " << comp[i] << endl;
    }

  }
};

int main() {
  int n, e;
  cout << "Enter number of vertices and edges:";
  cin >> n >> e;
  Graph g(n);
  cout << "Enter edges:";
  for (int i = 0; i < e; i++) {
    int x, y;
    cin >> x >> y;
    x--; y--;
    g.addEdge(x, y);
  }
  g.solve();
  return 0;
}

/*
Sample input-output:

Input:
6 7
1 2
2 3
3 1
3 4
4 5
5 6
6 4
Output:
1: 1
2: 1
3: 1
4: 2
5: 2
6: 2

Time Complexity: O(n+e)
n: Number of vertices
e: Number of edges
Space Complexity: O(1)
*/


<|start_filename|>Java/cp/PrimeRecursion.java<|end_filename|>
// check whether a number is Prime or not with recursion

import java.util.Scanner;
class PrimeRecursion
{
    public static int prime(int n,int div)
    {
        if(div<n)
        { if(n%div!=0)
            prime(n,div+1);
            else
            return 0;
        }
        return 1;
    }
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter a number : ");
        int n=(int)Math.abs(sc.nextInt());
        int c=prime(n,2);
        System.out.println(n+((c!=0)?" is a Prime Number." :" is not a Prime Number."));
    }
}

// Contributed By ErzaTitani-2001

/*
Sample Input and Output :
Input :
Enter a number : 13
Output :
13 is a Prime Number.
Space Complexity : O(n)
Time Complexity : O(n)
*/


<|start_filename|>C-Plus-Plus/graphs/min_and_max_in_BST.cpp<|end_filename|>
/*
 Program to find the maximum and minimum value in a Binary search Tree.
 The maximum value in the BST will be the right most node of the right sub-tree
 The minimum value in the BST will be the left most node of the left sub-tree
*/

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

struct Node
{
    int data;
    struct Node * left;
    struct Node * right;
};
Node* root = NULL;

// Utility function to create a new Tree Node
Node* newNode(int val)
{
    Node *temp = new Node;
    temp->data = val;
    temp->left = NULL;
    temp->right = NULL;

    return temp;
}

// Function to insert item in a tree
void insertItem(int item)
{
    Node *newnode = newNode(item);
    if(!root) {
        root = newnode;
        return;
    }
    Node *cur, *prev;
    cur = root;
    while(cur!= NULL) {
        prev = cur;
        if(cur->data > item)
            cur = cur->left;
        else
            cur = cur->right;
    }
    if(prev->data > item)
        prev->left = newnode;
    else
        prev->right = newnode;
}

// Function to find the minimum value in a BST
int minValue()
{
    Node *temp = root;
    while (temp->left != NULL)
    {
        temp = temp->left;
    }

    return temp->data;
}

// Function to find the maximum value in a BST
int maxValue()
{
    Node *temp = root;
    while (temp->right != NULL)
    {
        temp = temp->right;
    }

    return temp->data;
}

int main()
{
    int n;
    cin>>n;
    int arr[n];
    for(int i = 0; i < n; i++) {
        cin>>arr[i];
        insertItem(arr[i]);
    }
    cout<<maxValue()<<minValue();
    return 0;
}

/*
 Sample I/O
 Input format: The first line contains n - number of nodes in the tree
               The next line contains n spaced integers
 Output format: Two spaced integers denoting max and min value respectively.
 Example:
 5
 30 60 10 63 25

 Output - 63 10

 Explanation:
    30
   /  \
  10  60
    \   \
    25   63
 Max-element - 63 (rightmost element)
 Min-element - 10 (leftmost element)

*/

/*
 Complexity:
 Time complexity: O(Height of tree)
 Space complexity: O(1)
*/


<|start_filename|>C/ds/Leaf_Nodes_BST.c<|end_filename|>
/* COUNT OF LEAF NODES IN BINARY SEARCH TREE
    Binary Search Tree is a special type of binary tree where 
    1. The value of all the nodes in the left sub-tree is less than or equal to the value of the root.
    2. The value of all the nodes in the right sub-tree is greater than value of the root.
    3. This rule will be recursively applied to all the left and right sub-trees of the root.

    Leaf node is a node which does not have left or right child
    No. of leaf nodes varies with the order in which the nodes are inserted
*/

#include <stdio.h>
#include <stdlib.h>

/* Declare treeNode with data , rc (right child) and lc (left child )
    Initially count of leaf nodes is set as 0
*/
typedef struct treeNode
{
    int data;
    struct treeNode *lc;
    struct treeNode *rc;
} treeNode;

int count = 0;

//to insert a node into BST
treeNode *insertIntoTree(treeNode *root, int data)
{
    //If tree is empty insert as root node
    if (root == NULL)
    {
        treeNode *ptr;
        ptr = malloc(sizeof(treeNode));
        ptr->data = data;
        ptr->lc = NULL;
        ptr->rc = NULL;
        root = ptr;
    }
    else
    {
        // insert recursively in accordance with BST properties
        if (root->data >= data)
        {
            root->lc = insertIntoTree(root->lc, data);
        }
        else if (root->data < data)
        {
            root->rc = insertIntoTree(root->rc, data);
        }
    }
    return root;
}

//to count the leaf nodes
int leaf_nodes(treeNode *root)
{
    //If tree is not empty
    if (root)
    {
        //If the node doesn't have any child increment count
        if (root->lc == NULL && root->rc == NULL)
            count++;
        else
        {
            //recursively check left and right sub-trees
            if (root->lc)
                leaf_nodes(root->lc);
            if (root->rc)
                leaf_nodes(root->rc);
        }
    }
    return count;
}

// driver code
void main()
{
    //Initialize tree as empty
    treeNode *root;
    root = NULL;
    int n, data;
    //Accept the no. of elements and elements as user input
    scanf("%d", &n);

    for (int i = 0; i < n; i++)
    {
        scanf("%d", &data);
        root = insertIntoTree(root, data);
    }

    printf("\nNo. of leaf nodes in the binary search tree = %d", leaf_nodes(root));
    printf("\n");
}

/*
    Sample input:
    7
    1 6 2 5 3 8 4

    Sample output:
    No. of leaf nodes in the binary search tree = 2
*/

/*
    Time complexity : O(n)
    Space complexity : O(n)
*/


<|start_filename|>Kotlin/sort/MergeSort/src/MergeSort.kt<|end_filename|>
fun mergeSort(list : MutableList<Int>) : MutableList<Int>{
    // check if the given list has more than 1 elements
    if (list.size > 1){
        // a list to store sorted list
        val sortedList = MutableList(list.size) { 0 }
        // taking note of middle element of the list
        val middle = list.size / 2

        // splitting list into a left side and right side
        var leftSide = list.slice(0 until middle).toMutableList()
        var rightSide = list.slice(middle until list.size).toMutableList()

        // performing mergesort on the list and storing the results as the sides name
        leftSide = mergeSort(leftSide)
        rightSide = mergeSort(rightSide)

        var i = 0; var j = 0; var k = 0

        // getting smaller elements from the list until one of them is exhausted
        // once one list gets exhausted we know that the elements in the remaining
        // list are larger than the one's we sorted
        while (i < leftSide.size && j < rightSide.size){
            if (leftSide[i] < rightSide[j]) {
                sortedList[k] = leftSide[i]
                i++
            }
            else {
                sortedList[k] = rightSide[j]
                j++
            }
            k++
        }

        // putting the elements of leftSide if they are left after one list gets
        // exhausted
        while ( i < leftSide.size){
            sortedList[k] = leftSide[i]
            i++
            k++
        }

        // putting the elements of rightSide if they are left after one list gets
        // exhausted
        while ( j < rightSide.size){
            sortedList[k] = rightSide[j]
            j++
            k++
        }

        // returning the sorted list
        return sortedList
    }
    // if the size is less than 1 then the list is considered as sorted
    // in itself, just return the item
    return list
}

fun main() {
    print("Enter the number of items to sort - ")
    val lengthOfList = readLine()!!.toInt()

    val list = MutableList(lengthOfList) { 0 }
    list.withIndex().forEach {
        print("Enter value ${it.index + 1} - ")
        list[it.index] = readLine()!!.toInt()
    }
    println("unsorted list is $list")

    val sorted = mergeSort(list.toMutableList());
    println("sorted list is $sorted")
}

/*
    Enter the number of items to sort - 12
    Enter value 1 - 1
    Enter value 2 - 3
    Enter value 3 - 5
    Enter value 4 - 2
    Enter value 5 - 90
    Enter value 6 - 24
    Enter value 7 - 67
    Enter value 8 - 48
    Enter value 9 - 95
    Enter value 10 - 29
    Enter value 11 - 5
    Enter value 12 - 16
    unsorted list is [1, 3, 5, 2, 90, 24, 67, 48, 95, 29, 5, 16]
    sorted list is [1, 2, 3, 5, 5, 16, 24, 29, 48, 67, 90, 95]

    Time Complexity -
    Best Case Complexity: O(n*log n)
    Worst Case Complexity: O(n*log n)
    Average Case Complexity: O(n*log n)

    Space Complexity -
    The space complexity of merge sort is O(n).
 */


<|start_filename|>Go/math/Sum_of_digits/sumofdigitsofnumber.go<|end_filename|>
/* This is a simple program in go language to calculate the sum of
   the individual digits of a given number taken as input and
   prints the output sum */

package main

import(

 "fmt"

)

// global variables: number,reminder and sum
var n int
var r int
var sum int

//function to print the output sum
func printfunction(){

  fmt.Printf("The sum of digits of the number given is :%d",sum)

}

//function to calculate the sum of digits
func Sum(n int) {

  for n != 0{

     r = n%10
     sum += r
     n = n/10

  }

}

//driver function
func main() {

  fmt.Print("Enter the number :")
  fmt.Scanln(&n)

  //calling the sum function to calculate the sum of digits 
  Sum(n)

  //calling print function to print the output sum
  printfunction()

}
/*
   Sample I/O :

   Enter the number :1234
   The sum of digits of the number given is :10
*/



<|start_filename|>C-Plus-Plus/graphs/dfs_of_a_graph.cpp<|end_filename|>
/*
Depth first search is a graph traversal technique.
*/

#include<bits/stdc++.h>
using namespace std;
void dfs(int source, vector <int> adj[],bool visited[]){
    //visit the source
    cout<<source<<" ";
    //mark visited as true
    visited[source] = true;
    //Traverse all its adjacents
    for(auto s:adj[source]){
        //Check if the adjacent is not visited
        if(!visited[s]){
            //Do the same for this vertex i.e. call dfs for this adjacent as source
            //This lets you reach the depth of the graph, So you traverse down a hirearchy instead of going to all adjacents as we do in bfs
            dfs(s,adj,visited);
        }
    }
}
int main(){
    int n,m; cin>>n>>m;
    vector <int> adj[n];
    int a,b;
    for(int i=0;i<m;i++){
        cin>>a>>b;
        adj[a].push_back(b);
        adj[b].push_back(a);
    }
    bool visited[n];
    memset(visited,false,sizeof(visited));
    //Calling dfs for all non visited graphs to cover non connected compnents in graph
    for(int i=0;i<n;i++){
        if(!visited[i]){
            dfs(i,adj,visited);
        }
    }cout<<endl;
    return 0;
}
/*
Input:
4 5
0 1
2 3
1 3
0 3
1 2
Output:
0 1 3 2

Time Complexity: O(n+m) //Sum of vertices and edges
Space Complexity: O(n)  //For the visited array
*/


<|start_filename|>Java/cryptography/AffineCipher.java<|end_filename|>
/*
 * AFFINE CIPHER :-
 * 		It is one of the methods from cryptography.
 * 
 * 		Algorithm :- 
 * 			1) Input text
 * 			2) Find numeric value associated with each letter in the text as "A as 0", "B as 1",..."a as 26", ... etc.
 * 			3) Apply the encryption or decryption formula according to the given instructions.
 * 			4) Now you will get a numeric value, find its equivalent letter (described in step 2).
 * 			5) Collect all the letters and form the cipher text.
 * 			6) Display Cipher text.
 * 
 * 		The Encryption and Decryption formula's followed by the Affine Cipher are as follows :
 *
 * 			Encryption :-
 *				cipherCode = ((multiplicationFactor * inputCode) + additionFactor) % lengthOfAlphabets
 *
 *			Decrytion :-
 * 				decipherCode = ((inverse_multiplicationFactor) * (inputCode - additionFactor)) % lengthOfAlphabets
 * 
 * 			Symbols :-
 * 			1) Length of the alphabet list => 
 * 					It is the total no. of alphabets used as a dictionary to encrypt or decrypt the text.
 * 					In this case, we are considering english language so the dictionary has "A to Z" and "a to z"
 * 
 * 			2) Multiplication Factor => 
 * 					It is a multiplication factor to the input code. It should be coprime with z to work this algorithm.
 * 					In this case, we will be randomly choosing 'multiplication factor' from the set of coprime no.s to length of alphabets.
 * 
 * 			3) Inverse of Multiplication Factor => 	
 * 					This is the a-inverse i.e. the multiplicative inverse of a with respect to length of alphabets. 
 * 					Means (Multiplication Factor x Inverse Multiplication Factor) mod length of alphabets = 1.
 * 
 * 			4) Addition Factor => 
 * 					It is a addition factor. There are no specific constraints other than 0 <= Addition Factor <= Length of alphabets.
 */

import java.util.*;

public class AffineCipher {
	//Creating objects that will be used throughout the code. 
	List<Character> alphabets = new ArrayList<Character>();
	Random randomObject = new Random();
	int lengthOfAlphabets, multiplicationFactor, additionFactor, inverse_multiplicationFactor;
	
	//Constructor which initiates all objects.
	public AffineCipher() {
		//Creating list of "A to Z" and "a to z".
		char alphabet;
		for(alphabet='A'; alphabet<='Z'; alphabet++) {
			alphabets.add(alphabet);
		}
		for(alphabet='a'; alphabet<='z'; alphabet++) {
			alphabets.add(alphabet);
		}
		
		//Assigning values to the various factors used in the encryption/decryption formulas. 
		lengthOfAlphabets = alphabets.size();
		multiplicationFactor = getCoprimeFactor();
		additionFactor = randomObject.nextInt(lengthOfAlphabets+1);
		inverse_multiplicationFactor = getAInverse();
	}
	
	//Function for creating a list of coprime factors of 'z' and randomly assigning one of them to 'a'.
	public int getCoprimeFactor() {
		List<Integer> coprimeFactors = new ArrayList<Integer>();
		for(int coprimeFactor=1; coprimeFactor<=lengthOfAlphabets; coprimeFactor+=2) {
			if((lengthOfAlphabets % coprimeFactor) !=0) {
				coprimeFactors.add(coprimeFactor);
			}
		}
		return coprimeFactors.get(randomObject.nextInt(coprimeFactors.size()));
	}
	
	//Function to find the multiplicative inverse of 'a'.
	public int getAInverse() {
		int a_inverse_temp;
		for(a_inverse_temp=2; a_inverse_temp<=lengthOfAlphabets; a_inverse_temp++) {
			if((multiplicationFactor * a_inverse_temp) % lengthOfAlphabets == 1) {
				break;
			}
		}
		return a_inverse_temp;
	}
	
	//Function for applying affine cipher encryption formula
	public String encryptCipher(String input) {
		String output = "";
		for (char charInInput : input.toCharArray()) {
			int inputCode = alphabets.indexOf(charInInput); //Taking one character of text at a time and assigning its numeric value.
			int cipherCode = ((multiplicationFactor * inputCode) + additionFactor) % lengthOfAlphabets; //Applying encryption formula.
			if(cipherCode < 0) {
				cipherCode += lengthOfAlphabets;
			}
			output += alphabets.get(cipherCode); //Finding the character matching with the calculated cipher code.
		}
		return output;
	}
	
	public String decryptCipher(String input) {
		String output = "";
		for(char charInInput : input.toCharArray()) {
			int inputCode = alphabets.indexOf(charInInput);
			int decipherCode = (inverse_multiplicationFactor * (inputCode - additionFactor)) % lengthOfAlphabets; //Applying decryption formula.
			if(decipherCode < 0) {
				decipherCode += lengthOfAlphabets;
			}
			output += alphabets.get(decipherCode);
		}
		return output;
	}
	
	public static void main(String[] args) {
		//Creating class object so that constructor will instantiate all the constraints.
		AffineCipher affineCipher = new AffineCipher();
		Scanner scanner = new Scanner(System.in);
		
		String outputText;
		String string;
		
		do {
			System.out.println("Menu :-\n1. Encryption\n2. Decryption");
			int choice = scanner.nextInt();
			
			switch(choice) {
			
			case 1	:	//Encrypting given input text to cipher text.
						System.out.print("Enter input text :- ");
						scanner.nextLine();
						String encryptInputText = scanner.nextLine();
						encryptInputText = encryptInputText.replaceAll("\\s", ""); //Removing white spaces
						outputText = affineCipher.encryptCipher(encryptInputText); //Encrypting input text
						
						System.out.println("Input Text :- "+encryptInputText);
						System.out.println("Encrypted Text :- "+outputText);
						break;
						
			case 2	:	//Decrypting given cipher text to normal text.
						System.out.print("Enter input text :- ");
						scanner.nextLine();
						String decryptInputText = scanner.nextLine();
						decryptInputText = decryptInputText.replaceAll("\\s", ""); //Removing white spaces
						outputText = affineCipher.decryptCipher(decryptInputText); //Decrypting cipher text

						System.out.println("Input Text :- "+decryptInputText);
						System.out.println("Encrypted Text :- "+outputText);
						break;
			}
			
			System.out.println("Do you want to continue (Y/N) ? ");
			string = scanner.next();
			
		}while(string.equals("Y"));
		
		scanner.close();
	}
}

/* 
    Output of the Program :- 
	Menu :-
	1. Encryption
	2. Decryption
	1
	Enter input text :- Affine Cipher
	Input Text :- AffineCipher
	Encrypted Text :- dccrQXnramXk
	Do you want to continue (Y/N) ? 
	Y
	Menu :-
	1. Encryption
	2. Decryption
	2
	Enter input text :- dccrQXnramXk
	Input Text :- dccrQXnramXk
	Encrypted Text :- AffineCipher
	Do you want to continue (Y/N) ? 
	N
	
	*Encryption Cycle :- 
	Input 							:-							Affine Cipher
    Input(Removing white spaces) 	:- 							AffineCipher
    Output 							:- 							dccrQXnramXk
    
    *Decryption Cycle :-
    Input 							:-							dccrQXnramXk
    Input(Removing white spaces) 	:- 							dccrQXnramXk
    Output 							:- 							AffineCipher
    
    
	***Note :- 	All the factors except the lengthOfAlphabets are choosen at random so the result may not be the same at every execution of the program.
				But for the encryption and decryption used formula's are of Affine Cipher only. 
*/


<|start_filename|>C-Plus-Plus/dp/edit_distance.cpp<|end_filename|>

#include <iostream>
#include <vector> // for 2D vector
using namespace std;

//Edit distance Recursive approach
int edit_distance_recursive (string &x, string &y, int m, int n)
{
    //base case
    if (m==0) return n;
    if (n==0) return m;

    if(x[m-1]==y[n-1]) //if matches
    {
      return edit_distance_recursive(x,y,m-1,n-1);
    }

    return 1+min( min(edit_distance_recursive(x,y,m,n-1),edit_distance_recursive(x,y,m-1,n)), edit_distance_recursive(x,y,m-1,n-1));

}

//Edit distance DP approach
int edit_distance_dp (string &x, string &y)
{
    int len_x = x.length();
    int len_y = y.length();

    vector<vector<int> > dp (len_x+1, vector<int> (len_y+1,0));
    //base case
    //making last row and column of dp array 0
    for(int i=0;i<=len_x;i++)
        dp[i][0]=i;
    for(int j=0;j<=len_y;j++)
        dp[0][j]=j;

    for(int i=1;i<=len_x;i++)
    {
        for(int j=1;j<=len_y;j++)
        {
            if(x[i-1]==y[j-1]) //if matches
                dp[i][j] = dp[i-1][j-1];
            else     //if doesn't match
                dp[i][j] = 1+min(dp[i-1][j],min(dp[i][j-1],dp[i-1][j-1]));
        }

    }

    return dp[len_x][len_y];   //return last element
}


int main()
{
    string str1,str2;
    cout <<"Enter first string: ";
    cin>>str1;
    cout <<"Enter second string: ";
    cin>>str2;

    int m=str1.length();
    int n=str2.length();

    cout<<"minimum number of edits to convert string1 to string2 Using Recursive approach: ";
    cout<<edit_distance_recursive(str1,str2,m,n)<<endl;

    cout<<"minimum number of edits to convert string1 to string2 Using DP approach: ";
    cout<<edit_distance_dp(str1,str2)<<endl;
}

/*
working
input: sunday saturday
output:3
*/


<|start_filename|>C/other/ugly_number.c<|end_filename|>
/*
Ugly numbers are numbers whose only prime factors are 2, 3 or 5.
The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15 ..…
shows the first 11 ugly numbers.
Your Task is to find nth Ugly number
Time Complexity:O(n)
Space Complexity: O(n)
Example 1:
Sample Input:
10
Sample Output:
12
Example 2:
Sample Input:
4
Sample Output:
4
Language: C
*/

#include <stdio.h>

//return the minimum among x and y
#define MIN(X, Y)(((X) < (Y)) ? (X) : (Y))

//this function return nth ugly number
int get_ugly_no(int n)
{
	int ugly[n], i2 = 0, i3 = 0, i5 = 0;
	int nxt_mul_2 = 2, nxt_mul_3 = 3;
	int nxt_mul_5 = 5, nxt_ugly = 1;
	ugly[0] = 1;
	for (int i = 1; i < n; i++)
	{
		nxt_ugly = MIN(nxt_mul_2, MIN(nxt_mul_3, nxt_mul_5));
		ugly[i] = nxt_ugly;
		if (nxt_ugly == nxt_mul_2)
		{
			i2++;
			nxt_mul_2 = ugly[i2] * 2;
		}

		if (nxt_ugly == nxt_mul_3)
		{
			i3++;
			nxt_mul_3 = ugly[i3] * 3;
		}

		if (nxt_ugly == nxt_mul_5)
		{
			i5++;
			nxt_mul_5 = ugly[i5] * 5;
		}
	}

	return nxt_ugly;
}

int main()
{
	//find the nth ugly number
	int n;
	scanf("%d", &n);
	//calls the get_ugly_no function
	printf("%d", get_ugly_no(n));
	return 0;
}


<|start_filename|>Java/other/PainterPartition.java<|end_filename|>
import java.util.Scanner;

public class PainterPartition {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the array size, number of painters and amount of time:");
        int size = scanner.nextInt();
        int numOfPainters = scanner.nextInt();
        int time = scanner.nextInt();
        int[] boards = new int[size];
        System.out.println("Enter board sizes:");
        for (int i = 0; i < size; i++) {
            boards[i] = scanner.nextInt();
        }
        scanner.close();

        System.out.println("Total time taken:" + partition(boards, size, numOfPainters) * time);
    }

    private static int partition(int[] boards, int size, int numOfPainters) {

        // base cases
        if (numOfPainters == 1) {
            return totalLength(boards, 0, size - 1);
        }
        if (size == 1) {
            return boards[0];
        }

        int best = Integer.MAX_VALUE;

        // find minimum of all possible maximum sums of partitions of the array
        for (int i = 1; i <= size; i++) {
            best = Math.min(best, Math.max(partition(boards, i, numOfPainters - 1),
                    totalLength(boards, i, size - 1)));
        }

        return best;
    }

    private static int totalLength(int[] boards, int from, int to) {
        int total = 0;
        for (int i = from; i <= to; i++) {
            total += boards[i];
        }
        return total;
    }
}
/*
* Sample input/output:
* Enter the array size, number of painters and amount of time:
* 2 2 5
* Enter board sizes:
* 1 10
* Total time taken:50
* Enter the array size, number of painters and amount of time:
* 6 3 1
* Enter board sizes:
* 10 20 30 40 50 60
* Total time taken:90
*
* Time complexity: O(2^n)
*/


<|start_filename|>C-Plus-Plus/cp/minimum_spanning_tree.cpp<|end_filename|>
/*
There are n vertices and e edges and their weights, 
you need to construct minimum spanning tree.
vertex numbers start from 0.

Input:
first line containes the value of n and e.
next e lines follow 3 space seperated integers u, v, w, which means
there is a path between u and v having weight w.

Output:
First line containing the minimum weight of the tree.
next n-1 lines containes 2 space seperated integer u, v & w.
i.e. u and v have a path between them in the formed MST.
and w denotes the weight.

Efficiency: O(e log e + e alpha e)
Language: C++17
*/

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

#define MAX_VERTICES 100005

vector <int> parent(MAX_VERTICES);
vector <int> max_depth(MAX_VERTICES);

//optimised find function
int findparent(int u)
{
	while (u != parent[u])
	{
		//path compression technique
		parent[u] = parent[parent[u]];
		u = parent[u];
	}
	return u;
}

//union function
void take_union(int u, int v)
{
	u = findparent(u);
	v = findparent(v);
	if (max_depth[u] > max_depth[v])
		parent[v] = parent[u];
	else if (max_depth[u] < max_depth[v])
		parent[u] = parent[v];
	else
	{
		max_depth[u]++;
		parent[v] = u;
	}
}
int main()
{
	//decale and read the values of number of
	//vertices and edges respectively
	int n, e; 
	cin >> n >> e;
	//declare and read the values of edge list 
	//edge_list.first contains the weight
	//edge_list.second.first contains the value of u
	//edge_list.second.second contains the value of v. 
	vector <pair <int, pair<int, int> > > edges_list(e);
	for (int i = 0; i < e; i++)
	{
		cin >> edges_list[i].second.first >> edges_list[i].second.second;
		cin >> edges_list[i].first;
	}
	//sort the vector in ascending order in order to keep
	//the edge with weight less first.
	sort(edges_list.begin(), edges_list.end());
	//initialize the parent and max_depth vector.
	for (int i = 0; i <= n; i++)
		parent[i] = i, max_depth[i] = 0;
	//check one-by-one whether to add the edge to mst or not.
	int count_of_edge_mst = 0, total_weight = 0;	
	vector <pair <int, pair<int, int> > > final_edge_mst;
	for (int i = 0; i < e and count_of_edge_mst < n - 1; i++)
	{
		//check whether or not to add this edge 
		if (findparent(edges_list[i].second.first) != findparent(edges_list[i].second.second))
		{
			take_union(edges_list[i].second.first, edges_list[i].second.second);
			//add the dge into the final edge vector
			final_edge_mst.push_back(edges_list[i]);
			//increment the total weight
			total_weight += edges_list[i].first;
			count_of_edge_mst++;
		}
	}
	cout << total_weight << endl;
	for (auto val : final_edge_mst)
		cout << val.second.first << " " << val.second.second << " " << val.first << endl;
	return 0;	
}

/*
Sample Input 1:
9 14
0 1 4
0 7 8
1 7 11
1 2 8 
7 6 1
7 8 7
6 5 2
8 6 6
2 8 2
2 3 7
2 5 4
3 5 14
2 4 9
5 4 10

Sample Output:
37
7 6 1
2 8 2
6 5 2
0 1 4
2 5 4
2 3 7
0 7 8
2 4 9

*/


<|start_filename|>C-Plus-Plus/graphs/BFS1.cpp<|end_filename|>
/*
BFS stands for Breadth-first
search, is an algorithm for 
traversing tree or graph data
structures. It starts at the 
tree root (or some arbitrary 
node of a graph, sometimes
referred to as a 'search key'[1]),
and explores all of the neighbor
nodes at the present depth prior
to moving on to the nodes at the
next depth level. This Program
is to print BFS traversal from a
given source vertex. BFS(int s)
traverses vertices reachable 
from s.
*/

#include <iostream>

#include <list>

using namespace std;

class Graph {
    int V;

    list<int>* adj;

public:
    Graph(int V);

    void addEdge(int v, int w);

    void BFS(int s);
};

Graph::Graph(int V)
{
    this->V = V;
    adj = new list<int>[V];
}

void Graph::addEdge(int v, int w)
{
    adj[v].push_back(w);
}

void Graph::BFS(int s)
{
    bool* visited = new bool[V];
    for (int i = 0; i < V; i++)
        visited[i] = false;

    list<int> queue;

    visited[s] = true;
    queue.push_back(s);

    list<int>::iterator i;

    while (!queue.empty()) {
        s = queue.front();
        cout << s << " ";
        queue.pop_front();

        for (i = adj[s].begin();
             i != adj[s].end(); ++i) {
            if (!visited[*i]) {
                visited[*i] = true;
                queue.push_back(*i);
            }
        }
    }
}

int main()
{
    // Create a graph given in the above diagram
    int V, E, i, S, A, B;

    cout << "Enter the No of Vertex \n";
    cin >> V;
    Graph g(V);

    cout << "Enter the No of Edges \n";
    cin >> E;

    for (i = 0; i < E; i++) {
        cin >> A >> B;
        g.addEdge(A, B);
    }

    cout << "Enter the Vertex to traverse Graph\n";
    cin >> S;

    cout << "The BFS Traversal of given Graph is : "
         << "(starting from vertex )" << S << " \n";

    g.BFS(S);

    return 0;
}

/*
Time Complexity-O(|V|+|E|)
Space Complexity-O(|V|)
where V is the no of vertex in the graph
and E is the no of Edges.
Input
4
6
0 1
0 2
1 2
2 0
2 3
3 3
2
Output
2 0 3 1
*/



<|start_filename|>C-Plus-Plus/cp/Subarray_of_length_two.cpp<|end_filename|>
/*
Given an array A[] of N elements. In one operation, you can select any subarray of length 2 and multiply all 
elements of that subarray by -1. You can do any number of operations (possibly zero). Your task is to maximize 
the sum of all elements of all subarrays of A[].
*/

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

    int maxSum(int n, vector<int> &arr)
    {
        int sum=0,neg_num=0,maxi=INT_MIN;
        for(int i=0;i<n;i++)
        {
            sum+=abs(arr[i])*(n-i)*(i+1);
            if(arr[i]<0)
            neg_num++;
        }
        
        // if negative elements are even in number then sum will be equal to maximum sum of all element of all subarray of given array .
        if(neg_num %2==0)
        {
            return sum; 
        }
        for(int i=0;i<n;i++)
        {
            maxi=max(maxi,sum-2*(i+1)*(n-i)*abs(arr[i]));
        }
        return maxi;    //maximum sum of subarrays
    }

int main()
{
        int N;               // length of array
        cin>>N;
        vector<int> A(N);
        for(int i=0;i<N;i++)         // input array elements
        cin>>A[i];
        cout<<maxSum(N, A)<<endl;    // function call
    
    return 0;
}  

/*
Input:
         N = 3
         A[] = {-1, -2, -3}
         
 Output: 14

Time Complexity : O(N)
*/


<|start_filename|>Java/sort/MinimumSwapsForNIntegers.java<|end_filename|>
import java.util.*;

class MinimumSwapsForNIntegers {

    private static int minSwaps(int[] arr) {
        int countSwaps = 0;

        for(int i=0; i<arr.length; i++) {

            //swapping elements if not in their right positions
            if (arr[i] != i+1) {
                while (arr[i] != i+1) {
                    int temp = arr[arr[i]-1];
                    arr[arr[i]-1] = arr[i];
                    arr[i] = temp;
                    countSwaps++;
                }
            }
        }

        return countSwaps;
    }

    public static void main(String[] args) {
        Scanner sc =new Scanner(System.in);

        // taking input array
        System.out.println("Enter size of array:");
        int size = sc.nextInt();
        int arr[] = new int[size];
        System.out.println("Enter array elements:");
        for (int i=0; i<size; i++) {
            arr[i] = sc.nextInt();
        }
        sc.close();

        // initial array
        System.out.println("Array before sorting:");
        for (int i=0; i<size; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();

        int minSteps = minSwaps(arr);

        // final array
        System.out.println("Array after sorting:");
        for (int i=0; i<size; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();

        System.out.println("Minimum number of swaps required to sort:" + minSteps);
    }
}

/*
Sample input/output:

Enter size of array:
7
Enter array elements:
2
3
7
4
6
1
5
Array before sorting:
2 3 7 4 6 1 5 
Array after sorting:
1 2 3 4 5 6 7 
Minimum number of swaps required to sort:5

Time Complexity: O(N) where N is the size of array.
Auxiliary Space: O(1)
*/


<|start_filename|>C-Plus-Plus/ds/Sum_Of_Elements_Of_N_ary_Tree.cpp<|end_filename|>
/*
Introduction 
Given a N ary Tree ,
Generate a equivalent child sibling Tree , 
and  Print the sum of elements of this equivalent Tree.
It is guaranteed that all node's have unique key values.

Argument/Return Type
Input of total no.of nodes is taken
Input of key values of nodes of tree are taken in level order form 
Incase of a null node , -1 is taken as input
*/

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

//Define Node as structure
struct Node 
{
    int key;
    Node* firstChild;
    Node* nextSibling;
};
 
// Function to create a node with 'value' as the data stored in it. 
// Both the children of this new Node are initially null.
struct Node* newNode(int value)
{
    Node* n = new Node;
    n->key = value;
    n->firstChild = NULL;
    n->nextSibling = NULL;
    return n;
}

//Function to add Sibling and return it
struct Node* addSibling(struct Node* root, int data)
{
    //If root is a null node , return the null node
    if (root == NULL || data==-1)
        return NULL;
    
    //else move to the last sibling and then add the new node as sibling
    while (root->nextSibling)
        root = root->nextSibling;
 
    return (root->nextSibling = newNode(data));
}

//Function to add Child and return it
struct Node* addChild(struct Node* root, int data)
{
    //If root is a null node , return the null node
    if (root == NULL || data==-1)
        return NULL;
 
    //if the first child exists
    //add the new node as a sibling to the first child
    //else add the new node as first child
    if (root->firstChild)
        return addSibling(root->firstChild, data);
    else
        return (root->firstChild = newNode(data));
}

//Function to find sum of all elements of a given Tree
long SumOfNaryTree(struct Node* root)
{
    //If root is a NULL node , return 0
    if(root==NULL)
      return 0;
    
    //else return the sum of tree 
    //by recursively calculating sum of First Child Tree and next sibling
    //To make sure sum doesn't overflow , add it step by step
    long answer=root->key;
    answer=answer + SumOfNaryTree(root->firstChild) + SumOfNaryTree(root->nextSibling) ;

    return answer;
}
                
// Driver code
int main()
{
    //Input the head of N ary Tree
    struct Node* root;
    cout<<"Enter the key value of the head of the N ary Tree (incase of a NULL node , enter -1) : ";
    int data;
    cin>>data;
    if(data!=-1)
      root=newNode(data);
    else 
      root=NULL;

    // To take input of whole N ary Tree
    //create a queue and push all newly created nodes into it
    queue<struct Node*>q;
    q.push(root);

    struct Node* curr;

    //keep traversing the queue , till its empty
    while(!q.empty())
    {
      //If the root node is NULL break the loop
      if(q.front()==NULL)
        break;
      else
      {
         //During each visit of  a node , 
         //Collect its children nodes and build a child sibling Tree equivalent to N ary Tree
         struct Node* temp=q.front();
         q.pop();
         int n;
         //Input no.of child nodes of the current node
         cout<<"Enter total no.of child nodes of node with data value "<<temp->key<<" : ";
         cin>>n;
         //If there are no child nodes , continue
         if(n==0) 
           continue;
         cout<<"Enter values of children from left right , with space : ";
         //Input each node and add it as the child node for the current node
         for(int i=1;i<=n;i++)
         {
            cin>>data;
            //Push all the newly created nodes , i.e children nodes
            q.push(addChild(temp,data));
         }
      }    
    }

    //Call the function and print the result
    cout<<"Hence the sum of the given N ary Tree is : "<<SumOfNaryTree(root);

    return 0; 
}
    
/*
Input:
0 <= node->key < 1000000000
Each Node should have unique key value
if node is NULL , -1 is entered as it's key

Sample Test Case 1  
Input N ary Tree :                   

                          1                                 
           /           /       \    \                    
         2            13       16   18         
     /   |    \       / \       |       
    3    4     5     14  15     17      
  / | \  |    / | \                 
 6  7  8 9   10 11 12         

Input Format : 
Example :
Enter the key value of the head of the N ary Tree (incase of a NULL node , enter -1) : 1
Enter total no.of child nodes of node with data value 1 : 4
Enter values of children from left right , with space : 2 13 16 18
Enter total no.of child nodes of node with data value 2 : 3
Enter values of children from left right , with space : 3 4 5
Enter total no.of child nodes of node with data value 13 : 2
Enter values of children from left right , with space : 14 15
Enter total no.of child nodes of node with data value 16 : 1
Enter values of children from left right , with space : 17
Enter total no.of child nodes of node with data value 18 : 0
Enter total no.of child nodes of node with data value 3 : 3
Enter values of children from left right , with space : 6 7 8
Enter total no.of child nodes of node with data value 4 : 1
Enter values of children from left right , with space : 9
Enter total no.of child nodes of node with data value 5 : 3
Enter values of children from left right , with space : 10 11 12
Enter total no.of child nodes of node with data value 14 : 0
Enter total no.of child nodes of node with data value 15 : 0
Enter total no.of child nodes of node with data value 17 : 0
Enter total no.of child nodes of node with data value 6 : 0
Enter total no.of child nodes of node with data value 7 : 0
Enter total no.of child nodes of node with data value 8 : 0
Enter total no.of child nodes of node with data value 9 : 0
Enter total no.of child nodes of node with data value 10 : 0
Enter total no.of child nodes of node with data value 11 : 0
Enter total no.of child nodes of node with data value 12 : 0

Output Format :
Example : ( Output to the above input example ) 
Hence the sum of the given N ary Tree is : 171

Time/Space Complexity
Time Complexity : O(n) 
   Where n is the no.of nodes 
Space Complexity : O(n) 
   Where n is the no.of nodes
*/


<|start_filename|>Go/math/Noble_Integer/nobleinteger.go<|end_filename|>
/* This is a simple program to check if we have a noble number or not
   from the given array. An integer is said to be Noble in an array
   if the number of integers greater than integer is equal to integer.
*/

package main

import (

  "fmt"

)

// global variables
var number int
var arr [100]int

//This function helps us in finding the noble number
func nobleInteger() int{

    for i:=0;i<number;i++ {

      count :=0
      for j:=0;j<number;j++ {
         if(arr[i]<arr[j]){
            count += 1
         }
      }

      // if the count of greater elements = arr[i]
      if(count == arr[i]){
         fmt.Print("Noble integer is ",arr[i])
         return 1
      }

    }

    fmt.Printf("Noble integer not found")
    return 0
}

// driver function
func main(){

    fmt.Print("Enter the no of elements of the Array :")
    //taking the array size
    fmt.Scan(&number)

    var n int
    fmt.Print("Enter the elements of the array :")
    // scanning the elements of the array
    for i:=0;i<number;i++ {
       fmt.Scan(&n)
       arr[i] = n
    }

    //calling the noble integer function 
    nobleInteger()

}

/* Sample I/O :

   a) If no noble integer :

   Enter the no of elements of the Array :5
   Enter the elements of the array :1 2 3 4 5
   Noble integer not found

   b) If there is noble number :

   Enter the no of elements of the Array :5
   Enter the elements of the array :10 3 20 40 2
   Noble integer is 3   
*/



<|start_filename|>C/sort/MAX_MIN_HeapSort.c<|end_filename|>
/* C code for Heap Sorting*/ 

#include<stdio.h>

void maxHeap(int[], int);
void minHeap(int[], int);

int temp;
//function for maxHeap Sort
void maxHeap(int arr[], int len) {
  int pos, maxH;
  for (int i = 1; i < len; i++) {
    pos = i;
    do {
      maxH = (pos - 1) / 2;
      /* to build MAXHEAP  array */
      if (arr[maxH] < arr[pos]) {
        temp = arr[maxH];
        arr[maxH] = arr[pos];
        arr[pos] = temp;
      }
      pos = maxH;
    } while (pos != 0);
  }

  printf("Heap  array : \n");
  printf("Max Heap\n");
  for (int i = 0; i < len / 2; i++) {
    printf("Parent : %d Left Child : %d Right Child : %d\n", arr[i], arr[2 * i + 1], arr[2 * i + 2]);
  }
  for (int j = len - 1; j >= 0; j--) {
    temp = arr[0];
    arr[0] = arr[j];
    arr[j] = temp;
    maxH = 0;
    do {
      pos = 2 * maxH + 1;
      if ((arr[pos] < arr[pos + 1]) && pos < j - 1)
        pos++;
      if (arr[maxH] < arr[pos] && pos < j) {
        temp = arr[maxH];
        arr[maxH] = arr[pos];
        arr[pos] = temp;
      }
      maxH = pos;
    } while (pos < j);
  }
}

//Function for MinHeap Sort
void minHeap(int arr[], int len) {
  int pos, minH;
  for (int i = 1; i < len; i++) {
    pos = i;
    do {
      minH = (pos - 1) / 2;
      /* to build MINHEAP  array */
      if (arr[minH] > arr[pos]) {
        temp = arr[minH];
        arr[minH] = arr[pos];
        arr[pos] = temp;
      }
      pos = minH;
    } while (pos != 0);
  }
  printf("Min Heap\n");
  for (int i = 0; i < len / 2; i++) {
    printf("Parent : %d Left Child : %d Right Child : %d\n", arr[i], arr[2 * i + 1], arr[2 * i + 2]);
  }
  for (int j = len - 1; j >= 0; j--) {
    temp = arr[0];
    arr[0] = arr[j];
    arr[j] = temp;
    minH = 0;
    do {
      pos = 2 * minH + 1;
      if ((arr[pos] > arr[pos + 1]) && pos < j - 1)
        pos++;
      if (arr[minH] > arr[pos] && pos < j) {
        temp = arr[minH];
        arr[minH] = arr[pos];
        arr[pos] = temp;
      }
      minH = pos;
    } while (pos < j);
  }
}

//driver code to check above function
int main() {
  int size;
  printf("Input-->\n");
  printf("Enter the size of array :\n");
  scanf("%d", & size);
  int arr[size];
  printf("Enter the elements of array :\n");
  for (int i = 0; i < size; i++) {
    scanf("%d", & arr[i]);
  }
  maxHeap(arr, size);
  minHeap(arr, size);
  return 0;
}

/*
 Input-->                                                                                                     
 Enter the size of array :                                                                                    
 3                                                                                                            
 Enter the elements of array :                                                                                
 12                                                                                                           
 15                                                                                                           
 56                                                                                                           
 Heap  array :                                                                                                
 Max Heap                                                                                                     
 Parent : 56 Left Child : 12 Right Child : 15                                                                 
 Min Heap                                                                                                     
 Parent : 12 Left Child : 15 Right Child : 56  
 
 Time Complexity : O(n log n)
 Space Complexity : O(1)
 */



<|start_filename|>C/cp/LuhnsAlgo.c<|end_filename|>
/******************************************************************************

Author - @Suvraneel 
        <NAME>

*Luhn's Algorithm for credit card validation*

A credit card number consists of 16 decimal digits. The first (leftmost) digit corresponds to the type of the
card (4 for VISA cards, 5 for MASTERCARDs, 3 for Diners Club and American Express cards, and so on).
The next 6 digits correspond to the number of the bank that issues the card. The next 8 digits constitute the
account number of the card-holder. The last (rightmost) digit is a check digit that determines whether the
credit card number is valid or not. In order to determine the check digit, a checksum is computed as follows.
We first add the digits at the even positions (that is, the second, fourth, sixth, ... , sixteenth digits) of the card
number. Next, each digit in an odd position is doubled. If the doubled value exceeds 9, then the two digits
are added. Finally, these doubled digits (after adjustment of 2-digit values) are added to the checksum. The
check digit is so chosen that the checksum is a multiple of 10. Here is an example.
Card Number   5        9   8         7   6         5   4   0   2   4   6         8   1   3   5         5
Step 1        10       9   16        7   12        5   8   0   4   4   12        8   2   3   10        5
Step 2        1+0 = 1  9   1+6 = 7   7   1+2 = 3   5   8   0   4   4   1+2 = 3   8   2   3   1+0 = 1   5

Checksum = 1 + 9 + 7 + 7 + 3 + 5 + 8 + 0 + 4 + 4 + 3 + 8 + 2 + 3 + 1 + 5 = 70

Since the checksum is divisible by ten, 5987654024681355 is a valid credit card number. Write a program
that, upon input a 16-digit credit card number, determines whether the card number is valid. A 16-digit
integer cannot be accommodated in a long int variable, so read the input as a string (a character array).
*******************************************************************************/

#include <stdio.h>
//header for string operations
#include <string.h>

//global variable
//initiates checksum to zero
int checksum = 0;

//function to evaluate checksum
void checksum_calc(char card[])
{
    //iterates as many times as there are characters in the input string
    for (int i = 0; i < strlen(card); i++)
    {
        int digit = card[i] - '0';
        //even positions
        if (i%2==1){
            //digits added to checksum as it is
            checksum += digit;
            printf(" + %d", digit);
        }
        //odd positions (might require 2digit adjustments)
        if (i%2==0){
            checksum += (2*digit<10) ? (2*digit):((2*digit)%10)+1;
            /*
            Ternary operator used to imply single digits are added to checksum without any change;
            But for 2digit nos., sum of the digits is to be added to checksum.
            (n modulo 10) + 1 yields same value as the 2digit adjustment
            (eg, (11%10)+1 = 2 = 1+1   ;   10%10+1 =1 = 1+0 )
            */
            printf(" + %d", (2*digit<10) ? (2*digit):(((2*digit)%10)+1));
        }
    }
}

//driver code
int main()
{
    //character array
    char card[16];
    printf("Enter the credit card number:\n");
    //reads a line from stdin and stores it into the 'card' character array
    gets (card);
    //function to evaluate checksum
    checksum_calc(card);
    //test if checksum is valid (ie, if modulo10 = 0)
    printf("\t = %d\t",checksum);
    printf(checksum%10==0 && (int)strlen(card) == 16 ? "(Valid)":"(Invalid)");       
    //the card number must have exactly 16 digits   
    if ((int)strlen(card) != 16)
        printf("\n[Invalid because card number must have exactly 16 digits.]");            
    return 0; 
}

/*
Time Complexity = O(1)
Space Complexity = O(1)

Std O/P 1:
Enter the credit card number:
5987654024681355        
 + 1 + 9 + 7 + 7 + 3 + 5 + 8 + 0 + 4 + 4 + 3 + 8 + 2 + 3 + 1 + 5         = 70  (Valid)

Std O/P 2:
Enter the credit card number:
5987654024681353
 + 1 + 9 + 7 + 7 + 3 + 5 + 8 + 0 + 4 + 4 + 3 + 8 + 2 + 3 + 1 + 3         = 68  (Invalid)

Std O/P 3:
Enter the credit card number:
59876540246813550
 + 1 + 9 + 7 + 7 + 3 + 5 + 8 + 0 + 4 + 4 + 3 + 8 + 2 + 3 + 1 + 5 + 0     = 70  (Invalid)
[Invalid because card number must have exactly 16 digits.]
*/


<|start_filename|>C-Plus-Plus/other/subsets.cpp<|end_filename|>
//C++ Program to print all subsets of a given distinct array of positive integers
#include <bits/stdc++.h>
using namespace std;

void GetSubsets(vector<int> inputArray, vector<int> subsetArray, int pos)
{
	if (pos == inputArray.size())
	{
		//the input array has been traversed when pos = array size
		cout << "[";
		for (int i = 0; i < subsetArray.size(); i++)
		{
			if (subsetArray[i] != 0)	//ignoring empty values
				cout << subsetArray[i] << ",";
		}

		cout << "]\n";
	}
	else
	{
		GetSubsets(inputArray, subsetArray, pos + 1);	//Recursion tree branch 1

		subsetArray[pos] = inputArray[pos];
		GetSubsets(inputArray, subsetArray, pos + 1);	//Recursion tree branch 2
	}
}

//DRIVER FUNCTION
int main()
{
	int size;
	cout << "Enter size of the array: ";
	cin >> size;
	vector<int> inputArray(size);	//initializing input array with user-given size
	for (int i = 0; i < size; i++)
	{
		cin >> inputArray[i];
	}

	vector<int> subsetArray(size);	//empty array for storing subsets
	cout << "[";
	GetSubsets(inputArray, subsetArray, 0);	//prints the subsets
	cout << "]";
}

/*Sample IO

Input:
3
1 2 3
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
] 

TIME COMPLEXITY - O(2^n)
SPACE COMPLEXITY - O(n)

/*

<|start_filename|>JavaScript/sort/StoogeSort.js<|end_filename|>
/*

Stooge sort is a recursive sorting algorithm.
It is notable for its exceptionally bad time complexity which is slower compared to reasonable sorting algorithms.

Algorithm - 1) If value of the start is larger than the value at the end, swap them
            2) If there are 3 or more elements in the list, then -
                a] Stooge sort the initial 2/3 of the list
                b] Stooge sort the final 2/3 of the list
                c] Stooge sort the initial 2/3 of the list again

Time Complexity - O(n(log3/log1.5)) ( Slower than bubble sort )

*/

// Prompt node package for taking user input
const prompt = require("prompt-sync")({ sigint: true });

function stoogeSort(array, start, end) {
  let pivot;

  // Checking condition - whehther there are at least 2 elements or not
  if (end - start + 1 > 2) {
    pivot = Math.floor((end - start + 1) / 3);
    stoogeSort(array, start, end - pivot); // sort the first 2/3
    stoogeSort(array, start + pivot, end); // sort the last 2/3
    stoogeSort(array, start, end - pivot); // sort the first 2/3 again
  }

  // Swap if the leftmost element is larget than rightmost
  if (array[start] > array[end]) {
    [array[start], array[end]] = [array[end], array[start]];
  }
}

/* Workflow of user input */

// Take array length as input
let arrayLength = +prompt("Enter array length - ");

// Check whether the entered value is number or not
if (isNaN(arrayLength)) return console.log("Only numbers are allowed");

// Globally declared array
let array = [];

// Take array items
for (let i = 1; i <= arrayLength; i++) {
  array.push(+prompt(`Enter ${i} element - `));

  // Check whether the entered value is number or not
  if (array.includes(NaN)) return console.log("Only numbers are allowed");
}

console.log("Your array - ", array);

// Call the algorithm
stoogeSort(array, 0, arrayLength - 1);
console.log("Sorted Array - ", array);

// Sample I/O

/*

> node StoogeSort

Enter array length - 5
Enter 1 element - 45
Enter 2 element - 86
Enter 3 element - 23
Enter 4 element - 98
Enter 5 element - 66
Your array -  [ 45, 86, 23, 98, 66 ]
Sorted Array -  [ 23, 45, 66, 86, 98 ]

*/



<|start_filename|>C-Plus-Plus/graphs/zigzag_tree_traversal.cpp<|end_filename|>
/*
   This program will print ZigZag traversal of tree by using concept of Depth First Search with some modification
 */

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

struct node {
	node(int x): data(x), left_child(NULL), right_child(NULL) {}
	int data;
	node *left_child;
	node *right_child;
};

class bin_tree {
	node *root;
  public:
	// constructor of tree
	bin_tree() {
		root = NULL;
	}
	void insert_data(int x) {
		//if tree is empty
		if (!root) {
			node *tnode = new node(x);
			root = tnode;
		}
		//if tree if not empty
		else {
			node *temp = root;
			while (1) {
				//if data to be inserted is less then the data of current node
				if (x < temp->data ) {
					//if left child of current node is node present
					///we simple add new node with the data to be inserted
					if (!temp->left_child) {
						node *tnode = new node(x);
						temp->left_child = tnode;
						break;
					}
					//else we change the current node pointer 
					//with pointer of left child node pointer
					else
						temp = temp->left_child;
				}
				//if data to be inserted is grater then 
				//or equal to the data of current node
				else {
					//if right child of current node is node present 
					//we simple add new node with the data to be inserted
					if (!temp->right_child) {
						node *tnode = new node(x);
						temp->right_child = tnode;
						break;
					}
					//else we change the current node pointer 
					//with pointer of left child node pointer
					else
						temp = temp->right_child;
				}
			}
		}
	}
	void zigzag(node*);
	void zigzag_traversal_of_tree();
};

void bin_tree :: zigzag_traversal_of_tree() {
	zigzag(root);
}

void bin_tree :: zigzag(node* r) {
	//if no node is found
	if (!r)
		return;
    // declare two stacks to store nodes at current level and next level
	stack<struct node*> currentlevel; 
    stack<node*> nextlevel; 
  
    // push the root 
    currentlevel.push(root); 
  
    // check if stack is empty    
    bool lefttoright = true; 
    while (!currentlevel.empty()) { 
  
        // pop out of stack 
        node* temp = currentlevel.top(); 
        currentlevel.pop(); 
  
        // if not null 
        if (temp) { 
  
            // print the data in it 
            cout << temp->data << " "; 
  
            // store data according to current 
            // order. 
            if (lefttoright) { 
                if (temp->left_child) 
                    nextlevel.push(temp->left_child); 
                if (temp->right_child) 
                    nextlevel.push(temp->right_child); 
            } 
            else { 
                if (temp->right_child) 
                    nextlevel.push(temp->right_child); 
                if (temp->left_child) 
                    nextlevel.push(temp->left_child); 
            } 
        } 
  
        if (currentlevel.empty()) { 
            lefttoright = !lefttoright; 
            swap(currentlevel, nextlevel); 
        } 
    } 
}

int main() {
	bin_tree t;
	int n;
	cout << "Enter number of elements in tree: ";
	cin >> n;
	cout << "Enter elements to insert in  tree: ";
	while (n--) {
		int k; cin >> k;
		t.insert_data(k);
	}
	cout << "\nZigzag Traversal of tree:";
	t.zigzag_traversal_of_tree();
	return 0;
}

/*
	Sample case 1:
	
	Enter number of elements in tree: 8
	Enter elements to insert in  tree: 50 40 60 55 30 56 70 45
	Zigzag View of tree : 50 60 40 30 45 55 70 56
	     50
	  /     \
	 /       \
	40        60
	/   \     /   \
	/     \   /     \
	30    45  55      70
	        \
	         \
	         56

	.....................................................................
	Sample case 2:
	Enter number of elements in tree: 10
	Enter elements to insert in  tree: 50 40 30 45 60 55 54 70 75 72
	Left View of tree : 50 60 40 30 45 55 70 75 54 72
	     50
	  /     \
	 /       \
	40        60
	/   \     /   \
	/     \   /     \
	30    45   55      70
	       /        \
	      /          \
	      54        75
	                /
	               /
	               72
   
Time Complexity: O(n) 
Space Complexity: O(n)
*/


<|start_filename|>Java/ds/Stackll.java<|end_filename|>
//Stack implemetation Its readme file in wiki
import java.util.*;
import java.lang.*;
class mystack<E>
{
    static class Node<E> {
        E data;
        Node<E> next;
        Node(E data) {
            this.data = data;
            next = null;
        }
    }
    Node<E> head;
    Node<E> top;
    int c=0;
    boolean isempty(){ return head==null;}
    void push(E a){
        Node<E> temp=new Node<E>(a);
        Node<E> temp1=head;
        if(isempty()){
            head=temp;
            top=head;
            c++;
            return;
        }
        else{
            while(temp1.next!=null){
                temp1=temp1.next;
            }
            temp1.next=temp;
            c++;
            top=temp;
        }
    }
    E peek(){
        if(isempty())
            return null;
        return top.data;
    }
    E pop() throws Exception{
        if(isempty()){
            throw  new Exception("eeempty");
        }
        else if(head==top){
            Node<E> temp1=head;
            head=top=null;
            return temp1.data;
        }
        else{
            Node<E> temp1=head;
            Node<E> temp;
            while(temp1.next.next!=null){
                temp1=temp1.next;
            }
            temp=temp1.next;
            temp1.next=null;
            top=temp1;
            c--;
            return temp.data;
        }
    }
}

public class Stackll {
    public static void main(String[] args) throws Exception {
        mystack<Integer> s = new mystack<Integer>();
        s.push(1);
        s.push(2);
        s.push(3);
        System.out.println(s.peek());
        System.out.println(s.pop());
        System.out.println(s.pop());
        System.out.println(s.pop());
        System.out.println(s.peek());
        System.out.println(s.pop());
    }
}
/*
output:
3
3
2
1
null
Exception in thread "main" java.lang.Exception: eeempty
	at mystack.pop(Stackll.java:43)
	at Stackll.main(Stackll.java:76)
 */


<|start_filename|>C/cp/BoyerMooreVote.c<|end_filename|>
/*C code to find the majority element in a given set of string by Boyer-Moore voting algorithm */
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
struct boyerMajorityCheck
{
    int majority_number, majority_check;
}; //declaring a structure for returning two integers in a function

typedef struct boyerMajorityCheck Struct;

//function to find the boyer-moore majority element
Struct boyerMooreVote(int ar[], int len)
{
    Struct bmv;
    int i, count = 1;
    int temp = ar[0];
    for (i = 1; i < len - 1; i++)
    {
        if (count == 0)
        {
            temp = ar[i];
            count = 1;
        }
        else
        {
            if (temp == ar[i])
            {
                count += 1;
            }
            else
            {
                count -= 1;
            }
        }
        /*algorithm used to find the majoritty number */
    }
    bmv.majority_number = temp;
    int count2 = 0;
    for (i = 0; i < len - 1; i++)
    {
        if (temp == ar[i])
            count2 += 1;
    }
    if (count2 > len / 2)
        bmv.majority_check = 1;
    else
        bmv.majority_check = 0;
    return bmv;
}

//driver function

int main()
{
    int arr[MAX], n, i, result;
    printf("Enter the number of elements:-");
    scanf("%d", &n);
    printf("Enter the elements :-");
    for (i = 0; i < n; i++)
    {
        scanf("%d", &arr[i]);
    }
    Struct Result = boyerMooreVote(arr, n);
    if (Result.majority_check == 0)
        printf("The majority number is %d and it's occurance is less than N/2", Result.majority_number);
    else
    {
        printf("The majority number is %d and it's count is more than N/2", Result.majority_number);
    }
    return 0;
}

/* 
Time complexity : O(n) where n is the number of elements
OUTPUT
Enter the number of elements:-8
Enter the elements :-3 4 3 5 3 3 7 9
The majority number is 3 and it's count is more than N/2
*/


<|start_filename|>Java/other/3sum_closest_to_target.java<|end_filename|>
/*

Three sum closest to target

You will be given an array of integers arr[], and a target value
and your task will be to find three such elements whose sum comes
the closest to the target value.
The output will be the sum of the set of three numbers whose sum comes is the
closest to target value.

*/

import java.util.*; 
import java.util.Arrays; 

class 3sum_closest_to_target
{
    //function to find the closest sum
    public int 3sumClosest(int arr[], int target)
    {
        //storing result
        int res = arr[0] + arr[1] + arr[arr.length-1];

        Arrays.sort(arr);

        //using two pinter approach
        for(int i = 0; i<arr.length-2; i++)
        {
            int leftptr = i+1;
            int rightptr = arr.length-1;
            while(leftptr<rightptr)
            {
                int sum = arr[i] + arr[leftptr] + arr[rightptr];
                if(sum > target)
                {
                    rightptr--;
                }
                else {
                    leftptr++;
                }
                if(Math.abs(sum-target) < Math.abs(res-target))
                {
                    res = sum;
                }
            }
        }
        return res;
    }

    //driver method
    public static void main(String []args)
    {
        Scanner sc = new Scanner(System.in); 

        System.out.println("Enter the size of the array: "); 
        int size = sc.nextInt(); 

        System.out.println("Enter the target value: "); 
        int target = sc.nextInt();

        int arr[] = new int[size]; 
        System.out.println("Enter the elements of array: "); 
        for(int i = 0; i < size; i++) 
        { 
            arr[i] = sc.nextInt(); 
        } 

        System.out.println("Closest sum is: ");
        System.out.print(3sumClosest(arr, target));

    }
}

/* 

EXAMPLES:-

Example 1:
Input--
Enter the size of the array: 4
Enter the target value: 1
Enter the elements of array: 1, -1, -4, 2
Output--
Closest sum is: 2

Example 2:
Input--
Enter the size of the array: 5
Enter the target value: 7
Enter the elements of array: 2, 6, 1, 7, 4
Output--
Closest sum is: 7

Example 3:
Input--
Enter the size of the array: 1
Enter the target value: 1
Enter the elements of array: 0
Output--
Closest sum is: 0

TIME COMPLEXITY --> O(N^2)

*/


<|start_filename|>Java/ds/LevelOrderTraversalRecursion.java<|end_filename|>
/*
Introduction 
Any binary tree can be represented using multiple traversal techniques.One of them is level order traversal.
In this traversal, we print the nodes of a tree,level by level,one after another.
This could be implemented using recursion or queue data structure.
Here,this code is based on recursion.
There are basically two functions in this code.One prints all nodes at a given level and the other
prints level order traversal considering the subtrees individually.
At the end,it prints the level order traversal of the given binary tree.
*/
import java.util.*;
class Node
{
    int data;
    Node left;
    Node right;
    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}
class BinaryTree
{
    Node root;
    public BinaryTree()
	{
		root = null;
	}
    int height(Node root)
	{
		if (root == null)
		return 0;
		else
		{
			/* calculate height of each subtree individually */
			int lh = height(root.left);
			int rh = height(root.right);
			
			/* the height is the maximum path,theefore,return the larger one */
			if (lh > rh) return(lh+1);
			else return(rh+1);
		}
	}
    void printLevel (Node root ,int level)
	{
        /* if root is null,then the root is the last node,therefore,we end here */
		if (root == null)
			return;

        /* if it is the first level,then print the data */
		if (level == 1)
			System.out.print(root.data + " ");

        /* if the level is not 1, print the left and right subtree individually */
		else if (level > 1)
		{
			printLevel(root.left, level-1);
			printLevel(root.right, level-1);
		}

	}
    void LevelOrderTraversal(Node root)
	{
        /* calculate the height of the tree */
		int h = height(root);
		int i;

        /* traverse till the height */
		for (i=1; i<=h; i++)
			printLevel(root, i);
	}
    public Node insert(Node root, int data) 
    {
        if(root == null) {
            return new Node(data);
        } else {
            Node curr;
            if(data <= root.data) {
                curr = insert(root.left, data);
                root.left = curr;
            } else {
                curr = insert(root.right, data);
                root.right = curr;
           }
            return root;
        }
    }
}
public class LevelOrderTraversalRecursion
{
    public static void main (String[] args)
     {
        BinaryTree b=new BinaryTree();
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of nodes:");
        int t = sc.nextInt();
        System.out.println("Enter nodes:");
        Node root = null;
        while(t-- > 0)
        {
            int data = sc.nextInt();
            root = b.insert(root, data);
        }
        System.out.println("Level order traversal is:");
        b.LevelOrderTraversal(root);
    }

}
/*
input:
Enter number of nodes:
5
Enter nodes:
8 67 6 90 2

output:
Level order traversal is:
8 6 67 2 90
       8
      / \
     6   67
    /     \
   2       90

Time Complexity: O(n^2) in worst case.
 
Space Complexity: O(n) in worst case. 
*/



<|start_filename|>C/search/randomized_selection_algorithm.c<|end_filename|>
//This  algorithm is used to select i_th order statistic from the given data in O(n) time complexity and O(1) space complexity
#include <stdio.h>
#include <stdlib.h>
int arr[100000];

int part(int arr[], int lower, int upper) 
{
    int z = arr[upper];
    int i = lower - 1;
    for (int j = lower; j <= upper - 1; j++)
    {
        if (arr[j] <= z)
        {
            ++i;
            int change = arr[i]; // Now we are swapping arr[i] and arr[j]
            arr[i] = arr[j];
            arr[j] = change;
        }
    }
    int change2 = arr[i + 1]; // now we are swapping arr[i+1] and arr[upper]
    arr[i + 1] = arr[upper];
    arr[upper] = change2;
    return i + 1;
}
int random_type(int minimum, int maximum) 
{                    //this function is used to generate a random number in the given range
    int type = maximum - minimum + 1;
    int number = minimum + (rand() % type);
    return number;
}

int Randomized_type(int arr[], int lower, int upper) 
{
    int i = random_type(lower, upper);
    int change = arr[upper];
    arr[upper] = arr[i];
    arr[i] = change;
    return part(arr, lower, upper);
}

int Randomized_select_algo(int arr[], int lower, int upper, int i) 
{
    if (lower == upper)  //if the array has only one element
        return arr[lower];
    
    int x= Randomized_type(arr, lower, upper);
    int y= x+1-lower ;

    if (i == y)     // The value obtained is the answer
        return arr[x];
    else if (i > y) // the  value required lies on the upper side 
         return Randomized_select_algo(arr, x + 1, upper, i - y);
    else            // the  value required lies on the lower side 
        return Randomized_select_algo(arr, lower, x- 1, i);
}

int main()
{
    int n, i;
    printf("Enter number of elements: \n");
    scanf("%d",&n);
    
    for (int i = 0; i < n; i++)
         scanf("%d",&arr[i]);

    printf("Enter i: \n");
    scanf("%d",&i);
    printf("%d",Randomized_select_algo(arr, 0, n - 1, i));
    return 0;
}
/*
   sample test case
   let n = 6 and array input be [6, 89, 45, 12, 78, 3]  and i =4
   then Randomized_select_algo will give us answer 45 as 4th element of the sorted array or 45 is the next greater element than the first 3 element i.e. 3,6,12
   sorted array [3, 6, 12, 45, 78, 89]
*/


<|start_filename|>C-Plus-Plus/dp/K-Tree.cpp<|end_filename|>
/*
problem link: https://codeforces.com/problemset/problem/431/C

Problem description:
A k-tree is an infinite rooted tree where:
- each vertex has exactly k children.
- each edge has some weight.
- edge weights will be in order 1,2,..k from left most child to right most child
  of every node in the tree

count number of paths of total weight n (the sum of all weights of the edges in the path),
starting from the root of a k-tree and also containing at least one edge of weight at least d
*/

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

int dp[105][2];
int Number_of_Paths(int n, int k, int d, bool dcaught)
{
	// base case.
	if (n == 0)
	{
		return dcaught == true;
	}
	/* memoization step: checking whether the current required answer is already caluculated or not
	   if yes then we will simply return the answer.
	*/
	if (dp[n][dcaught] != -1)
	{
		return dp[n][dcaught];
	}
	// cnt variable has number of paths
	int cnt = 0;
	// min(n,k) is used because including edges with weight greater than n wont help us.
	for (int weight = 1; weight <= min(n, k); weight++)
	{
		/* if weight is >=d then we pass decaught as true
		   else we pass its current value only
		*/
		if (weight >= d)
		{
			cnt = (cnt % mod + Number_of_Paths(n - weight, k, d, true) % mod) % mod;
		}
		else
		{
			cnt = (cnt % mod + Number_of_Paths(n - weight, k, d, dcaught) % mod) % mod;
		}
	}
	// according to dp state the required answer will be at dp[n][dcaught]
	return dp[n][dcaught] = cnt;
}

int main()
{

	memset(dp, -1, sizeof(dp));
	int n, k, d;
	cin >> n >> k >> d;
	int ans = Number_of_Paths(n, k, d, false);
	cout << ans << endl;
	return 0;
}

/*
Time complexity:O(n*k)
Space complexity:O(n)
Input: 4 3 2
output:6
*/


<|start_filename|>JavaScript/Algorithms/LongestIncreasingSubsequenceDP.js<|end_filename|>
/*
1. We have to find the length of the longest increasing subsequence in the input array. 
2. Longest Increasing Subsequnce is length of the longest strictly increasing subsequence.
3. The problem can be solved using Dynamic Programming. 
4. The approch is to find the LIS for each element and return the largest of them. 
*/

//Function that finds the length of the longest increasing subsequence
let FindLIS = (list, len) => {
  //creating a new array of size len to store the LIS value
  let lis = new Array(len);

  //lis[i] stores the length of the longest increasing subsequence upto list[i]
  //Initializing lis[0] to be 1 as LIS for 1 element is 1
  lis[0] = 1;

  for (let i = 1; i < len; ++i) {
    lis[i] = 1;
    for (let j = 0; j < i; ++j) {
      //checking if i list[i] has a smaller element to its left so that list[i] can be updated
      if (list[j] < list[i] && lis[i] < lis[j] + 1) {
        lis[i] = lis[j] + 1;
      }
    }
  }

  //variable that stores the length of the longest increasing subsequence of the array
  let sizeOfLIS = 0;

  //finding the largest value in the lis array
  for (let i = 0; i < len; ++i) {
    sizeOfLIS = Math.max(sizeOfLIS, lis[i]);
  }

  //returning the LIS value
  return sizeOfLIS;
};

//Using the readline() function of JavaScript to take input from the user
console.log(
  "Enter the elements of the array for which length of Longest Increasing Subsequence has to be found"
);

//list is input array
let list = readline()
  .split(" ")
  .map((x) => parseInt(x));

//n is length of the input array
let n = list.length;

//storing LIS
let lengthOfLongestIncreasingSubsequence = FindLIS(list, n);

//printing the answer
console.log(
  `The length of the longest increaing subsequnce is ${lengthOfLongestIncreasingSubsequence}`
);

/*
Time complexity of the program - O(N^2)
Space Complexity of the program - O(N)
*/

/*
Sample Input Output : 

Input 1 : 
list = [10, 22, 9, 33, 21, 50, 41, 60, 74, 108]

Output 1 : 
The length of the longest increaing subsequnce is 7

Explanation : 
The longest increasing subsequnce is [10, 22, 33, 41, 60, 74, 108], hence the length of LIS is 7


Input 2 : 
list = [10,9,2,5,3,7,101,18]

Output 2 : 
The length of the longest increaing subsequnce is 4

Explanation : 
The longest increasing subsequnce is [2, 3, 7, 101], hence the length of LIS is 4


Input 3 : 
list = [7,7,7,7]

Output 3 : 
The length of the longest increaing subsequnce is 1

Explanation : 
The longest increasing subsequnce is [7], hence the length of LIS is 1
*/


<|start_filename|>C/ds/singly_linked_list.c<|end_filename|>
#include <stdio.h>
#include <malloc.h>

typedef struct node
{
    int value;
    struct node *next;
}node;

node* create_node(int);
void insert_node_first();
void insert_node_last();
void insert_node_pos();
void count();
void delete_pos();
void search();
void empty();
void display();

node *newnode, *ptr, *prev, *temp;
node *first = NULL, *last = NULL;

 int main()
 {
    int ch;
    char ans = 'Y';

    while (ans == 'Y'||ans == 'y')
    {
        printf("\n---------------------------------\n");
        printf("\nOperations on singly linked list\n");
        printf("\n---------------------------------\n");
        printf("\n1-Insert node at first");
        printf("\n2-Insert node at last");
        printf("\n3-Insert node at position");
        printf("\n4-Display the total number of nodes");
        printf("\n5-Delete Node from any Position");
        printf("\n6-Check if list is empty or not");
        printf("\n7-Search Element in the linked list");
        printf("\n8-Display List from Beginning to end");
        printf("\n9-Exit\n");
        printf("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
        printf("\nEnter your choice : ");
        scanf("%d", &ch);

        switch (ch)
        {
        case 1:
            printf("\nInserting node at first :\n");
            insert_node_first();
            break;
        case 2:
            printf("\nInserting node at last :\n");
            insert_node_last();
            break;
        case 3:
            printf("\nInserting node at position :\n");
            insert_node_pos();
            break;
        case 4:
            count();
            break;
        case 5:
            delete_pos();
            break;
        case 6:
            printf("\nchecking the list :\n");
            empty();
            break;
        case 7:
            printf("\nSearching Element in the List :\n");
            search();
            break;
        case 8:
            printf("\nDisplaying List From Beginning to End :\n");
            display();
            break;
        case 9:
            printf("\nExiting :\n");
            return 0;
            break;
        default:
            printf("\nInvalid Choice :\n");
            break;
        }
        printf("\nYOU WANT TO CONTINUE (Y/N)");
        scanf(" %c", &ans);
    }
    return 0;
 }

node* create_node(int val)
{
    newnode = (node *)malloc(sizeof(node));
    if (newnode == NULL)
    {
        printf("\nMemory was not allocated");
        return 0;
    }
    else
    {
        newnode->value = val;
        newnode->next = NULL;
        return newnode;
    }
}

void insert_node_first()
{
    int val;

    printf("\nEnter the value for the node:");
    scanf("%d", &val);
    newnode = create_node(val);
    if (first == last && first == NULL)
    {
        first = last = newnode;
        first->next = NULL;
        last->next = NULL;
    }
    else
    {
        temp = first;
        first = newnode;
        first->next = temp;
    }
    printf("\n----INSERTED----");
}

void insert_node_last()
{
    int val;

    printf("\nEnter the value for the Node:");
    scanf("%d", &val);
    newnode = create_node(val);
    if (first == last && last == NULL)
    {
        first = last = newnode;
        first->next = NULL;
        last->next = NULL;
    }
    else
    {
        last->next = newnode;
        last = newnode;
        last->next = NULL;
    }
 printf("\n----INSERTED----");
}

void insert_node_pos()
{
    int pos, val, cnt = 0, i;

    printf("\nEnter the value for the Node:");
    scanf("%d", &val);
    newnode = create_node(val);
     printf("\nEnter the position ");
    scanf("%d", &pos);
    ptr = first;
    while (ptr != NULL)
    {
        ptr = ptr->next;
        cnt++;
    }
    if (pos == 1)
    {
        if (first == last && first == NULL)
        {
            first = last = newnode;
            first->next = NULL;
            last->next = NULL;
        }
        else
        {
            temp = first;
            first = newnode;
            first->next = temp;
        }
        printf("\nInserted");
    }
    else if (pos>1 && pos<=cnt)
    {
        ptr = first;
        for (i = 1;i < pos;i++)
        {
            prev = ptr;
            ptr = ptr->next;
        }
        prev->next = newnode;
        newnode->next = ptr;
        printf("\n----INSERTED----");
    }
    else
    {
        printf("Position is out of range");
    }
}


void count()
{
    node *nxt;
    int t = 0;

    if (first == NULL)
    {
        printf("\nEMPTY LIST:");;
    }
    else
    {
        for (ptr = first;ptr != NULL;ptr = ptr->next)
        {
          t++;
        }
        printf("\nTotal Number of nodes : %d",t);

    }
}


void delete_pos()
{
    int pos, cnt = 0, i;

    if (first == NULL)
    {
        printf("\nEMPTY LIST:");;
        printf(":No node to delete\n");
    }
    else
    {
        printf("\nEnter the position of value to be deleted:");
        scanf(" %d", &pos);
        ptr = first;
        if (pos == 1)
        {
            first = ptr->next;
            printf("\nElement deleted");
        }
        else
        {
            while (ptr != NULL)
            {
                ptr = ptr->next;
                cnt = cnt + 1;
            }
            if (pos > 0 && pos <= cnt)
            {
                ptr = first;
                for (i = 1;i < pos;i++)
                {
                    prev = ptr;
                    ptr = ptr->next;
                }
                prev->next = ptr->next;
            }
            else
            {
                printf("Position is out of range");
            }
        free(ptr);
        printf("\nElement deleted");
        }
    }
}

void empty()
{
    int oldval, newval, flag = 0;

    if (first == NULL)
    {
        printf("The list is empty\n");
    }
}


void search()
{
    int flag = 0, key, pos = 0;

    if (first == NULL)
    {
        printf("\nEMPTY LIST:");;
        printf(":No nodes in the list\n");
    }
    else
    {
        printf("\nEnter the value to search");
        scanf("%d", &key);
        for (ptr = first;ptr != NULL;ptr = ptr->next)
        {
            pos = pos + 1;
            if (ptr->value == key)
            {
                flag = 1;
                break;
            }
        }
        if (flag == 1)
        {
            printf("\nElement %d found at %d position\n", key, pos);
        }
        else
        {
            printf("\nElement %d not found in list\n", key);
        }
    }
}

void display()
{
    if (first == NULL)
    {
        printf("\nEMPTY LIST:");;
        printf(":No nodes in the list to display\n");
    }
    else
    {
        for (ptr = first;ptr != NULL;ptr = ptr->next)
        {
            printf("%d\t", ptr->value);
        }
    }
}

/*
Following are the sample of Input/Output processed by this program :

---------------------------------

Operations on singly linked list

---------------------------------

1-Insert node at first
2-Insert node at last
3-Insert node at position
4-Display the total number of nodes
5-Delete Node from any Position
6-Check if list is empty or not
7-Search Element in the linked list
8-Display List from Beginning to end
9-Exit

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Enter your choice : 1

Inserting node at first :

Enter the value for the node:12

----INSERTED----
YOU WANT TO CONTINUE (Y/N)y

---------------------------------

Operations on singly linked list

---------------------------------

1-Insert node at first
2-Insert node at last
3-Insert node at position
4-Display the total number of nodes
5-Delete Node from any Position
6-Check if list is empty or not
7-Search Element in the linked list
8-Display List from Beginning to end
9-Exit

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Enter your choice : 2

Inserting node at last :

Enter the value for the Node:13

----INSERTED----
YOU WANT TO CONTINUE (Y/N)y

---------------------------------

Operations on singly linked list

---------------------------------

1-Insert node at first
2-Insert node at last
3-Insert node at position
4-Display the total number of nodes
5-Delete Node from any Position
6-Check if list is empty or not
7-Search Element in the linked list
8-Display List from Beginning to end
9-Exit

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Enter your choice : 8

Displaying List From Beginning to End :
12      13
YOU WANT TO CONTINUE (Y/N)n

Process returned 0 (0x0)   execution time : 31.014 s
Press any key to continue.
*/


<|start_filename|>Java/other/MaximumSquareMatrix.java<|end_filename|>
import java.util.Scanner;

public class MaximumSquareMatrix {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter number of rows and columns:");
        int r = scanner.nextInt();
        int c = scanner.nextInt();
        int[][] matrix = new int[r][c];
        System.out.println("Enter elements of the matrix:");
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                matrix[i][j] = scanner.nextInt();
            }
        }

        printMaxSquare(matrix);
    }

    private static void printMaxSquare(int[][] matrix) {

        int rows = matrix.length, cols = matrix[0].length, i, j, maxSquare, max_i, max_j;
        int[][] squareSizes = new int[rows][cols];

        // Set first column of squareSizes[][]
        for(i = 0; i < rows; i++) {
            squareSizes[i][0] = matrix[i][0];
        }

        // Set first row of squareSizes[][]
        for(j = 0; j < cols; j++) {
            squareSizes[0][j] = matrix[0][j];
        }

        // getting other entries for squareSizes
        for (i = 1; i < rows; i++) {
            for (j = 1; j < cols; j++) {
                if(matrix[i][j] == 1) {
                    squareSizes[i][j] = Math.min(squareSizes[i][j - 1],
                            Math.min(squareSizes[i - 1][j], squareSizes[i - 1][j - 1])) + 1;
                } else {
                    squareSizes[i][j] = 0;
                }
            }
        }

        // find max entry of squareSizes
        maxSquare = squareSizes[0][0]; max_i = 0; max_j = 0;
        for(i = 0; i < rows; i++)
        {
            for(j = 0; j < cols; j++)
            {
                if(maxSquare < squareSizes[i][j])
                {
                    maxSquare = squareSizes[i][j];
                    max_i = i;
                    max_j = j;
                }
            }
        }

        // print result
        System.out.println("Maximum size sub-matrix is: ");
        for(i = max_i; i > max_i - maxSquare; i--)
        {
            for(j = max_j; j > max_j - maxSquare; j--)
            {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}
/*
* Sample input/output:
* Enter number of rows and columns:
* 6 5
* Enter elements of the matrix:
* 0 1 1 0 1
* 1 1 0 1 0
* 0 1 1 1 0
* 1 1 1 1 0
* 1 1 1 1 1
* 0 0 0 0 0
* Maximum size sub-matrix is:
* 1 1 1
* 1 1 1
* 1 1 1
*
* Space and Time complexity = O(m*n)
*/


<|start_filename|>C-Plus-Plus/cp/Paint_Fence.cpp<|end_filename|>
/*
___Paint Fence Algorithm___

Problem:
Given a fence with n posts and k colors
Find out the number of ways of painting the fence
such that at most 2 adjacent posts have the same color.

Input:
n : number of posts
k : number of colors

Output:
result: number of ways of painting
        considering the condition above

*/

#include <iostream>
using namespace std;

//function uses permutation logic to output number of possible ways of painting

int paint_fence(int n, int k){          
    if(n<2 || k<(n/2)){
        return -1;
    }
    int total[n-1],same[n-1],diff[n-1];
    same[0]=k;
    diff[0]=k*(k-1);
    total[0]=k*k;
    for(int i=1;i<n-1;++i){
        same[i] = diff[i-1];
        diff[i] = total[i-1]*(k-1);
        total[i] = same[i]+diff[i];
    }
    return total[n-2];
}

int main(){
    int post,color;
    cout<<"Enter n,Number of Posts\n";
    cin>>post;
    cout<<"Enter k,Number of Colors\n";
    cin>>color;
    int result = paint_fence(post,color);
    if(result==-1){
        cout<<"Painting is not possible following the condition\n";
    }
    else{
        cout<<"Number of Possiblities: "<<result<<"\n";
    }
    return 0;
}


/*Sample Input/Output

Enter n,Number of Posts
3
Enter k,Number of Colors
5
Number of Possiblities: 120

Enter n,Number of Posts
10
Enter k,Number of Colors
4
Painting is not possible following the condition

Enter n,Number of Posts
5
Enter k,Number of Colors
3
Number of Possiblities: 180

Time Complexity  O(n)
Space Complexity O(n) 
*/


<|start_filename|>C-Plus-Plus/graphs/Dijkstra_algorithm.cpp<|end_filename|>
#include<iostream>
#include<utility>
#include<queue>
#include<vector>

using namespace std; 
# define INF 0x3f3f3f3f 
typedef pair<int, int> iPair; 
 
 /* Used priority queue STL and vector pair representation of graph
    for quicker implementation of Dijkstra's shortest path algorithm */
  
void addEdge(vector <pair<int, int> > adj[], int u, 
                                     int v, int wt) 
{ 
    adj[u].push_back(make_pair(v, wt)); 
    adj[v].push_back(make_pair(u, wt)); 
} 
   
  
void shortestPath(vector<pair<int,int> > adj[], int V, int src) 
{ 
  
    priority_queue< iPair, vector <iPair> , greater<iPair> > pq; 
  
    vector<int> dist(V, INF); 
  
    pq.push(make_pair(0, src)); 
    dist[src] = 0; 
  
    while (!pq.empty()) 
    { 
        int u = pq.top().second; 
        pq.pop(); 
  
        for (auto x : adj[u]) 
        { 
            int v = x.first; 
            int weight = x.second; 
            if (dist[v] > dist[u] + weight) 
            { 
                dist[v] = dist[u] + weight; 
                pq.push(make_pair(dist[v], v)); 
            } 
        } 
    } 
  
    printf("Vertex Distance from Source\n"); 
    for (int i = 0; i < V; ++i) 
        printf("%d \t\t %d\n", i, dist[i]); 
} 
  
int main() 
{ 
    //sample graph
    int V = 9; 
    vector<iPair > adj[V]; 
   
    //Adding edges of the graph
    addEdge(adj, 0, 1, 4); 
    addEdge(adj, 0, 7, 8); 
    addEdge(adj, 1, 2, 8); 
    addEdge(adj, 1, 7, 11); 
    addEdge(adj, 2, 3, 7); 
    addEdge(adj, 2, 8, 2); 
    addEdge(adj, 2, 5, 4); 
    addEdge(adj, 3, 4, 9); 
    addEdge(adj, 3, 5, 14); 
    addEdge(adj, 4, 5, 10); 
    addEdge(adj, 5, 6, 2); 
    addEdge(adj, 6, 7, 1); 
    addEdge(adj, 6, 8, 6); 
    addEdge(adj, 7, 8, 7); 
  
    shortestPath(adj, V, 0); 
  
    return 0; 
} 


<|start_filename|>JavaScript/ds/Stack.js<|end_filename|>
class Stack {
  //Initializing stack with an empty array
  constructor() {
    this.arr = [];
    var top = 0;
  }
  //push_back is used to push the elements in the stack
  push_back(num) {
    arr[top] = num;
    top++;
  }
  //peek is used to return the element which is on the top of stack
  peek() {
    return arr[top];
  }

  //pop returns the element which is at the top and also removes it from the stack
  pop() {
    if (this.isEmpty()) {
      console.log("UnderFlow");
      return 0;
    } else {
      var temp = arr[top];
      top--;
      console.log("One element has been removed from the stack");
      return temp;
    }
  }
  //isEmpty is used to check whether the stack is empty or not
  isEmpty() {
    if (top == 0) {
      return true;
    } else {
      return false;
    }
  }
  // print is used to print all the elements of the stack
  print() {
    var output = "";
    for (var i = 0; i < top; i++) {
      output += arr[i] + " ";
    }
    return output;
  }
  //size is used to return the size of the stack
  count() {
    return top;
  }
}
//Implementation

//Taking input from the user that how many values he/she wants to push into the stack
var input = prompt(
  "Enter the number of values you want to push into the stack"
);

var another_arr = []; //Declaring the array

input = parseInt(input);

for (var i = 0; i < input; i++) {
  //Taking array values as an input from the user
  another_arr[i] = prompt("Enter Element " + (i + 1));
}

/*I will be taking the value of input be 3 and array values as 56,75,24 for explanation. */
var input = 3;

const another_arr = [56, 75, 24];

//Making an object of the stack class
var mystack = new Stack();

//Checking whether the stack is empty or not by isEmpty()
if (mystack.isEmpty() == true) {
  console.log("The stack is empty right now");
} else {
  console.log("The stack has elements in it");
}

//We can check it by count() also but it will not return true or false
console.log("The size of the current stack is", mystack.count()); //It will print 0.

//Pushing elements in the stack
for (var i = 0; i < input; i++) {
  mystack.push_back(another_arr[i]);
}

//After pushing all the elements then mystack will be [56,75,24]

//Printing the new size of the array using count()
console.log("The new size of stack is ", count()); // It will print 3.

//Printing the stack with print()
console.log("The elements present in stack are ", mystack.print()); //It will print 56 75 24.

//Removing the topmost element from the stack by pop()
var removed_element = mystack.pop(); //This will return 24.

console.log("The element which is popped from the stack is ", removed_element); //It will print 24

//Printing the stack after removing the element using print()
console.log(
  "The elements present after removing one element in stack are ",
  mystack.print()
); //It will print 56 75


<|start_filename|>C-Plus-Plus/other/Decimal_to_gray.cpp<|end_filename|>
/*Gray code is an ordering of the binary numeral system such that two successive values differ in only one bit (binary digit).
In gray code, two consecutive values are differed by one bit of binary digits.
Binary number can be converted to gray code by performing xor of two consecutive bits.

Decimal to Gray code Conversion: Decimal(2) = 0010(Binary)
0  0  1  0
|\ /\ /\ /
0 0  1  1
Here, 1st bit is taken as it is. Next, xor of 2 consecutive bits is performed[xor of (0,0) , (0,1) , (1,0)]. Therefore, gray
code for 2 in binary format is 0011.

In this problem, the number in decimal is converted into gray code in decimal format.
Example:
I/O : 2
O/P : 3
Explanation: 2 in binary format is 0010. When converted into gray code, it is 0011. But decimal equivalent of 0011 is 3.
*/

#include<iostream>
using namespace std ;

int dec_to_gray_code(int fn_in_decimal)
{
    /*
    To get gray code, xor has to be performed for consecutive bits. So instead of dealing with only one pair of bits at a
    time, all xor operations are performed at one step by performing xor of input number and number obtained by shifting input
    number to right by 1.
    */
    return fn_in_decimal ^ (fn_in_decimal >> 1);
}

int main(void)
{
    int n_in_decimal = 0, n_in_gray = 0 ;

    //Take user input as decimal number
    cout << "Enter the number in decimal : " << endl ;
    cin >> n_in_decimal ;

    //Call to function dec_to_gray_code
    n_in_gray = dec_to_gray_code(n_in_decimal) ;

    cout << "The gray code value for decimal number " << n_in_decimal << " is : " << n_in_gray << endl ;
    return 0 ;
}

/*
 Sample Example :
 I/O : 7
 O/P : 4

 Explanation: 7 in binary is written as 0111. When converted to gray code, it is 0100. 0100 in decimal is 4. Hence code outputs 4.

 Time Complexity : O(1)
 Space Complexity : O(1)
*/



<|start_filename|>C-Plus-Plus/sort/Randomized_Quick_Sort.cpp<|end_filename|>
#include<iostream>        //Header file 
#include<ctime>           //To use time function as a seed for pseudo random generator
#include<cstdlib>         //For pseudo random number generator
using namespace std;      //For cin and cout

/*
    In Randomized Quick Sort, we use random number to pick the next pivot (or we randomly shuffle the array)
    and then apply quick sort on the array. Randomization is used here to eliminate the worst case time complexity
    of quick sort (that is, when the input array is already sorted).

    @author <NAME>
    @since 27-7-2020
*/

//Implemention randomShuffle function
void randomShuffle( int a[], int start, int end ){

    //Seed time to the pseudo random number generator
    srand( time( NULL ) );

    int i, j;

    //Generate random number and bring them to range 0 to i+1 and store in j
    //Swap element at ith and jth index
    for( i= end; i >= 0; i-- ){

        j= rand() % ( i + 1 );
        swap(a[j],a[i]);

    }
}

//Implement partitionPivot function
int partitionPivot( int a[], int start, int end ){

    int i= start-1;
    int j= start;
    int pivot= a[end];

    //Traverse the array - whenever an element smaller than pivot occurs, swap it with (i+1)th element 
    for(j= start; j<= end-1; j++){
        
        if(a[j] <= pivot){
            i++;
            swap(a[i],a[j]);
        }
    }

    //Place the pivot element at i+1 (between smaller and larger elements)
    swap(a[i+1],a[end]);

    //Return position of pivot
    return i+1;
}

//Implement Quick Sort function
void quickSort( int a[], int start, int end ){

    //base case
    //If start (index) crosses end (index), there are no elements to sort further, thus return
    if( start >= end ){
        return;
    }

    //Taking end element as pivot, place the pivot element in its right position such that
    //elements left to the pivot are smaller than pivot and elements right to the pivot are greater than pivot
    //Return pivot's position (index)
    int p= partitionPivot( a, start, end );

    //Recursively sort left and right part of the pivot element
    //Left part of the pivot
    quickSort( a, start, p-1 );
    //Right part of the pivot
    quickSort( a, p+1, end);

    return;
}

int main(){

    int n;
    cout<<"Enter the number of elements: ";
    cin>>n;

    int a[n];
    cout<<endl<<"Enter the elements of the array: ";
    
    for(int i= 0; i<n; i++){        //For loop to input n elements into the array
        cin>>a[i];
    }

    //Shuffle the array 
    randomShuffle( a, 0, n-1);

    //Call the quick sort function on the array - quickSort( array_name, start, end);
    quickSort( a, 0, n-1 );

    //Print the sorted array
    for(int i= 0; i< n; i++){
        cout<<a[i]<<" ";
    }


    return 0;
}



<|start_filename|>C-Plus-Plus/ds/inverse_of_an_array.cpp<|end_filename|>
/*
INVERSE OF AN ARRAY   
If the array elements are swapped with their corresponding indices,
the array finally results is inverse of an array. 
*/

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

void inverse(int a[], int n, int b[])
{
    for (int i = 0; i < n; i++)
    {
        int temp = a[i];
        b[temp] = i;
    }
    for (int i = 0; i < n; i++)
        cout << b[i] << " ";
}

int main()
{
    // Driver code begins
    int t, n;
    cin >> t;
    while (t--)
    {
        cin >> n;
        int ori[n];
        int inv[n];

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

        inverse(ori, n, inv);
    }
    return 0;
}

/*
time complexity -: O(n) 
Sample input:
2
5
4 0 2 3 1
3
0 1 2
Sample Output
1 4 2 3 0
0 1 2
*/



<|start_filename|>C/other/Russian_Peasant_Algorithm.c<|end_filename|>
/*
In this algorithm we keep halving one number and doubling the 2nd one.
While halving, if we get an odd number, we add the 2nd doubled number to the result.
This goes on until the halving makes the first reach 0.
It is also known as the Ancient Egyptian Multiplication, used by
scribes to do multiplication without using the multiplication table.
*/
#include <stdio.h>

int Russian_Peasant_Algo(int, int);
int main()
{
	int a, b, ans;
	printf("Enter the first number: ");
	scanf("%d", &a);
	printf("\nEnter the second number: ");
	scanf("%d", &b);
	ans = Russian_Peasant_Algo(a, b);
	printf("\nThe product of the given number is %d\n", ans);
	return 0;
}
// Implementing the Russian-Peasant Algorithm
int Russian_Peasant_Algo(int a, int b)
{
	int ans = 0;
	while (b)
	{
		if (b % 2)
		{
			ans += a;
		}
		a *= 2;
		b /= 2;
	}
	return ans;
}

/*
Time Complexity: O(log2(max(no of digits in a, no of digits in b)))

Sample Output
Enter the first number: 4
Enter the second number: 5
The product of the given numbers is 20
*/



<|start_filename|>Go/cryptography/RailFence_Cipher/railfencecipher.go<|end_filename|>
/* The rail fence cipher (also called a zigzag cipher) 
   is a form of transposition cipher. It derives its 
   name from the way in which it is encoded. Given a
   plain-text message and a numeric key, it cipher the
   given text using Rail Fence algorithm(here key == 2). 
*/

package main

import (

  "fmt"
  "unicode"
  "bufio"
  "os"
  "strings"

)

// Global variables
var plaintext string
var ciphertext string

// In this array we store the elements in step wise 
var array[2][100] string
var output string

/* This function formats the given ciphertext according to
   the orginal plaintext recieved from the user as input.
   In the monoalphabeticcipher function below, we converet
   the given plaintext into lowercase for our cinvinence of 
   checking. So, the ciphertext we get is also in all 
   lowercase. Here, we format the ciphertext so that wherever
   there is capital letter in the plaintext, same follows 
   in the ciphertext.*/
func format(temp string) {

    /* Checking if the given letter in plaintext is capital 
       or not and changint it to capttal if it was*/
    for i:=0; i < len(temp); i++ {

       if (unicode.IsUpper (rune(temp[i]) ) ) {

           output += strings.ToUpper(string(ciphertext[i]))

       }else {

          output += string(ciphertext[i])

       }

    }

}

/* In this function we store the given plaintext in form of
   step in the 2D array then we concatenate the letters in 
   the first row and then the second row*/
func railfencecipher() {


     // storing them step wise
     for i:=0;i<len(plaintext);i++ {

        for j:=0;j<2;j++ {

             array[j][i] = string(plaintext[i])

        }

     }

     k:=0
     // concatenating the 2 rows
     for k<len(plaintext) {

          for a:=0;a<2;a++ {

               b := a
               for b<len(plaintext) {

                    ciphertext += string(array[a][b])
                    k += 1
                    b += 2

               }

          }


     }


}

// driver function
func main() {

     // Taking the plaintext as input from user
     fmt.Print("Enter the plaintext : ")
     scanner := bufio.NewScanner(os.Stdin)
     scanner.Scan()

     plaintext = scanner.Text()
     temp := plaintext

     /* calling the railfence cipher function
        to encrypt the input string leaving the
        space in to small letters*/
     railfencecipher()

     /* calling the format function to format the 
        calculated cipher text in according to the 
        plaintext format */
     format(temp)

     // Printing the cipher text out
     fmt.Print("The cipher text is :",output)
}

/*
     Sample I/O :
 
     a) All small letters :

     Enter the plaintext : hello world
     The cipher text is :hlowrdel ol    

     b) All Capital letters :

     Enter the plaintext : HELLO WORLD
     The cipher text is :HLOWRDEL OL      

     c) Mix of small and capital letters :

     Enter the plaintext : Hello World
     The cipher text is :HloWrdEl ol

*/



<|start_filename|>C-Plus-Plus/stack/string_expression_evaluation_bodmas.cpp<|end_filename|>
/*
Evaluate string expression using BODMAS
==============================
Evaluate a string expression containing (,),+,-,/ and * using BODMAS rules
Application: Stack data structure
Time Complexity: O(n)
Space Complexity: O(n)
*/

#include<iostream>
#include<string>
#include<stack>
using namespace std;

//Function to remove spaces from string and return trimmed string.
string removeSpaces(string &s){
	int n = s.length();
	string trimmed;

	for(int i = 0; i < n; i++){
		if(s[i] != ' '){
			trimmed.push_back(s[i]);
		}
	}
	return trimmed;
}

//In Expression containing only '*','/','+' and '-' '*' and '/' have the highest precedence followed by '+' and '-'
int precedence(char c){
	if(c == '*' || c == '/'){
		return 3;
	}
	else if(c == '+' || c == '-'){
		return 2;
	}
	else{
		return 1;
	}
}

//calculate function is used to calculate a value given two operandsand one operator
int calculate(int num1, int num2, char symbol){
	if(symbol == '*'){
		return num1 * num2;
	}
	else if(symbol == '/'){
		return num1 / num2;
	}
	else if(symbol == '+'){
		return num1 + num2;
	}
	else if(symbol == '-'){
		return num1 - num2;
	}
	return -1;
}

//Two stacks are used. 'values' stack is used to store the operands
//'operators' stack is used to hold the operators
int evaluate(string token){
	stack<int>values;
	stack<char>operators;
	int i;
	
	//get length of given expression
	int n = token.length();
	
	for(i = 0; i < n; i++){
		if(isdigit(token[i])){
			int value = 0;
			
			//there may be more than one digit number e.g(48+5) '48' has 2 digits
			while(i<n && isdigit(token[i])){
				value = value * 10 + (token[i] - '0');
				i++;
			}
			
			values.push(value);
			i--;
	
		}

		//if opening paranthesis is encontered push it in 'operators' stack
		else if(token[i] == '('){
			operators.push('(');
		}

		//If a closing paranthesis is encountered continue to evaluate the expression 
		//until an opening paranthesis is encountered
		else if(token[i] == ')'){
			while(!operators.empty() && operators.top()!='('){
				
				int val2 = values.top();
				values.pop();

				int val1 = values.top();
				values.pop();

				//get the operator
				char symbol = operators.top();
				operators.pop();

				//calculate value 
				int calculated_value = calculate(val1, val2, symbol);

				values.push(calculated_value);
			}

			operators.pop();
		}

		//operator encountered
		else{
			//if 'operators' stack is empty simply push the operator
			if(operators.empty()){
				operators.push(token[i]);
			}
			else{
				//check precedence
				if(precedence(token[i]) > precedence(operators.top())){
					operators.push(token[i]);
				}
				//if precedence of current symbol is less than top of operator stack 
				//then evaluate expression
				else{
					while(!operators.empty() && (precedence(token[i]) <= precedence(operators.top())) ){

						int val2 = values.top();
						values.pop();
						
						int val1 = values.top();
						values.pop();
						
						char symbol = operators.top();
						operators.pop();
						
						int calculated_value = calculate(val1,val2,symbol);
						
						values.push(calculated_value);
					}
					operators.push(token[i]);
				}
			}
		}
	}
	
	//Expression is parsed now, evaluate remaining values
	while(!operators.empty()){
		int val2 = values.top();
		values.pop();

		int val1 = values.top();
		values.pop();
		
		char symbol = operators.top();
		operators.pop();
		
		int calculated_value = calculate(val1,val2,symbol);
		
		values.push(calculated_value);
	}
	
	//Evaluated expression value will be at the top of 'values' stack
	return values.top();
}

int main(){
	string s;
	getline(cin,s);
	string trimmed = removeSpaces(s);
	cout<<evaluate(trimmed)<<endl;
	return 0;
}

/*
Input:

((2+4)*2)/(2+4)

Output:

2

Input:

((7 * 3) + 2)/(1+2)

Output:
7

*/


<|start_filename|>C/math/strong_number.c<|end_filename|>
/*
 C Program to check whether a given number is Strong number or not.
 Strong number is a special number whose sum of factorial of digits is equal to the original number.
Eg: 145 is strong number. Since, 1! + 4! + 5! = 145
*/

#include <stdio.h>

int factorial (int num)
{
  int i = 0;
  int fact = 1;
  for (i = 1; i <= num; i++)
    {
      fact = fact * i;
    }
  return fact;
}

int main ()
{
  int sum = 0;
  int lastDigit, number;
  printf ("Enter the number to be checked\n");
  scanf ("%d", &number);
  int originalNumber = number;
  while (number > 0)
    {
      lastDigit = number % 10;
      sum = sum + factorial (lastDigit);
      number = number / 10;
    }
  if (sum == originalNumber)
    {
      printf ("Strong number!");
    }
  else
    {
      printf ("Not a strong number!");
    }
  return 0;
}

/*
Sample Input-Output:
Example 1-
Enter the number to be checked
145
Strong number!
Example 2-
Enter the number to be checked
456
Not a strong number!
*/


<|start_filename|>Java/cp/Main.java<|end_filename|>
import java.util.*;
class Wrapping_letter {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the target character");
        char ch = sc.nextLine().charAt(0); //target character
        List < Character > arr = new ArrayList < > ();
        System.out.println("Enter the letters");
        String s = sc.nextLine();
        for (int i = 0; i < s.length(); i++)
            arr.add((s.charAt(i)));
        arr.add((ch));
        Collections.sort(arr);
        int ind = arr.indexOf(ch);
        System.out.print("The closest letter : ");
        if (ind == (arr.size() - 1))
            System.out.println((arr.get(0)));
        else
            System.out.println((arr.get(ind + 1)));
    }

}

/*
Sample input and output:
Enter the target character
a
Enter the letters
cdf
The closest letter : c
Enter the target character
z
Enter the letters
abc
The closest letter : a

Time Complexity: O(n)
Space Complexity: O(1)
*/


<|start_filename|>C/other/remove_outermost_parentheses.c<|end_filename|>
//algorithm for removing remove outermost parantheses in O(n) time complexity and O(1) space complexity

#include <stdio.h>

char * remove_outer_parantheses(char * S)
{
    int count = 0;
    int stack = 0;
    char *ans = S;
    char c; 
    while (c = *S++)
    {
        if (c == ')') 
        {
            --stack;
        }
        if (stack > 0) 
        {
            ans[count++] = c;
        }
        if (c == '(') 
        {
            ++stack;
        }
            
    }
    ans[count] = '\0';
    return ans;
}

int main()
{   //taking input from the user
    char s[1000];
    printf(" Enter the string\n ");
    scanf(" %s ",s);
    //printing result
    printf("The final string is : %s\n ",remove_outer_parantheses(s));
    return 0;
}

/*
Sample Input 1:
Input: "(()())(())"
Output: The final string is : ()()()
  
Sample Input 2:
Input: "(())()"
Output: The final string is : ()
*/

<|start_filename|>C-Plus-Plus/other/Median_of_two_Sorted_arrays_of_equal_size.cpp<|end_filename|>
/* Find a Median of two Sorted arrays of equal size. */

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

/* Function to find Median of two Sorted array of equal size */
int solve()
{
    /* Input n1 = size of array 1
       Input n2 = size of array 2 */
    int n1,n2;
    cin >> n1 >> n2;

    int arr1[n1],arr2[n2];

    /* Input values in array 1 */
    for (int i = 0; i < n1; ++i)
    {
        cin >> arr1[i];
    }

    /* Input values in array 2 */
    for (int i = 0; i < n2; ++i)
    {
        cin >> arr2[i];
    }

    /* Create a vector */
    vector<int> v;

    /* Push array 1 element in vector */
    for (int i = 0; i < n1; ++i)
    {
        v.push_back(arr1[i]);
    }

    /* Push array 2 element in vector */
    for (int i = 0; i < n2; ++i)
    {
        v.push_back(arr2[i]);
    }

    /* Sort the given vector */
    sort(v.begin(), v.end());
    
    /* Find medina using this formula */
    int mid = (v[v.size()/2 - 1] + v[v.size()/2]) / 2;
    
    /* Return Calculated median */
    return mid;
}

int main()
{
    int Median = solve();

    cout << "Median is : " << Median <<endl;
    return 0;
}

/*
Test cases :
    
    Input 1 :
        5 5
        1 12 15 26 38
        2 13 17 30 45
        

    Output 1 :

        Median is : 16

    Input 2 :

        5 5
        1 2 3 4 5
        6 7 8 9 10
    
    Output 2 :
    
        Median is : 5
    
    Time complexity: O(nlogn)
    Space Complexity: O(n)
*/


<|start_filename|>Java/ds/Trie_with_Hashmap.java<|end_filename|>
/*  Trie is also called as 'Prefix Tree'. It is a tree data structure which is commonly used to store the strings/words. 
    The popoular applications of this data stucture are autocomplete and spellcheck.

    Problem Statement: 
    Designing a data structure which supports addition of new words and finds if a string matches any previously added string.
        
    Solution:
    1. Define a TrieNode class using a HashMap.
    2. Initialization of root node in Trie Class.
    3. void insert(String word) takes word from user and adds into the Trie.
    4. boolean search(String word) checks if the word entered by user matches to the previously added strings.
*/

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

//Class to define Trie node operations
class Trie{
    private TrieNode root;
    public Trie(){
        root = new TrieNode(false);
    }
    //Insertion of word into Trie
    public void insert(String word){
        TrieNode currentnode = root;
        for(char c :word.toCharArray()){
            if(currentnode!=null && !currentnode.nodes.containsKey(c)){
                TrieNode node = new TrieNode(false);
                currentnode.nodes.put(c, node);
            }
            currentnode.nodes.get(c);
        }
        currentnode.isEnd = true;
    }

    //Searching word in a Trie
    public boolean search(String word){
        TrieNode currentnode = root;
        for(char c : word.toCharArray()){
            if(currentnode!=null && currentnode.nodes.containsKey(c)){
                currentnode.nodes.get(c);
            } else{
                return false;
            }
        }
        return currentnode.isEnd;
    }

    //Creation of node using Hashmap (stores elements in key/value pairs).
    class TrieNode{
        Map<Character,TrieNode> nodes = new HashMap<>();
        boolean isEnd = false;
        TrieNode(boolean isEnd){
            this.isEnd = isEnd;
        }
    }
}

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

        Trie head = new Trie();
        Scanner scan = new Scanner(System.in);       
        char ch;
        System.out.println("\nInsert and Search Operations on Trie");
        System.out.println("--------------------------------------");
        do  {  
            System.out.println("1. insert ");
            System.out.println("2. search");
            int choice = scan.nextInt();            
            switch (choice){
            case 1: 
                System.out.print("Enter string to insert : ");
                head.insert( scan.next() );                     
                break;                          
            case 2: 
                //Search function returns 'true' if string is present in Trie
                System.out.print("Enter string to search : ");
                System.out.println("Search result : "+ head.search( scan.next() ));
                break;                                          
            default: 
                System.out.println("Invalid choice \n ");
                break;   
            }
            System.out.print("\nDo you want to continue (Type y or n) : ");
            ch = scan.next().charAt(0);                                    
        }while (ch == 'Y'|| ch == 'y');               
    }  
}
/*  
*       Insert and Search Operations on Trie
*       --------------------------------------
*       1. insert
*       2. search
*       1
*       Enter string to insert : init
*       
*       Do you want to continue (Type y or n) : y
*       1. insert 
*       2. search
*       1
*       Enter string to insert : initial
*
*       Do you want to continue (Type y or n) : y
*       1. insert 
*       2. search
*       1
*       Enter string to insert : initially
*
*       Do you want to continue (Type y or n) : y
*       1. insert
*       2. search
*       2
*       Enter string to search : initial
*       Search result : true
*
*       Do you want to continue (Type y or n) : y
*       1. insert
*       2. search
*       2
*       Enter string to search : initiate
*       Search result : false
*
*       Do you want to continue (Type y or n) : n
*       -------------------------------------------
*       Time complexity:  O(M)      ...M is maximum length of string
*       Space Complexity: O(N*M*C)  ...N is number of strings and C is char size 
*/


<|start_filename|>C-Plus-Plus/ds/BST_to_Greater_Sum_Tree.cpp<|end_filename|>
/*
Transforms given BST into greater sum tree (GST) where each node contains sum of all nodes greater than that node.
*/

#include<iostream>
using namespace std;

struct BST
{
	int a,count = 0; 
	BST *left = NULL;
	BST *right = NULL;
};

//points to the root node
BST *start = NULL; 

//function to convert array into Binary Search Tree with shortest height
BST *arr_to_BST(int arr[20], int beg, int end) 
{
	BST *ptr;
	
	if(beg <= end)
	{
		ptr = new BST;
		ptr->left = NULL;
		ptr->right = NULL;
		ptr->a = arr[(beg+end)/2];
		int mid = beg + ((end - beg) / 2);
		ptr->left = arr_to_BST(arr,beg,mid-1);
		ptr->right = arr_to_BST(arr,mid+1,end);	
		return ptr;
	}
	else
		return NULL;
}

//function to print Binary Search Tree
void Display_BST(BST *ptr) 
{
	if(ptr == NULL)
		return;
			
	if(ptr->left != NULL)
		Display_BST(ptr->left);
	
	cout<<"\t"<<ptr->a;

	if(ptr->right != NULL)
		Display_BST(ptr->right);
}

//function to convert BST to Greater Sum Tree
int BST_to_GST(BST *ptr=start, int sum = 0)
{
	int temp = 0;
	if(ptr != NULL)
	{
		sum = BST_to_GST(ptr->right,sum);
		temp = ptr->a;
		ptr->a = sum;
		sum = BST_to_GST(ptr->left,sum+temp);
	}
	else
		return sum;	
}

int main()
{
	int n, arr[20];
	cout<<"\nEnter number of elements:"; 
	cin>>n;
	cout<<"\nEnter sorted array:";
	for(int i = 0 ; i < n ; i++)
	{
		cin>>arr[i];
	}
	start = arr_to_BST(arr, 0, n-1);	
	cout<<"\nBinary Search Tree before conversion";
	Display_BST(start);

	BST_to_GST(start);

	cout<<"\nBinary Search Tree after conversion";
	Display_BST(start);

  	return 0;
}

/*
Time Complexity:
T(n)  = O(k) + 2 T(n/2) 
Space Complexity:
O(n)
Sample I/O:
Enter number of elements:6

Enter sorted array:1 2 3 4 5 6

Binary Search Tree before conversion    1       2       3       4       5       6
Binary Search Tree after conversion     20      18      15      11      6       0
*/


<|start_filename|>C-Plus-Plus/cp/Tug_of_water.cpp<|end_filename|>
/*
Given a set of n integers, divide the set in two subsets of n/2 sizes each such that the difference of the sum of two subsets is as minimum as possible. 
If n is even, then sizes of two subsets must be strictly n/2 and 
if n is odd, then size of one subset must be (n-1)/2 and size of other subset must be (n+1)/2.

 A C++ PROGRAM TO FIND TUG OF WATER USING BACKTRACKING
*/

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

void traverse(int* arr, int i, int n, int no_of_selected, int sum, int& diff, bool* take, vector<int>& result, vector<int> current, int current_sum)
{
    //if the current position is greater than or equals to n
    if (i >= n)
        return;
    /* if the value of difference is greater than
       Sum/2-current sum of the elements of Subset no.1 */
    
	if ((diff > abs(sum / 2 - current_sum)) && (no_of_selected == (n + 1) / 2 || no_of_selected == (n - 1) / 2)) 
	{
        diff = abs(sum / 2 - current_sum);
        //store the subset no. 1
        result = current;
    }
    //taking the elemets after the current element one by one
    for (int j = i; j < n; j++) 
	{
        take[j] = true;
        current.push_back(arr[j]);
        traverse(arr, j + 1, n, no_of_selected + 1, sum, diff, take, result, current, current_sum + arr[j]);
        current.pop_back();
        take[j] = false;
    }
}
void find(int* arr, int n)
{
    //array to distinguished the elements those are in subset no. 1
    bool take[n];
    int sum = 0;
    for (int i = 0; i < n; i++) 
	{
        sum += arr[i];
        take[i] = false;
    }
    int diff = INT_MAX;
    int no_of_selected = 0;
    vector<int> result;
    vector<int> current;
    int current_sum = 0;
    int i = 0;
    traverse(arr, i, n, no_of_selected, sum, diff, take, result, current, current_sum);
    set<int> s;
    //elements those are in subset no.1
    cout << "Set1 : { ";
    for (int j = 0; j < result.size(); j++) 
	{
        cout << result[j] << " ";
        s.insert(result[j]);
    }
    cout << "}" << endl;
    //elements those are in subset no.2
    cout << "Set2 : { ";
    for (int j = 0; j < n; j++) 
	{
        if (s.find(arr[j]) == s.end()) 
		{
            cout << arr[j] << " ";
        }
    }
    cout << "}" << endl;
}
int main()
{
    int t;
    cin >> t;
    while (t--) 
	{
        int n;
        cout << "Enter the value of n : ";
        cin >> n;
        int arr[n];
        cout << "Enter the values: ";
        //taking the set elements
        for (int i = 0; i < n; i++) 
		{
            cin >> arr[i];
        }
        find(arr, n);
    }
    return 0;
}
/*
TIME COMPLEXITY OF TUG OF WAR IS O(N^2) and SPACE COMPLEXITY IS O(1)  
T=3
N=3
1 2 3
Output:  set1: {1, 2} set2: {3}
N=4
1 2 3 4
Output: set1: {1, 4} set2: {2, 3}
N=10
1 4 8 6 -7 -10 87 54 16 100
Output: set1: {{ 4, -7, -10, 87, 54 } set2: {1, 8, 6, 16, 100 }
*/
   


<|start_filename|>C-Plus-Plus/cp/removeMinParantheses.cpp<|end_filename|>
/* Problem Statement: 
Given a string of '(' , ')' and lowercase english characters.
The task is to remove the minimum number of parentheses so that the resulting parentheses string is valid.
A parentheses string is valid if and only if:
1.It is the empty string, contains only lowercase characters, or
2.It can be written as AB (A concatenated with B), where A and B are valid strings, or
3.It can be written as (A), where A is a valid string. */

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

//checks if character a and b together make () or not
bool matching(char a, char b){ 
    if(a == '(' && b == ')'){
        return true;
    }
    return false;
}

string removeMin(string s){
    int n = s.size();
    //to store character and its index together
    stack<pair<char, int> > st;  
    for(int i = 0; i < n; i++){
        if(s[i] == '('){
            st.push({s[i], i});
        }
        else if(s[i] == ')'){
            if(st.empty() || !matching(st.top().first, s[i])){
                st.push({s[i], i});
            }
            else{
                st.pop();
            }
        }
    }
    while(!st.empty()){
        int idx = st.top().second;
        //remove all the elements from the string that were making the string invalid
        s.erase(s.begin() + idx); 
        st.pop();
    }
    return s;
}

int main() {
    string s;
    cin >> s;
    cout << removeMin(s);
    return 0;
}

/* Examples: 
1.  Input: "he((l)l)o)"
    Output: "he((l)l)o"
2.  Input: ")))((("
    Output: "" */


<|start_filename|>C-Plus-Plus/other/trappingRainwater.cpp<|end_filename|>
/* C++ program to solve Trapping Rainwater problem.An array of non-negative integers are given which
represent an elevation height each of width 1, the
goal is to compute total water trapped after raining*/

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

class Trapwater {
public:
    int trap(vector<int>& height){
    	int n = height.size();
    	int left = 0 , right = n-1;
    	// Initialize output
    	int res = 0;
    	// Maximum element on left and right
        int max_left = 0, max_right = 0;

        while(left <= right){

        	if(height[left] <= height[right]){

        		if(height[left] >= max_left)
        			// Update max in left
        			max_left = height[left];
        		else
        			// Water trapped on current index is max - current height
        			res += max_left - height[left];
        		left++;
        	}
        	else{

        		if(height[right] >= max_right)
        			// Update max in right
        			max_right = height[right];
        		else
        			res += max_right - height[right];
        		right--;
        	}
        	return res;
    }
};

int main(){
	int n,h;
	vector<int> height;
	// Taking input of number of buildings
	cin >> n;
	while(n--){
		// input the height of each building
		cin >> val;
		height.push_back(h);
	}
	Trapwater t;
	int result = t.trap(height);
	// display the amount of water trapped
	cout << result;
}

/*

Input -

n = 5
arr[n] = {2,3,1,0,5}

Sample Output -

5

Explanation -

Two units of water can be stored at index 2 and 
3 units at index 3

Time Complexity : O(n)
Space Complexity : O(1) 

*/


<|start_filename|>Java/dp/MaximumSumRectangle.java<|end_filename|>
import java.util.Scanner;

public class MaximumSumRectangle {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter number of rows and columns:");
        int r = scanner.nextInt();
        int c = scanner.nextInt();
        int[][] matrix = new int[r][c];
        System.out.println("Enter elements of the matrix:");
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                matrix[i][j] = scanner.nextInt();
            }
        }

        System.out.println("Maximum sum is:" + maxSum(matrix));
    }

    private static int maxSum(int[][] matrix) {

        int r = matrix.length;
        int c = matrix[0].length;
        int[][] prevSum = new int[r + 1][c];

        for(int i = 0; i < r; i++) {
            for(int j = 0; j < c; j++) {
                prevSum[i + 1][j] = prevSum[i][j] + matrix[i][j];
            }
        }

        // solving with the method of Kadane's Algorithm
        int maxSum = -1;
        int minSum = Integer.MIN_VALUE;
        int negRow = 0, negCol = 0;
        int rStart = 0, rEnd = 0, cStart = 0, cEnd = 0;
        for(int rowBegin = 0; rowBegin < r; rowBegin++) {
            for(int row = rowBegin; row < r; row++){
                int sum = 0;
                int curColStart = 0;
                for(int col = 0; col < c; col++) {
                    sum += prevSum[row + 1][col] - prevSum[rowBegin][col];
                    if(sum < 0) {
                        if(minSum < sum) {
                            minSum = sum;
                            negRow = row;
                            negCol = col;
                        }
                        sum = 0;
                        curColStart = col + 1;
                    }
                    else if(maxSum < sum) {
                        maxSum = sum;
                        rStart = rowBegin;
                        rEnd = row;
                        cStart = curColStart;
                        cEnd = col;
                    }
                }
            }
        }

        return maxSum == -1 ? minSum : maxSum;
    }
}
/*
* Sample input/output:
* Enter number of rows and columns:
* 4 5
* Enter elements of the matrix:
* 1 2 -1 -4 -20
* -8 -3 4 2 1
* 3 8 10 1 3
* -4 -1 1 7 -6
* Maximum sum is:29
*
* Time complexity: O(n^3)
*/


<|start_filename|>C-Plus-Plus/ds/Inorder.cpp<|end_filename|>
#include<iostream>
using namespace std;

//creating structure for node
struct Node {
    char data;
    struct Node *left;
    struct Node *right;
};

// Insert Function
Node* Insert(Node *root, char data) {
    //if root have no value
    //then create a node and insert values
    if (root == NULL) {
        root = new Node();
        root->data = data;
        root->left = root->right = NULL;
    }
    //check if data is less than root value
    //then insert into left subtree
    else if (data <= root->data)
        root->left = Insert(root->left, data);
    //check if data is less than root value
    //then insert into right subtree
    else
        root->right = Insert(root->right, data);
    return root;
}

//Inorder Function
void Inorder(Node *root) {
    // if tree is empty then return
    if (root == NULL) return;
    //visit left subtree
    Inorder(root->left);
    //Print data
    printf("%c ", root->data);
    //Visit right subtree
    Inorder(root->right);
}
//Main Function began
int main() {
    Node* root = NULL;
    //input values
    root = Insert(root, 'M');
    root = Insert(root, 'B');
    root = Insert(root, 'Q');
    root = Insert(root, 'Z');
    root = Insert(root, 'A');
    root = Insert(root, 'C');
    //Print Nodes in Preorder.
    cout << "\tOUTPUT\n";
    cout << "In-order traversal : ";
    Inorder(root);
    cout << "\n";
}
//Main Ends

/*
Sample Input Output:

Input -> M B Q Z A C

OUTPUT:
Postorder traversal : A B C M Q Z

Time Complexity: O(n)
*/


<|start_filename|>C-Plus-Plus/cp/Knuth_Morris_Pratt.cpp<|end_filename|>
// https://en.wikipedia.org/wiki/Knuth–Morris–Pratt_algorithm

// Time Complexity:-O(N+M).
// Space Complexity:-O(M).

#include <iostream>
#include <vector>
#include <string>

using namespace std;

// Fills lps for given patttern pat[0..M-1]
void computeLPS(string &patt, vector<int> &lps)
{
    int M = patt.size();
    // length of the previous longest prefix suffix
    int len = 0;

    lps[0] = 0;

    int i = 1;
    // the loop calculates lps[i] for i = 1 to M-1
    while (i < M)
    {
        if (patt[i] == patt[len])
        {
            len++;
            lps[i] = len;
            i++;
        }
        else
        {
            if (len != 0)
            {
                len = lps[len - 1];
            }
            else
            {
                lps[i] = 0;
                i++;
            }
        }
    }
}


// Prints occurrences of patt in text
void searchByKMP(string &text, string &patt)
{
    int N = text.size(), M = patt.size();

    // create lps vector that will hold the longest prefix suffix values for pattern
    vector<int> lps(M);

    // Preprocess the pattern(calculate lps vector)
    computeLPS(patt, lps);

    int i = 0, j = 0;

    while (i < N)
    {
        if (patt[j] == text[i])
        {
            i++;
            j++;
        }

        if (j == M)
        {
            cout << "Pattern found at index " << i - j << endl;
            j = lps[j - 1];
        }
        else if (i < N && patt[j] != text[i])
        {
            if (j == 0)
                i++;
            else
                j = lps[j - 1];
        }
    }
}

int main()
{
    string text = "", patt = "";

    int n;

    cout << "Enter Number of test Cases:";
    cin >> n;

    while (n)
    {
        cout << endl;
        cout << "Enter the text string:";
        cin >> text;

        cout << endl << "Enter the pattern string:";
        cin >> patt;

        searchByKMP(text, patt);
        n--;
        text.clear();
        patt.clear();
    }

    return 0;
}


<|start_filename|>Java/dp/BinarySearchTreeCount.java<|end_filename|>
import java.util.InputMismatchException;
import java.util.Scanner;

/**
 * <h1>Binary Tress with N nodes</h1> <b>Purpose</b>
 * <p>
 * Total Number of Binary Tress we can create with N number of nodes
 * </p>
 * <b>Description</b>
 * <p>
 * class BinarySearchTreeCount program is used to implement a program to find a
 * count of the total number of different binary search trees that we can make
 * with N nodes.
 * </p>
 * <p>
 * There are four approaches used to implement the given problem:
 * </p>
 * <ul>
 * <li>Using Dynamic Programming</li>
 * <li>Using Recursion</li>
 * <li>Using the Binomial Coefficient</li>
 * <li>Using a Custom made Formulae</li>
 * </ul>
 */
public class BinarySearchTreeCount {

    /**
     * This is a private method used to calculate the Binomial Coefficient
     * 
     * @param numberOne This is a first Integer parameter to
     *                  calculateBinomialCoefficient method.
     * @param numberTwo This is a second Integer paramter to
     *                  calculateBinomialCoefficient method.
     * @return Long This returns Binomial Coefficient of numberOne and numberTwo.
     */
    private Long calculateBinomialCoefficient(Integer numberOne, Integer numberTwo) {

        // Initialized coefficient to 1
        Long coefficient = 1L;

        /*
         * If substraction of numberOne and numberTwo is smaller than numberTwo then
         * numberTwo is assigned a new value which is the substraction of numberOne and
         * numberTwo.
         */
        if (numberTwo > (numberOne - numberTwo)) {
            numberTwo = numberOne - numberTwo;
        }

        /*
         * Calculating value of coefficient iteratively
         */
        for (int i = 0; i < numberTwo; i++) {
            coefficient *= (numberOne - i);
            coefficient /= (i + 1);
        }
        return coefficient;
    }

    /**
     * This is a public method used to calculate the total count of Binary Search
     * Trees which can be created with N nodes using Binomial Coefficient method.
     * <b>Formulae</b>
     * <p>
     * 1/(n+1) * (2n!/n!(2n-n)!)
     * </p>
     * 
     * <p>
     * <b>Time Complexity</b> O(n)
     * </p>
     * <p>
     * <b>Space Complexity</b> O(1)
     * </p>
     * 
     * @param totalNumberOfNodes This is used to store the value to the total number
     *                           of nodes present.
     * @return Long This returns the total number of Binary Search Trees which can
     *         be created with totalNumberOfNodes nodes
     */
    public Long getCountByBinomialCoefficient(Byte totalNumberOfNodes) {

        /*
         * Calls calculateBinomialCoefficient method to get the Binomial Coefficient of
         * 2 X totalNumberOfNodes and totalNumberOfNodes
         */
        Long binomialNumber = calculateBinomialCoefficient(2 * totalNumberOfNodes, 1 * totalNumberOfNodes);
        /*
         * Divides the binomial coefficient by sum of totalNumberOfNodes and 1 to
         * statisfy the formulae
         */
        Long binaryTreeNodeCount = binomialNumber / (totalNumberOfNodes + 1);
        // Returns the final count
        return binaryTreeNodeCount;
    }

    /**
     * This is a public method used to calculate the total count of Binary Search
     * Trees which can be created with N nodes using Recursive method. *
     * 
     * <p>
     * <b>Time Complexity</b> O(n)
     * </p>
     * 
     * @param totalNumberOfNodes This is used to store the value to the total number
     *                           of nodes present.
     * @return Long This returns the total number of Binary Search Trees which can
     *         be created with totalNumberOfNodes nodes
     */
    public Long getCountByRecursion(Byte totalNumberOfNodes) {

        Long binaryTreeNodeCount = 0L;
        /*
         * If totalNumberOfNodes comes down to 1 or less 1 is returned as the total
         * number of trees that could be created
         */
        if (totalNumberOfNodes <= 1) {
            return 1L;
        }
        for (int i = 0; i < totalNumberOfNodes; i++) {
            binaryTreeNodeCount += getCountByRecursion((byte) i)
                    * getCountByRecursion((byte) (totalNumberOfNodes - i - 1));
        }
        // Returns the final count
        return binaryTreeNodeCount;
    }

    /**
     * This is a public method used to calculate the total count of Binary Search
     * Trees which can be created with N nodes using a custom made formulae.
     * <p>
     * <b>Advantages</b>
     * </p>
     * <p>
     * We don't need to store any previous values or factorial in this solution,
     * which reduces it's time and space complexity
     * </p>
     * <b>Disadvantages</b>
     * <p>
     * The formulae is not functional in 100% test cases, it works best between
     * values 2-7
     * </p>
     * <b>Formulae</b>
     * <p>
     * ROUND( 2^((n-1)+(((n-1)-1)/2)-((n+1)-3)+(8*9^(n-6)) )
     * </p>
     * 
     * @param totalNumberOfNodes This is used to store the value to the total number
     *                           of nodes present.
     * @return Long This returns the total number of Binary Search Trees which can
     *         be created with totalNumberOfNodes nodes
     */
    public Long getCountByFormulae(Byte totalNumberOfNodes) {
        /*
         * If there's a occurance of 0 or 1 it directly returns 1
         */
        if (totalNumberOfNodes == 0 || totalNumberOfNodes == 1) {
            return 1L;
        }
        /*
         * Calculates the power of 2
         */
        Double powerCount = (totalNumberOfNodes - 1) + (((totalNumberOfNodes - 1) - 1) / 2.0);
        /*
         * Calculates the final value statisfying the given formulae
         */
        Long binaryTreeCount = Math.round(Math.pow(2, (powerCount)) - ((totalNumberOfNodes + 1) - 3)
                + (8 * Math.round(Math.pow(9, totalNumberOfNodes - 6))));
        // Returns the final count
        return binaryTreeCount;
    }

    /**
     * This is a public method used to calculate the total count of Binary Search
     * Trees which can be created with N nodes using Dynamic Programming. *
     * 
     * <p>
     * <b>Time Complexity</b> O(n^2)
     * </p>
     * 
     * @param totalNumberOfNodes This is used to store the value to the total number
     *                           of nodes present.
     * @return Long This returns the total number of Binary Search Trees which can
     *         be created with totalNumberOfNodes nodes
     */
    public Long getCountByDynamicProgramming(Byte totalNumberOfNodes) {
        /*
         * If there's a occurance of 0 or 1 it directly returns 1
         */
        if (totalNumberOfNodes == 0 || totalNumberOfNodes == 1) {
            return 1L;
        }

        /*
         * An array is used to store previous occuring values
         */
        Long[] binaryTreeNodeCount = new Long[totalNumberOfNodes + 1];

        /*
         * binaryTreeNodeCount[] is initialized with 0 as it's initial value
         */
        for (int i = 0; i <= totalNumberOfNodes; i++) {
            binaryTreeNodeCount[i] = 0L;
        }

        /*
         * Index 0 and 1 are assigned value as 1
         */
        binaryTreeNodeCount[0] = 1L;
        binaryTreeNodeCount[1] = 1L;

        /*
         * Iteratively according to the previous values the current value is calculated
         */
        for (int i = 2; i <= totalNumberOfNodes; i++) {
            for (int j = 0; j < i; j++) {
                binaryTreeNodeCount[i] += binaryTreeNodeCount[j] * binaryTreeNodeCount[i - j - 1];
            }
        }

        return binaryTreeNodeCount[totalNumberOfNodes];
    }

    /**
     * This is the main method which makes use of the following methods:
     * 
     * <ul>
     * <li>getCountByDynamicProgramming</li>
     * <li>getCountByRecursion</li>
     * <li>getCountByBinomialCoefficient</li>
     * <li>getCountByFormulae</li>
     * </ul>
     * 
     * And uses the following objects of types:
     * 
     * <ul>
     * <li>java.util.Scanner</li>
     * <li>java.lang.Byte</li>
     * <li>java.lang.Long</li>
     * <li>BinarySearchTreeCount</li>
     * </ul>
     * 
     * @param args for getting command line input [NOT USED].
     * @exception InputMismatchException On input error.
     */
    public static void main(String[] args) {
        // Created an object of Scanner class for asking for user input.
        Scanner scan = new Scanner(System.in);
        try // Openning try block
        {
            // Created an object of BinarySearchTreeCount for accessing it's methods
            BinarySearchTreeCount binarySearchTreeCount = new BinarySearchTreeCount();

            // Asking for user input for entering the total number of nodes
            System.out.println("Enter Total Number Of Nodes: ");
            // The user input is captured in totalNumberOfNodes
            Byte totalNumberOfNodes = scan.nextByte();

            // Calling method to calculate the total using Dynamic Programming
            Long binaryTreeCountByDynamicProgramming = binarySearchTreeCount
                    .getCountByDynamicProgramming(totalNumberOfNodes);

            // Calling method to calculate the total using Recursion
            Long binaryTreeCountByRecursion = binarySearchTreeCount.getCountByRecursion(totalNumberOfNodes);

            // Calling method to calculate the total using Binomial Coefficient
            Long binaryTreeCountByBinomialCoefficient = binarySearchTreeCount
                    .getCountByBinomialCoefficient(totalNumberOfNodes);

            // Printing the respective values
            System.out.println("COUNT By Binomial Coeffient: " + binaryTreeCountByBinomialCoefficient);
            System.out.println("COUNT by Dynamic Programming: " + binaryTreeCountByDynamicProgramming);
            System.out.println("COUNT by Recursion: " + binaryTreeCountByRecursion);

            /*
             * If totalNumberOfNodes is between 0 to 7 then it will call the method to
             * calculate the total using custom formulae, as for now the formulae works well
             * when values are under or equal to 7 and above than 0, the formulae should not
             * be used to calculate values greater than 7 for now.
             */
            if (totalNumberOfNodes >= 0 && totalNumberOfNodes <= 7) {
                // Calling method to calculate the total using Custom Formulae
                Long binaryTreeCountByFormulae = binarySearchTreeCount.getCountByFormulae(totalNumberOfNodes);
                // Printing the respective value
                System.out.println("COUNT by Formulae: " + binaryTreeCountByFormulae);
            }
            // If value of totalNumberOfNodes is entered below 0, an expection is raised
            if (totalNumberOfNodes < 0) {
                throw new InputMismatchException();
            }
        } // Closing try block
        catch (InputMismatchException inputMismatchException) {
            System.out.println("Please Enter values between 0 - 127");
        } finally {
            // Closing the Scanner object scan
            scan.close();
        }
    }
}

<|start_filename|>Java/cp/Stack_using_Queue.java<|end_filename|>

/* Java Program to implement a stack using two queue */

import java.util.*; 
  
class Stack_using_Queue { 
  
    static class Stack { 
        // Two inbuilt queues 
        static Queue<Integer> q1 = new LinkedList<Integer>(); 
        static Queue<Integer> q2 = new LinkedList<Integer>(); 
  
        // To maintain current number of elements 
        static int size; 
  
        Stack() 
        { 
            size = 0; 
        } 
  
        static void push(int x) 
        { 
           size++; 
  
            // Push x first in empty q2 
            q2.add(x); 
  
            // Push all the remaining 
            // elements in q1 to q2. 
            while (!q1.isEmpty()) { 
                q2.add(q1.peek()); 
                q1.remove(); 
            } 
  
            // swap the names of two queues 
            Queue<Integer> q = q1; 
            q1 = q2; 
            q2 = q; 
        } 
  
        static void pop() 
        { 
  
            // if no elements are there in q1 
            if (q1.isEmpty()) 
                return; 
            q1.remove(); 
            size--; 
        } 
  
        static int top() 
        { 
            if (q1.isEmpty()) 
                return -1; 
            return q1.peek(); 
        } 
  
        static int size() 
        { 
            return size; 
        } 
    } 
  
    // driver code 
    public static void main(String[] args) 
    { 
        Scanner sc = new Scanner(System.in);
        Stack s = new Stack(); 

        System.out.println("Enter the limit");
        int n = sc.nextInt();
        //accepting input from user
        for(int i = 1; i <= n; i++)  
          s.push(i); 
        
        //printing the output
        for(int i = 1; i <= n; i++){
           System.out.println(s.top()); 
           s.pop(); 
        }
  
    } 
} 

/* Time Complexity : O(n)
   Space Complexity : O(n)

   Input
   5

   Output
    5
    4
    3
    2
    1
*/


<|start_filename|>Java/other/SubSequences.java<|end_filename|>
import java.util.*;

class SubSequences {
    static void get_sequence(String str, String ans, int i) {
        // Base condition
        if (i == str.length()) {
            System.out.println("'" + ans + "'");
            return;
        }
        // Before character gets added to final
        get_sequence(str, ans, i + 1);
        // after character gets added to ans
        get_sequence(str, ans + str.charAt(i), i + 1);

    }

    public static void main(String arg[]) {
        Scanner sc = new Scanner(System.in);
        String str;
        System.out.println("Enter the string");
        str = sc.nextLine();

        System.out.println("All possible subsequences are:");
        get_sequence(str, "", 0);
    }
}


/*
output:
Enter the string
abcd
All possible subsequences are:
'' 'd' 'c' 'cd' 'b' 'bd' 'bc' 'bcd' 'a' 'ad' 'ac' 'acd' 'ab' 'abd' 'abc' 'abcd'

Time complexity : O(n^2)
space complexity : O(n)
*/


<|start_filename|>C-Plus-Plus/ds/Height_Of_Binary_Tree_Non_Recursive.cpp<|end_filename|>
/*

Introduction 
Given a Binary Tree , Find its height without using recursion.

Argument/Return Type
Input of total no.of nodes is taken
Input of key values of nodes of tree are taken in level order form 
Incase of a null node , -1 is taken as input
Function returns the height of the tree 

*/

//  Code / Solution

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

//Define Node as structure
struct Node 
{
    int key;
    Node* left;
    Node* right;
};
 
// Function to create a node with 'value' as the data stored in it. 
// Both the children of this new Node are initially null.
struct Node* newNode(int value)
{
    Node* n = new Node;
    n->key = value;
    n->left = NULL;
    n->right = NULL;
    return n;
}

// Function to build tree with given input
struct Node* createTree(vector<int>v)
{
    int n=v.size();
    if(n==0) 
      return NULL;
    vector<struct Node* >a(n);
    //Create a vector of individual nodes with given node values
    for(int i=0;i<n;i++)  
    {
        //If the data is -1 , create a null node
        if(v[i]==-1)  
          a[i] = NULL;
        else 
          a[i] = newNode(v[i]);
    }
    //Interlink all created nodes to create a tree
    //Use two pointers using int to store indexes
    //One to keep track of parent node and one for children nodes
    for(int i=0,j=1;j<n;i++) 
    {
        //If the parent node is NULL , advance children pointer twice
        if(!a[i])
        {
          j=j+2;
          continue;
        } 
        //Connect the two children nodes to parent node
        //First left and then right nodes
        a[i]->left = a[j++];
        if(j<n) 
          a[i]->right = a[j++];
    }
    return a[0];
}

//Function to find Height of Binary Tree without using recursion
int FindHeightNonRecursive(struct Node* root)
{
    //kepp counting levels , and finally return total no.of levels
    //Initialise level as 0
    int level=0;
    // If root is NULL , return 0 
    if (root == NULL)
        return level;

    // Create an queue
    queue<struct Node*> q;
    //Enqueue the root node and a null node to indicate a level is completed
    q.push(root);
    q.push(NULL);
 
    while (!q.empty()) 
    {
        //If we encounter a NULL node , it means a level is complete
        //Hence we increase level variable 
        //Enqueue a null node , if there are more nodes left to visit
        if(q.front()==NULL)
        {
            level++;
            q.pop();
            if(!q.empty())
            {
                //If there are more nodes in q , push a NULL node
                q.push(NULL);
            }
        }
        else
        {
            //Enqueue node's children , if they exist
            if(q.front()->left)
               q.push(q.front()->left);
            if(q.front()->right)
               q.push(q.front()->right);
            q.pop();
        }
    }
    return level;
}
 
// Driver code
int main()
{

    int n;
    cout<<"Enter total no.of nodes of the input Tree ( including NULL nodes ) : ";
    cin>>n;

    vector<int>v(n);
    cout<<"Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces"<<endl;
    for(int i=0;i<n;i++)
    {
        cin>>v[i]; //store the input values in a vector
    }

    //create the tree using input node values  
    struct Node* root=createTree(v); 

    //Call the function and print the result
    cout<<"Height of the given tree is "<<FindHeightNonRecursive(root);
    
    return 0; 
}
    
/*
Input:
0 <= node->key < 1000000000
if node is NULL , -1 is entered as it's key

Sample Test Case 1  
Input Binary Tree :                   

               10                                
           /         \                          
         11              11                    
     /       \        /   \               
    5       NULL    NULL   5             
   / \                    /  \            
  4 NULL                 NULL  4         


Input Format : 
Example :
Enter total no.of nodes of the input Tree ( including NULL nodes ) : 15
Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces
10 11 11 5 -1 -1 5 4 -1 -1 -1 -1 -1 -1 4

Output Format :
Example : ( Output to the above input example ) 
Height of the given tree is 4

Sample Test Case 2  
Input Binary Tree :                   

                  12                                
          /               \                          
         9                 17                    
     /       \          /      \               
    8       10         NULL    18                                


Input Format : 
Example :
Enter total no.of nodes of the input Tree ( including NULL nodes ) : 7
Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces
12 9 17 8 10 -1 18 

Output Format :
Example : ( Output to the above input example ) 
Height of the given tree is 3

Time/Space Complexity
Time Complexity : O(n) 
   Where n is the no.of nodes 
Space Complexity : O(n) 
   Where n is the no.of nodes
*/


<|start_filename|>C-Plus-Plus/ds/RED-BLACK-TREE.cpp<|end_filename|>
// Red Black Tree implementation in C++ (creation,insertion,traversal)

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

// structure of a node
struct Node {
	int data; 
	Node *parent; // pointer to the parent
	Node *left; // pointer to left child
	Node *right; // pointer to right child
	int color; // 1 -> Red, 0 -> Black
};

typedef Node *NodePtr;

// class RBTree implements the operations in Red Black Tree
class RBTree {
	NodePtr root;
	NodePtr TNULL;

	// initializes the nodes with appropirate values
	// all the pointers are pointing to the null pointer
	void initializeNULLNode(NodePtr node, NodePtr parent) {
		node->data = 0;
		node->parent = parent;
		node->left = nullptr;
		node->right = nullptr;
		node->color = 0;
	}

	void pre_Order(NodePtr node) {
		if (node != TNULL) {
			
 		string sColor = node->color?"RED":"BLACK";
		   cout<<node->data<<"("<<sColor<<")  ";
			pre_Order(node->left);
			pre_Order(node->right);
		} 
	}

	void in_Order(NodePtr node) {
		if (node != TNULL) {
			in_Order(node->left);
			string sColor = node->color?"RED":"BLACK";
		   cout<<node->data<<"("<<sColor<<")  ";
			in_Order(node->right);
		} 
	}

	void post_Order(NodePtr node) {
		if (node != TNULL) {
			post_Order(node->left);
			post_Order(node->right);
			string sColor = node->color?"RED":"BLACK";
		   cout<<node->data<<"("<<sColor<<")  ";
		} 
	}

	// fix the red-black tree
	void fixInsert(NodePtr k){
		NodePtr u;
		// when parent is red
		while (k->parent->color == 1) {
			if (k->parent == k->parent->parent->right) {
				u = k->parent->parent->left; // uncle
				if (u->color == 1) {
					// when uncle is also red
					u->color = 0;
					k->parent->color = 0;
					k->parent->parent->color = 1;
					k = k->parent->parent;
				} else {  
					if (k == k->parent->left) {
						k = k->parent;
						rightRotate(k);
					}
					
					k->parent->color = 0;
					k->parent->parent->color = 1;
					leftRotate(k->parent->parent);
				}
			} else {
				u = k->parent->parent->right; // uncle

				if (u->color == 1) {
					
					u->color = 0;
					k->parent->color = 0;
					k->parent->parent->color = 1;
					k = k->parent->parent;	
				} else {
					if (k == k->parent->right) {
						
						k = k->parent;
						leftRotate(k);
					}
					
					k->parent->color = 0;
					k->parent->parent->color = 1;
					rightRotate(k->parent->parent);
				}
			}
			if (k == root) {
				break;
			}
		}
		root->color = 0;
	}

public:
	RBTree() {
		TNULL = new Node;
		TNULL->color = 0;
		TNULL->left = nullptr;
		TNULL->right = nullptr;
		root = TNULL;
	}

	// Pre-Order traversal
	// Node->Left Subtree->Right Subtree
	void preorder() {
cout<<"PREORDER:- ";
		pre_Order(this->root);
		cout<<endl;
	}

	// In-Order traversal
	// Left Subtree -> Node -> Right Subtree
	void inorder() {
cout<<"INORDER:- ";
		in_Order(this->root);
		cout<<endl;
	}

	// Post-Order traversal
	// Left Subtree -> Right Subtree -> Node
	void postorder() {
cout<<"POSTORDER:- ";
		post_Order(this->root);
		cout<<endl;
	}

	
	// rotate left at node x
	void leftRotate(NodePtr x) {
		NodePtr y = x->right;
		x->right = y->left;
		if (y->left != TNULL) {
			y->left->parent = x;
		}
		y->parent = x->parent;
		if (x->parent == nullptr) {
			this->root = y;
		} else if (x == x->parent->left) {
			x->parent->left = y;
		} else {
			x->parent->right = y;
		}
		y->left = x;
		x->parent = y;
	}

	// rotate right at node x
	void rightRotate(NodePtr x) {
		NodePtr y = x->left;
		x->left = y->right;
		if (y->right != TNULL) {
			y->right->parent = x;
		}
		y->parent = x->parent;
		if (x->parent == nullptr) {
			this->root = y;
		} else if (x == x->parent->right) {
			x->parent->right = y;
		} else {
			x->parent->left = y;
		}
		y->right = x;
		x->parent = y;
	}

	// insert the key to the tree
	// and adjust the tree accordingly
	void insert(int key) {
		
		NodePtr node = new Node;
		node->parent = nullptr;
		node->data = key;
		node->left = TNULL;
		node->right = TNULL;
		node->color = 1; // new node must be red

		NodePtr y = nullptr;
		NodePtr x = this->root;

		while (x != TNULL) {
			y = x;
			if (node->data < x->data) {
				x = x->left;
			} else {
				x = x->right;
			}
		}

		// y is parent of x
		node->parent = y;
		if (y == nullptr) {
			root = node;
		} else if (node->data < y->data) {
			y->left = node;
		} else {
			y->right = node;
		}

		// if new node is a root node, simply return
		if (node->parent == nullptr){
			node->color = 0;
			return;
		}

		// if the grandparent is null, simply return
		if (node->parent->parent == nullptr) {
			return;
		}

		// Fix the tree
		fixInsert(node);
	}

	NodePtr getRoot(){
		return this->root;
	}


};

int main() {
	RBTree tree;
int n,i,nod;
cout<<"total no. of nodes\n";
cin>>n;
cout<<"enter nodes\n";
for(i=0;i<n;i++){
	cin>>nod;
	tree.insert(nod);
}
tree.inorder();
tree.postorder();
tree.preorder();

	return 0;
}
/* output:
total no. of nodes
5
enter nodes
8
5
15
17
18
INORDER:- 5(BLACK)  8(BLACK)  15(RED)  17(BLACK)  18(RED)  
POSTORDER:- 5(BLACK)  15(RED)  18(RED)  17(BLACK)  8(BLACK)  
PREORDER:- 8(BLACK)  5(BLACK)  17(BLACK)  15(RED)  18(RED) */


<|start_filename|>C/sort/MatrixSorting.c<|end_filename|>
/*Matrix Sort Method
Matrix is sorted in a way such that all elements in a row are sorted in increasing order and for row ‘i’, 
where 1 <= i <= n-1, first element of row 'i' is greater than or equal to the last element of row 'i-1'.
*/
#include <stdio.h>
#include <stdlib.h>

void matrix_sort(int[][10], int, int);
int main()
{
	int ROW, COLUMN;
	printf("Enter Row: ");
	scanf("%d", &ROW);
	printf("Enter Column: ");
	scanf("%d", &COLUMN);
	printf("Enter the elements of Matrix:\n");
	int arr[10][10], i, j;
	for (i = 0; i < ROW; i++)
	{
		for (j = 0; j < COLUMN; j++)
		{
			scanf("%d", &arr[i][j]);
		}
	}

	matrix_sort(arr, ROW, COLUMN);
	printf("\nSorted Matrix: \n");
	for (i = 0; i < ROW; i++)
	{
		for (j = 0; j < COLUMN; j++)
		{
			printf("%d ", arr[i][j]);
		}

		printf("\n");
	}

	return 0;
}

// Sorting the matrix using matrix sort method
void matrix_sort(int arr[][10], int ROW, int COLUMN)
{
	int i, j, minumum, temp, q, w, minimum, k, z;
	for (i = 0; i < ROW; i++)
	{
		for (j = 0; j < COLUMN; j++)
		{
			temp = i;
			q = j;
			minimum = arr[i][j];
			w = j;
			for (k = i; k < ROW; k++)
			{
				for (; w < COLUMN; w++)
				{
					if (arr[k][w] < minimum)
					{
						minimum = arr[k][w];
						z = k;
						q = w;
					}
				}

				w = 0;
			}

			if (arr[z][q] < arr[i][j])
			{
				temp = arr[i][j];
				arr[i][j] = minimum;
				arr[z][q] = temp;
			}
		}
	}
}

/*
Sample Output
Enter Row: 3
Enter Column: 3
Enter the elements of matrix :
7 8 9
5 6 4
3 1 2
Sorted Matrix :
1 2 3
4 5 6
7 8 9

Complexities
Time Complexity: O(n2log2n)
Space Complexity : Auxiliary Space: O(n2)
 */

 

<|start_filename|>C-Plus-Plus/other/vector_of_strings_occurs_more_than_one_time.cpp<|end_filename|>
/*
Given a list of strings.
those strings occurs more than one time, return them as a vector of strings.
*/

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

vector < string > get_duplicate_string( vector < string > vec_string, int Number)
{
    vector < string > duplicates;
    map < string , int > mp;
    for(int i = 0; i < vec_string.size(); i++)
    {
        /* if mp[vec_string[i]] == 0 means that
        that string is not present. right now it's occurrence
        is only 1
        */
        if(mp[vec_string[i]] == 0)
        {
            mp[vec_string[i]]++;
        }
        /* if mp[vec_string[i]] != 0 means that
        that string is already present. right now it's occurrence
        more than 1 , it's duplicate.
        */
        else if(mp[vec_string[i]] != 0)
        {
            duplicates.push_back(vec_string[i]);
        }
    }
    return duplicates;
}

int main()
{
    cout << "Enter the number of strings : \n";
    int Number;
    cin >> Number;
    vector < string > vec_string;
    cout << "Enter the strings :\n";
    for(int i = 1; i <= Number; i++)
    {
        string s;
        cin >> s;
        vec_string.push_back(s);
    }
    vector < string > duplicate_string = get_duplicate_string(vec_string, Number);
    cout << "Duplicate Strings are : ";
    for(auto i : duplicate_string)
    {
        cout << i << ' ';
    }
    cout << endl;
}
/*
Standard Input and Output

Enter the number of strings :
6
Enter the strings :
tom
lucius
ginny
harry
ginny
harry
Duplicate Strings are : ginny harry

Time Complexity : O(log N)
Space Complexity : O(N)

*/


<|start_filename|>C-Plus-Plus/dp/longest_palin_subseq.cpp<|end_filename|>
/*
Length of the longest palindromic subsequence in a string
 ALGORITHM
 *Reverse the string
 *Find the longest common subsequence between the string and its reverse
 */
#include<bits/stdc++.h>
using namespace std;
int longestPalinSubseq(string X,int n)
{
    string Y=X;
    reverse(Y.begin(),Y.end());
    
    int dp[n+1][n+1];
    //Base conditions
    for(int i=0;i<n+1;i++)
    {
        for(int j=0;j<n+1;j++)
        {
            if(i==0 || j==0)
            dp[i][j]=0;
        }
    }
    for(int i=1;i<n+1;i++)
    {
        for(int j=1;j<n+1;j++)
        {
            if(X[i-1]==Y[j-1])
            dp[i][j]=1+dp[i-1][j-1];
            else
            dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
        }
    }
    return dp[n][n];
}
int main()
{
    string X;
    cin>>X;
    int n=X.length();
    cout<<longestPalinSubseq(X,n)<<"\n";
}
/*
Time complexity:O(n^2)
INPUT:
X=ayan
OUTPUT:
3
*/


<|start_filename|>C-Plus-Plus/cp/Interval_list_Intersection.cpp<|end_filename|>
/*
You are given two lists of closed 
intervals,firstList and secondList,
where firstList[i] = [starti, endi]
and secondList[j] = [startj, endj].
Each list of intervals is pairwise
disjoint and in sorted order.Return
the intersection of these two inte-
-rval lists.The intersection of two
closed intervals is a set of real
numbers that are either empty or 
represented as a closed interval.
*/

#include <bits/stdc++.h>
using namespace std;
vector<int> IntervalList(int I1, int J1, int I2, int J2)
{
    vector<int> U;
    if (J2 == I1) {
        U.push_back(J2);
        U.push_back(J2);
        return U;
    }
    if ((I2 < I1) && (J2 > I1) && (J2 < J1)) {
        U.push_back(I1);
        U.push_back(J2);
        return U;
    }
    if ((I2 >= I1) && (J2 <= J1)) {
        U.push_back(I2);
        U.push_back(J2);
        return U;
    }
    if ((I2 > I1) && (J2 >= J1) && (I2 < J1)) {
        U.push_back(I2);
        U.push_back(J1);
        return U;
    }
    if ((I1 >= I2) && (J1 <= J2)) {
        U.push_back(I1);
        U.push_back(J1);
        return U;
    }
    if (J1 == I2) {
        U.push_back(J1);
        U.push_back(J1);
        return U;
    }
    return U;
}
vector<vector<int> > intervalIntersection(
    vector<vector<int> >& firstList,
    vector<vector<int> >& secondList)
{
    int X, Y, i, j, I1, J1, I2, J2;
    X = firstList.size();
    Y = secondList.size();
    vector<vector<int> > Ans;
    if ((X == 0) || (Y == 0))
        return Ans;
    I1 = firstList[0][0];
    J1 = firstList[0][1];
    I2 = secondList[0][0];
    J2 = secondList[0][1];
    i = 0;
    j = 0;
    while ((i < X) && (j < Y)) {
        vector<int> U = IntervalList(I1, J1, I2, J2);
        if (U.size() != 0) {
            Ans.push_back(U);
        }
        if (J1 < J2) {
            ++i;
            if (i < X) {
                I1 = firstList[i][0];
                J1 = firstList[i][1];
            }
        }
        else if (J1 == J2) {
            ++i;
            if (i < X) {
                I1 = firstList[i][0];
                J1 = firstList[i][1];
            }
            ++j;
            if (j < Y) {
                I2 = secondList[j][0];
                J2 = secondList[j][1];
            }
        }
        else {
            ++j;
            if (j < Y) {
                I2 = secondList[j][0];
                J2 = secondList[j][1];
            }
        }
    }
    return Ans;
}
int main()
{    
    int N, i, S, E, M;
    cout << "Enter the size of first list : ";
    cin >> N;
    vector<vector<int> > firstList;
    for (i = 0; i < N; i++) {
        vector<int> Temp;
        cin >> S >> E;
        Temp.push_back(S);
        Temp.push_back(E);
        firstList.push_back(Temp);
    }
    cout << "Enter the size of second list : ";
    cin >> M;
    vector<vector<int> > secondList;
    for (i = 0; i < M; i++) {
        vector<int> Temp;
        cin >> S >> E;
        Temp.push_back(S);
        Temp.push_back(E);
        secondList.push_back(Temp);
    }
    cout << "The Intersection of given two list : " << endl;
    vector<vector<int> > IntersectingList = intervalIntersection(firstList, secondList);
    for (i = 0; i < IntersectingList.size(); i++)
        cout << IntersectingList[i][0] << " " << IntersectingList[i][1] << endl;
    return 0;
}

/*
Time Complexity: O(N + M)
Space Complexity: O(M + N)
where N and M are the size of first
and second List respectively.

Sample Input 
Enter the size of first list :
4
0 2
5 10
13 23
24 25
Enter the size of second list : 
4
1 5
8 12
15 24
25 26

Output 
The Intersection of given two list :
1 2
5 5
8 10
15 23
24 24
25 25
*/


<|start_filename|>C-Plus-Plus/ds/Vector.cpp<|end_filename|>
/*
Vector
-------
A vector is a re-sizeable array. Internally, vectors use a dynamically allocated array
to store their elements. If the array is full and new elements have to be added
in it, then a new array of twice the size is declared and all the elements from the
previous array are copied onto the new array. This is an expensive operation

push_back() Time Complexity: O(current size)

*/

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

template<typename T>
class Vector {

	int cs; // Current Size : Gives count of the elements currently in vector
	int ms; // Maximum Size : Gives count of the maximum elements that can be in vector
	T *arr;	// Array declared
public:
	// Constructor
	Vector() {
		cs = 0;
		ms = 1;
		// Array is dynamically allocated memory space
		arr = new T[ms];
	}

	// Inserts new element into the vector from back
	void push_back(const T d) {

		if (cs == ms) {
			// Array is full
			T *oldArr = arr;
			// arr points to a new memory location with twice memory space
			arr = new T[2 * ms];
			ms = 2 * ms;
			// Copy elements from oldArr
			for (int i = 0; i < cs; i++) {
				arr[i] = oldArr[i];
			}
			// clear the old memory
			delete [] oldArr;
		}

		// Insert new element
		arr[cs] = d;
		cs++;
	}

	// Removes last element from the vector
	void pop_back() {
		cs--;
	}

	// Returns the element at the front of the vector
	T front() const {
		return arr[0];
	}

	// Returns the element at the back of the vector
	T back() const {
		return arr[cs - 1];
	}

	// Returns whether vector is empty
	bool empty() const {
		return cs == 0;
	}

	// Returns current size of the vector
	int size() const {
		return cs;
	}

	// Returns maximum size of the vector
	int capacity() const {
		return ms;
	}

	// Returns iterator to the start of the vector
	T* begin() const {
		return arr;
	}

	// Returns iterator to the end of the vector
	T* end() const {
		return arr + cs;
	}

	// Returns element at ith index
	T operator[](const int i) {
		return arr[i];
	}

	// Clears the vector
	void clear() {
		cs = 0;
	}
};

void printVector(Vector<int> v) {
	for (int i = 0; i < v.size(); i++) {
		cout << v[i] << " ";
	} cout << endl;
}

int main() {

	cout << "Enter <1> To push elements \n"
	     "<2> To pop (last) element \n"
	     "<3> To get front element \n"
	     "<4> To get back element\n"
	     "<5> To check if vector is empty \n"
	     "<6> To get size of vector \n"
	     "<7> To get capacity of vector \n"
	     "<8> To get iterator to start of vector \n"
	     "<9> To get iterator to the end of vector \n"
	     "<10> To clear vector \n"
	     "<11> To print the vector \n"
	     "<12> To exit program \n\n";

	cout << "Enter Choice: ";

	// Declaring a vector
	Vector<int> v;

	int choice;

	while (cin >> choice) {

		switch (choice) {

		case 1: cout << "Enter elements to push until -1: ";
			int x;
			cin >> x;
			while (x != -1) {
				v.push_back(x);
				cin >> x;
			} break;

		case 2: if(!v.empty()) v.pop_back(); 
			else cout<<"Vector is empty"<<endl;
			break;
		case 3: if(!v.empty()) cout << v.front() << endl; 
			else cout<<"Vector is empty"<<endl;
			break;
		case 4: if(!v.empty()) cout << v.back() << endl; 
			else cout<<"Vector is empty"<<endl;
			break;
		case 5: cout << v.empty() << endl; break;
		case 6: cout << v.size() << endl; break;
		case 7: cout << v.capacity() << endl; break;
		case 8: cout << v.begin() << endl; break;
		case 9: cout << v.end() << endl; break;
		case 10: v.clear(); break;
		case 11: printVector(v); break;

		default: exit(0);
		}

		cout << "Enter Choice: ";

	}
}

/*
Console output:

Enter <1> To push elements
<2> To pop elements
<3> To get front element
<4> To get back element
<5> To check if vector is empty
<6> To get size of vector
<7> To get capacity of vector
<8> To get iterator to start of vector
<9> To get end of vector
<10> To clear vector
<11> To print the vector
<12> To exit program
Enter Choice: 1
Enter elements to push until -1: 1 2 3 -1
Enter Choice: 11
1 2 3
Enter Choice: 2
Enter Choice: 11
1 2
Enter Choice: 3
1
Enter Choice: 4
2
Enter Choice: 5
0
Enter Choice: 6
2
Enter Choice: 7
4
Enter Choice: 8
0x6a0f68
Enter Choice: 9
0x6a0f70
Enter Choice: 10
Enter Choice: 11

Enter Choice: 12

*/


<|start_filename|>C-Plus-Plus/ds/Vertical_Level_Sums_Of_Binary_Tree.cpp<|end_filename|>
/*
Introduction 
Given a Binary Tree , Print all vertical level sum's.
It is guaranteed that all node's have unique key values.

Argument/Return Type
Input of total no.of nodes is taken
Input of key values of nodes of tree are taken in level order form 
Incase of a null node , -1 is taken as input
*/

#include <bits/stdc++.h> 
using namespace std;
//Declare Global maps to maintain sum of all vertical levels
map<int,int>verticalLevelSum;
//Define Global variable to keep track leftmost level and right most level
int LeftMostLevel;
int RightMostLevel;

//Define Node as structure
struct Node 
{
    int key;
    Node* left;
    Node* right;
};
 
// Function to create a node with 'value' as the data stored in it. 
// Both the children of this new Node are initially null.
struct Node* newNode(int value)
{
    Node* n = new Node;
    n->key = value;
    n->left = NULL;
    n->right = NULL;
    return n;
}

// Function to build tree with given input
struct Node* createTree(vector<int>v)
{
    int n=v.size();
    if(n==0) 
      return NULL;
    vector<struct Node* >a(n);
    //Create a vector of individual nodes with given node values
    for(int i=0;i<n;i++)  
    {
        //If the data is -1 , create a null node
        if(v[i]==-1)  
          a[i] = NULL;
        else 
          a[i] = newNode(v[i]);
    }
    //Interlink all created nodes to create a tree
    //Use two pointers using int to store indexes
    //One to keep track of parent node and one for children nodes
    for(int i=0,j=1;j<n;i++) 
    {
        //If the parent node is NULL , advance children pointer twice
        if(!a[i])
        {
          j=j+2;
          continue;
        } 
        //Connect the two children nodes to parent node
        //First left and then right nodes
        a[i]->left = a[j++];
        if(j<n) 
          a[i]->right = a[j++];
    }
    return a[0];
}

//Utility function to update levels of roots recursively 
void UpdateLevelsUtil(struct Node* root,int level)
{
  //If root is NULL , return
  if(root==NULL)
    return;

  //else add the root's value to its corresponding level
  verticalLevelSum[level]=verticalLevelSum[level]+root->key;

  //update LeftMost and RightMost levels
  LeftMostLevel=min(LeftMostLevel,level);
  RightMostLevel=max(RightMostLevel,level);

  //Now recursively update levels of children , by giving corresponding level values
  UpdateLevelsUtil(root->left,level-1);
  UpdateLevelsUtil(root->right,level+1);
  return ;
}

//Function to call utility function and update all levels and corresponding sums
void UpdateLevels(struct Node* root)
{
  UpdateLevelsUtil(root,0);
  return ;
}

//Function to print level sums of all levels from left to right
void PrintVerticalLevelSums()
{
  //print level sums of all levels from left most level to right most level
  for(int i=LeftMostLevel;i<=RightMostLevel;i++)
    cout<<verticalLevelSum[i]<<" ";
}
                
// Driver code
int main()
{

    int n;
    cout<<"Enter total no.of nodes of the input Tree ( including NULL nodes ) : ";
    cin>>n;

    vector<int>v(n);
    cout<<"Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces"<<endl;
    for(int i=0;i<n;i++)
    {
        cin>>v[i]; //store the input values in a vector
    }

    //create the tree using input node values  
    struct Node* root=createTree(v); 
    
    //initialise the variables as follows
    LeftMostLevel=INT_MAX;
    RightMostLevel=INT_MIN;

    //call the function to update Vertical Levels of all node's
    UpdateLevels(root);

    //Call the function and print the result
    cout<<"Hence vertical Level Sum's from left to right are : ";
    PrintVerticalLevelSums();
    
    return 0; 
}
    
/*
Input:
0 <= node->key < 1000000000
if node is NULL , -1 is entered as it's key

Sample Test Case 1  
Input Binary Tree :                   
               1                                
           /         \                          
         2              11                    
     /       \        /   \               
    3        5       12    13             
   / \      /  \    / \   /  \            

  4 NULL    6  7    8  9 NULL  4  

Vertically Level wise representation will be as follows :
                                        1
                                2               11
                           3            5,12           13
                       4      6,8,NULL         7,9,NULL      4

Input Format : 
Example :
Enter total no.of nodes of the input Tree ( including NULL nodes ) : 15
Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces
1 2 11 3 5 12 13 4 -1 6 7 8 9 -1 4

Output Format :
Example : ( Output to the above input example ) 
Hence vertical Level Sum's from left to right are : 4 3 16 18 27 13 4

Time/Space Complexity
Time Complexity : O(n) 
   Where n is the no.of nodes 
Space Complexity : O(w) 
   Where w is the width of the tree
*/


<|start_filename|>C-Plus-Plus/search/Binary_Recursive_Search.cpp<|end_filename|>
/* Below code is an implementation of binary search in CPP using
recursive method. An array is taken as input from the user, followed
by the element the user wants to search in the array. The search function
is called. If the element is present in the array, then print the index
of the element in the array.
NOTE : For binary search to work, the input array must be SORTED*/

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

// This function recursively searches for element in array
int search(int array[], int left, int right, int element) {

	// If left pointer exceeds the right pointer
	if(left > right) {
		return -1;
	}
	else {
		// Find the middle index
		int middle = left + (right - left) / 2;

		// If element is found return index
		if(array[middle] == element) {
			return middle;
		}
		/* If middle element is greater than the given element 
		to search, then, recursively search in the left half of
		the array.*/
		else if(array[middle] > element) {
			return search(array, left, middle - 1, element);
		}
		/* If middle element is less than the given element to
		search, then, recursively search in the right half of
		the array.*/
		else if(array[middle] < element) {
			return search(array, middle + 1, right, element);
		}
	}
	// If not found, return -1
	return -1;
}

int main() {

	// Take length of array as input from the user
	cout << "Enter the length of array: ";
	int length;
	cin >> length;

	// Take elements of array as input from the user
	cout << "Enter " << length << " elements followed by spaces: ";
	int array[length];
	for(int i = 0; i < length; i++) {
		cin >> array[i];
	}

	// Take element to search as input from the user
	cout << "Enter the element you want to search: ";
	int element;
	cin >> element;

	// Call search function to find the index
	int index = search(array, 0, length - 1, element);
	
	// New line
	cout << endl;

	// If index is -1, the element is not present
	if(index == -1) {
		cout << "The element " << element << " is not present in the given array." << endl;
	}
	// Else print index of element in the array
	else {
		cout << "The element " << element << " is present at index " << index << "." << endl;
	}
	return 0;
}

/* Sample I/O:

Enter the length of array: 10
Enter 10 elements followed by spaces: -11 -6 -3 2 4 6 8 10 12 20
Enter the element you want to search: 4

The element 4 is present at index 4.

Here, O is Thetha
Time Complexity: O(logn)
Space Complexity: O(n)
*/



<|start_filename|>C-Plus-Plus/math/Noble_Integer.cpp<|end_filename|>
/*An integer x is said to be Noble given an array 
if the number of integers greater than x are equal to x.
If noble integer is not found output is -1.
*/
#include <bits/stdc++.h>
using namespace std;
int nobleint(int[], int);
int main()
{
	int num, i, x, arr[10000];
	cout << "Enter the number of elements:";
	cin >> num;
	cout << "Enter the elements:";
	for (int i = 0; i < num; i++)
	{
		cin >> x;
		arr[i] = x;
	}
	cout << nobleint(arr, num);
	return 0;
}

// To find the noble integer from the given array
int nobleint(int arr[], int num)
{
	int x = 0, i;
	sort(arr, arr + num);
	for (i = 0; i < num - 1; i++)
	{
		if (arr[i] == arr[i + 1])
		{
			continue;
		}

		if (arr[i] == num - i - 1)
		{
			x = 1;
			return (num - i - 1);
			break;
		}
	}
	if (x == 0)
		return (-1);
}

/*
Sample Output

Enter the number of elements:4
Enter the elements:7 3 9 81
3
Enter the number of elements:3
Enter the elements:2 2 2
-1

Complexities
Time Complexity:O(nlogn)
Space Complexity:O(1)
*/



<|start_filename|>C/cp/zalgorithm.c<|end_filename|>
#include <stdio.h>
#include <string.h>

void getZ(char s[], int z[])
{
	int n = strlen(s);
	int left = 0, right = 0;
	for (int i = 1; i < n; ++i)
	{
		if (i > right)
		{
			left = right = i;
			while (right < n && s[right - left] == s[right])
				right++;
			z[i] = right - left;
			right--;
		}
		else
		{
			int k = i - left;
			if (z[k] < right - i + 1)
			{
				z[i] = z[k];
			}
			else
			{
				left = i;
				while (right < n && s[right - left] == s[right])
					right++;
				z[i] = right - left;
				right--;
			}
		}
	}
}

int main()
{
	char text[100], pattern[100];
	printf("Enter the text: ");
	scanf("%s", text);
	printf("\nEnter the pattern: ");
	scanf("%s", pattern);
	int m = strlen(pattern);
	strcat(pattern, "$");
	strcat(pattern, text);
	int n = strlen(pattern);
	int z[n];
	getZ(pattern, z);
	for (int i = 0; i < n; ++i)
	{
		if (z[i] == m)
		{
			printf("\nPattern found at index %d", i - m - 1);
		}
	}

	return 0;
}

/*
Time Complexity: O(length of text + length of pattern)

Input
Enter the text: AABACAAFGAABAABA
Enter the pattern: AABA

Output
Pattern found at index 0
Pattern found at index 9
Pattern found at index 12
*/


<|start_filename|>C-Plus-Plus/dp/Zero_One_Knapsack.cpp<|end_filename|>
#include <iostream>

using namespace std;
int n, k;
int * profit = NULL;
int * weight = NULL;
int ** table = NULL;
int max_profit = 0;
void input() {
  cin >> n;
  cin >> k;
  profit = new int[n];
  weight = new int[n];
  for (int i = 1; i <= n; i++) {
    cin >> profit[i];
    cin >> weight[i];
  }
  table = new int * [k + 1];
  for (int i = 0; i <= n; ++i)
    table[i] = new int[k + 1];

  for (int i = 0; i <= n; i++) {
    for (int j = 0; j <= k; j++)
      table[i][j] = -1;
  }
}

//finding maximum profit in iterative way
void knapsack() {
  for (int j = 0; j <= k; j++)
    table[0][j] = 0;
  for (int i = 0; i <= n; i++)
    table[i][0] = 0;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= k; j++) {
      if (j < weight[i]) //when size of knapsack is less than weight of item i
        table[i][j] = table[i - 1][j];
      else
        table[i][j] = max(table[i - 1][j], table[i - 1][j - weight[i]] + profit[i]);
    }
  }
  max_profit = table[n][k];
}

void display() {
  cout << "Number of items: " << n;
  cout << endl << "knapsack Size: " << k;
  for (int i = 1; i <= n; i++)
    cout << endl << "Item " << i << " (Prifit,Weight) is: (" << profit[i] << "," << weight[i] << ")";
  cout << endl << "Max Profit in the knapsack is: " << max_profit;
}
int main() {
  // your code goes here
  input();
  knapsack();
  display();
  return 0;
}

/*
Input:
3
50
60 10
100 20
120 30

output:
Number of items: 3
knapsack Size: 50
Item 1 (Profit,Weight) is: (60,10)
Item 2 (Profit,Weight) is: (100,20)
Item 3 (Profit,Weight) is: (120,30)
Max Profit in the knapsack is: 220

Complexity:
Time: O(n*k)
Space: O(n*k)
*/

<|start_filename|>Java/math/CatalanNumber.java<|end_filename|>
import java.util.*;

public class CatalanNumber {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter number: ");
        int num = sc.nextInt();
        System.out.println();
        int[] arr = new int[num + 2];
        arr[0] = 1;
        arr[1] = 1;
        for (int i = 1; i <= num; i++) {
            for (int j = i; j > 1; j--)
                arr[j] = arr[j] + arr[j - 1];
            arr[i + 1] = arr[i];
            for (int j = i + 1; j > 1; j--)
                arr[j] = arr[j] + arr[j - 1];
            System.out.printf("%d ", arr[i + 1] - arr[i]);
        }
    }
}

/*
Sample input and output
Enter number: 7

1 2 5 14 42 132 429 

time complexity: O(n^2)
space complexity: O(n)
*/


<|start_filename|>C-Plus-Plus/heap/Median_in_a_running_stream_of_integers.cpp<|end_filename|>
/*
Median of a stream of running integers
======================================
Print the median of given numbers while keep taking in new numbers

Concept:
We maintain two heaps - a minHeap and a maxHeap. minHeap contains numbers greater than the current median and
maxHeap contains numbers less than equal to the current median.
Note that if the number of elements in both the heaps are equal then median will be equal to the average of the
topmost elements of the two heaps. If any heap contains more elements than the other heap then its topmost element will
be the current median. Also note that the maximum difference in the number of elements between the two heaps should always be
less than equal to 1.

|n(minHeap) - n(maxHeap)|<=1

If we are in a situation where inserting an element causes increase in this difference, then we must transfer an element
from one heap to other to settle this.

Time Complexity: O(nlogn)
Space Complexity: O(n)
*/

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

// Prints median in a running stream of integers
void getMedian(int a[], int n) {
	// Declare a maxHeap and a minHeap
	priority_queue<int> maxHeap;
	priority_queue<int, vector<int>, greater<int>> minHeap;

	// Push in maxheap
	maxHeap.push(a[0]);

	// current median
	// When count of numbers is 1, median is equal to the number itself
	double curr = a[0];
	// Print current median
	cout << curr << " ";

	//  While numbers are being inputted
	for (int i = 1; i < n; i++) {
		int num = a[i];
		// INSERTION:

		// If num is greater than current median
		if (num > curr) {
			// Insert in minHeap
			// If size of minHeap is more
			if (minHeap.size() >= maxHeap.size() + 1) {
				// shift one element from minHeap to maxHeap
				int num = minHeap.top();
				minHeap.pop();
				maxHeap.push(num);
			}
			// Insert in minHeap
			minHeap.push(num);
		}

		// If num is less than equal to the current median
		else {
			// Insert in maxHeap
			// If size of maxHeap is more
			if (maxHeap.size() >= minHeap.size() + 1) {
				// shift one element from maxHeap to minHeap
				int num = maxHeap.top();
				maxHeap.pop();
				minHeap.push(num);
			}
			// Insert in maxHeap
			maxHeap.push(num);
		}

		// PRINTING:

		/// If sizes are equal, avearge must be taken
		if (minHeap.size() == maxHeap.size()) {
			curr = (minHeap.top() + maxHeap.top()) * 1.0 / 2.0;
			cout << curr << " ";
		}
		// else topmost element of heap with greater size is printed
		else if (minHeap.size() > maxHeap.size()) {
			curr = minHeap.top();
			cout << curr << " ";
		}
		else {
			curr =  maxHeap.top();
			cout << curr << " ";
		}
	}
}

// Driver code
int main() {

	// Take input
	int n; cin >> n;
	int a[n];
	for (int i = 0; i < n; i++) {
		cin >> a[i];
	}

	getMedian(a, n);
}

/*
Input:
4
5 15 1 3

Output:
5 10 5 4

Explanation:
Median of {5} -> 5
Median of {5, 15} -> 10
Median of {5, 15, 1} -> 5
Median of {5, 15, 1, 3} -> 4
*/


<|start_filename|>Java/search/Stack_Search.java<|end_filename|>
/* Stack search is a method to search an element in a stack and return the index at which its found. */

import java.util.*;

public class stack_search{
    
	public static void main(String[] args) {
	    
	    Scanner sc = new Scanner(System.in);
	    //enter the no of elemnts to be there inside stack
	    int n = sc.nextInt();
	    int no;
        Stack <Integer> st = new Stack <Integer> (); 
        for(int i = 1; i <= n; i++) {
        	no = sc.nextInt();
        	st.push(no);
        }
        // Displaying the Stack 
        System.out.println("The stack is: " + st); 
         //enter the element to be searched
            int item = sc.nextInt();
        // Checking for the element
            int search = st.search(item);
           System.out.println(item+" is seached at index="+(n-search+1));     
    } 
}


<|start_filename|>Java/search/Linear_search.java<|end_filename|>
import java.util.*;

public class Linear_search {
	//It iterates through the array to find key.
	//The average and worst case time complexity O(n).
	//The worst case space complexity is O(1).
	static int linSearch(int[] a, int k, int length) {
		for (int i = 0; i < length; i++) {
			if (a[i] == k)
				return i + 1; //returns position
		}
		return -1; //returns -1 if not found
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.print("Enter the length of the array: ");
		int length = sc.nextInt();
		int arr[] = new int[length];
		System.out.print("Enter array values: ");
		for (int i = 0; i < length; i++) {
			arr[i] = sc.nextInt();
		}
		System.out.print("Enter the value whose index needs to be searched: ");
		int value = sc.nextInt();
		System.out.println("Index of " + value + " is: " + linSearch(arr, value, length));
	}
}
/*
Input:
Enter the length of the array: 5
Enter array values: 2 7 8 9 1
Enter the value whose index needs to be searched: 9 
output:
Index of 9 is: 4
*/


<|start_filename|>C-Plus-Plus/ds/Binary_Tree_Kth_Smallest_Element.cpp<|end_filename|>
/*
Introduction 
Given a Binary Tree , Find its k th smallest element

Argument/Return Type
Input of total no.of nodes is taken
Input of key values of nodes of tree are taken in level order form 
Incase of a null node , -1 is taken as input
Function to find and return kth smallest element
*/

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

//Define Node as structure
struct Node 
{
    int key;
    Node* left;
    Node* right;
};
 
// Function to create a node with 'value' as the data stored in it. 
// Both the children of this new Node are initially null.
struct Node* newNode(int value)
{
    Node* n = new Node;
    n->key = value;
    n->left = NULL;
    n->right = NULL;
    return n;
}

// Function to build tree with given input
struct Node* createTree(vector<int>v)
{
    int n=v.size();
    if(n==0) 
      return NULL;
    vector<struct Node* >a(n);
    //Create a vector of individual nodes with given node values
    for(int i=0;i<n;i++)  
    {
        //If the data is -1 , create a null node
        if(v[i]==-1)  
          a[i] = NULL;
        else 
          a[i] = newNode(v[i]);
    }
    //Interlink all created nodes to create a tree
    //Use two pointers using int to store indexes
    //One to keep track of parent node and one for children nodes
    for(int i=0,j=1;j<n;i++) 
    {
        //If the parent node is NULL , advance children pointer twice
        if(!a[i])
        {
          j=j+2;
          continue;
        } 
        //Connect the two children nodes to parent node
        //First left and then right nodes
        a[i]->left = a[j++];
        if(j<n) 
          a[i]->right = a[j++];
    }
    return a[0];
}

//Traverse all nodes of a tree in level order fashion 
// and maintain k smallest elements
int kthSmallest(struct Node* root,int k)
{
    // If root is NULL , return -1
    if (root == NULL)
        return -1;
    //Store and maintain k smallest elements of tree
    priority_queue<int>heap;

    // Create an queue
    queue<struct Node*> q;
    //Enqueue the root node and a null node to indicate a level is completed
    q.push(root);
 
    while (!q.empty()) 
    {
        //Traverse each node 
        //If it is a null node , pop it and continue
        if(q.front()==NULL)
        {
            q.pop();
            continue;
        }
        //else update heap
        heap.push(q.front()->key);
        //if heap's size exceed k , 
        //pop the top element
        if(heap.size()>k)
           heap.pop();
        //Enqueue node's children , if they exist
        if(q.front()->left)
            q.push(q.front()->left);
        if(q.front()->right)
            q.push(q.front()->right);
        q.pop();
    }
    //If no.of nodes of tree is less than k , return -1
    //else return kth smallest element
    if(heap.size()<k)
      return -1;
    else
      return heap.top();
}
    
// Driver code
int main()
{

    int n;
    cout<<"Enter total no.of nodes of the input Tree ( including NULL nodes ) : ";
    cin>>n;

    vector<int>v(n);
    cout<<"Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces"<<endl;
    for(int i=0;i<n;i++)
    {
        cin>>v[i]; //store the input values in a vector
    }

    //create the tree using input node values  
    struct Node* root=createTree(v); 

    int k;
    cout<<"Enter the value of k : ";
    cin>>k;

    //Call the function and print the result
    int answer=kthSmallest(root,k);
    if (answer==-1)
      cout<<"Given Tree has less than k nodes for given value of k";
    else
      cout<<"Hence the kth smallest value of Tree for given value of k is "<<answer;
    
    return 0; 
}
    
/*
Input:
0 <= node->key < 1000000000
if node is NULL , -1 is entered as it's key

Sample Test Case 1  
Input Binary Tree :                   

               1                                
           /         \                          
         2              11                    
     /       \        /   \               
    3        5       12    13             
   / \      /  \    / \   /  \            

  4 NULL    6  7    8  9 NULL  4         

Input Format : 
Example :
Enter total no.of nodes of the input Tree ( including NULL nodes ) : 15
Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces
1 2 11 3 5 12 13 4 -1 6 7 8 9 -1 4
Enter the value of k : 2

Output Format :
Example : ( Output to the above input example ) 
Hence the kth smallest value of Tree for given value of k is 2

Time/Space Complexity
Time Complexity : O(n) 
   Where n is the no.of nodes 
Space Complexity : O(n) 
   Where n is the no.of nodes
*/


<|start_filename|>Go/math/Armstrong_Number/armstrongnumber.go<|end_filename|>
/*
   This is a simple program in go language to check if a given
   number is armstrong number or not. An armstrong number is
   a number that is equal to the sum of cubes of its individual digits.
   Example : 153 = 1^3+5^3+3^3 = 153!
*/

package main

import (

  "fmt"

)

// global variable 
var number int

// This fuction checks if the given number is armstrong or not
func check(sum int) {

    if(number == sum){

       fmt.Print("This is an Armstrong number ")

    }else{

        fmt.Print("This is not Armstrong number")
    }

}

// This function calculates the sum of cubes of digits 
func armstrongnumber() {

   var sum int
   var n int
   n = number
   sum = 0
   var r int
   r = 0

   for n != 0 {

      r = n%10
      sum += (r*r*r)
      n = n/10

   }

   // calling the check function
   check(sum)

}

// driver function
func main() {

   fmt.Print("Enter the number you want to check for :")
   // Taking the number as input we need to check
   fmt.Scan(&number)

   // calling the armstrong number
   armstrongnumber()
}

/*
   Simple I/O :

   a) Is an armstrong number :

   Enter the number you want to check for :153
   This is an Armstrong number

   b) Is not an armstrong number :

   Enter the number you want to check for :76
   This is not Armstrong number   

*/



<|start_filename|>C-Plus-Plus/cp/Kadane_Alogorithm.cpp<|end_filename|>
#include <bits/stdc++.h>
using namespace std;

int max_sum_subarray(int a[], int n){

    int max_ending=a[0];

    int ans=a[0];

    for(int i=1;i<n;i++)
    {
        max_ending=max(max_ending+a[i], a[i]);
        ans=max(ans,max_ending);
    }

    return ans;

}

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

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

    cout<<max_sum_subarray(a,n);
    
}


<|start_filename|>C-Plus-Plus/stack/smallest_element_in_an_array.cpp<|end_filename|>
/* Program to find the minimum element of an array using stack in O(1) space complexity and time complexity.
  
  Given Array A[]={1,2,-1,4,5};
         
  Then we will first create a stack of array of elemnents by pushing array elements and then find minimum 
  of them:-
  We define a variable min that stores the current minimum element in the stack.To handle the case when minimum element is removed 
  we push “2x – minEle” into the stack instead of x so that previous minimum element can be retrieved using current min and its value stored in stack.
  
*/
#include <bits/stdc++.h>
using namespace std;
//Creating a user-defined structure for operation on stack;
class UserStack
{ 
    private:
    stack<int> s; 
    int min;
    
    public:
    int getMin() 
    { 
        if (s.empty()) 
        {
          //Invalid operation hence returning INT_MAX;
            return INT_MAX;   
        } 
  
        else
        {
            return min;
        }
           
    } 
      void push(int x) 
    { 
       
        if (s.empty()) 
        { 
            min = x; 
            s.push(x); 
            return; 
        } 
          
     // If new number to be pushed is less than min
        if (x < min) 
        { 
            s.push(2*x - min); 
            min = x; 
        } 

        else
        {
             s.push(x); 
  
        }
          
    }
    
    
    void peek() 
    { 
        if (s.empty()) 
        { 
            cout << "Stack is empty "; 
            return; 
        } 
  
        int t = s.top();  
 
  // If t < min means min stores value of t.
  
        cout << "Top Most Element is:"; 
           if(t<min)
           {
               cout<<min<<"\n";
           }
           else
           {
               cout<<t<<"\n";
           }
        
    } 
    
      void pop() 
    { 
        if (s.empty()) 
        { 
            cout << "Stack is empty can't do pop operation\n"; 
            return; 
        } 
  
        
        int t = s.top(); 
        s.pop(); 
  
        /* Minimum will change as the minimum element 
         of the stack is being removed. */
        if (t < min) 
        { 
             
            min = 2*min - t; 
        } 
  
         
    } 
};
int main()
{
    int size;
    cout<<"Enter the size of array of which you want to find minimum\n";
    cin>>size;
    
    int A[size];
    
    cout<<"Enter the elements of array\n";
    
    for(int i=0;i<size;i++)
    {
        cin>>A[i];
    }
   
   //Creating an object of UserStack class defined by us
   UserStack S;
   
   for(int i=0;i<size;i++)
   {
       S.push(A[i]);
   }
   
   
   if(S.getMin()==INT_MAX)
   {
       cout<<"Stack is empty\n";
   }
   else
   {
        cout<<"The minimum element of the array using stack is:"<<S.getMin()<<"\n";
   
   }
  
   
    return 0;
}

/*

//Complexity Analysis

Time Complexity:-O(1) in finding minimum element (getMin() operation)
                O(1) for pushing and popping operation.
                O(N) for pushing array elements  in stack.
                
Space Complexity:-O(1)

//Input-Output Format
Input:- 5
        1,2,-2,7,6

Output:- -2

Input:- 9
        -1,-2,-9,7,6,11,34,9,8

Output:- -9

*/


<|start_filename|>C/ds/circularqueue.c<|end_filename|>
//headers
#include <stdio.h> 
#include <stdbool.h>
//defining the size of the queue we are taking here
#define size 5  

//defining a structure
typedef struct 
{
    // creating the queue structure with data, front and rear nodes pointing to front and the last(behind) node
    int data[5]; 
    
    //a node containg the value of a pointer/address pointing to the front node
    int front;
    
    //a node containing the value of a pointer/address pointing to the back/behind/rear node
    int rear;
} mainf;

//the name of the structure
mainf queuestructure;

//In the circular queue, in the last node, the front pointer points to the first node.
int enque(int number)
{ 
    //adding a value to the queue
    //if the queue is full user cant add anything more
    if (queuestructure.front == queuestructure.rear + 1) 
    {
        printf("Queue is full!\n");
    }
    else if (queuestructure.rear == size - 1)
    {
        queuestructure.rear = 0;
        printf("Rear resetted to one.\n");
    }
    else
    {
        queuestructure.rear++;
        //adding the value to the queue
        queuestructure.data[queuestructure.rear] = number; 
        printf("%d -> Added! \n", queuestructure.data[queuestructure.rear]);
    }
}


void dequeue()
//removing a specific node from the queue
{
    //the element which is being removed
    int out;
    queuestructure.front++;
    out = queuestructure.data[queuestructure.front];

    printf("%d -> Removed! \n", out);
}

int main(void)
{
    int user, value;
    //setting the front pointer to null
    queuestructure.front = -1; 
    //setting the rear pointer to null
    queuestructure.rear = -1; 
    //this means that our queue is empty at the beginning
    bool out = true;

    printf("Enter 1 to enqueue queue.\n");
    printf("Enter 2 to dequeue queue.\n");
    printf("Enter 3 to exit.\n");
    
    while (out = true)
    {
        scanf("%d", &user);

        if (user == 1)
        {
            printf("Enter a value to enqueue : ");
            scanf("%d", &value);
            //entering an element at the back
            enque(value);
            out = true;
        }
        else if (user == 2)
        {
            //to remove the first element
            dequeue();
            out = true;
        }
        else
        {
            out = false;
            return 0;
        }
    }
}


/*
Output:

Enter 1 to enqueue queue.                                                                                                                       
Enter 2 to dequeue queue.                                                                                                                       
Enter 3 to exit.                                                                                                                                
1                                                                                                                                               
Enter a value to enqueue : 11                                                                                                                   
11 -> Added!                                                                                                                                    
1                                                                                                                                               
Enter a value to enqueue : 12                                                                                                                   
12 -> Added!                                                                                                                                    
1                                                                                                                                               
Enter a value to enqueue : 14                                                                                                                   
14 -> Added!                                                                                                                                    
1                                                                                                                                               
Enter a value to enqueue : 13                                                                                                                   
13 -> Added!                                                                                                                                    
2                                                                                                                                               
11 -> Removed!                                                                                                                                  
3    
*/


<|start_filename|>C-Plus-Plus/ds/Max_Leaf_To_Leaf_Path_Sum_Of_Binary_Tree.cpp<|end_filename|>
/*

Introduction 
Given a Binary Tree , print maximum leaf to leaf path sum

Argument/Return Type
Input of total no.of nodes is taken
Input of key values of nodes of tree are taken in level order form 
Incase of a null node , -1 is taken as input
Function to find and return maximum leaf to leaf path sum

*/

//  Code / Solution

#include <bits/stdc++.h> 
using namespace std;
//Define a global variable and keep updating it whenever u get a maximum value
long MaxSum;

//Define Node as structure
struct Node 
{
    int key;
    Node* left;
    Node* right;
};
 
// Function to create a node with 'value' as the data stored in it. 
// Both the children of this new Node are initially null.
struct Node* newNode(int value)
{
    Node* n = new Node;
    n->key = value;
    n->left = NULL;
    n->right = NULL;
    return n;
}

// Function to build tree with given input
struct Node* createTree(vector<int>v)
{
    int n=v.size();
    if(n==0) 
      return NULL;
    vector<struct Node* >a(n);
    //Create a vector of individual nodes with given node values
    for(int i=0;i<n;i++)  
    {
        //If the data is -1 , create a null node
        if(v[i]==-1)  
          a[i] = NULL;
        else 
          a[i] = newNode(v[i]);
    }
    //Interlink all created nodes to create a tree
    //Use two pointers using int to store indexes
    //One to keep track of parent node and one for children nodes
    for(int i=0,j=1;j<n;i++) 
    {
        //If the parent node is NULL , advance children pointer twice
        if(!a[i])
        {
          j=j+2;
          continue;
        } 
        //Connect the two children nodes to parent node
        //First left and then right nodes
        a[i]->left = a[j++];
        if(j<n) 
          a[i]->right = a[j++];
    }
    return a[0];
}

//Function to calculate leaf to leaf sum and update it recursively
//If root->key is negative it may happen that leaf to leaf path sum < coresponding root to leaf path sum 
//Hence this function returns max root to leaf path sum in each case
long MaxLeafToLeafPathSum(struct Node* root)
{
    // If its a NULL node return 0
    if (root==NULL) return 0;
    //If it is a leaf node return its node value
    if (!root->left && !root->right) 
       return root->key;
 
    // Update MaxSum by recursively calling the function for subtrees
    // Store the values returned by function in variables
    //These are root to leaf max path sum for the coresponding subtrees
    long LeftMaxRtoLSum = MaxLeafToLeafPathSum(root->left);
    long RightMaxRtoLSum = MaxLeafToLeafPathSum(root->right);
 
 
    // If both left and right children exist
    if (root->left && root->right)
    {
        //If root->key is negative it may happen that 
        // leaf to leaf path sum < coresponding root to leaf path sum 
        // Hence Update result if needed
        MaxSum = max(MaxSum, LeftMaxRtoLSum + RightMaxRtoLSum  + root->key);
 
        // Return maxium root to leaf path with root as head
        return max(LeftMaxRtoLSum, RightMaxRtoLSum) + root->key;
    }
 
    // If one of the two children is empty, return
    // return the root to leaf path sum of existing child
    return (!root->left) ? RightMaxRtoLSum + root->key : LeftMaxRtoLSum + root->key;
}

// Driver code
int main()
{

    int n;
    cout<<"Enter total no.of nodes of the input Tree ( including NULL nodes ) : ";
    cin>>n;

    vector<int>v(n);
    cout<<"Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces"<<endl;
    for(int i=0;i<n;i++)
    {
        cin>>v[i]; //store the input values in a vector
    }

    //create the tree using input node values  
    struct Node* root=createTree(v); 

    //Initiate MaxSum with 0
    MaxSum=0;

    //Call the function and print the result
    MaxLeafToLeafPathSum(root);
    cout<<"Hence the maximum leaf to leaf path sum of given Binary Tree is "<<MaxSum;
    
    return 0; 
}
    
/*
Input:
0 <= node->key < 1000000000
if node is NULL , -1 is entered as it's key

Sample Test Case 1  
Input Binary Tree :                   

               1                                
           /         \                          
         2              11                    
     /       \        /   \               
    3        5       12    13             
   / \      /  \    / \   /  \            

  4 NULL    6  7    8  9 NULL  4         


Input Format : 
Example :
Enter total no.of nodes of the input Tree ( including NULL nodes ) : 15
Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces
1 2 11 3 5 12 13 4 -1 6 7 8 9 -1 4

Output Format :
Example : ( Output to the above input example ) 
Hence the maximum leaf to leaf path sum of given Binary Tree is 49

Sample Test Case 2  
Input Binary Tree :                   

                  12                                
          /               \                          
         9                 17                    
     /       \          /      \               
    8       10         NULL    18                                


Input Format : 
Example :
Enter total no.of nodes of the input Tree ( including NULL nodes ) : 7
Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces
12 9 17 8 10 -1 18

Output Format :
Example : ( Output to the above input example ) 
Hence the maximum leaf to leaf path sum of given Binary Tree is 66

Time/Space Complexity
Time Complexity : O(n) 
   Where n is the no.of nodes 
Space Complexity : O(1) 
   No additional space required
*/


<|start_filename|>C-Plus-Plus/other/divisors_of_natural_number.cpp<|end_filename|>
/* 
Divisors of a natural number.

For a given natural number num,
your task is to find out all the possible divisors of the given natural number and print them.
It is given that the output should have all the distinct divisors.
And the output is expected to be always sorted in ascending order.

*/

#include <bits/stdc++.h>

using namespace std;

//function to print all the possible divisors of num.
void divisorsOfNumber(int num)
{
    int pass;

    for(pass = 1; pass*pass < num; pass++)
    {
        if(num % pass == 0)
        {
            cout << pass << " ";
        }
    }

    for(pass = sqrt(num); pass >= 1; pass--)
    {
        if(num % pass == 0)
        {
            cout << (num/pass) << " ";
        }
    }
    cout << endl;
}

//main function
int main()
{
    int testCases;
    cout << "Enter the number of testcases: ";
    cin >> testCases;
    
    while(testCases--)
    {
        int num;
        cout << "Enter a natural number: ";
        cin >> num;

        cout << "All the possible divisors of " << num << " are: ";
        //calling the function divisorsOfNumber() by passing the natural number, which will print the divisors 
        divisorsOfNumber(num); 
    }

    return 0;
}

/*

FOR EXAMPLE:--

Example 1:
Input:-
Enter the number of testcases: 1
Enter a natural number: 60
Output:-
All the possible divisors of 60 are: 1 2 3 4 5 6 10 12 15 20 30 60

Example 2:
Input:-
Enter the number of testcases: 1
Enter a natural number: 101
Output:-
All the possible divisors of 101 are: 1 101

Example 3:
Input:-
Enter the number of testcases: 2
Enter a natural number:40
Enter a natural number:70
Output:-
All the possible divisors of 40 are: 1 2 4 5 8 10 20 40
All the possible divisors of 70 are: 1 2 5 7 10 14 35 70

SPACE COMPLEXITY = O(sqrt(N))
TIME COMPLEXITY = O(1)

*/


<|start_filename|>Julia/sort/circle_sort.jl<|end_filename|>
# Julia program to implement Circle Sort

# Performs recursive circular swaps and returns true if atleast one swap occurs
function rec_sort(arr, high, low)
    isSwap = false

    # If concerned array is empty, Return False
    if (high == low) 
        return false
    end

    # Storing the values of beg, end to later use in the recursive call
    highA = high
    lowA = low
    while( highA < lowA) 
        if (arr[highA] > arr[lowA]) 
            arr[highA], arr[lowA] = arr[lowA], arr[highA] 
            isSwap = true;
        end
        highA = highA + 1
        lowA = lowA - 1
    end

    # If the array has odd number of elements
    if (highA == lowA) 
        if (arr[highA] > arr[lowA + 1])     
            arr[high], arr[lowA+1] = arr[lowA+1], arr[high] 
            isSwap = true
        end
    end

    mid = (low - high) ÷ 2
    isSwapA = rec_sort(arr, high, high+mid)
    isSwapB = rec_sort(arr, high+mid+1, low)

    return (isSwap || isSwapA || isSwapB)
end


function circle_sort(arr, n)
    while (rec_sort(arr, 1, n))
    end 
end


print("How many numbers do you want to sort? ")
n = readline()
n = parse(Int64, n)
if (n <= 0)
    println("No numbers to sort!!!")
    exit()
end
arr = Int[]
print("Enter the numbers: ")
arr = [parse(Int, num) for num in split(readline())]
circle_sort(arr, n)
print("The numbers in sorted order is ")
print(arr)



"""
Time Complexity - O(n * log(n)), where 'n' is the size of the array
Space Complexity - O(n)

SAMPLE INPUT AND OUTPUT

SAMPLE I

How many numbers do you want to sort? 6
Enter the numbers: 76 243 89 25 8337 72
The numbers in sorted order is [25, 72, 76, 89, 243, 8337]

SAMPLE II

How many numbers do you want to sort? -3
No numbers to sort!!!
"""


<|start_filename|>C-Plus-Plus/ds/alternate_merging_of_linked_list.cpp<|end_filename|>
/*

Author: <NAME>


C++ program to merge alternate nodes two linked lists.
*/

#include <iostream>
#include <stdlib.h>
using namespace std;

//Creating a struct
struct node{
int data;
node *next;
};

//Function to create linked list
struct node* create(int n)
{

    struct node* head=NULL;
    struct node* tail=NULL;
    while(n!=0)
    {
        int x;
        cin>>x;
        if (head==NULL)
        {
            node* temp=new node;
            temp->data=x;
            temp->next=NULL;
            head=temp;
            tail=head;
        }
        else
        {
            node* temp=new node;
            temp->data=x;
            temp->next=NULL;
            tail->next=temp;
            tail=temp;
        }
        n--;
    }
    return head;
}
struct node* head=NULL;
struct node* tail=NULL;

//Function to create linked list
struct node* new_list(int x)
{

        if (head==NULL)
        {
            node* temp=new node;
            temp->data=x;
            temp->next=NULL;
            head=temp;
            tail=head;
        }
        else
        {
            node* temp=new node;
            temp->data=x;
            temp->next=NULL;
            tail->next=temp;
            tail=temp;
        }

    return head;
};

//Create Merged linked list function
struct node* merge_list(struct node* list1, struct node* list2,int y)
{
    node* list3=NULL;
    node* temp1=list1;
    node* temp2=list2;
    while(y!=0)
    {
        list3=new_list(temp1->data);
        list3=new_list(temp2->data);
        temp1=temp1->next;
        temp2=temp2->next;
        y--;
    }
    return list3;
}

//display function to print the linked lists
void display(struct node* head)
{
    node* temp=head;
    while(temp!=NULL)
    {
        cout<<temp->data<<"->";
        temp=temp->next;
    }
    cout<<"NULL"<<endl;
}

//main starts
int main()
{
    cout<<"Enter no. of nodes in both the linked lists: ";
    int y;
    cin>>y;
    node* list1=create(y);
    node* list2=create(y);
    cout<<"Linked List1: ";
    display(list1);
    cout<<"Linked List2: ";
    display(list2);
    node* list3=merge_list(list1,list2,y);
    cout<<"Linked List after merging: ";
    display(list3);


}

/*
Input format in test cases:
1st line contains number of nodes in each linked list(n).
2nd line contains value of each node of 1st linked list (total n) separated by spaces.
3rd line contains value of each node of 2nd linked list (total n) separated by spaces.

--------------------------------------------------------------------------------------
Test Case 1:
Input:
6
1 3 5 7 9 11
2 4 6 8 10 12

Output:
Linked List1: 1->3->5->7->9->11->NULL
Linked List2: 2->4->6->8->10->12->NULL
Linked List after merging: 1->2->3->4->5->6->7->8->9->10->11->12->NULL
--------------------------------------------------------------------------------------
Test Case 2:
Input:
9
1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1

Output:
Linked List1: 1->2->3->4->5->6->7->8->9->NULL
Linked List2: 9->8->7->6->5->4->3->2->1->NULL
Linked List after merging: 1->9->2->8->3->7->4->6->5->5->6->4->7->3->8->2->9->1->NULL
--------------------------------------------------------------------------------------

Time Complexity: merge_list() function: O(n)
Space complexity: merge_list() function: O(n)

*/


<|start_filename|>C-Plus-Plus/heap/Merge_k_sorted_arrays.cpp<|end_filename|>
/*
Merge K sorted arrays
=====================
Given K sorted arrays, merge all of them into a single sorted array

M-> Total number of elements
Time Complexity: O(MlogM)
Space Complexity: O(M)
*/
#include <iostream>
#include<queue>
using namespace std;

// Node class
class Node {
public:
	int value; // Stores value of the node
	int i; // Stores row number of the node
	int j; // Stores column number of the node

	// Constructor
	Node(int value, int i, int j) {
		this->value = value;
		this->i = i;
		this->j = j;
	}
};

// Comparator class for priority_queue
class NodeCompare {
public:
	bool operator()(Node a, Node b) {
		return a.value > b.value;
	}
};

// Merges k sorted arrays
void merge(vector<vector<int>> a, int k) {

	// minHeap declared
	priority_queue<Node, vector<Node>, NodeCompare> pq;

	// pq must be initialised with the first elements of all the k arrays
	for (int i = 0; i < k; i++) {
		Node node(a[i][0], i, 0); // node is located at the ith row and 0th column
		pq.push(node);
	}

	// Stores final array
	vector<int> ans;

	// While pq is not empty
	while (pq.size()) {
		// Consider the topmost element of pq
		Node f = pq.top();
		pq.pop();
		// Topmost element must be stored in ans
		ans.push_back(f.value);

		// Push next element of same row into the pq
		int row = f.i;
		int col = f.j;

		if (col + 1 < a[row].size()) {
			Node new_node(a[row][col + 1], row, col + 1);
			pq.push(new_node);
		}
	}

	// Print ans
	for (auto x : ans) {
		cout << x << " ";
	}
}

// driver code
int main() {

	int k; cin >> k;

	vector<vector<int>> a(k);

	for (int i = 0; i < k; i++) {
		int n; cin >> n;
		for (int j = 0; j < n; j++) {
			int x; cin >> x;
			a[i].push_back(x);
		}
	}

	merge(a, k);
}

/*
Input:
3
4
2 6 12 15
4
1 3 14 15
4
3 5 8 10

Output:
1 2 3 3 5 6 8 10 12 14 15 15
*/

<|start_filename|>Java/other/MergeSortedArrays.java<|end_filename|>
import java.util.*;

class MergeSortedArrays
{
	private static void merge(int arr1[], int arr2[])
	{
        if (arr1 == null || arr2 == null) {
            return;
        }

		// Iterate through all elements of arr2[] in reverse 
		for (int i = (arr2.length - 1); i >= 0; i--)
		{
            // In here we compare the different terms of
            // both arrays and place them in respective positions
			int j, last = arr1[arr1.length - 1];
			for (j = arr1.length - 2; j >= 0 && arr1[j] > arr2[i]; j--) {
                arr1[j+1] = arr1[j];
            }
			// If there was a greater element
			if (j != arr1.length - 2 || last > arr2[i])
			{
				arr1[j+1] = arr2[i];
				arr2[i] = last;
			}
		}
	}

	public static void main(String[] args)
	{
        Scanner sc = new Scanner(System.in);

        // taking input array 1
        System.out.println("Enter size of first array:");
        int size1 = sc.nextInt();
        int arr1[] = new int[size1];
        System.out.println("Enter array elements:");
        for (int i=0; i<size1; i++) {
            arr1[i] = sc.nextInt();
        }
        // taking input array 2
        System.out.println("Enter size of second array:");
        int size2 = sc.nextInt();
        int arr2[] = new int[size2];
        System.out.println("Enter array elements:");
        for (int i=0; i<size2; i++) {
            arr2[i] = sc.nextInt();
        }
        sc.close();
        
        merge(arr1, arr2);

        System.out.println("Sorted arrays are:");
        for (int i = 0; i < size1; i++) {
            System.out.print(arr1[i] + " ");
        }
        System.out.println();
        for (int i = 0; i < size2; i++) {
            System.out.print(arr2[i] + " ");
        }
	}
}
/**
 * Sample input/output
 * Enter size of first array:
 * 6
 * Enter array elements:
 * 1 8 9 15 16 18
 * Enter size of second array:
 * 4
 * Enter array elements:
 * 2 4 7 10
 * Sorted arrays are:
 * 1 2 4 7 8 9 
 * 10 15 16 18
 * 
 * Time complexity: O(m*n)
 * where m and n are sizes of the arrays
 * Space complexity: O(1)
 */


<|start_filename|>C/cp/two_pointers_method.c<|end_filename|>
/*
Given a sorted array A, size of N ( N elements) and a target value X,
find if there exists any pair of elements in the Array such that their total sum is equal to X.
we can solve this by using Two pointers Method.
Two pointers Method is a method where one pointer starts from beginning
and other from the end and they proceed towards each other simultaneously.
*/

#include <stdio.h>

// this Pair_exist_by_Two_Pointer_Method will tell us whether pair exists or not
int Pair_exist_by_Two_Pointer_Method(int ar[], int N, int X)
{
    int i = 0, j = N - 1, cur_sum = 0;
    while(i < j)
    {
        cur_sum = ar[i] + ar[j];
        if(cur_sum == X)
        {
            // means you got our expected pair
            return 1;
        }
        else if(cur_sum < X)
        {
            // we will move in right direction
            i++;
        }
        else if (cur_sum > X )
        {
            // we will move in left direction
            j--;
        }
    }
    // we don't get our pair
    return 0;
}

int main()
{
    int N, X;
    printf("Enter array size and target value\n");
    scanf("%d %d", &N, &X);
    int ar[N + 1];
    printf("Enter array elements \n");
    int i;
    for(i = 0; i < N; i++)
    {
        scanf("%d", &ar[i]);
    }
    int solve = Pair_exist_by_Two_Pointer_Method(ar , N , X);
    if(solve)
    {
        printf("Pair found and their total sum is equal to target value\n");
    }
    else
    {
       printf("Pair doesn't exist in the array\n");
    }
}

/*
Standard Input and Output

Enter array size and target value
6 70
10 20 35 50 75 80
Pair found and their total sum is equal to target value

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

*/


<|start_filename|>Java/other/FindGCDOfTwoNo.java<|end_filename|>
import java.util.*;

/*
A program to find the gcd of two numbers
GCD= Greatest common divisor
*/

public class FindGCDOfTwoNo{

    private static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {

        //taking the two numbers as input from the user
        System.out.println("Kindly enter the two numbers: ");
        int a = sc.nextInt();
        int b = sc.nextInt();

        int gcd = findgcd(a,b);

        System.out.println("The GCD of "+a+" and "+b+" = "+gcd);
    }

    //method to find the gcd of two numbers
    private static int findgcd(int a, int b) 
    {
        //the loop executes until the two numbers are equal to each other
        while(a!=b)   
        {  
            if(a>b)  
                a=a-b;  
            else  
                b=b-a;  
        }  
        return b;
    }
}

/*
Output:

Kindly enter the two numbers:
14
16
The GCD of 14 and 16 = 2

Kindly enter the two numbers:
18
1034
The GCD of 18 and 1034 = 2

Kindly enter the two numbers:
48
120
The GCD of 48 and 120 = 24

*/



<|start_filename|>C-Plus-Plus/cp/remove_spaces_from_a_string.cpp<|end_filename|>
/*
Given a string , remove spaces from it and then return new string. We can solve it By using getline function in C++ and then get a new string.
*/
#include <bits/stdc++.h>
using namespace std;
string new_string(string s)
{

    stringstream s2(s);
    string tem;

    // Making the string empty
    s = "";

    // Running loop till end of stream
    // and getting every word
    while (getline(s2, tem, ' ')) {
       s += tem;
    }
    return s;
}

int main()
{
    cout << "Enter the string\n";
    string s;
    getline(cin , s);
    cout << "After Removing Spaces the New String is : ";
    cout << new_string(s) << endl;
}
/*

Standard Input and Output

Input : I am a Open Source Contributor in GSSoC'21
Output : IamaOpenSourceContributorinGSSoC'21

Time Complexity : O(N) // String size
Space Complexity : O(N) // an intermediate string

*/


<|start_filename|>C-Plus-Plus/cp/Is_Valid_Sudoku.cpp<|end_filename|>
/*
Introduction 
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
- Each row must contain the digits 1-9 without repetition.
- Each column must contain the digits 1-9 without repetition.
- Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.

Note:
- A Sudoku board (partially filled) could be valid but is not necessarily solvable.
- Only the filled cells need to be validated according to the mentioned rules.

Argument/Return Type
Input of 9x9 matrix is taken
A function which returns bool is implemented
*/

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

// Function to determine if the sudoku is valid
bool isValidSudoku(vector<vector<char>>& sudoku) 
{
    /*Define 2D maps to store presence of already visited values 
      row wise , column wise and box wise */
    map<int,map<int,int>>row;
    map<int,map<int,int>>col;
    map<int,map<int,int>>box;

    // Now Traverse to every cell
    for(int rowInd=0;rowInd<=8;rowInd++)
    {
       //In each row visit all cells column wise
       for(int colInd=0;colInd<=8;colInd++)
       {
           // If the cell is not empty
           if( sudoku[rowInd][colInd] != '.')
            {
                // Get the relative ASCII value of character 
                int value = sudoku[rowInd][colInd]-'0';

                /* Check if the this value is already present in 
                   the column or row or box to which this value belongs to */
                bool isPresentInRow = row[value][rowInd];
                bool isPresentInCol = col[value][colInd];
                bool isPresentInBox = box[value][3*(rowInd/3)+(colInd/3)];
                if(isPresentInRow || isPresentInCol || isPresentInBox)   
                {
                   /*If it is present in any of them already
                    It means that the sudoku is not valid */
                   return false; 
                }    
                else
                {
                   /* else if value is not present in any of them 
                      increment corresponding map values 
                      to indicate the prescence of this value */
                    row[value][rowInd]++;
                    col[value][colInd]++;
                    box[value][3*(rowInd/3)+(colInd/3)]++;
                }    
            }
       }
    }
    //If vailidity is not failed for any cell return true
    return true;   
}


// Driver code
int main()
{
    //create a vector to take input and store them
    vector<vector<char>>sudoku;

    for(int row=0;row<9;row++)
    {
        cout<<"Enter cell values of row "<<row+1<<" with spaces between them , If any cell is empty enter '.' : ";
        vector<char>rowValues;
        for(int col=0;col<9;col++)
        {
           char value;
           cin>>value;
           rowValues.push_back(value);
        }
        sudoku.push_back(rowValues);
    }   

    //Call the function and print the result
    if(isValidSudoku(sudoku))
        cout<<"Hence the given sudoku is valid";
    else
        cout<<"Hence the given sudoku is not valid";

    return 0; 
}
    
/*
Input:
1 <= cell value <= 9
If cell is empty '.' is entered

Sample Test Case 1  

Input Format : 
Example :
Enter cell values of row 1 with spaces between them , If any cell is empty enter '.' : 5 3 . . 7 . . . .
Enter cell values of row 2 with spaces between them , If any cell is empty enter '.' : 6 . . 1 9 5 . . .
Enter cell values of row 3 with spaces between them , If any cell is empty enter '.' : . 9 8 . . . . 6 .
Enter cell values of row 4 with spaces between them , If any cell is empty enter '.' : 8 . . . 6 . . . 3
Enter cell values of row 5 with spaces between them , If any cell is empty enter '.' : 4 . . 8 . 3 . . 1
Enter cell values of row 6 with spaces between them , If any cell is empty enter '.' : 7 . . . 2 . . . 6
Enter cell values of row 7 with spaces between them , If any cell is empty enter '.' : . 6 . . . . 2 8 .
Enter cell values of row 8 with spaces between them , If any cell is empty enter '.' : . . . 4 1 9 . . 5
Enter cell values of row 9 with spaces between them , If any cell is empty enter '.' : . . . . 8 . . 7 9

Output Format :
Example : ( Output to the above input example ) 
Hence the given sudoku is valid

Time/Space Complexity
Time Complexity : O(1) 
Space Complexity : O(1) 

*/


<|start_filename|>Java/cp/String_to_int.java<|end_filename|>
import java.util.*;
import java.lang.*;
import java.io.*;

class String_to_int {
    public int myAtoi(String str) {
        if (str.length() == 0) return 0;
        
        String ans = "";
        if (str.length() > 2 ){     // for TESTCASE "+-6"
            if (str.charAt(0) == '-' && str.charAt(1) == '+') return 0;
            if (str.charAt(1) == '-' && str.charAt(0) == '+') return 0;
        }
        
        for (int i = 0 ; i < str.length(); i++){
	    
	    // ith Character of String str 
            char c = str.charAt(i);
            if (ans.length() > 0 && !(c >= '0' && c <= '9')) break;
            else if (str.charAt(i) == ' ') continue;
            else if (str.charAt(i) == '-') ans += str.charAt(i);
            else if (str.charAt(i) == '+') ans += str.charAt(i);
            
            else if (c >= '0' && c <= '9') ans += c;
            else if (ans.length() == 0 && !(c >= '0' && c <= '9')) break;
           
        }
        
        if (ans.length() == 0) return 0;
        if (ans.equals("-") || ans.equals("+")) return 0;
        // if (ans.length() > 9) 
        
        int max = Integer.MAX_VALUE;
        int digits_max = (int)Math.floor(Math.log10(max) + 1);  // hete it is 9 always 
        
        int min = Integer.MIN_VALUE;
        
        long count_0 = 0;
        for (int  i= 0 ; i < ans.length(); i++){
            if (ans.charAt(i) == '-' || ans.charAt(i) == '+') {
                count_0 ++;
                continue;
            }
            if (ans.charAt(i) != '0') break;
            count_0 ++;
            
        }
        
        if (ans.length() - count_0 > digits_max){
            if (ans.charAt(0) == '-') return min;
            return max;
        }
        
        long temp = Long.parseLong(ans) ;
        if (temp > Integer.MAX_VALUE) return Integer.MAX_VALUE;
        else if (temp < Integer.MIN_VALUE) return Integer.MIN_VALUE;
        
         return Integer.valueOf(ans);
    }
}

/*
TEST CASE

TIME COMPLEXITY : 0(N) 
SPACE COMPLEXITY: 0(N)

where N is length of given string

INPUT
"   -42"

OUTPUT
-42

INPUT
 "\n 12 4193 with words"

OUTPUT
0

INPUT
 "words and 987"

OUTPUT
0
*/



<|start_filename|>C-Plus-Plus/cp/all_possible_sums_using_fft.cpp<|end_filename|>
/*
We are given two arrays a[] and b[].
We have to find all possible sums a[i]+b[j], 
and for each sum count how often it appears.
Let the size of array a be n and array b be m.
Sample Input: 
3 2
1 2 3
4 5
Sample Output:
5 1
6 2
7 2
8 1
Large Data file: https://bit.ly/3l8Zo9q
Output file: https://bit.ly/3jqnz2C 
Constraints:
1<=n<=1e5
1<=m<=1e5
0<=ai<=1e4
0<=bi<=1e4
Time Limit: 1 sec
My Solution using Fast Fourier Transform:
We construct for the arrays a and b two polynomials A and B. 
The numbers of the array will act as the exponents in the polynomial (a[i]⇒xa[i]); 
and the coefficients of this term will by how often the number appears in the array.
Then, by multiplying these two polynomials in O(nlogn) time, we get a polynomial C, 9
where the exponents will tell us which sums can be obtained, 
and the coefficients tell us how often
Recorded Time for boundary limits:
n=1e5
m=1e5
0<=ai,bi<=1e4
Efficiency: O((n+m)log(n+m))
Execution Time: 0.621 secs
Language: C++17
for more details on this algorithm goto
https://cp-algorithms.com/algebra/fft.html
*/


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

using cd=complex<double>;
//Range is the maximum limit of ai & bi together
#define RANGE 1e4
const double PI = acos(-1);

//standard Fast Fourier Transform Algorithm
void fft(vector <cd> &a, bool invert) 
{
    int n = a.size();
    for (int i = 1, j = 0; i < n; i++) 
    {
        int bit = n>>1;
        for (; j & bit; bit>>=1)
            j ^= bit;
        j ^= bit;
        if (i < j) 
        	swap(a[i], a[j]);
    }
    for (int len = 2; len <= n; len<<=1) 
    {
        double ang=2*PI/len*(invert?-1:1);
        cd wlen(cos(ang),sin(ang));
        for(int i=0;i<n;i+=len) 
        {
            cd w(1);
            for (int j = 0; j < len/2; j++) 
            {
                cd u = a[i + j], v = a[i + j + len/2] * w;
                a[i + j] = u + v;
                a[i + j + len/2] = u - v;
                w *= wlen;
            }
        }
    }
    if (invert) 
    	for (cd &x : a) 
    	    x /= n;
}

/*This function works with polynomials with integer coefficients, 
however you can also adjust it to work with other types. 
Since there is some error when working with complex numbers, 
we need round the resulting coefficients at the end.*/
vector<int> multiply(vector <int> const &a, vector <int> const &b) 
{
    vector <cd> fa(a.begin(), a.end());
    vector <cd> fb(b.begin(), b.end());
    int n = 1;
    while (n < a.size() + b.size())
        n <<= 1;
    fa.resize(n);
    fb.resize(n);
    fft(fa, false);
    fft(fb, false);
    for (int i = 0; i < n; i++)
        fa[i] *= fb[i];
    fft(fa, true);
    vector <int> result(n);
    for (int i = 0; i < n; i++)
        result[i] = round(fa[i].real());
    return result;
}

int main()
{
    //declare and read the values of a and m;
    int n, m, temp; 
    cin >> n >> m;
    //declare and read the values of a[] of size n 
    //at the same time create the polynomial A
    vector <int> A(RANGE, 0);
    for (int i = 0; i < n; i++)
    {
        cin >> temp;
        A[temp]++;
    }
    //declare and read the values of a[] of size n 
    //at the same time create the polynomial B
    vector <int> B(RANGE, 0);
    for (int i = 0; i < m; i++)
    {
        cin >> temp;
        B[temp]++;
    }
    //apply the algorithm to compue the sums and
    //their respective frequency
    vector <int> ans = multiply(A, B);
    for (int i = 0; i < ans.size(); i++)
        //if the the frequency is not zero then the value exists
        if (ans[i] != 0) 
            cout << i << " " << ans[i] << endl;
    return 0;
}


<|start_filename|>C-Plus-Plus/graphs/left_view_of_tree.cpp<|end_filename|>
/*
   This program will print Left view of tree by using concept of Depth First Search with some modification
 */

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

struct node {
	node(int x): data(x), left_child(NULL), right_child(NULL) {}
	int data;
	node *left_child;
	node *right_child;
};

class bin_tree {
	node *root;
  public:
	// constructor of tree
	bin_tree() {
		root = NULL;
	}
	void insert_data(int x) {
		//if tree is empty
		if (!root) {
			node *tnode = new node(x);
			root = tnode;
		}
		//if tree if not empty
		else {
			node *temp = root;
			while (1) {
				//if data to be inserted is less then the data of current node
				if (x < temp->data ) {
					//if left child of current node is node present
					///we simple add new node with the data to be inserted
					if (!temp->left_child) {
						node *tnode = new node(x);
						temp->left_child = tnode;
						break;
					}
					//else we change the current node pointer 
					//with pointer of left child node pointer
					else
						temp = temp->left_child;
				}
				//if data to be inserted is grater then 
				//or equal to the data of current node
				else {
					//if right child of current node is node present 
					//we simple add new node with the data to be inserted
					if (!temp->right_child) {
						node *tnode = new node(x);
						temp->right_child = tnode;
						break;
					}
					//else we change the current node pointer 
					//with pointer of left child node pointer
					else
						temp = temp->right_child;
				}
			}
		}
	}
	void left_view(node* , int& , int );
	void left_view_of_tree();
};

void bin_tree :: left_view_of_tree() {
	
	int last = 0;
	int current = 1;
	left_view(root, last, current);
}

void bin_tree :: left_view(node* r, int &l, int c) {
	//if no node is found
	if (!r)
		return;
	//if we are at unvisited level
	if (c > l) {
		cout << r->data << " ";
		l++;
	}

	left_view(r->left_child, l, c + 1);
	left_view(r->right_child, l, c + 1);
}

int main() {
	bin_tree t;
	int n;
	cout << "Enter number of elements in tree: ";
	cin >> n;
	cout << "Enter elements to insert in  tree: ";
	while (n--) {
		int k; cin >> k;
		t.insert_data(k);
	}
	cout << "\nLeft View of tree:";
	t.left_view_of_tree();
	return 0;
}

/*
	Sample case 1:
	
	Enter number of elements in tree: 8
	Enter elements to insert in  tree: 50 40 60 55 30 56 70 45
	Left View of tree : 50 40 30 56
	     50
	  /     \
	 /       \
	40        60
	/   \     /   \
	/     \   /     \
	30    45  55      70
	        \
	         \
	         56

	.....................................................................
	Sample case 2:
	Enter number of elements in tree: 10
	Enter elements to insert in  tree: 50 40 30 45 60 55 54 70 75 72
	Left View of tree : 50 40 30 54 72
	     50
	  /     \
	 /       \
	40        60
	/   \     /   \
	/     \   /     \
	30    45   55      70
	       /        \
	      /          \
	      54        75
	                /
	               /
	               72
   
Time Complexity: O(n) 
Space Complexity: O(n)
*/


<|start_filename|>Java/math/check_strong_number.java<|end_filename|>

/*
Checking for a strong number using indirect recursion
Strong Number = 145
1! + 4! + 5! =145
sumOfFactorialOfDigit(int n) - extracts digit of n and calls factorial(n). Returns sum of factorial of digits
factorial(n)- returns factorial of extracted digits passed in the argument
*/

import java.util.*;
class check_strong_number {
    /*recursive function for sum of factorial of digits*/
    public static int sumOfFactorialOfDigit(int n)

    {
        if (n == 0)
            return n;
        else
            return (factorial(n % 10) + sumOfFactorialOfDigit(n / 10));

    }
    /*recursive function to find the factorial of n */
    public static int factorial(int n) {
        if (n == 0)
            return 1;
        else
            return (n * factorial(n - 1));
    }

    public static void main() {
        Scanner sc = new Scanner(System.in);
        System.out.print(" Enter Number. N = ");
        int num = sc.nextInt();
        if (num == sumOfFactorialOfDigit(num))
            System.out.println(" It is a Strong Number");
        else
            System.out.println(" It is not a Strong Number");
    }
}

/*
Sample Input And Output :
N = 145
It is a Strong Number
N = 534
It is not a Strong Number

Time Complexity : O(n)
Space Complexity : 1
*/


<|start_filename|>C-Plus-Plus/graphs/Depth_of_tree.cpp<|end_filename|>
/*
Depth of tree :- we can define depth of tree as total number of levels present in whole tree  tree.

Time Complexity: O(n)

Space Complexity: if tree is perfectly balanced tree O(log n)
		  if it is not perfectly balanced tree O(n)

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

struct node {
    node(int x): data(x), left_child(NULL), right_child(NULL) {}
    int data;
    node *left_child;
    node *right_child;
};

class bin_tree{
    node *root;
public:
   // constructor of tree
    bin_tree()
    {
        root = NULL;
    }
    void insert_data(int x){
        //if tree is empty
        if(!root)
        {
            node *tnode = new node(x);
            root = tnode;
        }
        //if tree if not empty
        else
        {
            node *temp =root;
            while(1)
            {
                //if data to be inserted is less then the data of current node
                if(x < temp->data )
                {
                    //if left child of current node is node present we simple add new node with the data to be inserted
                    if(!temp->left_child)
                        {
                            node *tnode = new node(x);
                            temp->left_child = tnode;
                            break;
                        }
                    //else we change the current node pointer with pointer of left child node pointer
                    else
                        temp = temp->left_child;
                }
                //if data to be inserted is grater then or equal to the data of current node
                else
                {
                    //if right child of current node is node present we simple add new node with the data to be inserted
                    if(!temp->right_child)
                        {
                            node *tnode = new node(x);
                            temp->right_child = tnode;
                            break;
                        }
                    //else we change the current node pointer with pointer of left child node pointer
                    else
                     temp = temp->right_child;
                }
            }
        }
    }

    int depth(node *level)
    {
        if(level == NULL)
        {
            return 0;
        }
        //depth of left subtree
        int left_depth = depth(level->left_child);
        //depth of right subtree
        int rigth_depth = depth(level->right_child);
        // depth of tree will max of depth of left subtree and depth of right subtree adding current node;
        return  max(left_depth,rigth_depth)+1;
    }
	
    //depth of whole tree
    int depth_of_tree()
    {
        return(depth(root));
    }
};
int main() {
    bin_tree t;
    int n;
    cout<<"Enter number of elements in tree: ";
    cin>>n;
    cout<< "Enter elements to insert in  tree: ";
    while(n--)
    {	
        int k; cin>>k;
        t.insert_data(k);
    }
    cout<<"\nDepth of tree:"<<t.depth_of_tree()<<endl;
    return 0;	
    /* 
    Sample case 1
    Enter number of elements in tree: 7
    Enter elements to insert in  tree: 50 60 40 55 30 70 45 
    Depth of tree : 3

         50                         level 1
      /     \
     /       \
    40        60                    level 2
   /   \     /   \
  /     \   /     \
30    45  55      70                level 3

......................................................................................................
    Sample case 2
    Enter number of elements in tree: 8
    Enter elements to insert in  tree: 50 40 60 55 30 56 70 45
    Depth of tree : 4

         50                         level 1
      /     \
     /       \
    40        60                    level 2
   /   \     /   \
  /     \   /     \
30    45  55      70                level 3
            \
             \
             56                     level 4
*/   
	
}


<|start_filename|>C-Plus-Plus/cp/zalgorithm.cpp<|end_filename|>
#include <bits/stdc++.h>
using namespace std;

void getZ(string s, int z[])
{
	int n = s.size();
	int left = 0, right = 0;
	for (int i = 1; i < n; ++i)
	{
		if (i > right)
		{
			left = right = i;
			while (right < n && s[right - left] == s[right])
				right++;
			z[i] = right - left;
			right--;
		}
		else
		{
			int k = i - left;
			if (z[k] < right - i + 1)
			{
				z[i] = z[k];
			}
			else
			{
				left = i;
				while (right < n && s[right - left] == s[right])
					right++;
				z[i] = right - left;
				right--;
			}
		}
	}
}

int main()
{
	string text, pattern;
	cout << "Enter the text: ";
	cin >> text;
	cout << "Enter the pattern: ";
	cin >> pattern;
	string concat = pattern + "$" + text;
	int n = concat.size();
	int m = pattern.size();
	int z[n];
	getZ(concat, z);
	for (int i = 0; i < n; ++i)
	{
		if (z[i] == m)
		{
			cout << "Pattern found at index " << i - m - 1 << "\n";
		}
	}
	return 0;
}

/*
Time Complexity: O(length of text + length of pattern)

Input
Enter the text: AABACAAFGAABAABA
Enter the pattern: AABA

Output
Pattern found at index 0
Pattern found at index 9
Pattern found at index 12
*/


<|start_filename|>Java/cp/MinimumWindowSubstring.java<|end_filename|>
/**
 * Minimum Window Substring 
 *          OR
 * Smallest Window in a String Containing All Characters of Another String
 * Given two strings string1 and string2, find the smallest substring in 
 * string1 containing all characters of string2. 
 */

import java.io.*;
public class MinimumWindowSubstring {
    
    static final int CHAR_COUNT = 26; 

    //Checking if all characters in pattern are contained in substring
    //or not
    public static boolean isValid(int[] str, int[] pattern) {
        for(int i=0; i<CHAR_COUNT; i++) {
            if(str[i] < pattern[i])
                return false; 
        }
        return true; 
    }

    public static String findSmallestSubstring(String str, String pattern) {

        //To store count of characters in str and pattern, respectively
        int strCount[] = new int[CHAR_COUNT];
        int ptrCount[] = new int[CHAR_COUNT]; 

        //Counting number of occurrences of each character in pattern
        for(int i=0; i<pattern.length(); i++) 
            ptrCount[pattern.charAt(i) - 'a']++; 

        int end, start;
        end = start = 0;
        String result = "-1"; //If no valid substring is found, "-1" is returned

        //start and end are pointers for start and end of substring
        while(end < str.length()) {

            //When substring does not contain all characters of pattern, we 
            //expand substring by adding characters from the end
            if(!isValid(strCount, ptrCount)) {
                strCount[str.charAt(end) - 'a']++; 
                end++; 
                continue; 
            } 

            //Updating substring contained in result
            if(result.equals("-1") || result.length() > (end - start))
                result = str.substring(start, end); 

            //To get length of smallest valid substring, we shorten the substring 
            //from front (i.e., eliminate characters from start)
            strCount[str.charAt(start) - 'a']--; 
            start++; 
        }

        //For the substrings which end at (str.length() - 1)
        while(isValid(strCount, ptrCount)) {
            if(result.equals("-1") || result.length() > (end - start))
                result = str.substring(start, end);
            strCount[str.charAt(start) - 'a']--; 
            start++;
        }

        return result; 
    }

    public static void main(String[] args) throws IOException {
        InputStreamReader read = new InputStreamReader(System.in);
	    BufferedReader buf = new BufferedReader(read); 

        //Taking input from user
        System.out.println("Enter a String text: ");
        String str = buf.readLine().trim();  
        System.out.println("Enter a String pattern: ");
        String pattern = buf.readLine().trim(); 

        //Printing output
        System.out.println("Smallest substring in text, containing all " +
                            "characters in pattern: ");
        System.out.println(findSmallestSubstring(str, pattern)); 
    }

}

/*
    Time complexity: O(N) (considering that isValid() method works in constant 
                        time as it makes a fixed number of comparisons) 
    Space complexity: O(CHAR_COUNT) 

    TEST CASES

    INPUT
    Enter a String text: 
    zaaskzaa
    Enter a String pattern: 
    zsk
    OUTPUT
    Smallest substring in text, containing all characters in pattern: 
    skz

    INPUT
    Enter a String text: 
    pompandpageantrygalore
    Enter a String pattern: 
    gtyn
    OUTPUT
    Smallest substring in text, containing all characters in pattern: 
    ntryg

 */


<|start_filename|>C-Plus-Plus/ds/Sparse_Matrix_Representation.cpp<|end_filename|>
// C++ program for Sparse Matrix Representation
// using Array
//A matrix is a two-dimensional data object made of m rows and n columns,
//therefore having total m x n values. If most of the elements
//of the matrix have 0 value, then it is called a sparse matrix.
#include <iostream>
using namespace std;
class Element
{
public:
    int row;
    int colmn;
    int entry;
};
class Sparse
{
private:
    int m;
    int n;
    int num;
    Element *ele;
public:
    Sparse(int m,int n,int num)
    {
    this->m=m;
    this->n=n;
    this->num=num;
    ele=new Element[this->num];
        }
    ~Sparse()
    {
    delete [] ele;
    }
    Sparse operator+(Sparse &s);
    friend istream & operator>>(istream &is,Sparse &s);
    friend ostream & operator<<(ostream &os,Sparse &s);
};
Sparse Sparse::operator+(Sparse &s)
{
    int row,colmn,new_index;
    if(m!=s.m || n!=s.n)
        return Sparse(0,0,0);
    Sparse *sum=new Sparse(m,n,num+s.num);
    row=colmn=new_index=0;
    while(row<num && colmn<s.num)
    {
        if(ele[row].row<s.ele[colmn].row)
            sum->ele[new_index++]=ele[row++];
        else if(ele[row].row > s.ele[colmn].row)
            sum->ele[new_index++]=s.ele[colmn++];
        else
        {
        if(ele[row].colmn<s.ele[row].colmn)
            sum->ele[new_index++]=ele[row++];
        else if(ele[row].colmn > s.ele[colmn].colmn)
            sum->ele[new_index++]=s.ele[colmn++];
        else
        {
            sum->ele[new_index]=ele[row];
            sum->ele[new_index++].entry=ele[row++].entry+s.ele[colmn++].entry;
        }
        }
    }
    for(;row<num;row++)sum->ele[new_index++]=ele[row];
    for(;colmn<s.num;colmn++)sum->ele[new_index++]=s.ele[colmn];
    sum->num=new_index;
    return *sum;
}
    istream & operator>>(istream &is,Sparse &s)
    {
        cout<<"Enter non-zero elements";
        for(int row=0;row<s.num;row++)
            cin>>s.ele[row].row>>s.ele[row].colmn>>s.ele[row].entry;
        return is;
    }
    ostream & operator<<(ostream &os,Sparse &s)
    {
    int new_index=0;
    for(int row=0;row<s.m;row++)
    {
        for(int colmn=0;colmn<s.n;colmn++)
        {
        if(s.ele[new_index].row==row && s.ele[new_index].colmn==colmn)
            cout<<s.ele[new_index++].entry<<" ";
        else
            cout<<"0 ";
        }
        cout<<endl;
    }
    return os;
}
int main()
{
    int m;
    int n ;
    int num;
    cout<<"Enter No of Row " <<endl;
    cin>>m;
    cout<<"Enter No of Column " <<endl;
    cin>>n;
    cout<<"Enter No of Non-zero Entry " <<endl;
    cin>>num;
    Sparse s1(m,n,num);
    Sparse s2(m,n,num);

    cin>>s1;
    cin>>s2;
    Sparse sum=s1+s2;
    cout<<"First Matrix"<<endl<<s1;
    cout<<"Second Matrix"<<endl<<s2;
    cout<<"Sum Matrix"<<endl<<sum;
    return 0;

/*
Enter No of Row
5
Enter No of Column
5
Enter No of Non-zero Entry
5
Enter non-zero elements
0 0 1
1 1 1
2 2 1
3 3 1
4 4 1
Enter non-zero elements
0 0 2
1 0 2
2 0 2
3 0 2
4 0 2
First Matrix
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
Second Matrix
2 0 0 0 0
2 0 0 0 0
2 0 0 0 0
2 0 0 0 0
2 0 0 0 0
Sum Matrix
3 0 0 0 0
2 1 0 0 0
2 0 1 0 0
2 0 0 1 0
2 0 0 0 1

*/
}


<|start_filename|>C-Plus-Plus/graphs/Articulation_points.cpp<|end_filename|>
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<ll> vl;
typedef set<ll> sl;
#define pb push_back

#define loop(x,n) for(ll x = 1; x <= n; ++x)

//Adjacency List of an Undirected Graph
vl graph[100001];

bool vis[100001];

ll in[100001], low[100001];

ll timer = 1;

//set to store unique articulation points
sl cut_vertices;
sl::iterator itr;

void dfs(ll source, ll parent) {
	vis[source] = true;
	in[source] = low[source] = timer;
	timer++;
	ll children = 0;
	for (auto child : graph[source]) {

		//if child equal to parent
		if (parent == child) continue;

		if (vis[child] == true)
			//back edge
			low[source] = min(low[source], in[child]);

		else {
			dfs(child, source);

			//visited forward edge
			low[source] = min(low[source], low[child]);

			//condition for having a articulation point
			if (low[child] >= in[source] && parent != -1)
				cut_vertices.insert(source);

			children++;
		}
	}

	//condition for source vertex for having a cut vertex
	if (parent == -1 && children > 1 )
		cut_vertices.insert(source);

}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);

	ll n, m, a, b;
	//n=no. of vertices, m=no. of edges
	cin >> n >> m;

	loop(i, m) {
		cin >> a >> b;
		graph[a].pb(b);
		graph[b].pb(a);
	}

	loop(i, n) {
		//initialise visited array as false;
		vis[i] = false;
	}

	loop(i, n) {
		//dfs call
		if (vis[i] == false) dfs(i, -1);
	}

	//print articulation points
	cout << "Artciulation points:\n";
	for (itr = cut_vertices.begin(); itr != cut_vertices.end(); ++itr)
		cout << *itr << " ";
	return 0;
}

/*
Input:
First line contains two space separated integers,(n,m)
n- no of vertices, m- no of edges.
Then m lines follow, each line has 2 space separated integers ui ,vi which denotes edge between vertex ui to vi.


TEST CASE
5 5
1 2
1 3
2 3
3 4
4 5

OUTPUT
Artciulation points:
3 4

Time- complexity: O(n+m)

Space Complexity: O(n)
*/


<|start_filename|>C-Plus-Plus/other/SwapTwoNibbles.cpp<|end_filename|>
//Given a byte, swap the two nibbles in it. For example 100 is be represented as 01100100 in a byte (or 8 bits).
//The two nibbles are (0110) and (0100). If we swap the two nibbles, we get 01000110 which is 70 in decimal.

#include <iostream>
using namespace std;
int main()
{
    int swapNibbles(int n);
    int n, result;
    cout << "Enter a number: ";
    cin >> n;
    result = swapNibbles(n);
    cout << result;

    return 0;
}

int swapNibbles(int n)
{
    return (((n & 0x0F) << 4) | ((n & 0xF0) >> 4));
}

/*
Input:
Enter a number: 100

Output: 
70

Time complexity: O(1)
*/

<|start_filename|>C-Plus-Plus/other/Kth_largest_element.cpp<|end_filename|>
/*
Q Kth largest element 

Given an array a[] and a number K where K is smaller than size of array, 
the task is to find the Kth largest element in the given array.
It is given that all array elements are distinct. */


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

//find the kth largest Element
void kthLargestElement(int a[], int size, int k){

    priority_queue <int, vector<int>, greater<int>> minHeap;
    
    for(int i = 0; i < size; i++){
        minHeap.push(a[i]);
        
        if(minHeap.size() > k){
            minHeap.pop();
        }
    }
    cout<< "Kth largest element in the array is: "<< minHeap.top();
}

int main()
{
    int size, k; 
    
    cout << "Enter the size of an Array : ";
    cin >> size;

    cout << "Enter the value of k : ";
    cin>> k;

    cout<< "Enter the elements of the array: " << endl;
    
    int a[size];
    

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

    kthLargestElement(a,size,k);  
    
    return 0;
}

/*
Input 
Enter the size of an Array : 7                                                                                                                
Enter the value of k : 3                                                                                                                      
Enter the elements of the array:                                                                                                              
7 5 9 8 6 4 10      

Output
Kth largest element in the array is: 8

Space complexity => O(k)
Time complexity => O(nlogk)
*/

<|start_filename|>C-Plus-Plus/sort/Bead_Sort.cpp<|end_filename|>
/* Bead sort, also called as gravity sort, is a natural sorting algorithm since this algorithm was inspired
from natural phenomenons and was designed keeping in mind objects(or beads) falling under the influence of gravity.
The bead sort operation can be compared to the manner in which beads slide on parallel poles, such as on an abacus.
However, each pole may have a distinct number of beads. */

// Header file to include STL library
#include <bits/stdc++.h>
//For cin and cout
using namespace std;

void beadSort(vector<int>& nums)
{
    // find maximum element in vector
    auto max = *max_element(nums.begin(), nums.end());

    // declare beads vector for sorting
    vector<unsigned char> beads(max * nums.size(), 0);

    // initialize the beads accordingly
    for(auto i = 0; i < nums.size(); i++)
        for(auto j = 0; j < nums[i]; j++)
            beads[i * max + j] = 1;

    // Use gravity to let beads fall
    for(auto j = 0; j < max; j++)
    {
        int sum = 0;
        // assign beads for each post
        for(auto i = 0; i < nums.size(); i++)
        {
            sum += beads[i * max + j];
            beads[i * max + j] = 0;
        }
        // Use gravity to bring beads down
        for(auto i = nums.size() - sum; i < nums.size(); i++)
            beads[i * max + j] = 1;
    }
    // put sorted beads back into vector
    for(auto i = 0; i < nums.size(); i++)
    {
        for(auto j = 0; j < max && beads[i * max + j]; ++j)
            nums[i] = j+1;
    }

}

int main()
{
    // initialize a vector of integers
    vector<int> nums;
    // Declaration of required variables
    int a,n;
    cout<<"Enter the number of elements :";
    cin>>n;
    cout<<"Enter the elements to be sorted : ";
    //For loop for taking elements from the user, can be space-separated as well
    for(int i=0;i<n;i++){
        cin>>a;
        nums.push_back(a);
    }

    // reserve static vector for optimal performance gain
    nums.reserve(n);

    // Print vector before sorting
    cout << "\nBefore sorting" << endl;
    for(auto const& i: nums)
        cout<<i<<" ";
    cout<<"\n";

    beadSort(nums);

    //For loop for printing out the array after sorting
    cout << "After sorting" << endl;
    for(auto const& i: nums)
        cout << i << " ";
    cout << endl;

    // Free memory space of vector
    nums.shrink_to_fit();
}

/*

Input:
Enter the number of elements :5
Enter the elements to be sorted : 4 6 3 2 8

Before sorting
4 6 3 2 8

Output:
After sorting
2 3 4 6 8

Time Complexities:
Bead sort can be implemented with four general levels of complexity, among others:
O(n): in best case
O(S): in worst case, where S is the sum of all beads

*/


<|start_filename|>C/ds/Spiral_Matrix.c<|end_filename|>
/*Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
*/
#include <stdio.h>

void spiral_matrix(int[][10], int, int);
int main()
{
	int ROW, COLUMN, is_null = 0;

	printf("Enter Row: ");
	scanf("%d", &ROW);

	printf("Enter column: ");
	scanf("%d", &COLUMN);

	int matrix[10][10];

	for (int i = 0; i < ROW; i++)
	{
		for (int j = 0; j < COLUMN; j++)
		{
			scanf("%d", &matrix[i][j]);
			if (matrix[i][j] == 0)
				is_null++;
		}
	}

	if (is_null == ROW *COLUMN)
	{
		printf("\nNull Matrix\n");
	}
	else
	{
		printf("Entered Matrix:\n");
		for (int i = 0; i < ROW; i++)
		{
			printf("\n");
			for (int j = 0; j < COLUMN; j++)
			{
				printf("%d", matrix[i][j]);
				printf("\t");
			}
		}

		spiral_matrix(matrix, ROW, COLUMN);
	}

	return 0;
}

// Prints the spiral matrix of the given matrix
void spiral_matrix(int matrix[][10], int ROW, int COLUMN)
{
	printf("\n\nSpiral Order Of the Matrix: \t");
	int i;
	int first_row = 0, first_column = 0;

	while (first_row < ROW && first_column < COLUMN)
	{
		/*Print the first row from the remaining rows */
		for (i = first_column; i < COLUMN; ++i)
		{
			printf("%d ", matrix[first_row][i]);
		}

		first_row++;

		/*Print the last column from the remaining columns */
		for (i = first_row; i < ROW; ++i)
		{
			printf("%d ", matrix[i][COLUMN - 1]);
		}

		COLUMN--;

		/*Print the last row from the remaining rows */
		if (first_row < ROW)
		{
			for (i = COLUMN - 1; i >= first_column; --i)
			{
				printf("%d ", matrix[ROW - 1][i]);
			}

			ROW--;
		}

		/*Print the first column from the remaining columns */
		if (first_column < COLUMN)
		{
			for (i = ROW - 1; i >= first_row; --i)
			{
				printf("%d ", matrix[i][first_column]);
			}

			first_column++;
		}
	}
}

/*
Sample Output
Enter Rows:2
Enter Column: 2
1	2
3	4

Entered Matrix:
1	2 
3 	4

Spiral Order of the Matrix: 1 2 4 3

Time Complexity: O(ROW*COLUMN)
Space Complexity:O(1).

*/



<|start_filename|>C-Plus-Plus/math/matrix_transpose.cpp<|end_filename|>
/*
Matrix is a 2-D array.
The transpose of a matrix is simply a flipped version of the original matrix.
Transpose of a matrix can be computed by switching its rows with its columns.
This code gives output as transpose of input matrix.
*/

#include<iostream>
using namespace std ;

//Function that computes transpose.
void transpose(int frows, int fcolumns, int **finput_matrix, int **ftranspose_matrix)
{
    int i = 0, j = 0 ;
    for(i=0 ; i<fcolumns ; ++i)
    {
        for(j=0 ; j<frows ; ++j)
        {
            //According to definition of transpose, each element of transpose matrix is assigned.
            ftranspose_matrix[i][j] = finput_matrix[j][i] ;
        }
    }
}

int main(void)
{
    int **input_matrix = NULL, **transpose_matrix = NULL ;
    int rows = 0, columns = 0, i = 0, j = 0 ;

    //Taking input as number of rows and columns.
    cout << "Enter the number of rows in matrix : " << endl ;
    cin >> rows ;
    cout << "Enter the number of columns in matrix : " << endl ;
    cin >> columns ;

    //Assigning the memory to the 2_D array according to input matrix size.
    input_matrix = new int*[rows] ;
    for(i=0 ; i<rows ; ++i)
    {
        input_matrix[i] = new int[columns] ;
    }

    cout << "Enter the elements of matrix in row wise manner separated by space : " << endl ;
    //Taking user input as each element of matrix.
    for(i=0 ; i<rows ; ++i)
    {
        for(j=0 ; j<columns ; ++j)
        {
            cin >> input_matrix[i][j] ;
        }
    }

    //Assigning the memory to the transpose matrix. It will have reversed rows and columns as that of input matrix.
    transpose_matrix = new int*[columns] ;
    for(i=0 ; i<columns ; ++i)
    {
        transpose_matrix[i] = new int[rows] ;
    }

    //Call to the function that computes the transpose.
    transpose(rows , columns , input_matrix , transpose_matrix) ;

    //Display input matrix on the screen.
    cout << "The input matrix is : " << endl ;
    for(i=0 ; i<rows ; ++i)
    {
        for(j=0 ; j<columns ; ++j)
        {
            cout << input_matrix[i][j] << " " ;
        }
        cout << endl ;
    }
    cout << endl ;

    //Display the transpose of input matrix on the screen.
    cout << "The transpose matrix of above matrix is : " << endl ; 
    for(i=0 ; i<columns ; ++i)
    {
        for(j=0 ; j<rows ; ++j)
        {
            cout << transpose_matrix[i][j] << " " ;
        }
        cout << endl ;
    }

    //Deallocate the memory assigned to input matrix as well as transpose of it.
    for(i=0 ; i<rows ; ++i)
    {
        delete[] input_matrix[i] ;
    }
    delete[] input_matrix ;

    for(i=0 ; i<columns ; ++i)
    {
        delete[] transpose_matrix[i] ;
    }
    delete[] transpose_matrix ;
    return 0 ;
}

/*
Sample I/O :
I/P :
2
3
1 2 3 4 5 6 

O/P :
1 4 
2 5
3 6

Explanation: Here, rows=2 & columns=3. On next line, each element of matrix is entered in rowwise manner separated by space.
So input matrix is:   1 2 3
                      4 5 6
The code gives output as its transpose.


Time Complexity : O(mn)  , where m = number of rows & n = number of columns
Space Complexity : Transpose matrix requires extra storage same as input matrix. So space complexity becomes O(mn).
*/



<|start_filename|>Julia/search/linear_search.jl<|end_filename|>
"""Julia program to implement Linear Search algorithm.
Given an array, Linear Search searches for an element by traversing the entire array once
and comparing each element with the element to be found out.
"""

function linear_search(arr, n, ele)
    # Traverse the entire array once
    for i in 1:n
        if(arr[i] == ele)
            return true
        end
    end
    return false
end


print("How many numbers are present in the array? ")
n = readline()
n = parse(Int, n)
if (n <= 0)
    println("Array is Empty!!!")
    exit()
end
arr = Int[]
print("Enter the numbers: ")
arr = [parse(Int, num) for num in split(readline())] 
print("Which number do you want to search in the array? ")
ele = readline()
ele = parse(Int, ele)
res = linear_search(arr, n, ele)
if res
    print("The number $ele is present in the array.")
else
    print("The number $ele is not present in the array")
end


"""
Time Complexity - O(n), where 'n' is the size of the array
Space Complexity - O(n)

SAMPLE INPUT AND OUTPUT

SAMPLE I

How many numbers are present in the array? 5 
Enter the numbers: 1 2 3 4 5
Which number do you want to search in the array? 6
The number 6 is not present in the array

SAMPLE II

How many numbers are present in the array? 3
Enter the numbers: 3 1 2
Which number do you want to search in the array? 2
The number 2 is present in the array.

"""


<|start_filename|>C-Plus-Plus/math/Hamming_Distance.cpp<|end_filename|>
/* Hamming Distance
-----------------
Problem: 
For given x and y, return the number of positions where their values differ in their binary representations as a 32-bit integer.

Implementation:
x = 10 (1010) and y = 6 (0110) if we apply xor to x and y the resultant ans = 12 (1100).
XOR is 0 when 2 bits are equal and 1 when 2 bits contrasts
Number of bits in ans = 2
*/

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

// O(N) time complexity
int solve1(int x, int y) 
{
    int ans = x^y;
    return __builtin_popcount(ans); 
}

// O(1) time complexity
int solve2(int x, int y) 
{
    int count = 0;
    for (int i = 0; i < 32; i++)
        if ( (x & (1 << i)) != (y & (1 << i)) )
            count++;
    return count;
}
int main()
{
    int x,y; 
    cin>>x>>y;
    cout<<solve2(x,y)<<endl;
}

/*
Input:
x = 10
y = 6
Output
2
*/

<|start_filename|>C/sort/circle_sort.c<|end_filename|>
// C++ program to implement Circle  Sort
#include <stdio.h>

// Helper function to swap to values
void swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
/*
Performs recursive circular swaps and returns value 1 if atleast one swap occurs
*/
int rec_sort(int arr[], int beg, int end)
{
    int isSwap = 0;

    // If concerned array is empty, Return
    if (beg == end)
        return 0;

    // Storing the values of beg, end to later use in the recursive call
    int begA, endA;
    for (begA = beg, endA = end; begA < endA; begA++, endA--)
    {
        //Compares the first and last elements
        if (arr[begA] > arr[endA])
        {
            swap(&arr[begA], &arr[endA]);
            isSwap = 1;
        }
    }

    // If the array has odd number of elements
    if (begA == endA)
        if (arr[begA] > arr[endA + 1])
        {
            swap(&arr[beg], &arr[endA + 1]);
            isSwap = 1;
        }

    int mid = (end - beg) / 2;
    int isSwapA = rec_sort(arr, beg, beg + mid);
    int isSwapB = rec_sort(arr, beg + mid + 1, end);

    return (isSwap || isSwapA || isSwapB);
}

void circle_sort(int arr[], int n)
{
    while (rec_sort(arr, 0, n - 1))
    {
    }
}

int main()
{
    int n;
    printf("\nHow many numbers do you want to sort? ");
    scanf("%d", &n);
    int arr[n];

    if (n <= 0)
    {
        printf("There are no numbers to sort!!!");
        return 0;
    }
    // Input the numbers to sort
    printf("Enter the numbers: ");
    for (int i = 0; i < n; i++)
        scanf("%d", &arr[i]);

    //Call the sort function
    circle_sort(arr, n);

    printf("The numbers in sorted order is: ");
    // Print the sorted array
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
    return 0;
}

/*

Time Complexity: O(n*log(n))
Space Complexity: O(n)

SAMPLE INPUT AND OUTPUT

SAMPLE 1

How many numbers do you want to sort? 5
Enter the numbers: 1 3 5 2 4
The numbers in sorted order is:  1  2  3  4  5

SAMPLE 2

How many numbers do you want to sort? 0
There are no numbers to sort!!!

*/


<|start_filename|>Java/sort/SleepSort.java<|end_filename|>
/*
    Sleep sort is a sorting algorithm used to sort non-negative integers. Sleep sort works by creating a separate thread for each item in the input which is to be sorted and then each thread sleeps for an amount of time which is proportional to the value of corresponding array element. Therefore, the thread which is having the least amount of sleep time wakes up first and the element gets printed and then the second least element and so on. The largest element wakes up after a long time and then the element gets printed at the last and thus the output obtained is a sorted array.
        
*/

import java.util.Scanner;
import java.util.concurrent.*;

public class SleepSort {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the number of elements in an array: ");
        int number = sc.nextInt();

        System.out.println("\nEnter the elements in an array: ");
        int array[] = new int[number];

        for (int i = 0; i < number; i++) {
            array[i] = sc.nextInt();

        }
        sleepSort(array);
    }

    public static void sleepSort(int[] array) {
        
        // CountDownLatch in java is used to make sure that a task waits for other threads before it starts.
        // Here the task is going to wait for threads which is equal to array length before it starts.
        final CountDownLatch countDone = new CountDownLatch(array.length);
        System.out.println("\nThe sorted array is: ");
        
        for (final int num : array) {
            // Creates a new thread.
            new Thread(new Runnable() {
                public void run() {
                    // Decrements the count of the countDone
                    countDone.countDown();
                    try {
                        //Causes the current thread to wait until the countDone has counted down to zero
                        countDone.await();
                        Thread.sleep(num);
                        System.out.println(num);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

}

/*
 * Output -
 * 
 * Enter the number of elements in an array: 7
 * 
 * Enter the elements in an array: 10 5 9 77 30 981 14
 * 
 * The sorted array is: 5 9 14 10 30 77 981
 *
 
Time Complexity -
    1. Best case - O(NlogN + max(input))
    2. Average case - O(NlogN + max(input))
    3. Worst case - O(NlogN + max(input))
    where N = number of elements in the input array, and array = input array elements
    
Space Complexity - O(N)
 
 */


<|start_filename|>C-Plus-Plus/cp/length_of_longest_substring_with_no_repeating_characters.cpp<|end_filename|>
/**
 * Length of Longest Substring Without Repeating Characters
 * Given a string, print the longest possible substring that has 
 * no repeating characters, i.e., all its characters are distinct. 
 * Consider a String contains upper and lower case alphabets.
 */

#include <bits/stdc++.h>
using namespace std;
int LongestSubstrNoRepeatingChar(string str)
{
    //2 pointer which denotes limits of current window
    int start = 0, end = 0;
    int len = str.length();
    //Maintain count of each character
    map<char, int> charCount;
    //Variable ans stores length og longest substring without repeating characters
    int ans = 0;
    while (end < len) {
        charCount[str[end]]++;
        //If window size and no. of distict elements are same
        //update ans
        if (charCount.size() == end - start + 1) {
            ans = max(ans, end - start + 1);
            end++;
        }

        else if (charCount.size() < end - start + 1) { //If there are repeating characters, we shorten substring by removing
            //characters from start, till we get a distinct substring.
            while (charCount.size() < end - start + 1) {
                charCount[str[start]]--;
                if (charCount[str[start]] == 0)
                    charCount.erase(str[start]);
                start++;
            }
            //move forward
            end++;
        }
    }
    return ans;
}

int main()
{
    //Taking input from user
    string str;
    cout << "Enter a string of alphabets: ";
    cin >> str;
    cout << "Length of longest substring with no repeating characters: ";
    cout << LongestSubstrNoRepeatingChar(str);
}

/*
	Test cases:

	INPUT:
	Enter a string of alphabets: xzvxzzvxxx
	OUTPUT:
	Length of longest substring with no repeating characters: 3

	INPUT:
	Enter a string of alphabets: PractisemakesanIndividualPerfect
	OUTPUT:
	Length of longest substring with no repeating characters: 10

	Time complexity: O(Length of String)
	Space complexity: O(52)

*/


<|start_filename|>C-Plus-Plus/math/Difference_of_Two_Strings.cpp<|end_filename|>
/*
DIFFERENCE OF TWO STRINGS
Problem Statement
    Given 2 strings a and b. String b has one more char added and shuffled. Find the char added in the string b.
Implementation 
    a. Using Hashmap (Slow approach and extra space)
    b. Using Bits Manipulation (Efficient Approach and no extra space)
*/

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

// Efficient Approach (Space - O(1) and time - O(N))
char bits_diff(string a, string b)
{
    char xorr = 0;
    int i = 0;
    for(i=0;i<a.size();i++){
        xorr ^= (a[i] ^ b[i]);
    }
    return xorr ^ b[i];
}

// Space - O(N) and Time - O(M+N) where m and n are the size of the 2 strings
char map_diff(string a, string b) {
    unordered_map<char,int> mp1, mp2;
    for(auto x:a) 
        mp1[x]++;
    for(auto y:b)
        mp2[y]++;
        
    for(auto x:b)
    {
        if(mp1.find(x)==mp2.end()) // finds the char of mp1 in mp2 
            return x;
        else if(mp1[x]!=mp2[x])  // a = 's' and b = 'ss' for the same char but diff count ans = 's'
            return x;
    }
    return b[(b.size())-1];
}

int main()
{
    string a,b; 
    cin>>a>>b;
    cout<< bits_diff(a,b) << endl;
    cout<< map_diff(a,b) << endl;
    return 0;
}

/*
Input 
    a = "abc"
    b = "abcd"
Output: d

Input 
    a = ""
    b = "c"
Output: c

Input 
    a = "zz"
    b = "zzz"
Output: z
*/

<|start_filename|>C-Plus-Plus/stack/next_greatest_right.cpp<|end_filename|>
/*Next greatest element to the right of each element in the array
  ALGORITHM
 *Using a stack to find out the next greatest element to the right
 *Start the scanning of the array from the right 
 *Declare an array and a stack
 *If the stack is empty, then no element to the right is greater than the present element
 *If the stack is not empty but the element present at the top of the stack is not greater than the current element then-
 * pop the stack till  the stack is not empty or the top element of stack is greater than the current element
 *If the stack is not empty and the element at the top of the stack is greater than the current element then push the topmost element to the stack
*/
#include <bits/stdc++.h>
using namespace std;
void nextLargest(int a[], int n)
{
    vector<int> v;
    stack<int> s;
    for (int i = n - 1; i >= 0; i--)
    {
        if (s.empty() == true)
            v.push_back(-1);
        else if (s.empty() != true && s.top() > a[i])
            v.push_back(s.top());
        else if (s.empty() != true && s.top() <= a[i])
        {
            while (s.top() <= a[i] && s.empty() != true)
            {
                s.pop();
            }

            if (s.empty() == true)
                v.push_back(-1);
            if (s.top() > a[i] && s.empty() != true)
                v.push_back(s.top());
        }

        s.push(a[i]);
    }
    //reversing the array containing the next greatest element to the right
    reverse(v.begin(), v.end());
    for (int i = 0; i < n; i++)
        cout << v[i] << " ";
}
int main()
{
    int n;
    cin >> n;
    int a[n];
    for (int i = 0; i < n; i++)
        cin >> a[i];
    nextLargest(a, n);
}
/*
INPUT:
n=4
a[n]=1 3 2 4
OUTPUT:
3 4 4 -1
Code Complexity: O(n^2)
*/


<|start_filename|>Java/math/Magicnumber.java<|end_filename|>
/* How to determine if a number is a Magic number.
   We calculate the sum of digits of the number till
   we get a single digit, recursively. If the single
   digit comes out to be 1, then we say that the number
   is a magic number.*/

import java.util.*;

//This function checks if a number is a magic number
class Magicnumber{
    
    static boolean magicNumber(int n){
         
         int sum = 0;
         /*We loop till the number is greater than 0 or we
           get a single digit sum of the digits of the number*/  
         while(n>0 || sum>9){
               
               //This is the iterating step.
               if(n == 0){
                  n =sum;
                  sum = 0; 
               }
               else{
                  //We find the sum of the digits of number
                  sum += n%10;
                  n = Math.floorDiv(n,10); 
               } 
         }

         /*After we get a single digit sum, we check if
           it 1, then it is a magic number and we return True.*/
         if(sum == 1){
            return true;
         }
         else{
            return false;
         }

    }    

    public static void main(String[] args){

         Scanner scan = new Scanner(System.in);
         System.out.print("Enter the number :");
         //Taking input from user
         int n = scan.nextInt();
         
         //checker  
         boolean check = magicNumber(n);
         
         //If the above function returns true, it means n is Magic number 
         if(check == true)
             System.out.println("The given number "+n+" is Magic number!");
         else
             System.out.println("The given number "+n+" is not Magic number!");       

    }     

}
/*
    Simple I/O :
 
    a) Is a magic number!
       
       Enter the number :112222
       The given number 112222 is Magic number!

    b) Is not a Magic number! 
      
       Enter the number :123
       The given number 123 is not Magic number!           
*/ 



<|start_filename|>Java/math/sieveOfAtkin.java<|end_filename|>
import java.util.ArrayList;
import java.util.stream.IntStream;

/**
 * The Sieve of Atkin is a modern algorithm for finding all prime
 * numbers up to a specified integer. Compared with the ancient
 * sieve of Eratosthenes, which marks off multiples of primes, the
 * sieve of Atkin does some preliminary work and then marks off
 * multiples of squares of primes, thus achieving a better theoretical
 * asymptotic complexity. It was created in 2003 by <NAME>
 * and <NAME>.
 *
 * Google it if you don't know about it.
 *
 * @author <NAME>
 * @since 3-7-2020
 */
public class sieveOfAtkin {

    public static ArrayList<Integer> sieve(int lowerLimit, int upperLimit) {
        ArrayList<Integer> result = new ArrayList<>();

        if (upperLimit > 2) {
            result.add(2);
        };
        if (upperLimit > 3) {
            result.add(3);
        };
        boolean[] sieve = new boolean[upperLimit];



        IntStream.range(0, upperLimit)
                .forEach(i -> sieve[i] = false);

        for (int x = 1; x * x < upperLimit; x++) {
            for (int y = 1; y * y < upperLimit; y++) {
                int n = (4 * x * x) + (y * y);
                if (n <= upperLimit && (n % 12 == 1 || n % 12 == 5)) sieve[n] ^= true;
                n = (3 * x * x) + (y * y);
                if (n <= upperLimit && n % 12 == 7) sieve[n] ^= true;
                n = (3 * x * x) - (y * y);
                if (x > y && n <= upperLimit && n % 12 == 11) sieve[n] ^= true;
            }
        }
        IntStream.iterate(5, r -> r * r < upperLimit, r -> r + 1)
                .filter(r -> sieve[r])
                .flatMap(r -> IntStream.iterate(r * r, i -> i < upperLimit, i -> i + r * r))
                .forEach(i -> sieve[i] = false);

        for (int a = lowerLimit; a < upperLimit; a++) {
            if (sieve[a]) {
                result.add(a);
            }

        }
       return result;
    }

}

<|start_filename|>Go/cryptography/Hill_Cipher/Hill_Cipher.go<|end_filename|>
/* This code is an implementation of Hill Cipher in Go. It
is a polygraphic substitution cipher. It forms a nxn matrix
of key and nx1 matrix(s) of the plaintext and then multiplies
the two matrices to obtains the matrix of ciphertext.*/

package main

import (
	"fmt"
	"os"
	"unicode"
	"strings"
)

// Define the size of the n (Globally)
var n int = 3

/* This function forms the nxn matrix of keyword.
The value of n can be changed using the global var.*/
func gen_key_matrix(key string, keymatrix [][]int) {

	var count int = 0
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			/*Converting ascii to decimal. Here, 
			a = 97, b = 98 and so on. We want a = 0,
			b = 1 and so on. So, we subtract 97.*/
			keymatrix[i][j] = int(key[count]) - 97
			count += 1
		}
	}
}

/* This function forms the nx1 matrix of the plaintext.
Value of n can be changed using the global var.*/
func gen_message_matrix(plaintext string, messagematrix [][]int) {

	var count int = 0
	for i := 0; i < n; i++ {
		for j := 0; j < 1; j++ {
			/*Converting ascii to decimal. As we did above,
			similarly, we subtract 97 from the decimal value
			to start indexing from 0.*/
			messagematrix[i][j] = int(plaintext[count]) - 97
			count += 1
		}
	}
}

/* This function forms the nx1 ciphertext matrix. The matrix of decimal
is then converted to ascii value and combined and then returned.*/
func gen_ciphertext(plaintext, key string, ciphermatrix [][]int) string {

	// Forming the keyword matrix
	var keymatrix = make([][]int, n)
	for i := range keymatrix {
		keymatrix[i] = make([]int, n)
	}
	// Calling the keyord matrix function
	gen_key_matrix(key, keymatrix)

	// Forming the plaintext matrix
	var messagematrix = make([][]int, n)
	for i := range messagematrix {
		messagematrix[i] = make([]int, 1)
	}
	// Calling the plaintext matrix function
	gen_message_matrix(plaintext, messagematrix)

	/* Initializing the ciphertext matrix values to
	zero. Otherwise, it would store garbage values.*/
	for i := 0; i < n; i++ {
		for j := 0; j < 1; j++ {
			ciphermatrix[i][j] = 0
		}
	}

	/* Multiplying key matrix with plaintext matrix
	and forming the ciphertext matrix. */
	for i := 0; i < n; i++ {
		for j := 0; j < 1; j++ {
			for k := 0; k < n; k++ {
				ciphermatrix[i][j] += keymatrix[i][k] * messagematrix[k][j]
			}
		}
	}

	/* Taking mod 26 of obtained ciphertext values
	to ensure they lie within the range [0-25].*/
	for i := 0; i < n; i++ {
		for j := 0; j < 1; j++ {
			ciphermatrix[i][j] = ciphermatrix[i][j] % 26		}
	}

	// This variable is declared to store the ciphertext
	var encrypted string

	/* Since, we decremented 97 from the decimal values
	of plaintext and key, we add back 97 to the ciphertext
	values, in order to get proper ASCII.*/
	for i := 0; i < n; i++ {
		for j := 0; j < 1; j++ {
			encrypted += string(ciphermatrix[i][j] + 97)
		}
	}

	// Returning the ciphertext
	return encrypted;

}

/* This function formats the ciphertext according
to the plaintext.*/
func format(plaintext, ciphertext string) string {

	var enc string

	/* Check wherever the plaintext is capital and
	then capitalize that character in the ciphertext*/
	for i := 0; i < len(plaintext); i++ {
		if(unicode.IsUpper(rune(plaintext[i]))) {
			enc += strings.ToUpper(string(ciphertext[i]))
		} else {
			enc += string(ciphertext[i])
		}
	}
	// Return the final formatted ciphertext
	return enc
}

func main() {

	fmt.Print("\n--------------HILL CIPHER-----------------\n\n")
	fmt.Print("The value of plaintext must be same as n\n")
	fmt.Print("\nCurrent value of n is: ", n, "\n\n")

	// Taking plaintext as input from user
	fmt.Print("Enter a plaintext of size ", n, ": ")
	var plaintext string
	fmt.Scan(&plaintext)

	// Checking if proper message is provided or not.
	if(len(plaintext) != n) {
		fmt.Print("Enter a valid message.\n")
		os.Exit(0)
	}

	// Taking key as input from user
	fmt.Print("Enter a keyword of size ", n*n, ": ")
	var key string
	fmt.Scan(&key)

	// Checking if proper key is provided or not.
	if(len(key) != n*n) {
		fmt.Print("Enter a valid key.\n")
		os.Exit(0)
	}

	var ciphertext string

	// Declaring the ciphertext matrix
	var ciphermatrix = make([][]int, n)
	for i := range ciphermatrix {
		ciphermatrix[i] = make([]int, 1)
	}

	// Calling the function to get the encrypted plaintext
	ciphertext = gen_ciphertext(strings.ToLower(plaintext), strings.ToLower(key), ciphermatrix)
	fmt.Print("\nEncrypted plaintext is: ", format(plaintext, ciphertext), "\n")
}

/* Sample I/O:

a)

--------------HILL CIPHER-----------------

The value of plaintext must be same as n

Current value of n is: 4

Enter a plaintext of size 4: helo
Enter a keyword of size 16: thisisabigmessag

Encrypted plaintext is: hmiw

b)

--------------HILL CIPHER-----------------

The value of plaintext must be same as n

Current value of n is: 3

Enter a plaintext of size 3: hey
Enter a keyword of size 9: thisiskey

Encrypted plaintext is: psm

*/


<|start_filename|>Java/math/ExtendedEuclidAlgo.java<|end_filename|>
import java.util.Scanner;

class Triplet{
	
	public int x,y,gcd;
	public Triplet() {	
	}
	
}
public class ExtendedEuclidAlgo {
	
	public static int euclidAlgo(int a,int b) {
		if(b==0) {
			return a;
		}
		
		return euclidAlgo(b, a%b);
	}
	
	public static Triplet extendedEuclid(int a,int b) {
		if(b==0) {
			Triplet ans=new Triplet();
			ans.x=1;
			ans.y=0;
			ans.gcd=a;
			return ans;
		}
		
		Triplet subAns=extendedEuclid(b, a%b);
		Triplet ans=new Triplet();
		ans.x=subAns.y;
		ans.y=subAns.x-(a/b)*subAns.y;
		ans.gcd=subAns.gcd;
		
		return ans;
	}
	
	public static void main(String[] args) {
		
		Scanner sc=new Scanner(System.in);
		int a=sc.nextInt();
		int b=sc.nextInt();
		Triplet ans=extendedEuclid(a, b);
		System.out.println("Gcd of ("+a+" , "+b+") : "+ans.gcd);
	}
	
//Sample Input 5 10 
//Sample Output : Gcd of (5 , 10) : 5

//Sample Input 51 68
//Sample Output : Gcd of (51 , 68) : 17	
	
}


<|start_filename|>C/search/linear_search.c<|end_filename|>
/*
a linear search or sequential search is a method for finding an element within a list. 
It sequentially checks each element of the list until a match is found or the whole list 
has been searched.

It has time complexity of O(n).
____________________
|1|5|8|9|0|10|11|12|  -----> search(9)
                                |
                                |
___________________        
|1|5|8|9|0|10|11|12|

 |_______________________is i==9 false next element i=1
   |_____________________is i==9 false next element i=5
     |___________________is i==9 false next element i=8
        |________________is i==9 true return found and break the loop i=9

So it is searching the whole array linearly.

*/

#include<stdio.h>
#include<stdlib.h>

//base utility function to create the array
int* create(int n){
    int *a = (int*)malloc(n*sizeof(int));

    for (int i = 0; i < n; i++)
    {
        /* code */
        scanf("%d",(a+i));
    }
    
    return a;
}


//linear searching a element
void linear_search(int element,int *a,int n){

     //loop intitialisation
     for (int i = 0; i < n; i++)
     {
         /* check if the element is in the array */
         if(*(a+i)==element){
             printf("\nelement found at:%d position",i);
             break;
         }
     }
     
}

//printting the array function
void display(int *a,int n){
    for (int i = 0; i < n; i++)
    {
        /* code */

        printf("%d ",*(a+i));
    }
    
}

//main function
int main(int argc, char const *argv[])
{
    int n;

    printf("\nenter the size of the array:");
    scanf("%d",&n);

    int *arr = create(n);
    
    printf("\n the array is:");
    display(arr,n);

    int element;//element to search

    printf("\n enter the element to search:");
    scanf("%d",&element);

    linear_search(element,arr,n);
    return 0;
}



<|start_filename|>JavaScript/dp/flightOfStairs.js<|end_filename|>
/*You are given positive integers n and k. You are currently at stair 0 and want to climb to stair n. 
You can either climb 1, 2, or 3 stairs at a time, but you can only climb 3 stairs at most k times.
Return the number of ways to climb to the nth stair.
*/

const FlightOfStairs = (n, k) => {
    const memo = new Array(n + 1);
    for (let i = 0; i < n + 1; i++)
    {
        memo[i] = new Array(k + 1).fill(0);
    }

    /*passing to the utility function*/
    console.log("The answer is ",solveUtil(n, k, memo));
};

const solveUtil = (n, k, memo) =>{

    /*base cases*/
    if (n == 0)
        return 1;
    else if (n < 0)
        return 0;
    else if (memo[n][k] != 0)
        return memo[n][k];

    /*calls for 1 and 2 steps*/
    memo[n][k] = solveUtil(n - 1, k, memo) + solveUtil(n - 2, k, memo);

    /*checking k before making calls for 3 steps*/
    if (k > 0)
        memo[n][k] += solveUtil(n - 3, k - 1, memo);

    return memo[n][k];
};

/*taking arguments using command line arguments*/
console.log("Enter the values of n and k: ");
var arguments = process.argv;
FlightOfStairs(parseInt(arguments[2]),parseInt(arguments[3]));

  
/*
Input:
Enter the values of n and k: 
4 1

Output:
The answer is 7
*/

/*
Time complexity: O(n*k)
Space complexity: O(n*k)
*/


<|start_filename|>C-Plus-Plus/cp/ToggleKthBitFromRight.cpp<|end_filename|>
/*
Toggle kth bit from the right.
i.e. For a given number n, if k-th bit from right is 0, then toggle it to 1
and if it is 1 then, toggle it to 0.
*/

#include <iostream>
using namespace std;

int main() {
	int n, k;
	//n=integer
	cin >> n >> k;
	int ans = (n ^ (1 << (k - 1)));
	cout << ans;
	return 0;
}


/*
  input:
  6 2
  ouput:
  4
  constraint:
  n is positive
*/

/*
  time-complexity: O(1)
*/


<|start_filename|>Java/cryptography/RailFenceCipher.java<|end_filename|>
import java.util.Queue;
import java.util.LinkedList;
import java.util.Scanner;

/**
 * <h1>Rail Fence</h1>
 * <p>
 * RailFence class acts as a custom Data Structure which consits of a Queue of Characters, Queue is used due to its
 * FIFO(First In First Out) property.
 * </p>
 */
class RailFence
{
    public Queue<Character> railFenceQueue;
}

/**
 * <h1>Rail Fence Cipher</h1>
 * <p>
 * To Implement Rail Fence Cipher
 * </p>
 * <b>Description</b>
 * <p>
 * class RailFenceCipher is used to encrypt plainText to cipherText using Rail Fence Cipher and decrypt cipherText to
 * plainText using the respective algorithm, Rail Fence Cipher is also called as Zig-Zag Cipher, it is a form of
 * Transposition cipher, it has derived its name from the technique it uses to encode the plain text, which forms a
 * zig-zag pattern which looks like a rail fence, it jumbles up the characters in the plain text to form the cipher
 * text.
 * </p>
 * <b>Requirements</b>
 * <p>
 * A string plain text and an integer key are required for encryption and for decryption the cipher text which is
 * calculated from the given key and the key itself.
 * </p>
 */
public class RailFenceCipher
{
    /**
     * <p>
     * This is a public method used to encrypt plainText using integer key using the Rail Fence Cipher algorithm.
     * </p>
     * 
     * <b>Process</b>
     * <ul>
     * <li>Place the characters in rail fence sequence
     * <p>
     * Here plain text= HelloHiHowAreYou? and key =3
     * </p>
     * <p>
     *    0 H               O                   O                       E                   ?
     *    1    E       L       H          H           W           R           Y        U
     *    2        L               I                       A                       O
     * </p>
     * </li>
     * 
     * <li>Fetch all the characters in index 0 then iterate it over other indexes until the last character of the index is
     * fetched Here in the above example,
     * <ul>
     * <li>First, fetch all the characters which come in index 1, i.e. HOOE?</li>
     * <li>Then, fetch all the characters which come in index 2, i.e. ELHHWRYU</li>
     * <li>Then, fetch all the characters which come in index 3, i.e. LIAO</li>
     * </ul>
     * Then concatenate all the strings of different indexes which becomes our cipher text = HOOE?ELHHWRYULIAO</li>
     * </ul>
     * 
     * @param plainText This is a String parameter to encrypt method, this signifies plain text which is passed.
     * @param key       This is an Integer parameter to encrypt method, this signifies key which is passed to encrypt
     *                  plainText.
     * 
     * @return String This returns the cipherText.
     */
    public String encrypt(String plainText, Integer key)
    {
        StringBuilder cipherText           = new StringBuilder("");// used to store cipher text
        RailFence[]   railFence            = new RailFence[key];   // used to store rail fence sequence
        Integer       currentIndexPosition = 0;                    // used to store the current index position 0 - (key-1)
        Boolean       incrementFlag        = false;                // used as a flag to know whether to increment/decrement value of currentIndexPosition
        
        // Initializing railFence
        for (int i = 0; i < key; i++)
        {
            railFence[i] = new RailFence();
            railFence[i].railFenceQueue = new LinkedList<Character>();
        }
        
        // Iterating through each character in plainText
        for (int i = 0; i < plainText.length(); i++)
        {
            // If currentIndexPosition reaches to its full length, then it needs to be decremented
            if (currentIndexPosition == key - 1)
            {
                incrementFlag = true;
            }
            // If currentIndexPosition reaches to its minimum length, then it needs to be incremented
            else if (currentIndexPosition == 0)
            {
                incrementFlag = false;
            }
            
            // Adds the current character to railFence sequence at a particular sequence
            railFence[currentIndexPosition].railFenceQueue.add(plainText.charAt(i));
            
            /*
             * If incrementFlag=true then currentIndexPosition has reached its maximum possible length, i.e. key-1 and
             * currentIndexPosition needs to be decremented now to satisfy the algorithm
             * 
             * If incrementFlag=false then currentIndexPosition has reached its minumum possible length, i.e. 0 and
             * currentIndexPosition needs to be incremented now to satisfy the algorithm
             */
            if (incrementFlag)
            {
                currentIndexPosition--;
            }
            else
            {
                currentIndexPosition++;
            }
        }
        
        // Iterating through railFence
        for (int i = 0; i < key; i++)
        {
            RailFence        rail       = railFence[i];       // used to store current railFence
            Queue<Character> characters = rail.railFenceQueue;// used to store queue of current railFence
            
            while (!characters.isEmpty())
            {
                // polls the character from the sequence
                Character currentCharacter = characters.poll();
                // appends the polled character to ciphertext
                cipherText.append(currentCharacter);
            }
        }
        
        // cipher text is retured
        return cipherText.toString();
    }
    
    /**
     * <p>
     * This is a public method used to decrypt cipher using integer key using Rail Fence Cipher algorithm.
     * </p>
     * <b>Process</b>
     * <ul>
     * <li>As in Rail Fence Cipher technique, the length of cipher text is equal to plain text, we first make a placeholder
     * rail fence sequence to get an idea of the length of each index</li>
     * <li>Incrementally we place each character of cipher text in the rail fence</li>
     * <li>Then we fetch each character from each index</li>
     * <li>Finally, we concatenate all the characters to get plain text</li>
     * </ul>
     * 
     * @param cipherText This is a String parameter to decrypt method, this signifies cipher text which is passed.
     * @param key        This is an Integer parameter to decrypt method, this signifies key which is passed to decrypt
     *                   cipherText
     * 
     * @return String This returns the plainText.
     */
    public String decrypt(String cipherText, Integer key)
    {
        StringBuilder plainText                     = new StringBuilder("");// used to store plain text
        RailFence[]   railFenceForPlacement         = new RailFence[key];   // used as a placeholder/template for railFence
        RailFence[]   railFence                     = new RailFence[key];   // used to store rail fence sequence
        Integer       currentIndexPosition          = 0;                    // used to store the current index position 0 - key-1 for railFenceForPlacement
        Integer       currentIndexPositionForDecode = 0;                    // used to store the current index position 0 - key-1 for railFence
        Integer       indexPointerForCharacter      = 0;                    // used to store the current pointing character in cipherText
        Boolean       incrementFlag                 = false;                // used as a flag to know wheter to increment/decrement value of currentIndexPosition
        Boolean       incrementFlagForDecode        = false;                // used as a flag to know wheter to increment/decrement value of currentIndexPositionForDecode
        
        // Initializing railFenceForPlacement and railFence
        for (int i = 0; i < key; i++)
        {
            railFenceForPlacement[i] = new RailFence();
            railFenceForPlacement[i].railFenceQueue = new LinkedList<Character>();
            railFence[i] = new RailFence();
            railFence[i].railFenceQueue = new LinkedList<Character>();
        }
        
        // Making a template for getting knowledge of length of characters in an index acts as a placeholder to railFence
        for (int i = 0; i < cipherText.length(); i++)
        {
            // If currentIndexPosition reaches to its full length then it needs to be decremented
            if (currentIndexPosition == key - 1)
            {
                incrementFlag = true;
            }
            // If currentIndexPosition reaches to its minimum length then it needs to be incremented
            else if (currentIndexPosition == 0)
            {
                incrementFlag = false;
            }
            
            // Adds a temporary to railFenceForPlacement sequence at a particular sequence
            railFenceForPlacement[currentIndexPosition].railFenceQueue.add('*');
            
            /*
             * If incrementFlag=true then currentIndexPosition has reached its maximum possible length, i.e. key-1 and
             * currentIndexPosition needs to be decremented now to statisfy the algorithm
             * 
             * If incrementFlag=false then currentIndexPosition has reached its minumum possible length, i.e. 0 and
             * currentIndexPosition needs to be incremented now to statisfy the algorithm
             */
            if (incrementFlag)
            {
                currentIndexPosition--;
            }
            else
            {
                currentIndexPosition++;
            }
        }
        
        // Iterating through railFenceForPlacement to make railFence character sequence
        for (int i = 0; i < key; i++)
        {
            RailFence        rail       = railFenceForPlacement[i]; // used to store current railFenceForPlacement
            Queue<Character> characters = rail.railFenceQueue;      // used to store queue of current railFenceForPlacement
            while (!characters.isEmpty())
            {
                // Adds cipherText indexPointerForCharacter character to railFence sequence at a particular location
                railFence[i].railFenceQueue.add(cipherText.charAt(indexPointerForCharacter));
                // polls the current character in Queue of railFenceForPlacement, making it empty
                railFenceForPlacement[i].railFenceQueue.poll();
                // Increments the count to point to next character in cipherText
                indexPointerForCharacter++;
            }
            
        }
        
        // Iterating through cipherText
        for (int i = 0; i < cipherText.length(); i++)
        {
            // If currentIndexPositionForDecode reaches to its full length, then it needs to be decremented
            if (currentIndexPositionForDecode == key - 1)
            {
                incrementFlagForDecode = false;
            }
            // If currentIndexPositionForDecode reaches to its minimum length, then it needs to be incremented
            else if (currentIndexPositionForDecode == 0)
            {
                incrementFlagForDecode = true;
            }
            
            RailFence        rail       = railFence[currentIndexPositionForDecode];// used to store current railFence
            Queue<Character> characters = rail.railFenceQueue;                     // used to store queue of current railFence
            
            // appends the polled character to plainText
            plainText.append(characters.poll());
            
            /*
             * If incrementFlag=true then incrementFlagForDecode has reached its maximum possible length, i.e. key-1 and
             * currentIndexPositionForDecode needs to be decremented now to satisfy the algorithm
             * 
             * If incrementFlag=false then incrementFlagForDecode has reached its minumum possible length, i.e. 0 and
             * currentIndexPositionForDecode needs to be incremented now to satisfy the algorithm
             */
            if (incrementFlagForDecode)
            {
                currentIndexPositionForDecode++;
            }
            else
            {
                currentIndexPositionForDecode--;
            }
        }
        
        // plain text is retured
        return plainText.toString();
    }
    
    /**
     * This is the main method which makes use of the following methods:
     * <ul>
     * <li>encrypt</li>
     * <li>decrypt</li>
     * </ul>
     * 
     * And uses the following objects of types:
     * <ul>
     * <li>java.util.Scanner</li>
     * <li>java.lang.Integer</li>
     * <li>RailFenceCipher</li>
     * </ul>
     * 
     * @param args not used
     */
    public static void main(String[] args)
    {
        Integer         key;                                     // Created an object of Integer class for storing key to be entered by the user
        String          plainText;                               // Create an object of String class for storing plain text to be entered by the user
        Scanner         scan            = new Scanner(System.in);// Created an object of Scanner class for asking for user input.
        RailFenceCipher railFenceCipher = new RailFenceCipher(); // Created an object of RailFenceCipher for accessing it's method for encryption and decryption
        
        // Asking user to enter plain text
        System.out.println("Please Enter Plain Text:");
        plainText = scan.nextLine();
        
        // Asking user to enter integer key
        System.out.println("Please Enter Key:");
        key = scan.nextInt();
        
        // Accessing method 'encrypt' of RailFenceCipher class to encrypt plainText by key
        String cipherText = railFenceCipher.encrypt(plainText, key);
        // Printing cipher text
        System.out.println("Cipher Text: " + cipherText);
        
        // Accessing method 'decrypt' of RailFenceCipher class to decrypt cipherText by key
        String decryptedText = railFenceCipher.decrypt(cipherText, key);
        // Printing decrypted text
        System.out.println("Decrypted Text: " + decryptedText);
        
        // Closing the Scanner object scan
        scan.close();
    }
}

/*
 * OUTPUT:
 * 
 * Please Enter Plain Text:
 * 
 * Attack Alice's troops at 5:00 PM today
 * 
 * Please Enter Key:
 * 
 * 3
 * 
 * Cipher Text: Acl'rs 0 atakAiestop t50 Mtdyt c oa:Po
 * 
 * Decrypted Text: Attack Alice's troops at 5:00 PM today
 */


<|start_filename|>Java/cp/Spiral_Matrix.java<|end_filename|>
import java.util.*;
import java.lang.*;
import java.io.*;

class SpiralMatrix {
    public List<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> arrLL = new ArrayList<>();
        
        //EDGE CASE
        if (matrix.length == 0) return arrLL;
        
        int m = matrix.length;      // Number of rows
        int n = matrix[0].length;  // Number of columns
        
        // Number of rows = Number of Columns = 1
        if (m == 1 && n == 1) {
            arrLL.add(matrix[0][0]);
            return arrLL;
        }
        
        // Number of rows = 1
        if (m == 1) {
            for (int j = 0; j < n; j++){
                arrLL.add(matrix[0][j]);
                
            }
            return arrLL;
        }
        
        // Number of columns = 1
        if (n == 1){
            for (int i = 0; i < m; i++){
                arrLL.add(matrix[i][0]);
                
            }
            return arrLL;
        }
        
        
        int i = 0;
        int j = 0;
        int k1 = 0;
        int k2 = 0;
        int itr = 0;
        while (j < n || i < m || j > k1 || i > k2){
            boolean one = false;
            while (j < n ){
                if (i != itr || i >= m) break;
                arrLL.add(matrix[i][j]);
                j++;
                one = true;
            }
        
            i++; j--; n--;
            boolean b = false;
            while (i < m && one == true){
                arrLL.add(matrix[i][j]);
                b = true;
                i++;
            }
            
            j--; i--; m--;
            
            boolean bk = false;
            while ( j>= k1  && b == true){
                arrLL.add(matrix[i][j]);
                j--;
                bk = true;
            }
            
            j++; i--; k1++;
            
            while ( i > k2 && bk == true) {
                arrLL.add(matrix[i][j]);
                i--;
            }
            
            j++; i++; k2++;
            itr ++;
        }
        return arrLL;
    }
}

/*
TEST CASE

TIME COMPLEXITY : 0(N*M) 
SPACE COMPLEXITY: 0(N+M)

where M is number of rows and N is number of columns

INPUT
[[ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]]

OUTPUT
[1,2,3,6,9,8,7,4,5]

INPUT
[[1, 2, 3, 4],
 [5, 6, 7, 8],
 [9,10,11,12]]

OUTPUT
[1,2,3,4,8,12,11,10,9,5,6,7]
*/



<|start_filename|>Java/cp/ArmStrongRecursion.java<|end_filename|>
// Checking Armstrong number with Recursion

import java.util.Scanner;
class ArmStrongRecursion
{
    static int p;
    public static int armstrong(int i)
    { if(i<10) //base class
        return (int)(Math.pow(i,p));
        else
        return((int)Math.pow(i%10,p)+armstrong(i/10));
    }
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.print("N = ");
        int n=sc.nextInt();
        p=Integer.toString(n).length(); //calculating the number of digits in the number by converting it into String

        if(n==armstrong(n))
        System.out.println(n+" is an Armstrong number");
        else
        System.out.println(n+" is not an Armstrong number");
    }
}

/*
Sample Input and Output :
N = 153
153 is an Armstrong number
Space Complexity: O(1)
Time Complexity : O(p)
*/


<|start_filename|>C/cryptography/caesar_cipher.c<|end_filename|>
/* Caesar Cipher Algorithm

Caesar Cipher Algorithm is an old encryption methodology used for encryption of data. Also known as Caesar Shift or
Caesar’s Code, it is one of the most straightforward and prevalent encryption technique. This Caesar Cipher
encryption algorithm is a kind of substitution cipher wherein every character in the plain-text or the user
input is replaced by another character which is defined with a fixed number of positions away from the existing character.
It is a method in which every letter or character in the plain text is altered and shifted. Every text character replaced
 by a specific character depending upon the algorithm.

The Caesar Cipher Algorithm is one of the oldest and easiest algorithms for encryption and decryption algorithm
in C programming language.

*/

#include<stdio.h>
#include<stdlib.h>

char data[50], temp;
int key, count;

/* Cipher_Caesar Encryption */
void encryption()
{
	for (count = 0; data[count] != '\0'; count++) {
		temp = data[count];
		if (temp >= 'a' && temp <= 'z') {
			temp = temp + key;
			if (temp > 'z') {
				temp = temp - 'z' + 'a' - 1;
			}
			data[count] = temp;
		} else if (temp >= 'A' && temp <= 'Z') {
			temp = temp + key;
			if (temp > 'Z') {
				temp = temp - 'Z' + 'A' - 1;
			}
			data[count] = temp;
		}
	}
	printf("Encrypted Message:\t%s\n", data);
}

/* Cipher_Caesar Decryption */
void decryption()
{
	for (count = 0; data[count] != '\0'; count++) {
		temp = data[count];
		if (temp >= 'a' && temp <= 'z') {
			temp = temp - key;
			if (temp < 'a') {
				temp = temp + 'z' - 'a' + 1;
			}
			data[count] = temp;
		} else if (temp >= 'A' && temp <= 'Z') {
			temp = temp - key;
			if (temp < 'A') {
				temp = temp + 'Z' - 'A' + 1;
			}
			data[count] = temp;
		}
	}
	printf("Decrypted Message:\t%s\n", data);
}

int main()
{
	printf("Enter a String:\t");
	scanf("%[^\n]s", data);

	printf("Enter a Key:\t");
	scanf("%d", &key);

	encryption();
	decryption();

	printf("\n");
	return 0;
}


/* Sample Output:

Enter a String: HACKINCODES
Enter a Key:    4
Encrypted Message:      LEGOMRGSHIW
Decrypted Message:      HACKINCODES

*/


<|start_filename|>Java/math/SieveOfEratosthenes.java<|end_filename|>
/* Sieve of Eratosthenes : 
  
  Sieve of Eratosthenes is an ancient algorithm for finding all prime numbers up to any given limit.
  It does so by iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with
  the first prime number, 2. The multiples of a given prime are generated as a sequence of numbers starting from that prime,
  with constant difference between them that is equal to that prime.

*/

import java.util.Scanner;

public class SieveOfEratosthenes {

	public static void sieve(int n) {
	
		boolean prime[]=new boolean[n+1];
		
		for(int i=0;i<=n;i++) {
			prime[i]=true;
		}
		
		prime[0]=prime[1]=false;
		
		for(int i=2;i*i<=n;i++) {
//	If a number is prime :	
			if(prime[i]==true) {
//	Marking all multiples of that number as false
				for(int j=i*i;j<=n;j+=i) {
					prime[j]=false;
				}
			}
		}
		
//	Printing all prime number less than n :	
		for(int i=0;i<=n;i++) {
			if(prime[i]==true) {
				System.out.print(i+" ");
			}
		}
		
	}
	
	public static void main(String[] args) {

		Scanner sc=new Scanner(System.in);
		
		System.out.print("Enter a number : ");
		int n=sc.nextInt();
		
		System.out.println("Prime number less than or equal to "+n+" are : ");
		sieve(n);
				
	}
/*	
 	Sample Input : 
	Enter a number : 100
 	
	Sample Output : 
	Prime number less than or equal to 100 are : 
	2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 	
*/

}


<|start_filename|>C-Plus-Plus/cp/Group_Anagrams.cpp<|end_filename|>
/*
Introduction 
Given an array of strings strs, group the anagrams together. 
You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, 
typically using all the original letters exactly once.

Argument/Return Type
Given a vector of strings as input
return answer as vector of vectors and print the result
*/

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

//Function to print all the groups of anagrams
void printGroups(vector<vector<string>>& Groups)
{
    //Print each group in a new line
    for(auto group : Groups)
    {
        for(auto str : group)
        {
            cout<<str<<" ";
        }
        cout<<endl;
    }
}

//Function to group anagrams together and return the result
vector<vector<string>> groupAnagrams(vector<string>& strings) 
{
    //Create a vector to store all groups of anagrams
    vector<vector<string>>Groups;
    //Create a map to store group number of each string
    map<string,int>groupNumber;
    
    //Keep count of number of groups
    int NumberOfGroups=0;
    
    //Visit all strings
    for(auto str : strings)
    {
        /* Create a temp string and sort it
        without disturbing original string */
        string temp=str;
        sort(temp.begin(),temp.end());

        //If the sorted string doesnot have a group already
        if(groupNumber[temp]==0)
        {
            /* Create a new group of strings
             push the string to the group and 
             push this group to the other groups */ 
            vector<string>group;
            group.push_back(str);
            Groups.push_back(group);

            //Increase no.of groups as new group is created
            NumberOfGroups++;
            //Store the group number of this sorted string
            groupNumber[temp]=NumberOfGroups;
        }
        else
        {
            /* If the group which this string belongs to already exists ,
              push the string to the corresponding group */
            Groups[groupNumber[temp]-1].push_back(str);
        }
    }

    return Groups;   
}

// Driver code
int main()
{
    //Take the input of total no.of strings
    int n;
    cout<<"Enter the total no.of strings : ";
    cin>>n;

    //Take input of the strings as vector
    vector<string>strings;
    for(int i=1;i<=n;i++)
    {
        string str;
        cout<<"Enter string "<<i<<" : ";
        cin>>str;
        strings.push_back(str);
    }

    //Call the function and print the result
    vector<vector<string>>result;
    result=groupAnagrams(strings);
    cout<<"Hence the grouped anagrams are "<<endl;
    printGroups(result);

    return 0; 
}
    
/*
Input:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i] consists of lower-case English letters.

Sample Test Case 1  

Input Format : 
Example :
Enter the total no.of strings : 6
Enter string 1 : eat
Enter string 2 : tea
Enter string 3 : tan
Enter string 4 : ate
Enter string 5 : nat
Enter string 6 : bat

Output Format :
Example : ( Output to the above input example ) 
Hence the grouped anagrams are
eat tea ate
tan nat
bat

Time/Space Complexity
  Time Complexity : O(n*klogk) 
  Space Complexity : O(n*k) 
*/


<|start_filename|>JavaScript/sort/cycleSort.js<|end_filename|>
/*CYCLE SORT:
	* an in-place unstable sorting Algorithm.
	* Optimal in terms of the total number of writes to original array.
	* Algorithm:
		STEP 1: For arr[i], find it's original_index in the sorted list by counting the smaller elements in arr.
		STEP 2: If element == arr[original_index], the iteration is skipped Else write it to original_index.
		STEP 3: If original_index is inhabited by a different element, repeat the above steps. 
		This is continued until an element is moved to the original position.This is a cycle.
		Such n cycles are executed.
*/

//importing readline module for dynamic input 
var readline = require('readline');
//initialising inputstream and outstream to process.stdin and process.stdout respectively.
var rl = readline.createInterface(
	process.stdin, process.stdout);

const cycleSort = (arr) => {
    const n = arr.length;
    //start is the index of the current element.
    for (let start = 0; start < n - 1; start++) {
        
        let currentKey = arr[start];
        let pos = start;
        for (let i = start + 1; i < n; i++) {
            if (arr[i] < currentKey)
                pos += 1;
        }
        // if pos = start => element is at original position. If so skip.
        if (pos == start) 
            continue;

        //check for duplicates in the array. 
        while (currentKey == arr[pos]) { 
            pos++ ;
        }
        //swapping current element and element at its original position.
        const temp = arr[pos];
        arr[pos] = currentKey;
        currentKey = temp;

        // rotate the rest of the cycle
        while (pos != start) {
            pos = start;
            //finding original position
            for (let i = start + 1; i < n; i++) {
                if (arr[i] < currentKey) 
                    pos += 1;
            }

            //checking for duplicates
            while (arr[pos] == currentKey) {
                pos += 1;
            }
            const temp = arr[pos];
            arr[pos] = currentKey;
            currentKey = temp;
        }
    }
    return arr;
}

//Reading input from console as a string and converting it to array 
rl.question('Enter array elements comma separated: ', (input) => {
    let numbers = input.split(",");
    numbers = numbers.map( (x) => parseInt(x));
    console.log(cycleSort(numbers));
	rl.close();
});

/*
CASE 1:
input = [1, 8, 7, 61, 5, 4, 11];
EXPECTED: [1,4,5,7,8,11,61]

CASE 2:
input = [1,8,3,9,10,10,2,4];
EXPECTED: [1,2,3,4,8,9,10,10]

    Time Complexity - O(n^2)
    Space Complexity - O(1)

*/


<|start_filename|>Java/other/SwapNibbles.java<|end_filename|>
import java.util.Scanner;

public class SwapNibbles {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number:");
        int num = sc.nextInt();

        int result = swapNibbles(num);

        System.out.println("Number after swapping nibbles:" + result);
        sc.close();
    }

    private static int swapNibbles(int x) {
        /* (x & 0x0F) << 4 gives us the last 4 bits of the number and
        shifts it by 4 bits to the left.
        (x & 0xF0) >> 4 gives us the last 4 bits of the number and
        shifts it to right by 4 bits. */
        return ((x & 0x0F) << 4 | (x & 0xF0) >> 4);
    }
}
/*
* Sample input/output
* Enter a number:
* 100
* Number after swapping nibbles:70
*
* Space and Time complexity = O(1)
*/


<|start_filename|>C/math/Kaprekar_no.c<|end_filename|>
/*
C program to check whether a number is kaprekar number or not
Kaprekar number is a number whose square when divided into two parts and then added gives the original number
Eg: 45 (45^2 = 2025 -->20+25 = 45)
*/

#include<stdio.h>
#include<math.h>
#include<stdbool.h>

bool kaprekar (int n);

int main ()
{
  int n;
  printf ("Enter the number to check:\n");
  scanf ("%d", &n);
  if (kaprekar (n) == true)
    {
      printf ("Kaprekar Number!");
    }
  else
    {
      printf ("Not Kaprekar Number !");
    }
  return 0;
}

bool kaprekar (int n)
{
  if (n == 1)
    return true;
  int s = n * n;
  int t = 0;
  while (s)
    {
      t = t + 1;
      s = s / 10;
    }
  s = n * n;
  for (int c = 1; c < t; c++)
    {
      int f, x1, x2, sum;
      f = pow (10, c);
      if (f == n)
	continue;
      x1 = s / f;
      x2 = s % f;
      sum = x1 + x2;
      if (sum == n)
	return true;
    }
  return false;
}

/*
SampleInput-Output1:
Enter the number to check:
297
Kaprekar Number!

SampleInput-Output2:
Enter the number to check:
12
Not Kaprekar Number!

Time Complexity: O(n)
*/


<|start_filename|>C-Plus-Plus/other/RussianPeasant.cpp<|end_filename|>
/*Russian Reasant Algorithm

In this algorithm, two numbers are multiplied without using multiplication operator.
We double the first number and halve the second number repeatedly till the second number doesn’t become 1. 
In the process, whenever the second number becomes odd, we add the first number to result.

In the 1800s, Peasants in a remote area of Russia were discovered multiplying numbers using this remarkably unusual process.
*/

#include <iostream>
using namespace std;
int main()
{
    int a, b, result = 0;

    cout << "Enter two numbers to multiply: \n";
    cin >> a >> b;
    while (b > 0)
    {
        if (b % 2 != 0)
        {
            result += a;
        }
        a = a << 1;
        b = b >> 1;
    }
    cout << "Product: " << result;
    return 0;
}

/*Input:
Enter two numbers to multiply: 
4 20

Output:
Product: 80

Time complexity: O(1)
*/

<|start_filename|>C/ds/infix_to_postfix.c<|end_filename|>
/* C code for Conversion of infix expression to post fix expression */

#include<stdio.h>
#include<stdlib.h>      /* for exit() */
#include<ctype.h>     /* for isdigit(char ) */
#include<string.h>

#define SIZE 100

/* declared here as global variable because stack[]
* is used by more than one functions */

char stack[SIZE];
int top = -1;

/* define push operation */

void push(char item)
{
	if(top>=SIZE-1)
	{
		printf("\nStack Overflow.");
	}
	else
	{
		top = top+1;
		stack[top] = item;
	}
}

/* define pop operation */

char pop()
{
	char item ;

	if(top <0)
	{
		printf("stack under flow: invalid infix expression");
		getchar();
		/* underflow may occur for invalid expression */
		/* where ( and ) are not matched */
		exit(1);
	}
	else
	{
		item = stack[top];
		top = top-1;
		return(item);
	}
}

/* define function that is used to determine whether any symbol is operator or not
(that is symbol is operand)
* this function returns 1 if symbol is operator else return 0 */

int is_operator(char symbol)
{
	if(symbol == '^' || symbol == '*' || symbol == '/' || symbol == '+' || symbol =='-' || symbol=='%')
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

/* define function that is used to assign precedence to operator.
* Here ^ denotes exponent operator.
* In this function we assume that higher integer value
* means higher precedence */

int precedence(char symbol)
{
	if(symbol == '^')/* exponent operator, highest precedence*/
	{
		return(3);
	}
	else if(symbol == '*' || symbol == '/' || symbol == '%')
	{
		return(2);
	}
	else if(symbol == '+' || symbol == '-')          /* lowest precedence */
	{
		return(1);
	}
	else
	{
		return(0);
	}
}

void InfixToPostfix(char infix_exp[], char postfix_exp[])
{
	int i,j;
	char item;
	char x;
	push('(');                               /* push '(' onto stack */
	strcat(infix_exp,")");                  /* add ')' to infix expression */
	i=0;
	j=0;
	item=infix_exp[i];         /* initialize before loop*/
	while(item != '\0')        /* run loop till end of infix expression */
	{
		if(item == '(')
		{
			push(item);
		}
		else if( isdigit(item) || isalpha(item))
		{
			postfix_exp[j] = item;              /* add operand symbol to postfix expression */
			j++;
		}
		else if(is_operator(item) == 1)        /* means symbol is operator */
		{
			x=pop();
			while(is_operator(x) == 1 && precedence(x)>= precedence(item))
			{
				postfix_exp[j] = x;                  /* so pop all higher precedence operator and */
				j++;
				x = pop();                       /* add them to postfix expression */
			}
			push(x);
			/* because just above while loop will terminate we have
			popped one extra item
			for which condition fails and loop terminates, so that one*/

			push(item);                 /* push current operator symbol onto stack */
		}
		else if(item == ')')         /* if current symbol is ')' then */
		{
			x = pop();                   /* pop and keep popping until */
			while(x != '(')                /* '(' encountered */
			{
				postfix_exp[j] = x;
				j++;
				x = pop();
			}
		}
		else
		{ /* if current symbol is neither operand not '(' nor ')' and nor
			operator */
			printf("\nInvalid infix Expression.\n");        /* then it is illegal  symbol */
			getchar();
			exit(1);
		}
		i++;


		item = infix_exp[i]; /* go to next symbol of infix expression */
	} /* while loop ends here */
	if(top>0)
	{
		printf("\nInvalid infix Expression.\n");        /* then it is illegal  symbol */
		getchar();
		exit(1);
	}
	if(top>0)
	{
		printf("\nInvalid infix Expression.\n");        /* the it is illegal  symbol */
		getchar();
		exit(1);
	}


	postfix_exp[j] = '\0'; /* add sentinel else puts() function */
	/* will print entire postfix[] array up to SIZE */

}

/* main function begins */

int main()
{
	char infix[SIZE],postfix[SIZE];         /* declare infix string and postfix string */

	/* why we asked the user to enter infix expression
	* in parentheses ( )
	* What changes are required in program to
	* get rid of this restriction since it is not
	* in algorithm
	* */
	printf("ASSUMPTION: The infix expression contains single letter variables and single digit constants only.\n");
	printf("\nEnter Infix expression : ");
	gets(infix);
	InfixToPostfix(infix,postfix);                   /* call to convert */
	printf("Postfix Expression: ");
	puts(postfix);                     /* print postfix expression */

	return 0;
}


/*
The process how the conversion of infix expression to postfix expression takes place by the above code is specified in the infix_to_postfix.md file.
*/



<|start_filename|>C-Plus-Plus/graphs/TopologicalSort.cpp<|end_filename|>
/**
Topological sort is linear ordering of vertices
in a directed acyclic graph (DAG). This algorithm is useful in 
solving many other applications on DAG
**/

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

void dfs_visit(vector<vector<int>>& Graph, int src, stack<int>& s, vector<bool>& visit) {
	visit[src] = 1;
	for(int i = 0; i < Graph[src].size(); i++)
		if(visit[Graph[src][i]] == 0)
		    dfs_visit(Graph, Graph[src][i], s, visit);
    s.push(src);
}

void dfs(vector<vector<int>>& Graph, int v, stack<int>& s) {
	vector<bool> visit(v);
	for(int i = 0; i < v; i++)
		if(visit[i] == 0)
			dfs_visit(Graph, i, s, visit);
}

void topological_sort(vector<vector<int>>& Graph, int v) {
	stack<int> s;
	dfs(Graph, v, s);
	while(!s.empty()) {
		cout << s.top() << ' ';
		s.pop();
	}
	cout << '\n';
}

int main() {
	int v, e, a, b;
	// all vertices are labelled from 0 to v-1
	cin >> v >> e;
	vector<vector<int>> Graph(v);
	// all directed edges
	for(int i = 0; i < e; i++) {
		cin >> a >> b;
		// edge a -> b
		Graph[a].push_back(b);
	} 
	topological_sort(Graph, v);
	return 0;
}

/**
Input :
6 8
0 3
0 4
0 5
1 5
1 0
2 1
3 4
4 5
Output :
2 1 0 3 4 5

Time Complexity : O(v+e)
Space Complexity : O(v)
**/


<|start_filename|>C/search/Manacher's_Algorithm.c<|end_filename|>
// Manacher's Algorithm is used to the find all the pairs (i,j) such that substring s[i…j] is a palindrome.
#include <stdio.h>
#include <string.h>

// Function to find the minumum between two numbers
int min(int num1, int num2)
{
	return (num1 > num2) ? num2 : num1;
}

// Function to find the maximum between two numbers
int max(int num1, int num2)
{
	return (num1 > num2) ? num1 : num2;
}

// Function to find the palindromic pairs and length of longest palindromic substring
int manacher_algo(char str[])
{
	int n = strlen(str);
	int d1[100] = {};  //d1 - odd length palindrome, 
	int d2[100] = {};  //d2 - even length palindrome
	for (int i = 0, l = 0, r = -1; i < n; ++i)
	{
		int k;
		if (i > r)
			k = 1;
		else
			k = min(d1[l + r - i], r - i + 1);
		while (0 <= i - k && i + k < n && str[i - k] == str[i + k])
		{
			k++;
		}

		d1[i] = k--;
		if (i + k > r)
		{
			l = i - k;
			r = i + k;
		}
	}

	for (int i = 0, l = 0, r = -1; i < n; ++i)
	{
		int k;
		if (i > r)
			k = 0;
		else
			k = min(d2[l + r - i + 1], r - i + 1);
		while (0 <= i - k - 1 && i + k < n && str[i - k - 1] == str[i + k])
		{
			k++;
		}

		d2[i] = k--;
		if (i + k > r)
		{
			l = i - k - 1;
			r = i + k;
		}
	}

	int ans = 0;
	printf("Following are the pairs which are palindromes: \n");
	for (int i = 0; i < n; ++i)
	{
		int x = d1[i];
		while (x)
		{
			ans = max(ans, 2 *x - 1);
			printf("%d %d\n", i - x + 1, i + x - 1);
			x--;
		}
	}

	for (int i = 0; i < n; ++i)
	{
		int x = d2[i];
		while (x)
		{
			ans = max(ans, 2 *x);
			printf("%d %d\n", i - x, i + x - 1);
			x--;
		}
	}

	return ans;
}

int main()
{
	char str[10];
	int ans;
	printf("Enter the string:");
    scanf("%s", str);
	ans = manacher_algo(str);
	printf("Length of longest palindromic substring: %d", ans);
	return 0;
}

/*

Sample Output
Enter the string:abcba
Following are the pairs which are palindromes: 
0 0
1 1
0 4
1 3
2 2
3 3
4 4
Length of longest palindromic substring: 5

Complexities
Time Complexity: O(N)
Space Complexity: O(N)

*/



<|start_filename|>C-Plus-Plus/cp/prefix_sum.cpp<|end_filename|>
/*
Given an array of N elements , find it's prefix sum array. In Competitive Programming, many times we need to calculate prefix sum array to solve our problem.
*/

#include <bits/stdc++.h>
using namespace std;
int ar[100009];

void prefix_sum_array(int ar[] ,int N)
{
    int pref_ar[N+1] = {0};
    pref_ar[0] = ar[0];
    // we will add the current element of ar[] array and previous element of pref_ar [] array
    for(int i = 1; i < N; i++)
    {
        pref_ar[i] = ar[i] + pref_ar[i - 1];
    }
    cout << "The New Prefix sum array is \n";
    for(int i = 0; i < N; i++)
    {
        cout << pref_ar[i] << ' ';
    }
    cout << endl;
    return;
}

int main()
{
    cout << "Input array size\n";
    int N;
    cin >> N;
    for(int i = 0; i < N; i++)
    {
        cin >> ar[i];
    }
    prefix_sum_array(ar , N);
}
/*
Standard Input and Output

Input array size
7
10 4 16 34 23 5 90
The New Prefix sum array is
10 14 30 64 87 92 182

Time Complexity : O(N)
Space Complexity : O(N)
*/


<|start_filename|>Java/graphs/Paths_From_Source_To_Destination.java<|end_filename|>

/* Here we are given a directed graph and 
   we have to print all paths from the source (src) 
   to the destination (dest) of the graph.
*/
import java.io.*;
import java.util.*;

public class Main {
    static class Edge {
        int src;
        int nbr;
        int wt;

        Edge(int src, int nbr, int wt) {
            this.src = src;
            this.nbr = nbr;
            this.wt = wt;
        }
    }

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int vtces = Integer.parseInt(br.readLine());
        ArrayList<Edge>[] graph = new ArrayList[vtces];
        for (int i = 0; i < vtces; i++) {
            graph[i] = new ArrayList<>();
        }

        int edges = Integer.parseInt(br.readLine());
        for (int i = 0; i < edges; i++) {
            String[] parts = br.readLine().split(" ");
            int v1 = Integer.parseInt(parts[0]);
            int v2 = Integer.parseInt(parts[1]);
            int wt = Integer.parseInt(parts[2]);
            graph[v1].add(new Edge(v1, v2, wt));
            graph[v2].add(new Edge(v2, v1, wt));
        }

        int src = Integer.parseInt(br.readLine());
        int dest = Integer.parseInt(br.readLine());

        boolean[] visited = new boolean[vtces];
        printAllPaths(graph, src, dest, visited, src + "");
    }

    // src -> source
    // dest -> destination
    // psf -> path so far
    public static void printAllPaths(ArrayList<Edge>[] graph, int src, int dest, boolean[] visited, String psf) {
        // When the destination vertex is reached print contents of path so for (psf).
        if (src == dest) {
            System.out.println(psf);
            return;
        }
        // Keep storing the visited vertices in an array (visited here) so that the
        // traversal doesn’t go in a cycle
        visited[src] = true;
        // traverse through graph
        for (Edge edge : graph[src]) {
            if (visited[edge.nbr] == false) {
                printAllPaths(graph, edge.nbr, dest, visited, psf + edge.nbr);
            }
        }
        // unmark the current vertex
        visited[src] = false;
    }
}

/*
 * Sample Input- 7 8 0 1 10 1 2 10 2 3 10 0 3 10 3 4 10 4 5 10 5 6 10 4 6 10 0 6
 * Sample Output- 0123456 012346 03456 0346
 */


<|start_filename|>C-Plus-Plus/sort/pigeon_hole_sort.cpp<|end_filename|>
// C++ program to implement Pigeon Hole  Sort

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

struct LargestAndSmallest
{
    int largest;
    int smallest;
};

//To find the largest and Smallest elements in an array with minimum comparisons
struct LargestAndSmallest find_max_min_elements(int arr[], int n)
{
    struct LargestAndSmallest pair;
    int i;
    //If there is only one element
    if (n % 2 == 1)
    {
        pair.smallest = arr[0];
        pair.largest = arr[0];
        i = 1;
    }
    else //Else If there is more than one element
    {
        if (arr[0] > arr[1])
        {
            pair.smallest = arr[1];
            pair.largest = arr[0];
        }
        else
        {
            pair.smallest = arr[0];
            pair.largest = arr[1];
        }
        i = 2;
    }

    while (i < n - 1)
    {
        if (arr[i] > arr[i + 1])
        {
            if (arr[i] > pair.largest)
                pair.largest = arr[i];

            if (arr[i + 1] < pair.smallest)
                pair.smallest = arr[i + 1];
        }
        else
        {
            if (arr[i + 1] > pair.largest)
                pair.largest = arr[i + 1];

            if (arr[i] < pair.smallest)
                pair.smallest = arr[i];
        }
        i = i + 2;
    }
    return pair;
}

// Pigeon hole sort
void pigeon_hole_sort(int arr[], int n)
{
    LargestAndSmallest pair = find_max_min_elements(arr, n);

    // Find statistical range of the given array
    int range = pair.largest - pair.smallest + 1;

    // Declare an array with the size of the range.
    int holes[range];

    memset(holes, 0, sizeof(holes)); //Initialize the new array with value 0.

    //Filling the 'holes' array with the input array values
    for (int j = 0; j < n; j++)
        holes[arr[j] - pair.smallest]++;

    // Put the elements back into the array in ascending occurence order.
    int j = 0;
    for (int i = 0; i < range; i++)
        while (holes[i]-- > 0)
        {
            arr[j] = i + pair.smallest;
            j++;
        }
}

int main()
{
    int n;
    cout << "\nHow many numbers do you want to sort? ";
    cin >> n;
    int arr[n];

    if (n <= 0)
    {
        cout << "The array is Empty!!!";
        return 0;
    }
    // Input the numbers to sort
    cout << "Enter the numbers: ";
    for (int i = 0; i < n; i++)
        cin >> arr[i];

    //Call the sort function
    pigeon_hole_sort(arr, n);

    cout << "The numbers in sorted order is: ";
    // Print the sorted array
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    cout << endl;

    return 0;
}

/*

Time Complexity: O(n+range), where 'range' is statistical range of the given input values
Space Complexity: O(n)

SAMPLE INPUT AND OUTPUT

SAMPLE 1
How many numbers do you want to sort? 5
Enter the numbers: 1 3 5 2 4
The numbers in sorted order is:  1  2  3  4  5

SAMPLE 2
How many numbers do you want to sort? 0
The array is Empty!!!

*/


<|start_filename|>Java/dp/Unique_BST.java<|end_filename|>
// Unique BSTs using DP
// For given n, how many structurally unique BST's that store values 1 ... n?

import java.io.*;
import java.util.*;

class Unique_BST {
    // function will return no. of unique bsts
    static int uniqueBST(int n) {
        int count[] = new int[n + 1];
        // for each 'i' number of nodes
        for (int i = 1; i <= n; ++i) {
            for (int j = 0; j < i; ++j) {
                // No. of trees if j is a root
                count[i] += Math.max(count[j], 1) * Math.max(count[i - j - 1], 1);
            }
        }
        return count[n];
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number:");
        int num = sc.nextInt();
        System.out.println("Number of Unique BSTs " + uniqueBST(num));
    }
}

/*
Input:
Enter the number:
3
Output:
Number of Unique BSTs 5
Time complexity : O(n)
*/


<|start_filename|>C-Plus-Plus/ds/Invert_Binary_Tree.cpp<|end_filename|>
/*

Introduction 
Given a Binary Tree , invert it and print its Levelorder

Argument/Return Type
Input of total no.of nodes is taken
Input of key values of nodes of tree are taken in level order form 
Incase of a null node , -1 is taken as input
Level Order of inverted tree is printed as output

*/

//  Code / Solution

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

//Define Node as structure
struct Node 
{
    int key;
    Node* left;
    Node* right;
};
 
//Function to create a node with 'value' as the data stored in it. 
//Both the children of this new Node are initially null.
struct Node* newNode(int value)
{
    Node* n = new Node;
    n->key = value;
    n->left = NULL;
    n->right = NULL;
    return n;
}

//Function to build tree with given input
struct Node* createTree(vector<int>v)
{
    int n=v.size();
    if(n==0) 
      return NULL;
    vector<struct Node* >a(n);
    //Create a vector of individual nodes with given node values
    for(int i=0;i<n;i++)  
    {
        //If the data is -1 , create a null node
        if(v[i]==-1)  
          a[i] = NULL;
        else 
          a[i] = newNode(v[i]);
    }
    //Interlink all created nodes to create a tree
    //Use two pointers using int to store indexes
    //One to keep track of parent node and one for children nodes
    for(int i=0,j=1;j<n;i++) 
    {
        //If the parent node is NULL , advance children pointer twice
        if(!a[i])
        {
          j=j+2;
          continue;
        } 
        //Connect the two children nodes to parent node
        //First left and then right nodes
        a[i]->left = a[j++];
        if(j<n) 
          a[i]->right = a[j++];
    }
    return a[0];
}

//Function to print Level order traversal of given tree
void levelOrder(struct Node* root)
{
    //If root is NULL , return it
    if (root == NULL)
        return;
    //Create a queue
    queue<Node*> q;
    //Push the root to the queue
    q.push(root);
    while (!q.empty()) 
    {
        //For each node we visit ,
        //Print its value , push their children if they exist
        //Pop it . Repeat this process till queue becomes empty
        cout << q.front()->key << " ";
        if (q.front()->left != NULL)
            q.push(q.front()->left);
        if (q.front()->right != NULL)
            q.push(q.front()->right);
        q.pop();
    }
} 

//Invert the given tree
void Invert(struct Node* node) 
{
    //If the node is NULL , return it 
    if (node == NULL) 
        return; 
    else
    {
        struct Node* temp;
          
        // recursively invert the subtrees
        Invert(node->left);
        Invert(node->right);
      
        // swap the pointers in this node */
        swap(node->left,node->right);
    }
} 

//Driver code
int main()
{

    int n;
    cout<<"Enter total no.of nodes of the input Tree ( including NULL nodes ) : ";
    cin>>n;

    vector<int>v(n);
    cout<<"Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces"<<endl;
    for(int i=0;i<n;i++)
    {
        cin>>v[i]; //store the input values in a vector
    }

    //create the tree using input node values  
    struct Node* root=createTree(v); 

    Invert(root); 

    // Print Level order and inorder traversals of inverted tree
    cout << "Level order traversal of the inverted tree is : ";
    levelOrder(root);
      
    return 0; 
}
    
/*
Input:
0 <= node->key < 1000000000
if node is NULL , -1 is entered as it's key

Sample Test Case  
Input Binary Tree :                    Output Inverted Binary Tree:

               1                                     1
           /         \                          /         \
         2              3                     3              2
     /       \        /   \               /       \        /   \
    4       NULL     5     6             6         5      NULL   4
   / \      /  \    / \   /  \          /  \      /  \    / \   /  \       
  7 NULL  NULL NULL 8  9 10  NULL      NULL 10 9 8 NULL NULL NULL  7    


Input Format : 
Example :
Enter total no.of nodes of the input Tree ( including NULL nodes ) : 15
Enter value of each node of the tree in level order ( if a node is NULL , enter -1 ) with spaces
1 2 3 4 -1 5 6 7 -1 -1 -1 8 9 10 -1

Output Format :
Example : ( Output to the above input example ) 
Level order traversal of the inverted tree is : 1 3 2 6 5 4 10 9 8 7 

Time/Space Complexity
Time Complexity : O(n) 
   Where n is the no.of nodes 
Space Complexity : O(n) 
   Where n is the no.of nodes
*/


<|start_filename|>Java/other/Search_insert_index.java<|end_filename|>
import java.util.*;

public class Search_insert_index {

    static int search(int[] nums, int target) {
        // using binary search since array is sorted.
        int start = 0;
        int end = nums.length - 1;

        while (start <= end) {
            int mid = (start + end) / 2;

            if (target > nums[mid]) {
                start = mid + 1;
            } else if (target < nums[mid]) {
                end = mid - 1;
            } else {
                return mid;
            }
        }

        return start;
    }

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int len, target, index;
        System.out.println("Enter the length of array");
        len = sc.nextInt();
        int arr[] = new int[len];
        System.out.println("Enter the array elements");
        for (int i = 0; i < len; i++)
            arr[i] = sc.nextInt();
        System.out.println("Enter the target value");
        target = sc.nextInt();
        index = search(arr, len);
        System.out.println("Index of the target element is " + index);
    }
}
/*
 * output: Enter the length of array 4 Enter the array elements 1 2 5 6 Enter
 * the target value 3 Index of the target element is 2
 *
 * Time Complexity: O(log(n)) space complexity: O(n)
 */


<|start_filename|>C-Plus-Plus/ds/K_Distance_Nodes_Binary_Tree.cpp<|end_filename|>
/*
    Given a binary tree with unique values, a target node in the binary tree, and an integer value k, print all the nodes
    that are at a distance k from the given target node.

    Sample input :
        Enter the size of preorder and inorder arrays   :  8
        Enter the elements of preorder traversal array  :  1 2 3 4 8 5 6 7
        Enter the elements of inorder traversal array   :  3 2 8 4 1 6 7 5
        Enter the target node in the binary tree        :  2
        Enter the value of distance K                   :  1

    Sample output :
        Nodes at a distance K are                       :  3 4 1

    @author : shankhanil007
    @created : 16-08-2020

*/


#include <iostream>
using namespace std;

// Basic definition of a node in binary tree
class node{
    public:
        int data;
        node* left;
        node* right;

        node(int d)
        {
            data = d;
            left = NULL;
            right = NULL;
        }
};

node* buildTree(int *preorder, int *inorder, int start, int end)
{
	static int i = 0;

	//Base Case
	if(start >  end){
		return NULL;
	}

	//Recursive Case
	node* newnode = new node(preorder[i]);

	int index = -1;

	for(int j = start; start <= end; j++)
	{
		if(preorder[i] == inorder[j])
		{
			index = j;
			break;
		}
	}

	i++;

	newnode->left = buildTree(preorder, inorder, start, index-1);
	newnode->right = buildTree(preorder, inorder, index+1, end);

	return newnode;
}

// Function to print the Kth level of the tree starting from a given node
void printKthLevel(node* root, int k)
{
    if(root == NULL)
        return;

    if(k == 0)
    {
        cout<<root->data<<" ";
        return;
    }

    printKthLevel(root->left, k-1);
    printKthLevel(root->right, k-1);

    return;
}

// Function to find the nodes at a distance K from a given node
int printAtDistanceK(node* root, int target, int k)
{
    // base case
    if(root == NULL){
        return -1;
    }

    //reach the target node
    if(root->data == target){
        printKthLevel(root , k);
        return 0;
    }

    // next step - ancestor
    int dl = printAtDistanceK(root->left, target, k);

    if(dl != -1){

        /* Again there are 2 cases
           Ancestor itself or you need to go to the right ancestor */
        if(dl+1 == k){
            cout<<root->data<<" ";
        }
        else{
            printKthLevel(root->right, k-2-dl);
        }

        return dl+1;
    }

    // next step - ancestor
    int dr = printAtDistanceK(root->right, target, k);

    if(dr != -1){

        /* Again there are 2 cases
           Ancestor itself or You need to go to the left ancestor */
        if(dr+1 == k){
            cout<<root->data<<" ";
        }
        else{
            printKthLevel(root->left, k-2-dr);
        }

        return dr+1;
    }

    //node was not present in left and right subtree
    return -1;
}

int main()
{
	cout<<"Enter the size of preorder and inorder arrays"<<endl;
	int n; cin>>n;
	int preorder[n];

	cout<<"Enter the elements of preorder traversal array"<<endl;
	for(int i=0;i<n;i++)
	{
		cin>>preorder[i];
	}

	int inorder[n];

	cout<<"Enter the elements of inorder traversal array"<<endl;
	for(int i=0;i<n;i++)
	{
		cin>>inorder[i];
	}

    int target, k;

    cout<<"Enter the target node in the binary tree"<<endl;
    cin>>target;

    cout<<"Enter the value of distance K"<<endl;
    cin>>k;

    node* root = buildTree(preorder, inorder, 0, n-1);

    cout<<"\nNodes at a distance K are : "<<endl;
        printAtDistanceK(root, target, k);
    cout<<endl;

    return 0;
}


<|start_filename|>C-Plus-Plus/math/Pythagorean_Triples.cpp<|end_filename|>
//C++ Program to generate Pythagorean Triples within a user-given limit
#include <bits/stdc++.h>
using namespace std;

//Function for computing Pythagorean Triples
void GetTriples(int& l)
{
	//Starting values of m=2, n=1 are mapped to a=3, b=4, c=5, which is the smallest Pythagorean triple
	int a = 0, b = 0, c = 0, m = 2, n = 1;

	while (c < l)
	{
		//For every m, evaluate a,b,c for all values of n from 1 to m-1
		n = 1;	
		while (n < m)
		{
			//Evaluating a, b, c using relation between a,b,c and m,n
			a = (int)(pow(m, 2)) - (int)(pow(n, 2));
			b = 2 *m * n;
			c = (int)(pow(m, 2)) + (int)(pow(n, 2));

			//Checking for limit being exceeded
			if (c > l)	
				break;

			//Display computed Triple
			cout << a << " " << b << " " << c << "\n";
			n++;
		}

		m++;
	}
}

//Driver function
int main()
{
	int l;
	//Prompts user for input
	cout << "Enter limit (>4) :";
	cin >> l;
	GetTriples(l);
	return 0;
}

/*
Sample I/O:
Enter limit: 30
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29

Time Complexity - O(k)[k = number of triples generated]
Space Complexity - O(1)

References: https://youtu.be/n6vL2KiWrD4
*/

<|start_filename|>C-Plus-Plus/cp/MinSwapToSortArray.cpp<|end_filename|>
/*
minimum no. of swaps needed to sort the array in ascending
order having integer in range 1 to N. For example:
array is 1 2 3 5 4 ,here it can be easily sorted by 
swapping 5 and 4. Therefore, 1 swap needed here.
*/
#include<iostream>
using namespace std;

int min_swap_needed(int a[],int n)
{
    int swap=0;
    for(int i=0;i<n-1;i++)
    {
        int j=a[i],temp;
    	  if((i+1)!=a[i])
    	  {
	        temp=a[i];
	        a[i]=a[j-1];
            	a[j-1]=temp;
	        swap++;
    	  }
    }
    return swap;
}

int main()
{
    int n;
    cin>>n;
    int a[n];
    for(int i=0;i<n;i++)cin>>a[i];
    int swap;
    swap=min_swap_needed(a,n);
    cout<<swap;
    return 0;
}
/*
input:
6
6 5 3 4 2 1
output:
2
*/

/*
Time-Complexity=O(N)
Space-Complexity=O(N)
*/


<|start_filename|>C-Plus-Plus/dp/min_ins_del.cpp<|end_filename|>
/** CONCEPT
 This code computes the number of insertions and deletions required to convert one string to another
 *Calculate the length of the longest common subsequence
 *Characters not present in the string X but present in string Y need to be inserted
 *Characters not present in the string Y but present in string X need to be deleted
**/
#include <bits/stdc++.h>
using namespace std;

void minInsertDel(string x, string y, int n, int m)
{
    int dp[n + 1][m + 1];

    /*Base conditions
    For calculating the longest common subsequence
    If the length of any one of the string is zero, then the length of common subsequence will be zero
    */
    for (int i = 0; i < n + 1; i++)
    {
        for (int j = 0; j < m + 1; j++)
        {
            if (i == 0 || j == 0)
                dp[i][j] = 0;
        }
    }

    for (int i = 1; i < n + 1; i++)
    {
        for (int j = 1; j < m + 1; j++)
        {
            if (x[i - 1] == y[j - 1])
                dp[i][j] = 1 + dp[i - 1][j - 1];
            else
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
        }
    }

    //Displaying the minimum number of insertions and deletions
    cout << "Minimum insertions=" << m - dp[n][m] << "\nMinimum deletions=" << n - dp[n][m] << "\n";
}

//Driver Code
int main()
{
    string x, y;
    cin >> x >> y;
    int n = x.length();
    int m = y.length();
    minInsertDel(x, y, n, m);
}
/*
 *TIME COMPLEXITY- O(n^2)
 *INPUT:
  X= abcdef
  Y= abcdg
  OUTPUT:
  Minimum insertions=1
  Minimum deletions=2
*/


<|start_filename|>C-Plus-Plus/graphs/celebrity_problem.cpp<|end_filename|>
/*
Celebrity Problem

Problem: In a party, we need to check if there is a celebrity who is known to everyone and he/she knows no one.

Input: A 2D co-relation matrix where rows and columns represent ids of persons present in the party and 
a value of matrix[i][j] = 1 indicates that the i'th person knows j'th person and a value of 0 indicates that
i'th person don't know j'th person. The primary diagonal must always be filled with zeroes, as a default value,
as thier values dont alter the solution logic.
*/

// C++ program to solve the Celebrity Problem
#include <bits/stdc++.h>
using namespace std;

/* If a celeb is present in the party, then his/her id'th column would be filled with 1 as values 
   except for the diagonal element and td'th row would be filled with 0s. */
int find_celebrity(int person[][9000], int n) {
    int low = 0;
    int high = n - 1;

    /* While loop to check if there is a column with value as 1 only except the diagonal value. 
       We start checking from the last column indexin the first row. */
    while (1) {
        if (low == high)
            break;

        if (person[low][high] == 1)
            low++;

        else
            high--;
    }
    for (int i = 0; i < n; i++) {
        if (low == i)
            continue;
        /* Check if low'th index is a celeb or not by checking
           if he/she knows anyone or anyone knows the celeb */
        if (person[low][i] == 1 || person[i][low] == 0)
            return -1;
    }
    return low;
}

int main() {
    int n;
    cout << "How many people are present in the party? ";
    cin >> n;
    int person[n][9000];
    cout << "Enter thier co-relation graph: ";
    // Input the co-relation matrix
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cin >> person[i][j];
        }
    }
    int celeb = find_celebrity(person, n);
    if (celeb >= 0) {
        cout << "Celebrity is present at the " << celeb;
        cout << "th index of the given co-relation graph";
    } else {
        cout << "Celebrity is not present in the party.";
    }
}

/*

Time Complexity: O(n)
Space Complexity: O(n^2)

SAMPLE INPUT AND OUTPUT

How many people are present in the party? 3
Enter thier co-relation graph: 0 1 0
                               0 0 1 
                               1 0 0
Celebrity is not present in the party.

*/


<|start_filename|>C-Plus-Plus/ds/Hashing_with_chaining.cpp<|end_filename|>
/**
 * @author omkarlanghe : https://github.com/omkarlanghe
 * A program to demostrate basic working of a data structure called Hashing.
 * This program supports seperate chaining method to avoid collision between hash indexes.
*/
#include <iostream>
#include <list>

class HashTable {
 private:
    int BUCKET;
    std::list<int> *table = nullptr;

 public:
        HashTable(int v);
        void insert_item(int x);
        void delete_item(int key);
        int hash_function(int data) { return (data % BUCKET); }
        void display_hash_table();
};

/** constructor function which initialized hash table */
HashTable::HashTable(int b) {
    this->BUCKET = b;
    table = new std::list<int>[BUCKET];
}

/** function to insert item in a hash table */
void HashTable::insert_item(int key) {
    int index = hash_function(key);
    table[index].push_back(key);
}

/** function to delete item from a hash table */
void HashTable::delete_item(int key) {
    int index = hash_function(key);
    std::list<int>::iterator it;
    for (it = table[index].begin() ; it != table[index].end() ; it++) {
        if (*it == key) {
            break;
        }
    }

    if (it != table[index].end()) {
        table[index].erase(it);
    }
}

/** function to display all the elements from hash table */
void HashTable::display_hash_table() {
    for (int i = 0 ; i < BUCKET; i++) {
        std::cout << i;
        for (auto x : table[i]) {
            std::cout << " :: " << x;
        }
        std::cout << std::endl;
    }
}

/** main function */
int main() {
    int size, x;
    std::cout << "Enter the size : " << std::endl;
    std::cin >> size;

    HashTable hash(size);

    std::cout << "Enter the elements in hash table : " << std::endl;
    for  (int i = 0 ; i < size ; i++) {
        std::cin >> x;
        hash.insert_item(x);
    }

    std::cout << "Display before deletion : " << std::endl;
    hash.display_hash_table();

    std::cout << "Enter the element to remove : " << std::endl;
    std::cin >> x;
    hash.delete_item(x);

    std::cout << "Display after deletion : " << std::endl;
    hash.display_hash_table();

    return (0);
}


<|start_filename|>C/ds/rabin_karp_algo.c<|end_filename|>
/* <NAME> ALGO in c issue - 2943
Rabin-Karp is  pattern searching algorithm to find the pattern in a more efficient way, 
finds the hash value. When the hash value is matched, then only it tries to check each character */
#include <stdio.h>
#include<string.h>
void hash(char word[], char format[], int max, int len1 ,int pos, int num, int  initial){
 /* C hash value calculation for pattern and text*/
  for (int index = 0; index < len1; index++) {
    initial = (num *  initial +format[index]) % max;
/* getting initial updated with hash value*/
    pos = (num * pos + word[index]) % max;
/* getting pos updated with hash value*/
  }
}
/* checking whether the pattern is present or not*/
int checking(char word[], char format[], int len2 , int len1 ,int pos, int  initial){
    int Index;
  for ( int index = 0; index <= len2 - len1; index++) {
 /* we check both size and intial positions */
    if (pos ==  initial) {
      for (Index = 0; Index < len1; Index++) {
        if (format[index + Index] != word[Index])
          break;
      }
 /* checking the len1 and the Indexes are equal or not */
      if (Index == len1)
        printf( "PATTERN IS AT POSITION %d", index + 1 );
/*printing the position of word present in format text*/
    }
  }
}
int main() {
   char format[1000];
   printf("enter the string format ");
   /* giving input text in string format */
   gets(format);
    char word[1000];
    printf("give pattern ");
    /*giving the pattern for checking word in text*/
    gets(word);
  int max = 100,index=0,Index=0;
 /* getting the length stored in len1 for word*/ 
  int len1 = strlen(word);
/*getting the length stored in len2 for format string*/  
  int len2 = strlen(format);
  int pos= 0, initial = 0, valuehash = 1, num=10;
  for (index = 0; index < len1- 1; index++){
    valuehash = (valuehash * num) % max;
  }
    hash(word, format, max , len1,pos, num, initial );
    checking(word, format, len2, len1, pos,  initial);
 /*we are checking the intial with lenght1 and 2, if is less make it postive by adding max*/  
for (index = 0; index <= len2 - len1; index++) {
    if ( initial < 0)
         initial= ( max +initial);
 if (index <len2 - len1) {
       initial = (num * ( initial - format[index] * valuehash) +format[index +len1]) % max;
 /* we have final output in form of integer to specify the positin*/
    }
   }
}
/* input :
enter the string format abcdehu                                                                                                                                                      
give pattern ab  
output: PATTERN IS AT POSITION 1 
time complexity  O(n+m) for searching at instance
space complexity O(1)
*/ 


<|start_filename|>Java/math/Neon_number.java<|end_filename|>
/*
Program by :: <NAME>
Date :: 13-03-2021

Aim :: To check the given number is Neon or not.

What is Neon number ?
A Neon number is a number where the sum of digits of square of the number is equal to that number.

                        ALGO
1. Take a number from the user
2. Find the square of the given number.
3. By using loop , find the sum of the square of the all individual digits
4. Check condition if our sum is equal to the user given number
        (a.) Return true
        (b.) Else return false.
5. Exit
 */

import java.util.Scanner; // for scanner class

public class Neon_number {

    public static void main(String[] args) {

        System.out.print("\nEnter the number :: ");

        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        if (isNeon(n)) // checking the number is Neon or not
            System.out.println(n + " is Neon number :)");
        else
            System.out.println(n + " is not a Neon number :(");

    }

    /**
     * method to check the given number is Neon or not
     *
     * @param num for storing the value given by user
     * @return ture if number is Neon else return false
     */
    public static boolean isNeon(int num) {

        // Accumulator :-> A running total is a sum of numbers that accumulate with each iteration of a loop
        int n, sum = 0; // assuming sum as accumulator

        n = num * num;
        while (n != 0) { // running loop till we consider all the digits of the squared number
            sum += (n % 10); //getting the last digit & adding the last digit to sum
            n /= 10; // neglecting the last number which we have counted
        }

        if (sum == num)
            return true;

        return false;
    }
}

/*
Test case :: T = 1
Enter the number :: 9   // input
9 is Neon number :)     // output

Explanation :->
1. square the number i,e.. 9 * 9 = 81
2. add up all the individual digits i,e.. 8 + 1 = 9
3. check the sum is equal to the given number ?  i,e.. ( 9 == 9 ? true : false )

Test case :: T = 2
Enter the number :: 0   // input
9 is Neon number :)     // output

Test case :: T = 3
Enter the number :: 1   // input
9 is Neon number :)     // output

Test case :: T = 4
Enter the number :: 3   // input
9 is not a Neon number :(     // output

Time complexity :: O(log(n))
Space complexity :: O(1)

 */


<|start_filename|>C-Plus-Plus/cp/LowestCommonAncestor_in_Tree.cpp<|end_filename|>
/* if you are given two nodes of a tree , this program will calculate 
   the Lowest Common Ancestor(LCA) of those two nodes
   Definition of LCA : 
   Let T be a rooted tree. The lowest common ancestor between two nodes n1 and n2 is defined 
   as the shared ancestor of n1 and n2 that is located farthest from the root T. 
*/
#include <bits/stdc++.h>
using namespace std;
vector<long long int> adj[100005];
long long int height_of_node[100005];
long long int parent_node[100005][18];

void calculate_parent_and_height_node(long long int node, long long int first_parent, long long int current_height = 1)
{
    height_of_node[node] = current_height;
    parent_node[node][0] = first_parent;
    for (int i = 1; i < 18; i++)
    {
        parent_node[node][i] = parent_node[parent_node[node][i - 1]][i - 1];
    }
    for (auto adjacent_node : adj[node])
    {
        if (adjacent_node != first_parent)
            calculate_parent_and_height_node(adjacent_node, node, current_height + 1);
    }
}
long long int LCA(int node1, int node2)
{

    // considering that height of node1 is always the maximum
    if (height_of_node[node1] < height_of_node[node2])
        swap(node1, node2);

    long long int difference_in_level = height_of_node[node1] - height_of_node[node2];
    // we are bring node1 and node 2 in the same level using binary lifting technique
    long long int count = 0;
    while (difference_in_level)
    {
        if (difference_in_level & 1)
        {
            node1 = parent_node[node1][count];
        }
        count++;
        difference_in_level = difference_in_level >> 1;
    }
    // if after bringing both nodes at same level, node1=node2 , then that is only the lca .
    if (node1 == node2)
    {
        // we could return any of the node as both are same.
        return node1; 
    }
    //Applying binary lifing and trying to reach the fartherst unequal nodes
    for (int powers_of_two = 17; powers_of_two >= 0; powers_of_two--)
    {
        if (parent_node[node1][powers_of_two] != parent_node[node2][powers_of_two])
        {
            node1 = parent_node[node1][powers_of_two];
            node2 = parent_node[node2][powers_of_two];
        }
    }
    // after applying binary liftine we know that the first parent of node1 will always be the LCA.
    return parent_node[node1][0];
}
int main()
{
    /*
   Assuming that first line of our input contains N i.e. total no of nodes in a tree.
   next N-1 line contains the parent of each node.
   and then Q queries ,
   where every query contains two nodes and we need to print the LCA between them.
    */
    int total_no_node;
    cout<<"Enter the Total number of nodes in a tree\n";
    cin >> total_no_node;
    cour<<"Enter the parent node of every node starting fron 2\n";
    for (int i = 2; i <= total_no_node; i++)
    {
        int node1;
        cin >> node1;
        // creating a bi- directional tree
        adj[node1].push_back(i);
        adj[i].push_back(node1);
    }
    // we are calculating the parent of all nodes and there height
    // Assuming 1 to the root node , as root node has no parent so we
    // consider it as 0.
    calculate_parent_and_height_node(1, 0);
    cout<<"Enter Total Number of queries\n";
    int query;
    cin >> query;
   cout<<"Enter two nodes for each query \n";
    while (query-- > 0)
    {
        int node1, node2;
        cin >> node1 >> node2;
        int lca = LCA(node1, node2);
        cout<<"LCA of Numbers "<<node1<<" and "<<node2<<" is : ";
        cout << lca << "\n";
    }

    return 0;
}

/* SAMPLE INPUT :
    Enter the Total number of nodes in a tree
    5 
    Enter the parent node of every node starting fron 2
    1 1 3 3
    Enter Total Number of queries
    3
    Enter two nodes for each query
    4 5
    2 5
    1 4
*/
/* Sample OUPUT :
   LCA of Numbers 4 and 5 is 3
   LCA of Numbers 2 and 5 is 1
   LCA of Numbers 1 and 4 is 1
*/
/* Time complexity Ansalysis : 
   Building of Tree takes O(N) time Complexity 
   Calulating the parent and height function takes another O(18*N) time complexity
    Then EACH query TAKES LOG(N) time to process the query and find the LCA
        
   Therefore, TOTAL Time COMPLEXITY O(N+(18*N)+(Q*LOG(N)) which is same as saying O(Q*LOG(N);
   
   SPACE COMPLEXITY :
    we ARE USING SPACE COMPLEXITY OF O(N*18) as maximum value of N can be 10^5, 
    so we have made an fixed Array size of [10^5][18] for the ease and better understanting 
    of the code.
    
    There total Space complexity equals O(N) as 18 is a constant.
*/


<|start_filename|>Java/ds/preOrderTraversal.java<|end_filename|>
import java.util.*;
import java.util.Stack;
 class Node {
     Node left;
     Node right;
     int data;

     Node(int data) {
         this.data = data;
         left = null;
         right = null;
     }
 }
 class preOrderTraversal{
                //recursive
     public static void preOrderRec(Node root){
         if(root == null)
         return;
         else{
             System.out.print(root.data+" ");
             preOrderRec(root.left);
             preOrderRec(root.right);
         }
     }
                //iterative
   public static void preOrderIte(Node root) {
         if (root == null) { 
             return; 
         } 
         Stack<Node> stack = new Stack<>();
         stack.push(root);
         while (!stack.empty()) {
             Node node = stack.pop();
             if (node != null) {
                 System.out.print(node.data + " ");
                 stack.push(node.right);
                 stack.push(node.left);
             }
         }
    }
 	public static Node insert(Node root, int data) {
         if(root == null) {
             return new Node(data);
         } else {
             Node curr;
             if(data <= root.data) {
                 curr = insert(root.left, data);
                 root.left = curr;
             } else {
                 curr = insert(root.right, data);
                 root.right = curr;
            }
             return root;
         }
     }
     public static void main(String[] args) {
         Scanner sc = new Scanner(System.in);
         System.out.println("Enter number of nodes:");
         int t = sc.nextInt();
         System.out.println("Enter nodes:");
         Node root = null;
         while(t-- > 0) {
             int data = sc.nextInt();
             root = insert(root, data);
         }
         System.out.print("Recursive approach: ");
         preOrderRec(root);
         System.out.println();
         System.out.print("Iterative approach: ");
         preOrderIte(root);
         sc.close();
     }	
 }
 /*                         
 sample Input                  Input:      
      1                        Enter no of nodes : 6             
       \                       Enter nodes : 1 2 5 3 6 4
        2  
         \                     output:
          5                    1 2 5 3 4 6 
         / \                   
        3   6
         \
          4  
 Sample Output
 1 2 5 3 4 6 
 */ 

<|start_filename|>C/other/Swap_two_nibbles.c<|end_filename|>
//algorithm for swap nibbles in O(1) time complexity and O(1) space complexity

#include <stdio.h>

int swapnibbles(int num)
{
    return (((num & 0x0F) << 4) | ((num & 0xF0) >> 4));
}

int main()
{   
    //taking input
    int num;
    printf(" Enter a number : \n");
    scanf("%d",&num);
    int result = swapnibbles(num);
    printf("output is  %d\n",result);
}

/*
Input:
Enter a number: 50
Output: 
35
*/ 


<|start_filename|>C-Plus-Plus/dp/string_permutations.cpp<|end_filename|>
/**
 * @author omkarlanghe
 * Given a string S. The task is to print all permutations of a given string.
 * Input:
 * The first line of input contains an integer T, denoting the number of test cases.
 * Each test case contains a single string S in capital letter.
 * 
 * Output:
 * For each test case, print all permutations of a given string S with single space
 * and all permutations should be in lexicographically increasing order.
 * 
 * Example:
 * Input:
 * 2
 * ABC
 * ABSG
 * 
 * Output:
 * ABC ACB BAC BCA CAB CBA 
 * ABGS ABSG AGBS AGSB ASBG ASGB BAGS BASG BGAS BGSA BSAG BSGA GABS GASB GBAS GBSA GSAB GSBA SABG SAGB SBAG SBGA SGAB SGBA
*/
#include <iostream>
#include <cstring>

/** @brief function to swap two characters */
void swap(char *x, char *y) {
    char temp = *x;
    *x = *y;
    *y = temp;
}

/** @brief function to find all permutations of a given string */
void string_permutations(char str[], int l, int r) {
    int i;
    if (l == r) {
        std::cout << str << " ";
    } else {
        for (int i = l ; i <= r ; i++) {
            swap((str + l), (str + i));
            string_permutations(str, l + 1, r);
            swap((str + l), (str + i));
        }
    }
}

/** Main function */
int main() {
    int t, n;
    std::cout << "Enter test cases : " << std::endl;
    std::cin >> t;

    while (t--) {
        char str[5];
        std::cout << "Enter the string : " << std::endl;
        std::cin >> str;
        int n = strlen(str);
        string_permutations(str, 0, n-1);
        std::cout << std::endl;
    }
    return (0);
}


<|start_filename|>C-Plus-Plus/other/whether_string_is_subsequence.cpp<|end_filename|>
/*
Given two strings s1 and s2, check if s1 is a subsequence of s2.
A subsequence of a string is a new string that is formed from the original string
by deleting some (can be none) of the characters
without disturbing the relative positions of the remaining characters.
*/

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

bool check_is_Subsequence(string s1, string s2)
{
    int size_1 = s1.size();
    int size_2 = s2.size();
    if(size_1 > size_2)
    {
        /* here string s1 size is greater than string s2 size
        so it can't be a subsequence of string s2.
        */
        return false;
    }
    if(size_1 <= size_2)
    {
        int j = 0;
        for(int i = 0; i < s2.size(); i++)
        {
            if(s1[j] == s2[i])
            {
                /* if s1[j] is same of s2[i]
                then we will increment j
                */
                j++;
            }
        }
        if(j == size_1)
        {
            /* here string s1 size is equal to j
              so it is a subsequence of string s2.
            */
            return true;
        }
        else
        {
            return false;
        }

    }
}
int main()
{
    cout << "Enter two strings : \n";
    string s1;
    cin >> s1;
    string s2;
    cin >> s2;
    bool is_Subsequence = check_is_Subsequence(s1, s2);
    if(is_Subsequence)
    {
        cout << "Yes! string s1 is a subsequence of string s2\n";
    }
    else
    {
        cout << "No! string s1 is NOT a subsequence of string s2\n";

    }
}

/*
Standard Input and Output

1.
Enter two strings :
abc
ahbgdc

Yes! string s1 is a subsequence of string s2

2.
Enter two strings :
sgdtb
vrdgtrv

No! string s1 is NOT a subsequence of string s2

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

*/


<|start_filename|>C-Plus-Plus/graphs/Preorder_Traversal.cpp<|end_filename|>
//This is the pre-order traversal of the binary tree
/*
Author - <NAME>
*/

/*
Working of the algorithm 
   1. Visit the root.
   2. Traverse the left subtree until you find null
   3. Traverse the right subtree until you find null
*/



#include <iostream>
using namespace std;


struct node
{
    int data;
    struct node *left, *right;
};

//Creation of new node
struct node *newNode(int item)
{
    struct node *temp = new node;
    temp->data = item;
    temp->left = temp->right = NULL;
    return temp;
};

//insertion of the node
struct node * insert(struct node *root, int element)
{
    if(root == NULL)
        return newNode(element);
    if(root->data > element)
        root->left = insert(root->left, element);
    else if (root->data < element)
        root->right = insert(root->right, element);
    return root;
}

//Pre-order traversal
void preorder(struct node *root)
{
    if(root == NULL)
        return;
    cout << root->data << " ";
    preorder(root->left);
    preorder(root->right);
}

int main()
{
    struct node *root = NULL;
    root = insert(root, 60);
    insert(root, 40);
    insert(root, 50);
    insert(root, 70);
    insert(root, 80);
    insert(root, 10);


    cout<<"Pre-order is " <<endl;
    preorder(root);
    return 0;
}

<|start_filename|>Java/cp/HappinessProblem.java<|end_filename|>
/*
There is an array of n integers. There are also 2 disjoint sets, A and B, each containing m integers.
You like all the integers in set A and dislike all the integers in set B. Your initial happiness is 0.
For each i integer in the array, if i e A , you add 1 to your happiness. If i e B, you add -1 to your happiness.
Otherwise, your happiness does not change. Output your final happiness at the end.
	Input Format

	The first line contains integers n and m separated by a space.
	The second line contains n integers, the elements of the array.
	The third and fourth lines contain m integers, A and B, respectively.

	Output Format

	Output a single integer, your total happiness.

Problem Link: https://www.hackerrank.com/challenges/no-idea/problem
*/

import java.util.Scanner;

public class HappinessProblem {
    public static int findHappiness(int[] arr, int A[], int B[]) {
        int happiness = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < A.length; j++) {
                if (arr[i] == A[j]) {
                    happiness++;
                    break;
                }
                if (arr[i] == B[j]) {
                    happiness--;
                    break;
                }
            }
        }
        return happiness;
    }

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter n and m:");
        // 1st line of input
        int n = sc.nextInt(), m = sc.nextInt();
        int[] A = new int[m], B = new int[m], arr = new int[n];

        System.out.println("Enter elements of array:");
        // 2nd Line of input
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }

        System.out.println("Enter elements of A:");
        // 3rd line of input
        for (int i = 0; i < m; i++) {
            A[i] = sc.nextInt();
        }

        System.out.println("Enter elements of B:");
        // 4th line of input
        for (int i = 0; i < m; i++) {
            B[i] = sc.nextInt();
        }

        int happiness = findHappiness(arr, A, B);
        System.out.println("Happiness: " + happiness);

        sc.close();
    }
}

/*
 * Sample input: Enter n and m: 3 2 Enter elements of array: 1 5 3 Enter
 * elements of A 3 1 Enter elements of B: 5 7
 *
 * Sample output: Happiness:1
 *
 * Time complexity: O(n^2) Space complexity: O(n)
 */

<|start_filename|>C-Plus-Plus/cp/max_sum_subarray_of_size_k.cpp<|end_filename|>
/**
 * Maximum Sum Subarray od Size k
 * Cpp program to find the maximum currentSum of a subarray of fixed size k,
 * given an array of integers, using the 'Sliding Window Technique',
 */

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

// Returns maximum Sum in a subarray of size k
int max_sum_subarray(int len, int arr[], int k)
{
    int currentSum = 0;
    int maxSum = INT_MIN;
    //Pointers to represent start and end of every window
    int start = 0, end = 0;
    //Finding sum of all possible k-sized windows, one by one
    while (end < len) {
        currentSum = currentSum + arr[end];
        //Increment end if current window size is less than k
        if (end - start + 1 < k)
            end++;
        else if (end - start + 1 == k) {
            maxSum = max(currentSum, maxSum);
            //Compute sums of remaining windows by removing
            // first element of previous window
            currentSum = currentSum - arr[start];
            //slide the  window
            start++;
            end++;
        }
    }
    return maxSum;
}

int main()
{
    //taking input from user
    int len, k;
    cout << "Enter length of array: ";
    cin >> len;
    cout << "Enter array elements: ";
    int arr[len];
    for (int start = 0; start < len; start++)
        cin >> arr[start];
    cout << "Enter size of window: ";
    cin >> k;
    cout << "Maximum currentSum of a subarray of size k: ";
    cout << max_sum_subarray(len, arr, k);
}

/*
    Test cases:

    INPUT:-
    Enter length of array: 7
    Enter array elements: 2 5 1 8 2 9 1
    Enter size of window: 3
    OUTPUT:
    Maximum currentSum of a subarray of size k: 19

    INPUT
    length of array: 10
    Enter array elements: 1 7 -2 4 5 2 1 6 11 -4
    Enter size of window: 3
    OUTPUT
    Maximum sum of a subarray of size 3: 18

    Time complexity: O(n)
    Space complexity: O(1)

*/


<|start_filename|>Julia/math/neon_number.jl<|end_filename|>
"""Julia program to check if a number is a Neon Number or not
A neon number is a number where the sum of digits of square of the number is equal to the number.
"""

function check_neon_num(n)
    sum = 0
    temp = n ^ 2
    while(temp != 0)
        sum = sum + (temp % 10)
        temp = temp  ÷ 10
    end
    if(sum == n)
        return true
    else
        return false
    end
end


print("Enter the number: ")
n = readline()
n = parse(Int, n)
res = check_neon_num(n)
if res
    println("The given number $n is a Neon Number.")
else
    println("The given number $n is not a Neon Number.")
end


"""
Time Complexity: O(log(num)), where 'num' is the given number
Space Complexity: O(1)

SAMPLE INPUT AND OUTPUT

SAMPLE 1
Enter the number: 0
The given number 0 is a Neon Number..

SAMPLE 2
Enter the number: 14
The given number 14 is not a Neon Number.

"""


<|start_filename|>Java/ds/IntersectionPointOfLL.java<|end_filename|>

class IntersectionPointOfLL {
    static class Node {

        int data;
        Node next;
    };

    static int intesection(Node head1, Node head2) {
        Node curr1 = head1;
        Node curr2 = head2;

        if (curr1 == null || curr2 == null)
            return -1;

        while (curr1 != null && curr2 != null && curr1 != curr2) {
            curr1 = curr1.next;
            curr2 = curr2.next;

            if (curr1 == curr2)
                return curr1.data;
            if (curr1 == null)
                curr1 = head2;
            if (curr2 == null)
                curr2 = head1;
        }

        return curr1.data;
    }

    public static void main(String[] args) {

        Node newNode;

        Node head1 = new Node();
        head1.data = 10;

        Node head2 = new Node();
        head2.data = 3;

        newNode = new Node();
        newNode.data = 6;
        head2.next = newNode;

        newNode = new Node();
        newNode.data = 9;
        head2.next.next = newNode;

        newNode = new Node();
        newNode.data = 15;
        head1.next = newNode;
        head2.next.next.next = newNode;

        newNode = new Node();
        newNode.data = 30;
        head1.next.next = newNode;

        head1.next.next.next = null;

        System.out.print(intesection(head1, head2));
    }

}
// O/P: 15

// Other examples

// if we put the values of 1st and 2nd Linked List as :
// 1st : 1->2->3->4->5->6
// 2nd : 7->4->9->3

// 4 is the intersection point

// if we put the values of 1st and 2nd Linked List as :
// 1st 3->8->9->12->10
// 2nd 10->12->80

// 12 is the intersection point


<|start_filename|>C-Sharp/other/Unique_Number_III.cs<|end_filename|>
//Unique_Number_III
//Given an array that contains all elements occurring 3 times, but one occurs only once. Find that unique element.

using System.IO;
using System;

class Neoalgo {
  static void Main() {
    int[] count = new int[64];
    int len, no, i;
    Console.WriteLine("Enter number of element:");
    len = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("Enter space separated elements:");
    for (i = 0; i < len; i++) {
      //Reading array element
      no = Convert.ToInt32(Console.ReadLine());

      int j = 0;
      //"AND" each element of the array with each set digit
      while (no > 0) {
        int last_bit = no & 1;
        count[j] += last_bit;
        j++;
        no = no >> 1;
      }
    }

    //consider all bits whose count is not multiple of 3
    int num = 1;
    int ans = 0;
    for (i = 0; i < 64; i++) {
      count[i] %= 3;
      ans += (count[i] * num);
      num = num << 1;
    }
    Console.Write("unique num is:");
    Console.Write(ans);
  }
}
/* output

Enter number of element: 7
Enter space separated elements: 10 10 12 21 21 10 21
unique num is: 12

Time Complexity:O(n)
*/



<|start_filename|>C-Plus-Plus/cp/Binary_Coded_String.cpp<|end_filename|>
/*
Given a binary string s and an
integer k.
Print True if every binary code
of length k is a substring of s.
Otherwise, Print False.

Constraints:
1 <= s.length <= 5 * 10^5
s consists of 0's and 1's only.
1 <= k <= 20
*/

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

/*
This Function will check all string 
of length k present in given string 
s or not.
*/

bool hasAllCodes(string s, int k) 
{
    int length,totalBinaryString,Z,i;
    length=s.length();
    totalBinaryString=pow(2,k);
    int A[2022600]={0};
    Z=0;
    for(i=0;i<k;i++)
    {
        if(i!=0  &&  Z!=0)
            Z=(Z<<1);
        if(s[i]=='1')
            Z++;
    }
    A[Z]=1;
    for(i=k;i<length;i++)
    {
        if(Z>=(pow(2,k-1)))
            Z-=(pow(2,k-1));
        if(Z!=0)
            Z=(Z<<1);
        if(s[i]=='1')
            Z++;
        A[Z]=1;
    }
    for(i=0;i<totalBinaryString;i++)
    {
        if(A[i]==0)
            return false;
    }
    return true;
}

int main()
{
    string S;
    int K;
    cout<<"Enter an String"<<endl;
    cin>>S;
    cout<<"Enter the integer"<<endl;
    cin>>K;
    bool Ans=hasAllCodes(S,K);
    if(Ans==true)
        cout<<"Yes"<<endl;
    else
        cout<<"No"<<endl;
    return 0;
}

/*
Time Complexity=O(N)
Space Complexity=O(2^K)
where N is the length of the given 
string and K is the given integer.

Sample Input Output
Input:
Enter an String
00110
Enter the integer
2
Output:
Yes
*/



<|start_filename|>Java/graphs/BFS.java<|end_filename|>
import java.util.*;

public class BFS {

	public static void breadthFirst(int edges[][],int V) {
//		A visited array to mark if the node is visited then not to go there again
		boolean visited[]=new boolean[V];
		
		for(int i=0;i<V;i++) {
			if(!visited[i]) {
				breadthFirstHelper(edges,visited,i);
			}
		}
	}
	
	public static void breadthFirstHelper(int edges[][],boolean visited[],int sv) {
		
		int V=edges.length;
		
		visited[sv]=true;
		
		Queue<Integer> queue=new LinkedList<Integer>();
		queue.add(sv);
		
		while(!queue.isEmpty()) {
			
			int size=queue.size();
			
			for(int i=0;i<size;i++) {
				int frontNode=queue.poll();
				for(int j=0;j<V;j++) {
					if(edges[frontNode][j]==1&&!visited[j]) {
						queue.add(j);
						visited[j]=true;
					}
				}
				System.out.print(frontNode+" ");
			}
		}
		
	}
	
	public static void main(String[] args) {
		
		Scanner sc=new Scanner(System.in);
	
		System.out.println("Enter the number of vertices in Graph : ");
		int V=sc.nextInt();
		
		System.out.println("Enter the number of edges in the Graph : ");
		int E=sc.nextInt();
		
//		Adjaceny Matrix :
		int edges[][]=new int[V][V];
		
//		Taking edges as input :
		System.out.println("Enter the edges :");
		for(int i=0;i<E;i++) {
			int sv=sc.nextInt();
			int ev=sc.nextInt();
			edges[sv][ev]=1;
			edges[ev][sv]=1;
		}
		
		System.out.println("BFS Traversal : ");
		breadthFirst(edges,V);

	}
	
/*
Sample Case : 

Enter the number of vertices in Graph : 
4
Enter the number of edges in the Graph : 
4
Enter the edges :
0 1
1 2
0 2
2 3
BFS Traversal : 
0 1 2 3 
*/
	 
}


<|start_filename|>C-Plus-Plus/cryptography/KeywordCipher.cpp<|end_filename|>
/*Below is an implementation of keyword cipher in C++. It is a form of
monoalphabetic substitution. A encryption is formed of alphabets from
[a-z] such that the first part of encrption contains unique letters of
the keyword and the rest are the remaining alphabets from [a-z]. That is,
until the keyword is used up, whereupon the rest of the ciphertext letters
are used in alphabetical order, excluding those already used in the key.*/

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

// This function generates the pad using the keyword
string generate_pad(string key) {

	int i = 0;
	string pad = "00000000000000000000000000";
	int count = 0;
	
	// Ignoring the spaces in the given keyword
	while(i < key.length()) {	
		if(key.at(i) == ' ') {
			i = i + 1;
			continue;
		}

		// Checking keyword alphabet-wise
		int missing = 0;
		for(int j = 0; j < key.length(); j++) {
			if(key.at(i) != pad.at(j)) {
				missing += 1;
			}
		}

		// Adding the unique words of key to pad
		if(missing == key.length()) {
			pad.at(count) = key.at(i);
			count += 1;
		}
		i = i + 1;
	}
	// Till here we get the first half of the pad

	string alphabet = "abcdefghijklmnopqrstuvwxyz";

	i = 0;
	// This while loop forms the remaining pad
	while(i < 26) {
		int not_present = 0;
		for(int j = 0; j < 26; j++) {
			if(alphabet.at(i) != pad.at(j)) {
				not_present += 1;
			}
		}
		
		/* Whatever alphabets from [a-z] are not present
		in the pad till now, add them to the pad.*/
		if(not_present == 26) {
			pad.at(count) = alphabet.at(i);
			count++;
		}
		i++;
	}
	// Return the length 26 pad
	return pad;
}

// This is the encryption function
string encrypt(string plaintext, string key) {
	
	// Generate the pad using the above function
	string pad = generate_pad(key);
	string alphabet = "abcdefghijklmnopqrstuvwxyz";

	// Replace all sapces in plaintext with underscores
	for(int i = 0; i < plaintext.length(); i++) {
		if(plaintext.at(i) == ' ') {
			plaintext.at(i) = '_';
		}
	}

	// Declare and initialize the encrypted string
	string encrypted;
	for(int i = 0; i < plaintext.length(); i++) {
		encrypted += "0";
	}
	
	for(int i = 0; i < plaintext.length(); i++) {
		
		/*If the message has space, add space to the
		encrypted message at the same index.*/
		if(plaintext.at(i) == '_') {
			encrypted.at(i) = ' ';
		}
		
		/*else replace it with the corresponding
		position in the pad*/
		else {
			int index = 0;
			for(int j = 0; j < alphabet.length(); j++) {
				if(plaintext.at(i) == alphabet.at(j)) {
					index = j;
				}
			}
			encrypted.at(i) = pad.at(index);
		}
	}
	// Return the encrypted message
	return encrypted;
}

int main() {

	// Take plaintext as input from the user
	string plaintext;
	cout << "Enter a plaintext to encrypt: ";
	getline(cin, plaintext);
	// Converting the plaintext to all lowercase
	transform(plaintext.begin(), plaintext.end(), plaintext.begin(), ::tolower);

	// Taking keyword as input from the user
	string key;
	cout << "Enter a key to encrypt      : ";
	getline(cin, key);
	// Converting the keyword to all lowercase
	transform(key.begin(), key.end(), key.begin(), ::tolower);

	// Calling the encrypt function and printing the ciphertext
	cout << "The encrypted plaintext is  : " << encrypt(plaintext, key) << endl;
	return 0;
}

/* Sample I/O:
	Enter a plaintext to encrypt: this is a secret
	Enter a key to encrypt      : mercury
	The encrypted plaintext is  : qbdp dp m purouq
*/



<|start_filename|>C/search/IterativeBinarySearch.c<|end_filename|>
// C program to implement Binary Search using Iterative Approach i.e Using Loop
#include <stdio.h>

/*(l is leftmost index , r the rightmost index and val is the element we are
   searching for) If value is present return the index else return -1
    */
int binarySearch(int arr[], int l, int r, int val) {
  int mid = 0;
  while (l <= r) {
    // Storing the middle index of the array
    mid = (l + r) / 2;
    // value matched with X i.e searched element
    if (arr[mid] == val) {
      return mid;
    }
    /* If val is less than the mid element
            Check the left sub-array */
    else if (val < arr[mid]) {
      r = mid - 1;
    }
    /* If val is greater than the mid element
    Check the right sub-array */
    else {
      l = mid + 1;
    }
  }
  /* value not found in the array
  return with -1 response */
  return -1;
}

int main() {
  int arr[] = {-2, 5, 14, 17, 19, 27};
  // searched value assuming to be val=19
  int val = 19;
  int n = sizeof(arr) / sizeof(arr[0]);
  int index = binarySearch(arr, 0, n - 1, val);

  if (index == -1) {
    printf("\nThe element %d is not present in the array", val);
  } else {
    printf("\nThe element %d is present at index: %d", val, index);
  }
  return 0;
}

// Time Complexity: O(logn)
// Space Complexity: O(n)

/* Sample Test Case:
Test-1:
        IF searched value is 19
        i.e val=19
        ------
        Output
        ------
        The element 19 is not present at index: 4

Test-2:
        IF searched value is 29
        i.e val=29
        ------
        Output
        ------
        The element 29 is not present in the array
 */


<|start_filename|>C-Plus-Plus/math/remove_invalid_parentheses.cpp<|end_filename|>
/*
This problem is solved using backtracking.
In this problem we will be given string of parenthesis which will open and closing parenthesis.
We will have to remove minimum no. of parenthesis to make the string valid and will print all possible valid strings made by min. removal.
*/
#include <bits/stdc++.h>
using namespace std;

// this function is to find no. of parenthesis to be removed from the string
int minRemoval(string str){
    stack<int> s;
    for(int i=0;i<str.length();i++){
        // if it is a open parentheses then we will always push
        if(str[i] == '('){
            s.push(str[i]);
        }
        // if closed parentheses
        else if(str[i] == ')'){
            // if stack is empty then we will push
            if(s.size() == 0){
                s.push(str[i]);
            }
            // if stack top is closed parentheses then we will push
            else if(s.top() == ')'){
                s.push(str[i]);
            }
            // if stack top is open parentheses then we will pop
            else {
                s.pop();
            }
        }
    }
    // size left will me the minimum parentheses to be removed to make the string valid
    return s.size();
}

void validParentheses(string str, int rm, unordered_set<string> &result){
    if(rm == 0){
        int remove = minRemoval(str);
        if(remove == 0){
            result.insert(str);
        }
        return;
    }
    for(int i=0;i<str.length();i++){
        string left = str.substr(0,i);
        string right = str.substr(i+1);
        validParentheses(left + right,rm-1,result);
    }
}

// driver code
int main() {
    // Input the parentheses string
    string str;
    cin>>str;
    unordered_set<string> result;
    // no. of parentheses to be removed
    int remove = minRemoval(str);
    //recursive call
    validParentheses(str,remove,result);
    for(auto i:result){
        cout<<i<<endl;
    }
    return 0;
}

/*
Input - ()())()
Output - 
()()()
()())()
Time Complexity - O(n!)
*/


<|start_filename|>C-Plus-Plus/cp/Merge_string_alternatively.cpp<|end_filename|>
/*

Problem:
You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. 
If a string is longer than the other, append the additional letters onto the end of the merged string.
Return the merged string.

Input Format:
The first line consists of an integer T which denotes the number of test cases.
For each test case we enter two strings to be merged alternatively

Output Format:
For each test case we get a alternatively merged string.

Explanation:
First we alternatively add both the strings to the resultant string till the length of the smallest string (both strings can also be equal length). 
After that we add the substring of the remaining longer string to resultant string if the length of both strings are not equal.

*/

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

/* A function that will take 2 string as input and return the resultant merged string formed alternatively from the inputted strings */
string mergeAlternately(string word1, string word2) {
    string ans="";

    /* A variable that will take the size of the smallest string among word1 and word2 */
    int less=min(word1.length(),word2.length());    
    int i=0,j=0; 

    /* Loop to alternatively add word by word from each string to resultant string */
    while(i<less || j<less){    
        if(j>=i){
            ans+=word1[i];
            i++;
        }
        else{
            ans+=word2[j];
            j++;
        }
    }

    /* If both strings are of unequal sizes then add the rest of substring to the resultant string */
    if(word1.length()!=word2.length()){     
        if(word1.length()>less){
            ans+=word1.substr(less,word1.length());
        }
        else{
            ans+=word2.substr(less,word2.length());
        }
    }

    return ans;
}

int main(){
    int t;
    cin>>t;
    while(t--){
        string word1,word2;
        cin>>word1>>word2;
        cout<<mergeAlternately(word1,word2)<<endl;
    }
}

/*

Time complexity: O(N) where N is the length of the longest string.
Space complexity: O(M) where M is the summation of length of both strings.

Sample input:
2
abc pqr
abcd pq

Sample Output:
apbqcr
apbqcd

*/


<|start_filename|>C/math/DecimalToBinary.c<|end_filename|>
/*
AIM :: To take any decimal number from the user 
       and convert that given decimal number into binary number
       using stack (by Array represention).
*/

#include <stdio.h>
//MACRO definition
#define SIZE 50

//Array representation of stack
int stack[SIZE];
int top = -1;

//function to check whether stack is empty or not by returning 1 for empty and 0 for non-empty
int isEmpty()
{
    if (top == -1)
        return 1;

    return 0;
}

//function to check whether stack is full or not by returning 1 for full and 0 for not-full
int isFull()
{
    if (top == SIZE - 1)
        return 1;

    return 0;
}

//function to insert value into the stack
void push(int r)
{
    if (isFull())
        printf("\nSTACK OVERFLOW\n");
    else
        stack[++top] = r;
}

//function for delete value from the stack
int pop()
{
    if (isEmpty())
        printf("\nSTACK UNDERFLOW\n");
    else
        return stack[top--];
}

int main()
{
    //number for storing decimal number given by user
    int number, num, reminder;

    printf("\nEnter decimal number: ");
    scanf("%d", &number);

    //preserving original number for further use
    num = number;
    while (num >= 1)
    {
        reminder = num % 2;
        push(reminder);
        num = num / 2;
    }

    printf("\nDECIMAL :: %d\n", number);
    printf("BINARY  :: ");

    while (!isEmpty())
        printf("%d", pop());

    return 0;
}

/*
TEST CASE

Enter decimal number: 10

DECIMAL :: 10
BINARY  :: 1010

TIME COMPLEXITY  :: O(n)
SPACE COMPLEXITY :: O(1)

*/


<|start_filename|>C-Plus-Plus/ds/inversion_vector.cpp<|end_filename|>
/****************************************************************************
 Author: <NAME>

 Create a singly linked list X of integers. A pair (xi,xj) is called an inversion of X if for i < j , xi > xj. The inversion vector of X is the sequence of integers d1, d2,.. dn such that dj is the number of elements greater than xj and to its left in the sequence, so 0 <= dj < j. Compute the inversion vector for a given permutation.
 Ex: Given link list X : 4-> 3-> 5-> 2-> 1->
 Inversion of X: 0, 1, 0, 3, 4
 ***************************************************************************/

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

//node structure
typedef struct node
{
    int value;
    struct node *next;
}node;

//global nodes
node *newnode, *ptr, *inv;
node *first = NULL, *last = NULL;

//creation of new node
node* create_node(int val)
{
    newnode = (node *)malloc(sizeof(node));
    if (newnode == NULL)
    {
        cout << endl << "Creation unsuccessful";
        return 0;
    }
    else
    {
        newnode->value = val;
        newnode->next = NULL;
        return newnode;
    }
}

//function to insert node at end
void insert_node()
{
    int val;
    cout << "Enter value of the Node:\t";
    cin >> val;
    newnode = create_node(val);
    if (first == last && last == NULL)
    {
        first = last = newnode;
        first->next = NULL;
        last->next = NULL;
    }
    else
    {
        last->next = newnode;
        last = newnode;
        last->next = NULL;
    }
 cout << val << " inserted as node";
}

//Function to calculate inversion vector
void inversion()
{
    //Empty condition
    if (first == NULL)
    {
        cout << endl << "No nodes in the list";
    }
    else
    {   
        //for every x
        for (ptr = first; ptr != NULL; ptr = ptr->next)
        {
            //set new count to zero
            int inversion_count = 0;
            //traverse from beginning to end to find how many elements satisfy condition
            for (inv = first; inv != ptr->next ; inv = inv-> next)
            {   
                //inversion condition
                if (inv->value > ptr->value)
                    inversion_count++;
            }
            cout << "   " << inversion_count;
        }
    }
}

//function to display linked list
void display()
{
    if (first == NULL)
        cout << endl << "No nodes in the list";
    else
        for (ptr = first;ptr != NULL;ptr = ptr->next)
            cout << ptr->value << " -> ";
}

//main driver code
 int main()
 {
    int choice;
    cout << endl << "---------------------------------";
    cout << endl << "1-Insert node";
    cout << endl << "2-Display current list";
    cout << endl << "3-Compute Inversion vector";
    cout << endl << "4-Exit";
    cout << endl << "---------------------------------";
    while (1)
    {
        cout << endl << endl << "Enter your choice : ";
        cin >> choice;

        switch (choice)
        {
        case 1:
            insert_node();
            break;

        case 2:
            cout << endl << "Current List :\t";
            display();
            break;

        case 3:
            cout << endl << "Inversion vector :";
            inversion();
            break;

        case 4:
            cout << "Program was terminated";
            exit(0);

        default:
            cout << endl << "Invalid Choice";
            break;
        }
    }
    return 0;
 }
/*
Time Complexity of Inversion Vector = O(n^2)
Space Complexity = O(n)

Sample Run:
---------------------------------
1-Insert node
2-Display current list
3-Compute Inversion vector       
4-Exit
---------------------------------

Enter your choice : 1
Enter value of the Node:        4
4 inserted as node

Enter your choice : 1
Enter value of the Node:        3
3 inserted as node

Enter your choice : 1
Enter value of the Node:        5
5 inserted as node

Enter your choice : 1
Enter value of the Node:        2
2 inserted as node

Enter your choice : 1
Enter value of the Node:        1
1 inserted as node

Enter your choice : 2

Current List :  4 -> 3 -> 5 -> 2 -> 1 ->

Enter your choice : 3

Inversion vector :   0   1   0   3   4

Enter your choice : 4
Program was terminated
*/


<|start_filename|>C-Plus-Plus/dp/Sprague_Grundy_Theorem.cpp<|end_filename|>
/*The game used to implement Sprague-Grundy is defined below

 -> There are 2 people playing this composite impartial game
 -> The second player writes an arbitrary string . 
 -> Then each player starting with the first player starts 
 	removing a continous substring which exists in a list of 
 	substrings that are possible to remove.
 -> The first player who can't remove a substring loses. */

#include <bits/stdc++.h>
using namespace std;
// Macros used 
typedef pair<int, int> pii;

#define maxs 33
#define INF 1e9

// Global Variables
int t, y, st[maxs][maxs], pc[maxs][maxs], kk[maxs][maxs];
string a, wq[maxs];

void process(int x)
{
	// Process the Grundy numbers for each input
	int g, h;
	pc[x][0] = -1;
	for (g = 0, h = -1; g < wq[x].size();)
	{
		while (h >= 0 && wq[x][g] != wq[x][h])
		{
			h = pc[x][h];
		}
		g++, h++;
		pc[x][g] = h;
	}
}
vector<pii> kmp(int x, string s)
{
	int g, h;
	vector<pii> all;
	for (g = 0, h = 0; g < s.size();)
	{
		while (h >= 0 && s[g] != wq[x][h])
		{
			h = pc[x][h];
		}
		g++, h++;
		if (h == wq[x].size())
		{
			all.push_back(pii(g - h, g));
			h = pc[x][h];
		}
	}
	return all;
}

// Sprague Grundy Theorem implemented
/*Note that after a player erases a substring S(a, b), 
in S(i, j), the game is split into two subgames, S(i, a-1) 
and S(b+1, j). Because a player can choose any game in his/her 
turn, the Grundy number of the game is simply the XOR of the 
Grundy numbers of the two subgames. */

int sprague_grundy(int nx, int ny)
{
	if (nx > ny)
		return 0;
	if (kk[nx][ny] == t)
		return st[nx][ny];
	int g, h, px, py, xr1, xr2, now;
	string s;
	vector<int> ss;
	vector<pii> all;
	for (g = nx; g <= ny; g++)
	{
		s += a[g];
	}
	for (g = 0; g < y; g++)
	{
		all = kmp(g, s);
		for (h = 0; h < all.size(); h++)
		{
			px = all[h].first, py = all[h].second;
			xr1 = (sprague_grundy(nx, nx + px - 1));
			xr2 = (sprague_grundy(nx + py, ny));
			ss.push_back(xr1 ^ xr2);
		}
	}
	sort(ss.begin(), ss.end());
	ss.erase(unique(ss.begin(), ss.end()), ss.end());
	/*A game is losing iff its Grundy number is zero. 
	So the first player, will win if G(1, |S|) is not zero.
	On the other hand, player 2 will win if G(1, |S|) is zero. */
	for (g = now = 0; g < ss.size(); g++, now++)
	{
		if (ss[g] != now)
			break;
	}
	st[nx][ny] = now;
	kk[nx][ny] = t;
	return now;
}

/*Let G(i, j) be the Grundy number of the substring 
S(i, j). Then G(i, j) = mex({G(i, a-1) XOR G(b+1, j) : S(a, b) 
exists in the dictionary and is a substring of S(i, j)} */
int main()
{
	int g, h, re;
	// Intitialising the array with value of INF
	for (g = 0; g <= 30; g++)
	{
		for (h = 0; h <= 30; h++)
		{
			kk[g][h] = INF;
		}
	}
	cout << "Enter Main String : ";
	cin >> a;
	cout << "Enter total number of substrings : ";
	cin >> y;
	cout << "Enter all " << y << " substrings : " << endl;
	for (g = 0; g < y; g++)
	{
		cin >> wq[g];
		process(g);
	}
	// Run the Sprague Grundy algo on each recursive combination
	re = sprague_grundy(0, a.size() - 1);
	// Outputting which player wins
	if (re == 1)
		cout << "Player 1 wins.";
	else
		cout << "Player 2 wins.";

	return 0;
}

/*
Time Complexity: O(n^2)

Sample Input:
Enter main string : spraguegrundy
Enter total number of substrings : 2
Enter all 2 substrings : 
spra
grundy

Sample Output: 
Player 2 wins.
*/


<|start_filename|>Java/other/three_Sum_problem.java<|end_filename|>
/* 

3 Sum problem

For a given array nums[], your task is to find the triplets  
whose sum add up to the target value given. 
The output is the triplet of the numbers which add up to target. 
For example:- 
if A + B + C = target then the output will be A, B, C. 
It is given that all the sets of triplets should be unique. 

*/  

import java.util.Scanner; 
import java.util.Arrays; 
import java.util.ArrayList; 
import java.util.List; 

class three_Sum_problem 
{ 
    //method for printing triplet 
    public List<Integer[]> threeSum(int nums[], int target) 
    { 
        Set<List<Integer[]>> tripletEvaluated = new Hashset<>(); 

        //if the array has no elements then we simpliy return  
        //empty list 
        if(nums.length == 0) 
            return new ArrayList<>(tripletEvaluated); 

        //else 
        Arrays.sort(nums); 

        //using two pointer approach 
        for(int i=0; i<nums.length; i++) 
        { 
            int leftptr = i + 1; 

            int rightptr = nums.length - 1; 

            while(leftptr < rightptr)
            { 
                int complement = target - num[i]; 

                int sum = nums[leftptr] + nums[rightptr]; 

                if(sum == complement) 
                { 
                    tripletEvaluated.add(Arrays.asList(nums[i], nums[leftptr], nums[rightptr])); 
                    leftptr++; 
                    rightptr--; 
                } 

                else if(sum > complement) 
                { 
                    rightptr--; 
                } 

                //else if sum < complement 
                else 
                { 
                    leftptr++; 
                } 
            } 
        } 
        return new ArrayList<>(tripletEvaluated); 
    } 

    //driver method 
    public static void main(String []args) 
    { 

        Scanner sc = new Scanner(System.in); 

        System.out.println("Enter the size of the array: "); 
        int size = sc.nextInt(); 

        System.out.println("Enter the target value: "); 
        int target = sc.nextInt();

        int nums[] = new int[size]; 
        System.out.println("Enter the elements of array: "); 
        for(int i = 0; i < size; i++) 
        { 
            nums[i] = sc.nextInt(); 
        } 

        List<Integer[]> tripletEvaluated = threeSum(nums, target); 

        System.out.println("The triplet values are: "); 
        for(Integer[] triplets: tripletEvaluated) { 
        for(int numb: triplets) 
        { 
            System.out.print(numb + " "); 
        } 
            System.out.println(); 
        } 
    } 
} 

/* 

EXAMPLES:- 

Example 1: 
Input-- 
Enter the size of the array: 6 
Enter the target value: 0 
Enter the elements of array: 1 2 -1 0 -2 1 
Output-- 
The triplet values are: [1, -1, 0] 
                        [2, 0, -2] 
                        [1, 1, -2] 

Example 2: 
Input-- 
Enter the size of the array: 0 
Enter the target value: 0 
Enter the elements of array: 0 
Output-- 
The triplet values are: 0 

Example 3: 
Input-- 
Enter the size of the array: 5 
Enter the target value: 0 
Enter the elements of array: 1 -1 -1 0 1 
Output-- 
The triplet values are: [1, -1, 0] 

TIME COMPLEXITY --> O(N^2) 

*/ 


<|start_filename|>C-Plus-Plus/dp/Unique_BST.cpp<|end_filename|>
// unique BSTs using DP
// Given n, how many structurally unique BST's that store values 1 ... n?

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

int uniqueBST(int n) {
	vector<int> count(n + 1);
	// for each 'i' number of nodes
	for (int i = 1; i <= n ; ++i) {
		for (int j = 0 ; j < i ; ++j) {
			// No. of trees if j is a root
			count[i] += max(count[j], 1) * max(count[i - j - 1], 1);
		}
	}
	return count[n];
}

int main() {
	int n;
	cout << "Enter value:";
	cin >> n;
	cout << "Number of Unique BSTs " << uniqueBST(n) << endl;

	return 0;
}

/*
output:
Enter value:3
Number of Unique BSTs 5
Time complexity : O(n)
*/


<|start_filename|>Java/other/UniqueIII.java<|end_filename|>
import java.util.HashMap;
import java.util.Scanner;

public class UniqueIII {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter number of elements:");
        int size = scanner.nextInt();
        int[] arr = new int[size];
        System.out.println("Enter array elements:");
        for (int i = 0; i < size; i++) {
            arr[i] = scanner.nextInt();
        }
        scanner.close();

        int result = findUnique(arr, size);

        if (result == -1) {
            System.out.println("No unique number found.");
        } else {
            System.out.println("Unique number:" + result);
        }
    }

    private static int findUnique(int[] arr, int length) {
        HashMap<Integer, Integer> freq = new HashMap<Integer, Integer>();
        for (int i = 0; i < length; i++) {
            if (freq.containsKey(arr[i])) {
                freq.put(arr[i], freq.get(arr[i]) + 1);
            } else {
                freq.put(arr[i], 1);
            }
        }

        for(Integer i : freq.keySet()) {
            if (freq.get(i) == 1) {
                return i;
            }
        }
        return -1;
    }
}
/*
 * Enter number of elements:
 * 7
 * Enter array elements:
 * 6 2 5 2 2 6 6
 * Unique number:5
 *
 * Time complexity: O(n)
 * Space complexity: O(n)
 */


<|start_filename|>Java/ds/MergeSortedArrays.java<|end_filename|>
/*
    Description: 
    Given two sorted arrays, the task is to merge them in a sorted manner.
    There are two sorted arrays and after merging there will be only one array in sorted manner.
*/
import java.util.*;
public class MergeSortedArrays {
   public static void main(String[] args) {
      int A[] = {-2,3,5,8,9};
      int B[] = {1,2,3,4,5};
      System.out.println(Arrays.toString(solve(A,B)));   
   }
   /*
       function to merge the given sorted arrays. 
   */
    public static int[] solve(final int[] A, final int[] B) {
       /* 
          Declaring a new Array of the expected result size i,e sum of length of Array A and Array B 
       */ 
       int ARR[] = new int[A.length+B.length]; 
       /*
          Declaring two pointers p1 and p2
          p1 points to first element of Array A
          p2 points to first element of Array B
       */ 
       int pointer1=0,pointer2=0;
        int k=0;
        while(pointer1<A.length && pointer2<B.length) {
            if(A[pointer1]<B[pointer2]) {
                ARR[k++] = A[pointer1++];
            }
            else {
                 ARR[k++] = B[pointer2++];
            }
        }
        while(pointer1<A.length) {
            ARR[k++]=A[pointer1++];
        }
        while(pointer2<B.length) {
            ARR[k++]=B[pointer2++];
        }
        return ARR;
    }
}
/*
  Example: 
  Input: 
      A[] = {-2,3,5,8,9}
      B[] = {1,2,3,4,5}
  Output:
     [-2,1,2,3,3,4,5,5,8,9]
     
   Explanation: 
      After Merging A and B produces the output as described above.
*/
/*
  Time and Space Complexity
  M = length of Array A
  N = length of Array B
  Time Complexity O(M+N)
  Space Complexity O(M+N)
*/


<|start_filename|>C-Plus-Plus/other/First_Missing_Positive_Number.cpp<|end_filename|>
/*
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, 
find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.

For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.

You can modify the input array in-place.

*/

#include<bits/stdc++.h>

using namespace std;

// finding the first missing positive number
int firstMissingNumber(int arr[], int n)
{
    int index, temp;
    // traversing the array
    for (index = 0; index < n; index++)
    {
        // We will ignore the negative numbers and the numbers greater than the array size
        // Also, check if the elements are in correct position, if they is not then do swap
        // operation
        while (arr[index] != arr[arr[index] - 1] && arr[index] >= 1 && arr[index] <= n)
        {
            // Swap operation
            temp = arr[arr[index] - 1];
            arr[arr[index] - 1] = arr[index];
            arr[index] = temp;
        }
    }
    // traversing the array one more time
    for (index = 0; index < n; index++)
    {
        // checking if all the elements are in the correct position
        // The one which is not in the correct position is the first 
        // missing positive number
        if ((index + 1) != arr[index])
            return index + 1;
    }
    return n + 1;
}

// DRIVER FUNCTION
int main()
{
    // size of the array
    int n;
    cout<<"Enter the size of the array: \n";
    // getting the size of the array
    cin >> n;
    int arr[n], index, res;
    cout<<"Enter the elements of the array: \n";
    // getting the array elements
    for (index = 0; index < n; index++)
        cin >> arr[index];
    printf("\n");
    // finding the first positive missing number
    res = firstMissingNumber(arr, n);
    cout <<"The First Missing Positive Number in the given array is: "<<res;
    return 0;
}
/*
For ex:
Example1:
Input:
4
3 4 7 1

Output:
2

Example 2:
Input:
4
3 4 -1 1

Output:
2
*/

<|start_filename|>Java/sort/Merge_sort.java<|end_filename|>
public class Merge_sort {
//merge sort function to recursively break the array to one-one element
    static void merge_sort(int[] a,int l,int h){
        int mid;
        if(l<h){
            mid=(l+h)/2;
            merge_sort(a,l,mid);
            merge_sort(a,mid+1,h);
            merge(a,l,mid,h);
        }
    }
//merge function to compare and merge to elements 
    static void merge(int[] a,int l,int mid,int h){
        int i=l,j=mid+1,k=l;
        int[] b=new int[100];
        while(i<=mid && j<=h){
            if(a[i]<a[j])
                b[k++]=a[i++];
            else
                b[k++]=a[j++];
        }
        for(;i<=mid;i++)
            b[k++]=a[i];
        for(;j<=h;j++)
            b[k++]=a[j];
        for(i=l;i<=h;i++)
            a[i]=b[i];
    }
    public static void main(String[] args){
        int[] a={11, 13,7,12,16,9,24,5,10,3};
        merge_sort(a,0,9);
        for(int i=0;i<10;i++)
            System.out.print(a[i]+" ");
    }
}
/*output:
3 5 7 9 10 11 12 13 16 24 
*/
//for more better understanding of how this algorithm is working read the readme file for merge sort.


<|start_filename|>C/math/mystery_number.c<|end_filename|>
// C program to Check if a number is a Mystery Number or Not.
/*
A mystery number is that number which can be expressed as a sum of two 
numbers and those two numbers must be the reverse of each other
*/
#include <stdio.h>
#include <stdbool.h>

// Helper function to reverse a number.
int reverse(int n)
{
    int rev = 0;
    for (; n > 0; n /= 10)
    {
        rev = rev * 10;
        rev = rev + (n % 10);
    }
    return rev;
}

bool check_mystery_num(int n)
{
    /* Let us iterate from 1 upto n/2, to check if there is any pair, such that thier
       sum equals the given number and check if the pair are reverse of each other  */
    for (int i = 1; i <= n / 2; i++)
    {
        if (reverse(i) == n - i)
        {
            return true;
        }
    }
    return false;
}

int main()
{
    int n;
    printf("Enter the number: ");
    scanf("%d", &n);
    bool res = check_mystery_num(n);
    if (res)
    {
        printf("The given number %d is a Mystery Number.", n);
    }
    else
    {
        printf("The given number %d is not a Mystery Number.", n);
    }
    return 0;
}

/*
Time Complexity: O(n*log(n)), where 'n' is the given number
Space Complexity: O(1)

SAMPLE INPUT AND OUTPUT

SAMPLE 1
Enter the number: 43234
The given number 43234 is a Mystery Number.

SAMPLE 2
Enter the number: 1234
The given number 1234 is not a Mystery Number.

*/


<|start_filename|>C-Plus-Plus/cp/find_no_of_digits_in_int.cpp<|end_filename|>
#include <bits/stdc++.h>
using namespace std;

int num_of_digits(int num){
    int count = 0;                                       //count is a variable for number of digits
    
    while(num > 0){                                      //Ex : num = 324, count = 0 (Initially)
        count++;                                         //     num = 324, count = 1 (1st iteration)
        num /= 10;                                       //     num = 32, count = 2 (2nd iteration)
    }                                                    //     num = 3, count = 3 (3rd iteration)
                                                         //     num = 0, out of the loop
    return count;
}

int num_of_digits_recursive(int num){
    if(num == 0){                                        //Base case
        return 0;
    }
    
    return 1 + num_of_digits_recursive(num / 10);        
}

int num_of_digits_stringsoln(int num){
    string number = to_string(num);
    return number.size();                                //returning string length
}

int num_of_digits_logbased(int num){
    return floor(log10(num) + 1);                        //Number of digits in integer = upper bound of log10(N)
}

int main() {
    int num;
    cin >> num;                                           //Inputting the number
    cout << "The number of digits in given integer (using normal approach): " << num_of_digits(num) << endl;
    cout << "The number of digits in given integer (using recursive approach): " << num_of_digits_recursive(num) << endl;
    cout << "The number of digits in given integer (using string): " << num_of_digits_stringsoln(num) << endl;
    cout << "The number of digits in given integer (log based approach): " << num_of_digits_logbased(num) << endl;
    return 0;
}


<|start_filename|>Java/Greedy_Algorithms/Job_Scheduling.java<|end_filename|>
/* Problem Description
Given a set of N jobs where each job i has a deadline and profit associated to it. 
Each job takes 1 unit of time to complete and only one job can be scheduled at a time.
We earn the profit if and only if the job is completed by its deadline.
The task is to find the maximum profit and the number of jobs done.
*/

import java.io.*;
import java.lang.*;
import java.util.*;

public class Job_Scheduling_Greedy {
    // this Job class will store the id, profit, deadline property 
	static class Job {
	    int id, profit, deadline;
	    Job(int id, int deadline, int profit){
            this.id = id;
            this.profit = profit;
            this.deadline = deadline;
        }
	};
	
	// solve() will do the task of getting the profit
	static int[] solve (Job[] arr , int n )
	{
		// Sort the array in descending order according to profit
		Arrays.sort(arr , (a,b) -> b.profit - a.profit );
		int res[]  = new int[2] ;
		int totalProfit = 0;
		int count = 0 ;        
		Boolean[] slots = new Boolean[n];
		Arrays.fill(slots, false);
	       /* iterate through the jobs with minDeadLine to remaining jobs and
		 check if there is any slote available and also claculate the profit
	       */
		for (int i = 0; i < n; i++) {
		    int minDeadLine = Math.min( arr[i].deadline - 1 , n- 1) ;
		    for (int j = minDeadLine ; j >= 0; j--) 
		    {
			if (slots[j] == false) {
			    count ++ ;
			    slots[j] = true;
			    totalProfit += arr[i].profit ;
			    break;
			}
		    }
		}
		// store the count and profit in res array and return the result
		res[0] = count ;
		res[1] = totalProfit ;
		return res ;
	}
	
 	public static void main(String[] args) throws IOException{
	    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	    System.out.println("Enter number of testcase");
	    int test = Integer.parseInt(br.readLine().trim());
	    while(test-->0){
            // input the no. of jobs
            System.out.println("Enter number of jobs");
            String input[] = br.readLine().trim().split(" ");
            int n = Integer.parseInt(input[0]);
            // Make a reference to Job and set size number of jobs 
            Job[] arr = new Job[n];
            System.out.println("Enter values of jobs");
            input = br.readLine().trim().split(" ");
            for(int i=0, k=0; i<n; i++){
                arr[i] = new Job(Integer.parseInt(input[k++]), Integer.parseInt(input[k++]), Integer.parseInt(input[k++]));
            }
            // call the method to get the result
            int[] result = solve(arr, n);
            // Print the required result
            System.out.println ("Maximum Profit : " + result[0] + " " + result[1]);            
        }
    }
}

/* Input
Enter number of testcase
1
Enter number of jobs
4
Enter values of jobs
1 4 20 2 1 10 3 1 40 4 1 30

Output :
Maximum Profit : 2 60

Explanation
Sort all the jobs according to descending in terms of profit and loop the jobs and check if slot is available or not
and according insert value to res array and output the result.

Time Complexity : O(NLogN)
Space Complexity : O(N)
*/




<|start_filename|>C-Plus-Plus/graphs/minimum_distance_using_SSSP_on_trees_by_DFS.cpp<|end_filename|>
/*
Given total number of nodes in an undirected graph
numbered from 1 to n [ number of nodes] and total number of edges in the graph.
Find  minimum distance of each node using SSSP (Single Source Shortest Path) on trees
by DFS.
*/

#include <bits/stdc++.h>
using namespace std;
vector < int > adj[10009];
int visited[10009];
int distance_array[10009];

// this function will print the minimum distance
void print_minimum_distance_of_each_nodes(int nodes)
{
    for(int i = 1; i <= nodes; i++)
    {
        cout << distance_array[i] << ' ';
    }
    cout << endl;
}

// this dfs function will visit the nodes
void dfs(int node, int dist)
{
    /* for each node we will put  visited[node] = 1
    means that node is visited
    and put distance_array[node] = dist means current distance.
    and then recursively will visit the
    adjacency vector
     */
    visited[node] = 1;
    distance_array[node] = dist;
    for(auto child : adj[node])
    {
        if(visited[child] == 0)
        {
            // will update the distance each step
             dfs(child , distance_array[node] + 1);
        }
    }

}

int main()
{
    cout << "Enter the nodes and edges of the graph :\n";
    int nodes, edges;
    cin >> nodes >> edges;
    cout << "Enter the start and end points that have edges \n";
    for(int i = 1; i <= edges; i++)
    {
        int point1, point2;
        cin >> point1 >> point2;
        adj[point1].push_back(point2);
        adj[point2].push_back(point1);

    }
    /* here dfs call(1, 0)
    from 1th node distance is 0
    */
    dfs(1, 0);

    cout << "Minimum Distance of Each Nodes: \n";
    print_minimum_distance_of_each_nodes(nodes);
}

/*
Standard Input and Output

Enter the nodes and edges of the graph :
6 5
Enter the start and end points that have edges
1 2
1 3
1 4
2 5
2 6

Minimum Distance of Each Nodes:
0 1 1 1 2 2

Time Complexity : O( E + N) // Edges and Nodes
Space Complexity : O( N )

*/


<|start_filename|>C-Plus-Plus/math/matrix_multiplication.cpp<|end_filename|>
// C++ program to implement Matrix Multiplication
#include <bits/stdc++.h>
using namespace std;

int main()
{
    int r1, c1, r2, c2;
    cout << "Enter the number of rows and columns of the first matrix:  ";
    cin >> r1 >> c1;
    cout << "Enter the number of rows and columns of the second matrix: ";
    cin >> r2 >> c2;

    //If the number of columns of the second matrix and the number of rows of first matrix differ, they cannot be added
    if (c1 != r2)
    {
        cout << "Given Matrices cannot be multiplyable!!!";
        return 0;
    }
    int A[r1][c1], B[r2][c2], C[r1][c2] = {0};

    // Input the values of the matrices
    cout << "Enter the values of the first matrix\n";
    for (int i = 0; i < r1; i++)
    {
        for (int j = 0; j < c1; j++)
            cin >> A[i][j];
    }
    cout << "Enter the values of the second matrix\n";
    for (int i = 0; i < r2; i++)
    {
        for (int j = 0; j < c2; j++)
            cin >> B[i][j];
    }

    // Multiply both the matrices
    for (int i = 0; i < r1; i++)
    {
        for (int j = 0; j < c2; j++)
        {
            C[i][j] = 0;
            for (int k = 0; k < c1; k++)
                C[i][j] += A[i][k] * B[k][j];
        }
    }

    cout << "The resultant matrix is:\n";
    for (int i = 0; i < r2; i++)
    {
        for (int j = 0; j < c2; j++)
            cout << C[i][j] << " ";
        cout << endl;
    }
    return 0;
}

/*
Time Complexity: O(r1 * c2 * c1), where 'r1' is the number of rows of first matrix and 'c2' is the number of columns 
                 of second matrix and 'c1' is the number of columns of first matrix   
Space Complexity: O(r1 * c2)

SAMPLE INPUT AND OUTPUT

Enter the number of rows and columns of the first matrix:  2 2
Enter the number of rows and columns of the second matrix: 2 2
Enter the values of the first matrix
1 1
1 1
Enter the values of the second matrix
1 1
1 1
The resultant matrix is:
2 2
2 2

*/


<|start_filename|>C-Plus-Plus/other/Unique_Number_III.cpp<|end_filename|>
/*Unique_Number_III
Given an array that contains all elements occurring 3 times, but one occurs only once. Find that unique element.*/
#include <iostream>
using namespace std;
int main()
{
	int cnt[64] = {0};
	int n, no;
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		cin >> no;

		int j = 0;
		while (no > 0)
		{
			int last_bit = (no & 1);
			cnt[j] += last_bit;
			j++;
			no = no >> 1;
		}
	}
	int p = 1;
	int ans = 0;
	for (int i = 0; i < 64; i++)
	{
		cnt[i] %= 3;
		ans += (cnt[i] * p);
		p = p << 1;
	}
	cout << ans << endl;
	return 0;
}
/*
Input : arr[] = {6, 2, 5, 2, 2, 6, 6}
Output : 5	
Time Complexity:O(n)
*/


<|start_filename|>C-Plus-Plus/math/armstrong_number.cpp<|end_filename|>
/*
In recreational number theory, a narcissistic number is also known
as a pluperfect digital invariant (PPDI), an Armstrong number or a
plus perfect number is a number that is the sum of its digits
each raised to the power of the number of digits.
*/

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

// Function to check whether the Number is Armstrong Number or Not.

bool is_armstrong(int n)
{
	if (n < 0)
	{
		return false;
	}
	int sum = 0;
	int var = n;
	int number_of_digits = floor(log10(n) + 1);
	while (var > 0)
	{
		int rem = var % 10;
		sum = sum + pow(rem, number_of_digits);
		var = var / 10;
	}
	return n == sum;
}

int main()
{
	cout << "Enter the Number to check whether it is Armstrong Number or Not:" << endl;
	int n;
	cin >> n;
	if (is_armstrong(n))
		cout << n << " is Armstrong Number." << endl;
	else
		cout << n << " is Not Armstrong Number." << endl;
	return 0;
}

/*
Input:
Enter the Number to check whether it is Armstrong Number or Not:
153
Output:
153 is Armstrong Number.
Input:
Enter the Number to check whether it is Armstrong Number or Not:
12
Output:
12 is Not Armstrong Number.

Time Complexity: O(log(n))
Space Complexity: O(1)
*/


<|start_filename|>C-Plus-Plus/cp/longestCommonPrefix.cpp<|end_filename|>
/*Problem: Given array of strings, find the longest common prefix present in all the strings.
Print the longest common prefix. If no common prefix is present, then print empty string ("").

Approach: Comparing characters of the same column in all the strings. If the character does not much
or the string ends at that column, algorithm will retun lcp till that point.

Time complexity:O(S) where S is the number of all the characters in all strings.
Space complexity: O(1)
*/

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

string solve(int n, string *strs)
{
    string lcp = "";
    char cur_car;
    int j = 0;
    if (n == 0)
    {
        return "";
    }
    while (1)
    {
        if (strs[0] == "")
        {
            return "";
        }
        if (strs[0][j] == '\0')
        {
            return lcp;
        }
        else
        {
            cur_car = strs[0][j];
        }
        for (int i = 1; i < n; i++)
        {
            if (strs[i] == "")
            {
                return "";
            }
            if (strs[i][j] == '\0' || strs[i][j] != cur_car)
            {
                return lcp;
            }
        }
        lcp += cur_car;
        j++;
    }
    return lcp;
}

int main()
{
    //input
    //number of strings in array
    cout << "Enter number of strings:" << endl;
    int n;
    cin >> n;
    string *strs = new string[n];
    //enter strings
    cout << "Enter the strings:" << endl;
    for (int i = 0; i < n; i++)
    {
        cin >> strs[i];
    }

    string lcp = solve(n, strs);
    if (lcp == "")
    {
        cout << "No common prefix";
    }
    else
    {
        cout << "Longest Common Prefix is: " << lcp;
    }
}

/*
Sample input:
"apple", "appology", "apps"

Sample output:
"app"
*/

<|start_filename|>C/sort/BST_Sort.c<|end_filename|>
/* SORTING USING BINARY SEARCH TREE
    Binary Search Tree is a special type of binary tree where 
    1. The value of all the nodes in the left sub-tree is less than or equal to the value of the root.
    2. The value of all the nodes in the right sub-tree is greater than value of the root.
    3. This rule will be recursively applied to all the left and right sub-trees of the root.

    Inorder traversal 
    1. Traverse the left subtree
    2. Visit the root.
    3. Traverse the right subtree

    Inorder traversal in BST gives sorted list
*/

#include <stdio.h>
#include <stdlib.h>

// Declare treeNode with data , rc (right child) and lc (left child )
typedef struct treeNode
{
    int data;
    struct treeNode *lc;
    struct treeNode *rc;
} treeNode;

int count = 0;

//to insert a node into BST
treeNode *insertIntoTree(treeNode *root, int data)
{
    //If tree is empty insert as root node
    if (root == NULL)
    {
        treeNode *ptr;
        ptr = malloc(sizeof(treeNode));
        ptr->data = data;
        ptr->lc = NULL;
        ptr->rc = NULL;
        root = ptr;
    }
    else
    {
        // insert recursively in accordance with BST properties
        if (root->data >= data)
        {
            root->lc = insertIntoTree(root->lc, data);
        }
        else if (root->data < data)
        {
            root->rc = insertIntoTree(root->rc, data);
        }
    }
    return root;
}

//to sort-inorder traversal gives sorted list
void inorder(treeNode *root)
{
    //If tree is empty
    if (root)
    {
        // recursively visit left sub-tree,root and right sub-tree
        inorder(root->lc);
        printf("%d ", root->data);
        inorder(root->rc);
    }
}

// driver code
void main()
{
    //Initialize tree as empty
    treeNode *root;
    root = NULL;
    int n, data;
    //Accept the no. of elements and elements as user input
    scanf("%d", &n);

    for (int i = 0; i < n; i++)
    {
        scanf("%d", &data);
        root = insertIntoTree(root, data);
    }

    printf("\nSorted list : ");
    inorder(root);
    printf("\n");
}

/*
    Sample input:
    7
    1 2 5 3 7 4 6

    Sample output:
    1 2 3 4 5 6 7
*/

/*
    Time complexity : O(n)
    Space complexity : O(n)
*/


<|start_filename|>Java/ds/Reverse_alternate_k_Nodes.java<|end_filename|>
﻿/*Given the head pointer to a linked list of length n and an integer k, we have to reverse every alternate k nodes in the linked list.

Approach:
1.Reverse the first k nodes
2.Link the next of head of the modified list to the (k+1)th node 
3.Traverse the next k nodes to skip their reversal
4.Since 2k nodes are already processed,recursively call the function for the rest n-2k nodes
5.Return the new head of the list

*/

import java.util.*;
public class Reverse_alternate_k_Nodes {

    //creating the head of the list
    static Node head;

    //class which defines the structure of each node in the list
    class Node {
        int data;
        Node next;

        // Constructor to initialize the data and next pointer
        Node(int data) {
            this.data = data;
            this.next = null;
        }
    }

    //Function to create the linked list with the elements given as input
    public void createList(int newData) {

        Node new_Node = new Node(newData);
        Node temp = head;
        if (head == null) {
            head = new_Node;
        } else {
            while (temp.next != null) {
                temp = temp.next;
            }
            temp.next = new_Node;
        }
    }

    //Function to display the linked list
    public void displayList(Node A) {

        Node temp = A;

        while (temp != null) {
            System.out.print(temp.data + " ");
            temp = temp.next;
        }
    }

    //Function which returns the head node of the result list
    public Node reverseAlternately(Node A, int k) {
        if (A == null || A.next == null)
            return A;
        Node head = null;
        Node current = A;
        Node forward = null;
        Node backward = null;

        //Reversing first k nodes of the current list
        for (int i = 0; i < k; i++) {
            forward = current.next;
            current.next = backward;
            backward = current;
            current = forward;
        }
        //Setting the head pointer to the result list after reversing k nodes
        head = backward;

        if (A != null)
            A.next = current;

        if (current == null)
            return head;

        //Next k nodes should not be reversed hence we skip them
        for (int i = 0; i < k - 1; i++) {
            current = current.next;
        }
        //Recursive call by making the rest of the list as next of current node
        current.next = reverseAlternately(current.next, k);
        return head;
    }

    public static void main(String[] args) {
        Reverse_alternate_k_Nodes list = new Reverse_alternate_k_Nodes();
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number of elements you want to insert in the list: ");
        int n = sc.nextInt();
        System.out.println("Enter the elements of the list: ");
        for (int i = 0; i < n; i++) {
            list.createList(sc.nextInt());
        }
        System.out.println("Enter the number of elements to be reversed alternately");
        int k = sc.nextInt();

        System.out.println("The original list is");
        list.displayList(head);

        head = list.reverseAlternately(head, k);
        System.out.println();

        System.out.println("The list after reversal is");
        list.displayList(head);
        sc.close();
    }
}
/*
Sample Input:
Enter the number of elements you want to insert in the list: 
6
Enter the elements of the list: 
1
4
6
6
4
10
Enter the number of elements to be reversed alternately
2

Sample Output:
The original list is
1 4 6 6 4 10 
The list after reversal is
4 1 6 6 10 4 

Time Complexity : O(n)
Space Complexity : O(n),since there is a recursive function
*/


<|start_filename|>C/cp/Knutt_Morris_Prat.c<|end_filename|>
/*Knuth–Morris–Pratt string-searching algorithm 
Searches for occurrences of a word W within a main text string S 
*/
#include <stdio.h>
#include <string.h>

int Knutt_Morris_Prat(char[], char[]);
int main()
{
	char string[20], matchcase[20];
	printf("Enter string: ");
	gets(string);
	printf("Enter substring: ");
	gets(matchcase);
	Knutt_Morris_Prat(string, matchcase);
	return 0;
}

int Knutt_Morris_Prat(char string[], char matchcase[])
{
	int i, j = 0, index;
	for (i = 0; i < strlen(string) - strlen(matchcase) + 1; i++)
	{
		index = i;
		if (string[i] == matchcase[j]) /*Check if characters match*/
		{
			/*Continue checking until the characters match or the end of pattern string is reached*/
			do {
				i++;
				j++;
			} while (j != strlen(matchcase) && string[i] == matchcase[j]);
			if (j == strlen(matchcase)) /*if j is equal to pattern length, pattern is found.*/
			{
				printf("Match found from position %d to %d.\n", index + 1, i);
				return 0;
			}
			else /*if j is not equal to pattern length, move to next character and continue the same steps.*/
			{
				i = index + 1;
				j = 0;
			}
		}
	}

	printf("No substring match found in the string.\n");
	return 0;
}

/*
Time Complexity: O(n + m)  - n is the length of string and m is the length of substring
Space Complexity: O(m) - m is the length of substring

Sample Output
Enter string: ABCABAABCABAC
Enter subsring: CAB 
Match found from position 3 to 5.
*/



<|start_filename|>C-Plus-Plus/cp/Rotten_Oranges.cpp<|end_filename|>
/*
Each cell is represented by either

0: Empty cell
1: Cells have fresh oranges
2: Cells have rotten oranges

Only a fresh orange adjacent to a rotten one will get rotten after 1 second.
*/

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

// A struct data type for storing each and every cell index pairs
struct cell
{
	int x, y;
};

// Checks if the index in consideration is valid or not
bool isValid(int x, int y, int R, int C)
{
	return (x >= 0 && x < R && y >= 0 && y < C);
}

// Checks if there are still some fresh oranges left
bool checkall(vector <int> arr[], int R)
{
	int C = arr[0].size();
	for (int i = 0; i < R; i++)
		for (int j = 0; j < C; j++)
			if (arr[i][j] == 1)
				return true;
	return false;
}

// A checker to take care of all corner case. In case the matrix is all zero then this checker takes care of such cases
bool checkzero(vector <int> arr[], int R)
{
	int C = arr[0].size();
    for (int i = 0; i < R; i++)
        for (int j = 0; j < C; j++)
            if (arr[i][j] != 0)
                return false;
    return true;
}

int rotOranges(vector <int> arr[], int R)
{
	queue <cell> q;
	cell curr;
	int time = -1, lsize, x, y, i, j;
	int xindex[] = {1, -1, 0, 0};
	int yindex[] = {0, 0, 1, -1};
	int C = arr[0].size();
	
	for (i=0; i < R; i++)
		for (j=0; j < C; j++)
			if (arr[i][j] == 2)
				q.push({i, j});

	while (!q.empty())
	{
		time++;
		lsize = q.size();
		
		while (lsize--)
		{
			curr = q.front();
			q.pop();
			
			for (int i=0; i < 4; i++)
			{
				x = curr.x + xindex[i];
				y = curr.y + yindex[i];
				
				if (!isValid(x, y, R, C))
					continue;
				
				if (arr[x][y] == 1)
				{
					arr[x][y] = 2;
					q.push({x, y});
				}
			}
		}
	}
	
	if (checkzero(arr, R))
		return 0;
	
	if (checkall(arr, R))
		return -1;
	return time;
}

int main()
{
	int R, C, num;
	
	cout << "Enter number of rows and columns: ";
	cin >> R >> C;
	
	vector <int> arr[R];
	
	for (int i = 0; i < R; i++)
	{
		for (int j = 0; j < C; j++)
		{
			cout << "\nEnter number : ";
			cin >> num;
			arr[i].push_back(num);
		}
	}
	
	int ans = rotOranges(arr, 3);
	if (ans != -1)
		cout << "\nThe time taken is " << ans << " seconds.";
    else
		cout << "\nAll the oranges cannot be rotten !!";
	
    return 0;
}

/*
Row = 3
Column = 5

Time t = 0

	2, 1, 0, 2, 1
	1, 0, 1, 2, 1
	1, 0, 0, 2, 1

Time t = 1

	2, 2, 0, 2, 2
	2, 0, 2, 2, 2
	1, 0, 0, 2, 2

Time t = 2

	2, 2, 0, 2, 2
	2, 0, 2, 2, 2
	2, 0, 0, 2, 2

All oranges are rotten. Time taken is 2 seconds.
*/


<|start_filename|>Kotlin/search/BinarySearch.kt<|end_filename|>
// Kotlin program to implement Binary Search using Iterative Approach

import java.util.Scanner

fun main(args: Array<String>) {

    val input = Scanner(System.`in`)

    var arrayLength = input.nextInt()
    var arrayOfElements = arrayListOf<Int>()

    for(index in 0 until arrayLength) {
        var element = input.nextInt()
        arrayOfElements.add(element)
    }

    var key = input.nextInt()
    var index = binarySearch(arrayOfElements , key)

    if(index == -1)
        println("Key: $key is not present in the array")
    else
        println("Key: $key is present in the array at index $index")

}

// Function to return the index of the key if it is present in the array, else returns an invalid index -1
fun binarySearch(arrayOfElements: ArrayList<Int>, key: Int): Int {

    // Lower and Upper bound of the array
    var low = 0
    var high = arrayOfElements.size - 1

    while(low <= high) {

        // To find the middle position for the given bounds of the array
        var mid = low + (high - low) / 2;

        // If the key is found, return the index
        if(arrayOfElements[mid] == key)
            return mid

        // If the key is smaller, then it is just required to search the left sub-array
        else if(arrayOfElements[mid] > key)
            high = mid - 1

        // If the key is larger, then is it just required to search the right sub-array
        else
            low = mid + 1
    }

    // Return an invalid index if key is not present
    return -1
}

// Time Complexity: O(logn)
// Auxiliary Space Complexity: O(1)

/* Sample Test Cases:
Test - 1:
    Input
        7
        12 34 47 100 231 387 789
        387

    Output
        Key: 387 is present in the array at index 5

Test - 2:
    Input
        5
        10 12 45 67 89
        1000

    Output
        Key: 1000 is not present in the array
 */


<|start_filename|>C/sort/countingSort.c<|end_filename|>
//***************************** CODE ************************************
#include <stdio.h>   
int countingSort(int A[], int k, int n){
 int i, j;
 int B[15], C[100];
 for (i = 0; i <= k; i++){
   C[i] = 0;
 }
 for (j = 1; j <= n; j++){
   C[A[j]] = C[A[j]] + 1;
 }
 for (i = 1; i <= k; i++){
   C[i] = C[i] + C[i-1];
 }
 for (j = n; j >= 1; j--){
   B[C[A[j]]] = A[j];
   C[A[j]] = C[A[j]] - 1;
 }
 printf("The Sorted array is : ");
 for (i = 1; i <= n; i++){
   printf("%d ", B[i]);
 }
 return 0;
}
int main(){
 int n, k = 0, A[15], i;
 printf("Enter the number of input : ");
 scanf("%d", &n);
 printf("\nEnter the elements to be sorted :\n");
 for (i = 1; i <= n; i++){
   scanf("%d", &A[i]);
   if (A[i] > k) {
      k = A[i]; }   
 }
 countingSort(A, k, n);
 printf("\n");
 return 0;
}

//*************************** SAMPLE OUTPUT ******************************
/*
Enter the number of input : 12
Enter the elements to be sorted : 76 54 32 90 87 55 32 65 77 88 42 10
The Sorted array is : 10 32 32 42 54 55 65 76 77 87 88 90 
*/

//************************* COMPLEXITIES **********************************
/*
Counting sort is an algorithm for sorting a collection of objects according to keys that are small integers i.e; it is an integer sorting algorithm. It operates by counting the number of objects that have each distinct key value, and using arithmetic on those counts to determine the positions of each key value in the output sequence. 
Worst complexity: O(n+k)
Average complexity: O(n+k)
Space complexity: O(n+k)
where n is the number of elements in input array and k is the range of input.
*/

//*********************************************************************
//This code is by japneetbhatia for submission in DWOC


<|start_filename|>Java/Operating-System/CPU_Scheduling_RR.java<|end_filename|>
/*
-In Round-robin scheduling, each ready task runs turn by turn only in a cyclic queue 
for a limited time slice. 
-This algorithm also offers starvation free execution of processes.
-It is preemptive as processes are assigned CPU only for a fixed slice of time at most.
*/

import java.util.*;

class Procces {
    float ArrivalTime, BurstTime, FinishTime, WaitingTime, TurnAroundTime, BT;
    int flag, id;

    public Procces(float BurstTime, int id) {
        this.ArrivalTime = 0;
        this.BurstTime = BurstTime;
        WaitingTime = 0;
        BT = BurstTime;
        this.id = id;
        flag = 0;
    }
}

class ManagingQueue {
    Procces P[] = new Procces[20];
    int SizeOfCircularQueue, TotalProcessesFinished;
    int front, rear;
    float Timer, AWT, ATT;

    ManagingQueue(int SizeOfCircularQueue) {
        front = -1;
        rear = -1;
        this.SizeOfCircularQueue = SizeOfCircularQueue;
        Timer = 0;
        TotalProcessesFinished = 0;
    }

    int IsQueueEmpty() { // Checking whether queue is empty
        if ((front == 0 && rear == -1) || (front == (rear + 1))) {
            return 1;
        } else {
            return 0;
        }
    }

    int IsQueueFull() { // checking queue is full or not
        if ((front == 0 && rear == (SizeOfCircularQueue - 1)) || front == (rear + 1) % SizeOfCircularQueue) {
            return 1;
        } else {
            return 0;
        }
    }

    void ManageProcessQueue() {
        float BurstTime;
        int id, i, QuantumTime;
        Scanner sc = new Scanner(System.in);
        Procces CircularQueue[] = new Procces[SizeOfCircularQueue];
        System.out.println("Enter Quantum time :");
        QuantumTime = sc.nextInt();
        for (i = 0; i < SizeOfCircularQueue; i++) {
            System.out.println("Enter Process ID :");
            id = sc.nextInt();
            System.out.println("Enter Burst time :");
            BurstTime = sc.nextFloat();
            P[i] = new Procces(BurstTime, id);
            if (IsQueueFull() != 1) {
                rear = (rear + 1) % SizeOfCircularQueue;
                CircularQueue[rear] = P[i]; // Enqueuing process

            }
        }
        while (TotalProcessesFinished != SizeOfCircularQueue) {
            for (i = 0; i < SizeOfCircularQueue; i++) {
                if (IsQueueEmpty() != 1) {
                    if (front == -1) {
                        front = 0;
                    }
                    if (P[i].flag != 1) {
                        if (P[i].BurstTime <= QuantumTime) {
                            TotalProcessesFinished++;
                            Timer = Timer + P[i].BurstTime;
                            P[i].BurstTime = 0;
                            P[i].FinishTime = Timer;
                            P[i].flag = 1;

                        } else {
                            P[i].BurstTime = P[i].BurstTime - QuantumTime;
                            Timer = Timer + QuantumTime;
                            if (IsQueueFull() != 1) {
                                rear = (rear + 1) % SizeOfCircularQueue;
                                CircularQueue[rear] = P[i];

                            }
                            front = (front + 1) % SizeOfCircularQueue; // Dequeue process
                        }

                    }
                }
            }
        }
        for (i = 0; i < SizeOfCircularQueue; i++) {
            P[i].TurnAroundTime = P[i].FinishTime;
            P[i].WaitingTime = P[i].TurnAroundTime - P[i].BT;
            AWT += P[i].WaitingTime;
            ATT += P[i].TurnAroundTime;
        }
        System.out.println("ProcessID    BurstTime FinishTime TurnAroundTime WaitingTime");
        for (i = 0; i < SizeOfCircularQueue; i++) {
            System.out.println(P[i].id + "\t\t" + P[i].BT + "\t" + P[i].FinishTime + "\t\t" + P[i].TurnAroundTime
                    + "\t\t" + P[i].WaitingTime);
        }
        System.out.println("Average turn around time is : " + (ATT / SizeOfCircularQueue) + "ms");
        System.out.println("Average waiting time is : " + (AWT / SizeOfCircularQueue) + "ms");
    }

}

public class CPU_Scheduling_RR {

    public static void main(String[] args) {
        int SizeOfCircularQueue;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter size :");
        SizeOfCircularQueue = sc.nextInt();
        ManagingQueue M = new ManagingQueue(SizeOfCircularQueue);
        M.ManageProcessQueue();

    }

}

/*
 * Enter size :4 
 * Enter Quantum time : 2 
 * Enter Process ID : 1 
 * Enter Burst time : 4 
 * Enter Process ID : 2 
 * Enter Burst time : 3 
 * Enter Process ID : 3 
 * Enter Burst time : 8 
 * Enter Process ID : 4 
 * Enter Burst time : 1 
 * 
 * ProcessID BurstTime FinishTime TurnAroundTime WaitingTime 
 * 1         4.0       9.0        9.0            5.0 
 * 2         3.0       10.0       10.0           7.0 
 * 3         8.0       16.0       16.0           8.0 
 * 4         1.0       7.0        7.0            6.0 
 * 
 * Average turn around time is : 10.5ms
 * Average waiting time is : 6.5ms
 * 
 */


<|start_filename|>C-Plus-Plus/cp/prime_factors.cpp<|end_filename|>
/* This algorithm will represent a number n(>1) as product of prime numbers.
 For example, if the input is 12 then output will be 2 2 3 , if input is 28 then output will be (2,2,7).
 Two concepts are used here. Firstly , through sieve of erathosthenes we will find all the prime numbers till n.
 Then we will check which prime numbers can divide n and for how many times*/

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

void prime_factors(int n)
{
    //Applying sieve of erathosthenes to store the prime numbers till n
    int arr[n+1]={0};
    arr[1]=1;
    for(int i=2;i<=sqrt(n);i++)
    {
        if(arr[i]==0)
        {
            for(int j=i*i;j<=n;j+=i)
            {
                arr[j]=1;
            }
        }
    }
    for(int i=1;i<=n;i++)
    {
        if(arr[i]==0)    //checking if i is prime
        {
         while(n%i==0)   //while i divides n, print i and keep on dividing n by i
         {
            cout<<i<<" ";
            n=n/i;
         }
        }
    }  
     return;
}
//Driver Code
int main()
{
    int num;
    cin>>num;
    prime_factors(num);
     return 0;
}
/* sample input: 12
   sample output: 2 2 3

   sample input: 24
   sample output: 2 2 2 3

   Time Complexity: O(n*log(log(n)) + log(n) + n)
   for sieve of erathrosthenes => O(n*log(log(n)))
   for printing the prime factors => O(n+ log(n))
   Space Complexity: O(n) */


<|start_filename|>C-Plus-Plus/other/n_string_concatenate.cpp<|end_filename|>
/*
String Concatenation 
Problem Statement : Take n string from user and concatenate them together.
Input Format : First line takes number of strings to be concatenated.
               Next n lines contains the strings to be concatenated.
Output Format : Print a single line that contains the concatenated string.
Note : No space is there in between a single string.

Approach : Take n strings as input using loop.
           Take a string variable and update it using append() function each time a new sting is entered.
           Print the string.
*/

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

//within concat_str(...) final string is calculated sing append()
void concat_str(vector<string> str,int size)
{
    string f_str="";
    for(int i=0;i<size;i++)
    {   
        f_str.append(str[i]);
    }
    cout<<f_str;
}

int main() 
{
    vector<string> s;
    //n stores the no. of string
    int n; 
    cin>>n; 
    //loop for taking n strings from user 
    for(int i=0;i<n;i++)
    {
        string a;
        cin>>a;
        s.push_back(a);
    }
    concat_str(s,n);
    return 0;
}

/*
Time Complexity : O(n*m), where m is maximum length of string a
Space Complexity : O(k), where k is final length of f_str

Sample Test Case :
Input : 4
        "This"
        "is"
        "Concatenated"
        "String."
Output : "ThisisConcatenatedString."
*/


<|start_filename|>C-Plus-Plus/sort/BST_Sort.cpp<|end_filename|>
/* SORTING USING BINARY SEARCH TREE
    Binary Search Tree is a special type of binary tree where
    1. The value of all the nodes in the left sub-tree is less than or equal to the value of the root.
    2. The value of all the nodes in the right sub-tree is greater than value of the root.
    3. This rule will be recursively applied to all the left and right sub-trees of the root.

    Inorder traversal
    1. Traverse the left subtree
    2. Visit the root.
    3. Traverse the right subtree

    Inorder traversal in BST gives sorted list
*/

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

// Declare treeNode with data , rc (right child) and lc (left child )
typedef struct treeNode
{
    int data;
    struct treeNode *lc;
    struct treeNode *rc;
} treeNode;

int count = 0;

//to insert a node into BST
treeNode *insertIntoTree(treeNode *root, int data)
{
    //If tree is empty insert as root node
    if (root == NULL)
    {
        treeNode *ptr;
        ptr = new treeNode;
        ptr->data = data;
        ptr->lc = NULL;
        ptr->rc = NULL;
        root = ptr;
    }
    else
    {
        // insert recursively in accordance with BST properties
        if (root->data >= data)
        {
            root->lc = insertIntoTree(root->lc, data);
        }
        else if (root->data < data)
        {
            root->rc = insertIntoTree(root->rc, data);
        }
    }
    return root;
}

//to sort-inorder traversal gives sorted list
void inorder(treeNode *root)
{
    //If tree is empty
    if (root)
    {
        // recursively visit left sub-tree,root and right sub-tree
        inorder(root->lc);
        printf("%d ", root->data);
        inorder(root->rc);
    }
}

// driver code
int main()
{
    //Initialize tree as empty
    treeNode *root;
    root = NULL;
    int n, data;
    //Accept the no. of elements and elements as user input
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &data);
        root = insertIntoTree(root, data);
    }
    printf("\nSorted list : ");
    inorder(root);
    printf("\n");
    return 0;
}
/*
    Sample input:
    7
    1 2 5 3 7 4 6

    Sample output:
    1 2 3 4 5 6 7
*/
/*
    Time complexity : O(n)
    Space complexity : O(n)
*/


<|start_filename|>C/search/random_search.c<|end_filename|>

/*
It is a monte carlo version of code with a depth,it give you the optimal or sub optimal result
*/

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int pick_random(int *a,int n){
    int i;
    time_t t;

    srand((unsigned)time(&t));

    return a[rand()%n];
}

int* create(int n){
    int* a = (int*)malloc(n*sizeof(n));

    for (int i = 0; i < n; i++)
    {
        /* code */
        scanf("%d",(a+i));
    }

    return a;
    
}

void display(int *a,int n){
    for (int i = 0; i < n; i++)
    {
        /* print the array */
        printf("%d ",*(a+i));
    }
    
}

int random_search(int element,int *a,int n){
    int set_depth = 1000;
     while (1 || set_depth<1000)
     {
         /* infinite loop untill get the element */
         int temp = pick_random(a,n);

         if (temp == element)
         {
             return 1;
             break;
         }

         set_depth++;
         
     }

     return 0;
     
}

int main(int argc, char const *argv[])
{
    int n;

    printf("enter the size of the array:");
    scanf("%d",&n);


    int *a = create(n);

    display(a,n);
    
    int element;

    printf("enter the element to search:");
    scanf("%d",&element);

    if(random_search(element,a,n)==1){
       printf("element found");
    }
    else
    {
        printf("element not found");
    }
    
    return 0;
}


<|start_filename|>C-Plus-Plus/dp/bellman_ford.cpp<|end_filename|>
#include<bits/stdc++.h>
using namespace std;

//Structure
typedef struct ed
{
  int from,dest,wt;
}ed;

//Bellman ford function began
void bellman(int nv,ed e[],int src_graph,int ne,int size)
{
  int u,v,weight,i,j=0;
  int arr[size];
  
  /* initializing array 'arr' with 999.*/
  for(i=0;i<nv;i++)
  {
    //999 is infinte distance
    arr[i]=999;
  }
  arr[src_graph]=0;
  for(i=0;i<nv-1;i++)
  {
    for(j=0;j<ne;j++)
    {
      u=e[j].from;
      v=e[j].dest;
      weight=e[j].wt;
      if(arr[u]!=999 && arr[u]+weight < arr[v])
      {
        arr[v]=arr[u]+weight;
      }  
    } 
  }
  
  /* check for negative cycle*/
  for(j=0;j<ne;j++)
  {
    u=e[j].from;
    v=e[j].dest;
    weight=e[j].wt;
    
    if(arr[u]+weight < arr[v])
    {
      cout<<"\n\nThere is NEGATIVE CYCLE!!\n";
      return;
    }  
  }
  // Print the output
  cout<<"\n\tOUTPUT\n";
  cout<<"\nVertex"<<"  Distance from source";
  for(i=1;i<=nv;i++)
  {
    cout<<"\n"<<i<<"\t"<<arr[i];
  }
}
//Bellman Ford function end

//Main Function began
int main()
{
  int nv,ne,src_graph,size;
  cout<<"Enter the max size of the array:\n";
  cin>>size;
  ed e[size];
  //Take input from the user
  cout<<"Enter the number of vertices: ";
  cin>>nv;  
  
  /* if you enter no of vertices: 5 then vertices will be 1,2,3,4,5.*/
  printf("Enter the source vertex: ");
  cin>>src_graph;  
  //Enter number of edges 
  cout<<"\nEnter no. of edges: ";
  cin>>ne;
  
  for(int i=0;i<ne;i++)
  {
    cout<<"\nEdge "<<i+1<<"=>";
    cout<<"\nEnter source vertex :";
    cin>>e[i].from;
    cout<<"Enter destination vertex :";
    cin>>e[i].dest;
    cout<<"Enter weight :";
    cin>>e[i].wt;  
  }
  //calling bellman ford function
  bellman(nv,e,src_graph,ne,size);
  return 0;
}
//Main function ends

/*Sample Input Output

Enter the max size of array : 10
Enter the number of vertices: 4
Enter the source vertex: 1

Enter no. of edges: 4

Edge 1=>
Enter source vertex :1
Enter destination vertex :2
Enter weight :4

Edge 2=>
Enter source vertex :1
Enter destination vertex :3
Enter weight :3

Edge 3=>
Enter source vertex :2
Enter destination vertex :4
Enter weight :7

Edge 4=>
Enter source vertex :3
Enter destination vertex :4
Enter weight :-2

Vertex  Distance from source
1       0
2       4
3       3
4       1

Time Complexity : O(V*E)
where V is no. of vertices and E is no. of edges in the graph.
*/


<|start_filename|>C-Plus-Plus/cp/minimum_window_substring.cpp<|end_filename|>
/**
 * Minimum Window Substring 
 *          OR
 * Smallest Window in a String Containing All Characters of Another String
 * Given two strings string1 and string2, find the smallest substring in 
 * string1 containing all characters of string2. 
 */

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

string minWindow(string str, string pattern)
{ //unordered map for storing the characters in pattern that we need to check for in str
    unordered_map<char, int> letters;
    for (auto c : pattern)
        letters[c]++;
    //counts number of pattern'str letters in current window
    int count = 0;
    int low = 0, min_length = INT_MAX, min_start = 0;
    for (int high = 0; high < str.length(); high++) {
        if (letters[str[high]] > 0)
            count++; //means that this letter is in pattern
        //reduce the count for the letter on which we are currently
        letters[str[high]]--;
        if (count == pattern.length()) {
            //if current windows contains all of the letters in pattern
            while (low < high && letters[str[low]] < 0)
                letters[str[low]]++, low++;
            //move low ahead if its not of any significance
            if (min_length > high - low)
                //update the min length
                min_length = high - (min_start = low) + 1;
            //move low ahead and also increment the value
            letters[str[low++]]++;
            //count-- as we are moving low ahead & low pointed to a char in pattern before
            count--;
        }
    }
    //check for edge case & return the result
    return min_length == INT_MAX ? "" : str.substr(min_start, min_length);
}
int main()
{
    //taking input from user
    string str, pattern;
    cout << "Enter a String text: ";
    cin >> str;
    cout << "Enter a String pattern: ";
    cin >> pattern;
    cout << "Smallest substring in text, containing all characters in pattern: ";
    cout << minWindow(str, pattern);
}
/*
    Test Cases:

    INPUT:
    Enter a String text: saazksaa
    Enter a String pattern: szk
    OUTPUT:
    Smallest substring in text, containing all characters in pattern: zks

    INPUT:
    Enter a String text: letuscontributetoopensource
    Enter a String pattern: ubr
    OUTPUT:
    Smallest substring in text, containing all characters in pattern: ribu

    Time Complexity: O(N)
    Space Compleaxity: O(Charcter Count)

 */


<|start_filename|>C-Plus-Plus/math/Happy_Number.cpp<|end_filename|>
/*
Write an algorithm to determine if a number n is happy.

A happy number is a number defined by the following process:

Starting with any positive integer, replace the number by the sum of the squares of its digits.
Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process ends in 1 are happy.

Example:

Input: n = 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
*/
#include <iostream>
using namespace std;

class Happy {
    int n;
public:
    void set_data(){
        cout<<"Enter the number you want to check"<<endl;
        cin>>n;
    }
    bool isHappy(int n) {
        if (n==1)
            return true;
        else if (n!=7 and n < 10)
            return false;
        else
            return isHappy(sq_of_dig(n));
        return false;
    }
    int sq_of_dig(int n){
        int s=0;
        while(n!=0){
            int d= n%10;
            s=s+d*d;
            n=n/10;
        }
        return s;
    }
    void display(){
        if(isHappy(n))
            cout<<"Yes its a happy number";
        else
            cout<<"No its not a happy number";
    }
};
int main()
{
    Happy h;
    h.set_data();
    h.display();

    return 0;
}
/*
Enter the number you want to check
Input: 19
Output: Yes its a happy number

Enter the number you want to check
Input: 2
Output: No its not a happy number
*/


<|start_filename|>C-Plus-Plus/ds/QueueLinkedList.cpp<|end_filename|>
/*Implementation of Queue using linked list U can peerfom enqueue , dequeue and display elements of queue */

#include<iostream>
using namespace std;

class Node {
  int data;
  Node *next;
public:
  friend class queue;
};


class queue {
  Node *front , *rear;
public:
  queue() {
    front = rear = NULL;

  }
  void enQueue(int x) {

    if (rear == NULL) {
      Node *temp = new Node();
      temp->data = x;
      temp->next = NULL;
      rear = temp;
      front = rear;
    }
    else {
      Node *temp = new Node();
      temp->data = x;
      temp->next = NULL;
      rear->next = temp;
      rear = temp;
    }

  }
  void deQueue() {
    // Node *temp = front;
    if (front == NULL)
    {
      return;
    }
    Node * temp = front;
    front = front->next;

    if (front == NULL) {
      rear = NULL;
    }
    cout << "Deleted Elemeted is :" << temp->data << endl;
    free(temp);

  }
  void displayQueue() {
    Node *temp = front;
    if ((front == NULL) || (rear == NULL)) {
      cout << "Queue is empty!!" << endl;
      return;
    }
    cout << "Queue Elements are :" << endl;
    while (temp != NULL) {
      cout << temp->data << " ";
      temp = temp->next;
    }
    cout << endl;
  }

};

int main() {
  queue q;
  int ch;
  do {
    cout << "Enter the option below :\n1.Enqueue an Element \n2.Dequeue an Element \n3.Display all elements of a queue\n4.Exit \n";
    cin >> ch;
    switch (ch) {
    case 1:
      int k;
      cin >> k;
      q.enQueue(k);
      break;
    case 2:
      q.deQueue();
      break;
    case 3:
      q.displayQueue();
      break;
    }
  } while (ch != 4);
}


<|start_filename|>C-Plus-Plus/cp/MosAlgo.cpp<|end_filename|>
#include <bits/stdc++.h>
using namespace std;

int b;

struct Problem
{
    int Left, Right;
};

void probRes(int a[], int n, Problem p[], int m)
{
    
    b = (int)sqrt(n);

    
    sort(p, p+m , check);

    int currLeft = 0, currRight = 0;
    int currSum = 0;

    
    for (int i=0; i<m; i++)
    {
        
        int Left = p[i].Left, Right = p[i].Right;
        while (currLeft < Left)
        {
            currSum -= a[currLeft];
            currLeft++;
        }
        while (currLeft > Left)
        {
            currSum += a[currLeft-1];
            currLeft--;
        }
        while (currRight <= Right)
        {
            currSum += a[currRight];
            currRight++;
        }

        while (currRight > Right+1)
        {
            currSum -= a[currRight-1];
            currRight--;
        }

        cout << "Sum of [" << Left << ", " << Right
            << "] is " << currSum << endl;
    }
}

bool check(Problem x, Problem y)
{
    
    if (x.Left/b != y.Left/b)
        return x.Left/b < y.Left/b;

    
    return x.Right < y.Right;
}

int main()
{
    int a[] = {1, 1, 2, 1, 3};
    int n = sizeof(a)/sizeof(a[0]);

    Problem p[] = {{1, 5}, {2, 4}};
    int m = sizeof(p)/sizeof(p[0]);
    
    probRes(a, n, p, m);
    return 0;
} 

// O(m * √n)

// O/P : Sum of [1, 5] is 6
// Sum of [2, 4] is 6



// Some other examples:
// I/P:
// Arr = [0, 1, 1, 0, 2, 3, 4, 1, 3, 5, 1, 5, 3, 5, 4, 0, 2, 2] of 18 elements
// Queries (0-indexed): [0, 8], [2, 5], [2, 11], [16, 17], [13, 14], [1, 17], [17, 17]


// O/P:
// 27
// 6
// 47
// 8
// 9
// 122
// 2


<|start_filename|>C-Plus-Plus/dp/Palindrome_Partitioning.cpp<|end_filename|>
/*
Given a string s, determine the minimum number of cuts required to make all substrings into palindrome.
*/
#include <bits/stdc++.h> 
using namespace std; 

bool dp[1001][1001];

int minCutToPalindrome_Opt(string s) {
        int n = s.length();
        // Computing dp (2D matrix) where [a,b] stores whether the sub-string 'a' to 'b' is a palindrome.
        bool dp[s.length()][s.length()];
        for (int mid = 0; mid < s.length(); mid++) {
            int si = 0, ei = mid;
            while (ei < s.length()) {
                //If no letter is present in the gap then it is a palindrome
                if (mid == 0) {
                    dp[si][ei] = true;
                } 
                //If one letter is present in middle then it is a palindrome if both the extreme letters are same
                else if (mid == 1) {
                    dp[si][ei] = s[si] == s[ei];
                } 
                //If more than more letter in the middle then both the extreme letters must be same, and compare the middle string represented by dp[si + 1][ei - 1];
                else {
                    if (s[si] == s[ei]) {
                        dp[si][ei] = dp[si + 1][ei - 1];
                    } else {
                        dp[si][ei] = false;
                    }
                }
                si++;
                ei++;
            }
        }
// Array to store minCuts for every suffix
        int cuts[n];
        for (int i = 0; i < n; i++) {
            if (dp[0][i] == true) {
                cuts[i] = 0;
            } else {
                cuts[i] = INT_MAX;
                for (int j = 0; j < i; j++) {
                    if(dp[j + 1][i] == true && 1 + cuts[j] < cuts[i]){
                        cuts[i] = 1 + cuts[j];
                    }
                }
            }
        }
        return cuts[n - 1];
    }

int main() 
{ 
    memset(dp,-1,sizeof(dp));
    string s;
    cin>>s;
    cout<<minCutToPalindrome_Opt(s)<<endl;
    return 0; 
}

/*
Time complexity: O(n^2) 

Sample Input 1: 
RADARROTATOR
Output: 1
Explanation: We can make 1 cut and make the resulting substrings palindromes. (RADAR | ROTATOR)

Sample Input 2:
REFERENCE
Output: 4
Explanation: We need to cut the string at 4 places i.e, REFER | E | N | C | E
*/


<|start_filename|>Java/Greedy_Algorithms/FractionalKnapsack.java<|end_filename|>
/* You are given two lists of integers weights and values which have 
the same length and an integer capacity. weights[i] and values[i] 
represent the weight and value of the ith item. Given that you can 
take at most capacity weights, and that you can take a fraction of 
an item's weight with proportionate value, return the maximum amount
of value you can get, rounded down to the nearest integer. */


import java.util.*;

public class FractionalKnapsack {

    /* Pair class used to store the weight, value, and ratio of value:weight of a particular item */
    static class Pair{
        int wt;
        int val;
        double ratio;
    }
    
    /* Used to sort all items based on their value:weight ratio in descending order */
    static class SortByRatio implements Comparator<Pair>{
        public int compare(Pair a, Pair b){
            if(b.ratio >= a.ratio){
                return 1;
            }else{
                return -1;
            }
        }
    }

    /* Function created to get maximum Profit */
    public static int getMaxProfit(int[] weights, int[] values, int capacity) {

        /* Creating a pairs array which stores all the items according to their weight,value and ratio */
        Pair pairs[] = new Pair[weights.length];

        /* Adding items to the pairs array */
        for(int i=0; i<weights.length; i++){

            Pair p = new Pair();
            p.val = values[i];
            p.wt = weights[i];
            double wt = weights[i];
            double val = values[i];
            
            p.ratio = val/wt;       
            pairs[i] = p; 
        }

        /* Sorting the pairs array based on their ratio */
        Arrays.sort(pairs, new SortByRatio());

        /* Initializing an ans variable */
        int ans = 0;

        /* Traversing through all items in the array */
        for(Pair p : pairs){

            /* Including a particular item, if we can accommodate it */
            if(p.wt <= capacity){
                ans += p.val;
                capacity-=p.wt;
            }
            /* Taking the fractional value of the item if we cannot accommodate it */
            else{
                ans += (p.ratio * capacity);

                /* Breaking from loop as we reached our peak capacity */
                break;
            }
        }

        return ans;
    }

    public static void main(String[] args) {
        
        Scanner input = new Scanner(System.in);

        int items = input.nextInt();

        int weights[] = new int[items];
        int values[] = new int[items];

        int capacity = 0;

        for(int i=0; i<items; i++){
            weights[i] = input.nextInt();
        }

        for(int i=0; i<items; i++){
            values[i] = input.nextInt();
        }

        capacity = input.nextInt();

        input.close();

        System.out.println(getMaxProfit(weights, values, capacity));
    }
}

/*
Input

weights = [5, 6, 2]
values = [100, 100, 1]
capacity = 8

Output

150

Explanation

Take the item with weight 5 and value 100, we are left with capacity 3
Take half of the item with weight 6, so it's value would become 50.
Thereby getting a maximum profit of 150

Time Complexity : O(N)
Space Complexity : O(N)

*/



<|start_filename|>Go/math/Happy_Number/happynumber.go<|end_filename|>
/*
   This is a simple program in go language 
   to find out if a number ios happy or not.
   Happy number is a number which eventually 
   reaches 1 when replaced by the sum of the 
   square of each digit. 

   Example : 10 => 1^2 +0^2 = 1
   So, 10 is happy number!

*/

package main

import (

   "fmt"

)

/* This function counts the number of digits 
   in the the given number*/
func digits(a int) int {

   var counter int
   counter = 0

   for a !=0 {

     a = a/10
     counter += 1

   }

   return counter
}

/* This function returns the sum of squares
   of the individual digits for a given number*/
func numbersquares(number int) int {

  var sum int
  sum = 0

  var digit int
  digit = 0

  var r int
  r = 0

  /* calling the digits function to return number
     of digits for the number we gave it has*/
  digit = digits(number)

  for i:=0;i<digit;i++ {

     r = number%10
     sum += r*r
     number = number/10

  }

  return sum

}

/* This function tells us if a given number number 
   is happy or not*/
func happynumber(n int) int{

    var final_sum int
    final_sum = n

    // base case as these are happy numbers
    if(n==1 || n==7){

       return 1

    }

    // if the sum is in double digits
    for final_sum > 9 {

       final_sum = numbersquares(n)

       if(final_sum == 1){

            return 1

       }

       n = numbersquares(n)

    }

    if(final_sum == 7){

       return 1

    }else{

      return 0

    }

}

// driver function
func main() {

   var number int

   // Taking the input here
   fmt.Print("Enter the number you want to check for :")
   fmt.Scan(&number)

   var checker int
   checker = happynumber(number)

   // we print out the message here
   if(checker == 1){

      fmt.Print("The number is Happy Number!")

   }else{

      fmt.Print("The number is not a Happy Number!")

   }

}

/*
   Sample I/O :

   a) Is a happy number :

   Enter the number you want to check for :10
   The number is Happy Number! 

   b) Is not a happy number :

   Enter the number you want to check for :5
   The number is not a Happy Number!  

*/



<|start_filename|>C-Sharp/other/Largest_Kth_Element.cs<|end_filename|>
﻿/*
* The Problem is finding the largest Kth item in Two Separated sorted Arrays
* Complexity O(log(N))
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NeoAlgo
{
    class Program
    {
        private static int KElement(int[] A1, int s1, int e1, int[] A2, int s2, int e2, int k)
        {
            int mid1 = (e1 - s1) / 2;
            int mid2 = (e2 - s2) / 2;

            if (s1 == e1)
                return A2[s2 + k];
            if (s2 == e2)
                return A1[s1 + k];
            /*
             * Ex: 1 4 8 , 2 10 15 K = 2
             * Trying to neglect one half of the arrays 
             */
            else if (mid1 + mid2 < k)
            {
                /*
                 * if A1[s1 + mid1] > A2[s2 + mid2]
                 * So I am Sure I can neglect first half of second array
                 */
                if (A1[s1 + mid1] > A2[s2 + mid2])
                    return KElement(A1, s1, e1, A2, s2 + mid2 + 1, e2, k - mid2 - 1);
                /*
                 * if A1[s1 + mid1] <= A2[s2 + mid2]
                 * So I am Sure I can neglect first half of first array
                 */
                else if (A1[s1 + mid1] <= A2[s2 + mid2])
                    return KElement(A1, s1 + mid1 + 1, e1, A2, s2, e2, k - mid1 - 1);

            }
            else
            {
                if (A1[s1 + mid1] >= A2[s2 + mid2])
                    return KElement(A1, s1, s1 + mid1, A2, s2, e2, k);
                else if (A2[s2 + mid2] > A1[s1 + mid1])
                    return KElement(A1, s1, e1, A2, s2, s2 + mid2, k);

            }
            return 0;
        }
        public static int GetKthItem(int[] arr1, int[] arr2, int N, int M, int K)
        {

            /*
             * Find the Position of Element if the two arrays was merged
             * EX:
             * In A1: 1 5 6  A2: 7 8 10 k = 4
             * Fourth Largest Element is 6
             * It's Position is (3+3) - 4 = 2
             * And true it's the third Element with index 2
             * And this is the new k
             */
            int s = (N + M) - K;
            int res = KElement(arr1, 0, N, arr2, 0, M, s);
            return res;
        }
       
        static void Main(string[] args)
        {
            Console.WriteLine("Enter Size of First Array: ");
            int N;
            N = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter Size of Second Array: ");
            int M;
            M = int.Parse(Console.ReadLine());
            int[] A1 = new int[N];
            int[] A2 = new int[M];
            Console.WriteLine("Enter Elements of First Sorted Array: ");
            for (int i = 0; i < N; i++)
            {
                A1[i] = int.Parse(Console.ReadLine());
            }
            
            Console.WriteLine("Enter Elements of Second Sorted Array: ");
            for (int i = 0; i < M; i++)
            {
                A2[i] = int.Parse(Console.ReadLine());
            }
            Console.WriteLine("Enter the Kth Item: ");
            int k = int.Parse(Console.ReadLine());
            Console.WriteLine("The number is: " + GetKthItem(A1, A2, N, M, k)); ;
            /*
             * Ex: A1: 1 5 7
             *     A2: 2 6 10
             *     k = 3
             *     Output = 7
             *     Complexity O(Log(N))
            */
        }
    }
}


<|start_filename|>C-Plus-Plus/cp/target_sum_triplets.cpp<|end_filename|>
#include<iostream>
#include<bits/stdc++.h>

using namespace std;

//triplets printing function
void printtriplets(int* arr,int n,int sum)
{
	//sorting array initially
	sort(arr,arr+n);
	cout<<"The triplet sets are:"<<endl; 
	for(int i =0;i<n-1;i++)
	{
		int left=i+1;
		int right=n-1;
		int current=arr[i];
		while (left < right) 
		{ 
                    if (current + arr[left] + arr[right] == sum) 
	            { 
			    // Print elements if it's sum is given sum.
				//printing elements in ascending order 
                            cout<<current<<", "<<arr[left]<<" and "<<arr[right]<<endl;
                            left++; 
                            right--; 
                    } 
  
                    // If current sum is less than 'sum' then increment the left index
                    else if (current + arr[left] + arr[right] < sum) 
                    left++; 
  
                    // if current sum is greater than  'sum', then decrement the right index 
                    else
                    right--; 
                } 
	 }
}

//Main function
int main() 
{
	int end,target;
	cout<<"Enter the no. of elements in array you want to enter"<<endl; 
	cin >> end;
	
	int* input = new int[end];
	cout<<"Enter elements"<<endl;
	for(int ind=0;ind<end;ind++)
		cin >> input[ind];
	
	cout<<"Enter target"<<endl;	
	cin>>target;
	printtriplets(input,end,target);
	delete[] input;
	return 0;
}


<|start_filename|>C-Plus-Plus/cp/Plucking_Flowers.cpp<|end_filename|>
/* 
Jay's neighbour has a garden in which there are N flowers and each flower has a beauty associated with it i.e. ith flower
 has B[i] beauty. Jay wants to pluck exactly K flowers from his neighbour's garden such that the sum of beauties of all flowers
 he plucked is maximum but to not get caught he can't pluck more than one flower in a row, more formally he can't pluck two 
flowers if they are adjacent. Your task is to find maximum sum of beauty of all flowers Jay can get.
*/

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

#define ll long long int

long long maxBeauty(int n, int k, vector<int> &B){
        ll i,j,dp[k+1][n+1];
        memset(dp,0,sizeof(dp));
        for(i=1;i<=k;i++)
        {
            for(j=2*i-1;j<=n;j++)
            {
                dp[i][j]=B[j-1];
                if(j-2>=0)
                {
                    dp[i][j]+=dp[i-1][j-2];
                }
                dp[i][j]=max(dp[i][j],dp[i][j-1]);
            }
        }
        return dp[k][n];
    }


int main(){
    
        int totalFlowers, k;
        cout << "Enter total number of flowers and maximum flowers to be plucked ";
        cin >> totalFlowers >> k;                          // size of array and max flowers required
        vector<int> Beauty(totalFlowers);
        cout<< " Enter beauty of each flower : " ;
        for(int i = 0; i < totalFlowers; i++){
            cin >> Beauty[i];                                    // input array
        }
        long long answer =maxBeauty(totalFlowers , k , Beauty);
        cout << " maximum sum of beauty by k flowers : " << answer << endl;
    
}    
    
/*

Input:
Enter total number of flowers and maximum flowers to be plucked : 3  2
Enter beauty of each flower : 1  1000000  1

Output: 
maximum sum of beauty by k flowers : 2

Time Complexity: O(totalFlowers*K)
Auxiliary Space: O(totalFlowers*K)

*/


<|start_filename|>C/ds/Hash_Table.c<|end_filename|>
/*  HASH TABLE USING LINEAR PROBING
    * Hash table is a type of access table which contains key-value pairs
    * Each value is placed into a location in the hash table
    * This location will be calculated from the value itself
    * The mapping between a value and an index in the hash table is known as hashing
    * Allotment of more than one key value in one location in hash table is called collision
    * Linear Probing / Closed Hashing is a collision resolution technique

    Closed hashing works as follows:
        1. Start with the index where collision has occured, say i
        2. Continue the sequential search in the following locations:
            i, i+1, i+2,...., h,1,2,...i-1
        3. Here the table is considered circular, ie,when the last location is reached,
           search proceeds to first location of table
*/

#include <stdio.h>
#include <stdlib.h>

//Declare a hash table of preferred size
#define SIZE 10
typedef int* HashTable;

//Hashing function to get index for a given value
int hash(int val)
{
    return val % SIZE;
}

//to insert into hash table
void insert(HashTable ht, int val)
{
    /*Compute the index and search for an empty location
      from key in a circular manner*/
    int key = hash(val);
    int i = key;
    do
    {
        if (ht[i] == 0)
        {
            ht[i] = val;
            return;
        }
        i = (i + 1) % SIZE;
    } while (i != key);
}

//to check if a value exists in the hash table
int doesExist(HashTable ht, int val)
{
    //return 1 if exists and 0 if not
    int k = hash(val), i = k;
    do
    {
        if (ht[i] == val)
            return 1;
        i = (i + 1) % SIZE;
    } while (i != k);
    return 0;
}

//to print hash table as key-value pairs
void print(HashTable ht)
{
    for (int i = 0; i < SIZE; i++)
        printf("%d -> %d\n", i, ht[i]);
}

// driver code
int main()
{
    HashTable ht = (int*)malloc(sizeof(int) * SIZE);
    int opt, val, exists;
    // menu-driven program to insert to,check for existence and print the hash table
    do
    {
        scanf("%d", &opt);
        switch (opt)
        {
            case 1:
                scanf("%d", &val);
                insert(ht, val);
                break;
            case 2:
                scanf("%d", &val);
                exists = doesExist(ht, val);
                if (exists)
                    printf("Exists\n");
                else
                    printf("Doesn't Exist\n");
                break;
            case 3:
                print(ht);
                break;
        }

    } while (opt != 4);

    return 0;
}

/*
    Sample Input:
    1                                                                                                                                               
    2                                                                                                                                               
    1                                                                                                                                               
    3                                                                                                                                               
    1                                                                                                                                               
    12                                                                                                                                              
    1                                                                                                                                               
    4                                                                                                                                               
    1                                                                                                                                               
    8                                                                                                                                               
    3  

    Sample Output:
    0 -> 0                                                                                                                                          
    1 -> 0                                                                                                                                          
    2 -> 2                                                                                                                                          
    3 -> 3                                                                                                                                          
    4 -> 12                                                                                                                                         
    5 -> 4                                                                                                                                          
    6 -> 0                                                                                                                                          
    7 -> 0                                                                                                                                          
    8 -> 8                                                                                                                                          
    9 -> 0  

*/

/*
    Time Complexity: O(SIZE)
    Space Complexity: O(n) , n-no of values
*/


<|start_filename|>JavaScript/sort/quicksort.js<|end_filename|>
/*
What is Quick Sort?

Quick Sort algorithm follows Divide and Conquer approach.
It divides elements into smaller parts based on some condition and
performing the sort operations on those divided smaller parts.

Time Complexity : O(N*logN)
*/

var items = [5,3,7,6,2,9];
function swap(items, leftIndex, rightIndex){
    var temp = items[leftIndex];
    items[leftIndex] = items[rightIndex];
    items[rightIndex] = temp;
}
function partition(items, left, right) {
    var pivot = items[Math.floor((right + left) / 2)], //middle element
        i = left,                                      //left pointer
        j = right;                                     //right pointer
    while (i <= j) {
        while (items[i] < pivot) {
            i++;
        }
        while (items[j] > pivot) {
            j--;
        }
        if (i <= j) {
            swap(items, i, j);                        //sawpping two elements
            i++;
            j--;
        }
    }
    return i;
}

function quickSort(items, left, right) {
    var index;
    if (items.length > 1) {
        index = partition(items, left, right);       //index returned from partition
        if (left < index - 1) {                      //more elements on the left side of the pivot
            quickSort(items, left, index - 1);
        }
        if (index < right) {                         //more elements on the right side of the pivot
            quickSort(items, index, right);
        }
    }
    return items;
}

// first call to quick sort

var sortedArray = quickSort(items, 0, items.length - 1);
console.log(sortedArray);

//prints [2,3,5,6,7,9]


<|start_filename|>C/cp/cp_sets_question.c<|end_filename|>
/* There is an array of n integers. There are also 2 disjoint sets, A and B, each containing m integers.
You like all the integers in set A and dislike all the integers in set B. Your initial happiness is 0. 
For each i integer in the array, if i e A , you add 1 to your happiness. If i e B, you add -1 to your happiness.
Otherwise, your happiness does not change. Output your final happiness at the end.

	Input Format
	
	The first line contains integers n and m separated by a space.
	The second line contains n integers, the elements of the array.
	The third and fourth lines contain m integers, A and B, respectively.
	
	Output Format
	
	Output a single integer, your total happiness.
	
Problem Link: https://www.hackerrank.com/challenges/no-idea/problem
*/

#include<stdio.h>

int countHappiness(int arr[], int n, int m, int A[], int B[]) {
  int happiness = 0, i, j;

  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++) {

      if (A[j] == arr[i]) {
        happiness += 1;
        break;
      }

      if (B[j] == arr[i]) {
        happiness -= 1;
        break;
      }
    }
  }
  return happiness;
}

int main() {
  int i, n, m, arr[100000], A[100000], B[100000], totalHappy;

  printf("Enter the value of n and m: ");
  scanf("%d%d", & n, & m);

  printf("Enter the elements of array: ");
  for (i = 0; i < n; i++)
    scanf("%d", & arr[i]);

  printf("Enter the elements of set A: ");
  for (i = 0; i < m; i++)
    scanf("%d", & A[i]);

  printf("Enter the elements of set B: ");
  for (i = 0; i < m; i++)
    scanf("%d", & B[i]);

  totalHappy = countHappiness(arr, n, m, A, B);
  printf("Total happiness= %d", totalHappy);

  return 0;
}

/*
	Sample input/output
	Enter the value of n and m: 3 2
	Enter the elements of array: 1 5 3
	Enter the elements of set A: 3 1
	Enter the elements of set B: 5 7
	Total happiness= 1
	
	Time Complexity= O(n^2) 
	Space Complexity= O(1)
*/


<|start_filename|>Java/ds/balancedBrackets.java<|end_filename|>
/*Given a string s containing round, curly, and square open and closing brackets,
 return whether the brackets are balanced. The aim of the program is to make use of stacks.*/

import java.util.*;

public class balancedBrackets {
    /* This method checks if the input string is balanced or not */
    public static boolean isBalanced(String s) {
        java.util.Stack<Character> stack = new java.util.Stack<>();
        if (s.length() == 1)
            return false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            /* If the present character is an opening bracket, we push it into the stack */
            if (c == '(' || c == '[' || c == '{')
                stack.add(c);

            /*
             * If it is a closing bracket, we check if the last character pushed into the
             * stack is the corresponding opening bracket or not and we pop it
             */
            else {
                if (c == ')') {
                    if (stack.isEmpty())
                        return false;
                    char c2 = stack.pop();
                    if (c2 != '(')
                        return false;
                } else if (c == ']') {
                    if (stack.isEmpty())
                        return false;
                    char c2 = stack.pop();
                    if (c2 != '[')
                        return false;
                } else if (c == '}') {
                    if (stack.isEmpty())
                        return false;
                    char c2 = stack.pop();
                    if (c2 != '{')
                        return false;
                }
            }
        }

        /*
         * At the end of all operations, if it turns out that the stack is not empty
         * i.e, the brackets are not balanced, we return false.
         */
        if (!stack.isEmpty())
            return false;
        return true;
    }

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);

        /* Taking the input string */
        System.out.println("Enter the string consisting of brackets");
        String s = sc.nextLine();

        /*
         * Passing the string to check if it is balanced or not and displaying output
         * accordingly
         */
        if (isBalanced(s))
            System.out.println("The given string " + s + " has balanced brackets in it.");
        else
            System.out.println("The given string " + s + " does not have balanced brackets in it.");
    }
}

/*
 * Sample Input: "([])[]({})" Output: The given string ([])[]({}) has balanced
 * brackets in it.
 */
/*
 * Time Complexity: O(n)
 */


<|start_filename|>C/ds/inorder_predecessor_successor.c<|end_filename|>
/*Inorder successor of a node is the next node in inorder traversal of the BST.
There is no inorder successor of the last node in inorder traversal of the BST.
Inorder predecessor of a node is the previous node in inorder traversal of the BST.
There is no inorder predecessor of the first node in inorder traversal of the BST.
*/

#include <stdio.h>
#include <stdlib.h>

struct tree
{
	struct tree * lptr;
	int data;
	struct tree * rptr;
};

//Insert function of BST
void insert(struct tree **b, int n)
{
	if (*b == NULL)
	{
		struct tree *new = (struct tree *) malloc(sizeof(struct tree));
		new->data = n;
		new->lptr = new->rptr = NULL;
		*b = new;
	}
	else
	{
		if ((*b)->data > n)
			insert(&((*b)->lptr), n);
		else
			insert(&((*b)->rptr), n);
	}
}

//Inorder display function using recursion
void inorder(struct tree *b)
{
	if (b != NULL)
	{
		inorder(b->lptr);
		printf("%d  ", b->data);
		inorder(b->rptr);
	}
}

//Function to find inorder predecessor of a node
int in_pre(struct tree *b, int node)
{
	struct tree *x = b, *xpre;
	int pre, flag = 0;
	while (x != NULL && x->data != node)
	{
		if (x->data > node)
			x = x->lptr;
		else
		{
			flag = 1;
			pre = x->data;
			x = x->rptr;
		}
	}

	if (x == NULL)
	{
		printf("Node not present in tree\n");
		return 0;
	}

	if (x->lptr != NULL)
	{
		xpre = x->lptr;
		while (xpre->rptr != NULL)
		{
			xpre = xpre->rptr;
		}

		printf("Predecessor of %d is %d\n", node, xpre->data);
		return 0;
	}
	else if (flag == 1)
		printf("Predecessor of %d is %d\n", node, pre);
	else
		printf("Predecessor of %d does not exist\n", node);
}

//Function to find inorder successor of a node
int in_succ(struct tree *b, int node)
{
	struct tree *x = b;
	int xsucc, f = 0;
	while (x != NULL && x->data != node)
	{
		if (x->data > node)
		{
			f = 1;
			xsucc = x->data;
			x = x->lptr;
		}
		else
			x = x->rptr;
	}

	if (x == NULL)
	{
		printf("Node not present in tree\n");
		return 0;
	}

	if (x->rptr != NULL)
	{
		x = x->rptr;
		while (x->lptr != NULL)
			x = x->lptr;
		printf("Successor of %d is %d\n", node, x->data);
		return 0;
	}
	else if (f == 1)
		printf("Successor of %d is %d\n", node, xsucc);
	else
		printf("Successor of %d does not exist\n", node);
}

int main()
{
	struct tree *root = NULL;
	char c;
	int ch, n;
	do {
		printf("\nMenu:\n1.Insert\t\t\t\t2.Inorder display\n3.Inorder Predecessor of a node\t\t4.Inorder Successor of a node\n");
		printf("Enter your choice: ");
		scanf("%d", &ch);
		switch (ch)
		{
			case 1:
				{
					printf("Enter data: ");
					scanf("%d", &n);
					insert(&root, n);
					break;
				}

			case 2:
				{
					if (root == NULL)
						printf("Tree is empty\n");
					else
					{
						printf("In-order Display: ");
						inorder(root);
						printf("\n");
					}

					break;
				}

			case 3:
				{
					if (root == NULL)
						printf("Tree is empty\n");
					else
					{
						printf("Enter the node for which you want inorder predecessor: ");
						scanf("%d", &n);
						in_pre(root, n);
					}

					break;
				}

			case 4:
				{
					if (root == NULL)
						printf("Tree is empty\n");
					else
					{
						printf("Enter the node for which you want inorder successor: ");
						scanf("%d", &n);
						in_succ(root, n);
					}

					break;
				}

			default:
				printf("Not a choice\n");
				break;
		}

		printf("Do you want to continue:(Y/y) ");
		scanf(" %c", &c);
	} while (c == 'Y' || c == 'y');
	return 0;
}

/*
Time Complexity:
Insertion - O(n)
Inorder display - O(n)
Inorder predecessor function - O(n)
Inorder successor function - O(n)

Space Complexity: O(n)

Sample Output: 
Menu:
1.Insert                                2.Inorder display
3.Inorder Predecessor of a node         4.Inorder Successor of a node
Enter your choice: 1
Enter data: 3
Do you want to continue:(Y/y) y
Menu:
1.Insert                                2.Inorder display
3.Inorder Predecessor of a node         4.Inorder Successor of a node
Enter your choice: 1
Enter data: 5
Do you want to continue:(Y/y) y
Menu:
1.Insert                                2.Inorder display
3.Inorder Predecessor of a node         4.Inorder Successor of a node
Enter your choice: 1
Enter data: 9
Do you want to continue:(Y/y) y
Menu:
1.Insert                                2.Inorder display
3.Inorder Predecessor of a node         4.Inorder Successor of a node
Enter your choice: 1
Enter data: 14
Do you want to continue:(Y/y) y
Menu:
1.Insert                                2.Inorder display
3.Inorder Predecessor of a node         4.Inorder Successor of a node
Enter your choice: 2
In-order Display: 3  5  9  14  
Do you want to continue:(Y/y) y
Menu:
1.Insert                                2.Inorder display
3.Inorder Predecessor of a node         4.Inorder Successor of a node
Enter your choice: 3
Enter the node for which you want inorder predecessor: 5
Predecessor of 5 is 3
Do you want to continue:(Y/y) y
Menu:
1.Insert                                2.Inorder display
3.Inorder Predecessor of a node         4.Inorder Successor of a node
Enter your choice: 4
Enter the node for which you want inorder successor: 9
Successor of 9 is 14
Do you want to continue:(Y/y) n
*/


<|start_filename|>Go/search/binary_search/binary_search.go<|end_filename|>
// Binary Search in Go
// Requires array to be sorted
// Return index of found element else return -1
package main

import (
	"fmt"
)

func main() {
	arr := []int{2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
	fmt.Printf("Array: %v\n", arr)
	var find int
	fmt.Printf("Please enter element to be found: ")
	fmt.Scan(&find)
	result := search(arr, find)
	fmt.Printf("Result: %d", result)
}

func search(list []int, item int) int {
	low := 0
	high := len(list) - 1
	for low <= high {
		middle := (low + high) / 2
		if list[middle] == item {
			return middle
		} else if list[middle] < item {
			low = middle + 1
		} else {
			high = middle - 1
		}
	}
	return -1
}


<|start_filename|>Java/math/Binary_Exponentiation.java<|end_filename|>
// Java Program to find Binary Exponent Iteratively and Recursively.

import java.util.Scanner;

public class Binary_Exponentiation {
   // Iterative function to calculate exponent.
   public static int binExpo_iterate(int a, int b) {
      int res = 1;
      while (b > 0) {
         if (b % 2 == 1) {
            res = res * a;
         }
         a = a * a;
         b /= 2;
      }
      return res;
   }
   // Recursive function to calculate exponent.
   public static int binExpo_recurse(int a, int b) {
      if (b == 0) {
         return 1;
      }
      int res = binExpo_recurse(a, b / 2);
      res = res * res;
      if (b % 2 == 1) {
         return res * a;
      } else {
         return res;
      }
   }
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);

      int a = sc.nextInt();
      int b = sc.nextInt();
      if (a == 0 && b == 0) {
         System.out.println("Math error");
      } else if (b < 0) {
         System.out.println("Exponent must be Positive");
      } else if (a == 0) {
         System.out.println("0");
      } else {
         int resIterate = binExpo_iterate(a, b);
         int resRecurse = binExpo_recurse(a, b);
         System.out.println(resIterate);
         System.out.println(resRecurse);
      }
   }
}


<|start_filename|>Go/math/Neon_Number/neonnumber.go<|end_filename|>
/* This is a simple program in go language to check if a given number is neon number
   or not. A neon number is a number where the sum of digits of the square of the
   number should be equal to the initial number.
*/

package main

import (

  "fmt"

)

// variables declared globally
var n int
var r int
var sum int
var square int

// This function calculates the sum of digits of a number
func Sum(square int) {

   for square != 0{

      r = square%10
      sum += r
      square = square/10

   }

}

// This function checks if a number is a neon number or not
func neon() {

   //calling sum function to calculate the sum
   Sum(square)

   if (sum == n){
      fmt.Print("The given number is a neon number !")

   }else{

      fmt.Print("The given number is not a neon number !")
   }

}

//driver function
func main() {

  fmt.Print("Enter the number here :")
  fmt.Scanln(&n)

  square = n*n

  //calling the neon function
  neon()

}

/*
   Sample I/O :

   a) Is a neon number :

   Enter the number here :9
   The given number is a neon number ! 

   b) Is not a neon number :

   Enter the number here :12
   The given number is not a neon number !  
*/



<|start_filename|>C-Plus-Plus/dp/Max_subarray_sum_constant_space(DP).cpp<|end_filename|>
/*

We can easily solve this problem in linear time using kadane’s algorithm.
The idea is to maintain maximum (positive sum) sub-array “ending” at each index of the given array.
This subarray is either empty (in which case its sum is zero) or consists of one more element than the maximum subarray ending at the previous index.
And, To Cover Both Positive and Negative Cases, approach requires two traversals of the input array.

*/

#include <bits/stdc++.h>

#define ll long long int
using namespace std;

// Function to find contiguous sub-array with the largest sum
// in given set of integers (handles negative numbers as well)

int kadane(ll arr[], ll n)
{
    // stores maximum sum sub-array found so far
    ll max_so_far = arr[0]; 

    // stores maximum sum of sub-array ending at current position
    ll max_ending_here = arr[0]; 

    for (ll i = 1; i < n; i++)
    {
        // update maximum sum of sub-array "ending" at index i (by adding current element to maximum sum ending at previous index i-1)
        max_ending_here = max_ending_here + arr[i];   
        
        // maximum sum is should be more than the current element
        max_ending_here = max(max_ending_here, arr[i]); 
        
        // update result if current sub-array sum is found to be greater
        max_so_far = max(max_so_far, max_ending_here); 
    }

    return max_so_far;
}

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

    cout << "" << kadane(arr, n);

    return 0;
}

/*

Time Complexity : O(n)
Space Complexity: O(1)

Sample Input: 

8
-2 1 -3 4 -1 2 1 -5 4

Sample Output:

6

*/


<|start_filename|>C-Plus-Plus/cp/replace_pi.cpp<|end_filename|>
/* Problem statement: 
You are given a string, you have to replace all the occurrences of "pi" int the string into 3.14. */
#include <bits/stdc++.h>
using namespace std;
void replacepi(char a[], int i)
{
    if (a[i] == '\0' or a[i + 1] == '\0')
    {
        return;
    }
    //checks if the current and the next part of the string is "pi"
    if (a[i] == 'p' and a[i + 1] == 'i')
    {
        //Shifting the replacement of 3.14
        int j = i + 2;
        //taking j to the end of the string
        while (a[j] != '\0')
        {
            j++;
        }

        while (j >= i + 2)
        {
            a[j + 2] = a[j];
            j--;
        }

        //replacing "pi" with 3.14
        a[i] = '3';
        a[i + 1] = '.';
        a[i + 2] = '1';
        a[i + 3] = '4';
        replacepi(a, i + 4);
    }
    //Go to the next position
    else
    {
        replacepi(a, i + 1);
    }
}

//Time Complexity :O(n)
int main()
{
    char a[1000];
    cin >> a;
    replacepi(a, 0);
    cout << a << endl;
    return 0;
}
/* 
Example 1:
Input : xpighpilmpipi
Output: x3.14gh3.14lm3.143.14

Example 2:
Input : abcpipikjpilk
Output: abc3.143.14kj3.14lk

Time Complexity :O(n) */

<|start_filename|>C/other/String_Palindrome_or_not.c<|end_filename|>
/*
To find whether the given string is a palindrome or not.
A palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward, such as madam or racecar.
*/

#include<stdio.h>
#include<conio.h>
struct Node
{
    char data;
    struct Node *next;
    struct Node *prev;
};
struct Node *head,*ptr;
void insert(char data)
{
    //allocate dynamic memory
    struct Node *newnode=(struct Node*)malloc(sizeof(struct Node));
    if(newnode==NULL)
    {
       printf("Overflow");
       return;
    }
    newnode->next=NULL;
    newnode->prev=NULL;
    newnode->data=data;
    if(head==NULL)
        head=newnode;
    else
    {
        ptr=head;
        while(ptr->next!=NULL)  
           ptr=ptr->next;
        ptr->next=newnode;
        newnode->prev=ptr;
    }
}
int isPalindrome()
{
    if(head==NULL)
        return 1;
    struct Node *right,*left;
    right=left=head;
    while(right->next!=NULL)
        right=right->next;
    while(left!=right)
    {
        if(left->data!=right->data)
            return 0;
        left=left->next;
        right=right->prev;
    }
    return 1;
}
void main()
{
    char s[20];
    int l=0,i=0,res;
    head=NULL;
    scanf("%s",&s);
    while(s[i]!='\0')
    {
        l++;
        i++;
    }
    for(i=0;i<l;i++)
        insert(s[i]);
    res=isPalindrome();
    if(res==1)
        printf("Palindrome");
    else
        printf("Not palindrome");
}

/*
Test case 1:
Input : malayalam
Output : Palindrome

Time complexity : O(n)
Space complexity : O(n)
*/


<|start_filename|>JavaScript/search/ManacherAlgorithm.js<|end_filename|>
const findPalindrome = (str) => {
  sequence = processString(str);

  // array for holding the palindromic sequence around every center
  let positions = [];
  let start = 0;
  let end = 0;

  // i is our current center
  for (let i = 0; i < sequence.length;) {

      // we check on both sides of i till where we can find same letters on 2
      // positions
      while (start > 0 && end < sequence.length - 1 && sequence[start - 1] === sequence[end + 1]) {
          start--;
          end++;
      }

      // getting the length of palindrome around current center
      positions.splice(i, 0, end - start + 1);

      // this is case 2. Current palindrome is proper suffix of input. Meaning input
      // is the longest palindrome
      if (end === (sequence.length - 1)) {
          break;
      }

      // Mark newCenter to be either end or end + 1 depending on if we dealing with
      // even or old number input.
      let newCenter = end + (i % 2 == 0 ? 1 : 0);

      for (let j = i + 1; j <= end; j++) {

          // Its possible left mirror might go beyond current center palindrome. So take
          // minimum of either left side palindrome or distance of j to end.
          // T[j] = Math.min(T[i - (j - i)], 2 * (end - j) + 1);
          num = positions[Math.abs(i - (j - i))];
          positions.splice(j, 0, (Math.min(num, (2 * (end - j) + i))));

          // This check is to make sure we do not pick j as new center. As soon as we find
          // a center lets break out of this inner loop.
          if (j + parseInt(positions[i - (j - i)] / 2) === end) {
              newCenter = j;
              break;
          }
      }

      // make i as newCenter. Set right and left to atleast the value we already know
      // should be matching based of left side palindrome.
      i = newCenter;
      if (i < positions.length) {
          end = i + parseInt(positions[i] / 2);
          start = i - parseInt(positions[i] / 2);
      }
  }

  let max = Math.max.apply(null, positions);
  let pos = positions.indexOf(max);

  let pos1 = pos - parseInt(max / 2);
  let pos2 = pos + parseInt(max / 2);
  if (positions.length % 2 == 0) {
      sequence = sequence.slice(pos1, pos2 + 1);
  } else {
      sequence = sequence.slice(pos1, pos2);
  }

  // removing $ signs
  str = originalString(sequence);

  return str;
}

const originalString = (arr) => {
  return arr.filter(x => x !== '$').join('');
}

const processString = (str) => {
  let strArr = ['$'];

  for (let i = 0; i < str.length; i++) {
      strArr.push(str[i]);
      strArr.push('$');
  }

  return strArr;
}

const str1 = findPalindrome("abba");
const str2 = findPalindrome("babcbaabcbaccba");

console.log("Longest palindromic substring for input 1:" + str1);
console.log("Size:" + str1.length);
console.log("Longest palindromic substring for input 2:" + str2);
console.log("Size:" + str2.length);

/**
* Outputs for the sample inputs:
* Longest palindromic substring for input 1:abba
* Size:4
* Longest palindromic substring for input 2:abcbaabcba
* Size:10
*
* Time complexity: O(n) Space complexity: O(n)
*/

<|start_filename|>Java/cp/MaximumOfMinimumSubarrays.java<|end_filename|>
/**
 * Maximum of Minimum for Every Window Size in an Array
 * Find the maximum of the minimums of every window size in a given 
 * positive integer array of size n. The size of windows in an array 
 * vary from 1 to n. 
 */

import java.io.*;
import java.util.*; 
public class MaximumOfMinimumSubarrays {

    public static int[] findMaximumOfMinimums(int[] numArray, int n) {

        //The next[] and prev[] arrays store the indices of next smaller 
        //and previous smaller integers for each element.  
        int[] next = new int[n]; 
        int[] prev = new int[n];

        //If next smaller element is non-existent, then n is stored, if
        //previous smaller element in non-existent, then -1 is stored. 
        for(int i=0; i<n; ++i) {
            next[i] = n; 
            prev[i] = -1; 
        }

        //Using stack to get next smaller element
        ArrayDeque<Integer> indices = new ArrayDeque<>(); 
        for(int i=0; i<n; i++) {
            while(indices.peek()!=null && numArray[indices.peek()] > numArray[i]) {
                next[indices.peek()] = i;
                indices.pop(); 
            }
            indices.push(i); 
        }
        indices.clear(); 

        //Using stack to get previous smaller element
        for(int i=n-1; i>=0; i--) {
            while(indices.peek()!=null && numArray[indices.peek()] > numArray[i]) {
                prev[indices.peek()] = i;
                indices.pop(); 
            }
            indices.push(i); 
        }
        
        int[] result = new int[n]; 
        int windowSize = 0; 
        //Here, windowSize stores the window size (length) for which the 
        //concerned element is minimum.
        for(int i=0; i<n; i++) {
            windowSize = next[i] - prev[i] - 1; 
            
            //Since we need the maximum of minimum values for a given windowSize.
            //Since windowSize is from 1 to n, but indices are from 0 to n-1,
            //we take result[windowSize - 1].
            //numArray[i] could be a potential value for current windowSize
            result[windowSize-1] = Math.max(result[windowSize-1], numArray[i]); 
        }
        
        //To fill all the remaining entries of result[]. The observation used 
        //to obtain these values is that result[i] is always >= result[i+1].
        for(int i=n-2; i>=0; i--) 
            result[i] = Math.max(result[i], result[i+1]); 
        
        return result;
    }
    
    public static void main(String[] args) throws IOException {
        InputStreamReader read = new InputStreamReader(System.in);
	    BufferedReader buf = new BufferedReader(read); 

        //Taking input from user
        System.out.println("Enter length of array of integers: ");
	    int len = Integer.parseInt(buf.readLine());
        System.out.println("Enter array of integers: ");
	    StringTokenizer st = new StringTokenizer(buf.readLine());
	    int numArray[] = new int[len];
	    for(int i=0; i<len; i++) {
	        numArray[i] = Integer.parseInt(st.nextToken()); 
	    }

        int arr[] = findMaximumOfMinimums(numArray, len); 
        //Printing the obtained array values as a String
        System.out.println("String of maximum of the minimums of every window" +
                            " size from 1 to " + len + ":");
        String result = "";
        for(int i=0; i<len; i++)
            result += (arr[i] + " "); 
        System.out.println(result); 
    }

}

/*
    Time complexity: O(N)
    Space complexity: O(N) (Space used for stack and auxiliary arrays)

    TEST CASES

    INPUT
    Enter length of array of integers: 
    10
    Enter array of integers: 
    4 7 3 5 0 8 4 10 10 0
    OUTPUT
    String of maximum of the minimums of every window size from 1 to 10:
    10 10 4 4 0 0 0 0 0 0

    INPUT
    Enter length of array of integers: 
    5
    Enter array of integers: 
    3 3 4 2 4
    OUTPUT
    String of maximum of the minimums of every window size from 1 to 10:
    4 3 3 2 2 

 */


<|start_filename|>Julia/dp/length_longest_common_substring.jl<|end_filename|>
"""Length of Longest Common Substring problem in Julia

Given two strings, we have to find the longest common substring in Julia

The problem can be solved using Dynamic Programming
"""

function lengthoflongestcommonsubstring(S1, S2)
    # Build a 2D matrix in Bottom-Up manner. Every element
    # dp[i][j] contains the length of the longest common substring
    # of S1[0 .. i] and S2[0 .. j].
    n = length(S1)
    m = length(S2)
    ans = 0
    # Fill every element of the 2D matrix with 0 as value
    dp = zeros(Int, n+1, m+1)

    for i in 1:(n+1)
        for j in 1:(m+1)

            # length of LCS when one of the string is empty is zero
            if i == 1 || j == 1
                dp[i,j] = 0

            # If the elements of both the strings match, then
            # the value of LCS increments by one.
            # Also Check if the value of lcs has reached the max till now.
            elseif S1[i-1] == S2[j-1]
                dp[i,j] = dp[(i - 1),(j - 1)] + 1
                ans = max(ans, dp[i,j])
            else
                dp[i,j] = 0
            end
        end
    end
    return ans
end


print("Enter the first string: ")
s1 = readline()
print("Enter the second string: ")
s2 = readline()
res = lengthoflongestcommonsubstring(s1, s2)
print("The length of the longest common substring is ")
print(res)


# Time Complexity: O(n * m), where n, m are the size of the given strings
# Space Complexity: O(n * m)

# SAMPLE INPUT AND OUTPUT

# Enter the first string: runner
# Enter the second string: run
# The length of the longest common substring is 3


<|start_filename|>Java/sort/MergeSortRecursion.java<|end_filename|>
//merge sort using divide and conquer and recursion
import java.util.Scanner;
class MergeSortRecursion 
{
    
    public static void sort(int arr[], int start, int end)
    {
        if(start==end) //base case
        return;
        else
             {
            // Find the mid of the array
           int mid = start + ((end - start) / 2);
 
            // Sort first and second halves
            sort(arr, start, mid);
            sort(arr, mid + 1, end);
            merge(arr,start, mid, end); // Merge the sorted halves
        }
    }
    public static void merge(int arr[], int start, int mid, int end)
    {
        // Find sizes of two subarrays to be merged
        int nL = mid - start + 1; //left size
        int nR = end - mid;     //right size
 
        /* Create temporary arrays */
        int L[] = new int[nL];  //left array
        int R[] = new int[nR]; //right array
 
        /*Copy data to temporary arrays*/
        for (int i = 0; i < nL; ++i)
            L[i] = arr[start + i];
        for (int j = 0; j < nR; ++j)
            R[j] = arr[mid + 1 + j];
        int i = 0, j = 0;
 
        // Initial index of merged subarry array
        int k = start;
        while (i < nL && j < nR) {
            if (L[i] <= R[j]) {
                arr[k] = L[i];
                i++;
            }
            else {
                arr[k] = R[j];
                j++;
            }
            k++;
        }
 
        /* Copy remaining elements of L[] */
        while (i < nL) {
            arr[k] = L[i];
            i++;
            k++;
        }
 
        /* Copy remaining elements of R[] */
        while (j < nR) {
            arr[k] = R[j];
            j++;
            k++;
        }
    }
    public static void printArray(int arr[])
    {
        int n = arr.length;
        for (int i = 0; i < n; ++i)
            System.out.print(arr[i] + " ");
        System.out.println();
    }
    public static void main(String args[])
    {
       Scanner sc=new Scanner(System.in);
       System.out.print("Enter size of array"+"\n"+" n = ");
       int n=sc.nextInt();
        int arr[] = new int[n];
        for(int i=0;i<n;i++)
        arr[i]=sc.nextInt();
 
        System.out.println("Inputted array : ");
        printArray(arr);
        sort(arr, 0, n-1);
 
        System.out.println("\nMergeSorted array : ");
        printArray(arr);
    }
}

/* Sample Input And Output : 
 * Enter size of array
 n = 5
33 47 19 2 101
Inputted array : 
33 47 19 2 101 

MergeSorted array : 
2 19 33 47 101 

Time Complexity : 
Worst case: O(n*log n)
Best Case: O(n*log n)

Space Complexity : O(n)
*/
 


<|start_filename|>C-Plus-Plus/ds/Priority_Queue_using_LinkedList.cpp<|end_filename|>
/* 
AIM :: To implement Priority Queue (PQ) using Linked List (LL).

            WHAT IS PRIORITY QUEUE ?
A priority queue is an abstract data type that behaves similarly to the normal queue except that each element has some priority, 
i.e., the element with the highest priority would come first in a priority queue. 
The priority of the elements in a priority queue will determine the order in which elements are removed from the priority queue.

*/

#include <iostream>
#include <stdlib.h> // for using malloc (DMA)
using namespace std;

struct node
{
    int data;          // to store data
    int prior;         // to store priority of data
    struct node *next; // to store next node's pointer
} * front;             // front pointer of PQ
typedef struct node PQ;

// prototypes
void enq();     // for insertion
void deq();     // for deletion
void display(); // for display

int main()
{
    int choice; //for storing the choice of user after viewing the options
    cout << "\n\t\tPQ IMPLEMENTATION" << endl;

    while (true)
    {
        // give the menu to user
        cout << "\n1. ENQ\n2. DEQ\n3. DISPLAY\n4. EXIT" << endl;
        cout << "Enter your choice :: ";
        cin >> choice;

        switch (choice)
        {
        case 1:
            enq();
            break;

        case 2:
            deq();
            break;

        case 3:
            display();
            break;

        case 4:
            cout << "Exiting...";
            exit(0);
            break;

        default:
            cout << "Invalid choice :(" << endl;
        }
    }
    return 0;
}

void enq()
{
    //creating new node
    PQ *new_node = (PQ *)malloc(sizeof(PQ));
    new_node->next = NULL;

    //ask user to enter the data and priority of that data
    cout << "Enter the data :: ";
    cin >> new_node->data; // storing data into data field of newly created node

    cout << "Enter priority of " << new_node->data << " :: ";
    cin >> new_node->prior; // storing priority of that data

    // if linked list is empty or priority is less than first position
    if (front == NULL || new_node->prior <= front->prior)
    { // then insert at begin
        new_node->next = front;
        front = new_node;
    }
    else
    {
        PQ *temp = front;
        //traverse till the appropriate position
        while (temp->next != NULL && temp->next->prior <= new_node->prior)
            temp = temp->next;

        //inseting node at it's appropriate position
        new_node->next = temp->next;
        temp->next = new_node;
    }
    display(); // display the result
}

void deq()
{
    if (front == NULL) // means queue is empty
        cout << "QUEUE UNDERFLOW" << endl;
    else
    {
        PQ *temp = front;

        //every time deleting the first
        front = front->next;
        temp->next = NULL;
        free(temp);

        display();
    }
}

void display()
{
    if (front == NULL) // means queue is empty
        cout << "QUEUE UNDERFLOW" << endl;
    else
    {
        //temp_data to store and display the data of queue while traversing
        PQ *temp_data = front;

        //temp_priority to store and display the priority of data that are being displayed
        PQ *temp_priority = front;

        // displaying data in queue
        cout << "\nDATA     :: ";
        while (temp_data != NULL)
        {
            cout << temp_data->data << "    ";
            temp_data = temp_data->next;
        }

        // displaying priority of all the data in the queue
        cout << "\nPRIORITY :: ";
        while (temp_priority != NULL)
        {
            cout << temp_priority->prior << "     ";
            temp_priority = temp_priority->next;
        }
    }
}

/*
TEST CASE

                PQ IMPLEMENTATION

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 1
Enter the data :: 30
Enter priority of 30 :: 2

DATA     :: 30
PRIORITY :: 2

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 1
Enter the data :: 10
Enter priority of 10 :: 1

DATA     :: 10    30
PRIORITY :: 1     2

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 2

DATA     :: 30
PRIORITY :: 2

1. ENQ
2. DEQ
3. DISPLAY
4. EXIT
Enter your choice :: 4

Exiting...


TIME COMPLEXITY
    INSERTION :: O(n)
    DELETION :: O(n)
    DISPLAY  :: O(n)
*/


<|start_filename|>JavaScript/math/catalan_number.js<|end_filename|>
/*
Catalan numbers is a number sequence, which is found useful in a number of
combinatorial problems, often involving recursively-defined objects.
*/

var n = prompt("Enter the number:");

var c = [];

function catalan(n) {
    if (n == 0) return 1;
    if (!c[n]) {
        var s = 0;
        for (var i = 0; i < n; i++)
            s += catalan(i) * catalan(n - i - 1);
        c[n] = s;
    }
    return c[n];
}
document.write("Nth Catalan Number are:")
document.write("<br>");
for (var i = 0; i <= n; i++) {
    document.write(catalan(i));
    document.write("<br>");
}

/*
Input:
Enter the number:
15
Output:
Nth Catalan Number are:
1
1
2
5
14
42
132
429
1430
4862
16796
58786
208012
742900
2674440
9694845

Time Complexity: O(2^n)
Space Complexity: O(1)
*/

<|start_filename|>C-Plus-Plus/other/palindrome_linked_list.cpp<|end_filename|>
//A program to check if a given singly linked list is a palindrome or not in linear time and no extra space
//The idea is to reverse the second half of the linked list, and then compare the two halfs for palindrome checking

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

class ListNode {
public:
    int val;
    ListNode* next;
};

//return if the linked list is a palindrome or not
bool is_palindrome(ListNode* head)
{

    ListNode* A = head;
    int cnt = 0;

    //Count the number of nodes in the linked list
    while (A != NULL) {
        cnt++;
        A = A->next;
    }

    //If there is only one node, then its clearly a palindrome
    if (cnt == 1) {
        return 1;
    }

    //Traverse upto the node(half_end) after which we need to reverse the linked list
    int half = (cnt + 1) / 2;
    half--;

    ListNode* half_end = head;
    while (half > 0) {
        half_end = half_end->next;
        half--;
    }

    //Take 2 pointers to reverse the linked list after node half_end
    ListNode* p1 = half_end;
    ListNode* p2 = half_end->next;

    ListNode* temp = p2->next;
    p2->next = NULL;
    p1 = p2;
    p2 = temp;

    while (p2) {
        temp = p2->next;
        p2->next = p1;
        p1 = p2;
        p2 = temp;
    }

    //Join the head of the reversed linked list to the current endthat is, half_end
    half_end->next = p1;

    //Take 2 pointers and compare the 2 parts
    p2 = head;
    p1 = half_end->next;

    while (p1) {
        //If any one value is different, return 0
        if ((p2->val) != (p1->val)) {
            return 0;
        }
        else {
            p2 = p2->next;
            p1 = p1->next;
        }
    }

    return 1;
}

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

    int node_val;
    cin >> node_val;

    ListNode* head = new ListNode();
    head->val = node_val;
    head->next = NULL;

    ListNode* temp = head;

    for (int i = 1; i < nodes; i++) {
        cin >> node_val;
        ListNode* new_node = new ListNode();
        new_node->val = node_val;
        new_node->next = NULL;
        temp->next = new_node;
    }

    if (is_palindrome(head)) {
        cout << "Yes, it is a palindrome" << endl;
    }
    else {
        cout << "No, it is not a palindrome" << endl;
    }
}

/*Test Case 1:
  n= 6
  input= 2->4->6->6->4->2
  output= Yes, it is a palindrome

  Test Case 2:
  n= 5
  input= 1->2->3->5->9
  output= No, it is not a palindrome

  Time Complexity: O(n)
  (Since, we traverse the linked list only thrice, once for counting the nodes,
   then to reverse the second half and then for checking if it is a palindrome)
  Space Complexity: O(1) (No extra space is used)*/


<|start_filename|>Java/search/Bilinear_Search.java<|end_filename|>
import java.util.Scanner;
public class Bilinear_Search
{
    static int findElement(int arr[], int size, int search){
        /* l for left index; r for right index
        found==-1 means element not found
        found other than -1 will be location of the element */
        int l=0, r=size-1;
	    int found=-1;
	    while(l<=r){
	        if(arr[l]==search){
	            found=l;
	            break;
	        }else if(arr[r]==search){
	            found=r;
	            break;
	        }
	        else{
	            l++;
	            r--;
	        }
	    }
	    return found;
    }
	public static void main(String[] args) {
	    Scanner sc = new Scanner(System.in);
	    System.out.print("Enter number of elements : ");
	    int n = sc.nextInt();
	    int[] arr = new int[n];
	    System.out.print("Enter the elements: ");
	    for(int i=0; i<n; i++){
	        arr[i] = sc.nextInt();
	    }
	    System.out.print("Enter element to search: ");
	    int search = sc.nextInt();
	    int found = findElement(arr, n, search);
	    if(found!=-1){
	        // found+1 because index starts from 0.
	        System.out.println("element found at location : "+(found+1));
	    }else{
	        System.out.println("element not found");
	    }
	}
}
/*
Sample input and output
Enter number of elements : 7
Enter the elements: 4 3 6 8 2 1 9
Enter element to search: 2
element found at location : 5


time complexity: O(n)
space complexity: O(n)
*/


<|start_filename|>C-Plus-Plus/other/knapsackfraction.cpp<|end_filename|>
/*
Given weights and values of n items, we need to put these items in a knapsack of capacity W to get the maximum total value in the knapsack.
Here We are solving fractional knapsack in which we can take a fraction of item too.
*/

#include <iostream>
using namespace std;
// A function to sort the arrays according to profit/weight
void sort_arr(float ratio[], float profit[], float weight[], int n) 
{
    float temp;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n - i - 1; j++)
            if (ratio[j] < ratio[j + 1])
            {
                temp = ratio[j];
                ratio[j] = ratio[j + 1];
                ratio[j + 1] = temp;

                temp = weight[j];
                weight[j] = weight[j + 1];
                weight[j + 1] = temp;

                temp = profit[j];
                profit[j] = profit[j + 1];
                profit[j + 1] = temp;
            }
}

//function to calculate max value in knapsack.
int knapsack_fraction(float weight[], float ratio[], float profit[], int n, int capacity) 
{
    int final = 0;
    int i;
    //iterating over all items
    for (i = 0; i < n; i++) 
    {
        //checking if current weight is greater tahn break i.e this weight can't be put into knapsack.
        if (weight[i] > capacity) 
            break;
        //else add profir to final varibale i.e max profit and update capacity accordingly
        else 
        {
            final = final + profit[i];
            capacity = capacity - weight[i];
        }
    }
    //for fraction amount of item
    if (i < n) 
        final = final + (ratio[i] * capacity);
    return final;
}

int main()
{
    float weight[20], profit[20], ratio[20], final, temp, capacity, amount;
    int n, i, j;
    cout << "Enter the number of items :";
    cin >> n;
    //accepting the profit and weight values for given value of n.
    for (i = 0; i < n; i++) 
    {
        cout << "Enter Profit and weight for item" << i + 1;
        cin >> profit[i] >> weight[i];
    }
    cout << "Enter the capacity of knapsack :" << endl;
    cin >> capacity;
    //making the new array and storing ratio (profit/weight)
    for (i = 0; i < n; i++)
        ratio[i] = profit[i] / weight[i];
    //first sort the array acc to Profit/weight
    sort_arr(ratio, profit, weight, n); 
    //call the function to calculate max profit.
    int ans = knapsack_fraction(weight, ratio, profit, n, capacity); 
    cout << "the maximum profit is : " << ans << endl;
    return 0;
}

/*
OUTPUT:-
Enter the number of items :5
Enter Profit and weight for item15 2
Enter Profit and weight for item23 1
Enter Profit and weight for item36 3
Enter Profit and weight for item48 1
Enter Profit and weight for item510 6
Enter the capacity of knapsack :
the maximum profit is : 32
*/


<|start_filename|>C/ds/Queueimplementation.c<|end_filename|>
// Program to Implement a Queue
#include <stdio.h>
#include <stdlib.h>
#define MAX 50
void insert();
void delete();
void display();
int queue_array[MAX];
int rear = -1;
int front = -1;
int main()
{
	int choice;
	while (1)
	{
		printf("1.Insert element to queue \n");
		printf("2.Delete element from queue \n");
		printf("3.Display all elements of queue \n");
		printf("4.Quit \n");
		printf("Enter your choice : ");
		scanf("%d", &choice);
		switch (choice)
		{
			case 1:
				insert();
				break;
			case 2:
				delete();
				break;
			case 3:
				display();
				break;
			case 4:
				exit(1);
			default:
				printf("Wrong choice \n");
		}
	}
}
// Inserting an element
void insert()
{
	int item;
	if (rear == MAX - 1)
		printf("Queue Overflow \n");
	else
	{
		if (front == -1)
			front = 0;
		printf("Inset the element in queue : ");
		scanf("%d", &item);
		rear = rear + 1;
		queue_array[rear] = item;
	}
}
// Deleting an element
void delete()
{
	if (front == -1 || front > rear)
	{
		printf("Queue Underflow \n");
		return;
	}
	else
	{
		printf("Element deleted from queue is : %d\n", queue_array[front]);
		front = front + 1;
	}
}
// Displaying the elements in the queue
void display()
{
	int i;
	if (front == -1)
		printf("Queue is empty \n");
	else
	{
		printf("Queue is : \n");
		for (i = front; i <= rear; i++)
			printf("%d ", queue_array[i]);
		printf("\n");
	}
}

/*
Sample Output
1.Insert element to queue 
2.Delete element from queue 
3.Display all elements of queue 
4.Quit 
Enter your choice : 1
Insert the element in queue : 2
1.Insert element to queue 
2.Delete element from queue 
3.Display all elements of queue 
4.Quit 
Enter your choice : 1
Insert the element in queue : 1
.Insert element to queue 
2.Delete element from queue 
3.Display all elements of queue 
4.Quit 
Enter your choice : 3
Queue is : 
2 1 
1.Insert element to queue 
2.Delete element from queue 
3.Display all elements of queue 
4.Quit 
Enter your choice : 4

Complexities
Time Complexity:O(n)
Space Complexity:O(n)
*/



<|start_filename|>C-Plus-Plus/cp/rotate2darray.cpp<|end_filename|>
/*
This code is for Rotating an NxN 2D array in 90 degrees anticlockwise direction.
*/

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

//function to rotate the user  matrix anticlockwise
void rotatematrix(int a[][10], int n)
{
  //reversing each row
  for (int row = 0; row < n; row++)
  {
    int start_col = 0;
    int end_col = n - 1;
    while (start_col < end_col)
    {
      swap(a[row][start_col], a[row][end_col]);
      start_col++;
      end_col--;
    }
  }
  //taking transpose
  for (int i = 0; i < n; i++)
  {
    for (int j = 0; j < n; j++)
    {
      if (i < j)
      {
        swap(a[i][j], a[j][i]);
      }
    }
  }
}
//function for displaying the rotated 2darray/matrix
void display(int a[10][10], int n)
{
  for (int i = 0; i < n; i++)
  {
    for (int j = 0; j < n; j++)
    {
      cout << a[i][j]<<" ";
    }
    cout<<endl;
  }
}

//driver function
int main()
{
  int a[10][10];
  //'n' here is declared for the order of your matrix
  int n;
  //taking input for the order of matrix
  cout << "enter the order for your square matrix:" << endl;
  cin >> n;

  //taking input for the matrix data
  cout << "please enter the elements of your matrix to be Rotated:" << endl;
  for (int i = 0; i < n; i++)
  {
    for (int j = 0; j < n; j++)
    {
      cin >> a[i][j];
    }
  }

  cout << "the matrix to be rotated:" << endl;
  //calling the function for displaying the initial matrix
  display(a, n);
  //calling the function for rotating the matrix
  rotatematrix(a, n);
  cout << "the matrix after rotation:" << endl;
  //calling the function for displaying the rotated matrix
  display(a, n);
}
/*EXECUTION:-

SAMPLE OUTPUT-1:
enter the order for your square matrix:
2
please enter the elements of your matrix to be Rotated:
1
2
3
4
the matrix to be rotated:
1 2
3 4
the matrix after rotation:
2 4
1 3

SAMPLE OUTPUT-2:
enter the order for your square matrix:
3
please enter the elements of your matrix to be Rotated:
2
3
4
5
6
7
8
9
1
the matrix to be rotated:
2 3 4
5 6 7
8 9 1
the matrix after rotation:
4 7 1
3 6 9
2 5 8

The time complexity of the code is O(N2) for an N × N matrix 
and it doesn’t require any extra space therefore the space complexity is O(1).
*/


<|start_filename|>C-Plus-Plus/math/krishnamurthy_number.cpp<|end_filename|>
/*
    If the factorial of individual digits of a number when summed up yields the number itself then the number is called Krishnamurthy 
    Number. 
    Example : 
    Consider the number 145
    Summing of factorials of the individual digits we get = 1! + 4! + 5! = 1 + 24 + 120 =145.
    Hence 145 is not a Krishnamurthy number.
*/

//CPP Program to find whether a number is a Krishnamurthy number

#include<iostream>

//Function to calculate the factorial of the individual digits

int Factorial ( int n )
{
    if ( n == 1 || n == 0 )
    {
        return 1;
    }
    return n * Factorial( n - 1 );
}

int Krishnamurthy_No ( int num )
{
    int digit, sum = 0 ,copy = num;

    //Running a loop till we have extracted all the digits from the copy of the given number
    
    while ( copy > 0 ) 
    {
        digit = copy % 10;
        sum = sum + Factorial ( digit );
        copy = copy / 10;
    }
    return sum;
}

int main () 
{
    int number, digit, sum = 0;
    std::cout << "Enter a natural number " << std::endl;
    std::cin >> number;
    int answer = Krishnamurthy_No ( number ); 

    //Comparing if calculated sum adds up to the number

    if ( answer == number)
    {
        std:: cout << number <<" is a krishnamurthy number. ";
    }
    else
    {
        std:: cout << number <<" is not a krishnamurthy number. ";
    }
}

/*
    Test Case 1 :-
        INPUT : 37 
        OUTPUT : 37 is not a krishnamurthy number.
    Test Case 2 :-
        INPUT : 145
        OUTPUT: 145 is a krishnamurthy number.
        
*/


<|start_filename|>C/ds/middle_element_of_linkedlist.c<|end_filename|>
/*
A program written in C language to detect the middle element of a linkedlist. 
The approach used is the Two-pointer Approach. 
In this approach, we use 2 pointers, assign both to the head. We move the first pointer by one mode and the other pointer by two nodes, such that when the second pointer reaches the end, the first pointer reaches the middle. Hence, we are able to detect the middle element of the linkedlist.
*/
#include<stdio.h>  
#include<stdlib.h>  
  
/*Defining a Node*/
struct Node  
{  
    int val;  
    struct Node* next;  
};  
/*Fuction to dtetct the middle element*/
void detectMiddle(struct Node *head)  
{  
    struct Node *first_ptr = head;  
    struct Node *second_ptr = head;  
  
    if (head!=NULL)  
    {  
        while (second_ptr != NULL && second_ptr->next != NULL)  
        {  
            second_ptr = second_ptr->next->next;  
            first_ptr = first_ptr->next;  
        }  
        printf("The middle element is %d\n", first_ptr->val);  
    }  
}  
/*A Function to push the element at the end of the linkedlist*/  
void push(struct Node** head_ref, int new_data)  
{  
    
    struct Node* new_node =  
        (struct Node*) malloc(sizeof(struct Node));  
  
    
    new_node->val = new_data;  
  
   
    new_node->next = (*head_ref);  
  
    
    (*head_ref) = new_node;  
}  
/* Driver function*/
int main()  
{  
    struct Node* head = NULL;  
    int i;
    printf("Enter the number of elements in the linkedlist "); 
    scanf("%d",&i); 
    for (int p=i; p>0; p--)  
    {  
        int c;
        printf("\nEnter the element ");
        scanf("%d",&c);
        push(&head, c);  
    }  
     detectMiddle(head); 
    return 0;  
}  

/*
Output: 
Enter the number of elements 5
Enter the element 2
Enter the element 3
Enter the element 1
Enter the element 6
Enter the element 7
The middle element is 1
*/

<|start_filename|>Java/search/Exponential_search.java<|end_filename|>
import java.util.*; 

class Exponential_Search 
{ 
    // Returns position of first occurrence of x in array 
    static int expoSearch(int input[], int n, int x) 
    { 
        // If x is present at firt location itself 
	if (input[0] == x) 
	    return 0; 
	
	// Find range for binary search by repeated doubling 
	int i = 1; 
	while (i < n && input[i] <= x) 
	    i = i*2; 
	
	// Call binary search for the found range. 
	return Arrays.binSearch(input, i/2, Math.min(i, n), x); 
    } 
	
    // Driver code 
    public static void main(String args[]) 
    { 
	
	int n;
	Scanner s = new Scanner(System.in);
	n = s.nextInt();
        int arr[] = new int[n];
	for (int i = 0; i < n; i++)
        {
            a[i] = s.nextInt();
        }
	int x = s.nextInt();
	int result = expoSearch(arr, arr.length, x); 
		
	System.out.println((result < 0) ? "Element is not present in array" : "index " + result); 
     } 
} 

/* 
INPUT:
n = 5
arr[] = {4, 5, 15, 80, 90}
x = 90
OUPUT:
index 4
*/



<|start_filename|>C-Plus-Plus/cp/recursion_string_permutation.cpp<|end_filename|>
// Here I use recursion to find all permutation of a string.
// This method is useful for  non repeated character containing string and small length's strings because its time complaxity is in terms of n! .  

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

void recursion (string s , int left_index , int right_index){
    if( left_index == right_index ) {
       cout<<s<<"  ";
    }
    // here my approach is to fix a character and find all permutation of next all character 
    // and fixing of characters is done by swaping
    for(int i = left_index ; i <= right_index ; i++) {
        swap(s[left_index] , s[i]) ;
        recursion(s , left_index + 1 , right_index) ; 
        swap(s[left_index] , s[i]) ;  
    }
}

int main() {
    string S ;
    cin>>S;
    recursion(S , 0 , S.size() - 1 ) ;
}

/*  Sample input : ab 
    sample output : ab , ba

    Test cases
    Input_1:xyz
    Output_1 : xyz  xzy  yxz  yzx  zyx  zxy

    Input_2 : abcde
    Output_2 :abcde  abced  abdce  abdec  abedc  abecd  acbde  acbed  acdbe  acdeb  acedb  
              acebd  adcbe  adceb  adbce  adbec  adebc  adecb  aecdb  aecbd  aedcb  aedbc  
              aebdc  aebcd  bacde  baced  badce  badec  baedc  baecd  bcade  bcaed  bcdae  
              bcdea  bceda  bcead  bdcae  bdcea  bdace  bdaec  bdeac  bdeca  becda  becad  
              bedca  bedac  beadc  beacd  cbade  cbaed  cbdae  cbdea  cbeda  cbead  cabde  
              cabed  cadbe  cadeb  caedb  caebd  cdabe  cdaeb  cdbae  cdbea  cdeba  cdeab  
              ceadb  ceabd  cedab  cedba  cebda  cebad  dbcae  dbcea  dbace  dbaec  dbeac  
              dbeca  dcbae  dcbea  dcabe  dcaeb  dceab  dceba  dacbe  daceb  dabce  dabec  
              daebc  daecb  decab  decba  deacb  deabc  debac  debca  ebcda  ebcad  ebdca  
              ebdac  ebadc  ebacd  ecbda  ecbad  ecdba  ecdab  ecadb  ecabd  edcba  edcab  
              edbca  edbac  edabc  edacb  eacdb  eacbd  eadcb  eadbc  eabdc  eabcd  */

/* Time complaxity : O(n * n!) where n is length of string
    Space complaxity : o(n * n!) */

<|start_filename|>C-Plus-Plus/Bit--Manipulation/no_of_bits_to_be_flipped_to_inter_convert_two_numbers.cpp<|end_filename|>
// C++ program to find the number of bits to be flipped to convert one number to another
#include <bits/stdc++.h>
using namespace std;

/*
Inorder to compare the individual bits of given the numbers, we can compute the number of
set bits in thier XOR, as we know that XOR operation yields set bits, only when two same
bits are XORed.
*/
int get_num_flips(int n1, int n2) {
    int count = 0, n = n1 ^ n2;

    // Loop till 'n' becomes zero
    while (n) {
        // If the lsb is set, increase the count by 1
        if (n & 1)
            count++;
        // Shift the bits to right by 1.
        n = n >> 1;
    }

    return count;
}

int main() {
    int n1, n2;
    cout << "\nEnter the two numbers: ";
    cin >> n1 >> n2;

    cout << "Number of flips required to inter-convert the given numbers is ";
    cout << get_num_flips(n1, n2);
    return 0;
}

/*

Time Complexity: O(log(n)), where n is the greater of the input number
Space Complexity: O(1)

SAMPLE INPUT AND OUTPUT

Enter the two numbers: 12 24
Number of flips required to inter-convert the given numbers is 2

*/


<|start_filename|>C/dp/tiling_problem.c<|end_filename|>
/*
PROBLEM STATEMENT:
Given a floor of size 2Xn and tiles of size 2X1. We've to find the number number of ways in which the floor can be tiled using tiles of size 2X1. 
A tile can be either placed horizontally or vertically.
*/

#include<stdio.h>

int NoOfWays(int n){
	int tiles[n+1];
	for(int i = 0; i <= n; i++){
		//Base cases
		if(i == 0)
			tiles[i] = 0;
		else if(i == 1)
			tiles[i] = 1;
		//Adding the solutions that we get by placing first tile vertically and by placing first tile horizontally 
		else
			tiles[i] = tiles[i-1] + tiles[i-2];
	}
	//returning the ways in which floor of size 2Xn can be tiled
	return tiles[n];
}

//Driver function
int main(){
	int n;
	printf("Enter value of n: ");
	scanf("%d",&n);
	printf("Total no. of ways in which floor of size 2X%d can be tiled are: %d", n, NoOfWays(n));
	return 0;
}

/*
TEST CASE:
Input: 4
Output: 3

TIME COMPLEXITY: O(n), due to the single for loop used
SPACE COMPLEXITY: O(n), due to the additional dp array created
where 'n' denotes the breadth of the floor as entered by the user
*/


<|start_filename|>Java/other/RainWaterHarvesting.java<|end_filename|>
import java.util.Scanner;

class RainWaterHarvesting {

    public static int saveWater(int[] arr, int size) {

        int result = 0;

        // traverse the array from second to second last element
        for (int i = 1; i < size - 1; i++) {

            // Find maximum element on its left
            int left = arr[i];
            for (int j = 0; j < i; j++) {
                left = Math.max(left, arr[j]);
            }

            // Find maximum element on its right
            int right = arr[i];
            for (int j = i + 1; j < size; j++) {
                right = Math.max(right, arr[j]);
            }

            // Update maximum water value
            result += Math.min(left, right) - arr[i];
        }
        return result;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter array size:");
        int size = scanner.nextInt();
        int[] arr = new int[size];
        System.out.println("Enter array elements:");
        for (int i = 0; i < size; i++) {
            arr[i] = scanner.nextInt();
        }
        scanner.close();

        System.out.println("Maximum amount of water that can be saved is:" + saveWater(arr, size));
    }
}

/*
* Sample input/output:
* Enter array size:
* 10
* Enter array elements:
* 0 2 1 3 0 1 2 1 2 1
* Maximum amount of water that can be saved is:5
*
* Time complexity: O(n^2)
* space complexity: O(1)
*/


<|start_filename|>C-Plus-Plus/ds/iterative_inorder.cpp<|end_filename|>
/*
The traversal operation is a frequently used operation on a binary tree. This operation is used to visit each node in the tree exactly once
A full traversal on a binary tree gives a linear ordering of data in the tree .  This is the iterative inorder tree traversal algorithms
*/
#include <bits/stdc++.h>

using namespace std;
//structure for the binary tree node
class TreeNode
{
public:
    char data;
    TreeNode *left;
    TreeNode *right;
};
//structure for stack which is used for the iterative traversal algorithms
//stack is implemented using linked list
class Stack
{
public:
    TreeNode *node;
    Stack *next;
};
//push operation for the stack
void push(Stack **s, TreeNode *node)
{
    Stack *New = new Stack();
    New->node = node;
    New->next = (*s);
    (*s) = New;
}
// pop operation for the stack
TreeNode *pop(Stack **s)
{
    if ((*s) != NULL)
    {
        TreeNode *ptr = (*s)->node;
        (*s) = (*s)->next;
        return ptr;
    }
}
//checks whether the stack is empty or not
int isEmpty(Stack **s)
{
    if ((*s) == NULL)
    {
        return 1;
    }
    return 0;
}
//iterative inorder traversal
void inorder(TreeNode *root)
{
    TreeNode *ptr = root;
    Stack *s = NULL;
    while (!isEmpty(&s) || ptr != NULL)
    {
        if (ptr != NULL)
        {
            push(&s, ptr);
            ptr = ptr->left;
        }
        else
        {
            ptr = pop(&s);
            cout << ptr->data << " ";
            ptr = ptr->right;
        }
    }
}
//search function returns the pointer to the node which contains the value key , it is used in the insertion operation
TreeNode *search(TreeNode *root, int k)
{
    if (root == NULL)
    {
        return NULL;
    }
    else if (root->data == k)
    {
        return root;
    }
    else
    {
        TreeNode *x = search(root->left, k);
        if (x)
            return x; //if we find in left subtree, return result
        return search(root->right, k);
    }
}
// Insertion operation of the binary tree
void insert(TreeNode *root, char key, char c)
{
    TreeNode *ptr = search(root, key);
    if (ptr == NULL)
    {
        cout << "Search Unsuccessfull No Insertion \n";
        return;
    }
    char option;
    if (ptr->left == NULL || ptr->right == NULL)
    {
        cout << "Enter Where to insert left or right (L/R)\n";
        cin >> option;
        if (option == 'L' || option == 'l')
        {
            if (ptr->left == NULL)
            {
                TreeNode *New = new TreeNode();
                ptr->left = New;
                New->data = c;
                cout << "Inserting " << c << " as the left" << endl;
                New->left = NULL;
                New->right = NULL;
            }
            else
            {
                cout << "Insertion not Possible as Left child " << endl;
            }
        }
        else
        {
            if (ptr->right == NULL)
            {
                TreeNode *New = new TreeNode();
                ptr->right = New;
                New->data = c;
                cout << "Inserting " << c << " as the right" << endl;
                New->left = NULL;
                New->right = NULL;
            }
            else
            {
                cout << "Insertion not possible as the right child" << endl;
            }
        }
    }
    else
    {
        cout << "The Node Already has child" << endl;
    }
}

int main()
{
    cout << "Enter the value for root node" << endl;
    TreeNode *root = new TreeNode();
    char c;
    scanf("%c", &c);
    root->data = c;
    root->right = NULL;
    root->left = NULL;
    char choice = 'y';
    char data;
    do
    {
        cout << "Enter the Node to be Inserted" << endl;
        cin >> data;
        cout << "Enter the Parent node of the node to be inserted" << endl;
        cin >> c;
        insert(root, c, data);
        cout << "Do you want to continue (y/n)" << endl;
        cin >> choice;
    } while (choice == 'y' || choice == 'Y');
    cout << "Inorder Traversal of the Tree" << endl;
    inorder(root);
    return 0;
}
/*
Sample I/O:
Enter the value for root node
A
Enter the Node to be Inserted
B
Enter the Parent node of the node to be inserted
A
Enter Where to insert left or right (L/R)
L
Inserting B as the left
Do you want to continue (y/n)
y
Enter the Node to be Inserted
C
Enter the Parent node of the node to be inserted
A
Enter Where to insert left or right (L/R)
R
Inserting C as the right
Do you want to continue (y/n)
n
Inorder Traversal of the Tree
B A C
Time Complexity = O( n )
Space Complexity = O( n )
*/


<|start_filename|>Java/sort/InsertionSort.java<|end_filename|>
/* Insertion Sort using Iteration */

public class InsertionSort{
 
     public static void insertionSort(int[] ar){
       
    //Starting index from index 1 to create sorted array at left side of the array

             for(int i = 1; i < ar.length; i++){
                  int j = i-1,k = i;                // Assigning j = i-1 and iterating to 0 in sorted part of the array
                 while(j >= 0 && ar[k] < ar[j]){   // checking if element at index i is smaller than elements in the sorted array and then swap them
                     swap(ar,k,j);                 // swapping elements in the same array by passing ar and indexes i and j
                     j--;
                     k--;
                }
             }
          }

     public static void main(String args[]){
         int[] ar = {19,8,7,6,5,4,3,2,1};
         insertionSort(ar);

         for(int i = 0; i < ar.length; i++){
             System.out.print(ar[i]+" ");
         }
     }
    
     public static void swap(int[] ar, int i , int j){   // swapping elements in the array 
         int temp = ar[i];
         ar[i] = ar[j];
         ar[j] = temp;
     }

}

/* It is an interesting algorithm so I challenge you to apply Insertion Sort using recursion */
/* Good Luck */


<|start_filename|>C/graphs/BFS.c<|end_filename|>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

#define size 20
#define TRUE 1
#define FALSE 0

int g[size][size];
int visit[size];
int Q[size];
int n;

void main()
{
    int v1, v2;
    char ans = 'y';
    void create(), bfs();
    create();
    printf("The Adjacency Matrix for the graph is \n");
    for (v1 = 0; v1 < n; v1++)
    {
        for (v2 = 0; v2 < n; v2++)
            printf("%d", g[v1][v2]);
        printf("\n");
    }
    getchar();
    do
    {
        for (v1 = 0; v1 < n; v1++)
            visit[v1] = FALSE;


        printf("Enter the Vertex from which you want to traverse ");
        scanf("%d", &v1);
        if (v1 >= n)
            printf("Invalid Vertex\n");
        else
        {
            printf("The Breadth First Search of the Graph is\n");
            bfs(v1);
            getchar();
        }
        printf("\nDo you want to traverse from any other node?");
        ans = getchar();
    } while (ans == 'y');
    exit(0);
}
void create()
{
    int v1, v2;
    char ans = 'y';
    printf("\n\t\t This is a program to create a Graph");
    printf("\n\t\t The Dispaly Is In Breadth First Manner");
    printf("\nEnter no. of nodes");
    scanf("%d", &n);
    for (v1 = 0; v1 < n; v1++)
        for (v2 = 0; v2 < n; v2++)
            g[v1][v2] = FALSE;
    printf("\nEnter the vertices no. starting from 0");
    do
    {
        printf("\nEnter the vertices v1 & v2");
        scanf("%d%d", &v1, &v2);
        if (v1 >= n || v2 >= n)
            printf("Invalid Vertex Value\n");
        else
        {
            g[v1][v2] = TRUE;
            g[v2][v1] = TRUE;
        }
        printf("\n\nAdd more edges??(y/n)");
        ans = getchar();
    } while (ans == 'y');
}
void bfs(int v1)
{
    int v2, front, rear;
    visit[v1] = TRUE;
    front = rear = -1;
    Q[++rear] = v1;
    while (front != rear)
    {
        v1 = Q[++front];
        printf("%d\n", v1);
        for (v2 = 0; v2 < n; v2++)
        {
            if (g[v1][v2] == TRUE && visit[v2] == FALSE)
            {
                Q[++rear] = v2;
                visit[v2] = TRUE;
            }
        }
    }
}


/*
Sample Case : 
This is a Program To Create a Graph
The Display Is In Breadth First Manner
Enter no. of nodes 4
Enter the vertices no. starting from 0
Enter the vertices v1 & v2
0 1
Add more edges??(y/n)y
Enter the vertices v1 & v2
0 2
Add more edges??(y/n)y
Enter the vertices v1 & v2
1 3
Add more edges??(y/n)y
Enter the vertices v1 & v2
2 3
Add more edges??(y/n)
The Adjacency Matrix for the graph is
0 1 1 0
1 0 0 1
1 0 0 1
0 1 1 0
Enter the Vertex from which you want to traverse : 0
The Breadth First Search of the Graph is
0 
1 
2 
3
Do you want to traverse from any other node?
Enter the Vertex from which you want to traverse 1
The Breadth First Search of the Graph is
1 
0 
3 
2
Do you want to traverse from any other node?
*/


<|start_filename|>C/ds/Sparse_Matrix.c<|end_filename|>
/* SPARSE MATRIX REPRESENTATION USING LINKED LIST
    Representing a sparse matrix by a 2D array leads to wastage of lots of memory.
    A sparse matrix can be effectively represented by storing the non- zero elements
    Here a Linked list is used wherein each node stores
        1. row number
        2. column number
        3. non-zero value
    This representation reduces memory wastage
*/

#include <stdio.h>
#include <stdlib.h>

/* Declare node with row,column and data for storing non-zero term of
   sparse matrix.
   next points to the subsequent node
*/
typedef struct node
{
    int row, column, data;
    struct node *next;
} node;
node *head;

//to represent and print sparse matrix
void sparse_matrix(int rows, int cols, int mat[10][10])
{
    // traverse the matrix row-wise
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            //If a non-zero term is encountered
            if (mat[i][j] != 0)
            {
                //Store the non-zero term in a new node of the linked list
                node *new = malloc(sizeof(node));
                new->row = i;
                new->column = j;
                new->data = mat[i][j];
                new->next = NULL;
                //If the list is empty insert as first node
                if (head == NULL)
                    head = n;
                else
                {
                    node *ptr = head;
                    //Traverse till the end of the list
                    while (ptr->next != NULL)
                        ptr = ptr->next;
                    //insert as last node
                    ptr->next = new;
                }
            }
        }
    }
    node *ptr = head;
    printf("\nSPARSE MATRIX REPRESENTATION\nRow\tColumn\tValue\n");
    //Traverse the linked list and print each node
    while (ptr != NULL)
    {
        printf("%d\t%d\t%d\n", ptr->row, ptr->column, ptr->data);
        ptr = ptr->next;
    }
}

//driver code
int main()
{
    node *head = NULL;
    int matrix[10][10], rows, cols, count;
    //accept rows,columns and matrix entries as user input
    scanf("%d%d", &rows, &cols);
    int i, j;
    for (i = 0; i < rows; i++)
    {
        for (j = 0; j < cols; j++)
        {
            scanf("%d", &matrix[i][j]);
        }
    }

    sparse_matrix(rows, cols, matrix);
}

/*
    Sample Input:
    5 5
    0 0 2 0 1
    3 0 0 0 0
    0 0 0 0 0
    0 5 0 4 2
    0 0 6 0 0

    Sample Output:
    Row     Column  Value
    0       2       2
    0       4       1
    1       0       3
    3       1       5
    3       3       4
    3       4       2
    4       2       6
*/

/*
    Time Complexity : O(rows*cols)
    Space Complexity : O(n), where n= number of non-zero terms
*/


<|start_filename|>Java/ds/AVL_Tree.java<|end_filename|>
/*
AVL tree is a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees cannot
be more than one for all nodes and if at any time they differ by more than one, rebalancing is done to restore this property.
Each node maintains extra information called a balance factor whose value is either -1, 0 or +1 where balance factor of node
in an AVL tree is the difference between the height of the left subtree and that of the right subtree of that node.
*/

import java.util.*;

public class AVL_Tree {

    private Node root;

    private class Node {
        int data;
        Node left;
        Node right;
        int height;

        public Node(int data) {
            this.data = data;
            this.height = 1;
            left = null;
            right = null;
        }
    }

    // Inserting node in a tree
    public void insert(int num) {
        this.root = insert(this.root, num);
    }

    // Inorder Traversal
    public void inOrder(Node node) {
        if (node != null) {
            inOrder(node.left);
            System.out.print(node.data + " ");
            inOrder(node.right);
        }
    }

    // Preorder traversal
    public void preOrder(Node node) {
        if (node != null) {
            System.out.print(node.data + " ");
            preOrder(node.left);
            preOrder(node.right);
        }
    }

    // Postorder traversal
    public void postOrder(Node node) {
        if (node != null) {
            postOrder(node.left);
            postOrder(node.right);
            System.out.print(node.data + " ");
        }
    }

    private Node insert(Node node, int num) {

        if (node == null) {
            Node node_new = new Node(num);
            return node_new;
        }

        if (num > node.data) {
            node.right = insert(node.right, num);
        } else if (num < node.data) {
            node.left = insert(node.left, num);
        }

        node.height = Math.max(height(node.left), height(node.right)) + 1;

        int balancefactor = balancefactor(node);

        // L-L Case
        if (balancefactor > 1 && num < node.left.data) {
            return rightRotate(node);
        }

        // R-R Case
        if (balancefactor < -1 && num > node.right.data) {
            return leftRotate(node);
        }

        // L-R Case
        if (balancefactor > 1 && num > node.left.data) {
            node.left = leftRotate(node.left);
            return rightRotate(node);
        }

        // R-L Case
        if (balancefactor < -1 && num < node.right.data) {
            node.right = rightRotate(node.right);
            return leftRotate(node);
        }
        return node;
    }

    // Finding height of the node
    private int height(Node node) {
        if (node == null) {
            return 0;
        }
        return node.height;
    }

    // Balance Factor (difference between the height of the left subtree and that of the right subtree of the node)
    private int balancefactor(Node node) {
        if (node == null) {
            return 0;
        }

        return height(node.left) - height(node.right);
    }

    //Right rotation
    private Node rightRotate(Node node) {

        Node node1 = node.left;
        Node node2 = node.left.right;

        node1.right = node;
        node.left = node2;

        node.height = Math.max(height(node.left), height(node.right)) + 1;
        node1.height = Math.max(height(node1.left), height(node1.right)) + 1;

        return node1;
    }

    //Left rotation
    private Node leftRotate(Node node) {

        Node node1 = node.right;
        Node node2 = node1.left;

        node1.left = node;
        node.right = node2;

        node.height = Math.max(height(node.left), height(node.right)) + 1;
        node1.height = Math.max(height(node1.left), height(node1.right)) + 1;

        return node1;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        AVL_Tree tree = new AVL_Tree();
        System.out.println("Enter the number of nodes: ");
        int num = sc.nextInt();

        System.out.println("Enter the value of nodes: ");
        for (int i = 0; i < num; i++) {
            int value = sc.nextInt();
            tree.insert(value);
        }

        System.out.println("Preorder display: ");
        tree.preOrder(tree.root);
        System.out.println("\n\nInorder display: ");
        tree.inOrder(tree.root);
        System.out.println("\n\nPostorder display: ");
        tree.postOrder(tree.root);

    }
}

/*

Enter the number of nodes: 
10
Enter the value of nodes: 
10
20
40
30
80
60
50
44
22
18
Preorder display: 
40 20 10 18 30 22 60 50 44 80

Inorder display:
10 18 20 22 30 40 44 50 60 80

Postorder display:
18 10 22 30 20 44 50 80 60 40

--------------------------------
Space Complexity :
 O(n) in all the cases

Time Complexity :
 O(log n) in all the cases

*/
