Instruction
stringlengths 261
35k
| Response
stringclasses 1
value |
---|---|
For this Question: Given an array Arr of N integers. Find the number of subarrays of this array that are powerful.
A subarray [L, R] (1 <= L <= R <= N) is said to be powerful if the product A<sub>L</sub> * A<sub>L+1</sub> * ... * A<sub>R-1</sub> * A<sub>R</sub> is odd.The first line of input contains a single integer N
The second line of input contains N integers representing the elements of the array Arr
<b>Constraints </b>
1 <= N <= 100000
1 <= Arr[i] <= 100000Output the number of powerful subarrays of array Arr.Sample Input 1
5
2 4 4 5 3
Sample output 1
3
Sample Input 2
3
1 5 1
Sample Output 2
6
<b>Explanation:</b>
(3), (5), (3, 5) are the required subarrays.
(1), (2), (1), (1, 5), (5, 1]) (1, 5, 1) are the required subarrays., I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
long cnt=0;
long ans=0;
for(int i=0;i<n;i++){
if(a[i]&1){cnt++;}
else{
ans+=(cnt*(cnt+1))/2;
cnt=0;
}
}
ans+=(cnt*(cnt+1))/2;
cout<<ans;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array Arr of N integers. Find the number of subarrays of this array that are powerful.
A subarray [L, R] (1 <= L <= R <= N) is said to be powerful if the product A<sub>L</sub> * A<sub>L+1</sub> * ... * A<sub>R-1</sub> * A<sub>R</sub> is odd.The first line of input contains a single integer N
The second line of input contains N integers representing the elements of the array Arr
<b>Constraints </b>
1 <= N <= 100000
1 <= Arr[i] <= 100000Output the number of powerful subarrays of array Arr.Sample Input 1
5
2 4 4 5 3
Sample output 1
3
Sample Input 2
3
1 5 1
Sample Output 2
6
<b>Explanation:</b>
(3), (5), (3, 5) are the required subarrays.
(1), (2), (1), (1, 5), (5, 1]) (1, 5, 1) are the required subarrays., I have written this Solution Code: n = int(input())
arr = list(map(int,input().split()))
c=0
result=0
for i in arr:
if i % 2 != 0:
c += 1
else:
result += (c*(c+1)) / 2
c=0
result += (c*(c+1)) / 2
print(int(result)), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array Arr of N integers. Find the number of subarrays of this array that are powerful.
A subarray [L, R] (1 <= L <= R <= N) is said to be powerful if the product A<sub>L</sub> * A<sub>L+1</sub> * ... * A<sub>R-1</sub> * A<sub>R</sub> is odd.The first line of input contains a single integer N
The second line of input contains N integers representing the elements of the array Arr
<b>Constraints </b>
1 <= N <= 100000
1 <= Arr[i] <= 100000Output the number of powerful subarrays of array Arr.Sample Input 1
5
2 4 4 5 3
Sample output 1
3
Sample Input 2
3
1 5 1
Sample Output 2
6
<b>Explanation:</b>
(3), (5), (3, 5) are the required subarrays.
(1), (2), (1), (1, 5), (5, 1]) (1, 5, 1) are the required subarrays., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args)throws IOException {
InputStreamReader inputStreamReader=new InputStreamReader(System.in);
BufferedReader reader=new BufferedReader(inputStreamReader);
int n =Integer.parseInt(reader.readLine());
String str=reader.readLine();
String[] strarr=str.split(" ");
int[] arr=new int[n];
for(int i=0;i<n;i++){
arr[i]=Integer.parseInt(strarr[i]);
}
long noOfsubArrays=0;
int start=0;
boolean sFlag=false;
for(int i=0;i<n;i++){
if(arr[i]%2!=0){
if(!sFlag){
start=i;
noOfsubArrays++;
sFlag=true;
continue;
}
noOfsubArrays+=2;
int temp=start;
temp++;
while(temp<i){
temp++;
noOfsubArrays++;
}
}else if(arr[i]%2==0 && sFlag){
sFlag=false;
}
}
System.out.println(noOfsubArrays);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You think that integers divisible by K are nice. Given L and R (L<=R), find the number of nice integers from L to R (both inclusive).First Line of input contains three integers L R K
Constraints :
0 <= L <= R <= 1000000000000000000(10^18)
1 <= K <= 1000000000000000000(10^18)Output a single integer which is the number of nice integers from L to R (both inclusive).Sample input 1
1 10 2
Sample output 1
5
Sample intput 2
4 5 3
Sample output 2
0
Explanation:-
Required divisors = 2 4 6 8 10, I have written this Solution Code:
import java.io.*;
import java.util.*;
class Main{
public static void main(String[] args)throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str[]=br.readLine().split(" ");
long l=Long.parseLong(str[0]);
long r=Long.parseLong(str[1]);
long k=Long.parseLong(str[2]);
long count=(r/k)-((l-1)/k);
System.out.print(count);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You think that integers divisible by K are nice. Given L and R (L<=R), find the number of nice integers from L to R (both inclusive).First Line of input contains three integers L R K
Constraints :
0 <= L <= R <= 1000000000000000000(10^18)
1 <= K <= 1000000000000000000(10^18)Output a single integer which is the number of nice integers from L to R (both inclusive).Sample input 1
1 10 2
Sample output 1
5
Sample intput 2
4 5 3
Sample output 2
0
Explanation:-
Required divisors = 2 4 6 8 10, I have written this Solution Code: l,r,k=[int(x)for x in input().split()]
print(r//k - (l-1)//k), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You think that integers divisible by K are nice. Given L and R (L<=R), find the number of nice integers from L to R (both inclusive).First Line of input contains three integers L R K
Constraints :
0 <= L <= R <= 1000000000000000000(10^18)
1 <= K <= 1000000000000000000(10^18)Output a single integer which is the number of nice integers from L to R (both inclusive).Sample input 1
1 10 2
Sample output 1
5
Sample intput 2
4 5 3
Sample output 2
0
Explanation:-
Required divisors = 2 4 6 8 10, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main(){
unsigned long long x,l,r,k;
cin>>l>>r>>k;
x=l/k;
if(l%k==0){x--;}
cout<<r/k-x;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: N numbers are arranged in Circle. Find the Sum of all K contiguous Sub-arrays.The first line of the input contains an integer N, the length of the array, and K. The next line contains N integers which are elements of the array.
<b>User task:</b> Since this is a functional problem you don't have to worry about the input. You just have to complete the function kCircleSum(arr, N, K) which contains arr(array) and N(size of the array), and K as a parameter
<b>Constraints</b>
1 <= N <= 100000
1 <= arr[I] <= 100000
1 <= K <= NYou need to print N space-separated integers ith integer denoting Sum of sub-array of length K starting at index i.Sample Input
3 1
1 2 3
Sample Output
1 2 3
Explanation : k=1 so ans is 1, 2, and 3.
Sample Input
5 2
6 4 3 4 1
Sample Output
10 7 7 5 7, I have written this Solution Code: void kCircleSum(int arr[],int n,int k){
long long ans=0;
for(int i=0;i<k;i++){
ans+=arr[i];
}
for(int i=0;i<n;i++){
printf("%lli ",ans);
ans+=arr[(i+k)%n]-arr[i];
}
}, In this Programming Language: C, Now tell me if this Code is compilable or not? | Compilable |
For this Question: N numbers are arranged in Circle. Find the Sum of all K contiguous Sub-arrays.The first line of the input contains an integer N, the length of the array, and K. The next line contains N integers which are elements of the array.
<b>User task:</b> Since this is a functional problem you don't have to worry about the input. You just have to complete the function kCircleSum(arr, N, K) which contains arr(array) and N(size of the array), and K as a parameter
<b>Constraints</b>
1 <= N <= 100000
1 <= arr[I] <= 100000
1 <= K <= NYou need to print N space-separated integers ith integer denoting Sum of sub-array of length K starting at index i.Sample Input
3 1
1 2 3
Sample Output
1 2 3
Explanation : k=1 so ans is 1, 2, and 3.
Sample Input
5 2
6 4 3 4 1
Sample Output
10 7 7 5 7, I have written this Solution Code: function kCircleSum(arr, arrSize, k)
{
var list = new Array(2*arrSize + 5)
for(var i = 0; i < arrSize; i++)
{
list[i+1] = arr[i]
list[i+arrSize+1] = list[i+1]
}
for(var i = 0; i < 2*arrSize; i++)
dp[i] = 0
for(var i=1;i<=2*arrSize;i++)
{
dp[i] = dp[i-1]+list[i]
}
var ans = ""
for(var i = 1; i <= arrSize; i++)
{
ans += (dp[i+k-1]-dp[i-1]) + " "
}
console.log(ans)
}, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: N numbers are arranged in Circle. Find the Sum of all K contiguous Sub-arrays.The first line of the input contains an integer N, the length of the array, and K. The next line contains N integers which are elements of the array.
<b>User task:</b> Since this is a functional problem you don't have to worry about the input. You just have to complete the function kCircleSum(arr, N, K) which contains arr(array) and N(size of the array), and K as a parameter
<b>Constraints</b>
1 <= N <= 100000
1 <= arr[I] <= 100000
1 <= K <= NYou need to print N space-separated integers ith integer denoting Sum of sub-array of length K starting at index i.Sample Input
3 1
1 2 3
Sample Output
1 2 3
Explanation : k=1 so ans is 1, 2, and 3.
Sample Input
5 2
6 4 3 4 1
Sample Output
10 7 7 5 7, I have written this Solution Code: static void kCircleSum(int arr[],int n,int k){
long ans=0;
for(int i=0;i<k;i++){
ans+=arr[i];
}
for(int i=0;i<n;i++){
System.out.print(ans+" ");
ans+=arr[(i+k)%n]-arr[i];
}
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: N numbers are arranged in Circle. Find the Sum of all K contiguous Sub-arrays.The first line of the input contains an integer N, the length of the array, and K. The next line contains N integers which are elements of the array.
<b>User task:</b> Since this is a functional problem you don't have to worry about the input. You just have to complete the function kCircleSum(arr, N, K) which contains arr(array) and N(size of the array), and K as a parameter
<b>Constraints</b>
1 <= N <= 100000
1 <= arr[I] <= 100000
1 <= K <= NYou need to print N space-separated integers ith integer denoting Sum of sub-array of length K starting at index i.Sample Input
3 1
1 2 3
Sample Output
1 2 3
Explanation : k=1 so ans is 1, 2, and 3.
Sample Input
5 2
6 4 3 4 1
Sample Output
10 7 7 5 7, I have written this Solution Code: def kCircleSum(arr,n,k):
ans=0
for i in range (0,k):
ans=ans+arr[i]
for i in range (0,n):
print(ans,end=" ")
ans=ans+arr[int((i+k)%n)]-arr[i]
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: N numbers are arranged in Circle. Find the Sum of all K contiguous Sub-arrays.The first line of the input contains an integer N, the length of the array, and K. The next line contains N integers which are elements of the array.
<b>User task:</b> Since this is a functional problem you don't have to worry about the input. You just have to complete the function kCircleSum(arr, N, K) which contains arr(array) and N(size of the array), and K as a parameter
<b>Constraints</b>
1 <= N <= 100000
1 <= arr[I] <= 100000
1 <= K <= NYou need to print N space-separated integers ith integer denoting Sum of sub-array of length K starting at index i.Sample Input
3 1
1 2 3
Sample Output
1 2 3
Explanation : k=1 so ans is 1, 2, and 3.
Sample Input
5 2
6 4 3 4 1
Sample Output
10 7 7 5 7, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
void kCircleSum(int arr[],int n,int k){
long long ans=0;
for(int i=0;i<k;i++){
ans+=arr[i];
}
for(int i=0;i<n;i++){
printf("%lli ",ans);
ans+=arr[(i+k)%n]-arr[i];
}
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a binary sorted non-increasing array arr of size <b>N</b>. You need to print the count of <b>1's</b> in the binary array.
Try to solve the problem using binary searchThe input line contains T, denotes the number of testcases.
Each test case contains two lines. The first line contains N (size of binary array). The second line contains N elements of binary array separated by space.
<b>Constraints:</b>
1 <= T <= 100
1 <= N <= 10^6
arr[i] = 0,1
<b>Sum of N over all testcases does not exceed 10^6</b>For each testcase in new line, print the count 1's in binary array.Input:
2
8
1 1 1 1 1 0 0 0
8
1 1 0 0 0 0 0 0
Output:
5
2
Explanation:
Testcase 1: Number of 1's in given binary array : 1 1 1 1 1 0 0 0 is 5.
Testcase 2: Number of 1's in given binary array : 1 1 0 0 0 0 0 0 is 2., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64];
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static void main (String[] args) throws IOException {
Reader sc=new Reader();
int t=sc.nextInt();
while(t-->0){
int n=sc.nextInt();
int[] a=new int[n];
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
}
int count=search(a,0,n-1);
System.out.println(count);
}
}
public static int search(int[] a,int l,int h){
while(l<=h){
int mid=l+(h-l)/2;
if ((mid==h||a[mid+1]==0)&&(a[mid]==1))
return mid+1;
if (a[mid]==1)
l=mid+1;
else h=mid-1;
}
return 0;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a binary sorted non-increasing array arr of size <b>N</b>. You need to print the count of <b>1's</b> in the binary array.
Try to solve the problem using binary searchThe input line contains T, denotes the number of testcases.
Each test case contains two lines. The first line contains N (size of binary array). The second line contains N elements of binary array separated by space.
<b>Constraints:</b>
1 <= T <= 100
1 <= N <= 10^6
arr[i] = 0,1
<b>Sum of N over all testcases does not exceed 10^6</b>For each testcase in new line, print the count 1's in binary array.Input:
2
8
1 1 1 1 1 0 0 0
8
1 1 0 0 0 0 0 0
Output:
5
2
Explanation:
Testcase 1: Number of 1's in given binary array : 1 1 1 1 1 0 0 0 is 5.
Testcase 2: Number of 1's in given binary array : 1 1 0 0 0 0 0 0 is 2., I have written this Solution Code: #include "bits/stdc++.h"
#pragma GCC optimize "03"
using namespace std;
#define int long long int
#define ld long double
#define pi pair<int, int>
#define pb push_back
#define fi first
#define se second
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#ifndef LOCAL
#define endl '\n'
#endif
const int N = 1e6 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
int a[N];
signed main() {
IOS;
int t; cin >> t;
while(t--){
int n; cin >> n;
for(int i = 1; i <= n; i++)
cin >> a[i];
int l = 0, h = n+1;
while(l+1 < h){
int m = (l + h) >> 1;
if(a[m] == 1)
l = m;
else
h = m;
}
cout << l << endl;
}
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a binary sorted non-increasing array arr of size <b>N</b>. You need to print the count of <b>1's</b> in the binary array.
Try to solve the problem using binary searchThe input line contains T, denotes the number of testcases.
Each test case contains two lines. The first line contains N (size of binary array). The second line contains N elements of binary array separated by space.
<b>Constraints:</b>
1 <= T <= 100
1 <= N <= 10^6
arr[i] = 0,1
<b>Sum of N over all testcases does not exceed 10^6</b>For each testcase in new line, print the count 1's in binary array.Input:
2
8
1 1 1 1 1 0 0 0
8
1 1 0 0 0 0 0 0
Output:
5
2
Explanation:
Testcase 1: Number of 1's in given binary array : 1 1 1 1 1 0 0 0 is 5.
Testcase 2: Number of 1's in given binary array : 1 1 0 0 0 0 0 0 is 2., I have written this Solution Code: c=int(input())
for x in range(c):
size=int(input())
s=input()
print(s.count('1')), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Traverse through the tree according to preorder traversal and print the elements of the tree while traversing.The first line of the input contains an integer N, the number of nodes in the tree.
The N lines contains two integers s, d representing parent and child
Constraints
2 <= N <= 100000
1 <= s, d <= 100000
Print the nodes in pre-order traversal.Input
5
1 2
1 3
2 4
2 5
Output:1 2 4 5 3
Input:
5
1 2
1 3
1 4
4 5
Output: 1 2 3 4 5, I have written this Solution Code: #include<bits/stdc++.h>
using namespace std;
#define pu push_back
#define fi first
#define se second
#define mp make_pair
#define int long long
#define pii pair<int,int>
#define mm (s+e)/2
#define all(x) x.begin(), x.end()
#define For(i, st, en) for(int i=st; i<en; i++)
#define tr(x) for(auto it=x.begin(); it!=x.end(); it++)
#define fast std::ios::sync_with_stdio(false);cin.tie(NULL);
#define sz 200000
vector<int> NEB[sz];
void dfs(int s,int f)
{
cout<<s<<" ";
for(auto it:NEB[s])
{
if(it!=f)
{
dfs(it,s);
}
}
}
signed main()
{
int n;
cin>>n;
for(int i=0;i<n-1;i++)
{
int a,b;
cin>>a>>b;
NEB[a].pu(b);
NEB[b].pu(a);
}
for(int i=1;i<=n;i++)
{
sort(NEB[i].begin(),NEB[i].end());
}
dfs(1,-1);
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Let's define P[i] as the ith Prime Number. Therefore, P[1]=2, P[2]=3, P[3]=5, so on.
Given two integers L, R (L<=R), find the value of P[L]+P[L+1]+P[L+2]...+P[R].The first line of the input contains an integer T denoting the number of test cases.
The next T lines contain two integers L and R.
Constraints
1 <= T <= 50000
1 <= L <= R <= 50000For each test case, print one line corresponding to the required valueSample Input
4
1 3
2 4
5 5
1 5
Sample Output
10
15
11
28, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t= Integer.parseInt(br.readLine());
int max = 1000001;
boolean isNotPrime[] = new boolean[max];
ArrayList<Integer> arr = new ArrayList<Integer>();
isNotPrime[0] = true; isNotPrime[1] = true;
for (int i=2; i*i <max; i++) {
if (!isNotPrime[i]) {
for (int j=i*i; j<max; j+= i) {
isNotPrime[j] = true;
}
}
}
for(int i=2; i<max; i++) {
if(!isNotPrime[i]) {
arr.add(i);
}
}
while(t-- > 0) {
String str[] = br.readLine().trim().split(" ");
int l = Integer.parseInt(str[0]);
int r = Integer.parseInt(str[1]);
System.out.println(primeRangeSum(l,r,arr));
}
}
static long primeRangeSum(int l , int r, ArrayList<Integer> arr) {
long sum = 0;
for(int i=l; i<=r;i++) {
sum += arr.get(i-1);
}
return sum;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Let's define P[i] as the ith Prime Number. Therefore, P[1]=2, P[2]=3, P[3]=5, so on.
Given two integers L, R (L<=R), find the value of P[L]+P[L+1]+P[L+2]...+P[R].The first line of the input contains an integer T denoting the number of test cases.
The next T lines contain two integers L and R.
Constraints
1 <= T <= 50000
1 <= L <= R <= 50000For each test case, print one line corresponding to the required valueSample Input
4
1 3
2 4
5 5
1 5
Sample Output
10
15
11
28, I have written this Solution Code: def SieveOfEratosthenes(n):
prime = [True for i in range(n+1)]
pri = []
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
for p in range(2, n+1):
if prime[p]:
pri.append(p)
return pri
N = int(input())
X = []
prim = SieveOfEratosthenes(1000000)
for i in range(1,len(prim)):
prim[i] = prim[i]+prim[i-1]
for i in range(N):
nnn = input()
X.append((int(nnn.split()[0]),int(nnn.split()[1])))
for xx,yy in X:
if xx==1:
print(prim[yy-1])
else:
print(prim[yy-1]-prim[xx-2])
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Let's define P[i] as the ith Prime Number. Therefore, P[1]=2, P[2]=3, P[3]=5, so on.
Given two integers L, R (L<=R), find the value of P[L]+P[L+1]+P[L+2]...+P[R].The first line of the input contains an integer T denoting the number of test cases.
The next T lines contain two integers L and R.
Constraints
1 <= T <= 50000
1 <= L <= R <= 50000For each test case, print one line corresponding to the required valueSample Input
4
1 3
2 4
5 5
1 5
Sample Output
10
15
11
28, I have written this Solution Code: #include "bits/stdc++.h"
#pragma GCC optimize "03"
using namespace std;
#define int long long int
#define ld long double
#define pi pair<int, int>
#define pb push_back
#define fi first
#define se second
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#ifndef LOCAL
#define endl '\n'
#endif
const int N = 1e6 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
int a[N];
signed main() {
IOS;
vector<int> v;
v.push_back(0);
for(int i = 2; i < N; i++){
if(a[i]) continue;
v.push_back(i);
for(int j = i*i; j < N; j += i)
a[j] = 1;
}
int p = 0;
for(auto &i: v){
i += p;
p = i;
}
int t; cin >> t;
while(t--){
int l, r;
cin >> l >> r;
cout << v[r] - v[l-1] << endl;
}
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: A conveyor belt has parcels that must be shipped from one point to another within D days.
The i-th parcel on the conveyor belt has a weight of weights[i]. Each day, we load the ship with parcels on the conveyor belt (in the order given). We may not load more weight than the maximum weight capacity of the ship.
Return the least weight capacity of the ship that will result in all the parcels on the conveyor belt being shipped within D days.
Note:- the cargo must be shipped in the order givenThe input line contains T, denoting the number of testcases. Each testcase contains two lines. First line N ,contains size of the conveyor belt and D days separated by space. Second line contains weights of parcels.
Constraints:
1 <= T <= 100
1 <= D <= N <= 5*10^4
1 <= weights[i] <= 500
Sum if N over all test cases is <= 1000000For each testcase you need to print the least weight capacity of the ship that will result in all the parcels on the conveyor belt being shipped within D days.Sample Input:
2
10 5
1 2 3 4 5 6 7 8 9 10
6 3
3 2 2 4 1 4
Sample Output:
15
6
Explanation:
Testcase 1:
A ship capacity of 15 is the minimum to ship all the parcels in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10
Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the parcels into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed., I have written this Solution Code: def isValid(weight, n, D, mx):
st = 1
sum = 0
for i in range(n):
sum += weight[i]
if (sum > mx):
st += 1
sum = weight[i]
if (st > D):
return False
return True
def shipWithinDays(weight, D, n):
sum = 0
for i in range(n):
sum += weight[i]
s = weight[0]
for i in range(1, n):
s = max(s, weight[i])
e = sum
res = -1
while (s <= e):
mid = s + (e - s) // 2
if (isValid(weight, n, D, mid)):
res = mid
e = mid - 1
else:
s = mid + 1
print(res)
if __name__ == '__main__':
n=int(input())
l=[]
for r in range(n):
leng,D=input().split()
D=int(D)
weight=input().split()
weight = [ int(i) for i in weight ]
N = len(weight)
l.append(shipWithinDays(weight, D, N))
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: A conveyor belt has parcels that must be shipped from one point to another within D days.
The i-th parcel on the conveyor belt has a weight of weights[i]. Each day, we load the ship with parcels on the conveyor belt (in the order given). We may not load more weight than the maximum weight capacity of the ship.
Return the least weight capacity of the ship that will result in all the parcels on the conveyor belt being shipped within D days.
Note:- the cargo must be shipped in the order givenThe input line contains T, denoting the number of testcases. Each testcase contains two lines. First line N ,contains size of the conveyor belt and D days separated by space. Second line contains weights of parcels.
Constraints:
1 <= T <= 100
1 <= D <= N <= 5*10^4
1 <= weights[i] <= 500
Sum if N over all test cases is <= 1000000For each testcase you need to print the least weight capacity of the ship that will result in all the parcels on the conveyor belt being shipped within D days.Sample Input:
2
10 5
1 2 3 4 5 6 7 8 9 10
6 3
3 2 2 4 1 4
Sample Output:
15
6
Explanation:
Testcase 1:
A ship capacity of 15 is the minimum to ship all the parcels in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10
Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the parcels into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed., I have written this Solution Code: import java.util.*;
import java.io.*;
import java.lang.*;
class Main
{
public static void main(String args[])throws IOException
{
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(read.readLine());
while(t-- > 0)
{
String str[] = read.readLine().trim().split(" ");
int N = Integer.parseInt(str[0]);
int D = Integer.parseInt(str[1]);
int arr[] = new int[N];
str = read.readLine().trim().split(" ");
for(int i = 0; i < N; i++)
arr[i] = Integer.parseInt(str[i]);
int res = shipWithinDays(arr, D);
//print(res);
System.out.println(res);
}
}
static void print(int list[])
{
for(int i = 0; i < list.length; i++)
System.out.print(list[i] + " ");
}
public static int shipWithinDays(int[] weights, int D) {
// set lower/upper bound for binary search
int low = 0, high = 0;
for(int weight: weights) {
low = Math.max(low, weight);
high += weight;
}
while(low < high) {
int mid = low + (high - low)/2;
if(calDays(mid, weights) > D) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
public static int calDays(int w, int[] weights) {
int days = 0;
int accuSum = 0;
for(int i=0;i<weights.length;i++) {
if(accuSum + weights[i] <= w) {
accuSum += weights[i];
} else {
accuSum = weights[i];
days++;
}
}
if(accuSum>0) {
days++;
}
return days;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: A conveyor belt has parcels that must be shipped from one point to another within D days.
The i-th parcel on the conveyor belt has a weight of weights[i]. Each day, we load the ship with parcels on the conveyor belt (in the order given). We may not load more weight than the maximum weight capacity of the ship.
Return the least weight capacity of the ship that will result in all the parcels on the conveyor belt being shipped within D days.
Note:- the cargo must be shipped in the order givenThe input line contains T, denoting the number of testcases. Each testcase contains two lines. First line N ,contains size of the conveyor belt and D days separated by space. Second line contains weights of parcels.
Constraints:
1 <= T <= 100
1 <= D <= N <= 5*10^4
1 <= weights[i] <= 500
Sum if N over all test cases is <= 1000000For each testcase you need to print the least weight capacity of the ship that will result in all the parcels on the conveyor belt being shipped within D days.Sample Input:
2
10 5
1 2 3 4 5 6 7 8 9 10
6 3
3 2 2 4 1 4
Sample Output:
15
6
Explanation:
Testcase 1:
A ship capacity of 15 is the minimum to ship all the parcels in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10
Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the parcels into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed., I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n,d;
cin>>n>>d;
long sum=0;
long ma=0;
long a[n];
for(int i=0;i<n;i++){
cin>>a[i];
sum+=a[i];
ma=max(ma,a[i]);
}
long low=ma;
long high=sum;
int mid;
while(low<high){
mid=low+(high-low)/2;
int ans=0;
int i=0;
int cnt=1;
while(i<n){
ans+=a[i];
if(ans>mid){
ans=a[i];
cnt++;
}
i++;
}
if(cnt<=d){high=mid;}
else
{
low=mid+1;
}
}
cout<<low<<endl;}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Write a function called lucky_sevens which takes an array of integers and returns true if any three consecutive elements sum to 7An array containing numbers.Print true if such triplet exists summing to 7 else print falseSample input:-
[2, 1, 5, 1, 0]
[1, 6]
Sample output:-
true
false
Explanation:-
1+5+1 = 7
no 3 consecutive numbers so false, I have written this Solution Code: function lucky_sevens(arr) {
// if less than 3 elements then this challenge is not possible
if (arr.length < 3) {
console.log(false)
return;
}
// because we know there are at least 3 elements we can
// start the loop at the 3rd element in the array (i=2)
// and check it along with the two previous elements (i-1) and (i-2)
for (let i = 2; i < arr.length; i++) {
if (arr[i] + arr[i-1] + arr[i-2] === 7) {
console.log(true)
return;
}
}
// if loop is finished and no elements summed to 7
console.log(false)
}
, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given a string S consisting of lowercase English letters. Determine whether adding some number of a's (possibly zero) at the beginning of S can make it a palindrome.The input consists of a single string S.
Constraints
1 ≤ ∣S∣ ≤ 10^6
S consists of lowercase English letters.If adding some number of a's (possibly zero) at the beginning of S can make it a palindrome, print Yes; otherwise, print No.<b>Sample Input 1</b>
kasaka
<b>Sample Output 1</b>
Yes
<b>Sample Input 2</b>
reveh
<b>Sample Output 2</b>
No, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main(void) {
int n, x, y;
string a;
cin >> a;
n = a.size();
x = 0;
for (int i = 0; i < n; i++) {
if (a[i] == 'a')x++;
else break;
}
y = 0;
for (int i = n - 1; i >= 0; i--) {
if (a[i] == 'a')y++;
else break;
}
if (x == n) {
cout << "Yes" << endl;
return 0;
}
if (x > y) {
cout << "No" << endl;
return 0;
}
for (int i = x; i < (n - y); i++) {
if (a[i] != a[x + n - y - i - 1]) {
cout << "No" << endl;
return 0;
}
}
cout << "Yes" << endl;
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: N people are standing in line numbered 1 to N from left to right. Each person wants to know the height of the person to left of him having height less than him. If there are multiple such people he wants to know the height of the person closest to him.
If there is no such person report -1.The first line of input contains N, the size of the array.
The second line of input contains N space-separated integers.
Constraints
2 ≤ N ≤ 100000
0 ≤ Arr[i] ≤ 1000000000 (Height can be zero wierd people :p )The output should contain N space separated integers, the ith integer should be the height reported to ith person (-1 if no person to the left is found whose height is less).Sample Input 1
5
1 2 3 4 5
Sample Output 1
-1 1 2 3 4
Sample Input 2
2
1 1
Sample Output 2
-1 -1, I have written this Solution Code: import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Stack;
import java.util.StringTokenizer;
public class Main {
final static long MOD = 1000000007;
public static void main(String args[]) {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = fs.nextInt();
int[] a = fs.nextIntArray(n);
Stack<Integer> stck = new Stack<>();
for (int i = 0; i < n; i++) {
while (!stck.isEmpty() && stck.peek() >= a[i]) {
stck.pop();
}
if (stck.isEmpty()) {
out.print("-1 ");
stck.push(a[i]);
} else {
out.print(stck.peek() + " ");
stck.push(a[i]);
}
}
out.flush();
out.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
} catch (Exception e) {
e.printStackTrace();
}
}
public String next() {
if (st.hasMoreTokens())
return st.nextToken();
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
String line = "";
try {
line = br.readLine();
} catch (Exception e) {
e.printStackTrace();
}
return line;
}
public char nextChar() {
return next().charAt(0);
}
public Integer[] nextIntegerArray(int n) {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public char[] nextCharArray() {
return nextLine().toCharArray();
}
}
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: N people are standing in line numbered 1 to N from left to right. Each person wants to know the height of the person to left of him having height less than him. If there are multiple such people he wants to know the height of the person closest to him.
If there is no such person report -1.The first line of input contains N, the size of the array.
The second line of input contains N space-separated integers.
Constraints
2 ≤ N ≤ 100000
0 ≤ Arr[i] ≤ 1000000000 (Height can be zero wierd people :p )The output should contain N space separated integers, the ith integer should be the height reported to ith person (-1 if no person to the left is found whose height is less).Sample Input 1
5
1 2 3 4 5
Sample Output 1
-1 1 2 3 4
Sample Input 2
2
1 1
Sample Output 2
-1 -1, I have written this Solution Code: import sys
n=int(input())
myList = [int(x) for x in sys.stdin.readline().rstrip().split(' ')]
outputList = []
outputList.append(-1);
for i in range(1,len(myList),1):
flag=False
for j in range(i-1,-1,-1):
if myList[j]<myList[i]:
outputList.append(myList[j])
flag=True
break
if flag==False:
outputList.append(-1)
print(*outputList), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: N people are standing in line numbered 1 to N from left to right. Each person wants to know the height of the person to left of him having height less than him. If there are multiple such people he wants to know the height of the person closest to him.
If there is no such person report -1.The first line of input contains N, the size of the array.
The second line of input contains N space-separated integers.
Constraints
2 ≤ N ≤ 100000
0 ≤ Arr[i] ≤ 1000000000 (Height can be zero wierd people :p )The output should contain N space separated integers, the ith integer should be the height reported to ith person (-1 if no person to the left is found whose height is less).Sample Input 1
5
1 2 3 4 5
Sample Output 1
-1 1 2 3 4
Sample Input 2
2
1 1
Sample Output 2
-1 -1, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
stack <long long > s;
long long a;
for(int i=0;i<n;i++){
cin>>a;
while(!(s.empty())){
if(s.top()<a){break;}
s.pop();
}
if(s.empty()){cout<<-1<<" ";}
else{cout<<s.top()<<" ";}
s.push(a);
}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You will be given an array of several arrays that each contain integers and your goal is to write a function that
will sum up all the numbers in all the arrays. For example, if the input is [[3, 2], [1], [4, 12]] then your
program should output 22 because 3 + 2 + 1 + 4 + 12 = 22An array containing arrays which can contain any number of elements.Sum of all the elements in all of the arrays.Sample input:-
[[3, 2], [1], [4, 12]]
Sample output:-
22
Explanation:-
3 + 2 + 1 + 4 + 12 = 22, I have written this Solution Code: function sum_array(arr) {
// store our final answer
var sum = 0;
// loop through entire array
for (var i = 0; i < arr.length; i++) {
// loop through each inner array
for (var j = 0; j < arr[i].length; j++) {
// add this number to the current final sum
sum += arr[i][j];
}
}
console.log(sum);
}, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: The coolness of the subarray of an array is the sum of elements in the subarray. The coolest subarray is the subarray having the maximum coolness, while the hottest subarray is the one having minimum coolness (obviously it can be negative). The coolest and the hottest subarrays are always <b>non-empty</b>.
Tono believes that cool and hot are happy together. The happiness of the array is the absolute difference between the coolness of its coolest and its hottest subarray.
Given an array A consisting of N elements, find its happiness.The first line of the input contains an integer N.
The next line contains N singly spaced integers A[1], A[2],...A[N]
Constraints
1 <= N <= 200000
-1000000000 <= A[i] <= 1000000000Output a single integer, the happiness of the array.
(The output may not fit into 32 bit integer datatype, use long long integer datatype instead).Sample Input
5
-1 2 -3 1 -5
Sample Output
9
Explanation: Coolest subarray of the array is [2], while the hottest subarray of the array is [-3, 1, -5]. The happiness of the array is 2-(-7)=9., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static long KadanesAlgoMax(int[] a,int n)
{
long maxSum=Integer.MIN_VALUE;
long currSum=0;
for(int i=0;i<n;i++)
{
currSum+=a[i];
if(currSum>maxSum)maxSum=currSum;
if(currSum<0)currSum=0;
}
return maxSum;
}
public static long KadanesAlgoMin(int[] a,int n)
{
long minSum=Integer.MAX_VALUE;
long currSum=0;
for(int i=0;i<n;i++)
{
currSum+=a[i];
if(currSum<minSum)minSum=currSum;
if(currSum>0)currSum=0;
}
return minSum;
}
public static void main (String[] args)throws IOException {
BufferedReader rd=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(rd.readLine());
String[] s=rd.readLine().split(" ");
int[] a=new int[n];
for(int i=0;i<n;i++)
{
a[i]=Integer.parseInt(s[i]);
}
System.out.print((long)Math.abs(KadanesAlgoMax(a,n)-KadanesAlgoMin(a,n)));
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: The coolness of the subarray of an array is the sum of elements in the subarray. The coolest subarray is the subarray having the maximum coolness, while the hottest subarray is the one having minimum coolness (obviously it can be negative). The coolest and the hottest subarrays are always <b>non-empty</b>.
Tono believes that cool and hot are happy together. The happiness of the array is the absolute difference between the coolness of its coolest and its hottest subarray.
Given an array A consisting of N elements, find its happiness.The first line of the input contains an integer N.
The next line contains N singly spaced integers A[1], A[2],...A[N]
Constraints
1 <= N <= 200000
-1000000000 <= A[i] <= 1000000000Output a single integer, the happiness of the array.
(The output may not fit into 32 bit integer datatype, use long long integer datatype instead).Sample Input
5
-1 2 -3 1 -5
Sample Output
9
Explanation: Coolest subarray of the array is [2], while the hottest subarray of the array is [-3, 1, -5]. The happiness of the array is 2-(-7)=9., I have written this Solution Code: l = int(input())
arr = list(map(int,input().split()))
maxSum = arr[0]
currSum =0
maxSumB = arr[0]
currSumB = 0
for j in range(0,l):
currSum = currSum + arr[j]
if(maxSum>currSum):
maxSum = currSum
if(currSum>0):
currSum = 0
currSumB = currSumB + arr[j]
if(maxSumB<currSumB):
maxSumB = currSumB
if(currSumB<0):
currSumB = 0
print(abs(maxSumB-maxSum)), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: The coolness of the subarray of an array is the sum of elements in the subarray. The coolest subarray is the subarray having the maximum coolness, while the hottest subarray is the one having minimum coolness (obviously it can be negative). The coolest and the hottest subarrays are always <b>non-empty</b>.
Tono believes that cool and hot are happy together. The happiness of the array is the absolute difference between the coolness of its coolest and its hottest subarray.
Given an array A consisting of N elements, find its happiness.The first line of the input contains an integer N.
The next line contains N singly spaced integers A[1], A[2],...A[N]
Constraints
1 <= N <= 200000
-1000000000 <= A[i] <= 1000000000Output a single integer, the happiness of the array.
(The output may not fit into 32 bit integer datatype, use long long integer datatype instead).Sample Input
5
-1 2 -3 1 -5
Sample Output
9
Explanation: Coolest subarray of the array is [2], while the hottest subarray of the array is [-3, 1, -5]. The happiness of the array is 2-(-7)=9., I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#define sd(x) scanf("%d", &x)
#define sz(v) (int) v.size()
#define pr(v) For(i, 0, sz(v)) {cout<<v[i]<<" ";} cout<<endl;
#define slld(x) scanf("%lld", &x)
#define all(x) x.begin(), x.end()
#define For(i, st, en) for(ll i=st; i<en; i++)
#define tr(x) for(auto it=x.begin(); it!=x.end(); it++)
#define fast std::ios::sync_with_stdio(false);cin.tie(NULL);
#define pb push_back
#define ll long long
#define int long long
#define mp make_pair
#define F first
#define S second
typedef pair<int, int> pii;
typedef vector<int> vi;
#define MOD 1000000007
#define INF 1000000000000000007LL
const int N = 200005;
// it's swapnil07 ;)
#ifdef SWAPNIL07
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
cout << name << " : " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
const char* comma = strchr(names + 1, ',');cout.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
}
int begtime = clock();
#define end_routine() cout << "\n\nTime elapsed: " << (clock() - begtime)*1000/CLOCKS_PER_SEC << " ms\n\n";
#else
#define endl '\n'
#define trace(...)
#define end_routine()
#endif
int arr[N];
int n;
int kadane(){
int sum = 0;
int mx = 0;
For(i, 0, n){
sum += arr[i];
if(sum < 0){
sum = 0;
}
mx = max(sum, mx);
}
if(mx > 0)
return mx;
// all elements negative
mx = -10000000000LL;
For(i, 0, n){
mx = max(mx, arr[i]);
}
return mx;
}
signed main()
{
fast
#ifdef SWAPNIL07
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
cin>>n;
For(i, 0, n){
cin>>arr[i];
}
int v1 = kadane();
For(i, 0, n){
arr[i]=-1*arr[i];
}
int v2 = kadane();
cout<<v1+v2;
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Numbers are awesome, larger numbers are more awesome!
Given an array A of size N, you need to find the maximum sum that can be obtained from the elements of the array (the selected elements need not be contiguous). You may even decide to take no element to get a sum of 0.The first line of the input contains the size of the array.
The next line contains N (white-space separated) integers denoting the elements of the array.
<b>Constraints:</b>
1 ≤ N ≤ 10<sup>4</sup>
-10<sup>7</sup> ≤ A[i] ≤10<sup>7</sup>For each test case, output one integer representing the maximum value of the sum that can be obtained using the various elements of the array.Input 1:
5
1 2 1 -1 1
output 1:
5
input 2:
5
0 0 -1 0 0
output 2:
0
<b>Explanation 1:</b>
In order to maximize the sum among [ 1 2 1 -1 1], we need to only consider [ 1 2 1 1] and neglect the [-1]., I have written this Solution Code: #include "bits/stdc++.h"
#pragma GCC optimize "03"
using namespace std;
#define int long long int
#define ld long double
#define pi pair<int, int>
#define pb push_back
#define fi first
#define se second
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#ifndef LOCAL
#define endl '\n'
#endif
const int N = 2e5 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
signed main() {
IOS;
int n; cin >> n;
int sum = 0;
for(int i = 1; i <= n; i++){
int p; cin >> p;
if(p > 0)
sum += p;
}
cout << sum;
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Numbers are awesome, larger numbers are more awesome!
Given an array A of size N, you need to find the maximum sum that can be obtained from the elements of the array (the selected elements need not be contiguous). You may even decide to take no element to get a sum of 0.The first line of the input contains the size of the array.
The next line contains N (white-space separated) integers denoting the elements of the array.
<b>Constraints:</b>
1 ≤ N ≤ 10<sup>4</sup>
-10<sup>7</sup> ≤ A[i] ≤10<sup>7</sup>For each test case, output one integer representing the maximum value of the sum that can be obtained using the various elements of the array.Input 1:
5
1 2 1 -1 1
output 1:
5
input 2:
5
0 0 -1 0 0
output 2:
0
<b>Explanation 1:</b>
In order to maximize the sum among [ 1 2 1 -1 1], we need to only consider [ 1 2 1 1] and neglect the [-1]., I have written this Solution Code: n=int(input())
li = list(map(int,input().strip().split()))
sum=0
for i in li:
if i>0:
sum+=i
print(sum), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Numbers are awesome, larger numbers are more awesome!
Given an array A of size N, you need to find the maximum sum that can be obtained from the elements of the array (the selected elements need not be contiguous). You may even decide to take no element to get a sum of 0.The first line of the input contains the size of the array.
The next line contains N (white-space separated) integers denoting the elements of the array.
<b>Constraints:</b>
1 ≤ N ≤ 10<sup>4</sup>
-10<sup>7</sup> ≤ A[i] ≤10<sup>7</sup>For each test case, output one integer representing the maximum value of the sum that can be obtained using the various elements of the array.Input 1:
5
1 2 1 -1 1
output 1:
5
input 2:
5
0 0 -1 0 0
output 2:
0
<b>Explanation 1:</b>
In order to maximize the sum among [ 1 2 1 -1 1], we need to only consider [ 1 2 1 1] and neglect the [-1]., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws IOException {
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
int n = Integer.parseInt(br.readLine());
String str[] = br.readLine().split(" ");
long arr[] = new long[n];
long sum=0;
for(int i=0;i<n;i++){
arr[i] = Integer.parseInt(str[i]);
if(arr[i]>0){
sum+=arr[i];
}
}
System.out.print(sum);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two integers N and D, your task is to find the numbers between 1 to N which contains the digit D at least 1 time.Input contains only two integers N and D.
Constraints:-
1 < = N < = 100000
1 < = D < = 9Print all the numbers from 1 to N which contains the digit D in it separated by space in non decreasing order.Sample Input:-
20 5
Sample Output:-
5 15
Sample Input:-
15 1
Sample Output:-
1 10 11 12 13 14 15, I have written this Solution Code: /**
* author: tourist1256
* created: 2022-07-08 04:16:54
**/
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
template <class T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <class key, class value, class cmp = std::less<key>>
using ordered_map = tree<key, value, cmp, rb_tree_tag, tree_order_statistics_node_update>;
// find_by_order(k) returns iterator to kth element starting from 0;
// order_of_key(k) returns count of elements strictly smaller than k;
#ifdef LOCAL
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 2351
#endif
#define int long long
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
inline int64_t random_long(int l = LLONG_MIN, int r = LLONG_MAX) {
uniform_int_distribution<int64_t> generator(l, r);
return generator(rng);
}
int32_t main() {
auto start = std::chrono::high_resolution_clock::now();
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, d;
cin >> n >> d;
int cnt = 0;
function<int(int, int)> f = [&](int d, int m) {
while (d) {
int x = d % 10;
d /= 10;
if (x == m) {
return 1;
}
}
return 0;
};
for (int i = 1; i <= n; i++) {
if (f(i, d)) {
cout << i << " ";
}
}
auto stop = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(stop - start);
cerr << "Time taken : " << ((long double)duration.count()) / ((long double)1e9) << "s\n";
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two integers N and D, your task is to find the numbers between 1 to N which contains the digit D at least 1 time.Input contains only two integers N and D.
Constraints:-
1 < = N < = 100000
1 < = D < = 9Print all the numbers from 1 to N which contains the digit D in it separated by space in non decreasing order.Sample Input:-
20 5
Sample Output:-
5 15
Sample Input:-
15 1
Sample Output:-
1 10 11 12 13 14 15, I have written this Solution Code: def index(st, ch):
for i in range(len(st)):
if (st[i] == ch):
return i;
return -1
def printNumbers(n, d):
# Converting d to character
st = "" + str(d)
ch = st[0]
l = []
# Loop to check each digit one by one.
for i in range(0, n + 1, 1):
# initialize the string
st = ""
st = st + str(i)
# checking for digit
if (i == d or index(st, ch) >= 0):
# print(i, end = " ")
l.append(i)
for k in range(0, len(l) - 1):
print(l[k], end=" ")
print(l[len(l) - 1])
# Driver code
if __name__ == '__main__':
li = list(map(int, input().strip().split()))
n = li[0]
d = li[1]
printNumbers(n, d), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two integers N and D, your task is to find the numbers between 1 to N which contains the digit D at least 1 time.Input contains only two integers N and D.
Constraints:-
1 < = N < = 100000
1 < = D < = 9Print all the numbers from 1 to N which contains the digit D in it separated by space in non decreasing order.Sample Input:-
20 5
Sample Output:-
5 15
Sample Input:-
15 1
Sample Output:-
1 10 11 12 13 14 15, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int d=sc.nextInt();
printnumber(n,d);
}
static boolean ispresent(int n,int d){
while(n>0){
if(n%10==d)
break;
n=n / 10;
}
return n>0;
}
static void printnumber(int n,int d){
for(int i=0;i<=n;i++){
if(i==d||ispresent(i,d)){
System.out.print(i+" ");
}
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a linked list consisting of N nodes, your task is to delete every kth Node from the circular linked list until only one node is left. Also, print the intermediate lists
<b>Note:
Sample Input and Output just show how a linked list will look depending on the questions. Do not copy-paste as it is in custom input</b><b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>deleteK()</b> that takes head node of circular linked list and the integer K as parameter.
Constraints:
1 <= K <= N <= 500
1 <= Node. data<= 1000Print the intermediate nodes until one node is left as shown in example.Sample Input:-
4 2
1 2 3 4
Sample Output:-
1->2->3->4->1
1->2->4->1
2->4->2
2->2
Sample Input:-
9 4
1 2 3 4 5 6 7 8 9
Sample Output:-
1->2->3->4->5->6->7->8->9->1
1->2->3->4->6->7->8->9->1
1->2->3->4->6->7->8->1
1->2->3->6->7->8->1
2->3->6->7->8->2
2->3->6->8->2
2->3->8->2
2->3->2
2->2, I have written this Solution Code: static void printList(Node head)
{
if (head == null)
return;
Node temp = head;
do
{
System.out.print( temp.data + "->");
temp = temp.next;
}
while (temp != head);
System.out.println(head.data );
}
/*Function to delete every kth Node*/
static Node deleteK(Node head_ref, int k)
{
Node head = head_ref;
// If list is empty, simply return.
if (head == null)
return null;
// take two pointers - current and previous
Node curr = head, prev=null;
while (true)
{
// Check if Node is the only Node\
// If yes, we reached the goal, therefore
// return.
if (curr.next == head && curr == head)
break;
// Print intermediate list.
printList(head);
// If more than one Node present in the list,
// Make previous pointer point to current
// Iterate current pointer k times,
// i.e. current Node is to be deleted.
for (int i = 0; i < k; i++)
{
prev = curr;
curr = curr.next;
}
// If Node to be deleted is head
if (curr == head)
{
prev = head;
while (prev.next != head)
prev = prev.next;
head = curr.next;
prev.next = head;
head_ref = head;
}
// If Node to be deleted is last Node.
else if (curr.next == head)
{
prev.next = head;
}
else
{
prev.next = curr.next;
}
}
return head;
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two sorted linked list of size s1 and s2(sizes may or may not be same), your task is to merge them such that resultant list is also sorted.<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>Merge()</b> that takes the head node of both the linked list as the parameter.
Use <b>insert()</b> function for inserting nodes in the linked list.
<b>Constraints:</b>
1 < = s1, s2 < = 1000
1 < = val < = 10000Return the head of the merged linked list, printing will be done by the driver codeSample Input:
5 6
1 2 3 4 5
3 4 6 8 9 10
Sample Output:
1 2 3 3 4 4 5 6 8 9 10, I have written this Solution Code: public static Node Merge (Node head1, Node head2){
Node head =null;
while(head1!=null && head2!=null){
if(head1.val<head2.val){
head=insert(head,head1.val);
head1=head1.next;
}
else{
head=insert(head,head2.val);
head2=head2.next;
}
}
while(head1!=null){
head=insert(head,head1.val);
head1=head1.next;
}
while(head2!=null){
head=insert(head,head2.val);
head2=head2.next;
}
return head;
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: For a given integer N, super primes are those integers from 1 to N whose multiples (other than themselves) do no exist in the range [1, N].
Your task is to generate all super primes <= N in sorted order.
</b>Note: Super primes are not related to primes in any way.</b><b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>SuperPrime()</b> that takes the integer N as a parameter.
Constraints:-
2 < = N <= 1000Printing will be done by the driver code you just need to complete the generator function.Sample Input:-
5
Sample Output:-
3 4 5
Sample Input:-
4
Sample Output:-
3 4, I have written this Solution Code: public static void SuperPrimes(int n){
int x = n/2+1;
for(int i=x ; i<=n ; i++){
out.printf("%d ",i);
}
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: For a given integer N, super primes are those integers from 1 to N whose multiples (other than themselves) do no exist in the range [1, N].
Your task is to generate all super primes <= N in sorted order.
</b>Note: Super primes are not related to primes in any way.</b><b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>SuperPrime()</b> that takes the integer N as a parameter.
Constraints:-
2 < = N <= 1000Printing will be done by the driver code you just need to complete the generator function.Sample Input:-
5
Sample Output:-
3 4 5
Sample Input:-
4
Sample Output:-
3 4, I have written this Solution Code: def SuperPrimes(N):
for i in range (int(N/2)+1,N+1):
yield i
return
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You need to make an order counter to keep track of the total number of orders received.
Complete the function <code> generateOrder() </code> which returns a <code>function func()</code>. This function <code>func</code> should maintain a <code> count (initially 0)</code>. Every time <code>func</code> is called, <code> count</code> must be incremented by 1 and the string <code>"Total orders = " + count</code> must be returned.
<b>Note:</b> The function generateOrder() will be called internally. You do not need to call it yourself. The generateOrder() takes no argument. It is called internally.The generateOrder() function returns a function that returns the string <code>"Total orders = " + count</code>, where <code>count</code> is the number of times the function is called.
const initC = generateOrder(starting);
console.log(initC()) //prints "Total orders = 1"
console.log(initC()) //prints "Total orders = 2"
console.log(initC()) //prints "Total orders = 3"
, I have written this Solution Code: let generateOrder = function() {
let prefix = "Total orders = ";
let count = 0;
let totalOrders = function(){
count++
return prefix + count;
}
return totalOrders;
}, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given three distinct positive integers, A, B and C, in the input. Your task is to find their median.
The median of a set of integers is the number at the middle position if they are arranged in ascending order.The input consists of a single line containing three integers A, B and C.
<b> Constraints: </b>
1 ≤ A, B, C ≤ 10<sup>9</sup>
A, B, C are pairwise distinct.
Print a single integer, the median of the given numbers.Sample Input 1:
5 1 3
Sample Output 1:
3
Sample Input 2:
1 2 3
Sample Output 2:
2, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) {
try{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(r);
String a = in.readLine();
String[] nums = a.split(" ");
long[] l = new long[3];
for(int i=0; i<3; i++){
l[i] = Long.parseLong(nums[i]);
}
Arrays.sort(l);
System.out.print(l[1]);
}
catch(Exception e){
System.out.println(e);
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given three distinct positive integers, A, B and C, in the input. Your task is to find their median.
The median of a set of integers is the number at the middle position if they are arranged in ascending order.The input consists of a single line containing three integers A, B and C.
<b> Constraints: </b>
1 ≤ A, B, C ≤ 10<sup>9</sup>
A, B, C are pairwise distinct.
Print a single integer, the median of the given numbers.Sample Input 1:
5 1 3
Sample Output 1:
3
Sample Input 2:
1 2 3
Sample Output 2:
2, I have written this Solution Code:
//#define ASC
//#define DBG_LOCAL
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// #pragma GCC optimize("Ofast")
// #pragma GCC target("avx,avx2,fma")
#define int long long
// #define int __int128
#define all(X) (X).begin(), (X).end()
#define pb push_back
#define endl '\n'
#define fi first
#define se second
// const int mod = 1e9 + 7;
const int mod=998'244'353;
const long long INF = 2e18 + 10;
// const int INF=1e9+10;
#define readv(x, n) \
vector<int> x(n); \
for (auto &i : x) \
cin >> i;
template <typename T>
using v = vector<T>;
template <typename T>
using vv = vector<vector<T>>;
template <typename T>
using vvv = vector<vector<vector<T>>>;
typedef vector<int> vi;
typedef vector<double> vd;
typedef vector<vector<int>> vvi;
typedef vector<vector<vector<int>>> vvvi;
typedef vector<vector<vector<vector<int>>>> vvvvi;
typedef vector<vector<double>> vvd;
typedef pair<int, int> pii;
int multiply(int a, int b, int in_mod) { return (int)(1LL * a * b % in_mod); }
int mult_identity(int a) { return 1; }
const double PI = acosl(-1);
auto power(auto a, auto b, const int in_mod)
{
auto prod = mult_identity(a);
auto mult = a % 2;
while (b != 0)
{
if (b % 2)
{
prod = multiply(prod, mult, in_mod);
}
if(b/2)
mult = multiply(mult, mult, in_mod);
b /= 2;
}
return prod;
}
auto mod_inv(auto q, const int in_mod)
{
return power(q, in_mod - 2, in_mod);
}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define stp cout << fixed << setprecision(20);
void solv()
{
int A ,B, C;
cin>>A>>B>>C;
vector<int> values;
values.push_back(A);
values.push_back(B);
values.push_back(C);
sort(all(values));
cout<<values[1]<<endl;
}
void solve()
{
int t = 1;
// cin>>t;
for(int i = 1;i<=t;i++)
{
// cout<<"Case #"<<i<<": ";
solv();
}
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cerr.tie(NULL);
#ifndef ONLINE_JUDGE
if (fopen("INPUT.txt", "r"))
{
freopen("INPUT.txt", "r", stdin);
freopen("OUTPUT.txt", "w", stdout);
}
#else
#ifdef ASC
namespace fs = std::filesystem;
std::string path = "./";
string filename;
for (const auto & entry : fs::directory_iterator(path)){
if( entry.path().extension().string() == ".in"){
filename = entry.path().filename().stem().string();
}
}
if(filename != ""){
string input_file = filename +".in";
string output_file = filename +".out";
if (fopen(input_file.c_str(), "r"))
{
freopen(input_file.c_str(), "r", stdin);
freopen(output_file.c_str(), "w", stdout);
}
}
#endif
#endif
// auto clk = clock();
// -------------------------------------Code starts here---------------------------------------------------------------------
signed t = 1;
// cin >> t;
for (signed test = 1; test <= t; test++)
{
// cout<<"Case #"<<test<<": ";
// cout<<endl;
solve();
}
// -------------------------------------Code ends here------------------------------------------------------------------
// clk = clock() - clk;
#ifndef ONLINE_JUDGE
// cerr << fixed << setprecision(6) << "\nTime: " << ((float)clk) / CLOCKS_PER_SEC << "\n";
#endif
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given three distinct positive integers, A, B and C, in the input. Your task is to find their median.
The median of a set of integers is the number at the middle position if they are arranged in ascending order.The input consists of a single line containing three integers A, B and C.
<b> Constraints: </b>
1 ≤ A, B, C ≤ 10<sup>9</sup>
A, B, C are pairwise distinct.
Print a single integer, the median of the given numbers.Sample Input 1:
5 1 3
Sample Output 1:
3
Sample Input 2:
1 2 3
Sample Output 2:
2, I have written this Solution Code: lst = list(map(int, input().split()))
lst.sort()
print(lst[1]), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a circular linked list consisting of N nodes and an integer K, your task is to add the integer K at the end of the list.
<b>Note:
Sample Input and Output just show how a linked list will look depending on the questions. Do not copy-paste as it is in custom input</b><b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>Insertion()</b> that takes head node of circular linked list and the integer K as parameter.
Constraints:
1 <=N <= 1000
1 <= Node.data, K<= 1000Return the head node of the modified circular linked list.Sample Input 1:-
3
1- >2- >3
4
Sample Output 1:-
1- >2- >3- >4
Sample Input 2:-
3
1- >3- >2
1
Sample Output 2:-
1- >3- >2- >1, I have written this Solution Code: public static Node Insertion(Node head, int K){
Node node=head;
while ( node.next != head)
{node = node.next; }
Node temp = new Node(K);
node.next=temp;
temp.next=head;
return head;}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a queue of integers and N queries. Your the task is to perform these operations:-
enqueue:-this operation will add an element to your current queue.
dequeue:-this operation will delete the element from the starting of the queue
displayfront:-this operation will print the element presented at front
Note:-if queue is empty than dequeue operation will do nothing, and 0 will be printed as a front element of queue if it is empty.User task:
Since this will be a functional problem, you don't have to take input. You just have to complete the functions:
<b>enqueue()</b>:- that takes integer to be added as a parameter.
<b>dequeue()</b>:- that takes no parameter.
<b>displayfront()</b> :- that takes no parameter.
Constraints:
1 <= N(Number of queries) <= 10<sup>3</sup>You don't need to print anything else other than in displayfront() in which you require to print the element at front of your queue in a new line, if the queue is empty you just need to print 0.Sample Input:-
7
displayfront
enqueue 2
displayfront
enqueue 4
displayfront
dequeue
displayfront
Sample Output:-
0
2
2
4
Sample input:
5
enqueue 4
enqueue 5
displayfront
dequeue
displayfront
Sample output:-
4
5, I have written this Solution Code: class Queue
{
private Node front, rear;
private int currentSize;
class Node {
Node next;
int val;
Node(int val) {
this.val = val;
next = null;
}
}
public Queue()
{
front = null;
rear = null;
currentSize = 0;
}
public boolean isEmpty()
{
return (currentSize <= 0);
}
public void dequeue()
{
if (isEmpty())
{
}
else{
front = front.next;
currentSize--;
}
}
//Add data to the end of the list.
public void enqueue(int data)
{
Node oldRear = rear;
rear = new Node(data);
if (isEmpty())
{
front = rear;
}
else
{
oldRear.next = rear;
}
currentSize++;
}
public void displayfront(){
if(isEmpty()){
System.out.println("0");
}
else{
System.out.println(front.val);
}
}
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a boolean Matrix of size N*M, A cell of the matrix is called "Good" if it is completely surrounded by the cells containing '1' i.e. each adjacent cell (which shares a common edge) contains '1'. Your task is to find the number of such cells.
See the below example for a better understandingFirst line of input contains two space- separated integers N and M. Next N lines of input contain M space- separated integers depicting the values of the matrix.
Constraints:-
3 <= N, M <= 500
0 <= Matrix[][] <= 1Print the number of good cells.Sample Input:-
3 3
1 1 0
1 1 1
1 1 1
Sample Output:-
1
Explanation:-
Only cell at position 1, 1 is good
Sample Input:-
5 4
1 0 1 0
0 1 0 1
1 0 1 0
0 1 0 1
1 0 1 0
Sample Output:-
3
Explanation:-
(1, 2), (2, 1) and (3, 2) are good cells, I have written this Solution Code: // mat is the matrix/ 2d array
// n,m are dimensions
function goodCell(mat, n, m) {
// write code here
// do not console.log
// return the answer as a number
let cnt = 0;
for (let i = 1; i < n - 1; i++) {
for (let j = 1; j < m - 1; j++) {
if (mat[i - 1][j] == 1 && mat[i + 1][j] == 1 && mat[i][j - 1] == 1 && mat[i][j + 1] == 1) {
cnt++;
}
}
}
return cnt
}
, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a boolean Matrix of size N*M, A cell of the matrix is called "Good" if it is completely surrounded by the cells containing '1' i.e. each adjacent cell (which shares a common edge) contains '1'. Your task is to find the number of such cells.
See the below example for a better understandingFirst line of input contains two space- separated integers N and M. Next N lines of input contain M space- separated integers depicting the values of the matrix.
Constraints:-
3 <= N, M <= 500
0 <= Matrix[][] <= 1Print the number of good cells.Sample Input:-
3 3
1 1 0
1 1 1
1 1 1
Sample Output:-
1
Explanation:-
Only cell at position 1, 1 is good
Sample Input:-
5 4
1 0 1 0
0 1 0 1
1 0 1 0
0 1 0 1
1 0 1 0
Sample Output:-
3
Explanation:-
(1, 2), (2, 1) and (3, 2) are good cells, I have written this Solution Code: N, M= list(map(int,input().split()))
mat =[]
for i in range(N):
List =list(map(int,input().split()))[:M]
mat.append(List)
count =0
for i in range(1,N-1):
for j in range(1,M-1):
if (mat[i][j-1] == 1 and mat[i][j+1] == 1 and mat[i-1][j] == 1 and mat[i+1][j] == 1):
count +=1
print(count), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a boolean Matrix of size N*M, A cell of the matrix is called "Good" if it is completely surrounded by the cells containing '1' i.e. each adjacent cell (which shares a common edge) contains '1'. Your task is to find the number of such cells.
See the below example for a better understandingFirst line of input contains two space- separated integers N and M. Next N lines of input contain M space- separated integers depicting the values of the matrix.
Constraints:-
3 <= N, M <= 500
0 <= Matrix[][] <= 1Print the number of good cells.Sample Input:-
3 3
1 1 0
1 1 1
1 1 1
Sample Output:-
1
Explanation:-
Only cell at position 1, 1 is good
Sample Input:-
5 4
1 0 1 0
0 1 0 1
1 0 1 0
0 1 0 1
1 0 1 0
Sample Output:-
3
Explanation:-
(1, 2), (2, 1) and (3, 2) are good cells, I have written this Solution Code:
#include <bits/stdc++.h>
using namespace std;
#define MEM(a, b) memset(a, (b), sizeof(a))
#define FOREACH(it, l) for (auto it = l.begin(); it != l.end(); it++)
#define IN(A, B, C) assert( B <= A && A <= C)
#define MP make_pair
#define FOR(i,a) for(int i=0;i<a;i++)
#define FOR1(i,j,a) for(int i=j;i<a;i++)
#define EB emplace_back
#define INF (int)1e9
#define EPS 1e-9
#define PI 3.1415926535897932384626433832795
#define max1 1000001
#define MOD 1000000007
#define read(type) readInt<type>()
#define out(x) cout<<x<<'\n'
#define out1(x) cout<<x<<" "
#define END cout<<'\n'
#define int long long
#define sz(v) ((int)(v).size())
#define all(v) (v).begin(), (v).end()
void fast(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
signed main(){
int n,m;
cin>>n>>m;
int a[n][m];
FOR(i,n){
FOR(j,m){
cin>>a[i][j];}}
int sum=0,sum1=0;;
FOR1(i,1,n-1){
FOR1(j,1,m-1){
if(a[i-1][j]==1 && a[i+1][j]==1 && a[i][j-1]==1 && a[i][j+1]==1){
sum++;
}
}
}
out1(sum);
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a boolean Matrix of size N*M, A cell of the matrix is called "Good" if it is completely surrounded by the cells containing '1' i.e. each adjacent cell (which shares a common edge) contains '1'. Your task is to find the number of such cells.
See the below example for a better understandingFirst line of input contains two space- separated integers N and M. Next N lines of input contain M space- separated integers depicting the values of the matrix.
Constraints:-
3 <= N, M <= 500
0 <= Matrix[][] <= 1Print the number of good cells.Sample Input:-
3 3
1 1 0
1 1 1
1 1 1
Sample Output:-
1
Explanation:-
Only cell at position 1, 1 is good
Sample Input:-
5 4
1 0 1 0
0 1 0 1
1 0 1 0
0 1 0 1
1 0 1 0
Sample Output:-
3
Explanation:-
(1, 2), (2, 1) and (3, 2) are good cells, I have written this Solution Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m= sc.nextInt();
int a[][]= new int[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
a[i][j]=sc.nextInt();}}
int cnt=0;
for(int i=1;i<n-1;i++){
for(int j=1;j<m-1;j++){
if(a[i-1][j]==1 && a[i+1][j]==1 && a[i][j-1]==1 && a[i][j+1]==1){
cnt++;
}
}
}
System.out.print(cnt);
}
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given a chessboard of size N x N, where the top left square is black. Each square contains a value. Find the sum of the values of all black squares and all white squares.
Remember that in a chessboard black and white squares are alternate.The first line of input will be the N size of the matrix. Then next N lines will consist of elements of the matrix. Each row will contain N elements since it is a square matrix.
<b>Constraints:-</b>
1 ≤ N ≤ 800
1 ≤ Matrix[i][j] ≤ 100000
Print two lines, the first line containing the sum of black squares and the second line containing the sum of white squares.Input 1:
3
1 2 3
4 5 6
7 8 9
Output 1:
25
20
Sample Input 2:
4
1 2 3 4
6 8 9 10
11 12 13 14
15 16 17 18
Sample Output 2:
80
79
<b>Explanation 1</b>
The black square contains 1, 3, 5, 7, 9; sum = 25
The white square contains 2, 4, 6, 8; sum = 20, I have written this Solution Code: n=int(input())
bSum=0
wSum=0
for i in range(n):
c=(input().split())
for j in range(len(c)):
if(i%2==0):
if(j%2==0):
bSum+=int(c[j])
else:
wSum+=int(c[j])
else:
if(j%2==0):
wSum+=int(c[j])
else:
bSum+=int(c[j])
print(bSum)
print(wSum), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given a chessboard of size N x N, where the top left square is black. Each square contains a value. Find the sum of the values of all black squares and all white squares.
Remember that in a chessboard black and white squares are alternate.The first line of input will be the N size of the matrix. Then next N lines will consist of elements of the matrix. Each row will contain N elements since it is a square matrix.
<b>Constraints:-</b>
1 ≤ N ≤ 800
1 ≤ Matrix[i][j] ≤ 100000
Print two lines, the first line containing the sum of black squares and the second line containing the sum of white squares.Input 1:
3
1 2 3
4 5 6
7 8 9
Output 1:
25
20
Sample Input 2:
4
1 2 3 4
6 8 9 10
11 12 13 14
15 16 17 18
Sample Output 2:
80
79
<b>Explanation 1</b>
The black square contains 1, 3, 5, 7, 9; sum = 25
The white square contains 2, 4, 6, 8; sum = 20, I have written this Solution Code: import java.util.*;
import java.io.*;
import java.lang.*;
class Main
{
public static void main (String[] args)throws IOException {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int mat[][] = new int[N][N];
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
mat[i][j] = sc.nextInt();
}
alternate_Matrix_Sum(mat,N);
}
static void alternate_Matrix_Sum(int mat[][], int N)
{
long sum =0, sum1 = 0;
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
if((i+j)%2 == 0)
sum += mat[i][j];
else sum1 += mat[i][j];
}
}
System.out.println(sum);
System.out.print(sum1);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N elements, your task is to update every element with multiplication of previous and next elements with following exceptions:-
a) First element is replaced by multiplication of first and second.
b) Last element is replaced by multiplication of last and second last.
See example for more clarityFirst line of input contains the size of array N, next line contains N space separated integers denoting values of array.
Constraints:-
2 < = N < = 100000
1 < = arr[i] < = 100000Print the modified arraySample Input :-
5
2 3 4 5 6
Sample Output:-
6 8 15 24 30
Explanation:-
{2*3, 2*4, 3*5, 4*6, 5*6}
Sample Input:-
2
3 4
Sample Output:-
12 12, I have written this Solution Code: // arr is the array of numbers, n is the number fo elements
function replaceArray(arr, n) {
// write code here
// do not console.log
// return the new array
const newArr = []
newArr[0] = arr[0] * arr[1]
newArr[n-1] = arr[n-1] * arr[n-2]
for(let i= 1;i<n-1;i++){
newArr[i] = arr[i-1] * arr[i+1]
}
return newArr
}
, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N elements, your task is to update every element with multiplication of previous and next elements with following exceptions:-
a) First element is replaced by multiplication of first and second.
b) Last element is replaced by multiplication of last and second last.
See example for more clarityFirst line of input contains the size of array N, next line contains N space separated integers denoting values of array.
Constraints:-
2 < = N < = 100000
1 < = arr[i] < = 100000Print the modified arraySample Input :-
5
2 3 4 5 6
Sample Output:-
6 8 15 24 30
Explanation:-
{2*3, 2*4, 3*5, 4*6, 5*6}
Sample Input:-
2
3 4
Sample Output:-
12 12, I have written this Solution Code: n = int(input())
X = [int(x) for x in input().split()]
lst = []
for i in range(len(X)):
if i == 0:
lst.append(X[i]*X[i+1])
elif i == (len(X) - 1):
lst.append(X[i-1]*X[i])
else:
lst.append(X[i-1]*X[i+1])
for i in lst:
print(i,end=" "), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N elements, your task is to update every element with multiplication of previous and next elements with following exceptions:-
a) First element is replaced by multiplication of first and second.
b) Last element is replaced by multiplication of last and second last.
See example for more clarityFirst line of input contains the size of array N, next line contains N space separated integers denoting values of array.
Constraints:-
2 < = N < = 100000
1 < = arr[i] < = 100000Print the modified arraySample Input :-
5
2 3 4 5 6
Sample Output:-
6 8 15 24 30
Explanation:-
{2*3, 2*4, 3*5, 4*6, 5*6}
Sample Input:-
2
3 4
Sample Output:-
12 12, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
long long b[n],a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
for(int i=1;i<n-1;i++){
b[i]=a[i-1]*a[i+1];
}
b[0]=a[0]*a[1];
b[n-1]=a[n-1]*a[n-2];
for(int i=0;i<n;i++){
cout<<b[i]<<" ";}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N elements, your task is to update every element with multiplication of previous and next elements with following exceptions:-
a) First element is replaced by multiplication of first and second.
b) Last element is replaced by multiplication of last and second last.
See example for more clarityFirst line of input contains the size of array N, next line contains N space separated integers denoting values of array.
Constraints:-
2 < = N < = 100000
1 < = arr[i] < = 100000Print the modified arraySample Input :-
5
2 3 4 5 6
Sample Output:-
6 8 15 24 30
Explanation:-
{2*3, 2*4, 3*5, 4*6, 5*6}
Sample Input:-
2
3 4
Sample Output:-
12 12, I have written this Solution Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int a[] = new int[n];
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
}
System.out.print(a[0]*a[1]+" ");
for(int i=1;i<n-1;i++){
System.out.print(a[i-1]*a[i+1]+" ");
}
System.out.print(a[n-1]*a[n-2]);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Implement the function <code>ceil</code>, which should take a number which can be a float(decimal)
and return its result as an integer with ceil function applied to it (Use JS In built functions)Function will take a float as inputFunction will return a numberconsole.log(ceil(1.99)) // prints 2
console.log(ceil(2.1)) // prints 3
console.log(ceil(-1.1)) // prints -1, I have written this Solution Code: function ceil(num){
// write code here
// return the output , do not use console.log here
return Math.ceil(num)
}, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Implement the function <code>ceil</code>, which should take a number which can be a float(decimal)
and return its result as an integer with ceil function applied to it (Use JS In built functions)Function will take a float as inputFunction will return a numberconsole.log(ceil(1.99)) // prints 2
console.log(ceil(2.1)) // prints 3
console.log(ceil(-1.1)) // prints -1, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
float a =sc.nextFloat();
int b=(int)(Math.ceil(a));
System.out.println(b);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: There is an integer array nums having n integers, given as input. Find out whether the given array is spirally sorted or not.
<b>Note:</b>
An array nums, having N elements is spirally sorted if nums[0] ≤ nums[N – 1] ≤ nums[1] ≤ nums[N – 2] …An integer n (size of array nums) is given as input. In the Second line, n space-separated integers are given as input.
<b>Constraints</b>
1 ≤ n ≤ 10<sup>5</sup>
0 ≤ nums[i] ≤ 5*10<sup>4</sup>
0 ≤ i ≤ n-1Print "YES" if Array is Spirally sorted else "NO"(without quotes).Sample Input 1:
7
1 10 14 20 18 12 5
Sample Output 1:
YES
Explanation:
arr[0] < arr[6]
arr[1] < arr[5]
arr[2] < arr[4]
Therefore, the required output is YES.
Sample Input 2:
4
1 2 4 3
Sample Output 2:
NO, I have written this Solution Code: import java.io.*;
import java.security.KeyStore.Entry;
import java.util.*;
public class Main{
public static int[] arr=new int[1005];
public static List<Integer> ls=new ArrayList<>();
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int[] arr=new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
int mx=(n+1)/2;
for(int i=0;i<mx;i++){
if(arr[i]>arr[n-i-1]){
System.out.println("NO");
return;
}
if(i>0&&arr[i]<Math.max(arr[i-1], arr[n-i])){
System.out.println("NO");
return;
}
}
System.out.println("YES");
return;
}
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Print unique values from an array containing only numbers.
Complete the given function such that it returns unique numbers from the array given as input.`arrOfNum` is an array of numbers onlyThe function should return an array containing only the unique numbers from the input arrayINPUT:
1 1 1 2
OUTPUT:
1
2
INPUT:
1 2 2 4 5 6 6
OUTPUT:
1
2
4
5
6
, I have written this Solution Code: function uniqueNumber(arrOfNum) {
const set = new Set(arrOfNum);
return [...set];
}, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Alex always skips math class. As a punishment, his teacher has given him an array of size n where every number except one is the power of x.
Being poor in mathematics, Alex has asked for your help to solve the problem. Can you help him to find the bad number which is not a power of x?
<b>NOTE:</b>
It is guaranteed that there always exists an answer.The first line of the input contains the integers n and x
The following line contains n integers describing the array a
<b>Constraints</b>
2 ≤ n ≤ 1000
1 ≤ x ≤ 20
1 &le a<sub>i</sub> ≤ 10<sup>8</sup>For each test case, output a single line containing the bad number.input
6 7
16807 343 50 823543 2401 5764801
output
50, I have written this Solution Code: y=input().split()
n=int(y[0])
x=int(y[1])
a=input().split()
a=list(map(int,a))
k=0
for i in a:
r=i
while r!=1:
r/=x
if int(r)!=r:
print(i)
k=1
break
if k==1:
break, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Alex always skips math class. As a punishment, his teacher has given him an array of size n where every number except one is the power of x.
Being poor in mathematics, Alex has asked for your help to solve the problem. Can you help him to find the bad number which is not a power of x?
<b>NOTE:</b>
It is guaranteed that there always exists an answer.The first line of the input contains the integers n and x
The following line contains n integers describing the array a
<b>Constraints</b>
2 ≤ n ≤ 1000
1 ≤ x ≤ 20
1 &le a<sub>i</sub> ≤ 10<sup>8</sup>For each test case, output a single line containing the bad number.input
6 7
16807 343 50 823543 2401 5764801
output
50, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main() {
long long n, x;
cin >> n >> x;
vector<long long> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
vector<long long> powers;
long long MX = 1e8;
powers.push_back(1); // to store all the powers of x which are <= 10^8
while (true) {
long long curr = powers.back() * x;
if (curr <= MX) powers.push_back(curr);
else break;
}
for (int i = 0; i < n; i++) {
// checking if a[i] is in the powers array, i.e whether a[i] is a power of x or not
bool found = binary_search(powers.begin(), powers.end(), a[i]);
if (!found) {
cout << a[i];
return 0;
}
}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Alex always skips math class. As a punishment, his teacher has given him an array of size n where every number except one is the power of x.
Being poor in mathematics, Alex has asked for your help to solve the problem. Can you help him to find the bad number which is not a power of x?
<b>NOTE:</b>
It is guaranteed that there always exists an answer.The first line of the input contains the integers n and x
The following line contains n integers describing the array a
<b>Constraints</b>
2 ≤ n ≤ 1000
1 ≤ x ≤ 20
1 &le a<sub>i</sub> ≤ 10<sup>8</sup>For each test case, output a single line containing the bad number.input
6 7
16807 343 50 823543 2401 5764801
output
50, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int x = sc.nextInt();
int ans = 0;
for(int i=0; i<n; i++){
int a = sc.nextInt();
if(!solve(a,x)){
System.out.print(a);
break;
}
}
}
static boolean solve(int a, int b){
while(a>1){
if(a%b!=0)
return false;
a = a/b;
}
return true;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Naruto and Sasuke are on a S- Rank mission. Now They got bored and thought of competing in a race against each other in a horizontal plane. They decides a common spot C at which both of them will try to reach. Whoever reaches first wins the race, both of them run at the same speed.
Given initial positions of Naruto and Sasuke as A and B recpectively.
you need to tell which of them will win the race. If Naruto wins print "N" ( without the quotes ), if Sasuke wins print "S" ( without the quotes ).
if both of them reach the common spot at the same time, print "D" (for draw, without the quotes ).<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function
<b>Race</b> that takes the integer A (initial position of Naruto) and B (initial position of Sasuke) and C (position of common spot) as parameter.
Constraints
1 <= A, B, C <= 100Return the character according to the given scenario.Sample Input
1 2 3
Sample Output
S
Sample Input
1 3 2
Sample Output
D, I have written this Solution Code:
char Race(int A, int B, int C){
if(abs(C-A)==abs(C-B)){return 'D';}
if(abs(C-A)>abs(C-B)){return 'S';}
else{
return 'N';}
}
, In this Programming Language: C, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Naruto and Sasuke are on a S- Rank mission. Now They got bored and thought of competing in a race against each other in a horizontal plane. They decides a common spot C at which both of them will try to reach. Whoever reaches first wins the race, both of them run at the same speed.
Given initial positions of Naruto and Sasuke as A and B recpectively.
you need to tell which of them will win the race. If Naruto wins print "N" ( without the quotes ), if Sasuke wins print "S" ( without the quotes ).
if both of them reach the common spot at the same time, print "D" (for draw, without the quotes ).<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function
<b>Race</b> that takes the integer A (initial position of Naruto) and B (initial position of Sasuke) and C (position of common spot) as parameter.
Constraints
1 <= A, B, C <= 100Return the character according to the given scenario.Sample Input
1 2 3
Sample Output
S
Sample Input
1 3 2
Sample Output
D, I have written this Solution Code: def Race(A,B,C):
if abs(C-A) ==abs(C-B):
return 'D'
if abs(C-A)>abs(C-B):
return 'S'
return 'N'
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Naruto and Sasuke are on a S- Rank mission. Now They got bored and thought of competing in a race against each other in a horizontal plane. They decides a common spot C at which both of them will try to reach. Whoever reaches first wins the race, both of them run at the same speed.
Given initial positions of Naruto and Sasuke as A and B recpectively.
you need to tell which of them will win the race. If Naruto wins print "N" ( without the quotes ), if Sasuke wins print "S" ( without the quotes ).
if both of them reach the common spot at the same time, print "D" (for draw, without the quotes ).<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function
<b>Race</b> that takes the integer A (initial position of Naruto) and B (initial position of Sasuke) and C (position of common spot) as parameter.
Constraints
1 <= A, B, C <= 100Return the character according to the given scenario.Sample Input
1 2 3
Sample Output
S
Sample Input
1 3 2
Sample Output
D, I have written this Solution Code:
char Race(int A, int B, int C){
if(abs(C-A)==abs(C-B)){return 'D';}
if(abs(C-A)>abs(C-B)){return 'S';}
else{
return 'N';}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Naruto and Sasuke are on a S- Rank mission. Now They got bored and thought of competing in a race against each other in a horizontal plane. They decides a common spot C at which both of them will try to reach. Whoever reaches first wins the race, both of them run at the same speed.
Given initial positions of Naruto and Sasuke as A and B recpectively.
you need to tell which of them will win the race. If Naruto wins print "N" ( without the quotes ), if Sasuke wins print "S" ( without the quotes ).
if both of them reach the common spot at the same time, print "D" (for draw, without the quotes ).<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function
<b>Race</b> that takes the integer A (initial position of Naruto) and B (initial position of Sasuke) and C (position of common spot) as parameter.
Constraints
1 <= A, B, C <= 100Return the character according to the given scenario.Sample Input
1 2 3
Sample Output
S
Sample Input
1 3 2
Sample Output
D, I have written this Solution Code: static char Race(int A,int B,int C){
if(Math.abs(C-A)==Math.abs(C-B)){return 'D';}
if(Math.abs(C-A)>Math.abs(C-B)){return 'S';}
else{
return 'N';}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N elements. In the array, each element is present twice except for 1 element whose frequency in the array is 1. Hence the length of the array will always be odd.
Find the unique number.An integer, N, representing the size of the array. In the next line, N space-separated integers follow.
<b>Constraints:</b>
1 <= N <=10<sup>5</sup>
1 <= A[i] <=10<sup>8</sup>Output the element with frequency 1.Input :
5
1 1 2 2 3
Output:
3, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int noofterm=Integer.parseInt(br.readLine());
int arr[] = new int[noofterm];
String s[] = br.readLine().split(" ");
for(int i=0; i<noofterm;i++){
arr[i]= Integer.parseInt(s[i]);
}
System.out.println(unique(arr));
}
public static int unique(int[] inputArray)
{
int result = 0;
for(int i=0;i<inputArray.length;i++)
{
result ^= inputArray[i];
}
return (result>0 ? result : -1);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N elements. In the array, each element is present twice except for 1 element whose frequency in the array is 1. Hence the length of the array will always be odd.
Find the unique number.An integer, N, representing the size of the array. In the next line, N space-separated integers follow.
<b>Constraints:</b>
1 <= N <=10<sup>5</sup>
1 <= A[i] <=10<sup>8</sup>Output the element with frequency 1.Input :
5
1 1 2 2 3
Output:
3, I have written this Solution Code: n = int(input())
a = [int (x) for x in input().split()]
mapp={}
for index,val in enumerate(a):
if val in mapp:
del mapp[val]
else:
mapp[val]=1
for key, value in mapp.items():
print(key), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N elements. In the array, each element is present twice except for 1 element whose frequency in the array is 1. Hence the length of the array will always be odd.
Find the unique number.An integer, N, representing the size of the array. In the next line, N space-separated integers follow.
<b>Constraints:</b>
1 <= N <=10<sup>5</sup>
1 <= A[i] <=10<sup>8</sup>Output the element with frequency 1.Input :
5
1 1 2 2 3
Output:
3, I have written this Solution Code: #include<bits/stdc++.h>
using namespace std;
signed main()
{
int n;
cin>>n;
int p=0;
for(int i=0;i<n;i++)
{
int a;
cin>>a;
p^=a;
}
cout<<p<<endl;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Remove duplicates of an array and return an array of only unique elements.An array containing numbers.Space separated unique elements from the array.Sample Input:-
1 2 3 5 1 5 9 1 2 8
Sample Output:-
1 2 3 5 9 8
<b>Explanation:-</b>
Extra 1, 2, and 5 were removed since they were occurring multiple times.
Note: You only have to remove the extra occurrences i.e. each element in the final array should have a frequency equal to one., I have written this Solution Code: nan, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Remove duplicates of an array and return an array of only unique elements.An array containing numbers.Space separated unique elements from the array.Sample Input:-
1 2 3 5 1 5 9 1 2 8
Sample Output:-
1 2 3 5 9 8
<b>Explanation:-</b>
Extra 1, 2, and 5 were removed since they were occurring multiple times.
Note: You only have to remove the extra occurrences i.e. each element in the final array should have a frequency equal to one., I have written this Solution Code:
inp = eval(input(""))
new_set = []
for i in inp:
if(str(i) not in new_set):
new_set.append(str(i))
print(" ".join(new_set)), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a matrix of N*N dimensions (Mat). Print the matrix rotated by 90 degrees and 180 degrees.The first line contains N.
N lines follow each containing N space-separated integers.
<b>Constraints</b>
2 <= N <= 100
1 <= Mat[i][j] <= 10000Output 2*N+1 lines.
First N lines should contain the Matrix rotated by 90 degrees.
Then print a blank line.
Then N lines should contain the Matrix rotated by 180 degrees.Sample Input 1:
2
3 4
7 6
Sample Output 1:
7 3
6 4
6 7
4 3
Sample Input 2:
2
1 2
3 4
Sample Output 2:
3 1
4 2
4 3
2 1, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#define N 1000
// Function to rotate the matrix 90 degree clockwise
void rotate90Clockwise(int a[][N],int n)
{
// Traverse each cycle
for (int i = 0; i < n / 2; i++) {
for (int j = i; j < n - i - 1; j++) {
// Swap elements of each cycle
// in clockwise direction
int temp = a[i][j];
a[i][j] = a[n - 1 - j][i];
a[n - 1 - j][i] = a[n - 1 - i][n - 1 - j];
a[n - 1 - i][n - 1 - j] = a[j][n - 1 - i];
a[j][n - 1 - i] = temp;
}
}
}
// Function for print matrix
void printMatrix(int arr[][N],int n)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cout << arr[i][j] << " ";
cout << '\n';
}
}
// Driver code
int main()
{
int n;
cin>>n;
int arr[n][N];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>arr[i][j];
}}
rotate90Clockwise(arr,n);
printMatrix(arr,n);
cout<<endl;
rotate90Clockwise(arr,n);
printMatrix(arr,n);
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a matrix of N*N dimensions (Mat). Print the matrix rotated by 90 degrees and 180 degrees.The first line contains N.
N lines follow each containing N space-separated integers.
<b>Constraints</b>
2 <= N <= 100
1 <= Mat[i][j] <= 10000Output 2*N+1 lines.
First N lines should contain the Matrix rotated by 90 degrees.
Then print a blank line.
Then N lines should contain the Matrix rotated by 180 degrees.Sample Input 1:
2
3 4
7 6
Sample Output 1:
7 3
6 4
6 7
4 3
Sample Input 2:
2
1 2
3 4
Sample Output 2:
3 1
4 2
4 3
2 1, I have written this Solution Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[][] = new int[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
a[i][j]= sc.nextInt();
}
}
//rotating by 90 degree
for (int i = 0; i < n / 2; i++) {
for (int j = i; j < n - i - 1; j++) {
int temp = a[i][j];
a[i][j] = a[n - 1 - j][i];
a[n - 1 - j][i] = a[n - 1 - i][n - 1 - j];
a[n - 1 - i][n - 1 - j] = a[j][n - 1 - i];
a[j][n - 1 - i] = temp;
}
}
for(int i =0;i<n;i++){
for(int j=0;j<n;j++){
System.out.print(a[i][j]+" ");
}
System.out.println();
}
//rotating by 90 degree
for (int i = 0; i < n / 2; i++) {
for (int j = i; j < n - i - 1; j++) {
int temp = a[i][j];
a[i][j] = a[n - 1 - j][i];
a[n - 1 - j][i] = a[n - 1 - i][n - 1 - j];
a[n - 1 - i][n - 1 - j] = a[j][n - 1 - i];
a[j][n - 1 - i] = temp;
}
}
System.out.println();
for(int i =0;i<n;i++){
for(int j=0;j<n;j++){
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a matrix of N*N dimensions (Mat). Print the matrix rotated by 90 degrees and 180 degrees.The first line contains N.
N lines follow each containing N space-separated integers.
<b>Constraints</b>
2 <= N <= 100
1 <= Mat[i][j] <= 10000Output 2*N+1 lines.
First N lines should contain the Matrix rotated by 90 degrees.
Then print a blank line.
Then N lines should contain the Matrix rotated by 180 degrees.Sample Input 1:
2
3 4
7 6
Sample Output 1:
7 3
6 4
6 7
4 3
Sample Input 2:
2
1 2
3 4
Sample Output 2:
3 1
4 2
4 3
2 1, I have written this Solution Code: x=int(input())
l1=[]
for i in range(x):
a1=list(map(int,input().split()))
l1.append(a1)
for j in range(x):
for i in range(1,x+1):
print(l1[-i][j], end=" ")
print()
print()
for i in range(1,x+1):
for j in range(1,x+1):
print(l1[-i][-j], end=" ")
print(), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given the length, breadth, and height of a cuboid. Your task is to calculate its Perimeter.
Note:- Formula for the perimeter of the cuboid is 4(Length + Breadth + height)<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>Perimeter()</b> that takes integers L, B, and H as parameters.
Constraints:-
1 <= L, B, H <= 100Return the length of the Cuboid.Sample Input:-
L = 3, B = 5, H = 1
Sample Output:-
36
Sample Input:-
L = 1, B = 1, H = 1
Sample Output:-
12, I have written this Solution Code:
L,B,H=input().split()
a=4*(int(L)+int(B)+int(H))
print(a), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given the length, breadth, and height of a cuboid. Your task is to calculate its Perimeter.
Note:- Formula for the perimeter of the cuboid is 4(Length + Breadth + height)<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>Perimeter()</b> that takes integers L, B, and H as parameters.
Constraints:-
1 <= L, B, H <= 100Return the length of the Cuboid.Sample Input:-
L = 3, B = 5, H = 1
Sample Output:-
36
Sample Input:-
L = 1, B = 1, H = 1
Sample Output:-
12, I have written this Solution Code: static int Perimeter(int L, int B, int H){
return 4*(L+B+H);
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given a multiset (i. e. a set that can contain multiple equal integers) containing 2n integers. Determine if you can split it into exactly n pairs (e.g. each element should be in exactly one pair) so that the sum of the two elements in each pair is odd (i. e. when divided by 2, the remainder is 1).The first line of input contains an integer n. The second line of the input contains 2n integers a<sub>1</sub>, a<sub>2</sub>, …, a<sub>2n</sub>, (0≤ai≤100) denoting the numbers in the set.
<b>Constraints</b>
1 ≤ n ≤ 100
0 ≤ a<sub>i</sub> ≤ 100Print "Yes" if it can be split into exactly n pairs so that the sum of the two elements in each pair is odd, and "No" otherwise.<b>Sample Input 1</b>
2
2 3 4 5
<b>Sample Output 1</b>
Yes
<b>Sample Input 2</b>
3
2 3 4 5 5 5
<b>Sample Output 2</b>
No, I have written this Solution Code: #include <bits/stdc++.h>
using i64 = long long;
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int t=1;
// std::cin >> t;
while (t--) {
int n;
std::cin >> n;
int odd = 0;
for (int i = 0; i < 2 * n; i++) {
int x;
std::cin >> x;
if (x % 2 == 1) {
odd++;
}
}
if (odd == n) {
std::cout << "Yes\n";
} else {
std::cout << "No\n";
}
}
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two positive integers N and M. The task is to check whether N is a <b>Special-M-visor</b> or not.
<b>Special-M-visor</b>: A number is called Special-m-visor if it has exactly M even divisors for a given N.<b>User Task:</b>
Since this is a functional problem, you don’t have to worry about the input, you just have to complete the function <b>checkSpecial_M_Visor()</b>. Where you will get N and M as a parameter.
Constraints:
1 <= N <= 10^6
0 <= M <= 10^6Return "Yes" without quotes if the number N is a <b>Special- M- visor</b> else return "No"Sample Input:-
4 2
Sample Output:-
Yes
Explanation:- 2 and 4 are the only even divisors of 4
Sample Input:-
8 5
Sample Output:-
No, I have written this Solution Code:
def checkSpecial_M_Visor(N,M) :
# Final result of summation of divisors
i=2;
count=0
while i<=N :
if(N%i==0):
count=count+1
i=i+2
if(count == M):
return "Yes"
return "No"
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two positive integers N and M. The task is to check whether N is a <b>Special-M-visor</b> or not.
<b>Special-M-visor</b>: A number is called Special-m-visor if it has exactly M even divisors for a given N.<b>User Task:</b>
Since this is a functional problem, you don’t have to worry about the input, you just have to complete the function <b>checkSpecial_M_Visor()</b>. Where you will get N and M as a parameter.
Constraints:
1 <= N <= 10^6
0 <= M <= 10^6Return "Yes" without quotes if the number N is a <b>Special- M- visor</b> else return "No"Sample Input:-
4 2
Sample Output:-
Yes
Explanation:- 2 and 4 are the only even divisors of 4
Sample Input:-
8 5
Sample Output:-
No, I have written this Solution Code:
static String checkSpecial_M_Visor(int N, int M)
{
int temp=0;
for(int i = 2; i <=N; i+=2)
{
if(N%i==0)
temp++;
}
if(temp==M)
return "Yes";
else return "No";
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two positive integers N and M. The task is to check whether N is a <b>Special-M-visor</b> or not.
<b>Special-M-visor</b>: A number is called Special-m-visor if it has exactly M even divisors for a given N.<b>User Task:</b>
Since this is a functional problem, you don’t have to worry about the input, you just have to complete the function <b>checkSpecial_M_Visor()</b>. Where you will get N and M as a parameter.
Constraints:
1 <= N <= 10^6
0 <= M <= 10^6Return "Yes" without quotes if the number N is a <b>Special- M- visor</b> else return "No"Sample Input:-
4 2
Sample Output:-
Yes
Explanation:- 2 and 4 are the only even divisors of 4
Sample Input:-
8 5
Sample Output:-
No, I have written this Solution Code:
string checkSpecial_M_Visor(int N,int M){
int count=0;
for(int i=2;i<=N;i+=2){
if(N%i==0){
count++;
}
}
if(count==M){return "Yes";}
return "No";
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two positive integers N and M. The task is to check whether N is a <b>Special-M-visor</b> or not.
<b>Special-M-visor</b>: A number is called Special-m-visor if it has exactly M even divisors for a given N.<b>User Task:</b>
Since this is a functional problem, you don’t have to worry about the input, you just have to complete the function <b>checkSpecial_M_Visor()</b>. Where you will get N and M as a parameter.
Constraints:
1 <= N <= 10^6
0 <= M <= 10^6Return "Yes" without quotes if the number N is a <b>Special- M- visor</b> else return "No"Sample Input:-
4 2
Sample Output:-
Yes
Explanation:- 2 and 4 are the only even divisors of 4
Sample Input:-
8 5
Sample Output:-
No, I have written this Solution Code: const char* checkSpecial_M_Visor(int N,int M){
int count=0;
for(int i=2;i<=N;i+=2){
if(N%i==0){
count++;
}
}
char* ans;
if(count==M){return "Yes";}
return "No";
}
, In this Programming Language: C, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Rohit's uncle gives him D chocolates for up to N days, He already has C chocolates with him if he eats one chocolate a day how many chocolates will he have at the end of N days?<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>Chocolates()</b> that takes integers D, N and C as parameters.
Constraints:-
1 <= D <= 100
1 <= N <= 100
1 <= C <= 100Return the number of chocolates at the end of N daysSample Input:-
5 5 5
Sample Output:-
25
Explanation:-
At the end of the First day:- 5 + 5 - 1 = 9
At the end of the Second day:- 9 + 5 - 1 = 13
At the end of the Third day:- 13 + 5 - 1 = 17
At the end of the Fourth day:- 17 + 5 - 1 = 21
At the end of the Fifth day:- 21 + 5 - 1 = 25
Sample Input:-
1 2 3
Sample Output:-
3, I have written this Solution Code:
int Chocolates(int D, int N, int C){
return N*(D-1)+C;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Rohit's uncle gives him D chocolates for up to N days, He already has C chocolates with him if he eats one chocolate a day how many chocolates will he have at the end of N days?<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>Chocolates()</b> that takes integers D, N and C as parameters.
Constraints:-
1 <= D <= 100
1 <= N <= 100
1 <= C <= 100Return the number of chocolates at the end of N daysSample Input:-
5 5 5
Sample Output:-
25
Explanation:-
At the end of the First day:- 5 + 5 - 1 = 9
At the end of the Second day:- 9 + 5 - 1 = 13
At the end of the Third day:- 13 + 5 - 1 = 17
At the end of the Fourth day:- 17 + 5 - 1 = 21
At the end of the Fifth day:- 21 + 5 - 1 = 25
Sample Input:-
1 2 3
Sample Output:-
3, I have written this Solution Code: def Chocolates(D,N,C):
return N*(D-1) + C
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Rohit's uncle gives him D chocolates for up to N days, He already has C chocolates with him if he eats one chocolate a day how many chocolates will he have at the end of N days?<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>Chocolates()</b> that takes integers D, N and C as parameters.
Constraints:-
1 <= D <= 100
1 <= N <= 100
1 <= C <= 100Return the number of chocolates at the end of N daysSample Input:-
5 5 5
Sample Output:-
25
Explanation:-
At the end of the First day:- 5 + 5 - 1 = 9
At the end of the Second day:- 9 + 5 - 1 = 13
At the end of the Third day:- 13 + 5 - 1 = 17
At the end of the Fourth day:- 17 + 5 - 1 = 21
At the end of the Fifth day:- 21 + 5 - 1 = 25
Sample Input:-
1 2 3
Sample Output:-
3, I have written this Solution Code:
int Chocolates(int D, int N, int C){
return N*(D-1)+C;
}
, In this Programming Language: C, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Rohit's uncle gives him D chocolates for up to N days, He already has C chocolates with him if he eats one chocolate a day how many chocolates will he have at the end of N days?<b>User Task:</b>
Since this will be a functional problem, you don't have to take input. You just have to complete the function <b>Chocolates()</b> that takes integers D, N and C as parameters.
Constraints:-
1 <= D <= 100
1 <= N <= 100
1 <= C <= 100Return the number of chocolates at the end of N daysSample Input:-
5 5 5
Sample Output:-
25
Explanation:-
At the end of the First day:- 5 + 5 - 1 = 9
At the end of the Second day:- 9 + 5 - 1 = 13
At the end of the Third day:- 13 + 5 - 1 = 17
At the end of the Fourth day:- 17 + 5 - 1 = 21
At the end of the Fifth day:- 21 + 5 - 1 = 25
Sample Input:-
1 2 3
Sample Output:-
3, I have written this Solution Code:
static int Chocolates(int D, int N, int C){
return N*(D-1)+C;
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given an array of size n consisting of unique integers and an integer k. A function f is defined as follows:
f(i) = Minimum j such that subarray a<sub>i</sub>, a<sub>i+1</sub>, ., a<sub>j</sub> have k elements strictly greater than a<sub>i</sub>
and -1 (if no such j exists)
Your task is to calculate f(i) for all 1 ≤ i ≤ n.The first line contains an integer t (1 <= T <= 10<sup>5</sup>) - the number of test cases.
The first line of each test case contains two integers n and k (1 <= n <= 10<sup>5</sup>, 1 <= k <= n).
The second line of each test case contains n integers a<sub>1</sub>, a<sub>2</sub>, …a<sub>n</sub> (−10<sup>9</sup> <= a<sub>i</sub> <= 10<sup>9</sup>).
It is guaranteed that elements in a given array are unique.
It is guaranteed that the sum of n over all test cases does not exceed 2 * 10<sup>5</sup>.For each test case, print a separate line containing space-separated n integers f(1), f(2),. , f(n).Sample Input 1:
1
3 1
2 1 3
Sample Output 1:
2 2 -1
Explanation:
For index 0, the element at index 2 is the first element greater than 2.
For index 1, the element at index 2 is the first element greater than 1.
For index 2, no such index exists.
, I have written this Solution Code: import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
public static void process() throws IOException {
int n = sc.nextInt(),k = sc.nextInt();
FenwickTree tree = new FenwickTree(n+1);
int arr[] = sc.readArray(n);
compress(arr);
ArrayList<Pair> q = new ArrayList<Main.Pair>();
for(int i = 1; i<=n; i++)q.add(new Pair(arr[i-1], i));
Collections.sort(q);
int[] res = new int[n];
for(int i = 1; i<=n; i++) {
Pair curr = q.get(i-1);
int l = curr.y,r = n;
int ans = -1;
while(l<=r) {
int mid = (l+r)/2;
int len = (mid-curr.y+1);
len-=tree.find(curr.y,mid);
if(len > k) {
ans = mid-1;
r = mid-1;
}
else {
l = mid+1;
}
}
res[curr.y-1] = ans;
tree.add(curr.y, 1);
}
for(int e : res)out.print(e+" ");
out.println();
}
static class FenwickTree
{
public int[] tree;
public int size;
public FenwickTree(int size)
{
this.size = size;
tree = new int[size+5];
}
public void add(int i, int v)
{
while(i <= size)
{
tree[i] += v;
i += i&-i;
}
}
public int find(int i)
{
int res = 0;
while(i >= 1)
{
res += tree[i];
i -= i&-i;
}
return res;
}
public int find(int l, int r)
{
return find(r)-find(l-1);
}
}
private static long INF = 2000000000000000000L, M = 1000000007, MM = 998244353;
private static int N = 2_000_00;
private static void google(int tt) {
System.out.print("Case #" + (tt) + ": ");
}
static FastScanner sc;
static FastWriter out;
public static void main(String[] args) throws IOException {
boolean oj = true;
if (oj) {
sc = new FastScanner();
out = new FastWriter(System.out);
} else {
sc = new FastScanner("input.txt");
out = new FastWriter("output.txt");
}
long s = System.currentTimeMillis();
int t = 1;
t = sc.nextInt();
int TTT = 1;
while (t-- > 0) {
process();
}
out.flush();
}
private static boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private static void tr(Object... o) {
if (!oj)
System.err.println(Arrays.deepToString(o));
}
static class Pair implements Comparable<Pair> {
int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
return Integer.compare(this.x, o.x);
}
}
static int ceil(int x, int y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static long ceil(long x, long y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static long sqrt(long z) {
long sqz = (long) Math.sqrt(z);
while (sqz * 1L * sqz < z) {
sqz++;
}
while (sqz * 1L * sqz > z) {
sqz--;
}
return sqz;
}
static int log2(int N) {
int result = (int) (Math.log(N) / Math.log(2));
return result;
}
public static long gcd(long a, long b) {
if (a > b)
a = (a + b) - (b = a);
if (a == 0L)
return b;
return gcd(b % a, a);
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static int lower_bound(int[] arr, int x) {
int low = 0, high = arr.length - 1, mid = -1;
int ans = -1;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] > x) {
high = mid - 1;
} else {
ans = mid;
low = mid + 1;
}
}
return ans;
}
public static int upper_bound(int[] arr, int x) {
int low = 0, high = arr.length - 1, mid = -1;
int ans = arr.length;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= x) {
ans = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
return ans;
}
static void ruffleSort(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
Arrays.sort(a);
}
static void reverseArray(int[] a) {
int n = a.length;
int arr[] = new int[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
static void reverseArray(long[] a) {
int n = a.length;
long arr[] = new long[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
public static void push(TreeMap<Integer, Integer> map, int k, int v) {
if (!map.containsKey(k))
map.put(k, v);
else
map.put(k, map.get(k) + v);
}
public static void pull(TreeMap<Integer, Integer> map, int k, int v) {
int lol = map.get(k);
if (lol == v)
map.remove(k);
else
map.put(k, lol - v);
}
public static int[] compress(int[] arr) {
ArrayList<Integer> ls = new ArrayList<Integer>();
for (int x : arr)
ls.add(x);
Collections.sort(ls);
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int boof = 1;
for (int x : ls)
if (!map.containsKey(x))
map.put(x, boof++);
int[] brr = new int[arr.length];
for (int i = 0; i < arr.length; i++)
brr[i] = map.get(arr[i]);
return brr;
}
public static class FastWriter {
private static final int BUF_SIZE = 1 << 13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter() {
out = null;
}
public FastWriter(OutputStream os) {
this.out = os;
}
public FastWriter(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE)
innerflush();
return this;
}
public FastWriter write(char c) {
return write((byte) c);
}
public FastWriter write(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE)
innerflush();
}
return this;
}
public FastWriter write(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE)
innerflush();
});
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000)
return 10;
if (l >= 100000000)
return 9;
if (l >= 10000000)
return 8;
if (l >= 1000000)
return 7;
if (l >= 100000)
return 6;
if (l >= 10000)
return 5;
if (l >= 1000)
return 4;
if (l >= 100)
return 3;
if (l >= 10)
return 2;
return 1;
}
public FastWriter write(int x) {
if (x == Integer.MIN_VALUE) {
return write((long) x);
}
if (ptr + 12 >= BUF_SIZE)
innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L)
return 19;
if (l >= 100000000000000000L)
return 18;
if (l >= 10000000000000000L)
return 17;
if (l >= 1000000000000000L)
return 16;
if (l >= 100000000000000L)
return 15;
if (l >= 10000000000000L)
return 14;
if (l >= 1000000000000L)
return 13;
if (l >= 100000000000L)
return 12;
if (l >= 10000000000L)
return 11;
if (l >= 1000000000L)
return 10;
if (l >= 100000000L)
return 9;
if (l >= 10000000L)
return 8;
if (l >= 1000000L)
return 7;
if (l >= 100000L)
return 6;
if (l >= 10000L)
return 5;
if (l >= 1000L)
return 4;
if (l >= 100L)
return 3;
if (l >= 10L)
return 2;
return 1;
}
public FastWriter write(long x) {
if (x == Long.MIN_VALUE) {
return write("" + x);
}
if (ptr + 21 >= BUF_SIZE)
innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision) {
if (x < 0) {
write('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
write((long) x).write(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
write((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastWriter writeln(char c) {
return write(c).writeln();
}
public FastWriter writeln(int x) {
return write(x).writeln();
}
public FastWriter writeln(long x) {
return write(x).writeln();
}
public FastWriter writeln(double x, int precision) {
return write(x, precision).writeln();
}
public FastWriter write(int... xs) {
boolean first = true;
for (int x : xs) {
if (!first)
write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs) {
boolean first = true;
for (long x : xs) {
if (!first)
write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln() {
return write((byte) '\n');
}
public FastWriter writeln(int... xs) {
return write(xs).writeln();
}
public FastWriter writeln(long... xs) {
return write(xs).writeln();
}
public FastWriter writeln(char[] line) {
return write(line).writeln();
}
public FastWriter writeln(char[]... map) {
for (char[] line : map)
write(line).writeln();
return this;
}
public FastWriter writeln(String s) {
return write(s).writeln();
}
private void innerflush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush() {
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) {
return write(b);
}
public FastWriter print(char c) {
return write(c);
}
public FastWriter print(char[] s) {
return write(s);
}
public FastWriter print(String s) {
return write(s);
}
public FastWriter print(int x) {
return write(x);
}
public FastWriter print(long x) {
return write(x);
}
public FastWriter print(double x, int precision) {
return write(x, precision);
}
public FastWriter println(char c) {
return writeln(c);
}
public FastWriter println(int x) {
return writeln(x);
}
public FastWriter println(long x) {
return writeln(x);
}
public FastWriter println(double x, int precision) {
return writeln(x, precision);
}
public FastWriter print(int... xs) {
return write(xs);
}
public FastWriter print(long... xs) {
return write(xs);
}
public FastWriter println(int... xs) {
return writeln(xs);
}
public FastWriter println(long... xs) {
return writeln(xs);
}
public FastWriter println(char[] line) {
return writeln(line);
}
public FastWriter println(char[]... map) {
return writeln(map);
}
public FastWriter println(String s) {
return writeln(s);
}
public FastWriter println() {
return writeln();
}
}
static class FastScanner {
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1)
return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] readArray(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] readArrayLong(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public int[][] readArrayMatrix(int N, int M, int Index) {
if (Index == 0) {
int[][] res = new int[N][M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++)
res[i][j] = (int) nextLong();
}
return res;
}
int[][] res = new int[N][M];
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++)
res[i][j] = (int) nextLong();
}
return res;
}
public long[][] readArrayMatrixLong(int N, int M, int Index) {
if (Index == 0) {
long[][] res = new long[N][M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++)
res[i][j] = nextLong();
}
return res;
}
long[][] res = new long[N][M];
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++)
res[i][j] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC)
c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-')
neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] readArrayDouble(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32)
return true;
while (true) {
c = getChar();
if (c == NC)
return false;
else if (c > 32)
return true;
}
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given an array of size n consisting of unique integers and an integer k. A function f is defined as follows:
f(i) = Minimum j such that subarray a<sub>i</sub>, a<sub>i+1</sub>, ., a<sub>j</sub> have k elements strictly greater than a<sub>i</sub>
and -1 (if no such j exists)
Your task is to calculate f(i) for all 1 ≤ i ≤ n.The first line contains an integer t (1 <= T <= 10<sup>5</sup>) - the number of test cases.
The first line of each test case contains two integers n and k (1 <= n <= 10<sup>5</sup>, 1 <= k <= n).
The second line of each test case contains n integers a<sub>1</sub>, a<sub>2</sub>, …a<sub>n</sub> (−10<sup>9</sup> <= a<sub>i</sub> <= 10<sup>9</sup>).
It is guaranteed that elements in a given array are unique.
It is guaranteed that the sum of n over all test cases does not exceed 2 * 10<sup>5</sup>.For each test case, print a separate line containing space-separated n integers f(1), f(2),. , f(n).Sample Input 1:
1
3 1
2 1 3
Sample Output 1:
2 2 -1
Explanation:
For index 0, the element at index 2 is the first element greater than 2.
For index 1, the element at index 2 is the first element greater than 1.
For index 2, no such index exists.
, I have written this Solution Code: #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace std;
using namespace __gnu_pbds;
template <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
#define endl '\n'
#define pb push_back
#define ub upper_bound
#define lb lower_bound
#define fi first
#define se second
#define int long long
typedef long long ll;
typedef long double ld;
#define pii pair<int,int>
#define sz(x) ((ll)x.size())
#define fr(a,b,c) for(int a=b; a<=c; a++)
#define frev(a,b,c) for(int a=c; a>=b; a--)
#define rep(a,b,c) for(int a=b; a<c; a++)
#define trav(a,x) for(auto &a:x)
#define all(con) con.begin(),con.end()
#define done(x) {cout << x << endl;return;}
#define mini(x,y) x = min(x,y)
#define maxi(x,y) x = max(x,y)
const ll infl = 0x3f3f3f3f3f3f3f3fLL;
const int infi = 0x3f3f3f3f;
mt19937_64 mt(chrono::steady_clock::now().time_since_epoch().count());
//const int mod = 998244353;
const int mod = 1e9 + 7;
typedef vector<int> vi;
typedef vector<string> vs;
typedef vector<vector<int>> vvi;
typedef vector<pair<int, int>> vpii;
typedef map<int, int> mii;
typedef set<int> si;
typedef set<pair<int,int>> spii;
typedef queue<int> qi;
uniform_int_distribution<int> rng(0, 1e9);
// DEBUG FUNCTIONS START
void __print(int x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}
template<typename T, typename V> void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T> void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void deb() {cerr << "\n";}
template <typename T, typename... V> void deb(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; deb(v...);}
// DEBUG FUNCTIONS END
const int N = 2e5 + 5;
void solve(){
int n, k;
cin >> n >> k;
vi a(n);
rep(i,0,n){
cin >> a[i];
}
vi b = a;
sort(all(b));
vi pos(n);
ordered_set<int> s;
rep(i,0,n){
a[i] = lb(all(b), a[i]) - b.begin();
pos[a[i]] = i;
s.insert(i);
}
vi res(n, -1);
rep(i,0,n){
int position = pos[i];
int idx = s.order_of_key(position);
if(sz(s) > idx + k){
res[position] = *s.find_by_order(idx + k);
}
s.erase(position);
}
rep(i,0,n){
cout << res[i] << " ";
}
cout << endl;
}
signed main(){
ios_base::sync_with_stdio(0), cin.tie(0);
cout << fixed << setprecision(15);
//freopen ("03.txt","r",stdin);
//freopen ("3.txt","w",stdout);
int t = 1;
cin >> t;
while (t--)
solve();
return 0;
}
int powm(int a, int b){
int res = 1;
while (b) {
if (b & 1)
res = res * a % mod;
a = a * a % mod;
b >>= 1;
}
return res;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array A and an integer K. Find the maximum for each and every contiguous subarray of size K.
Problem asked in Amazon, Flipkart.The first line of each test case contains a single integer N denoting the size of array and the size of subarray K. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.
Constraints:
1 ≤ N ≤ 10^5
1 ≤ K ≤ N
0 ≤ A[i] <= 10^5Print the maximum for every subarray of size K.Sample Input:
9 3
1 2 3 1 4 5 2 3 6
Sample Output:
3 3 4 5 5 5 6
Explanation:
Starting from the first subarray of size k = 3, we have 3 as maximum. Moving the window forward, maximum element are as 3, 4, 5, 5, 5 and 6., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void printMax(int arr[], int n, int k) {
int j, max;
for(int i = 0; i <= n - k; i++) {
max = arr[i];
for(j = 1; j < k; j++) {
if(arr[i + j] > max) {
max = arr[i + j];
}
}
System.out.print(max + " ");
}
}
public static void main (String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str1[] = br.readLine().trim().split(" ");
int n = Integer.parseInt(str1[0]);
int k = Integer.parseInt(str1[1]);
String str2[] = br.readLine().trim().split(" ");
int arr[] = new int[n];
for(int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(str2[i]);
}
printMax(arr, n ,k);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array A and an integer K. Find the maximum for each and every contiguous subarray of size K.
Problem asked in Amazon, Flipkart.The first line of each test case contains a single integer N denoting the size of array and the size of subarray K. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.
Constraints:
1 ≤ N ≤ 10^5
1 ≤ K ≤ N
0 ≤ A[i] <= 10^5Print the maximum for every subarray of size K.Sample Input:
9 3
1 2 3 1 4 5 2 3 6
Sample Output:
3 3 4 5 5 5 6
Explanation:
Starting from the first subarray of size k = 3, we have 3 as maximum. Moving the window forward, maximum element are as 3, 4, 5, 5, 5 and 6., I have written this Solution Code: n,k=input().split()
n=int(n)
k=int(k)
arr=input().split()
for i in range(0,n):
arr[i]=int(arr[i])
m=max(arr[0:k])
for i in range(k-1,n):
if(arr[i] > m):
m=arr[i]
if(arr[i-k]==m):
m=max(arr[i-k+1:i+1])
print (m, end=' '), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array A and an integer K. Find the maximum for each and every contiguous subarray of size K.
Problem asked in Amazon, Flipkart.The first line of each test case contains a single integer N denoting the size of array and the size of subarray K. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.
Constraints:
1 ≤ N ≤ 10^5
1 ≤ K ≤ N
0 ≤ A[i] <= 10^5Print the maximum for every subarray of size K.Sample Input:
9 3
1 2 3 1 4 5 2 3 6
Sample Output:
3 3 4 5 5 5 6
Explanation:
Starting from the first subarray of size k = 3, we have 3 as maximum. Moving the window forward, maximum element are as 3, 4, 5, 5, 5 and 6., I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
// A Dequeue (Double ended queue) based method for printing maximum element of
// all subarrays of size k
void printKMax(int arr[], int n, int k)
{
// Create a Double Ended Queue, Qi that will store indexes of array elements
// The queue will store indexes of useful elements in every window and it will
// maintain decreasing order of values from front to rear in Qi, i.e.,
// arr[Qi.front[]] to arr[Qi.rear()] are sorted in decreasing order
std::deque<int> Qi(k);
/* Process first k (or first window) elements of array */
int i;
for (i = 0; i < k; ++i) {
// For every element, the previous smaller elements are useless so
// remove them from Qi
while ((!Qi.empty()) && arr[i] >= arr[Qi.back()])
Qi.pop_back(); // Remove from rear
// Add new element at rear of queue
Qi.push_back(i);
}
// Process rest of the elements, i.e., from arr[k] to arr[n-1]
for (; i < n; ++i) {
// The element at the front of the queue is the largest element of
// previous window, so print it
cout << arr[Qi.front()] << " ";
// Remove the elements which are out of this window
while ((!Qi.empty()) && Qi.front() <= i - k)
Qi.pop_front(); // Remove from front of queue
// Remove all elements smaller than the currently
// being added element (remove useless elements)
while ((!Qi.empty()) && arr[i] >= arr[Qi.back()])
Qi.pop_back();
// Add current element at the rear of Qi
Qi.push_back(i);
}
// Print the maximum element of last window
cout << arr[Qi.front()];
}
// Driver program to test above functions
int main()
{
int n,k;
cin>>n>>k;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
printKMax(arr, n, k);
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array, A of N integers. Find the product of maximum values for every subarray of size K. Print the answer modulo 10<sup>9</sup>+7.
A subarray is any contiguous sequence of elements in an array.The first line contains two integers N and K, denoting the size of the array and the size of the subarray respectively.
The next line contains N integers denoting the elements of the array.
<b>Constarints</b>
1 <= K <= N <= 1000000
1 <= A[i] <= 1000000Print a single integer denoting the product of maximums for every subarray of size K modulo 1000000007Sample Input 1:
6 4
1 5 2 3 6 4
Sample Output 1:
180
<b>Explanation:</b>
For subarray [1, 5, 2, 3], maximum = 5
For subarray [5, 2, 3, 6], maximum = 6
For subarray [2, 3, 6, 4], maximum = 6
Therefore, ans = 5*6*6 = 180, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args)throws IOException {
Reader sc=new Reader();
int n=sc.nextInt();
int b=sc.nextInt();
int[] a=new int[n];
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
}
int j, max;
long mul=1;
Deque<Integer> dq= new LinkedList<Integer>();
for (int i = 0;i<b;i++)
{
while (!dq.isEmpty() && a[i] >=a[dq.peekLast()])
dq.removeLast();
dq.addLast(i);
}
mul=((mul%1000000007)*(a[dq.peek()]%1000000007))%1000000007;
for (int i=b; i < n;i++)
{
while ((!dq.isEmpty()) && dq.peek() <=i-b)
dq.removeFirst();
while ((!dq.isEmpty()) && a[i]>=a[dq.peekLast()])
dq.removeLast();
dq.addLast(i);
mul=((mul%1000000007)*(a[dq.peek()]%1000000007))%1000000007;
}
System.out.println(mul%1000000007);
}
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64];
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array, A of N integers. Find the product of maximum values for every subarray of size K. Print the answer modulo 10<sup>9</sup>+7.
A subarray is any contiguous sequence of elements in an array.The first line contains two integers N and K, denoting the size of the array and the size of the subarray respectively.
The next line contains N integers denoting the elements of the array.
<b>Constarints</b>
1 <= K <= N <= 1000000
1 <= A[i] <= 1000000Print a single integer denoting the product of maximums for every subarray of size K modulo 1000000007Sample Input 1:
6 4
1 5 2 3 6 4
Sample Output 1:
180
<b>Explanation:</b>
For subarray [1, 5, 2, 3], maximum = 5
For subarray [5, 2, 3, 6], maximum = 6
For subarray [2, 3, 6, 4], maximum = 6
Therefore, ans = 5*6*6 = 180, I have written this Solution Code: from collections import deque
deq=deque()
n,k=list(map(int,input().split()))
array=list(map(int,input().split()))
for i in range(k):
while(deq and array[deq[-1]]<=array[i]):
deq.pop()
deq.append(i)
ans=1
for j in range(k,n):
ans=ans*array[deq[0]]
ans=(ans)%1000000007
while(deq and deq[0]<=j-k):
deq.popleft()
while(deq and array[deq[-1]]<=array[j]):
deq.pop()
deq.append(j)
ans=ans*array[deq[0]]
ans=(ans)%1000000007
print(ans), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array, A of N integers. Find the product of maximum values for every subarray of size K. Print the answer modulo 10<sup>9</sup>+7.
A subarray is any contiguous sequence of elements in an array.The first line contains two integers N and K, denoting the size of the array and the size of the subarray respectively.
The next line contains N integers denoting the elements of the array.
<b>Constarints</b>
1 <= K <= N <= 1000000
1 <= A[i] <= 1000000Print a single integer denoting the product of maximums for every subarray of size K modulo 1000000007Sample Input 1:
6 4
1 5 2 3 6 4
Sample Output 1:
180
<b>Explanation:</b>
For subarray [1, 5, 2, 3], maximum = 5
For subarray [5, 2, 3, 6], maximum = 6
For subarray [2, 3, 6, 4], maximum = 6
Therefore, ans = 5*6*6 = 180, I have written this Solution Code: #include<bits/stdc++.h>
#define int long long
#define ll long long
#define pb push_back
#define endl '\n'
#define pii pair<int,int>
#define vi vector<int>
#define all(a) (a).begin(),(a).end()
#define F first
#define S second
#define sz(x) (int)x.size()
#define hell 1000000007
#define rep(i,a,b) for(int i=a;i<b;i++)
#define dep(i,a,b) for(int i=a;i>=b;i--)
#define lbnd lower_bound
#define ubnd upper_bound
#define bs binary_search
#define mp make_pair
using namespace std;
const int N = 1e6 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
int a[N];
void solve(){
int n, k;
cin >> n >> k;
for(int i = 1; i <= n; i++)
cin >> a[i];
deque<int> q;
for(int i = 1; i <= k; i++){
while(!q.empty() && a[q.back()] <= a[i])
q.pop_back();
q.push_back(i);
}
int ans = a[q.front()];
for(int i = k+1; i <= n; i++){
if(q.front() == i-k)
q.pop_front();
while(!q.empty() && a[q.back()] <= a[i])
q.pop_back();
q.push_back(i);
ans = (ans*a[q.front()]) % mod;
}
cout << ans;
}
void testcases(){
int tt = 1;
//cin >> tt;
while(tt--){
solve();
}
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
clock_t start = clock();
testcases();
cerr << (double)(clock() - start)*1000/CLOCKS_PER_SEC << " ms: ";
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Implement <code>getObjKeys</code> which only takes one argument which will be a object.
The function should return all they keys present in object as a string where elements are seperated by a ', '. (No nested objects)(Use JS Built in function)Function will take one argument which will be an objectFunction will is string which contain all the keys from the input object seperated by a ', 'const obj = {email:"akshat. sethi@newtonschool. co", password:"123456"}
const keyString = getObjKeys(obj)
console. log(keyString) // prints email, password, I have written this Solution Code: function getObjKeys(obj){
return Object.keys(obj).join(",")
}, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N, your task is to find the maximum value of X such that sum of some X consecutive natural numbers is N.Input contains a single integer N.
Constraints:-
1 <= N <= 1000000000Print the maximum value of X such that sum of some X consecutive natural numbers is N.Sample Input:-
5
Sample Output:-
2
Explanation:-
2 + 3 = 5
Sample Input:-
50
Sample Output:-
5
Explanation:-
8 + 9 + 10 + 11 + 12 = 50, I have written this Solution Code:
import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws IOException{
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(read.readLine());
int sumOfCon = 0;
for(int i=1; i<=N; i++) {
for(int j=i; j<=N; j++) {
sumOfCon += j;
if(sumOfCon > N) {
break;
}
if(sumOfCon == N) {
System.out.print(j-i+1);
break;
}
}
if(sumOfCon == N) {
break;
}
sumOfCon = 0;
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N, your task is to find the maximum value of X such that sum of some X consecutive natural numbers is N.Input contains a single integer N.
Constraints:-
1 <= N <= 1000000000Print the maximum value of X such that sum of some X consecutive natural numbers is N.Sample Input:-
5
Sample Output:-
2
Explanation:-
2 + 3 = 5
Sample Input:-
50
Sample Output:-
5
Explanation:-
8 + 9 + 10 + 11 + 12 = 50, I have written this Solution Code: n = int(input())
i = 1
j = 1
s = 0
while(True):
if(s == n):
print(j-i)
break
s += j
j += 1
while(s > n):
s -= i
i += 1, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N, your task is to find the maximum value of X such that sum of some X consecutive natural numbers is N.Input contains a single integer N.
Constraints:-
1 <= N <= 1000000000Print the maximum value of X such that sum of some X consecutive natural numbers is N.Sample Input:-
5
Sample Output:-
2
Explanation:-
2 + 3 = 5
Sample Input:-
50
Sample Output:-
5
Explanation:-
8 + 9 + 10 + 11 + 12 = 50, I have written this Solution Code:
#include <bits/stdc++.h>
using namespace std;
#define MEM(a, b) memset(a, (b), sizeof(a))
#define FOREACH(it, l) for (auto it = l.begin(); it != l.end(); it++)
#define IN(A, B, C) assert( B <= A && A <= C)
#define MP make_pair
#define FOR(i,a) for(int i=0;i<a;i++)
#define FOR1(i,j,a) for(int i=j;i<a;i++)
#define EB emplace_back
#define INF (int)1e9
#define EPS 1e-9
#define PI 3.1415926535897932384626433832795
#define max1 1000001
#define MOD 1000000000000007
#define read(type) readInt<type>()
#define out(x) cout<<x<<'\n'
#define out1(x) cout<<x<<" "
#define END cout<<'\n'
#define int long long
#define sz(v) ((int)(v).size())
#define all(v) (v).begin(), (v).end()
void fast(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
int cnt[max1];
signed main(){
int t;
t=1;
while(t--){
int n;
cin>>n;
int x=1;
int p=2*sqrt(n);
int ans=1,t=1;
while(t<=n){
if((n-t)%x==0){ans=x;}
x++;
t=x*(x+1);
t=t/2;
}
out(ans);
}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two strings A and B, check if the string A is a sub-string of string B or not.First line of input contains a string A, the second line of the input contains the string B.
Constraints:-
1 < = |A| < = |B| < = 1000
Note:- String will only contain lowercase english letters.Print "Yes" if the string A is the substring of string B, else print "No".Sample Input:-
ewt
newton
Sample Output:-
Yes
Sample Input:-
erf
sdafa
Sample Output:-
No, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String A=br.readLine();
String B=br.readLine();
int j=0;
boolean flag=false;
for(int i=0;i<B.length();i++)
{
if(A.charAt(j)==B.charAt(i))
{
j+=1;
}
else
j=0;
if(j==A.length())
{
System.out.println("Yes");
flag=true;
break;
}
}
if(!flag)
System.out.println("No");
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two strings A and B, check if the string A is a sub-string of string B or not.First line of input contains a string A, the second line of the input contains the string B.
Constraints:-
1 < = |A| < = |B| < = 1000
Note:- String will only contain lowercase english letters.Print "Yes" if the string A is the substring of string B, else print "No".Sample Input:-
ewt
newton
Sample Output:-
Yes
Sample Input:-
erf
sdafa
Sample Output:-
No, I have written this Solution Code: # Take input from users
MyString1 = input()
MyString2 = input()
if MyString1 in MyString2:
print("Yes")
else:
print("No")
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.