![]() |
VOOZH | about |
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:
Below is the implementation of the above approach :
3
Time Complexity: O(30*N)
Auxiliary Space: O(1)
Related Articles: