VOOZH about

URL: https://www.geeksforgeeks.org/dsa/queries-for-decimal-values-of-subarray-of-a-binary-array/

⇱ Queries for decimal values of subarrays of a binary array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Queries for decimal values of subarrays of a binary array

Last Updated : 28 Mar, 2023

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]*

  1. Make an array pre[] of same size as of given array where pre[i] stores the sum of arr[j]*where j includes each value from i to n-1.
  2. The number represented by subarray arr[l..r] will be equal to (pre[l] - pre[r+1])/.pre[l] - pre[r+1] is equal to arr[l]*+ arr[l+1]*+......arr[r]*. So if we divide it by , we get the required answer


 

👁 Image
Flowchart

Implementation:


Output
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 :


Output
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.

Comment