Find the longest Substring of a given String S
Last Updated :
10 Feb, 2023
Given a string S of length, N. Find the maximum length of any substring of S such that, the bitwise OR of all the characters of the substring is equal to the bitwise OR of the remaining characters of the string. If no such substring exists, print -1.
Examples:
Input: S = "2347"
Output: 3
?Explanation: Consider the substring "234" having length 3. The bitwise OR of the characters of the substring is 2 | 3 | 4 = 7 and the bitwise OR of the remaining characters of the string is 7. Thus, the bitwise OR of all elements of the substring is equal to the bitwise OR of the remaining characters of the string.
Input: S = "124"
Output: -1
Approach: The problem can be solved based on the following observation:
Observations:
- First compute the bitwise OR of all the characters in the input string, Let M = S1 | S2 | … | SN be the bitwise OR of all the characters.
- And then use a sliding window approach to iterate over the possible substrings of the string, keeping track of the bitwise OR of the characters in the current substring and comparing it to the bitwise OR of the rest of the string.
- If the two ORs are equal, the condition for the problem is satisfied and the length of the current substring is compared to the current maximum length.
- And if the length of the substring is non-zero print the length. Otherwise, print -1.
Follow the steps mentioned below to implement the idea:
- Set or = 0 and then calculate the bitwise OR of all the elements of lis and store it in or.
- An array count is initialized to all 0s and then the code iterates through each element of lis. For each element, it sets the value of each element in the count to 1 if the corresponding bit in the element is set.
- Initialise ans = 0, l = 0, and tempOr = 0.
- Iterate through each element of lis from left to right. For each element, do the following:
- Set tempOr to the result of a bitwise OR of itself and the current element in lis.
- After that sets flag = true
- Iterate through each bit in the current element of lis. If the bit is set, decrement the corresponding element in the count array.
- If the corresponding element in count becomes 0, then flag = false.
- If flag = false, do the following:
- Iterate through lis from the leftmost element to the current element r. For each element, do the following:
- Set flag1 = true and then iterates through each bit in the element.
- If the bit is set, it increments the corresponding element in the count array.
- If the corresponding element in count becomes 0, then flag1 = false.
- When flag1 = false, the loop breaks, and l is incremented.
- If tempOr = or, then ans = max(ans, (r - l + 1))
- After the loop completes, check if ans != 0, and, if it is, print the value of ans. Otherwise, it prints -1.
Below is the implementation of the above approach :
Java
// Java implementation of the above approach
import java.io.*;
import java.util.*;
public class GFG {
// Function to maximum length of
// substring of S
public static void maxLength(int lis[], int n)
{
long or = 0;
// Calculate OR of each element
// of string
for (int i = 0; i < n; i++) {
or |= lis[i];
}
int[] count = new int[32];
for (int i = 0; i < n; i++) {
for (int j = 0; j < 32; j++) {
if ((lis[i] & (1L << j)) != 0)
count[j]++;
}
}
long ans = 0, l = 0, tempOr = 0;
for (int r = 0; r < n; r++) {
tempOr |= lis[r];
boolean flag = true;
for (int i = 0; i < 32; i++) {
if ((lis[r] & (1L << i)) != 0) {
count[i]--;
if (count[i] == 0)
flag = false;
}
}
// If flag = false
if (!flag) {
for (; l <= r;) {
boolean flag1 = true;
for (int i = 0; i < 32; i++) {
if ((lis[(int)l] & (1L << i))
!= 0) {
count[i]++;
}
if (count[i] == 0)
flag1 = false;
}
l++;
if (flag1)
break;
}
}
// If OR of leftover elements and
// substring elements is equal
if (tempOr == or) {
ans = Math.max(ans, r - l + 1);
}
}
// Print the result
if (ans != 0)
System.out.println(ans);
else
System.out.println(-1);
}
// Driver Code
public static void main(String[] args)
{
String S = "2347";
int N = S.length();
int[] A = new int[N];
for (int i = 0; i < N; i++) {
A[i] = S.charAt(i) - '0';
}
// Function Call
maxLength(A, N);
}
}
Python3
# Python implementation of the above approach
import math
def maxLength(lis, n):
or_val = 0
# Calculate OR of each element of string
for i in range(n):
or_val |= lis[i]
count = [0 for i in range(32)]
for i in range(n):
for j in range(32):
if (lis[i] & (1 << j)) != 0:
count[j] += 1
ans = 0
l = 0
temp_or = 0
for r in range(n):
temp_or |= lis[r]
flag = True
for i in range(32):
if (lis[r] & (1 << i)) != 0:
count[i] -= 1
if count[i] == 0:
flag = False
# If flag = false
if not flag:
while l <= r:
flag1 = True
for i in range(32):
if (lis[l] & (1 << i)) != 0:
count[i] += 1
if count[i] == 0:
flag1 = False
l += 1
if flag1:
break
# If OR of leftover elements and substring elements is equal
if temp_or == or_val:
ans = max(ans, r - l + 1)
# Print the result
if ans != 0:
print(ans)
else:
print(-1)
# Driver Code
S = "2347"
N = len(S)
A = [int(S[i]) for i in range(N)]
# Function Call
maxLength(A, N)
# This code is contributed by lokeshmvs21.
C#
// C# implementation of the above approach
using System;
using System.Linq;
public class GFG {
// Function to maximum length of
// substring of S
static void maxLength(int[] lis, int n)
{
long or = 0;
// Calculate OR of each element
// of string
for (int i = 0; i < n; i++) {
or |= lis[i];
}
int[] count = new int[32];
for (int i = 0; i < n; i++) {
for (int j = 0; j < 32; j++) {
if ((lis[i] & (1L << j)) != 0)
count[j]++;
}
}
long ans = 0, l = 0, tempOr = 0;
for (int r = 0; r < n; r++) {
tempOr |= lis[r];
bool flag = true;
for (int i = 0; i < 32; i++) {
if ((lis[r] & (1L << i)) != 0) {
count[i]--;
if (count[i] == 0)
flag = false;
}
}
// If flag = false
if (!flag) {
for (; l <= r;) {
bool flag1 = true;
for (int i = 0; i < 32; i++) {
if ((lis[(int)l] & (1L << i))
!= 0) {
count[i]++;
}
if (count[i] == 0)
flag1 = false;
}
l++;
if (flag1)
break;
}
}
// If OR of leftover elements and
// substring elements is equal
if (tempOr == or) {
ans = Math.Max(ans, r - l + 1);
}
}
// Print the result
if (ans != 0) {
Console.WriteLine(ans);
}
else {
Console.WriteLine(-1);
}
}
static public void Main()
{
// Code
string S = "2347";
int N = S.Length;
int[] A = new int[N];
for (int i = 0; i < N; i++) {
A[i] = S[i] - '0';
}
// Function call
maxLength(A, N);
}
}
// This code is contributed by lokesh.
C++
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
void maxLength(int lis[], int n)
{
long long or_result = 0;
// Calculate OR of each element
// of string
for (int i = 0; i < n; i++) {
or_result |= lis[i];
}
int count[32] = {0};
for (int i = 0; i < n; i++) {
for (int j = 0; j < 32; j++) {
if ((lis[i] & (1LL << j)) != 0)
count[j]++;
}
}
long long ans = 0, l = 0, tempOr = 0;
for (int r = 0; r < n; r++) {
tempOr |= lis[r];
bool flag = true;
for (int i = 0; i < 32; i++) {
if ((lis[r] & (1LL << i)) != 0) {
count[i]--;
if (count[i] == 0)
flag = false;
}
}
// If flag = false
if (!flag) {
for (; l <= r;) {
bool flag1 = true;
for (int i = 0; i < 32; i++) {
if ((lis[l] & (1LL << i)) != 0) {
count[i]++;
}
if (count[i] == 0)
flag1 = false;
}
l++;
if (flag1)
break;
}
}
// If OR of leftover elements and
// substring elements is equal
if (tempOr == or_result) {
ans = max(ans, r - l + 1);
}
}
// Print the result
if (ans != 0)
cout << ans << endl;
else
cout << -1 << endl;
}
// Driver Code
int main()
{
string S = "2347";
int N = S.length();
int A[N];
for (int i = 0; i < N; i++) {
A[i] = S.at(i) - '0';
}
// Function Call
maxLength(A, N);
return 0;
}
JavaScript
function maxLength( lis, n)
{
let or_result = 0;
// Calculate OR of each element
// of string
for (let i = 0; i < n; i++) {
or_result |= lis[i];
}
let count=new Array(32).fill(0);
for (let i = 0; i < n; i++) {
for (let j = 0; j < 32; j++) {
if ((lis[i] & (1 << j)) != 0)
count[j]++;
}
}
let ans = 0, l = 0, tempOr = 0;
for (let r = 0; r < n; r++) {
tempOr |= lis[r];
let flag = true;
for (let i = 0; i < 32; i++) {
if ((lis[r] & (1 << i)) != 0) {
count[i]--;
if (count[i] == 0)
flag = false;
}
}
// If flag = false
if (!flag) {
for (; l <= r;) {
let flag1 = true;
for (let i = 0; i < 32; i++) {
if ((lis[l] & (1 << i)) != 0) {
count[i]++;
}
if (count[i] == 0)
flag1 = false;
}
l++;
if (flag1)
break;
}
}
// If OR of leftover elements and
// substring elements is equal
if (tempOr == or_result) {
ans = Math.max(ans, r - l + 1);
}
}
// Print the result
if (ans != 0)
document.write(ans);
else
document.write(-1);
}
// Driver Code
let S = "2347";
let N = S.length;
let A=new Array(N);
for (let i = 0; i < N; i++) {
A[i] = parseInt(S[i]);
}
// Function Call
maxLength(A, N);
Time Complexity: O(30*N)
Auxiliary Space: O(1)
Related Articles:
Similar Reads
Find the Longest Non-Prefix-Suffix Substring in the Given String Given a string s of length n. The task is to determine the longest substring t such that t is neither the prefix nor the suffix of string s, and that substring must appear as both prefix and suffix of the string s. If no such string exists, print -1. Example: Input: s = "fixprefixsuffix"Output: fix
7 min read
Find longest substring of S1 that matches in S2 with a given cost Given two strings S1 and S2 of length n. Additionally, two positive integers, target and C. The task is to determine the maximum length of a contiguous substring in S1 such that, by changing any character in the substring of S1 to another character, the resulting substring matches the corresponding
12 min read
Print the longest common substring Given two strings âXâ and âYâ, print the length of the longest common substring. If two or more substrings have the same value for the longest common substring, then print any one of them. Examples: Input : X = "GeeksforGeeks", Y = "GeeksQuiz" Output : Geeks Input : X = "zxabcdezy", Y = "yzabcdezx"
15+ min read
Find length of repeating Substring Given a string s and a positive integer K, the task is to find the length of the longest contiguous substring that appears at least K times in s. Examples: Input: s = "abababcdabcd", K = 2Output: 4Explanation: "abcd" is the longest repeating substring at least K times. Input: s = "aacd", K = 4Output
11 min read
Print the longest palindromic prefix of a given string Given a string str, the task is to find the longest palindromic prefix of the given string. Examples: Input: str = "abaac" Output: aba Explanation: The longest prefix of the given string which is palindromic is "aba". Input: str = "abacabaxyz" Output: abacaba Explanation: The prefixes of the given s
12 min read
Longest substring of 0s in a string formed by k concatenations Given a binary string of length n and an integer k. Consider another string T which is formed by concatenating the given binary string k times. The task is to print the maximum size of a substring of T containing only zeroes. Examples: Input: str = 110010, k = 3 Output: 2 str = 110010 T = 1100101100
8 min read
Length of longest increasing subsequence in a string Given a string S, the task is to find the length of the longest increasing subsequence present in the given string. A sequence of characters placed in increasing order of their ASCII values is called an increasing sequence. Examples: Input: S = "abcfgffs"Output: 6Explanation: Subsequence "abcfgs" is
7 min read
Length of Longest sub-string that can be removed Given a binary string (consists of only 0 and 1). If there is "100" as a sub-string in the string, then we can delete this sub-string. The task is to find the length of longest sub-string which can be make removed? Examples: Input : str = "1011100000100" Output : 6 // Sub-strings present in str that
9 min read
Substring of length K having maximum frequency in the given string Given a string str, the task is to find the substring of length K which occurs the maximum number of times. If more than one string occurs maximum number of times, then print the lexicographically smallest substring. Examples: Input: str = "bbbbbaaaaabbabababa", K = 5Output: ababaExplanation:The sub
14 min read
K-th lexicographically smallest unique substring of a given string Given a string S. The task is to print the K-th lexicographically the smallest one among the different substrings of s.A substring of s is a string obtained by taking out a non-empty contiguous part in s. For example, if s = ababc, a, bab and ababc are substrings of s, while ac, z, and an empty stri
5 min read