Pretty Good Proportion (Small)
InterviewTime limit5sMemory limit512 MB
Given a binary string and a target fraction F, find the start index of the contiguous substring whose share of 1s is closest to F.
- Level
Medium4 of 10
- Topics
- Brute force, Prefix sum
- Solved
- No attempts yet
Problem
You have a string of binary digits. Find a contiguous substring whose fraction of 1s is as close as possible to a target value . A substring whose fraction equals exactly may not exist, so take the one with the smallest difference.
The fraction of 1s in a substring is the number of 1s in it divided by its length. Only substrings of length 1 or more count. Report the starting index of a substring that minimizes .
Input
The first line contains the number of test cases . Each test case takes two lines. The first line contains and , separated by a single space. is a decimal fraction between 0 and 1 inclusive with exactly 6 digits after the decimal point. The second line contains digits, each 0 or 1, with no separators.
Limits
- has exactly 6 digits after the decimal point.
Output
For each test case, print one line in the form Case #x: y, where is the test case number starting from 1 and is the starting index of the substring whose fraction of 1s is closest to . Indices are 0-based. If several substrings achieve the smallest error, print the smallest starting index among them.
Hint
Take the string 001001010111 with . No substring has a fraction of 1s equal to . The closest reachable value is , and five substrings reach it. The ones of length 3 start at indices 5, 7, and 8 (101, 101, 011), and the ones of length 6 start at indices 5 and 6 (101011, 010111). The smallest of those starting indices is 5.