Given a binary string S of length N and an integer K, the task is to find the smallest non-zero sub-string of S that can be jumbled to produce a binary string divisible by 2K. If no such sub-string exists then print -1. Note that K is always greater than 0. Examples:
Input: S = “100”, k = 1 Output: 2 Smallest substring that can be jumbled is “10”. Thus, the answer is 2. Input: S = “1111”, k = 2 Output: -1
Approach: Let’s look at the condition of the permutation of a string being divisible by 2K.
The string must have at least K number of 0s.
The string must have at least one 1.
This can be implemented using two-pointer technique. For every index i, try to find the smallest index j such that the substring S[i…j-1] satisfies the above two conditions. Let’s say the left pointer is pointing at index i and the right pointer is pointing at j and ans stores the length of the smallest required substring. If the condition is not satisfied then increment j, else increment i. While iterating, find the minimum (j – i) satisfying the above two conditions and update the answer as ans = min(ans, j – i). Below is the implementation of the above approach:
Please Login to comment...