![]() |
VOOZH | about |
Given a binary array arr[], we to find the number represented by the subarray a[l..r]. There are multiple such queries.
Examples:
Input : arr[] = {1, 0, 1, 0, 1, 1};
l = 2, r = 4
l = 4, r = 5
Output : 5
3
Subarray 2 to 4 is 101 which is 5 in decimal.
Subarray 4 to 5 is 11 which is 3 in decimal.
Input : arr[] = {1, 1, 1}
l = 0, r = 2
l = 1, r = 2
Output : 7
3
A Simple Solution is to compute decimal value for every given range using simple binary to decimal conversion. Here each query takes O(len) time where len is length of range.
An Efficient Solution is to do per-computations, so that queries can be answered in O(1) time.
The number represented by subarray arr[l..r] is arr[l]*+ arr[l+1]*..... + arr[r]*
Implementation:
5 3
Time complexity: O(n)
Auxiliary Space: O(n)
Efficient approach :
traverse the array from the given start index to end index, multiplying each binary digit with the corresponding power of 2 and adding the result.
Implementation :
5 3
Time complexity: O(r-l+1), which is equivalent to the length of the subarray
Auxiliary Space: O(1), as we are not using any additional data structures.