Find the longest Substring of a given String S
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.
Input: S = “2347”
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”
Approach: The problem can be solved based on the following observation:
- 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 :
Time Complexity: O(30*N)
Auxiliary Space: O(1)
Please Login to comment...