Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Count of strictly increasing N-digit numbers
Next article icon

Count ways to partition a number into increasing sequences of digits

Last Updated : 20 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a numeric string S, the task is to find the number of ways to partition a string into substrings consisting of digits in increasing order.

Examples:

Input: S = “1345”
Output: 5
Explanation: Possible partitions are as follows: 

  1. [1345]
  2. [13, 45], [1, 345]
  3. [1, 3, 45]
  4. [1, 3, 4, 5]

Input: S = “12”
Output: 2

Approach: This problem can be solved by observing that between each digit either it will be a part of the previous number or it will be a new number so to solve the problem recursion can be used. Follow the steps below to solve the problem:

  • Initialize an integer variable, say count as 0, to store the number of ways to partition a string into increasing subsets.
  • Declare a function print() with index(storing current position), string S(given string in the question), and string ans( as parameters.
  • Now, following two cases are required to be considered: 
    • If S[index] is inserted in the previous number, then append S[index] at the end of ans and recall the function print() with parameters index + 1, S, and ans.
    • If S[index] is not a part of the previous number, then append ” “(space) at the end of ans and then insert S[index] and recall the function print() with parameters index + 1, S, ans.
  • If index = S.length(), then check if  the digits in the sequences formed are in increasing order or not. If the sequences formed are increasing, increase count by 1.
  • Print count as the answer after performing the above steps.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include<bits/stdc++.h>
using namespace std;
 
// Stores the number of ways
// to partition a string
int count1 = 0;
vector<string> split(string str)
{
    vector<string> ans;
    string word = "";
    for(auto x : str)
    {
        if (x == ' ')
        {
            ans.push_back(word);
            word = "";
        }
        else
        {
            word = word + x;
        }
    }
    ans.push_back(word);
    return ans;
}
 
// Function to check if a sequence
// is strictly increasing or not
bool check(string m)
{
     
    // If there is only one number
    if (m.length() == 1)
    {
        return true;
    }
     
    // Split the string m when there is space
    vector<string> temp = split(m);
    int number[temp.size()];
     
    // Insert all the splits into the array
    for(int i = 0; i < temp.size(); ++i)
    {
        number[i] = stoi(temp[i]);
    }
     
    int first = number[0];
    for(int i = 1; i < temp.size(); ++i)
    {
        if (number[i] > first)
        {
            first = number[i];
        }
        else
        {
             
            // If number is not increasing
            return false;
        }
    }
     
    // If the sequence is increasing
    return true;
}
 
// Recursive function to partition
// a string in every possible substrings
void print1(string m, int index, string ans)
{
     
    // If index = m.length, check if ans
    // forms an increasing sequence or not
    if (index == m.length())
    {
     
        if (check(ans))
        {
         
            // Increment count by 1,
            // if sequence is increasing
            count1++;
        }
        return;
    }  
 
    // If S[index] is appended to previous number
    print1(m, index + 1, ans + m[index]);
     
    if (index != 0)
     
        // If S[index] is starting a new number
        print1(m, index + 1,
              ans + " " + m[index]);
}
 
// Driver Code
int main()
{
     
    // Given Input
    string k = "1345";
     
    // Function Call
    print1(k, 0, "");
     
    // Print the answer.
    cout << count1;
}
 
// This code is contributed by ipg2016107
 
 

Java




// Java program for the above approach
 
import java.io.*;
import java.util.*;
class GFG {
 
    // Stores the number of ways
    // to partition a string
    static int count = 0;
 
    // Function to check if a sequence
    // is strictly increasing or not
    static boolean check(String m)
    {
        // If there is only one number
        if (m.length() == 1) {
            return true;
        }
 
        // Split the string m when there is space
        String temp[] = m.split(" ");
        int number[] = new int[temp.length];
 
        // Insert all the splits into the array
        for (int i = 0; i < temp.length; ++i) {
 
            number[i] = Integer.parseInt(temp[i]);
        }
 
        int first = number[0];
        for (int i = 1; i < number.length; ++i) {
 
            if (number[i] > first) {
                first = number[i];
            }
            else {
 
                // If number is not increasing
                return false;
            }
        }
 
        // If the sequence is increasing
        return true;
    }
 
    // Recursive function to partition
    // a string in every possible substrings
    static void print(String m,
                      int index, String ans)
    {
        // If index = m.length, check if ans
        // forms an increasing sequence or not
        if (index == m.length()) {
 
            if (check(ans)) {
 
                // Increment count by 1,
                // if sequence is increasing
                ++count;
            }
            return;
        }
 
        // If S[index] is appended to previous number
        print(m, index + 1, ans + m.charAt(index));
        if (index != 0)
            // If S[index] is starting a new number
            print(m, index + 1,
                  ans + " " + m.charAt(index));
    }
 
    // DriverCode
    public static void main(String[] args)
    {
        // Given Input
        String k = Integer.toString(1345);
 
        // Function Call
        print(k, 0, "");
 
        // Print the answer.
        System.out.println(count);
    }
}
 
 

Python3




# Python3 program for the above approach
count = 0
  
# Function to check if a sequence
# is strictly increasing or not
def check(m):
   
    # If there is only one number
    if (len(m) == 1):
        return True
 
    # Split the string m when there is space
    temp = m.split(" ")
    number = [0]*(len(temp))
 
    # Insert all the splits into the array
    for i in range(len(temp)):
        number[i] = int(temp[i])
 
    first = number[0]
    for i in range(1, len(number)):
        if (number[i] > first):
            first = number[i]
        else:
            # If number is not increasing
            return False
    # If the sequence is increasing
    return True
 
# Recursive function to partition
# a string in every possible substrings
def Print(m, index, ans):
    global count
     
    # If index = m.length, check if ans
    # forms an increasing sequence or not
    if (index == len(m)):
        if (check(ans)):
           
            # Increment count by 1,
            # if sequence is increasing
            count+=1
        return
 
    # If S[index] is appended to previous number
    Print(m, index + 1, ans + m[index])
    if (index != 0):
       
        # If S[index] is starting a new number
        Print(m, index + 1, ans + " " + m[index])
 
# Given Input
k = "1345"
  
# Function Call
Print(k, 0, "")
  
# Print the answer.
print(count)
 
# This code is contributed by suresh07.
 
 

C#




using System;
 
public class GFG {
    static int count = 0;
 
    // Function to check if a sequence
    // is strictly increasing or not
    static bool check(String m)
    {
        // If there is only one number
        if (m.Length == 1) {
            return true;
        }
 
        // Split the string m when there is space
        String[] temp = m.Split(" ");
        int[] number = new int[temp.Length];
 
        // Insert all the splits into the array
        for (int i = 0; i < temp.Length; ++i) {
 
            number[i] = int.Parse(temp[i]);
        }
 
        int first = number[0];
        for (int i = 1; i < number.Length; ++i) {
 
            if (number[i] > first) {
                first = number[i];
            }
            else {
 
                // If number is not increasing
                return false;
            }
        }
 
        // If the sequence is increasing
        return true;
    }
 
    // Recursive function to partition
    // a string in every possible substrings
    static void print(String m, int index, String ans)
    {
        // If index = m.length, check if ans
        // forms an increasing sequence or not
        if (index == m.Length) {
 
            if (check(ans)) {
 
                // Increment count by 1,
                // if sequence is increasing
                ++count;
            }
            return;
        }
 
        // If S[index] is appended to previous number
        print(m, index + 1, ans + m[index]);
        if (index != 0)
            // If S[index] is starting a new number
            print(m, index + 1, ans + " " + m[index]);
    }
    static public void Main()
    {
 
        String k = "1345";
 
        // Function Call
        print(k, 0, "");
 
        // Print the answer.
        Console.WriteLine(count);
    }
}
 
// This code is contributed by maddler.
 
 

Javascript




<script>
 
// JavaScript program for the above approach
 
// Stores the number of ways
// to partition a string
let count = 0;
 
// Function to check if a sequence
// is strictly increasing or not
function check(m)
{
     
    // If there is only one number
    if (m.length == 1)
    {
        return true;
    }
 
    // Split the string m when there is space
    let temp = m.split(" ");
    let number = new Array(temp.length);
 
    // Insert all the splits into the array
    for(let i = 0; i < temp.length; ++i)
    {
        number[i] = parseInt(temp[i]);
    }
     
    let first = number[0];
    for(let i = 1; i < number.length; ++i)
    {
        if (number[i] > first)
        {
            first = number[i];
        }
        else
        {
             
            // If number is not increasing
            return false;
        }
    }
     
    // If the sequence is increasing
    return true;
}
 
// Recursive function to partition
// a string in every possible substrings
function print(m, index, ans)
{
     
    // If index = m.length, check if ans
    // forms an increasing sequence or not
    if (index == m.length)
    {
        if (check(ans))
        {
             
            // Increment count by 1,
            // if sequence is increasing
            ++count;
        }
        return;
    }
 
    // If S[index] is appended to previous number
    print(m, index + 1, ans + m[index]);
     
    if (index != 0)
     
        // If S[index] is starting a new number
        print(m, index + 1,
              ans + " " + m[index]);
}
 
// Driver Code
 
// Given Input
let k = "1345";
 
// Function Call
print(k, 0, "");
 
// Print the answer.
document.write(count);
 
// This code is contributed by code_hunt
 
</script>
 
 
Output: 
5

 

Time Complexity: O(N*2N) where N is the length of string S
Auxiliary Space: O(1)

 



Next Article
Count of strictly increasing N-digit numbers
author
zack_aayush
Improve
Article Tags :
  • DSA
  • Mathematical
  • Recursion
  • Strings
  • number-digits
  • partition
  • subsequence
  • substring
Practice Tags :
  • Mathematical
  • Recursion
  • Strings

Similar Reads

  • Count of strictly increasing N-digit numbers
    Given a positive integer N, the task is to find the number of N-digit numbers such that every digit is smaller than its adjacent digits. Examples: Input: N = 1Output: 10Explanation: All numbers from [0 - 9] satisfy the condition as there is only one digit. Input: N = 3Output: 525 Naive Approach: The
    13 min read
  • Count number of ways to generate digit K at the end.
    Given an array arr[] containing N elements, each element is between 0 to 9. The task is to count the number of ways modulo 109 + 7 these operations can be performed so that at the end array with digit K left. Following operations are allowed on the array and any of the operations can be performed mo
    15+ min read
  • Count of repeating digits in a given Number
    Given a number N, the task is to count the total number of repeating digits in the given number. Examples: Input: N = 99677 Output: 2Explanation:In the given number only 9 and 7 are repeating, hence the answer is 2. Input: N = 12Output: 0Explanation:In the given number no digits are repeating, hence
    12 min read
  • Count number of increasing subsequences of size k
    Given an array arr[] containing n integers. The problem is to count number of increasing subsequences in the array of size k. Examples: Input : arr[] = {2, 6, 4, 5, 7}, k = 3Output : 5The subsequences of size '3' are:{2, 6, 7}, {2, 4, 5}, {2, 4, 7},{2, 5, 7} and {4, 5, 7}.Input : arr[] = {12, 8, 11,
    15+ min read
  • Count of ways to split a given number
    Given a number N, the task is to find the count of unique ways to split it into different parts. Note: {2, 1} and {1, 2} will be considered as one way. Examples: Input: n = 5 Output: 7Explanation: There are 7 ways to split 5:54 + 13 + 23 + 1 + 12 + 2 + 12 + 1 + 1 + 11 + 1 + 1 + 1 + 1 Input: n = 3 Ou
    8 min read
  • Count of unique digits in a given number N
    Given a number N, the task is to count the number of unique digits in the given number. Examples: Input: N = 22342 Output: 2 Explanation:The digits 3 and 4 occurs only once. Hence, the output is 2. Input: N = 99677 Output: 1Explanation:The digit 6 occurs only once. Hence, the output is 1. Naive Appr
    6 min read
  • Print all n-digit strictly increasing numbers
    Given number of digits n in a number, print all n-digit numbers whose digits are strictly increasing from left to right.Examples: Input: n = 2 Output: 01 02 03 04 05 06 07 08 09 12 13 14 15 16 17 18 19 23 24 25 26 27 28 29 34 35 36 37 38 39 45 46 47 48 49 56 57 58 59 67 68 69 78 79 89 Input: n = 3 O
    6 min read
  • Count numbers present in partitions of N
    Given an integer N, the task is to count the numbers in ordered integer partitions of N.Examples: Input: N = 3 Output: 8 Integer partitions of N(=3) are {{1 + 1 + 1}, {1 + 2}, {2 + 1}, {3}}. Numbers in integer partition of N are:{1, 1, 1, 1, 2, 2, 1, 3} Therefore, the count of numbers in integer par
    3 min read
  • Print all n-digit numbers whose sum of digits equals to given sum
    Given number of digits n, print all n-digit numbers whose sum of digits adds upto given sum. Solution should not consider leading 0’s as digits.Examples: Input: N = 2, Sum = 3Output: 12 21 30Input: N = 3, Sum = 6Output: 105 114 123 132 141 150 204 213 222 231 240 303 312 321 330 402 411 420 501 510
    10 min read
  • Count subsequences of Array having single digit integer sum K
    Given an array arr[] and integer K, the task is to count the number of subsequences of the array such that after adding all the elements of that subsequences their single digit integer sum is exactly K. Note: Single digit integer sum is obtained by replacing a number with its digit sum until the num
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences