VOOZH about

URL: https://www.geeksforgeeks.org/dsa/largest-prime-number-possible-from-a-subsequence-of-a-binary-string/

⇱ Largest Prime Number possible from a subsequence of a Binary String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Largest Prime Number possible from a subsequence of a Binary String

Last Updated : 23 Jul, 2025

Given a Binary string, the task is to find the largest Prime Number possible by the decimal representation of a subsequence of the given binary string. If no prime number can be obtained, print -1.

Examples:

Input: S = "1001"
Output:
Explanation: Out of all subsequences of the string "1001", the largest prime number that can be obtained is "101" (= 5).

Input: "1011"
Output: 11 
Explanation: Out of all subsequences of the string "1011", the largest prime number that can be obtained is "1011" (= 11).

Approach:  To solve the problem, the idea is to generate all possible subsequences of the string, and convert each subsequence to its equivalent decimal form. Print the largest prime number obtained from this subsequences. 

Follow the steps below to solve this problem:

  • Initialize a vector of pairs, say vec, for storing pairs of strings and their equivalent decimal values, in Pair.first and Pair.second respectively.
  • Initialize a variable, say ans, to store the required answer.
  • Iterate a loop from i = 0 to length of the string s:
    • Iterate a loop from j = 0 to the length of vec:
      • Store the jth pair in temp.
      • If the ith character of string s is '1':
        • Add the character in temp.first.
        • Update the value of temp.second by left shifting the current value and adding 1 to it.
      • Otherwise:
        • Add the character in temp.first.
        • Update the value of temp.second by left shifting the current value and adding 0 to it.
      • Store this temp pair into vec.
      • If the temp.second is prime:
        • Store max of ans and temp.second in ans.
    • If ans is equal to 0:
      • No prime number can be obtained from the string s.
    • Otherwise:
      • Print ans.

Below is the implementation of the above approach:


Output: 
3

 

Time Complexity: O(2N * ?N), where N is the length of the string.
Auxiliary Space: O(2N * N)


 

Comment