Skip to content
Programmingoneonone
Programmingoneonone
  • Home
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programmingoneonone

HackerEarth Gaurav And Sub-array problem solution

YASH PAL, 31 July 2024
In this HackerEarth Gaurav And Sub-array problem solution, You are given an array A[] consisting of N non-negative integers. Now, you need to answer Q queries of the following type given an integer K in each query.
You need to find the minimum length L of any subarray of A, such that if all elements of this subarray are represented in binary notation and concatenated to form a binary string, then no of 1’s in the resulting string is at least K.
HackerEarth Gaurav And Sub-array problem solution

HackerEarth Gaurav And Sub-array problem solution.

#include <bits/stdc++.h>
using namespace std;

const int N = 1000005;
int sbit[N];
int a[N];
int sum[N];
int func(int n)
{
int cnt=0;
while(n)
{
n=n&(n-1);
cnt++;
}
return cnt;
}
void pre()
{
for(int i=0;i<N;i++)
{
sbit[i]=func(i);
}
}
void calSum(int n)
{
sum[0]=a[0];
for(int i=1;i<=n;i++)
{
sum[i]=sum[i-1]+sbit[a[i]];
}
}
bool check(int n,int x,int k)
{
for(int i=0;i<=n-x;i++)
{
if((sum[i+x]-sum[i])>=k)
{
return true;
}
}
return false;
}
int main()
{
pre();
int n,q,k;
scanf("%d%d",&n,&q);
a[0]=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
calSum(n);
while(q--)
{
scanf("%d",&k);
int lo,mid,hi,ans;
lo=1;
hi=n;
ans=-1;
while(hi-lo>=0)
{
mid=(lo+hi)/2;
if(check(n,mid,k))
{
ans=mid;
hi=mid-1;
}
else
{
lo=mid+1;
}
}
printf("%dn",ans);
}
return 0;
}
coding problems solutions

Post navigation

Previous post
Next post

Pages

  • About US
  • Contact US
  • Privacy Policy

Programing Practice

  • C Programs
  • java Programs

HackerRank Solutions

  • C
  • C++
  • Java
  • Python
  • Algorithm

Other

  • Leetcode Solutions
  • Interview Preparation

Programming Tutorials

  • DSA
  • C

CS Subjects

  • Digital Communication
  • Human Values
  • Internet Of Things
  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2025 Programmingoneonone | WordPress Theme by SuperbThemes