Longest Subsequence from a numeric String divisible by K
Last Updated :
19 Jul, 2022
Given an integer K and a numeric string str, the task is to find the longest subsequence from the given string which is divisible by K.
Examples:
Input: str = "121400", K = 8
Output: 121400
Explanation:
Since the whole string is divisible by 8, the entire string is the answer.
Input: str: "7675437", K = 64
Output: 64
Explanation:
The longest subsequence from the string which is divisible by 64, is "64" itself.
Approach: The idea is to find all subsequences of the given string and for each subsequence, check if its integer representation is divisible by K or not. Follow the steps below to solve the problem:
- Traverse the string. For every character encountered, two possibilities exists.
- Either consider the current character in the subsequence or not. For both the cases, proceed to the next characters of the string and find the longest subsequence that is divisible by K.
- Compare the longest subsequences obtained above with the current maximum length of longest subsequence and update accordingly.
- Repeat the above steps for every character of the string and finally, print the maximum length obtained.
Below is the implementation of the above approach.
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to if the integer representation
// of the current string is divisible by K
bool isdivisible(string& newstr, long long K)
{
// Stores the integer
// representation of the string
long long num = 0;
for (int i = 0; i < newstr.size(); i++) {
num = num * 10 + newstr[i] - '0';
}
// Check if the num is
// divisible by K
if (num % K == 0)
return true;
else
return false;
}
// Function to find the longest subsequence
// which is divisible by K
void findLargestNo(string& str, string& newstr,
string& ans, int index,
long long K)
{
if (index == (int)str.length()) {
// If the number is divisible by K
if (isdivisible(newstr, K)) {
// If current number is the
// maximum obtained so far
if ((ans < newstr
&& ans.length() == newstr.length())
|| newstr.length() > ans.length()) {
ans = newstr;
}
}
return;
}
string x = newstr + str[index];
// Include the digit at current index
findLargestNo(str, x, ans, index + 1, K);
// Exclude the digit at current index
findLargestNo(str, newstr, ans, index + 1, K);
}
// Driver Code
int main()
{
string str = "121400";
string ans = "", newstr = "";
long long K = 8;
findLargestNo(str, newstr, ans, 0, K);
// Printing the largest number
// which is divisible by K
if (ans != "")
cout << ans << endl;
// If no number is found
// to be divisible by K
else
cout << -1 << endl;
}
Java
// Java program for the
// above approach
import java.util.*;
import java.lang.*;
class GFG{
// Function to if the integer representation
// of the current string is divisible by K
static boolean isdivisible(StringBuilder newstr,
long K)
{
// Stores the integer
// representation of the string
long num = 0;
for(int i = 0; i < newstr.length(); i++)
{
num = num * 10 + newstr.charAt(i) - '0';
}
// Check if the num is
// divisible by K
if (num % K == 0)
return true;
else
return false;
}
// Function to find the longest
// subsequence which is divisible
// by K
static void findLargestNo(String str, StringBuilder newstr,
StringBuilder ans, int index,
long K)
{
if (index == str.length())
{
// If the number is divisible by K
if (isdivisible(newstr, K))
{
// If current number is the
// maximum obtained so far
if ((newstr.toString().compareTo(ans.toString()) > 0 &&
ans.length() == newstr.length()) ||
newstr.length() > ans.length())
{
ans.setLength(0);
ans.append(newstr);
}
}
return;
}
StringBuilder x = new StringBuilder(
newstr.toString() + str.charAt(index));
// Include the digit at current index
findLargestNo(str, x, ans, index + 1, K);
// Exclude the digit at current index
findLargestNo(str, newstr, ans, index + 1, K);
}
// Driver code
public static void main (String[] args)
{
String str = "121400";
StringBuilder ans = new StringBuilder(),
newstr = new StringBuilder();
long K = 8;
findLargestNo(str, newstr, ans, 0, K);
// Printing the largest number
// which is divisible by K
if (ans.toString() != "")
System.out.println(ans);
// If no number is found
// to be divisible by K
else
System.out.println(-1);
}
}
// This code is contributed by offbeat
Python3
# Python3 program for the above approach
# Function to if the integer representation
# of the current string is divisible by K
def isdivisible(newstr, K):
# Stores the integer
# representation of the string
num = 0;
for i in range(len(newstr)):
num = num * 10 + int(newstr[i])
# Check if the num is
# divisible by K
if (num % K == 0):
return True
else:
return False
# Function to find the longest subsequence
# which is divisible by K
def findLargestNo(str, newstr, ans, index, K):
if (index == len(str)):
# If the number is divisible by K
if (isdivisible(newstr, K)):
# If current number is the
# maximum obtained so far
if ((ans < newstr and len(ans) == len(newstr)) or len(newstr) > len(ans)):
ans = newstr
return ans
x = newstr + str[index];
# Include the digit at current index
ans = findLargestNo(str, x, ans, index + 1, K);
# Exclude the digit at current index
ans = findLargestNo(str, newstr, ans, index + 1, K);
return ans;
# Driver Code
str = "121400";
ans = ""
newstr = "";
K = 8;
ans = findLargestNo(str, newstr, ans, 0, K);
# Printing the largest number
# which is divisible by K
if (ans != "") :
print(ans)
# If no number is found
# to be divisible by K
else:
print( -1)
# This code is contributed by phasing17
C#
// C# program for the above approach
using System;
using System.Text;
class GFG{
// Function to if the integer representation
// of the current string is divisible by K
static bool isdivisible(StringBuilder newstr,
long K)
{
// Stores the integer representation
// of the string
long num = 0;
for(int i = 0; i < newstr.Length; i++)
{
num = num * 10 + newstr[i] - '0';
}
// Check if the num is
// divisible by K
if (num % K == 0)
return true;
else
return false;
}
// Function to find the longest
// subsequence which is divisible
// by K
static void findLargestNo(String str, StringBuilder newstr,
StringBuilder ans, int index,
long K)
{
if (index == str.Length)
{
// If the number is divisible by K
if (isdivisible(newstr, K))
{
// If current number is the
// maximum obtained so far
if ((newstr.ToString().CompareTo(ans.ToString()) > 0 &&
ans.Length == newstr.Length) ||
newstr.Length > ans.Length)
{
ans.EnsureCapacity(0);//.SetLength(0);
ans.Append(newstr);
}
}
return;
}
StringBuilder x = new StringBuilder(
newstr.ToString() + str[index]);
// Include the digit at current index
findLargestNo(str, x, ans, index + 1, K);
// Exclude the digit at current index
findLargestNo(str, newstr, ans, index + 1, K);
}
// Driver code
public static void Main(String[] args)
{
String str = "121400";
StringBuilder ans = new StringBuilder(),
newstr = new StringBuilder();
long K = 8;
findLargestNo(str, newstr, ans, 0, K);
// Printing the largest number
// which is divisible by K
if (ans.ToString() != "")
Console.WriteLine(ans);
// If no number is found
// to be divisible by K
else
Console.WriteLine(-1);
}
}
// This code is contributed by gauravrajput1
JavaScript
<script>
// Javascript program for the above approach
// Function to if the integer representation
// of the current string is divisible by K
function isdivisible(newstr, K)
{
// Stores the integer
// representation of the string
var num = 0;
for(var i = 0; i < newstr.length; i++)
{
num = num * 10 + newstr[i].charCodeAt(0) -
'0'.charCodeAt(0);
}
// Check if the num is
// divisible by K
if (num % K == 0)
return true;
else
return false;
}
// Function to find the longest subsequence
// which is divisible by K
function findLargestNo(str, newstr, ans, index, K)
{
if (index == str.length)
{
// If the number is divisible by K
if (isdivisible(newstr, K))
{
// If current number is the
// maximum obtained so far
if ((ans < newstr &&
ans.length == newstr.length) ||
newstr.length > ans.length)
{
ans = newstr;
}
}
return ans;
}
var x = newstr + str[index];
// Include the digit at current index
ans = findLargestNo(str, x, ans,
index + 1, K);
// Exclude the digit at current index
ans = findLargestNo(str, newstr, ans,
index + 1, K);
return ans;
}
// Driver Code
var str = "121400";
var ans = "", newstr = "";
var K = 8;
ans = findLargestNo(str, newstr, ans, 0, K);
// Printing the largest number
// which is divisible by K
if (ans != "")
document.write(ans)
// If no number is found
// to be divisible by K
else
document.write( -1)
// This code is contributed by itsok
</script>
Time Complexity: O(N * 2N)
Auxiliary Space: O(1)
Similar Reads
Number of subsequences in a string divisible by n Given a string consisting of digits 0-9, count the number of subsequences in it divisible by m.Examples: Input : str = "1234", n = 4Output : 4The subsequences 4, 12, 24 and 124 are divisible by 4. Input : str = "330", n = 6Output : 4The subsequences 30, 30, 330 and 0 are divisible by n.Input : str =
11 min read
Longest subsequence whose sum is divisible by a given number Given an array arr[] and an integer M, the task is to find the length of the longest subsequence whose sum is divisible by M. If there is no such sub-sequence then print 0. Examples: Input: arr[] = {3, 2, 2, 1}, M = 3 Output: 3 Longest sub-sequence whose sum is divisible by 3 is {3, 2, 1}Input: arr[
15+ min read
Longest subsequence whose sum is divisible by a given number Given an array arr[] and an integer M, the task is to find the length of the longest subsequence whose sum is divisible by M. If there is no such sub-sequence then print 0. Examples: Input: arr[] = {3, 2, 2, 1}, M = 3 Output: 3 Longest sub-sequence whose sum is divisible by 3 is {3, 2, 1}Input: arr[
15+ min read
Longest sub-sequence of a binary string divisible by 3 Given a binary string S of length N, the task is to find the length of the longest sub-sequence in it which is divisible by 3. Leading zeros in the sub-sequences are allowed.Examples:  Input: S = "1001" Output: 4 The longest sub-sequence divisible by 3 is "1001". 1001 = 9 which is divisible by 3.In
9 min read
Longest sub-sequence of a binary string divisible by 3 Given a binary string S of length N, the task is to find the length of the longest sub-sequence in it which is divisible by 3. Leading zeros in the sub-sequences are allowed.Examples:  Input: S = "1001" Output: 4 The longest sub-sequence divisible by 3 is "1001". 1001 = 9 which is divisible by 3.In
9 min read
Largest sub-string of a binary string divisible by 2 Given binary string str of length N, the task is to find the longest sub-string divisible by 2. If no such sub-string exists then print -1. Examples: Input: str = "11100011" Output: 111000 Largest sub-string divisible by 2 is "111000".Input: str = "1111" Output: -1 There is no sub-string of the give
3 min read