Software Development

Verify if String could be divided into two Subsequences in order that product of sum is odd

Verify if String could be divided into two Subsequences in order that product of sum is odd
Written by admin


Enhance Article

Save Article

Like Article

Enhance Article

Save Article

Given a string S of size N, the duty is to test whether or not it’s attainable to partition the string S into two disjoint non-empty subsequences S1 and S2 such that sum(S1) × sum(S2) is odd and each character of S should be in both S2 and S1.

Examples:

Enter: S = “1122”
Output: Sure

Clarification: We partition the string into two subsequences .Let S1 be the underlined components and S2 be the opposite ones. sum(S1) × sum(S2) = 3 × 3 = 9.

Enter: S = “135”
Output: No

Method: The issue could be solved primarily based on the next remark:

To make the product of two numbers odd, each numbers must be odd. So, the sum of S1 and S2 should be odd. That is solely attainable when every of them has odd variety of odd integers. If the string has even quantity (besides 0) of wierd digits then solely such a partition is posisble. 

This satisfies that the sum of S may even be even and there will probably be atleast 2 odd numbers.

Observe the steps talked about beneath to implement the concept:

  • Traverse by the string S.
  • Verify if the sum is even and the variety of odd digits is at the least 2.
    • If the situation is happy, the partition is feasible.
    • In any other case, the partition just isn’t attainable.

Beneath is the implementation of the above strategy.

Java

  

import java.io.*;

import java.util.*;

  

public class GFG {

  

    

    

    

    

    public static String test(String S, int n)

    {

        int[] arr = new int[n];

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

            arr[i] = S.charAt(i) - '0';

        }

        int S1 = 0;

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

            if ((arr[i] & 1) != 0)

                S1++;

  

        if ((S1 & 1) != 0 || S1 == 0)

            return "No";

        return "Sure";

    }

  

    

    public static void major(String[] args)

    {

        String S = "1122";

        int N = S.size();

  

        

        System.out.println(test(S, N));

    }

}

Time Complexity: O(N)
Auxiliary Area: O(1)

Associated Articles:

About the author

admin

Leave a Comment