Hamiltonian Cycle

A Hamiltonian Cycle or Circuit in a graph G is a cycle that visits each vertex of G exactly once and returns to the starting vertex.
If a graph has a Hamiltonian cycle, it's a Hamiltonian graph; otherwise, it's non-Hamiltonian.
Finding a Hamiltonian cycle is an NP-complete problem, meaning there's no known efficient solution for all graph types, but solutions exist for smaller or specific types.
The Hamiltonian Cycle problem has applications in logistics, network design, and computer science.
Given an undirected graph, the task is to determine if it contains a Hamiltonian cycle. If found, print the path; otherwise, print "Solution does not exist".

Input: N=5, adjMat[][] = [[0, 1, 0, 1, 0], [1, 0, 1, 1, 1], [0, 1, 0, 0, 1], [1, 1, 0, 0, 1], [0, 1, 1, 1, 0]]

Output: [0, 1, 2, 4, 3, 0]

import java.util.ArrayList;\nimport java.util.List;\n\npublic class InfobayAI {\n    \n    // Check if it's valid to place vertex at current position\n    private static boolean isSafe(int vertex, int[][] adjMat, \n                                    List<Integer> path, int pos) {\n        \n        // The vertex must be adjacent to the previous vertex\n        if (adjMat[path.get(pos - 1)][vertex] == 0) {\n            return false;\n        }\n\n        // The vertex must not already be in the path\n        for (int i = 0; i < pos; i++) {\n            if (path.get(i) == vertex) {\n                return false;\n            }\n        }\n\n        return true;\n    }\n\n    // Recursive backtracking to construct Hamiltonian Cycle\n    private static boolean hamCycleUtil(int[][] adjMat, \n                                List<Integer> path, int pos, int n) {\n        \n        // Base case: all vertices are in the path\n        if (pos == n) {\n            \n            // Check if there's an edge from last to first vertex\n            return adjMat[path.get(pos - 1)][path.get(0)] == 1;\n        }\n\n        // Try all possible vertices as next candidate\n        for (int v = 1; v < n; v++) {\n            if (isSafe(v, adjMat, path, pos)) {\n                \n                path.set(pos, v);\n                \n                if (hamCycleUtil(adjMat, path, pos + 1, n)) {\n                    return true;\n                }\n\n                // Backtrack if v doesn't lead to a solution\n                path.set(pos, -1);\n            }\n        }\n\n        return false;\n    }\n\n    // Initialize path and invoke backtracking function\n    public static List<Integer> hamCycle(int[][] adjMat) {\n        \n        int n = adjMat.length;\n        List<Integer> path = new ArrayList<>(n);\n        \n        for (int i = 0; i < n; i++) {\n            path.add(-1);\n        }\n\n        // Start path with vertex 0\n        path.set(0, 0);\n\n        if (!hamCycleUtil(adjMat, path, 1, n)) {\n            \n            List<Integer> noSolution = new ArrayList<>();\n            noSolution.add(-1);\n            return noSolution;\n        }\n\n        return path;\n    }\n\n    // Driver Code\n    public static void main(String[] args) {\n        int[][] adjMat = {\n            {0, 1, 0, 1, 0},\n            {1, 0, 1, 1, 1},\n            {0, 1, 0, 0, 1},\n            {1, 1, 0, 0, 1},\n            {0, 1, 1, 1, 0}\n        };\n\n        List<Integer> path = hamCycle(adjMat);\n\n        if (path.get(0) == -1) {\n            System.out.println("Solution does not Exist");\n        } \n        else {\n            for (int i = 0; i < path.size(); i++) {\n                System.out.print(path.get(i) + " ");\n            }\n            System.out.print(path.get(0));\n        }\n    }\n}


Hamiltonian Cycle

A Hamiltonian Cycle or Circuit in a graph G is a cycle that visits each vertex of G exactly once and returns to the starting vertex.
If a graph has a Hamiltonian cycle, it's a Hamiltonian graph; otherwise, it's non-Hamiltonian.
Finding a Hamiltonian cycle is an NP-complete problem, meaning there's no known efficient solution for all graph types, but solutions exist for smaller or specific types.
The Hamiltonian Cycle problem has applications in logistics, network design, and computer science.
Given an undirected graph, the task is to determine if it contains a Hamiltonian cycle. If found, print the path; otherwise, print "Solution does not exist".

Input: N=5, adjMat[][] = [[0, 1, 0, 1, 0], [1, 0, 1, 1, 1], [0, 1, 0, 0, 1], [1, 1, 0, 0, 1], [0, 1, 1, 1, 0]]

Output: [0, 1, 2, 4, 3, 0]

# Check if it's valid to place vertex at current position\ndef isSafe(vertex, adjMat, path, pos):\n\n    # The vertex must be adjacent to the previous vertex\n    if adjMat[path[pos - 1]][vertex] == 0:\n        return False\n\n    # The vertex must not already be in the path\n    for i in range(pos):\n        if path[i] == vertex:\n            return False\n\n    return True\n\n\n# Recursive backtracking to construct Hamiltonian Cycle\ndef hamCycleUtil(adjMat, path, pos, n):\n\n    # Base case: all vertices are in the path\n    if pos == n:\n\n        # Check if there's an edge from last to first vertex\n        return adjMat[path[pos - 1]][path[0]] == 1\n\n    # Try all possible vertices as next candidate\n    for v in range(1, n):\n        if isSafe(v, adjMat, path, pos):\n\n            path[pos] = v\n\n            if hamCycleUtil(adjMat, path, pos + 1, n):\n                return True\n\n            # Backtrack if v doesn't lead to a solution\n            path[pos] = -1\n\n    return False\n\n\n# Initialize path and invoke backtracking function\ndef hamCycle(adjMat):\n\n    n = len(adjMat)\n    path = [-1] * n\n\n    # Start path with vertex 0\n    path[0] = 0\n\n    if not hamCycleUtil(adjMat, path, 1, n):\n        return [-1]\n\n    return path\n\n\nif __name__ == "__main__":\n    adjMat = [\n        [0, 1, 0, 1, 0],\n        [1, 0, 1, 1, 1],\n        [0, 1, 0, 0, 1],\n        [1, 1, 0, 0, 1],\n        [0, 1, 1, 1, 0]\n    ]\n    \n    path = hamCycle(adjMat)\n    \n    if path[0] == -1:\n        print("Solution does not Exist")\n    else:\n        for v in path:\n            print(v, end=" ")\n        print(path[0])


Hamiltonian Cycle

A Hamiltonian Cycle or Circuit in a graph G is a cycle that visits each vertex of G exactly once and returns to the starting vertex.
If a graph has a Hamiltonian cycle, it's a Hamiltonian graph; otherwise, it's non-Hamiltonian.
Finding a Hamiltonian cycle is an NP-complete problem, meaning there's no known efficient solution for all graph types, but solutions exist for smaller or specific types.
The Hamiltonian Cycle problem has applications in logistics, network design, and computer science.
Given an undirected graph, the task is to determine if it contains a Hamiltonian cycle. If found, print the path; otherwise, print "Solution does not exist".

Input: N=5, adjMat[][] = [[0, 1, 0, 1, 0], [1, 0, 1, 1, 1], [0, 1, 0, 0, 1], [1, 1, 0, 0, 0], [0, 1, 1, 0, 0]]

Output: "Solution Does Not Exists"

#include <iostream>\n#include <vector>\n\nusing namespace std;\n\n// Check if it's valid to place vertex at current position\nbool isSafe(int vertex, vector<vector<int>> &adjMat, \n            vector<int> &path, int pos) {\n    \n    // The vertex must be adjacent to the previous vertex\n    if (!adjMat[path[pos - 1]][vertex]) {\n        return false;\n    }\n\n    // The vertex must not already be in the path\n    for (int i = 0; i < pos; i++) {\n        if (path[i] == vertex) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\n// Recursive backtracking to construct Hamiltonian Cycle\nbool hamCycleUtil(vector<vector<int>> &adjMat, \n                  vector<int> &path, int pos, int n) {\n    \n    // Base case: all vertices are in the path\n    if (pos == n) {\n        \n        // Check if there's an edge from last to first vertex\n        return adjMat[path[pos - 1]][path[0]];\n    }\n\n    // Try all possible vertices as next candidate\n    for (int v = 1; v < n; v++) {\n        if (isSafe(v, adjMat, path, pos)) {\n            path[pos] = v;\n\n            if (hamCycleUtil(adjMat, path, pos + 1, n)) {\n                return true;\n            }\n\n            // Backtrack if v doesn't lead to a solution\n            path[pos] = -1;\n        }\n    }\n\n    return false;\n}\n\n// Initialize path and invoke backtracking function\nvector<int> hamCycle(vector<vector<int>> &adjMat) {\n    int n = adjMat.size();\n    vector<int> path(n, -1);\n\n    // Start path with vertex 0\n    path[0] = 0;\n\n    if (!hamCycleUtil(adjMat, path, 1, n)) {\n        return {-1};\n    }\n\n    return path;\n}\n\n// Driver Code\nint main() {\n    \n    vector<vector<int>> adjMat = {\n        {0, 1, 0, 1, 0}, \n        {1, 0, 1, 1, 1}, \n        {0, 1, 0, 0, 1}, \n        {1, 1, 0, 0, 1}, \n        {0, 1, 1, 1, 0}\n    };\n\n    vector<int> path = hamCycle(adjMat);\n    \n    if(path[0] == -1) {\n        cout << "Solution does not Exist";\n    }\n    else {\n        for (int i = 0; i < path.size(); i++) {\n           cout << path[i] << " ";\n        }\n        cout << path[0];\n    }\n    return 0;\n}


Hamiltonian Cycle

A Hamiltonian Cycle or Circuit in a graph G is a cycle that visits each vertex of G exactly once and returns to the starting vertex.
If a graph has a Hamiltonian cycle, it's a Hamiltonian graph; otherwise, it's non-Hamiltonian.
Finding a Hamiltonian cycle is an NP-complete problem, meaning there's no known efficient solution for all graph types, but solutions exist for smaller or specific types.
The Hamiltonian Cycle problem has applications in logistics, network design, and computer science.
Given an undirected graph, the task is to determine if it contains a Hamiltonian cycle. If found, print the path; otherwise, print "Solution does not exist".

Input: N=5, adjMat[][] = [[0, 1, 0, 1, 0], [1, 0, 1, 1, 1], [0, 1, 0, 0, 1], [1, 1, 0, 0, 0], [0, 1, 1, 0, 0]]

Output: "Solution Does Not Exists"

import java.util.ArrayList;\nimport java.util.List;\n\npublic class InfobayAI {\n    \n    // Check if it's valid to place vertex at current position\n    private static boolean isSafe(int vertex, int[][] adjMat, \n                                    List<Integer> path, int pos) {\n        \n        // The vertex must be adjacent to the previous vertex\n        if (adjMat[path.get(pos - 1)][vertex] == 0) {\n            return false;\n        }\n\n        // The vertex must not already be in the path\n        for (int i = 0; i < pos; i++) {\n            if (path.get(i) == vertex) {\n                return false;\n            }\n        }\n\n        return true;\n    }\n\n    // Recursive backtracking to construct Hamiltonian Cycle\n    private static boolean hamCycleUtil(int[][] adjMat, \n                                List<Integer> path, int pos, int n) {\n        \n        // Base case: all vertices are in the path\n        if (pos == n) {\n            \n            // Check if there's an edge from last to first vertex\n            return adjMat[path.get(pos - 1)][path.get(0)] == 1;\n        }\n\n        // Try all possible vertices as next candidate\n        for (int v = 1; v < n; v++) {\n            if (isSafe(v, adjMat, path, pos)) {\n                \n                path.set(pos, v);\n                \n                if (hamCycleUtil(adjMat, path, pos + 1, n)) {\n                    return true;\n                }\n\n                // Backtrack if v doesn't lead to a solution\n                path.set(pos, -1);\n            }\n        }\n\n        return false;\n    }\n\n    // Initialize path and invoke backtracking function\n    public static List<Integer> hamCycle(int[][] adjMat) {\n        \n        int n = adjMat.length;\n        List<Integer> path = new ArrayList<>(n);\n        \n        for (int i = 0; i < n; i++) {\n            path.add(-1);\n        }\n\n        // Start path with vertex 0\n        path.set(0, 0);\n\n        if (!hamCycleUtil(adjMat, path, 1, n)) {\n            \n            List<Integer> noSolution = new ArrayList<>();\n            noSolution.add(-1);\n            return noSolution;\n        }\n\n        return path;\n    }\n\n    // Driver Code\n    public static void main(String[] args) {\n        int[][] adjMat = {\n            {0, 1, 0, 1, 0},\n            {1, 0, 1, 1, 1},\n            {0, 1, 0, 0, 1},\n            {1, 1, 0, 0, 1},\n            {0, 1, 1, 1, 0}\n        };\n\n        List<Integer> path = hamCycle(adjMat);\n\n        if (path.get(0) == -1) {\n            System.out.println("Solution does not Exist");\n        } \n        else {\n            for (int i = 0; i < path.size(); i++) {\n                System.out.print(path.get(i) + " ");\n            }\n            System.out.print(path.get(0));\n        }\n    }\n}


Hamiltonian Cycle

A Hamiltonian Cycle or Circuit in a graph G is a cycle that visits each vertex of G exactly once and returns to the starting vertex.
If a graph has a Hamiltonian cycle, it's a Hamiltonian graph; otherwise, it's non-Hamiltonian.
Finding a Hamiltonian cycle is an NP-complete problem, meaning there's no known efficient solution for all graph types, but solutions exist for smaller or specific types.
The Hamiltonian Cycle problem has applications in logistics, network design, and computer science.
Given an undirected graph, the task is to determine if it contains a Hamiltonian cycle. If found, print the path; otherwise, print "Solution does not exist".

Input: N=5, adjMat[][] = [[0, 1, 0, 1, 0], [1, 0, 1, 1, 1], [0, 1, 0, 0, 1], [1, 1, 0, 0, 0], [0, 1, 1, 0, 0]]

Output: "Solution Does Not Exists"

# Check if it's valid to place vertex at current position\ndef isSafe(vertex, adjMat, path, pos):\n\n    # The vertex must be adjacent to the previous vertex\n    if adjMat[path[pos - 1]][vertex] == 0:\n        return False\n\n    # The vertex must not already be in the path\n    for i in range(pos):\n        if path[i] == vertex:\n            return False\n\n    return True\n\n\n# Recursive backtracking to construct Hamiltonian Cycle\ndef hamCycleUtil(adjMat, path, pos, n):\n\n    # Base case: all vertices are in the path\n    if pos == n:\n\n        # Check if there's an edge from last to first vertex\n        return adjMat[path[pos - 1]][path[0]] == 1\n\n    # Try all possible vertices as next candidate\n    for v in range(1, n):\n        if isSafe(v, adjMat, path, pos):\n\n            path[pos] = v\n\n            if hamCycleUtil(adjMat, path, pos + 1, n):\n                return True\n\n            # Backtrack if v doesn't lead to a solution\n            path[pos] = -1\n\n    return False\n\n\n# Initialize path and invoke backtracking function\ndef hamCycle(adjMat):\n\n    n = len(adjMat)\n    path = [-1] * n\n\n    # Start path with vertex 0\n    path[0] = 0\n\n    if not hamCycleUtil(adjMat, path, 1, n):\n        return [-1]\n\n    return path\n\n\nif __name__ == "__main__":\n    adjMat = [\n        [0, 1, 0, 1, 0],\n        [1, 0, 1, 1, 1],\n        [0, 1, 0, 0, 1],\n        [1, 1, 0, 0, 1],\n        [0, 1, 1, 1, 0]\n    ]\n    \n    path = hamCycle(adjMat)\n    \n    if path[0] == -1:\n        print("Solution does not Exist")\n    else:\n        for v in path:\n            print(v, end=" ")\n        print(path[0])


Length of longest common prime subsequence from two given arrays

Given two arrays arr1[] and arr2[] of length N and M respectively, the task is to find the length of the longest common prime subsequence that can be obtained from the two given arrays.

Input: arr1[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}, arr2[] = {2, 5, 6, 3, 7, 9, 8}

Output:
4
Explanation:
The longest common prime subsequence present in both the arrays is {2, 3, 5, 7}.

// CPP implementation of the above approach\n#include <bits/stdc++.h>\nusing namespace std;\n\n// Function to calculate the LCS\nint recursion(vector<int> arr1,\n              vector<int> arr2, int i,\n              int j, map<pair<int, int>, \n              int> dp)\n{\n    if (i >= arr1.size() or j >= arr2.size())\n        return 0;\n    pair<int, int> key = { i, j };\n    if (arr1[i] == arr2[j])\n        return 1 \n               + recursion(arr1, arr2, \n                            i + 1, j + 1,\n                           dp);\n    if (dp.find(key) != dp.end())\n        return dp[key];\n\n    else\n        dp[key] = max(recursion(arr1, arr2, \n                                i + 1, j, dp),\n                      recursion(arr1, arr2, i, \n                                j + 1, dp));\n    return dp[key];\n}\n\n// Function to generate\n// all the possible\n// prime numbers\nvector<int> primegenerator(int n)\n{\n    int cnt = 0;\n    vector<int> primes(n + 1, true);\n    int p = 2;\n    while (p * p <= n)\n    {\n        for (int i = p * p; i <= n; i += p)\n            primes[i] = false;\n        p += 1;\n    }\n    return primes;\n}\n\n// Function which returns the\n// length of longest common\n// prime subsequence\nint longestCommonSubseq(vector<int> arr1, \n                        vector<int> arr2)\n{\n\n    // Minimum element of\n    // both arrays\n    int min1 = *min_element(arr1.begin(), \n                            arr1.end());\n    int min2 = *min_element(arr2.begin(),\n                            arr2.end());\n\n    // Maximum element of\n    // both arrays\n    int max1 = *max_element(arr1.begin(),\n                            arr1.end());\n    int max2 = *max_element(arr2.begin(), \n                            arr2.end());\n\n    // Generating all primes within\n    // the max range of arr1\n    vector<int> a = primegenerator(max1);\n\n    // Generating all primes within\n    // the max range of arr2\n    vector<int> b = primegenerator(max2);\n\n    vector<int> finala;\n    vector<int> finalb;\n\n    // Store precomputed values\n    map<pair<int, int>, int> dp;\n\n    // Store all primes in arr1[]\n    for (int i = min1; i <= max1; i++) \n    {\n        if (find(arr1.begin(), arr1.end(), i) \n            != arr1.end()\n            and a[i] == true)\n            finala.push_back(i);\n    }\n\n    // Store all primes of arr2[]\n    for (int i = min2; i <= max2; i++) \n    {\n        if (find(arr2.begin(), arr2.end(), i) \n            != arr2.end()\n            and b[i] == true)\n            finalb.push_back(i);\n    }\n\n    // Calculating the LCS\n    return recursion(finala, finalb, 0, 0, dp);\n}\n\n// Driver Code\nint main()\n{\n    vector<int> arr1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n    vector<int> arr2 = { 2, 5, 6, 3, 7, 9, 8 };\n    \n    // Function Call\n    cout << longestCommonSubseq(arr1, arr2);\n}


Given two arrays arr1[] and arr2[] of length N and M respectively, the task is to find the length of the longest common prime subsequence that can be obtained from the two given arrays.

Input: arr1[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}, arr2[] = {2, 5, 6, 3, 7, 9, 8}

Output:
4
Explanation:
The longest common prime subsequence present in both the arrays is {2, 3, 5, 7}.

// JAVA implementation of the above approach\nimport java.util.*;\nimport java.io.*;\nimport java.math.*;\npublic class InfobayAI\n{\n\n  // Function to calculate the LCS\n  static int recursion(ArrayList<Integer> arr1,\n                       ArrayList<Integer> arr2, int i,\n                       int j, Map<ArrayList<Integer>, \n                       Integer> dp)\n  {\n    if (i >= arr1.size() || j >= arr2.size())\n      return 0;\n    ArrayList<Integer> key = new ArrayList<>();\n    key.add(i);\n    key.add(j);\n    if (arr1.get(i) == arr2.get(j))\n      return 1 + recursion(arr1, arr2, \n                           i + 1, j + 1,\n                           dp);\n    if (dp.get(key) != dp.get(dp.size()-1))\n      return dp.get(key);\n\n    else\n      dp.put(key,Math.max(recursion(arr1, arr2, \n                                    i + 1, j, dp),\n                          recursion(arr1, arr2, i, \n                                    j + 1, dp)));\n    return dp.get(key);\n  }\n\n  // Function to generate\n  // all the possible\n  // prime numbers\n  static ArrayList<Boolean> primegenerator(int n)\n  {\n    int cnt = 0;\n    ArrayList<Boolean> primes = new ArrayList<>();\n    for(int i = 0; i < n + 1; i++)\n      primes.add(true);\n    int p = 2;\n    while (p * p <= n)\n    {\n      for (int i = p * p; i <= n; i += p)\n        primes.set(i,false);\n      p += 1;\n    }\n    return primes;\n  }\n\n  // Function that returns the Minimum element of an ArrayList\n  static int min_element(ArrayList<Integer> al)\n  {\n    int min = Integer.MAX_VALUE;\n    for(int i = 0; i < al.size(); i++)\n    {\n      min=Math.min(min, al.get(i));\n    }\n    return min;\n  }\n\n  // Function that returns the Minimum element of an ArrayList\n  static int max_element(ArrayList<Integer> al)\n  {\n    int max = Integer.MIN_VALUE;\n    for(int i = 0; i < al.size(); i++)\n    {\n      max = Math.max(max, al.get(i));\n    }\n    return max;\n  }\n\n  // Function which returns the\n  // length of longest common\n  // prime subsequence\n  static int longestCommonSubseq(ArrayList<Integer> arr1, \n                                 ArrayList<Integer> arr2)\n  {\n\n    // Minimum element of\n    // both arrays\n    int min1 = min_element(arr1);\n    int min2 = min_element(arr2);\n\n    // Maximum element of\n    // both arrays\n    int max1 = max_element(arr1);\n    int max2 = max_element(arr2);\n\n    // Generating all primes within\n    // the max range of arr1\n    ArrayList<Boolean> a = primegenerator(max1);\n\n    // Generating all primes within\n    // the max range of arr2\n    ArrayList<Boolean> b = primegenerator(max2);\n    ArrayList<Integer> finala = new ArrayList<>();\n    ArrayList<Integer> finalb = new ArrayList<>();\n\n    // Store precomputed values\n    Map<ArrayList<Integer>,Integer> dp = \n      new HashMap <ArrayList<Integer>,Integer> ();\n\n    // Store all primes in arr1[]\n    for (int i = min1; i <= max1; i++) \n    {\n      if (arr1.contains(i)\n          && a.get(i) == true)\n        finala.add(i);\n    }\n\n    // Store all primes of arr2[]\n    for (int i = min2; i <= max2; i++) \n    {\n      if (arr2.contains(i)\n          && b.get(i) == true)\n        finalb.add(i);\n    }\n\n    // Calculating the LCS\n    return recursion(finala, finalb, 0, 0, dp);\n  }\n\n  // Driver Code\n  public static void main(String args[])\n  {\n    int a1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n    int a2[] = { 2, 5, 6, 3, 7, 9, 8 };\n\n    // Converting into list\n    ArrayList<Integer> arr1 = new ArrayList<Integer>();\n    for(int i = 0; i < a1.length; i++)\n      arr1.add(a1[i]);\n\n    ArrayList<Integer> arr2 = new ArrayList<Integer>();\n    for(int i = 0; i < a2.length; i++)\n      arr2.add(a2[i]);\n\n    // Function Call\n    System.out.println(longestCommonSubseq(arr1, arr2));\n  }\n}\n\n


Given two arrays arr1[] and arr2[] of length N and M respectively, the task is to find the length of the longest common prime subsequence that can be obtained from the two given arrays.

Input: arr1[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}, arr2[] = {2, 5, 6, 3, 7, 9, 8}

Output:
4
Explanation:
The longest common prime subsequence present in both the arrays is {2, 3, 5, 7}.

# Python implementation of the above approach\n\n# Function to calculate the LCS\n\ndef recursion(arr1, arr2, i, j, dp):\n    if i >= len(arr1) or j >= len(arr2):\n        return 0\n    key = (i, j)\n    if arr1[i] == arr2[j]:\n        return 1 + recursion(arr1, arr2,\n                             i + 1, j + 1, dp)\n    if key in dp:\n        return dp[key]\n    else:\n        dp[key] = max(recursion(arr1, arr2,\n                                i + 1, j, dp),\n                      recursion(arr1, arr2,\n                                i, j + 1, dp))\n    return dp[key]\n\n# Function to generate\n# all the possible\n# prime numbers\n\n\ndef primegenerator(n):\n    cnt = 0\n    primes = [True for _ in range(n + 1)]\n    p = 2\n    while p * p <= n:\n        for i in range(p * p, n + 1, p):\n            primes[i] = False\n        p += 1\n    return primes\n\n# Function which returns the\n# length of longest common\n# prime subsequence\n\n\ndef longestCommonSubseq(arr1, arr2):\n\n    # Minimum element of\n    # both arrays\n    min1 = min(arr1)\n    min2 = min(arr2)\n\n    # Maximum element of\n    # both arrays\n    max1 = max(arr1)\n    max2 = max(arr2)\n\n    # Generating all primes within\n    # the max range of arr1\n    a = primegenerator(max1)\n\n    # Generating all primes within\n    # the max range of arr2\n    b = primegenerator(max2)\n\n    finala = []\n    finalb = []\n\n    # Store precomputed values\n    dp = dict()\n\n    # Store all primes in arr1[]\n    for i in range(min1, max1 + 1):\n        if i in arr1 and a[i] == True:\n            finala.append(i)\n\n    # Store all primes of arr2[]\n    for i in range(min2, max2 + 1):\n        if i in arr2 and b[i] == True:\n            finalb.append(i)\n\n    # Calculating the LCS\n    return recursion(finala, finalb,\n                     0, 0, dp)\n\n\n# Driver Code\narr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]\narr2 = [2, 5, 6, 3, 7, 9, 8]\n\n# Function Call\nprint(longestCommonSubseq(arr1, arr2))


Given two arrays arr1[] and arr2[] of length N and M respectively, the task is to find the length of the longest common prime subsequence that can be obtained from the two given arrays.

Input: arr1[] = {1, 3, 5, 7, 9}, arr2[] = {2, 4, 6, 8, 10}

Output:
0
Explanation:
In the above arrays, the prime subsequence of arr1[] is {1, 3, 5, 7} and arr2[] is {2}. Therefore, there is no common prime numbers which are present in both the arrays. Hence, the result is 0.

// CPP implementation of the above approach\n#include <bits/stdc++.h>\nusing namespace std;\n\n// Function to calculate the LCS\nint recursion(vector<int> arr1,\n              vector<int> arr2, int i,\n              int j, map<pair<int, int>, \n              int> dp)\n{\n    if (i >= arr1.size() or j >= arr2.size())\n        return 0;\n    pair<int, int> key = { i, j };\n    if (arr1[i] == arr2[j])\n        return 1 \n               + recursion(arr1, arr2, \n                            i + 1, j + 1,\n                           dp);\n    if (dp.find(key) != dp.end())\n        return dp[key];\n\n    else\n        dp[key] = max(recursion(arr1, arr2, \n                                i + 1, j, dp),\n                      recursion(arr1, arr2, i, \n                                j + 1, dp));\n    return dp[key];\n}\n\n// Function to generate\n// all the possible\n// prime numbers\nvector<int> primegenerator(int n)\n{\n    int cnt = 0;\n    vector<int> primes(n + 1, true);\n    int p = 2;\n    while (p * p <= n)\n    {\n        for (int i = p * p; i <= n; i += p)\n            primes[i] = false;\n        p += 1;\n    }\n    return primes;\n}\n\n// Function which returns the\n// length of longest common\n// prime subsequence\nint longestCommonSubseq(vector<int> arr1, \n                        vector<int> arr2)\n{\n\n    // Minimum element of\n    // both arrays\n    int min1 = *min_element(arr1.begin(), \n                            arr1.end());\n    int min2 = *min_element(arr2.begin(),\n                            arr2.end());\n\n    // Maximum element of\n    // both arrays\n    int max1 = *max_element(arr1.begin(),\n                            arr1.end());\n    int max2 = *max_element(arr2.begin(), \n                            arr2.end());\n\n    // Generating all primes within\n    // the max range of arr1\n    vector<int> a = primegenerator(max1);\n\n    // Generating all primes within\n    // the max range of arr2\n    vector<int> b = primegenerator(max2);\n\n    vector<int> finala;\n    vector<int> finalb;\n\n    // Store precomputed values\n    map<pair<int, int>, int> dp;\n\n    // Store all primes in arr1[]\n    for (int i = min1; i <= max1; i++) \n    {\n        if (find(arr1.begin(), arr1.end(), i) \n            != arr1.end()\n            and a[i] == true)\n            finala.push_back(i);\n    }\n\n    // Store all primes of arr2[]\n    for (int i = min2; i <= max2; i++) \n    {\n        if (find(arr2.begin(), arr2.end(), i) \n            != arr2.end()\n            and b[i] == true)\n            finalb.push_back(i);\n    }\n\n    // Calculating the LCS\n    return recursion(finala, finalb, 0, 0, dp);\n}\n\n// Driver Code\nint main()\n{\n    vector<int> arr1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n    vector<int> arr2 = { 2, 5, 6, 3, 7, 9, 8 };\n    \n    // Function Call\n    cout << longestCommonSubseq(arr1, arr2);\n}


Given two arrays arr1[] and arr2[] of length N and M respectively, the task is to find the length of the longest common prime subsequence that can be obtained from the two given arrays.

Input: arr1[] = {1, 3, 5, 7, 9}, arr2[] = {2, 4, 6, 8, 10}

Output:
0
Explanation:
In the above arrays, the prime subsequence of arr1[] is {1, 3, 5, 7} and arr2[] is {2}. Therefore, there is no common prime numbers which are present in both the arrays. Hence, the result is 0.

// JAVA implementation of the above approach\nimport java.util.*;\nimport java.io.*;\nimport java.math.*;\npublic class InfobayAI\n{\n\n  // Function to calculate the LCS\n  static int recursion(ArrayList<Integer> arr1,\n                       ArrayList<Integer> arr2, int i,\n                       int j, Map<ArrayList<Integer>, \n                       Integer> dp)\n  {\n    if (i >= arr1.size() || j >= arr2.size())\n      return 0;\n    ArrayList<Integer> key = new ArrayList<>();\n    key.add(i);\n    key.add(j);\n    if (arr1.get(i) == arr2.get(j))\n      return 1 + recursion(arr1, arr2, \n                           i + 1, j + 1,\n                           dp);\n    if (dp.get(key) != dp.get(dp.size()-1))\n      return dp.get(key);\n\n    else\n      dp.put(key,Math.max(recursion(arr1, arr2, \n                                    i + 1, j, dp),\n                          recursion(arr1, arr2, i, \n                                    j + 1, dp)));\n    return dp.get(key);\n  }\n\n  // Function to generate\n  // all the possible\n  // prime numbers\n  static ArrayList<Boolean> primegenerator(int n)\n  {\n    int cnt = 0;\n    ArrayList<Boolean> primes = new ArrayList<>();\n    for(int i = 0; i < n + 1; i++)\n      primes.add(true);\n    int p = 2;\n    while (p * p <= n)\n    {\n      for (int i = p * p; i <= n; i += p)\n        primes.set(i,false);\n      p += 1;\n    }\n    return primes;\n  }\n\n  // Function that returns the Minimum element of an ArrayList\n  static int min_element(ArrayList<Integer> al)\n  {\n    int min = Integer.MAX_VALUE;\n    for(int i = 0; i < al.size(); i++)\n    {\n      min=Math.min(min, al.get(i));\n    }\n    return min;\n  }\n\n  // Function that returns the Minimum element of an ArrayList\n  static int max_element(ArrayList<Integer> al)\n  {\n    int max = Integer.MIN_VALUE;\n    for(int i = 0; i < al.size(); i++)\n    {\n      max = Math.max(max, al.get(i));\n    }\n    return max;\n  }\n\n  // Function which returns the\n  // length of longest common\n  // prime subsequence\n  static int longestCommonSubseq(ArrayList<Integer> arr1, \n                                 ArrayList<Integer> arr2)\n  {\n\n    // Minimum element of\n    // both arrays\n    int min1 = min_element(arr1);\n    int min2 = min_element(arr2);\n\n    // Maximum element of\n    // both arrays\n    int max1 = max_element(arr1);\n    int max2 = max_element(arr2);\n\n    // Generating all primes within\n    // the max range of arr1\n    ArrayList<Boolean> a = primegenerator(max1);\n\n    // Generating all primes within\n    // the max range of arr2\n    ArrayList<Boolean> b = primegenerator(max2);\n    ArrayList<Integer> finala = new ArrayList<>();\n    ArrayList<Integer> finalb = new ArrayList<>();\n\n    // Store precomputed values\n    Map<ArrayList<Integer>,Integer> dp = \n      new HashMap <ArrayList<Integer>,Integer> ();\n\n    // Store all primes in arr1[]\n    for (int i = min1; i <= max1; i++) \n    {\n      if (arr1.contains(i)\n          && a.get(i) == true)\n        finala.add(i);\n    }\n\n    // Store all primes of arr2[]\n    for (int i = min2; i <= max2; i++) \n    {\n      if (arr2.contains(i)\n          && b.get(i) == true)\n        finalb.add(i);\n    }\n\n    // Calculating the LCS\n    return recursion(finala, finalb, 0, 0, dp);\n  }\n\n  // Driver Code\n  public static void main(String args[])\n  {\n    int a1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n    int a2[] = { 2, 5, 6, 3, 7, 9, 8 };\n\n    // Converting into list\n    ArrayList<Integer> arr1 = new ArrayList<Integer>();\n    for(int i = 0; i < a1.length; i++)\n      arr1.add(a1[i]);\n\n    ArrayList<Integer> arr2 = new ArrayList<Integer>();\n    for(int i = 0; i < a2.length; i++)\n      arr2.add(a2[i]);\n\n    // Function Call\n    System.out.println(longestCommonSubseq(arr1, arr2));\n  }\n}\n\n


Given two arrays arr1[] and arr2[] of length N and M respectively, the task is to find the length of the longest common prime subsequence that can be obtained from the two given arrays.

Input: arr1[] = {1, 3, 5, 7, 9}, arr2[] = {2, 4, 6, 8, 10}

Output:
0
Explanation:
In the above arrays, the prime subsequence of arr1[] is {1, 3, 5, 7} and arr2[] is {2}. Therefore, there is no common prime numbers which are present in both the arrays. Hence, the result is 0.

# Python implementation of the above approach\n\n# Function to calculate the LCS\n\ndef recursion(arr1, arr2, i, j, dp):\n    if i >= len(arr1) or j >= len(arr2):\n        return 0\n    key = (i, j)\n    if arr1[i] == arr2[j]:\n        return 1 + recursion(arr1, arr2,\n                             i + 1, j + 1, dp)\n    if key in dp:\n        return dp[key]\n    else:\n        dp[key] = max(recursion(arr1, arr2,\n                                i + 1, j, dp),\n                      recursion(arr1, arr2,\n                                i, j + 1, dp))\n    return dp[key]\n\n# Function to generate\n# all the possible\n# prime numbers\n\n\ndef primegenerator(n):\n    cnt = 0\n    primes = [True for _ in range(n + 1)]\n    p = 2\n    while p * p <= n:\n        for i in range(p * p, n + 1, p):\n            primes[i] = False\n        p += 1\n    return primes\n\n# Function which returns the\n# length of longest common\n# prime subsequence\n\n\ndef longestCommonSubseq(arr1, arr2):\n\n    # Minimum element of\n    # both arrays\n    min1 = min(arr1)\n    min2 = min(arr2)\n\n    # Maximum element of\n    # both arrays\n    max1 = max(arr1)\n    max2 = max(arr2)\n\n    # Generating all primes within\n    # the max range of arr1\n    a = primegenerator(max1)\n\n    # Generating all primes within\n    # the max range of arr2\n    b = primegenerator(max2)\n\n    finala = []\n    finalb = []\n\n    # Store precomputed values\n    dp = dict()\n\n    # Store all primes in arr1[]\n    for i in range(min1, max1 + 1):\n        if i in arr1 and a[i] == True:\n            finala.append(i)\n\n    # Store all primes of arr2[]\n    for i in range(min2, max2 + 1):\n        if i in arr2 and b[i] == True:\n            finalb.append(i)\n\n    # Calculating the LCS\n    return recursion(finala, finalb,\n                     0, 0, dp)\n\n\n# Driver Code\narr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]\narr2 = [2, 5, 6, 3, 7, 9, 8]\n\n# Function Call\nprint(longestCommonSubseq(arr1, arr2))


Lexicographically smallest permutation of a string that can be reduced to length K by removing K-length prefixes from palindromic substrings of length 2K

Given a binary string str of length N, and an integer K, the task is to find the lexicographically smallest permutation of the string str that can be reduced to length K by removal of every K-length prefix from palindromic substrings of length 2K. If no such permutation exists, print "Not Possible".

Input: str = "0000100001100001”, K = 4

Output:
0001100000011000
Explanation: In the string "0001100000011000", every 2K length substring becomes a palindrome whenever a K-length prefix is removed, until string length reduces to K.

// C++ program for the above approach\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n// Function to count the number of\n// zeroes present in the string\nint count_zeroes(int n, string str)\n{\n    int cnt = 0;\n\n    // Traverse the string\n    for (int i = 0; i < str.size(); i++) {\n        if (str[i] == '0')\n            cnt++;\n    }\n\n    // Return the count\n    return cnt;\n}\n\n// Function to rearrange the string s.t\n// the string can be reduced to a length\n// K as per the given rules\nstring kReducingStringUtil(\n    int n, int k, string str,\n    int no_of_zeroes)\n{\n\n    // Distribute the count of 0s and\n    // 1s in segment of length 2k\n    int zeroes_in_2k = ((no_of_zeroes)\n                        * (2 * k))\n                       / n;\n\n    int ones_in_2k = 2 * k - zeroes_in_2k;\n\n    // Store string that are initially\n    // have formed lexicographically\n    // smallest 2k length substring\n    string temp_str = "";\n\n    for (int i = 0;\n         i < (zeroes_in_2k) / 2; i++) {\n        temp_str.push_back('0');\n    }\n    for (int i = 0; i < ones_in_2k; i++) {\n        temp_str.push_back('1');\n    }\n    for (int i = 0;\n         i < (zeroes_in_2k) / 2; i++) {\n        temp_str.push_back('0');\n    }\n\n    // Store the lexicographically\n    // smallest string of length n\n    // that satisfy the condition\n    string final_str = "";\n\n    // Insert temp_str into final_str\n    // (n/2k) times and add (n%2k)\n    // characters of temp_str at end\n    for (int i = 0;\n         i < n / (2 * k); i++) {\n        final_str += (temp_str);\n    }\n\n    for (int i = 0;\n         i < n % (2 * k); i++) {\n        final_str.push_back(temp_str[i]);\n    }\n\n    // Return the final string\n    return final_str;\n}\n\n// Function to reduce the string to\n// length K that follows the given\n// conditions\nstring kReducingString(int n, int k,\n                       string str)\n{\n    // If the string contains either\n    // 0s or 1s then it always be\n    // reduced into a K length string\n    int no_of_zeroes = count_zeroes(n, str);\n\n    int no_of_ones = n - no_of_zeroes;\n\n    // If the string contains only 0s\n    // 1s then it always reduces to\n    // a K length string\n    if (no_of_zeroes == 0\n        || no_of_zeroes == n) {\n        return str;\n    }\n\n    // If K = 1\n    if (k == 1) {\n        if (no_of_zeroes == 0\n            || no_of_zeroes == n) {\n            return str;\n        }\n        else {\n            return "Not Possible";\n        }\n    }\n\n    // Check whether the given string\n    // is K reducing string or not\n    bool check = 0;\n\n    for (int i = (n / k);\n         i < n; i += (n / k)) {\n\n        if (no_of_zeroes == i\n            || no_of_ones == i) {\n            check = 1;\n            break;\n        }\n    }\n\n    if (check == 0) {\n        return "Not Possible";\n    }\n\n    // Otherwise recursively find\n    // the string\n    return kReducingStringUtil(n, k,\n                               str,\n                               no_of_zeroes);\n}\n\n// Driver Code\nint main()\n{\n    string str = "0000100001100001";\n    int K = 4;\n    int N = str.length();\n\n    // Function Call\n    cout << kReducingString(N, K, str);\n\n    return 0;\n}


Given a binary string str of length N, and an integer K, the task is to find the lexicographically smallest permutation of the string str that can be reduced to length K by removal of every K-length prefix from palindromic substrings of length 2K. If no such permutation exists, print "Not Possible".

Input: str = "0000100001100001”, K = 4

Output:
0001100000011000
Explanation: In the string "0001100000011000", every 2K length substring becomes a palindrome whenever a K-length prefix is removed, until string length reduces to K.

// Java program for the above approach\nimport java.io.*;\n\nclass InfobayAI{\n\n// Function to count the number of\n// zeroes present in the string\nstatic int count_zeroes(int n, String str)\n{\n    int cnt = 0;\n    \n    // Traverse the string\n    for(int i = 0; i < str.length(); i++) \n    {\n        if (str.charAt(i) == '0')\n            cnt++;\n    }\n\n    // Return the count\n    return cnt;\n}\n\n// Function to rearrange the string s.t\n// the string can be reduced to a length\n// K as per the given rules\nstatic String kReducingStringUtil(int n, int k, \n                                  String str,\n                                  int no_of_zeroes)\n{\n    \n    // Distribute the count of 0s and\n    // 1s in segment of length 2k\n    int zeroes_in_2k = ((no_of_zeroes) * \n                        (2 * k)) / n;\n\n    int ones_in_2k = 2 * k - zeroes_in_2k;\n\n    // Store string that are initially\n    // have formed lexicographically\n    // smallest 2k length substring\n    String temp_str = "";\n\n    for(int i = 0; i < (zeroes_in_2k) / 2; i++) \n    {\n        temp_str += '0';\n    }\n    for(int i = 0; i < ones_in_2k; i++) \n    {\n        temp_str += '1';\n    }\n    for(int i = 0; i < (zeroes_in_2k) / 2; i++) \n    {\n        temp_str += '0';\n    }\n    \n    // Store the lexicographically\n    // smallest string of length n\n    // that satisfy the condition\n    String final_str = "";\n\n    // Insert temp_str into final_str\n    // (n/2k) times and add (n%2k)\n    // characters of temp_str at end\n    for(int i = 0; i < n / (2 * k); i++) \n    {\n        final_str += (temp_str);\n    }\n\n    for(int i = 0; i < n % (2 * k); i++) \n    {\n        final_str += temp_str.charAt(i);\n    }\n\n    // Return the final string\n    return final_str;\n}\n\n// Function to reduce the string to\n// length K that follows the given\n// conditions\nstatic String kReducingString(int n, int k, \n                              String str)\n{\n    \n    // If the string contains either\n    // 0s or 1s then it always be\n    // reduced into a K length string\n    int no_of_zeroes = count_zeroes(n, str);\n\n    int no_of_ones = n - no_of_zeroes;\n\n    // If the string contains only 0s\n    // 1s then it always reduces to\n    // a K length string\n    if (no_of_zeroes == 0 || \n        no_of_zeroes == n) \n    {\n        return str;\n    }\n\n    // If K = 1\n    if (k == 1) \n    {\n        if (no_of_zeroes == 0 || \n            no_of_zeroes == n)\n        {\n            return str;\n        }\n        else\n        {\n            return "Not Possible";\n        }\n    }\n\n    // Check whether the given string\n    // is K reducing string or not\n    boolean check = false;\n\n    for(int i = (n / k); i < n; i += (n / k)) \n    {\n        if (no_of_zeroes == i || \n            no_of_ones == i)\n        {\n            check = true;\n            break;\n        }\n    }\n\n    if (check == false)\n    {\n        return "Not Possible";\n    }\n\n    // Otherwise recursively find\n    // the string\n    return kReducingStringUtil(n, k, str,\n                               no_of_zeroes);\n}\n\n// Driver Code\npublic static void main(String[] args)\n{\n    String str = "0000100001100001";\n    int K = 4;\n    int N = str.length();\n\n    // Function Call\n    System.out.println(kReducingString(N, K, str));\n}\n}\n\n


Given a binary string str of length N, and an integer K, the task is to find the lexicographically smallest permutation of the string str that can be reduced to length K by removal of every K-length prefix from palindromic substrings of length 2K. If no such permutation exists, print "Not Possible".

Input: str = "0000100001100001”, K = 4

Output:
0001100000011000
Explanation: In the string "0001100000011000", every 2K length substring becomes a palindrome whenever a K-length prefix is removed, until string length reduces to K.

# Python3 program for the above approach\n\n# Function to count the number of\n# zeroes present in the string\ndef count_zeroes(n, str):\n  \n  cnt = 0\n\n  # Traverse the string\n  for i in range(0, len(str)):\n    if (str[i] == '0'):\n      cnt += 1\n      \n  # Return the count\n  return cnt\n\n# Function to rearrange the string s.t\n# the string can be reduced to a length\n# K as per the given rules\ndef kReducingStringUtil(n, k, str, \n                        no_of_zeroes):\n  \n  # Distribute the count of 0s and\n  # 1s in segment of length 2k\n  zeroes_in_2k = (((no_of_zeroes) * \n                   (2 * k)) // n)\n\n  ones_in_2k = 2 * k - zeroes_in_2k\n\n  # Store string that are initially\n  # have formed lexicographically\n  # smallest 2k length substring\n  temp_str = ""\n\n  for i in range(0, (zeroes_in_2k) // 2):\n    temp_str += '0'\n    \n  for i in range(0, (ones_in_2k)):\n    temp_str += '1'\n  \n  for i in range(0, (zeroes_in_2k) // 2):\n    temp_str += '0'\n    \n  # Store the lexicographically\n  # smallest string of length n\n  # that satisfy the condition\n  final_str = ""\n\n  # Insert temp_str into final_str\n  # (n/2k) times and add (n%2k)\n  # characters of temp_str at end\n  for i in range(0, n // (2 * k)):\n    final_str += (temp_str)\n\n  for i in range(0, n % (2 * k)):\n    final_str += (temp_str[i])\n    \n  # Return the final string\n  return final_str\n\n# Function to reduce the string to\n# length K that follows the given\n# conditions\ndef kReducingString(n, k, str):\n  \n  # If the string contains either\n  # 0s or 1s then it always be\n  # reduced into a K length string\n  no_of_zeroes = count_zeroes(n, str)\n\n  no_of_ones = n - no_of_zeroes\n\n  # If the string contains only 0s\n  # 1s then it always reduces to\n  # a K length string\n  if (no_of_zeroes == 0 or \n      no_of_zeroes == n):\n    return str\n\n  # If K = 1\n  if (k == 1):\n    if (no_of_zeroes == 0 or \n        no_of_zeroes == n):\n      return str\n    else:\n      return "Not Possible"\n    \n  # Check whether the given string\n  # is K reducing string or not\n  check = 0\n\n  for i in range((n // k), n, (n // k)):\n    if (no_of_zeroes == i or no_of_ones == i):\n      check = 1\n      break\n      \n  if (check == 0):\n    return "Not Possible"\n\n  # Otherwise recursively find\n  # the string\n  return kReducingStringUtil(n, k, str, \n                             no_of_zeroes)\n\n# Driver Code\nif __name__ == '__main__':\n  \n  str = "0000100001100001"\n  K = 4;\n  N = len(str)\n\n  # Function Call\n  print(kReducingString(N, K, str))\n  \n


Given a binary string str of length N, and an integer K, the task is to find the lexicographically smallest permutation of the string str that can be reduced to length K by removal of every K-length prefix from palindromic substrings of length 2K. If no such permutation exists, print "Not Possible".

Input: str = "100111", K = 2

Output: "Not Possible"

// C++ program for the above approach\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n// Function to count the number of\n// zeroes present in the string\nint count_zeroes(int n, string str)\n{\n    int cnt = 0;\n\n    // Traverse the string\n    for (int i = 0; i < str.size(); i++) {\n        if (str[i] == '0')\n            cnt++;\n    }\n\n    // Return the count\n    return cnt;\n}\n\n// Function to rearrange the string s.t\n// the string can be reduced to a length\n// K as per the given rules\nstring kReducingStringUtil(\n    int n, int k, string str,\n    int no_of_zeroes)\n{\n\n    // Distribute the count of 0s and\n    // 1s in segment of length 2k\n    int zeroes_in_2k = ((no_of_zeroes)\n                        * (2 * k))\n                       / n;\n\n    int ones_in_2k = 2 * k - zeroes_in_2k;\n\n    // Store string that are initially\n    // have formed lexicographically\n    // smallest 2k length substring\n    string temp_str = "";\n\n    for (int i = 0;\n         i < (zeroes_in_2k) / 2; i++) {\n        temp_str.push_back('0');\n    }\n    for (int i = 0; i < ones_in_2k; i++) {\n        temp_str.push_back('1');\n    }\n    for (int i = 0;\n         i < (zeroes_in_2k) / 2; i++) {\n        temp_str.push_back('0');\n    }\n\n    // Store the lexicographically\n    // smallest string of length n\n    // that satisfy the condition\n    string final_str = "";\n\n    // Insert temp_str into final_str\n    // (n/2k) times and add (n%2k)\n    // characters of temp_str at end\n    for (int i = 0;\n         i < n / (2 * k); i++) {\n        final_str += (temp_str);\n    }\n\n    for (int i = 0;\n         i < n % (2 * k); i++) {\n        final_str.push_back(temp_str[i]);\n    }\n\n    // Return the final string\n    return final_str;\n}\n\n// Function to reduce the string to\n// length K that follows the given\n// conditions\nstring kReducingString(int n, int k,\n                       string str)\n{\n    // If the string contains either\n    // 0s or 1s then it always be\n    // reduced into a K length string\n    int no_of_zeroes = count_zeroes(n, str);\n\n    int no_of_ones = n - no_of_zeroes;\n\n    // If the string contains only 0s\n    // 1s then it always reduces to\n    // a K length string\n    if (no_of_zeroes == 0\n        || no_of_zeroes == n) {\n        return str;\n    }\n\n    // If K = 1\n    if (k == 1) {\n        if (no_of_zeroes == 0\n            || no_of_zeroes == n) {\n            return str;\n        }\n        else {\n            return "Not Possible";\n        }\n    }\n\n    // Check whether the given string\n    // is K reducing string or not\n    bool check = 0;\n\n    for (int i = (n / k);\n         i < n; i += (n / k)) {\n\n        if (no_of_zeroes == i\n            || no_of_ones == i) {\n            check = 1;\n            break;\n        }\n    }\n\n    if (check == 0) {\n        return "Not Possible";\n    }\n\n    // Otherwise recursively find\n    // the string\n    return kReducingStringUtil(n, k,\n                               str,\n                               no_of_zeroes);\n}\n\n// Driver Code\nint main()\n{\n    string str = "0000100001100001";\n    int K = 4;\n    int N = str.length();\n\n    // Function Call\n    cout << kReducingString(N, K, str);\n\n    return 0;\n}


Given a binary string str of length N, and an integer K, the task is to find the lexicographically smallest permutation of the string str that can be reduced to length K by removal of every K-length prefix from palindromic substrings of length 2K. If no such permutation exists, print "Not Possible".

Input: str = "100111", K = 2

Output: "Not Possible"

// Java program for the above approach\nimport java.io.*;\n\nclass InfobayAI{\n\n// Function to count the number of\n// zeroes present in the string\nstatic int count_zeroes(int n, String str)\n{\n    int cnt = 0;\n    \n    // Traverse the string\n    for(int i = 0; i < str.length(); i++) \n    {\n        if (str.charAt(i) == '0')\n            cnt++;\n    }\n\n    // Return the count\n    return cnt;\n}\n\n// Function to rearrange the string s.t\n// the string can be reduced to a length\n// K as per the given rules\nstatic String kReducingStringUtil(int n, int k, \n                                  String str,\n                                  int no_of_zeroes)\n{\n    \n    // Distribute the count of 0s and\n    // 1s in segment of length 2k\n    int zeroes_in_2k = ((no_of_zeroes) * \n                        (2 * k)) / n;\n\n    int ones_in_2k = 2 * k - zeroes_in_2k;\n\n    // Store string that are initially\n    // have formed lexicographically\n    // smallest 2k length substring\n    String temp_str = "";\n\n    for(int i = 0; i < (zeroes_in_2k) / 2; i++) \n    {\n        temp_str += '0';\n    }\n    for(int i = 0; i < ones_in_2k; i++) \n    {\n        temp_str += '1';\n    }\n    for(int i = 0; i < (zeroes_in_2k) / 2; i++) \n    {\n        temp_str += '0';\n    }\n    \n    // Store the lexicographically\n    // smallest string of length n\n    // that satisfy the condition\n    String final_str = "";\n\n    // Insert temp_str into final_str\n    // (n/2k) times and add (n%2k)\n    // characters of temp_str at end\n    for(int i = 0; i < n / (2 * k); i++) \n    {\n        final_str += (temp_str);\n    }\n\n    for(int i = 0; i < n % (2 * k); i++) \n    {\n        final_str += temp_str.charAt(i);\n    }\n\n    // Return the final string\n    return final_str;\n}\n\n// Function to reduce the string to\n// length K that follows the given\n// conditions\nstatic String kReducingString(int n, int k, \n                              String str)\n{\n    \n    // If the string contains either\n    // 0s or 1s then it always be\n    // reduced into a K length string\n    int no_of_zeroes = count_zeroes(n, str);\n\n    int no_of_ones = n - no_of_zeroes;\n\n    // If the string contains only 0s\n    // 1s then it always reduces to\n    // a K length string\n    if (no_of_zeroes == 0 || \n        no_of_zeroes == n) \n    {\n        return str;\n    }\n\n    // If K = 1\n    if (k == 1) \n    {\n        if (no_of_zeroes == 0 || \n            no_of_zeroes == n)\n        {\n            return str;\n        }\n        else\n        {\n            return "Not Possible";\n        }\n    }\n\n    // Check whether the given string\n    // is K reducing string or not\n    boolean check = false;\n\n    for(int i = (n / k); i < n; i += (n / k)) \n    {\n        if (no_of_zeroes == i || \n            no_of_ones == i)\n        {\n            check = true;\n            break;\n        }\n    }\n\n    if (check == false)\n    {\n        return "Not Possible";\n    }\n\n    // Otherwise recursively find\n    // the string\n    return kReducingStringUtil(n, k, str,\n                               no_of_zeroes);\n}\n\n// Driver Code\npublic static void main(String[] args)\n{\n    String str = "0000100001100001";\n    int K = 4;\n    int N = str.length();\n\n    // Function Call\n    System.out.println(kReducingString(N, K, str));\n}\n}\n\n


Given a binary string str of length N, and an integer K, the task is to find the lexicographically smallest permutation of the string str that can be reduced to length K by removal of every K-length prefix from palindromic substrings of length 2K. If no such permutation exists, print "Not Possible".

Input: str = "100111", K = 2

Output: "Not Possible"

# Python3 program for the above approach\n\n# Function to count the number of\n# zeroes present in the string\ndef count_zeroes(n, str):\n  \n  cnt = 0\n\n  # Traverse the string\n  for i in range(0, len(str)):\n    if (str[i] == '0'):\n      cnt += 1\n      \n  # Return the count\n  return cnt\n\n# Function to rearrange the string s.t\n# the string can be reduced to a length\n# K as per the given rules\ndef kReducingStringUtil(n, k, str, \n                        no_of_zeroes):\n  \n  # Distribute the count of 0s and\n  # 1s in segment of length 2k\n  zeroes_in_2k = (((no_of_zeroes) * \n                   (2 * k)) // n)\n\n  ones_in_2k = 2 * k - zeroes_in_2k\n\n  # Store string that are initially\n  # have formed lexicographically\n  # smallest 2k length substring\n  temp_str = ""\n\n  for i in range(0, (zeroes_in_2k) // 2):\n    temp_str += '0'\n    \n  for i in range(0, (ones_in_2k)):\n    temp_str += '1'\n  \n  for i in range(0, (zeroes_in_2k) // 2):\n    temp_str += '0'\n    \n  # Store the lexicographically\n  # smallest string of length n\n  # that satisfy the condition\n  final_str = ""\n\n  # Insert temp_str into final_str\n  # (n/2k) times and add (n%2k)\n  # characters of temp_str at end\n  for i in range(0, n // (2 * k)):\n    final_str += (temp_str)\n\n  for i in range(0, n % (2 * k)):\n    final_str += (temp_str[i])\n    \n  # Return the final string\n  return final_str\n\n# Function to reduce the string to\n# length K that follows the given\n# conditions\ndef kReducingString(n, k, str):\n  \n  # If the string contains either\n  # 0s or 1s then it always be\n  # reduced into a K length string\n  no_of_zeroes = count_zeroes(n, str)\n\n  no_of_ones = n - no_of_zeroes\n\n  # If the string contains only 0s\n  # 1s then it always reduces to\n  # a K length string\n  if (no_of_zeroes == 0 or \n      no_of_zeroes == n):\n    return str\n\n  # If K = 1\n  if (k == 1):\n    if (no_of_zeroes == 0 or \n        no_of_zeroes == n):\n      return str\n    else:\n      return "Not Possible"\n    \n  # Check whether the given string\n  # is K reducing string or not\n  check = 0\n\n  for i in range((n // k), n, (n // k)):\n    if (no_of_zeroes == i or no_of_ones == i):\n      check = 1\n      break\n      \n  if (check == 0):\n    return "Not Possible"\n\n  # Otherwise recursively find\n  # the string\n  return kReducingStringUtil(n, k, str, \n                             no_of_zeroes)\n\n# Driver Code\nif __name__ == '__main__':\n  \n  str = "0000100001100001"\n  K = 4;\n  N = len(str)\n\n  # Function Call\n  print(kReducingString(N, K, str))\n  \n