When submitting a solution in C++, please select either C++14 (GCC 6-32) or C++17 (GCC 7-32) as your compiler. ×

i_priyanshu's blog

By i_priyanshu, history, 3 years ago, In English

Given a Binary string str and integer x , y. Return the no. of 1's occuring in between x and y indexes if the string can be repeated Infintely.

For Example — Str = "11010" int x = 7; int y = 23; return the count of all 1's between 7 and 23. if the String can be concatenated to itself infinite times.

  • Vote: I like it
  • -24
  • Vote: I do not like it

| Write comment?
»
3 years ago, # |
  Vote: I like it -21 Vote: I do not like it

First, you can define a function f(n), to calculate number of 1s from 1 to n

Then, in f(n), if the length of the binary string is m, you need to set an array nums of length m, with the ith element is the number of 1s between 1 and i, for example, 11010 correspond to [1,2,2,3,3], and the tot number of 1 in str is 3.

Finally, f(n) = nums[m] * (n//m) + nums[n%m+1] (1-based indexing), and the result is f(y+1) — f(x)

»
3 years ago, # |
  Vote: I like it 0 Vote: I do not like it

This is a problem you should be able to solve on your own with some thought. Perhaps you've already come up with this approach, but here's a hint:

Imagine an infinite string, with repetitions. Then the problem can be broken into 3 parts:

  1. x will start somewhere within a repetition. Find the number of ones until the end of the repetition. Then reassign x to the ending index.

  2. Find the number of full repetitions between x and y.

  3. Find the number of ones in the leftover indices.

Hope this helps!

»
3 years ago, # |
  Vote: I like it -21 Vote: I do not like it

prefix count of 1's and for every query take mod of x-1 and y-1 with string length.