Count ways to split string into K Substrings starting with even digit and min length M
Last Updated :
23 Jul, 2025
Given a string s of length n consisting of digits from '0' to '9'. The task is to determine the total number of possible ways to partition the string into k substrings such that :
- Each substring has a minimum length of m (m >= 2).
- Substring must start with an even digit number and end with an odd digit number.
Examples:
Input: s = "432387429", m = 2, k = 3
Output: 3
Explanation: Following are valid partitions of the string s
43|23|87429, 4323|87|429, 43|2387|429
Input: s = "546521", m = 3, k = 2,
Output: 0
Explanation: There is no way to partition the given string.
Using Recursion - O(n^k) Time and O(k) Space
The idea is to explore all possible ways to partition the string into k substrings with minimum length m. The function starts from the beginning of the string and tries to create valid partitions by checking the digit parity conditions. At each step, it recursively explores potential partitions by moving the starting point forward and reducing the number of remaining partitions while ensuring each substring meets the specified constraints of starting with an even digit and ending with an odd digit.
Let countWays(i, k, s) represent the number of ways to partition s into k substrings starting at index i.
Base Cases:
- if length of remaining substring (s.length - i) is less than m, return 0.
- if k == 1 and the current substring is valid, return 1.
countWays(i, k, s) = countWays(j, k-1, s) where j is from i + m (to maintain minimum length of m for current substring) to last index and s[j] is an even integer and s[j-1] is an odd integer.
C++
// C++ program to count ways to
// split string into k Substrings using recursion
#include <bits/stdc++.h>
using namespace std;
int countRecur(string &s, int i, int k, int m) {
int n = s.length();
// If length of remaining substring
// is less than m, return 0.
if (n - i < m)
return 0;
// Base case for k=1.
if (k == 1)
return 1;
int ans = 0;
// Set j= i+1 to ensure length
// of current substring s[i, j]
// is atleast m.
for (int j = i + m; j < n; j++) {
int end = s[j - 1] - '0';
int start = s[j] - '0';
// If the end integer of current
// string is valid and starting
// integer of next string is valid.
if (end % 2 == 1 && start % 2 == 0) {
ans += countRecur(s, j, k - 1, m);
}
}
return ans;
}
int countWays(string &s, int m, int k) {
int start = s[0] - '0';
int n = s.length();
int end = s[n - 1] - '0';
// If the string is invalid, it cannot
// be splitted.
if (start % 2 == 1 || end % 2 == 0)
return 0;
return countRecur(s, 0, k, m);
}
int main() {
int m = 2, k = 3;
string s = "432387429";
cout << countWays(s, m, k);
return 0;
}
Java
// Java program to count ways to
// split string into K Substrings using recursion
import java.util.*;
class GfG {
static int countRecur(String s, int i, int k, int m) {
int n = s.length();
// If length of remaining substring
// is less than m, return 0.
if (n - i < m) return 0;
// Base case for k=1.
if (k == 1) return 1;
int ans = 0;
// Set j= i+1 to ensure length
// of current substring s[i, j]
// is atleast m.
for (int j = i + m; j < n; j++) {
int end = s.charAt(j - 1) - '0';
int start = s.charAt(j) - '0';
// If the end integer of current
// string is valid and starting
// integer of next string is valid.
if (end % 2 == 1 && start % 2 == 0) {
ans += countRecur(s, j, k - 1, m);
}
}
return ans;
}
static int countWays(String s, int m, int k) {
int start = s.charAt(0) - '0';
int n = s.length();
int end = s.charAt(n - 1) - '0';
// If the string is invalid, it cannot
// be splitted.
if (start % 2 == 1 || end % 2 == 0) return 0;
return countRecur(s, 0, k, m);
}
public static void main(String[] args) {
int m = 2, k = 3;
String s = "432387429";
System.out.println(countWays(s, m, k));
}
}
Python
# Python program to count ways to
# split string into K Substrings using recursion
def countRecur(s, i, k, m):
n = len(s)
# If length of remaining substring
# is less than m, return 0.
if n - i < m:
return 0
# Base case for k=1.
if k == 1:
return 1
ans = 0
# Set j= i+1 to ensure length
# of current substring s[i, j]
# is atleast m.
for j in range(i + m, n):
end = int(s[j - 1])
start = int(s[j])
# If the end integer of current
# string is valid and starting
# integer of next string is valid.
if end % 2 == 1 and start % 2 == 0:
ans += countRecur(s, j, k - 1, m)
return ans
def countWays(s, m, k):
start = int(s[0])
n = len(s)
end = int(s[n - 1])
# If the string is invalid, it cannot
# be splitted.
if start % 2 == 1 or end % 2 == 0:
return 0
return countRecur(s, 0, k, m)
if __name__ == "__main__":
m = 2
k = 3
s = "432387429"
print(countWays(s, m, k))
C#
// C# program to count ways to
// split string into K Substrings using recursion
using System;
class GfG {
static int countRecur(string s, int i, int k, int m) {
int n = s.Length;
// If length of remaining substring
// is less than m, return 0.
if (n - i < m) return 0;
// Base case for k=1.
if (k == 1) return 1;
int ans = 0;
// Set j= i+1 to ensure length
// of current substring s[i, j]
// is atleast m.
for (int j = i + m; j < n; j++) {
int end = s[j - 1] - '0';
int start = s[j] - '0';
// If the end integer of current
// string is valid and starting
// integer of next string is valid.
if (end % 2 == 1 && start % 2 == 0) {
ans += countRecur(s, j, k - 1, m);
}
}
return ans;
}
static int countWays(string s, int m, int k) {
int start = s[0] - '0';
int n = s.Length;
int end = s[n - 1] - '0';
// If the string is invalid, it cannot
// be splitted.
if (start % 2 == 1 || end % 2 == 0) return 0;
return countRecur(s, 0, k, m);
}
static void Main(string[] args) {
int m = 2, k = 3;
string s = "432387429";
Console.WriteLine(countWays(s, m, k));
}
}
JavaScript
// JavaScript program to count ways to
// split string into K Substrings using recursion
function countRecur(s, i, k, m) {
let n = s.length;
// If length of remaining substring
// is less than m, return 0.
if (n - i < m) return 0;
// Base case for k=1.
if (k === 1) return 1;
let ans = 0;
// Set j= i+1 to ensure length
// of current substring s[i, j]
// is atleast m.
for (let j = i + m; j < n; j++) {
let end = s[j - 1] - '0';
let start = s[j] - '0';
// If the end integer of current
// string is valid and starting
// integer of next string is valid.
if (end % 2 === 1 && start % 2 === 0) {
ans += countRecur(s, j, k - 1, m);
}
}
return ans;
}
function countWays(s, m, k) {
let start = s[0] - '0';
let n = s.length;
let end = s[n - 1] - '0';
// If the string is invalid, it cannot
// be splitted.
if (start % 2 === 1 || end % 2 === 0) return 0;
return countRecur(s, 0, k, m);
}
let m = 2, k = 3;
let s = "432387429";
console.log(countWays(s, m, k));
Using Top-Down DP (Memoization) - O(n*n*k) Time and O(n*k) Space
If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming:
1. Optimal Substructure: Number of ways to make k substrings at index i, i.e., countWays(i, k, s), depends on the optimal solutions of the subproblems countWays(j, k-1, s) where j lies between i+m and s.length. By combining these optimal substructures, we can efficiently calculate number of ways to make k substrings at index i.
2. Overlapping Subproblems: While applying a recursive approach in this problem, we notice that certain subproblems are computed multiple times.
- There are only are two parameters: i and k that changes in the recursive solution. So we create a 2D matrix of size n*(k+1) for memoization.
- We initialize this matrix as -1 to indicate nothing is computed initially.
- Now we modify our recursive solution to first check if the value is -1, then only make recursive calls. This way, we avoid re-computations of the same subproblems.
C++
// C++ program to count ways to
// split string into K Substrings using memoization
#include <bits/stdc++.h>
using namespace std;
int countRecur(string &s, int i, int k, int m,
vector<vector<int>> &memo) {
int n = s.length();
// If length of remaining substring
// is less than m, return 0.
if (n - i < m)
return 0;
// Base case for k=1.
if (k == 1)
return 1;
// If value is memoized
if (memo[i][k] != -1) {
return memo[i][k];
}
int ans = 0;
// Set j= i+1 to ensure length
// of current substring s[i, j]
// is atleast m.
for (int j = i + m; j < n; j++) {
int end = s[j - 1] - '0';
int start = s[j] - '0';
// If the end integer of current
// string is valid and starting
// integer of next string is valid.
if (end % 2 == 1 && start % 2 == 0) {
ans += countRecur(s, j, k - 1, m, memo);
}
}
return memo[i][k] = ans;
}
int countWays(string &s, int m, int k) {
int start = s[0] - '0';
int n = s.length();
int end = s[n - 1] - '0';
// If the string is invalid, it cannot
// be splitted.
if (start % 2 == 1 || end % 2 == 0)
return 0;
vector<vector<int>> memo(n, vector<int>(k + 1, -1));
return countRecur(s, 0, k, m, memo);
}
int main() {
int m = 2, k = 3;
string s = "432387429";
cout << countWays(s, m, k);
return 0;
}
Java
// Java program to count ways to
// split string into K Substrings using memoization
import java.util.Arrays;
class GfG {
static int countRecur(String s, int i, int k,
int m, int[][] memo) {
int n = s.length();
// If length of remaining substring
// is less than m, return 0.
if (n - i < m) return 0;
// Base case for k=1.
if (k == 1) return 1;
// If value is memoized
if (memo[i][k] != -1) {
return memo[i][k];
}
int ans = 0;
// Set j= i+1 to ensure length
// of current substring s[i, j]
// is atleast m.
for (int j = i + m; j < n; j++) {
int end = s.charAt(j - 1) - '0';
int start = s.charAt(j) - '0';
// If the end integer of current
// string is valid and starting
// integer of next string is valid.
if (end % 2 == 1 && start % 2 == 0) {
ans += countRecur(s, j, k - 1, m, memo);
}
}
return memo[i][k] = ans;
}
static int countWays(String s, int m, int k) {
int start = s.charAt(0) - '0';
int n = s.length();
int end = s.charAt(n - 1) - '0';
// If the string is invalid, it cannot
// be splitted.
if (start % 2 == 1 || end % 2 == 0) return 0;
int[][] memo = new int[n][k + 1];
for (int[] row : memo) Arrays.fill(row, -1);
return countRecur(s, 0, k, m, memo);
}
public static void main(String[] args) {
int m = 2, k = 3;
String s = "432387429";
System.out.println(countWays(s, m, k));
}
}
Python
# Python program to count ways to
# split string into K Substrings using memoization
def countRecur(s, i, k, m, memo):
n = len(s)
# If length of remaining substring
# is less than m, return 0.
if n - i < m:
return 0
# Base case for k=1.
if k == 1:
return 1
# If value is memoized
if memo[i][k] != -1:
return memo[i][k]
ans = 0
# Set j= i+1 to ensure length
# of current substring s[i, j]
# is atleast m.
for j in range(i + m, n):
end = int(s[j - 1])
start = int(s[j])
# If the end integer of current
# string is valid and starting
# integer of next string is valid.
if end % 2 == 1 and start % 2 == 0:
ans += countRecur(s, j, k - 1, m, memo)
memo[i][k] = ans
return ans
def countWays(s, m, k):
start = int(s[0])
n = len(s)
end = int(s[-1])
# If the string is invalid, it cannot
# be splitted.
if start % 2 == 1 or end % 2 == 0:
return 0
memo = [[-1] * (k + 1) for _ in range(n)]
return countRecur(s, 0, k, m, memo)
if __name__ == "__main__":
m = 2
k = 3
s = "432387429"
print(countWays(s, m, k))
C#
// C# program to count ways to
// split string into K Substrings using memoization
using System;
class GfG {
static int countRecur(string s, int i, int k,
int m, int[,] memo) {
int n = s.Length;
// If length of remaining substring
// is less than m, return 0.
if (n - i < m) return 0;
// Base case for k=1.
if (k == 1) return 1;
// If value is memoized
if (memo[i, k] != -1) {
return memo[i, k];
}
int ans = 0;
// Set j= i+1 to ensure length
// of current substring s[i, j]
// is atleast m.
for (int j = i + m; j < n; j++) {
int end = s[j - 1] - '0';
int start = s[j] - '0';
// If the end integer of current
// string is valid and starting
// integer of next string is valid.
if (end % 2 == 1 && start % 2 == 0) {
ans += countRecur(s, j, k - 1, m, memo);
}
}
memo[i, k] = ans;
return ans;
}
static int countWays(string s, int m, int k) {
int start = s[0] - '0';
int n = s.Length;
int end = s[n - 1] - '0';
// If the string is invalid, it cannot
// be splitted.
if (start % 2 == 1 || end % 2 == 0) return 0;
int[,] memo = new int[n, k + 1];
for (int i = 0; i < n; i++)
for (int j = 0; j <= k; j++)
memo[i, j] = -1;
return countRecur(s, 0, k, m, memo);
}
static void Main(string[] args) {
int m = 2, k = 3;
string s = "432387429";
Console.WriteLine(countWays(s, m, k));
}
}
JavaScript
// JavaScript program to count ways to
// split string into K Substrings using memoization
function countRecur(s, i, k, m, memo) {
let n = s.length;
// If length of remaining substring
// is less than m, return 0.
if (n - i < m) return 0;
// Base case for k=1.
if (k === 1) return 1;
// If value is memoized
if (memo[i][k] !== -1) {
return memo[i][k];
}
let ans = 0;
// Set j= i+1 to ensure length
// of current substring s[i, j]
// is atleast m.
for (let j = i + m; j < n; j++) {
let end = s[j - 1] - '0';
let start = s[j] - '0';
// If the end integer of current
// string is valid and starting
// integer of next string is valid.
if (end % 2 === 1 && start % 2 === 0) {
ans += countRecur(s, j, k - 1, m, memo);
}
}
memo[i][k] = ans;
return ans;
}
function countWays(s, m, k) {
let start = s[0] - '0';
let n = s.length;
let end = s[n - 1] - '0';
// If the string is invalid, it cannot
// be splitted.
if (start % 2 === 1 || end % 2 === 0) return 0;
let memo = Array.from({ length: n }, () => Array(k + 1).fill(-1));
return countRecur(s, 0, k, m, memo);
}
let m = 2, k = 3;
let s = "432387429";
console.log(countWays(s, m, k));
Using Bottom-Up DP (Tabulation) - O(n*n*k) Time and O(n*k) Space
The idea is to fill the DP table from bottom to up. For each index i and partitions j, the dynamic programming relation is as follows:
- If string is not valid (does not start with even integer or length is less than m), set dp[i][j] = 0.
- If j == 1 and string is valid, set dp[i][j] = 1.
- Else dp[i][j] = sum(dp[x][j-1]) for all x in range [i+m, s.length].
C++
// C++ program to count ways to
// split string into K Substrings using tabulation
#include <bits/stdc++.h>
using namespace std;
int countWays(string &s, int m, int k) {
int start = s[0] - '0';
int n = s.length();
int end = s[n - 1] - '0';
// If the string is invalid, it cannot
// be splitted.
if (start % 2 == 1 || end % 2 == 0)
return 0;
vector<vector<int>> dp(n, vector<int>(k + 1, 0));
for (int i = n - 1; i >= 0; i--) {
for (int j = 1; j <= k; j++) {
int start = s[i] - '0';
// If current substring does not
// start with even digit or its
// minimum length is less than m.
if (start % 2 == 1 || n - i < m) {
dp[i][j] = 0;
continue;
}
// For k=1 and valid substring.
if (j == 1) {
dp[i][j] = 1;
continue;
}
for (int x = i + m; x < n; x++) {
int st = s[x] - '0';
int e = s[x - 1] - '0';
if (st % 2 == 0 && e % 2 == 1) {
dp[i][j] += dp[x][j - 1];
}
}
}
}
return dp[0][k];
}
int main() {
int m = 2, k = 3;
string s = "432387429";
cout << countWays(s, m, k);
return 0;
}
Java
// Java program to count ways to
// split string into K Substrings using tabulation
class GfG {
static int countWays(String s, int m, int k) {
int start = s.charAt(0) - '0';
int n = s.length();
int end = s.charAt(n - 1) - '0';
// If the string is invalid, it cannot
// be splitted.
if (start % 2 == 1 || end % 2 == 0) return 0;
int[][] dp = new int[n][k + 1];
for (int i = n - 1; i >= 0; i--) {
for (int j = 1; j <= k; j++) {
int startDigit = s.charAt(i) - '0';
// If current substring does not
// start with even digit or its
// minimum length is less than m.
if (startDigit % 2 == 1 || n - i < m) {
dp[i][j] = 0;
continue;
}
// For k=1 and valid substring.
if (j == 1) {
dp[i][j] = 1;
continue;
}
for (int x = i + m; x < n; x++) {
int st = s.charAt(x) - '0';
int e = s.charAt(x - 1) - '0';
if (st % 2 == 0 && e % 2 == 1) {
dp[i][j] += dp[x][j - 1];
}
}
}
}
return dp[0][k];
}
public static void main(String[] args) {
int m = 2, k = 3;
String s = "432387429";
System.out.println(countWays(s, m, k));
}
}
Python
# Python program to count ways to
# split string into K Substrings using tabulation
def countWays(s, m, k):
start = int(s[0])
n = len(s)
end = int(s[-1])
# If the string is invalid, it cannot
# be splitted.
if start % 2 == 1 or end % 2 == 0:
return 0
dp = [[0] * (k + 1) for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(1, k + 1):
startDigit = int(s[i])
# If current substring does not
# start with even digit or its
# minimum length is less than m.
if startDigit % 2 == 1 or n - i < m:
dp[i][j] = 0
continue
# For k=1 and valid substring.
if j == 1:
dp[i][j] = 1
continue
for x in range(i + m, n):
st = int(s[x])
e = int(s[x - 1])
if st % 2 == 0 and e % 2 == 1:
dp[i][j] += dp[x][j - 1]
return dp[0][k]
if __name__ == "__main__":
m = 2
k = 3
s = "432387429"
print(countWays(s, m, k))
C#
// C# program to count ways to
// split string into K Substrings using tabulation
using System;
class GfG {
static int countWays(string s, int m, int k) {
int start = s[0] - '0';
int n = s.Length;
int end = s[n - 1] - '0';
// If the string is invalid, it cannot
// be splitted.
if (start % 2 == 1 || end % 2 == 0) return 0;
int[,] dp = new int[n, k + 1];
for (int i = n - 1; i >= 0; i--) {
for (int j = 1; j <= k; j++) {
int startDigit = s[i] - '0';
// If current substring does not
// start with even digit or its
// minimum length is less than m.
if (startDigit % 2 == 1 || n - i < m) {
dp[i, j] = 0;
continue;
}
// For k=1 and valid substring.
if (j == 1) {
dp[i, j] = 1;
continue;
}
for (int x = i + m; x < n; x++) {
int st = s[x] - '0';
int e = s[x - 1] - '0';
if (st % 2 == 0 && e % 2 == 1) {
dp[i, j] += dp[x, j - 1];
}
}
}
}
return dp[0, k];
}
static void Main(string[] args) {
int m = 2, k = 3;
string s = "432387429";
Console.WriteLine(countWays(s, m, k));
}
}
JavaScript
// JavaScript program to count ways to
// split string into K Substrings using tabulation
function countWays(s, m, k) {
const start = s[0] - '0';
const n = s.length;
const end = s[n - 1] - '0';
// If the string is invalid, it cannot
// be splitted.
if (start % 2 === 1 || end % 2 === 0) return 0;
const dp = Array.from({ length: n }, () => Array(k + 1).fill(0));
for (let i = n - 1; i >= 0; i--) {
for (let j = 1; j <= k; j++) {
const startDigit = s[i] - '0';
// If current substring does not
// start with even digit or its
// minimum length is less than m.
if (startDigit % 2 === 1 || n - i < m) {
dp[i][j] = 0;
continue;
}
// For k=1 and valid substring.
if (j === 1) {
dp[i][j] = 1;
continue;
}
for (let x = i + m; x < n; x++) {
const st = s[x] - '0';
const e = s[x - 1] - '0';
if (st % 2 === 0 && e % 2 === 1) {
dp[i][j] += dp[x][j - 1];
}
}
}
}
return dp[0][k];
}
const m = 2, k = 3;
const s = "432387429";
console.log(countWays(s, m, k));
Using Space Optimized DP - O(k*n*n) Time and O(n) Space
In previous approach of dynamic programming, we observe that for calculating dp[i][j], we only need previous column dp[i][j-1]. There is no need to store all previous states.
C++
// C++ program to count ways to
// split string into K Substrings.
#include <bits/stdc++.h>
using namespace std;
int countWays(string &s, int m, int k) {
int start = s[0] - '0';
int n = s.length();
int end = s[n - 1] - '0';
// If the string is invalid, it cannot be split.
if (start % 2 == 1 || end % 2 == 0)
return 0;
vector<int> prev(n, 0), curr(n, 0);
for (int j = 1; j <= k; j++) {
for (int i = n - 1; i >= 0; i--) {
int startDigit = s[i] - '0';
// If current substring does not start with an even digit
// or its minimum length is less than m.
if (startDigit % 2 == 1 || n - i < m) {
curr[i] = 0;
continue;
}
// For k = 1 and valid substring.
if (j == 1) {
curr[i] = 1;
continue;
}
curr[i] = 0;
for (int x = i + m; x < n; x++) {
int st = s[x] - '0';
int e = s[x - 1] - '0';
if (st % 2 == 0 && e % 2 == 1) {
curr[i] += prev[x];
}
}
}
// Swap curr and prev for the next iteration.
swap(curr, prev);
}
return prev[0];
}
int main() {
int m = 2, k = 3;
string s = "432387429";
cout << countWays(s, m, k);
return 0;
}
Java
// Java program to count ways to
// split string into K Substrings.
import java.util.*;
class GfG {
static int countWays(String s, int m, int k) {
int start = s.charAt(0) - '0';
int n = s.length();
int end = s.charAt(n - 1) - '0';
// If the string is invalid, it cannot be split.
if (start % 2 == 1 || end % 2 == 0) {
return 0;
}
int[] prev = new int[n];
int[] curr = new int[n];
for (int j = 1; j <= k; j++) {
for (int i = n - 1; i >= 0; i--) {
int startDigit = s.charAt(i) - '0';
// If current substring does not start with an even digit
// or its minimum length is less than m.
if (startDigit % 2 == 1 || n - i < m) {
curr[i] = 0;
continue;
}
// For k = 1 and valid substring.
if (j == 1) {
curr[i] = 1;
continue;
}
curr[i] = 0;
for (int x = i + m; x < n; x++) {
int st = s.charAt(x) - '0';
int e = s.charAt(x - 1) - '0';
if (st % 2 == 0 && e % 2 == 1) {
curr[i] += prev[x];
}
}
}
// Swap curr and prev for the next iteration.
int[] temp = curr;
curr = prev;
prev = temp;
}
return prev[0];
}
public static void main(String[] args) {
int m = 2, k = 3;
String s = "432387429";
System.out.println(countWays(s, m, k));
}
}
Python
# Python program to count ways to
# split string into K Substrings.
def countWays(s, m, k):
start = int(s[0])
n = len(s)
end = int(s[n - 1])
# If the string is invalid, it cannot be split.
if start % 2 == 1 or end % 2 == 0:
return 0
prev = [0] * n
curr = [0] * n
for j in range(1, k + 1):
for i in range(n - 1, -1, -1):
startDigit = int(s[i])
# If current substring does not start with an even digit
# or its minimum length is less than m.
if startDigit % 2 == 1 or n - i < m:
curr[i] = 0
continue
# For k = 1 and valid substring.
if j == 1:
curr[i] = 1
continue
curr[i] = 0
for x in range(i + m, n):
st = int(s[x])
e = int(s[x - 1])
if st % 2 == 0 and e % 2 == 1:
curr[i] += prev[x]
# Swap curr and prev for the next iteration.
prev, curr = curr, prev
return prev[0]
if __name__ == "__main__":
m = 2
k = 3
s = "432387429"
print(countWays(s, m, k))
C#
// C# program to count ways to
// split string into K Substrings.
using System;
class GfG {
static int countWays(string s, int m, int k) {
int start = s[0] - '0';
int n = s.Length;
int end = s[n - 1] - '0';
// If the string is invalid, it cannot be split.
if (start % 2 == 1 || end % 2 == 0) {
return 0;
}
int[] prev = new int[n];
int[] curr = new int[n];
for (int j = 1; j <= k; j++) {
for (int i = n - 1; i >= 0; i--) {
int startDigit = s[i] - '0';
// If current substring does not start with an even digit
// or its minimum length is less than m.
if (startDigit % 2 == 1 || n - i < m) {
curr[i] = 0;
continue;
}
// For k = 1 and valid substring.
if (j == 1) {
curr[i] = 1;
continue;
}
curr[i] = 0;
for (int x = i + m; x < n; x++) {
int st = s[x] - '0';
int e = s[x - 1] - '0';
if (st % 2 == 0 && e % 2 == 1) {
curr[i] += prev[x];
}
}
}
// Swap curr and prev for the next iteration.
var temp = curr;
curr = prev;
prev = temp;
}
return prev[0];
}
static void Main(string[] args) {
int m = 2, k = 3;
string s = "432387429";
Console.WriteLine(countWays(s, m, k));
}
}
JavaScript
// JavaScript program to count ways to
// split string into K Substrings.
function countWays(s, m, k) {
const start = parseInt(s[0]);
const n = s.length;
const end = parseInt(s[n - 1]);
// If the string is invalid, it cannot be split.
if (start % 2 === 1 || end % 2 === 0) {
return 0;
}
let prev = new Array(n).fill(0);
let curr = new Array(n).fill(0);
for (let j = 1; j <= k; j++) {
for (let i = n - 1; i >= 0; i--) {
const startDigit = parseInt(s[i]);
// If current substring does not start with an even digit
// or its minimum length is less than m.
if (startDigit % 2 === 1 || n - i < m) {
curr[i] = 0;
continue;
}
// For k = 1 and valid substring.
if (j === 1) {
curr[i] = 1;
continue;
}
curr[i] = 0;
for (let x = i + m; x < n; x++) {
const st = parseInt(s[x]);
const e = parseInt(s[x - 1]);
if (st % 2 === 0 && e % 2 === 1) {
curr[i] += prev[x];
}
}
}
// Swap curr and prev for the next iteration.
[curr, prev] = [prev, curr];
}
return prev[0];
}
const m = 2, k = 3;
const s = "432387429";
console.log(countWays(s, m, k));
Time Complexity: O(k*n*n), due to the 3 nested for loops: outer loop (from 1 to k), inner loop ( n-1 to 0 ) , innermost loop ( In the worst case, the innermost loop executes about n - i
iterations, which is roughly n
for each iteration of i
)
Space Complexity: O(n), both vectors prev
and curr
takes O(n)
space as they store values for each index of the string.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem