Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Split the given string into Odds: Digit DP

  • Last Updated : 19 May, 2021

Prerequisites: Digit-DP 
Given string str that represents a large number, the task is to find the minimum number of segments the given string can be divided such that each segment is an odd number in the range of 1 to 109.
Examples: 
 

Input: str = “123456789123456789123” 
Output:
Explanation: 
The number can be divided as {123456789, 123456789, 123}
Input: str = “123456” 
Output: -1 
Explanation: 
We can’t split the given number such that all segments are odd. 
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

 



Approach: The idea is to use dynamic programming with the help of digit-dp concept to solve this problem. Therefore, a splitDP[] array is defined where splitDP[i] denotes the minimum number of splits required in the prefix string of length ‘i’ to break it into the odd subdivision. 
The splitDP[] array is filled in the following way: 
 

  • A loop is used to iterate through all the indices of the given string.
  • For every index ‘i’ from the above loop, another loop is iterated from 1 to 9 to check if the substring from (i + j)th index is Odd or not.
  • If it forms a Odd number, then the value at splitDP[] is updated as:
    splitDP[i + j] = min(splitDP[i + j], 1 + splitDP[i]);
  • After updating all the values of the array, the value at the last index is the minimum number of splits for the entire string.

Below is the implementation of the above approach:
 

C++




// C++ program to split the given string into odds
#include <bits/stdc++.h>
using namespace std;
  
// Function to check whether a string
// is an odd number or not
bool checkOdd(string number)
{
    int n = number.length();
  
    int num = number[n - 1] - '0';
  
    return (num & 1);
}
  
// A function to find the minimum
// number of segments the given string
// can be divided such that every
// segment is a odd number
int splitIntoOdds(string number)
{
    int numLen = number.length();
  
    // Declare a splitdp[] array
    // and initialize to -1
    int splitDP[numLen + 1];
    memset(splitDP, -1, sizeof(splitDP));
  
    // Build the DP table in
    // a bottom-up manner
    for (int i = 1; i <= numLen; i++) {
  
        // Initially Check if the entire prefix is odd
        if (i <= 9 && checkOdd(number.substr(0, i)))
            splitDP[i] = 1;
  
        // If the Given Prefix can be split into Odds
        // then for the remaining string from i to j
        // Check if Odd. If yes calculate
        // the minimum split till j
        if (splitDP[i] != -1) {
            for (int j = 1; j <= 9
                            && i + j <= numLen;
                 j++) {
  
                // To check if the substring from i to j
                // is a odd number or not
                if (checkOdd(number.substr(i, j))) {
  
                    // If it is an odd number,
                    // then update the dp array
                    if (splitDP[i + j] == -1)
                        splitDP[i + j] = 1 + splitDP[i];
  
                    else
                        splitDP[i + j] = min(splitDP[i + j],
                                             1 + splitDP[i]);
                }
            }
        }
    }
  
    // Return the minimum number of splits
    // for the entire string
    return splitDP[numLen];
}
  
// Driver code
int main()
{
    cout << splitIntoOdds("123456789123456789123") << "\n";
    return 0;
}

Java




// Java program to split the given string into odds 
class GFG {
  
    // Function to check whether a string 
    // is an odd number or not 
    static int checkOdd(String number) 
    
        int n = number.length(); 
      
        int num = number.charAt(n - 1) - '0'
      
        return (num & 1); 
    
  
    // A function to find the minimum 
    // number of segments the given string 
    // can be divided such that every 
    // segment is a odd number 
    static int splitIntoOdds(String number) 
    
        int numLen = number.length(); 
      
        // Declare a splitdp[] array 
        // and initialize to -1 
        int splitDP[] = new int[numLen + 1]; 
          
        for(int i= 0; i < numLen + 1; i++)
            splitDP[i] = -1;
              
        // Build the DP table in 
        // a bottom-up manner 
        for (int i = 1; i <= numLen; i++) { 
      
            // Initially Check if the entire prefix is odd 
            if (i <= 9 && (checkOdd(number.substring(0, i)) == 1)) 
                splitDP[i] = 1
      
            // If the Given Prefix can be split into Odds 
            // then for the remaining string from i to j 
            // Check if Odd. If yes calculate 
            // the minimum split till j 
            if (splitDP[i] != -1) { 
                for (int j = 1; j <= 9 
                                && i + j <= numLen; 
                    j++) { 
      
                    // To check if the substring from i to j 
                    // is a odd number or not 
                    if (checkOdd(number.substring(i, i + j)) == 1) { 
      
                        // If it is an odd number, 
                        // then update the dp array 
                        if (splitDP[i + j] == -1
                            splitDP[i + j] = 1 + splitDP[i]; 
      
                        else
                            splitDP[i + j] = Math.min(splitDP[i + j], 
                                                1 + splitDP[i]); 
                    
                
            
        
      
        // Return the minimum number of splits 
        // for the entire string 
        return splitDP[numLen]; 
    
      
    // Driver code 
    public static void main (String[] args)
    
        System.out.println(splitIntoOdds("123456789123456789123")); 
    
}
  
// This code is contributed by AnkitRai01

Python3




# Python3 program to split the given string into odds 
  
# Function to check whether a string 
# is an odd number or not 
def checkOdd(number):
    n = len(number)
    num = ord(number[n - 1]) - 48
    return (num & 1)
  
# A function to find the minimum 
# number of segments the given string 
# can be divided such that every 
# segment is a odd number 
def splitIntoOdds(number): 
    numLen = len(number)
      
    # Declare a splitdp[] array 
    # and initialize to -1 
    splitDP = [-1 for i in range(numLen + 1)] 
  
    # Build the DP table in 
    # a bottom-up manner 
    for i in range(1, numLen + 1): 
  
        # Initially Check if the entire prefix is odd 
        if (i <= 9 and checkOdd(number[0:i]) > 0): 
            splitDP[i] = 1
  
        # If the Given Prefix can be split into Odds 
        # then for the remaining string from i to j 
        # Check if Odd. If yes calculate 
        # the minimum split till j 
        if (splitDP[i] != -1):
            for j in range(1, 10):
                if(i + j > numLen):
                    break;
  
                # To check if the substring from i to j 
                # is a odd number or not 
                if (checkOdd(number[i:i + j])):
                      
                    # If it is an odd number, 
                    # then update the dp array 
                    if (splitDP[i + j] == -1):
                        splitDP[i + j] = 1 + splitDP[i] 
                    else:
                        splitDP[i + j] = min(splitDP[i + j], 1 + splitDP[i])
  
    # Return the minimum number of splits 
    # for the entire string 
    return splitDP[numLen]
  
# Driver code 
print(splitIntoOdds("123456789123456789123"))
  
# This code is contributed by Sanjit_Prasad

C#




// C# program to split the given string into odds 
using System;
  
class GFG { 
  
    // Function to check whether a string 
    // is an odd number or not 
    static int checkOdd(string number) 
    
        int n = number.Length; 
      
        int num = number[n - 1] - '0'
      
        return (num & 1); 
    
  
    // A function to find the minimum 
    // number of segments the given string 
    // can be divided such that every 
    // segment is a odd number 
    static int splitIntoOdds(string number) 
    
        int numLen = number.Length; 
      
        // Declare a splitdp[] array 
        // and initialize to -1 
        int []splitDP = new int[numLen + 1]; 
          
        for(int i= 0; i < numLen + 1; i++) 
            splitDP[i] = -1; 
              
        // Build the DP table in 
        // a bottom-up manner 
        for (int i = 1; i <= numLen; i++) { 
      
            // Initially Check if the entire prefix is odd 
            if (i <= 9 && (checkOdd(number.Substring(0, i)) == 1)) 
                splitDP[i] = 1; 
      
            // If the Given Prefix can be split into Odds 
            // then for the remaining string from i to j 
            // Check if Odd. If yes calculate 
            // the minimum split till j 
            if (splitDP[i] != -1) { 
                for (int j = 1; j <= 9
                                && i + j <= numLen; 
                    j++) { 
      
                    // To check if the substring from i to j 
                    // is a odd number or not 
                    if (checkOdd(number.Substring(i, j)) == 1) { 
      
                        // If it is an odd number, 
                        // then update the dp array 
                        if (splitDP[i + j] == -1) 
                            splitDP[i + j] = 1 + splitDP[i]; 
      
                        else
                            splitDP[i + j] = Math.Min(splitDP[i + j], 
                                                1 + splitDP[i]); 
                    
                
            
        
      
        // Return the minimum number of splits 
        // for the entire string 
        return splitDP[numLen]; 
    
      
    // Driver code 
    public static void Main (string[] args) 
    
        Console.WriteLine(splitIntoOdds("123456789123456789123")); 
    
  
// This code is contributed by AnkitRai01 

Javascript




<script>
  
// JavaScript program to split the
// given string into odds 
  
    // Function to check whether a string 
    // is an odd number or not 
    function checkOdd(number) 
    
        let n = number.length; 
      
        let num = number[n - 1] - '0'
      
        return (num & 1); 
    
  
    // A function to find the minimum 
    // number of segments the given string 
    // can be divided such that every 
    // segment is a odd number 
    function splitLetoOdds(number) 
    
        let numLen = number.length; 
      
        // Declare a splitdp[] array 
        // and initialize to -1 
        let splitDP = 
        Array.from({length: numLen + 1}, (_, i) => 0);
          
        for(let i= 0; i < numLen + 1; i++)
            splitDP[i] = -1;
              
        // Build the DP table in 
        // a bottom-up manner 
        for (let i = 1; i <= numLen; i++) 
        
      
            // Initially Check if the
            // entire prefix is odd 
            if (i <= 9 &&
            (checkOdd(number.substr(0, i)) == 1)) 
                splitDP[i] = 1; 
      
            // If the Given Prefix can 
            // be split leto Odds 
            // then for the remaining
            // string from i to j 
            // Check if Odd.
            // If yes calculate 
            // the minimum split till j 
            if (splitDP[i] != -1) { 
                for (let j = 1; j <= 9 
                      && i + j <= numLen; j++) { 
      
                 // To check if the 
                // substring from i to j 
               // is a odd number or not 
                 if (checkOdd(number.substr(i, i + j)) == 1)
                    
      
                  // If it is an odd number, 
                 // then update the dp array 
                   if (splitDP[i + j] == -1) 
                       splitDP[i + j] = 1 + splitDP[i]; 
      
                        else
                            splitDP[i + j] = 
                            Math.min(splitDP[i + j], 
                                        1 + splitDP[i]); 
                    
                
            
        
      
        // Return the minimum number of splits 
        // for the entire string 
        return splitDP[numLen]; 
    
  
// Driver code
  
    document.write(splitLetoOdds("123456789123456789123")); 
  
</script>
Output: 
3

 

Time Complexity: O(N)
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :