Instruction
stringlengths 261
35k
| Response
stringclasses 1
value |
---|---|
For this Question: There is a robot starting at the position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.
You have given a string of moves that represents the move sequence of the robot where moves[i] represent its ith move. Valid moves are 'R' (right), 'L' (left), 'U' (up), and 'D' (down).
Return true if the robot returns to the origin after it finishes all of its moves, or false otherwise.
<b>Note:</b>
The way that the robot is "facing" is irrelevant. 'R' will always make the robot move to the right once, 'L' will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.There is a single line containing a string as input.
<b>Constraints:</b>
1 ≤ s. length ≤ 10<sup>5</sup>
s contains only characters 'L', 'R', 'U', 'D'Print True if the robot returns to the origin after it finishes all of its moves, or False otherwise.Sample Input:
UD
Sample Output:
True, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args)throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int horz = 0, vert=0;
for(int i=0; i<s.length(); i++){
if(s.charAt(i)=='L') horz--;
if(s.charAt(i)=='R') horz++;
if(s.charAt(i)=='U') vert++;
if(s.charAt(i)=='D') vert--;
}
if(horz==0 && vert==0) System.out.print("True");
else System.out.print("False");
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Take input from standard input while you do not get 0 as an input. Print all the inputs separated by space. It is guaranteed that the number of integers are less than 100000.The input will contain a series of integers in one line each. Input should be taken while you have not get a 0 as an input.
0 <= input <= 10Print the input integers seperated by space.Sample Input
6
5
5
0
Sample Output
6 5 5 0
Sample Input
9
3
5
7
6
9
8
3
2
7
7
3
5
0
Sample Output
9 3 5 7 6 9 8 3 2 7 7 3 5 0, I have written this Solution Code: n=1
index=0
li=[]
while n!=0:
n=int(input())
li.append(n)
index=index+1
#li = list(map(int,input().strip().split()))
for i in range(0,len(li)-1):
print(li[i],end=" ")
print(li[len(li)-1]), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Take input from standard input while you do not get 0 as an input. Print all the inputs separated by space. It is guaranteed that the number of integers are less than 100000.The input will contain a series of integers in one line each. Input should be taken while you have not get a 0 as an input.
0 <= input <= 10Print the input integers seperated by space.Sample Input
6
5
5
0
Sample Output
6 5 5 0
Sample Input
9
3
5
7
6
9
8
3
2
7
7
3
5
0
Sample Output
9 3 5 7 6 9 8 3 2 7 7 3 5 0, 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=100001;
int a;
for(int i=0;i<n;i++){
a=sc.nextInt();
System.out.print(a+" ");
if(a==0){break;}
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Take input from standard input while you do not get 0 as an input. Print all the inputs separated by space. It is guaranteed that the number of integers are less than 100000.The input will contain a series of integers in one line each. Input should be taken while you have not get a 0 as an input.
0 <= input <= 10Print the input integers seperated by space.Sample Input
6
5
5
0
Sample Output
6 5 5 0
Sample Input
9
3
5
7
6
9
8
3
2
7
7
3
5
0
Sample Output
9 3 5 7 6 9 8 3 2 7 7 3 5 0, 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;
while(cin >> n){
cout << n << " ";
if(n == 0) break;
}
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given N flags, initially set to 0. Now you have to perform two operations on them:
1. Increase(F) by 1: flag F is increased by 1.
2. max_flag: all flags are set to a maximum value of any flag.
A non-empty array arr[] will be given of size M. This array represents consecutive operations:
a) If arr[K] = F, such that 1 <= F <= N then operation K is Increase(F).
b) If arr[K] = N+1 then operation K is max_flag.
The goal is to calculate the value of every flag after all operations.The input line contains T, denoting the number of test cases.
Each test case contains two lines.
The first line contains an integer N, the number of flags, and an integer M, the size of the array 'arr'.The second line contains elements of the array 'arr' separated by space.
<b>Constraints:</b>
1 <= T <= 100
1 <= N, M <= 10^5
1 <= arr[i] <= N+1
Sum of N and M for each test case is less than or equal to 10^5For each testcase you need to print the updated array after all operations in new line.Sample Input:
1
5 7
3 4 4 6 1 4 4
Sample Output:
3 2 2 4 2
<b>Explanation:</b>
Testcase 1:
the values of the flags after each consecutive operation will be:
(0, 0, 1, 0, 0)
(0, 0, 1, 1, 0)
(0, 0, 1, 2, 0)
(2, 2, 2, 2, 2)
(3, 2, 2, 2, 2)
(3, 2, 2, 3, 2)
(3, 2, 2, 4, 2), I have written this Solution Code: t=int(input())
while t>0:
t-=1
n,m=map(int,input().split())
a=map(int,input().split())
b=[0]*(n+1)
for i in a:
if i==n+1:
v=max(b)
for i in range(1,n+1):
b[i]=v
else:b[i]+=1
for i in range(1,n+1):
print(b[i],end=' ')
print(), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given N flags, initially set to 0. Now you have to perform two operations on them:
1. Increase(F) by 1: flag F is increased by 1.
2. max_flag: all flags are set to a maximum value of any flag.
A non-empty array arr[] will be given of size M. This array represents consecutive operations:
a) If arr[K] = F, such that 1 <= F <= N then operation K is Increase(F).
b) If arr[K] = N+1 then operation K is max_flag.
The goal is to calculate the value of every flag after all operations.The input line contains T, denoting the number of test cases.
Each test case contains two lines.
The first line contains an integer N, the number of flags, and an integer M, the size of the array 'arr'.The second line contains elements of the array 'arr' separated by space.
<b>Constraints:</b>
1 <= T <= 100
1 <= N, M <= 10^5
1 <= arr[i] <= N+1
Sum of N and M for each test case is less than or equal to 10^5For each testcase you need to print the updated array after all operations in new line.Sample Input:
1
5 7
3 4 4 6 1 4 4
Sample Output:
3 2 2 4 2
<b>Explanation:</b>
Testcase 1:
the values of the flags after each consecutive operation will be:
(0, 0, 1, 0, 0)
(0, 0, 1, 1, 0)
(0, 0, 1, 2, 0)
(2, 2, 2, 2, 2)
(3, 2, 2, 2, 2)
(3, 2, 2, 3, 2)
(3, 2, 2, 4, 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 = 1e5 + 5;
const int mod = 1e9 + 7;
const int inf = 1e9 + 9;
int a[N];
signed main() {
IOS;
int t; cin >> t;
while(t--){
memset(a, 0, sizeof a);
int n, m;
cin >> n >> m;
int mx = 0, flag = 0;
for(int i = 1; i <= m; i++){
int p; cin >> p;
if(p == n+1){
flag = mx;
}
else{
a[p] = max(a[p], flag) + 1;
mx = max(mx, a[p]);
}
}
for(int i = 1; i <= n; i++){
a[i] = max(a[i], flag);
cout << a[i] << " ";
}
cout << endl;
}
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Find the number of prime numbers before N (Including that number too).The first line of the input contains the number of test cases T.
Next T lines contain the value N.
<b>Constraints</b>
1 <= T <= 1e5
1 <= N <= 1e5Print the number of primes number before that number.Sample Input 1:
2
3
11
Sample Output 1:
2
5, I have written this Solution Code: import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
class Main
{
static int [] booleanArray(int num)
{
boolean [] bool = new boolean[num+1];
int [] count = new int [num+1];
bool[0] = true;
bool[1] = true;
for(int i=2; i*i<=num; i++)
{
if(bool[i]==false)
{
for(int j=i*i; j<=num; j+=i)
bool[j] = true;
}
}
int counter = 0;
for(int i=1; i<=num; i++)
{
if(bool[i]==false)
{
counter = counter+1;
count[i] = counter;
}
else
{
count[i] = counter;
}
}
return count;
}
public static void main (String[] args) throws IOException {
InputStreamReader ak = new InputStreamReader(System.in);
BufferedReader hk = new BufferedReader(ak);
int[] v = booleanArray(100000);
int t = Integer.parseInt(hk.readLine());
for (int i = 1; i <= t; i++) {
int a = Integer.parseInt(hk.readLine());
System.out.println(v[a]);
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Find the number of prime numbers before N (Including that number too).The first line of the input contains the number of test cases T.
Next T lines contain the value N.
<b>Constraints</b>
1 <= T <= 1e5
1 <= N <= 1e5Print the number of primes number before that number.Sample Input 1:
2
3
11
Sample Output 1:
2
5, I have written this Solution Code: m=100001
prime=[True for i in range(m)]
p=2
while(p*p<=m):
if prime[p]:
for i in range(p*p,m,p):
prime[i]=False
p+=1
c=[0 for i in range(m)]
c[2]=1
for i in range(3,m):
if prime[i]:
c[i]=c[i-1]+1
else:
c[i]=c[i-1]
t=int(input())
while t>0:
n=int(input())
print(c[n])
t-=1, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Find the number of prime numbers before N (Including that number too).The first line of the input contains the number of test cases T.
Next T lines contain the value N.
<b>Constraints</b>
1 <= T <= 1e5
1 <= N <= 1e5Print the number of primes number before that number.Sample Input 1:
2
3
11
Sample Output 1:
2
5, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 2351
#endif
vector<bool> sieve(int n) {
vector<bool> is_prime(n + 1, true);
is_prime[0] = is_prime[1] = false;
for (int i = 2; i * i <= n; i++) {
if (is_prime[i]) {
for (int j = i * i; j <= n; j += i)
is_prime[j] = false;
}
}
return is_prime;
}
int main() {
vector<bool> prime = sieve(1e5 + 1);
vector<int> prefix(1e5 + 1, 0);
for (int i = 1; i <= 1e5; i++) {
if (prime[i]) {
prefix[i] = prefix[i - 1] + 1;
} else {
prefix[i] = prefix[i - 1];
}
}
int tt;
cin >> tt;
while (tt--) {
int n;
cin >> n;
cout << prefix[n] << "\n";
}
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a linked list, the task is to move all 0’s to the front of the linked list. The order of all another element except 0 should be same after rearrangement.
Note: Avoid use of any type of Java Collection frameworks.
Note: For custom input/output, enter the list in reverse order, and the output will come in right order.<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>moveZeroes()</b> that takes head node as parameter.
Constraints:
1 <= T <= 100
1 <= N <= 100000
0<=Node.data<=100000
Note:- Sum of all test cases doesn't exceed 10^5
Return the head of the modified linked list.Input:
2
10
0 4 0 5 0 2 1 0 1 0
7
1 1 2 3 0 0 0
Output:
0 0 0 0 0 4 5 2 1 1
0 0 0 1 1 2 3
Explanation:
Testcase 1:
Original list was 0->4->0->5->0->2->1->0->1->0->NULL.
After processing list becomes 0->0->0->0->0->4->5->2->1->1->NULL.
Testcase 2:
Original list was 1->1->2->3->0->0->0->NULL.
After processing list becomes 0->0->0->1->1->2->3->NULL., I have written this Solution Code: static public Node moveZeroes(Node head){
ArrayList<Integer> a=new ArrayList<>();
int c=0;
while(head!=null){
if(head.data==0){
c++;
}
else{
a.add(head.data);
}
head=head.next;
}
head=null;
for(int i=a.size()-1;i>=0;i--){
if(head==null){
head=new Node(a.get(i));
}
else{
Node temp=new Node(a.get(i));
temp.next=head;
head=temp;
}
}
while(c-->0){
Node temp=new Node(0);
temp.next=head;
head=temp;
}
return head;
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N such that no digit of N is 0, find minimum numbers of digits that need to be removed from N such that N becomes divisible by 3. Note: if all the digits of N needs to removed report -1.Input contains a single integer N.
Constraints:
1 <= N <= 10^18
No digit of N is 0.Print the minimum number of digits that needs to removed to make N divisible by 3. Note: if all the digits of N needs to removed report -1.Sample Input 1
35
Sample Output 1
1
Explanation: we remove 5 from 35 making it 3.
Sample Input 2
44
Sample Output 2
-1
Explanation: As we have to remove all digits we report -1., I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args)throws IOException {
BufferedReader s=new BufferedReader(new InputStreamReader(System.in));
String S=s.readLine();
int arr[]=new int[3];
for(int i=0;i<3;i++){
arr[i]=0;
}
int sum=0;
for(int i=0;i<S.length();i++){
sum+=(int)S.charAt(i);
int num=(int)S.charAt(i);
int rem=num%3;
if(rem==0){
arr[0]++;
}
if(rem==1){
arr[1]++;
}
if(rem==2){
arr[2]++;
}
}
int cnt=S.length();
if(sum % 3 == 0)
{
System.out.println("0");
}
else if(sum % 3 == 1)
{
if(arr[1]>=1 && cnt > 1)
{
System.out.println("1");
}
else if(arr[2] >= 2 && cnt > 2)
{
System.out.println("2");
}
else
{
System.out.println("-1");
}
}
else if(sum % 3 == 2)
{
if(arr[2]>=1 && cnt > 1)
{
System.out.println("1");
}
else if(arr[1] >= 2 && cnt > 2)
{
System.out.println("2");
}
else
{
System.out.println("-1");
}
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N such that no digit of N is 0, find minimum numbers of digits that need to be removed from N such that N becomes divisible by 3. Note: if all the digits of N needs to removed report -1.Input contains a single integer N.
Constraints:
1 <= N <= 10^18
No digit of N is 0.Print the minimum number of digits that needs to removed to make N divisible by 3. Note: if all the digits of N needs to removed report -1.Sample Input 1
35
Sample Output 1
1
Explanation: we remove 5 from 35 making it 3.
Sample Input 2
44
Sample Output 2
-1
Explanation: As we have to remove all digits we report -1., I have written this Solution Code:
number = input()
def divisible(num):
n = len(num)
sum_ = 0
for i in range(n):
sum_ += int(num[i])
if (sum_ % 3 == 0):
return 0
if (n == 1):
return -1
for i in range(n):
if (sum_ % 3 == int(num[i]) % 3):
return 1
if (n == 2):
return -1
return 2
print(divisible(number)), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer N such that no digit of N is 0, find minimum numbers of digits that need to be removed from N such that N becomes divisible by 3. Note: if all the digits of N needs to removed report -1.Input contains a single integer N.
Constraints:
1 <= N <= 10^18
No digit of N is 0.Print the minimum number of digits that needs to removed to make N divisible by 3. Note: if all the digits of N needs to removed report -1.Sample Input 1
35
Sample Output 1
1
Explanation: we remove 5 from 35 making it 3.
Sample Input 2
44
Sample Output 2
-1
Explanation: As we have to remove all digits we report -1., I have written this Solution Code: #pragma GCC optimize ("Ofast")
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define VV vector
#define pb push_back
#define bitc __builtin_popcountll
#define m_p make_pair
#define infi 1e18+1
#define eps 0.000000000001
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);
string char_to_str(char c){string tem(1,c);return tem;}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T>//usage rand<long long>()
T rand() {
return uniform_int_distribution<T>()(rng);
}
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template<class T>
using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// string to integer stoi()
// string to long long stoll()
// string.substr(position,length);
// integer to string to_string();
//////////////
auto clk=clock();
#define all(x) x.begin(),x.end()
#define S second
#define F first
#define sz(x) ((long long)x.size())
#define int long long
#define f80 __float128
#define pii pair<int,int>
/////////////
int n;
int num[20];
int cnt = 0;
int sum = 0;
int amount[3];
signed main()
{
fastio;
#ifdef ANIKET_GOYAL
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
cin >> n;
while(n)
{
num[++cnt] = n % 10;
n /= 10;
}
for(int i = 1; i <= cnt; i++)
{
sum += num[i];
}
for(int i = 1; i <= cnt; i++)
{
amount[num[i] % 3]++;
}
if(sum % 3 == 0)
{
printf("0\n");
}
else if(sum % 3 == 1)
{
if(amount[1] && cnt > 1)
{
printf("1\n");
}
else if(amount[2] >= 2 && cnt > 2)
{
printf("2\n");
}
else
{
printf("-1\n");
}
}
else if(sum % 3 == 2)
{
if(amount[2] && cnt > 1)
{
printf("1\n");
}
else if(amount[1] >= 2 && cnt > 2)
{
printf("2\n");
}
else
{
printf("-1\n");
}
}
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: 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: Actually, a pair of chopsticks need not have two sticks that are the same length. You can eat with a pair of sticks as long as the length difference is no greater than D. Samar is appointed as a head chef of a restaurant. He is provided with N sticks, the i<sup>th</sup>stick of which is L[i] units long. More than one set of chopsticks cannot share the same stick. Assist him in matching the sticks to create as many functional pairs of chopsticks as possible.The first line contains two space-separated integers N and D. The next N lines contain one integer each, the i<sup>th</sup>line giving the value of L[i].
<b>Constraints</b>
1 ≤ N ≤ 10,000 (10<sup>5</sup>)
0 ≤ D ≤ 1,000,000,000 (10<sup>9</sup>)
1 ≤ L[i] ≤ 1,000,000,000 (10<sup>9</sup>) for all integers i from 1 to NOutput a single line containing the maximum number of pairs of chopsticks Samar can form.Sample Input :
5 2
1
3
3
9
4
Sample Output :
2
Explanation :
The 5 sticks have lengths 1, 3, 3, 9, and 4 respectively. The maximum allowed difference in the lengths of two sticks forming a pair is at most 2. It is clear that the 4th stick (length 9) cannot be used with any other stick. The remaining 4 sticks can be paired as (1st and 3rd) and (2nd and 5th) to form 2 pairs of usable chopsticks., 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 d=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
int count=0;
Arrays.sort(arr);
for(int i=0;i<n-1;i++){
if(arr[i+1]-arr[i]<=d){
count++;
i++;
}
}
System.out.println(count);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Actually, a pair of chopsticks need not have two sticks that are the same length. You can eat with a pair of sticks as long as the length difference is no greater than D. Samar is appointed as a head chef of a restaurant. He is provided with N sticks, the i<sup>th</sup>stick of which is L[i] units long. More than one set of chopsticks cannot share the same stick. Assist him in matching the sticks to create as many functional pairs of chopsticks as possible.The first line contains two space-separated integers N and D. The next N lines contain one integer each, the i<sup>th</sup>line giving the value of L[i].
<b>Constraints</b>
1 ≤ N ≤ 10,000 (10<sup>5</sup>)
0 ≤ D ≤ 1,000,000,000 (10<sup>9</sup>)
1 ≤ L[i] ≤ 1,000,000,000 (10<sup>9</sup>) for all integers i from 1 to NOutput a single line containing the maximum number of pairs of chopsticks Samar can form.Sample Input :
5 2
1
3
3
9
4
Sample Output :
2
Explanation :
The 5 sticks have lengths 1, 3, 3, 9, and 4 respectively. The maximum allowed difference in the lengths of two sticks forming a pair is at most 2. It is clear that the 4th stick (length 9) cannot be used with any other stick. The remaining 4 sticks can be paired as (1st and 3rd) and (2nd and 5th) to form 2 pairs of usable chopsticks., I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main() {
long int n, d;
cin >> n >> d;
long int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
sort(arr, arr + n);
int cnt = 0;
for (int i = 1; i < n; i++) {
if (arr[i] - arr[i - 1] <= d) {
cnt++;
i++;
}
}
cout << cnt << endl;
return 0;
}
, 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 number 'N'. The task is to find the Nth number whose each digit is a prime number(<10) i.e 2, 3, 5, 7. In other words you have to find nth number of this sequence : 2, 3, 5, 7, 22, 23 ,.. and so on.The first line contains a single integer T i.e. the number of test cases. The first and only line of each test case consists of a single integer N.
Constraints:
1 <= T <= 100
1 <= N <= 100000For each testcase print the nth number of the given sequence made of prime digits in a new line.Input:
2
10
21
Output:
33
222
Explanation:
Testcase 1: 10th number in the sequence of numbers whose each digit is prime is 33.
Testcase 2: 21th number in the sequence of numbers whose each digit is prime is 222., 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());
while(t-->0)
{
int n = Integer.parseInt(br.readLine());
String ans = check(n);
StringBuffer sbr = new StringBuffer(ans);
System.out.println(sbr.reverse());
}
}
static String check(int x)
{
String ans="";
while(x>0)
{
switch(x%4)
{
case 1:ans +="2"; break;
case 2:ans +="3"; break;
case 3:ans+="5"; break;
case 0:ans+="7"; break;
}
if(x%4==0)
x--;
x/=4;
}
return ans;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a number 'N'. The task is to find the Nth number whose each digit is a prime number(<10) i.e 2, 3, 5, 7. In other words you have to find nth number of this sequence : 2, 3, 5, 7, 22, 23 ,.. and so on.The first line contains a single integer T i.e. the number of test cases. The first and only line of each test case consists of a single integer N.
Constraints:
1 <= T <= 100
1 <= N <= 100000For each testcase print the nth number of the given sequence made of prime digits in a new line.Input:
2
10
21
Output:
33
222
Explanation:
Testcase 1: 10th number in the sequence of numbers whose each digit is prime is 33.
Testcase 2: 21th number in the sequence of numbers whose each digit is prime is 222., I have written this Solution Code: def nthprimedigitsnumber(number):
num=""
while (number > 0):
rem = number % 4
if (rem == 1):
num += '2'
if (rem == 2):
num += '3'
if (rem == 3):
num += '5'
if (rem == 0):
num += '7'
if (number % 4 == 0):
number = number - 1
number = number // 4
return num[::-1]
T=int(input())
for i in range(T):
number = int(input())
print(nthprimedigitsnumber(number)), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a number 'N'. The task is to find the Nth number whose each digit is a prime number(<10) i.e 2, 3, 5, 7. In other words you have to find nth number of this sequence : 2, 3, 5, 7, 22, 23 ,.. and so on.The first line contains a single integer T i.e. the number of test cases. The first and only line of each test case consists of a single integer N.
Constraints:
1 <= T <= 100
1 <= N <= 100000For each testcase print the nth number of the given sequence made of prime digits in a new line.Input:
2
10
21
Output:
33
222
Explanation:
Testcase 1: 10th number in the sequence of numbers whose each digit is prime is 33.
Testcase 2: 21th number in the sequence of numbers whose each digit is prime is 222., I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
void nthprimedigitsnumber(long long n)
{
long long len = 1;
long long prev_count = 0;
while (true) {
long long curr_count = prev_count + pow(4, len);
if (prev_count < n && curr_count >= n)
break;
len++;
prev_count = curr_count;
}
for (int i = 1; i <= len; i++) {
for (long long j = 1; j <= 4; j++) {
if (prev_count + pow(4, len - i) < n)
prev_count += pow(4, len - i);
else {
if (j == 1)
cout << "2";
else if (j == 2)
cout << "3";
else if (j == 3)
cout << "5";
else if (j == 4)
cout << "7";
break;
}
}
}
cout << endl;
}
int main(){
int t;
cin>>t;
while(t--){
long long n;
cin>>n;
nthprimedigitsnumber(n);
}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array Arr of length N. Print the lexographically minimum rotation of the array Arr.
All the elements of the array are distinct.First line of input contains a single integer N.
Second line of input contains N integers denoting the array Arr.
Constraints:
1 <= N <= 100000
1 <= Arr[i] <= 1000000000Print the lexographically minimum rotation of the array Arr.Sample Input
5
2 3 1 4 10
Sample Output
1 4 10 2 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));
br.readLine();
String[] line = br.readLine().split(" ");
int minIndex = 0;
long minVal = Long.MAX_VALUE;
for (int i=0;i<line.length;++i){
long el = Long.parseLong(line[i]);
if (minVal>el){
minVal = el;
minIndex = i;
}
}
StringBuilder sb = new StringBuilder();
for (int i = minIndex;i< line.length;++i){
sb.append(line[i]+" ");
}
for (int i=0;i<minIndex;++i){
sb.append(line[i]+" ");
}
System.out.print(sb);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array Arr of length N. Print the lexographically minimum rotation of the array Arr.
All the elements of the array are distinct.First line of input contains a single integer N.
Second line of input contains N integers denoting the array Arr.
Constraints:
1 <= N <= 100000
1 <= Arr[i] <= 1000000000Print the lexographically minimum rotation of the array Arr.Sample Input
5
2 3 1 4 10
Sample Output
1 4 10 2 3, I have written this Solution Code: N = int(input())
arr = list(map(int, input().split()))
mi = arr.index(min(arr))
ans = arr[mi:] + arr[:mi]
for e in ans:
print(e, end=' '), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array Arr of length N. Print the lexographically minimum rotation of the array Arr.
All the elements of the array are distinct.First line of input contains a single integer N.
Second line of input contains N integers denoting the array Arr.
Constraints:
1 <= N <= 100000
1 <= Arr[i] <= 1000000000Print the lexographically minimum rotation of the array Arr.Sample Input
5
2 3 1 4 10
Sample Output
1 4 10 2 3, I have written this Solution Code: #pragma GCC optimize ("Ofast")
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define VV vector
#define pb push_back
#define bitc __builtin_popcountll
#define m_p make_pair
#define infi 1e18+1
#define eps 0.000000000001
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);
string char_to_str(char c){string tem(1,c);return tem;}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T>//usage rand<long long>()
T rand() {
return uniform_int_distribution<T>()(rng);
}
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template<class T>
using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// string to integer stoi()
// string to long long stoll()
// string.substr(position,length);
// integer to string to_string();
//////////////
auto clk=clock();
#define all(x) x.begin(),x.end()
#define S second
#define F first
#define sz(x) ((long long)x.size())
#define int long long
#define f80 __float128
#define pii pair<int,int>
/////////////
signed main()
{
fastio;
#ifdef ANIKET_GOYAL
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
int n;
cin>>n;
int a[n];
for(int i=0;i<n;++i){
cin>>a[i];
}
int mi=0;
for(int i=0;i<n;++i)
if(a[i]<a[mi])
mi=i;
for(int i=0;i<n;++i)
cout<<a[(i+mi)%n]<<" ";
#ifdef ANIKET_GOYAL
// cout<<endl<<endl<<endl<<endl<<"Time elapsed: "<<(double)(clock()-clk)/CLOCKS_PER_SEC<<endl;
#endif
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two elements A and B, your task is to swap the given two elements.<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>Swap(int A, int B)</b>.Print one line which contains the output of swapped elements.Sample Input:-
5 7
Sample Output:-
7 5
Sample Input:-
3 6
Sample Output:-
6 3, I have written this Solution Code: class Solution {
public static void Swap(int A, int B){
int C = A;
A = B;
B = C;
System.out.println(A + " " + B);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two elements A and B, your task is to swap the given two elements.<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>Swap(int A, int B)</b>.Print one line which contains the output of swapped elements.Sample Input:-
5 7
Sample Output:-
7 5
Sample Input:-
3 6
Sample Output:-
6 3, I have written this Solution Code: # Python program to swap two variables
li= list(map(int,input().strip().split()))
x=li[0]
y=li[1]
# create a temporary variable and swap the values
temp = x
x = y
y = temp
print(x,end=" ")
print(y,end="")
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Create a basic table namely TEST_TABLE with 1 field TEST_FIELD as int.
( USE ONLY UPPER CASE LETTERS )
<schema>[{'name': 'TEST_TABLE', 'columns': [{'name': 'TEST_FIELD', 'type': 'INT'}]}]</schema>nannannan, I have written this Solution Code: CREATE TABLE TEST_TABLE (
TEST_FIELD INT
);, In this Programming Language: SQL, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given two arrays - value and frequency both containing N elements.
There is also a third array C which is currently empty. Then you perform N insertion operation in the array. For ith operation you insert value[i] to the end of the array frequency[i] number of times.
Finally you have to tell the kth smallest element in the array C.First line of input contains N.
Second line contains N integers denoting array - value
Third line contains N integers denoting array - frequency
Fourth line contains single integer K.
Constraints
1 <= N, value[i], frequency[i] <= 100000
1 <= k <= frequency[1] + frequency[2] +frequency[3] +........ + frequency[N]
Output a single integer which is the kth smallest element of the array C.Sample input 1
5
1 2 3 4 5
1 1 1 2 2
3
Sample output 1
3
Explanation 1:
Array C constructed is 1 2 3 4 4 5 5
Third smallest element is 3
Sample input 2
3
2 1 3
3 3 2
2
sample output 2
1
Explanation 2:
Array C constructed is 2 2 2 1 1 1 3 3
Second smallest element is 1, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args)throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
int[] val = new int[n];
for(int i=0; i<n; i++){
val[i] = Integer.parseInt(st.nextToken());
}
st = new StringTokenizer(br.readLine());
int[] freq = new int[n];
for(int i=0; i<n; i++){
freq[i] = Integer.parseInt(st.nextToken());
}
int k = Integer.parseInt(br.readLine());
for (int i=0; i<n; i++) {
for (int j=i+1; j<n; j++) {
if (val[j] < val[i]) {
int temp = val[i];
val[i] = val[j];
val[j] = temp;
int temp1 = freq[i];
freq[i] = freq[j];
freq[j] = temp1;
}
}
}
int element=0;
for(int i=0; i<n; i++){
for(int j=0; j<freq[i]; j++){
element++;
int value = val[i];
if(element==k){
System.out.print(value);
break;
}
}
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given two arrays - value and frequency both containing N elements.
There is also a third array C which is currently empty. Then you perform N insertion operation in the array. For ith operation you insert value[i] to the end of the array frequency[i] number of times.
Finally you have to tell the kth smallest element in the array C.First line of input contains N.
Second line contains N integers denoting array - value
Third line contains N integers denoting array - frequency
Fourth line contains single integer K.
Constraints
1 <= N, value[i], frequency[i] <= 100000
1 <= k <= frequency[1] + frequency[2] +frequency[3] +........ + frequency[N]
Output a single integer which is the kth smallest element of the array C.Sample input 1
5
1 2 3 4 5
1 1 1 2 2
3
Sample output 1
3
Explanation 1:
Array C constructed is 1 2 3 4 4 5 5
Third smallest element is 3
Sample input 2
3
2 1 3
3 3 2
2
sample output 2
1
Explanation 2:
Array C constructed is 2 2 2 1 1 1 3 3
Second smallest element is 1, I have written this Solution Code: def myFun():
n = int(input())
arr1 = list(map(int,input().strip().split()))
arr2 = list(map(int,input().strip().split()))
k = int(input())
arr = []
for i in range(n):
arr.append((arr1[i], arr2[i]))
arr.sort()
c = 0
for i in arr:
k -= i[1]
if k <= 0:
print(i[0])
return
myFun()
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: You are given two arrays - value and frequency both containing N elements.
There is also a third array C which is currently empty. Then you perform N insertion operation in the array. For ith operation you insert value[i] to the end of the array frequency[i] number of times.
Finally you have to tell the kth smallest element in the array C.First line of input contains N.
Second line contains N integers denoting array - value
Third line contains N integers denoting array - frequency
Fourth line contains single integer K.
Constraints
1 <= N, value[i], frequency[i] <= 100000
1 <= k <= frequency[1] + frequency[2] +frequency[3] +........ + frequency[N]
Output a single integer which is the kth smallest element of the array C.Sample input 1
5
1 2 3 4 5
1 1 1 2 2
3
Sample output 1
3
Explanation 1:
Array C constructed is 1 2 3 4 4 5 5
Third smallest element is 3
Sample input 2
3
2 1 3
3 3 2
2
sample output 2
1
Explanation 2:
Array C constructed is 2 2 2 1 1 1 3 3
Second smallest element is 1, I have written this Solution Code: #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define VV vector
#define pb push_back
#define bitc __builtin_popcountll
#define m_p make_pair
#define inf 1e18+1
#define eps 0.000000000001
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);
string char_to_str(char c){string tem(1,c);return tem;}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T>//usage rand<long long>()
T rand() {
return uniform_int_distribution<T>()(rng);
}
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> oset;
// string to integer stoi()
// string to long long stoll()
// string.substr(position,length);
// integer to string to_string();
//////////////
auto clk=clock();
#define all(x) x.begin(),x.end()
#define S second
#define F first
#define sz(x) ((long long)x.size())
#define int long long
#define f80 __float128
#define pii pair<int,int>
/////////////
signed main()
{
fastio;
#ifdef ANIKET_GOYAL
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
int N;ll K;
cin>>N;
int c=0;
pair<int, ll> A[N];
for(int i=0;i<N;++i){
cin >> A[i].first ;
}
for(int i=0;i<N;++i){
cin >> A[i].second ;
}
cin>>K;
sort(A, A+N);
for(int i=0;i<N;++i){
K -= A[i].second;
if(K <= 0){
cout << A[i].first << endl;;
break;
}
}
#ifdef ANIKET_GOYAL
// cout<<endl<<endl<<endl<<endl<<"Time elapsed: "<<(double)(clock()-clk)/CLOCKS_PER_SEC<<endl;
#endif
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a directed graph, detect the presence of a cycle in the graph.The first line of input contains two integers N and M which denotes the no of vertices and no of edges in the graph respectively.
Next M lines contain space-separated integers u and v denoting that there is a directed edge from u to v.
Constraints:
1 <= N, M <= 1000
0 <= u, v <= N-1, u != v
There are no self loops or multiple edges.The method should return 1 if there is a cycle else it should return 0.Sample Input 1:
4 5
0 1
1 2
2 3
3 0
0 2
Sample Output 1:
Yes
Explanation:
There is a cycle with nodes 0, 1, 2, 3
Sample Input 2:
4 4
0 1
1 2
2 3
0 3
Sample Output 2:
No
Explanation:
There is no cycle in this graph, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
static ArrayList<ArrayList<Integer>> adj;
static void graph(int v){
adj =new ArrayList<>();
for(int i=0;i<=v;i++) adj.add(new ArrayList<Integer>());
}
static void addedge(int u, int v){
adj.get(u).add(v);
}
static boolean dfs(int i, boolean [] vis, int parent[]){
vis[i] = true; parent[i] = 1;
for(Integer it: adj.get(i)){
if(vis[it]==false) {
if(dfs(it, vis, parent)==true) return true;
}
else if(parent[it]==1) return true;
}
parent[i] = 0;
return false;
}
static boolean helper(int n){
boolean vis[] = new boolean [n+1];
int parent[] = new int[n+1];
for(int i=0;i<=n;i++){
if(vis[i]==false){
if(dfs(i, vis, parent)) return true;
}
}
return false;
}
public static void main (String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String t[] = br.readLine().split(" ");
int n = Integer.parseInt(t[0]);
graph(n);
int e = Integer.parseInt(t[1]);
for(int i=0;i<e;i++) {
String num[] = br.readLine().split(" ");
int u = Integer.parseInt(num[0]);
int v = Integer.parseInt(num[1]);
addedge(u, v);
}
if(helper(n)) System.out.println("Yes");
else System.out.println("No");
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a directed graph, detect the presence of a cycle in the graph.The first line of input contains two integers N and M which denotes the no of vertices and no of edges in the graph respectively.
Next M lines contain space-separated integers u and v denoting that there is a directed edge from u to v.
Constraints:
1 <= N, M <= 1000
0 <= u, v <= N-1, u != v
There are no self loops or multiple edges.The method should return 1 if there is a cycle else it should return 0.Sample Input 1:
4 5
0 1
1 2
2 3
3 0
0 2
Sample Output 1:
Yes
Explanation:
There is a cycle with nodes 0, 1, 2, 3
Sample Input 2:
4 4
0 1
1 2
2 3
0 3
Sample Output 2:
No
Explanation:
There is no cycle in this graph, I have written this Solution Code: from collections import defaultdict
class Graph():
def __init__(self,vertices):
self.graph = defaultdict(list)
self.V = vertices
def addEdge(self,u,v):
self.graph[u].append(v)
def isCyclicUtil(self, v, visited, recStack):
visited[v] = True
recStack[v] = True
for neighbour in self.graph[v]:
if visited[neighbour] == False:
if self.isCyclicUtil(neighbour, visited, recStack) == True:
return True
elif recStack[neighbour] == True:
return True
recStack[v] = False
return False
def isCyclic(self):
visited = [False] * (self.V + 1)
recStack = [False] * (self.V + 1)
for node in range(self.V):
if visited[node] == False:
if self.isCyclicUtil(node,visited,recStack) == True:
return True
return False
V,edges=map(int,input().split())
g = Graph(V)
for i in range(edges):
u,v=map(int,input().split())
g.addEdge(u,v)
if g.isCyclic() == 1:
print ("Yes")
else:
print ("No"), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a directed graph, detect the presence of a cycle in the graph.The first line of input contains two integers N and M which denotes the no of vertices and no of edges in the graph respectively.
Next M lines contain space-separated integers u and v denoting that there is a directed edge from u to v.
Constraints:
1 <= N, M <= 1000
0 <= u, v <= N-1, u != v
There are no self loops or multiple edges.The method should return 1 if there is a cycle else it should return 0.Sample Input 1:
4 5
0 1
1 2
2 3
3 0
0 2
Sample Output 1:
Yes
Explanation:
There is a cycle with nodes 0, 1, 2, 3
Sample Input 2:
4 4
0 1
1 2
2 3
0 3
Sample Output 2:
No
Explanation:
There is no cycle in this graph, 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;
vector<int> g[N];
int vis[N];
bool flag = 0;
void dfs(int u){
vis[u] = 1;
for(auto i: g[u]){
if(vis[i] == 1)
flag = 1;
if(vis[i] == 0) dfs(i);
}
vis[u] = 2;
}
signed main() {
IOS;
int n, m;
cin >> n >> m;
for(int i = 1; i <= m; i++){
int u, v;
cin >> u >> v;
g[u].push_back(v);
}
for(int i = 0; i < n; i++){
if(vis[i]) continue;
dfs(i);
}
if(flag)
cout << "Yes";
else
cout << "No";
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: A child is running up a staircase with n steps and can hop either 1 step, 2 steps or 3 steps at a time. Implement a method to count how many possible ways the child can run-up to the stairs. You need to return all possible number of ways.
The time complexity of your code should be O(n).
Print answer modulo 10^9 + 7.The input line contains T, denoting the number of testcases. Each testcase contains single line containing N, i.e. stairs having number of steps.
Constraints
1 <= T <= 10
1 <= N <= 10^5Find the total number of ways. Since the answer can be very large, thus print them as modulo 10^9 + 7.Sample Input
2
4
3
Sample output
7
4
Explanation:
Testcase 1:
In this case we have stairs with 4 steps. So we can figure out how many ways are there to reach at the top.
1st: (1, 1, 1, 1)
2nd: (1, 1, 2)
3rd: (1, 2, 1)
4th: (1, 3)
5th: (2, 1, 1)
6th: (2, 2)
7th: (3, 1), I have written this Solution Code:
dp = [1,2,4]
n = int(input())
for i in range(n):
k=int(input())
one = 1
two = 2
three = 4
four = 0
if k<4:
print(dp[k-1])
continue
for i in range(3,k):
four = one + two + three
one = two
two = three
three = four
print(four%(10**9+7)), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: A child is running up a staircase with n steps and can hop either 1 step, 2 steps or 3 steps at a time. Implement a method to count how many possible ways the child can run-up to the stairs. You need to return all possible number of ways.
The time complexity of your code should be O(n).
Print answer modulo 10^9 + 7.The input line contains T, denoting the number of testcases. Each testcase contains single line containing N, i.e. stairs having number of steps.
Constraints
1 <= T <= 10
1 <= N <= 10^5Find the total number of ways. Since the answer can be very large, thus print them as modulo 10^9 + 7.Sample Input
2
4
3
Sample output
7
4
Explanation:
Testcase 1:
In this case we have stairs with 4 steps. So we can figure out how many ways are there to reach at the top.
1st: (1, 1, 1, 1)
2nd: (1, 1, 2)
3rd: (1, 2, 1)
4th: (1, 3)
5th: (2, 1, 1)
6th: (2, 2)
7th: (3, 1), I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static long waysBottomUp(int n, long dp[]){
for(int i=4; i<=n; i++){
dp[i]= ((dp[i-1]%1000000007) + (dp[i-2]%1000000007) + (dp[i-3]%1000000007))%1000000007;
}
return dp[n];
}
public static void main (String[] args)throws IOException {
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
long dp[] = new long[100001];
int t = Integer.parseInt(rd.readLine());
while(t-->0){
int n = Integer.parseInt(rd.readLine());
dp[0] =1;
dp[1] = 1;
dp[2] = 2;
dp[3] = 4;
System.out.println(waysBottomUp(n, dp)%1000000007);}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: A child is running up a staircase with n steps and can hop either 1 step, 2 steps or 3 steps at a time. Implement a method to count how many possible ways the child can run-up to the stairs. You need to return all possible number of ways.
The time complexity of your code should be O(n).
Print answer modulo 10^9 + 7.The input line contains T, denoting the number of testcases. Each testcase contains single line containing N, i.e. stairs having number of steps.
Constraints
1 <= T <= 10
1 <= N <= 10^5Find the total number of ways. Since the answer can be very large, thus print them as modulo 10^9 + 7.Sample Input
2
4
3
Sample output
7
4
Explanation:
Testcase 1:
In this case we have stairs with 4 steps. So we can figure out how many ways are there to reach at the top.
1st: (1, 1, 1, 1)
2nd: (1, 1, 2)
3rd: (1, 2, 1)
4th: (1, 3)
5th: (2, 1, 1)
6th: (2, 2)
7th: (3, 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;
int a[N];
signed main() {
IOS;
int t; cin >> t;
a[0] = 1;
for(int i = 1; i < N; i++){
if(i >= 1) a[i] += a[i-1];
if(i >= 2) a[i] += a[i-2];
if(i >= 3) a[i] += a[i-3];
a[i] %= mod;
}
while(t--){
int n; cin >> n;
cout << a[n] << endl;
}
return 0;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a sorted array arr[] of N integers and a number K is given. The task is to check if the element K is present in the array or not.
<b>Note:</b> Use binary search to solve the problemThe first line of input contains a number of test cases T. For each test case, the first line of input contains a number of elements in the array, and the number K is separated by space. The next line contains N elements.
<b>Constraints:</b>
1 ≤ T ≤ 10
1 ≤ N ≤ 10<sup>5</sup>
1 ≤ K ≤ 10<sup>9</sup>
1 ≤ arr[i] ≤ 10<sup>9</sup>
<b>Sum of N over all test cases doesn't exceed 10<sup>6</sup></b>If the element is present in the array print "1" else print "-1".Sample Input:
2
5 6
1 2 3 4 6
5 2
1 3 4 5 6
Sample Output:
1
-1, I have written this Solution Code: static int isPresent(long arr[], int n, long k)
{
int left = 0;
int right = n-1;
int res = -1;
while(left<=right){
int mid = (left+right)/2;
if(arr[mid] == k){
res = 1;
break;
}else if(arr[mid] < k){
left = mid + 1;
}else{
right = mid - 1;
}
}
return res;
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a sorted array arr[] of N integers and a number K is given. The task is to check if the element K is present in the array or not.
<b>Note:</b> Use binary search to solve the problemThe first line of input contains a number of test cases T. For each test case, the first line of input contains a number of elements in the array, and the number K is separated by space. The next line contains N elements.
<b>Constraints:</b>
1 ≤ T ≤ 10
1 ≤ N ≤ 10<sup>5</sup>
1 ≤ K ≤ 10<sup>9</sup>
1 ≤ arr[i] ≤ 10<sup>9</sup>
<b>Sum of N over all test cases doesn't exceed 10<sup>6</sup></b>If the element is present in the array print "1" else print "-1".Sample Input:
2
5 6
1 2 3 4 6
5 2
1 3 4 5 6
Sample Output:
1
-1, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
unordered_map<long long,int> m;
long k;
cin>>k;
long long a;
for(int i=0;i<n;i++){
cin>>a;
m[a]++;
}
if(m.find(k)!=m.end()){
cout<<1<<endl;
}
else{
cout<<-1<<endl;
}
}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a sorted array arr[] of N integers and a number K is given. The task is to check if the element K is present in the array or not.
<b>Note:</b> Use binary search to solve the problemThe first line of input contains a number of test cases T. For each test case, the first line of input contains a number of elements in the array, and the number K is separated by space. The next line contains N elements.
<b>Constraints:</b>
1 ≤ T ≤ 10
1 ≤ N ≤ 10<sup>5</sup>
1 ≤ K ≤ 10<sup>9</sup>
1 ≤ arr[i] ≤ 10<sup>9</sup>
<b>Sum of N over all test cases doesn't exceed 10<sup>6</sup></b>If the element is present in the array print "1" else print "-1".Sample Input:
2
5 6
1 2 3 4 6
5 2
1 3 4 5 6
Sample Output:
1
-1, I have written this Solution Code: def binary_search(arr, low, high, x):
if high >= low:
mid = (high + low) // 2
if arr[mid] == x:
return 1
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
else:
return binary_search(arr, mid + 1, high, x)
else:
return -1
def position(n,arr,x):
return binary_search(arr,0,n-1,x)
, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a sorted array arr[] of N integers and a number K is given. The task is to check if the element K is present in the array or not.
<b>Note:</b> Use binary search to solve the problemThe first line of input contains a number of test cases T. For each test case, the first line of input contains a number of elements in the array, and the number K is separated by space. The next line contains N elements.
<b>Constraints:</b>
1 ≤ T ≤ 10
1 ≤ N ≤ 10<sup>5</sup>
1 ≤ K ≤ 10<sup>9</sup>
1 ≤ arr[i] ≤ 10<sup>9</sup>
<b>Sum of N over all test cases doesn't exceed 10<sup>6</sup></b>If the element is present in the array print "1" else print "-1".Sample Input:
2
5 6
1 2 3 4 6
5 2
1 3 4 5 6
Sample Output:
1
-1, I have written this Solution Code: // arr is they array to search from
// x is target
function binSearch(arr, x) {
// write code here
// do not console.log
// return the 1 or -1
let l = 0;
let r = arr.length - 1;
let mid;
while (r >= l) {
mid = l + Math.floor((r - l) / 2);
// If the element is present at the middle
// itself
if (arr[mid] == x)
return 1;
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr[mid] > x)
r = mid - 1;
// Else the element can only be present
// in right subarray
else
l = mid + 1;
}
// We reach here when element is not
// present in array
return -1;
}, In this Programming Language: JavaScript, 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: How many ways are there to place a black and a white knight on an N * M chessboard such that they do not attack each other? The knights have to be placed on different squares. A knight can move two squares horizontally and one square vertically (L shaped), or two squares vertically and one square horizontally (L shaped). The knights attack each other if one can reach the other in one move.The first line contains the number of test cases T. Each of the next T lines contains two integers N and M which is size of matrix.
Constraints:
1 <= T <= 100
1 <= N, M <= 100For each testcase in a new line, print the required answer, i.e, number of possible ways to place knights.Sample Input:
3
2 2
2 3
4 5
Sample Output:
12
26
312
Explanation:
Test Case 1: We can place a black and a white knight in 12 possible ways such that none of them attacks each other., I have written this Solution Code: import java.io.*;
import java.util.*;
import java.math.BigInteger;
class Main{
public static void main (String[] args) throws IOException {
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s = reader.readLine();
int T = Integer.parseInt(s);
for (int t=0; t<T; t++) {
s = reader.readLine();
int index = s.indexOf(' ');
long N = Integer.parseInt(s.substring(0,index));
long M = Integer.parseInt(s.substring(index+1));
if (N < M) {
long temp = N;
N = M;
M = temp;
}
long answer;
if (M == 1) {
answer = 0;
} else if (M == 2) {
if (N == 2) {
answer = 0;
} else if (N == 3) {
answer = 4;
} else {
answer = 2*N*M-8;
}
} else if (M == 3) {
if (N == 3) {
answer = 16;
} else {
answer = 4*N*M-20;
}
} else {
answer = (N-4)*(8*M-12)+2*(4*M-6)+2*(6*M-10);
}
BigInteger all = BigInteger.valueOf(N*M);
BigInteger result = all.multiply(all.add(BigInteger.ONE.negate())).add(BigInteger.valueOf(-answer));
output.append(result).append("\n");
}
System.out.print(output);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: How many ways are there to place a black and a white knight on an N * M chessboard such that they do not attack each other? The knights have to be placed on different squares. A knight can move two squares horizontally and one square vertically (L shaped), or two squares vertically and one square horizontally (L shaped). The knights attack each other if one can reach the other in one move.The first line contains the number of test cases T. Each of the next T lines contains two integers N and M which is size of matrix.
Constraints:
1 <= T <= 100
1 <= N, M <= 100For each testcase in a new line, print the required answer, i.e, number of possible ways to place knights.Sample Input:
3
2 2
2 3
4 5
Sample Output:
12
26
312
Explanation:
Test Case 1: We can place a black and a white knight in 12 possible ways such that none of them attacks each other., I have written this Solution Code: t = int(input())
for i in range(t):
n, m = input().split()
n = int(n)
m = int(m)
if n < m:
n, m = m, n
if n == 1 or m == 1:
print(n * (n - 1))
else:
b = n * m
print((b * (b - 1)) - (4 * (((n - 1) * (m - 2)) + ((m - 1) * (n - 2))))), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: How many ways are there to place a black and a white knight on an N * M chessboard such that they do not attack each other? The knights have to be placed on different squares. A knight can move two squares horizontally and one square vertically (L shaped), or two squares vertically and one square horizontally (L shaped). The knights attack each other if one can reach the other in one move.The first line contains the number of test cases T. Each of the next T lines contains two integers N and M which is size of matrix.
Constraints:
1 <= T <= 100
1 <= N, M <= 100For each testcase in a new line, print the required answer, i.e, number of possible ways to place knights.Sample Input:
3
2 2
2 3
4 5
Sample Output:
12
26
312
Explanation:
Test Case 1: We can place a black and a white knight in 12 possible ways such that none of them attacks each other., I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main() {
int t;cin>>t;while(t--){
long n,m,c,count=0,len=0;
cin>>n>>m;
c=n*m;
count=c*(c-1);
if(m>1 && n>1){
len+=(2*(m-2))*(n-1);
len+=(2*(n-2))*(m-1);
len*=2;}
/*for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(i+1<n && j+2<m)
len++;
if(i+1<n && j-2>=0)
len++;
if(i-1>=0 && j+2<m)
len++;
if(i-1>=0 && j-2>=0)
len++;
if(i+2<n && j+1<m)
len++;
if(i+2<n && j-1>=0)
len++;
if(i-2>0 && j+1<m)
len++;
if(i-2>=0 && j-1>=0)
len++;
}
}*/
count-=len;
cout<<count<<endl;
}
//code
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a number, you task is to reverse its digits. If the reversed number contains 0s in the beginning, you must remove them as well.First line consists of a single integer denoting n.
Constraint:-
1<=size of n<=100Output is a single line containing reversed number n.Sample Input
123445
Sample Output
544321
Sample Input
16724368
Sample Output
86342761, 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();
int i=str.length()-1;
if(i==0){
int number=Integer.parseInt(str);
System.out.println(number);
}else{
while(str.charAt(i)=='0'){
i--;
}
for(int j=i;j>=0;j--){
System.out.print(str.charAt(j));
}
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a number, you task is to reverse its digits. If the reversed number contains 0s in the beginning, you must remove them as well.First line consists of a single integer denoting n.
Constraint:-
1<=size of n<=100Output is a single line containing reversed number n.Sample Input
123445
Sample Output
544321
Sample Input
16724368
Sample Output
86342761, I have written this Solution Code: n=int(input())
def reverse(n):
return int(str(n)[::-1])
print(reverse(n)), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a number, you task is to reverse its digits. If the reversed number contains 0s in the beginning, you must remove them as well.First line consists of a single integer denoting n.
Constraint:-
1<=size of n<=100Output is a single line containing reversed number n.Sample Input
123445
Sample Output
544321
Sample Input
16724368
Sample Output
86342761, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
cin>>s;
reverse(s.begin(),s.end());
int I;
for( I=0;I<s.length();I++){
if(s[I]!='0'){break;}
}
if(I==s.length()){cout<<0;return 0;}
for(int j=I;j<s.length();j++){
cout<<s[j];}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: For an integer N, your task is to calculate sum of first N natural numbers.<b>User Task:</b>
Since this will be a functional problem, you don't have to worry about input. You just have to complete the function <b>sum()</b> which takes the integer N as a parameter.
Constraints:
1 <= N < = 100000000Print the sum of first N natural numbers.Sample Input:-
5
Sample Output:-
15
Sample Input:-
3
Sample Output:-
6, I have written this Solution Code:
static void sum(int N){
long x=N;
x=x*(x+1);
x=x/2;
System.out.print(x);
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Complete the function <code>checkCanIVote</code>
<ol>
<li>Takes 2 arguments</li>
<li>1st argument <code>time</code>, which is the number of milliseconds after the function will resolve or reject</li>
<li>Second argument is the <code>age</code> upon (also a number) which you will use to return the string based on logic mentioned below</li>
<li>The function returns a promise, which will have 2 functions as arguments <code>resolve</code> and <code>reject</code> like any other promise.</li>
<li>The <code>resolve</code> function should be called with the argument <code>"You can vote"</code> after x milliseconds if <code>age</code> is greater than or equal to 18</li>
<li>The <code>reject</code> function should be called with the argument with "You can not vote" after x milliseconds if <code>age</code> less than 18</li>
</ol>
Note:- You only have to implement the function, in the example it
shows how your implemented question will be ran.Function will take two arguments
1) 1st argument will be a number which tells after how much milliseconds promise will be resolved or rejected.
2) 2nd argument will be a number (age)Function returns a promise which resolves to "You can vote" or rejects to "You can not vote".
If age >= 18 resolves to "You can vote" else rejects to "You can not vote".checkCanIVote(200, 70). then(data=>{
console. log(data) // prints 'You can vote'
}).catch((err)=>{
console.log(err) // does not do anything
})
checkCanIVote(200, 16). then(data=>{
console. log(data) // does not do anything
}).catch((err)=>{
console.log(err) // prints 'You can not vote'
}), I have written this Solution Code: function checkCanIVote(number, dat) {
return new Promise((res,rej)=>{
if(dat >= 18){
setTimeout(()=>{
res('You can vote')
},number)
}else{
setTimeout(()=>{
rej('You can not vote')
},number)
}
})
// return the output using return keyword
// do not console.log it
}, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of positive integers. The task is to find inversion count of array.
Inversion Count : For an array, inversion count indicates how far (or close) the array is from being sorted. If array is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count is the maximum.
Formally, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j.
Asked in Adobe, Amazon, Microsoft.The first line of each test case is N, the size of the array. The second line of each test case contains N elements.
Constraints:-
1 ≤ N ≤ 10^5
1 ≤ a[i] ≤ 10^5Print the inversion count of array.Sample Input:
5
2 4 1 3 5
Sample Output:
3
Explanation:
Testcase 1: The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 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 n=Integer.parseInt(br.readLine());
String input[]=br.readLine().split("\\s");
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=Integer.parseInt(input[i]);
}
System.out.print(implementMergeSort(a,0,n-1));
}
public static long implementMergeSort(int arr[], int start, int end)
{
long count=0;
if(start<end)
{
int mid=start+(end-start)/2;
count +=implementMergeSort(arr,start,mid);
count +=implementMergeSort(arr,mid+1,end);
count +=merge(arr,start,end,mid);
}
return count;
}
public static long merge(int []a,int start,int end,int mid)
{
int i=start;
int j=mid+1;
int k=0;
int len=end-start+1;
int c[]=new int[len];
long inv_count=0;
while(i<=mid && j<=end)
{
if(a[i]<=a[j])
{
c[k++]=a[i];
i++;
}
else
{
c[k++]=a[j];
j++;
inv_count +=(mid-i)+1;
}
}
while(i<=mid)
{
c[k++]=a[i++];
}
while(j<=end)
{
c[k++]=a[j++];
}
for(int l=0;l<len;l++)
a[start+l]=c[l];
return inv_count;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of positive integers. The task is to find inversion count of array.
Inversion Count : For an array, inversion count indicates how far (or close) the array is from being sorted. If array is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count is the maximum.
Formally, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j.
Asked in Adobe, Amazon, Microsoft.The first line of each test case is N, the size of the array. The second line of each test case contains N elements.
Constraints:-
1 ≤ N ≤ 10^5
1 ≤ a[i] ≤ 10^5Print the inversion count of array.Sample Input:
5
2 4 1 3 5
Sample Output:
3
Explanation:
Testcase 1: The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3)., I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
#define mod 1000000007
#define int long long
long long _mergeSort(int arr[], int temp[], int left, int right);
long long merge(int arr[], int temp[], int left, int mid, int right);
/* This function sorts the input array and returns the
number of inversions in the array */
long long mergeSort(int arr[], int array_size)
{
int temp[array_size];
return _mergeSort(arr, temp, 0, array_size - 1);
}
/* An auxiliary recursive function that sorts the input array and
returns the number of inversions in the array. */
long long _mergeSort(int arr[], int temp[], int left, int right)
{
int mid, inv_count = 0;
if (right > left) {
/* Divide the array into two parts and
call _mergeSortAndCountInv()
for each of the parts */
mid = (right + left) / 2;
/* Inversion count will be sum of
inversions in left-part, right-part
and number of inversions in merging */
inv_count += _mergeSort(arr, temp, left, mid);
inv_count += _mergeSort(arr, temp, mid + 1, right);
/*Merge the two parts*/
inv_count += merge(arr, temp, left, mid + 1, right);
}
return inv_count;
}
/* This funt merges two sorted arrays
and returns inversion count in the arrays.*/
long long merge(int arr[], int temp[], int left,
int mid, int right)
{
int i, j, k;
long long inv_count = 0;
i = left; /* i is index for left subarray*/
j = mid; /* j is index for right subarray*/
k = left; /* k is index for resultant merged subarray*/
while ((i <= mid - 1) && (j <= right)) {
if (arr[i] <= arr[j]) {
temp[k++] = arr[i++];
}
else {
temp[k++] = arr[j++];
/* this is tricky -- see above
explanation/diagram for merge()*/
inv_count = inv_count + (mid - i);
}
}
/* Copy the remaining elements of left subarray
(if there are any) to temp*/
while (i <= mid - 1)
temp[k++] = arr[i++];
/* Copy the remaining elements of right subarray
(if there are any) to temp*/
while (j <= right)
temp[k++] = arr[j++];
/*Copy back the merged elements to original array*/
for (i = left; i <= right; i++)
arr[i] = temp[i];
return inv_count;
}
signed main()
{
int n;
cin>>n;
int a[n];
unordered_map<int,int> m;
for(int i=0;i<n;i++){
cin>>a[i];
if(m.find(a[i])==m.end()){
m[a[i]]=i;
}
}
cout<<mergeSort(a,n);
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: For a given number N, Consider a table of N X N in which elements at the intersection of ith row and jth column are the product of i and j, i. e i x j.
Also given a positive integer X. Your task is to count the number of elements in the table that contain the integer X.<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>OccurenceOfX()</b> that takes the integer N and the integer X as parameter.
Constraints:-
1 <= N <= 10^5
1 <= X <= 10^9Return the count of X.Sample Input:-
5 5
Sample Output:-
2
Explanation:-
table :-
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Count of occurrence of X is :- 2
Sample Input:-
10 13
Sample Output:-
0, I have written this Solution Code: def OccurenceOfX(N,X):
cnt=0
for i in range(1, N+1):
if(X%i==0 and X/i<=N):
cnt=cnt+1
return cnt, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: For a given number N, Consider a table of N X N in which elements at the intersection of ith row and jth column are the product of i and j, i. e i x j.
Also given a positive integer X. Your task is to count the number of elements in the table that contain the integer X.<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>OccurenceOfX()</b> that takes the integer N and the integer X as parameter.
Constraints:-
1 <= N <= 10^5
1 <= X <= 10^9Return the count of X.Sample Input:-
5 5
Sample Output:-
2
Explanation:-
table :-
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Count of occurrence of X is :- 2
Sample Input:-
10 13
Sample Output:-
0, I have written this Solution Code:
int OccurenceOfX(int N,long X){
int cnt=0,i;
for( i=1;i<=N;i++){
if(X%i==0 && X/i<=N){cnt++;}}
return cnt;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: For a given number N, Consider a table of N X N in which elements at the intersection of ith row and jth column are the product of i and j, i. e i x j.
Also given a positive integer X. Your task is to count the number of elements in the table that contain the integer X.<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>OccurenceOfX()</b> that takes the integer N and the integer X as parameter.
Constraints:-
1 <= N <= 10^5
1 <= X <= 10^9Return the count of X.Sample Input:-
5 5
Sample Output:-
2
Explanation:-
table :-
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Count of occurrence of X is :- 2
Sample Input:-
10 13
Sample Output:-
0, I have written this Solution Code:
int OccurenceOfX(int N,long X){
int cnt=0,i;
for( i=1;i<=N;i++){
if(X%i==0 && X/i<=N){cnt++;}}
return cnt;
}
int main()
{
, In this Programming Language: C, Now tell me if this Code is compilable or not? | Compilable |
For this Question: For a given number N, Consider a table of N X N in which elements at the intersection of ith row and jth column are the product of i and j, i. e i x j.
Also given a positive integer X. Your task is to count the number of elements in the table that contain the integer X.<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>OccurenceOfX()</b> that takes the integer N and the integer X as parameter.
Constraints:-
1 <= N <= 10^5
1 <= X <= 10^9Return the count of X.Sample Input:-
5 5
Sample Output:-
2
Explanation:-
table :-
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Count of occurrence of X is :- 2
Sample Input:-
10 13
Sample Output:-
0, I have written this Solution Code: public static int OccurenceOfX(int N,int X){
int cnt=0,i;
for( i=1;i<=N;i++){
if(X%i==0 && X/i<=N){cnt++;}}
return cnt;
}
, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer array <b>arr</b> and a target value <b>K</b>. Print the minimum integer value <b>V</b> such that when we change all values greater than V in the array to V, <b>the absolute difference (|sum - K|) between the sum of the array elements and K is minimized.</b>
Note: the answer is not necessarily a number from arr.The input line containing T, denoting the number of testcases. Each testcase contains 2 lines. First line contains N, size of array and target K separated by space. Second line contains elements of array.
Constraints:
1 <= T <= 50
1 <= N <= 10^4
1 <= arr[i], K <= 10^5For each testcase you need to print the minimum such integer possible in a new line.Input:
2
3 10
4 9 3
3 10
2 3 5
Output:
3
5
Explanation:
Testcase 1: When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer., I have written this Solution Code: def findBestValue(arr,target):
org_sum=sum(arr)
if org_sum<target:
return max(arr)
l=1
r=max(arr)
while l<r:
mid=l+(r-l)//2;
tmp=0
for val in arr:
if val>mid:
tmp+=mid
else:
tmp+=val
if tmp<target:
l=mid+1
else:
r=mid
sum1=0
sum2=0
for val in arr:
if val>l:
sum1+=l
else:
sum1+=val
if val>l-1:
sum2+=l-1
else:
sum2+=val
if abs(sum2-target)<= abs(sum1-target):
return l-1
else:
return l
t=int(input())
while t:
n,target=map(int,input().split())
list1=list(map(int,input().split()))
print(findBestValue(list1,target))
t-=1, In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer array <b>arr</b> and a target value <b>K</b>. Print the minimum integer value <b>V</b> such that when we change all values greater than V in the array to V, <b>the absolute difference (|sum - K|) between the sum of the array elements and K is minimized.</b>
Note: the answer is not necessarily a number from arr.The input line containing T, denoting the number of testcases. Each testcase contains 2 lines. First line contains N, size of array and target K separated by space. Second line contains elements of array.
Constraints:
1 <= T <= 50
1 <= N <= 10^4
1 <= arr[i], K <= 10^5For each testcase you need to print the minimum such integer possible in a new line.Input:
2
3 10
4 9 3
3 10
2 3 5
Output:
3
5
Explanation:
Testcase 1: When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer., I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n,k;
cin>>n>>k;
int a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
sort(a,a+n);
long sum=0;
int j=0;
long ans=0;
long res;
long total=INT_MAX;
for(int i=0;i<=100000;i++){
if(i>a[j] && j!=n){sum+=a[j];j++;}
ans=sum+i*(n-j);
if(abs(ans-k)<total){res=i;total=abs(ans-k);}
}
cout<<res<<endl;
}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an integer array <b>arr</b> and a target value <b>K</b>. Print the minimum integer value <b>V</b> such that when we change all values greater than V in the array to V, <b>the absolute difference (|sum - K|) between the sum of the array elements and K is minimized.</b>
Note: the answer is not necessarily a number from arr.The input line containing T, denoting the number of testcases. Each testcase contains 2 lines. First line contains N, size of array and target K separated by space. Second line contains elements of array.
Constraints:
1 <= T <= 50
1 <= N <= 10^4
1 <= arr[i], K <= 10^5For each testcase you need to print the minimum such integer possible in a new line.Input:
2
3 10
4 9 3
3 10
2 3 5
Output:
3
5
Explanation:
Testcase 1: When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer., 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 K = Integer.parseInt(str[1]);
//`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[] = moveZeroes(arr);
//print(res);
System.out.println(findBestValue(arr, K));
}
}
static void print(int list[])
{
for(int i = 0; i < list.length; i++)
System.out.print(list[i] + " ");
}
static int findBestValue(int arr[], int target) {
int sum = 0;
int mx = Integer.MIN_VALUE;
int sz = arr.length;
int remaining_target = target;
int remaining_items = sz;
int one_part = target / sz;
for(int i = 0; i < sz; ++i) {
mx = Math.max(mx, arr[i]);
sum += arr[i];
if(arr[i] < one_part) {
remaining_items--;
remaining_target -= arr[i];
}
}
if(sum <= target) {
return mx;
}
int val1 = remaining_target / remaining_items;
int min_val = val1 - 1;
int min_diff = Math.abs(remaining_target - (min_val * remaining_items));
int diff1 = Math.abs(remaining_target - (val1 * remaining_items));
if(diff1 < min_diff) {
min_val = val1;
min_diff = diff1;
}
int val2 = val1 + 1;
int diff2 = Math.abs(remaining_target - (val2 * remaining_items));
return (diff2 < min_diff) ? val2 : min_val;
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two integers N and M, your task is to print the number of primes present between N and M (both included).
<b>Note</b>:- You have already provided a function that will check if the given number is prime or not. To use the given function you need to call <b>check_prime(x)</b> where x is the number you want to check. If the given number is prime the function will return 1 else it returns 0.
<b>Note</b>:- Do not close your main class.The input contains two space- separated integers depicting the values of N and M.
Constraints:-
1 <= N <= M <= 10000Print the count of prime numbers in the given range.Sample Input:-
1 10
Sample Output:-
4
Sample Input:-
8 10
Sample Output:-
0, I have written this Solution Code: from math import sqrt
def isPrime(n):
if (n <= 1):
return False
for i in range(2, int(sqrt(n))+1):
if (n % i == 0):
return False
return True
x=input().split()
n=int(x[0])
m=int(x[1])
count = 0
for i in range(n,m):
if isPrime(i):
count = count +1
print(count), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given two integers N and M, your task is to print the number of primes present between N and M (both included).
<b>Note</b>:- You have already provided a function that will check if the given number is prime or not. To use the given function you need to call <b>check_prime(x)</b> where x is the number you want to check. If the given number is prime the function will return 1 else it returns 0.
<b>Note</b>:- Do not close your main class.The input contains two space- separated integers depicting the values of N and M.
Constraints:-
1 <= N <= M <= 10000Print the count of prime numbers in the given range.Sample Input:-
1 10
Sample Output:-
4
Sample Input:-
8 10
Sample Output:-
0, 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 cnt=0;
for(int i=n;i<=m;i++){
if(check_prime(i)==1){cnt++;}
}
System.out.println(cnt);
}
, 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 a matrix of size N*N, your task is to find the sum of the primary and secondary diagonal of the matrix.
For Matrix:-
M<sub>00</sub> M<sub>01</sub> M<sub>02</sub>
M<sub>10</sub> M<sub>11</sub> M<sub>12</sub>
M<sub>20</sub> M<sub>21</sub> M<sub>22</sub>
Primary diagonal:- M<sub>00</sub> M<sub>11</sub> M<sub>22</sub>
Secondary diagonal:- M<sub>02</sub> M<sub>11</sub> M<sub>20</sub>The first line of input contains a single integer N, The next N lines of input contains N space-separated integers depicting the values of the matrix.
Constraints:-
1 <= N <= 500
1 <= Matrix[][] <= 100000Print the sum of primary and secondary diagonal separated by a space.Sample Input:-
2
1 4
2 6
Sample Output:-
7 6
Sample Input:-
3
1 4 2
1 5 7
3 8 1
Sample Output:-
7 10, 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;
cin>>n;
int a[n][n];
FOR(i,n){
FOR(j,n){
cin>>a[i][j];}}
int sum=0,sum1=0;;
FOR(i,n){
sum+=a[i][i];
sum1+=a[n-i-1][i];
}
out1(sum);out(sum1);
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a matrix of size N*N, your task is to find the sum of the primary and secondary diagonal of the matrix.
For Matrix:-
M<sub>00</sub> M<sub>01</sub> M<sub>02</sub>
M<sub>10</sub> M<sub>11</sub> M<sub>12</sub>
M<sub>20</sub> M<sub>21</sub> M<sub>22</sub>
Primary diagonal:- M<sub>00</sub> M<sub>11</sub> M<sub>22</sub>
Secondary diagonal:- M<sub>02</sub> M<sub>11</sub> M<sub>20</sub>The first line of input contains a single integer N, The next N lines of input contains N space-separated integers depicting the values of the matrix.
Constraints:-
1 <= N <= 500
1 <= Matrix[][] <= 100000Print the sum of primary and secondary diagonal separated by a space.Sample Input:-
2
1 4
2 6
Sample Output:-
7 6
Sample Input:-
3
1 4 2
1 5 7
3 8 1
Sample Output:-
7 10, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String args[])throws Exception {
InputStreamReader inr= new InputStreamReader(System.in);
BufferedReader br= new BufferedReader(inr);
String str=br.readLine();
int row = Integer.parseInt(str);
int col=row;
int [][] arr=new int [row][col];
for(int i=0;i<row;i++){
String line =br.readLine();
String[] elements = line.split(" ");
for(int j=0;j<col;j++){
arr[i][j]= Integer.parseInt(elements[j]);
}
}
int sumPrimary=0;
int sumSecondary=0;
for(int i=0;i<row;i++){
sumPrimary=sumPrimary + arr[i][i];
sumSecondary= sumSecondary + arr[i][row-1-i];
}
System.out.println(sumPrimary+ " " +sumSecondary);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a matrix of size N*N, your task is to find the sum of the primary and secondary diagonal of the matrix.
For Matrix:-
M<sub>00</sub> M<sub>01</sub> M<sub>02</sub>
M<sub>10</sub> M<sub>11</sub> M<sub>12</sub>
M<sub>20</sub> M<sub>21</sub> M<sub>22</sub>
Primary diagonal:- M<sub>00</sub> M<sub>11</sub> M<sub>22</sub>
Secondary diagonal:- M<sub>02</sub> M<sub>11</sub> M<sub>20</sub>The first line of input contains a single integer N, The next N lines of input contains N space-separated integers depicting the values of the matrix.
Constraints:-
1 <= N <= 500
1 <= Matrix[][] <= 100000Print the sum of primary and secondary diagonal separated by a space.Sample Input:-
2
1 4
2 6
Sample Output:-
7 6
Sample Input:-
3
1 4 2
1 5 7
3 8 1
Sample Output:-
7 10, I have written this Solution Code: // mat is the matrix/ 2d array
// the dimensions of array are n * n
function diagonalSum(mat, n) {
// write code here
// console.log the answer as in example
let principal = 0, secondary = 0;
for (let i = 0; i < n; i++) {
principal += mat[i][i];
secondary += mat[i][n - i - 1];
}
console.log(`${principal} ${secondary}`);
}
, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a matrix of size N*N, your task is to find the sum of the primary and secondary diagonal of the matrix.
For Matrix:-
M<sub>00</sub> M<sub>01</sub> M<sub>02</sub>
M<sub>10</sub> M<sub>11</sub> M<sub>12</sub>
M<sub>20</sub> M<sub>21</sub> M<sub>22</sub>
Primary diagonal:- M<sub>00</sub> M<sub>11</sub> M<sub>22</sub>
Secondary diagonal:- M<sub>02</sub> M<sub>11</sub> M<sub>20</sub>The first line of input contains a single integer N, The next N lines of input contains N space-separated integers depicting the values of the matrix.
Constraints:-
1 <= N <= 500
1 <= Matrix[][] <= 100000Print the sum of primary and secondary diagonal separated by a space.Sample Input:-
2
1 4
2 6
Sample Output:-
7 6
Sample Input:-
3
1 4 2
1 5 7
3 8 1
Sample Output:-
7 10, I have written this Solution Code: n = int(input())
sum1 = 0
sum2 = 0
for i in range(n):
a = [int(j) for j in input().split()]
sum1 = sum1+a[i]
sum2 = sum2+a[n-1-i]
print(sum1,sum2), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: For Christmas decoration, Jerry has set up N christmas lights in a row. The brightness of the i<sup>th</sup> light from the left is B[i]. A light at position i is powerful if its brightness is greater than or equal to the sum of brightness of all the lights to its left. Now, Tom wants the number of powerful lights to be maximum so he wants to rearrange the lights so that maximum number of lights are powerful. Find the maximum number of powerful lights, and make Tom and Jerry happy this Christmas.The first line of the input contains a single integer N.
The next line contain N integers denoting array B.
Constraints
1 <= N <= 100000
1 <= B[i] <= 10<sup>15</sup>Print a single integer denoting maximum number of powerful lights after rearrangement.Sample Input 1
5
10 1 3 23 3
Sample Output 1
4
Explanation: we can rearrange the lights as 1 3 10 23 3. In this lights at index 1, 2, 3 and 4 are powerful.
Sample Input 2
5
1 1 1 1 1
Sample Output 2
2, I have written this Solution Code: import java.io.*;
import java.util.*;
public class Main {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve(int TC) throws Exception {
int n = ni();
long[] a = new long[n];
for(int i=0;i<n;i++) {
a[i] = nl();
}
long sum = 0, ans = 0;
Arrays.sort(a);
for(long i: a) {
if(i >= sum) {
++ ans;
sum += i;
}
}
pn(ans);
}
boolean TestCases = false;
public static void main(String[] args) throws Exception { new Main().run(); }
void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
static void dbg(Object... o){System.err.println(Arrays.deepToString(o));}
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
int T = TestCases ? ni() : 1;
for(int t=1;t<=T;t++) solve(t);
out.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
void p(Object o) { out.print(o); }
void pn(Object o) { out.println(o); }
void pni(Object o) { out.println(o);out.flush(); }
int ni() {
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-') {
minus = true;
b = readByte();
}
while(true) {
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
long nl() {
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-') {
minus = true;
b = readByte();
}
while(true) {
if(b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
double nd() { return Double.parseDouble(ns()); }
char nc() { return (char)skip(); }
int BUF_SIZE = 1024 * 8;
byte[] inbuf = new byte[BUF_SIZE];
int lenbuf = 0, ptrbuf = 0;
int readByte() {
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
} return inbuf[ptrbuf++];
}
boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))) {
sb.appendCodePoint(b); b = readByte();
} return sb.toString();
}
char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
} return n == p ? buf : Arrays.copyOf(buf, p);
}
void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); }
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: For Christmas decoration, Jerry has set up N christmas lights in a row. The brightness of the i<sup>th</sup> light from the left is B[i]. A light at position i is powerful if its brightness is greater than or equal to the sum of brightness of all the lights to its left. Now, Tom wants the number of powerful lights to be maximum so he wants to rearrange the lights so that maximum number of lights are powerful. Find the maximum number of powerful lights, and make Tom and Jerry happy this Christmas.The first line of the input contains a single integer N.
The next line contain N integers denoting array B.
Constraints
1 <= N <= 100000
1 <= B[i] <= 10<sup>15</sup>Print a single integer denoting maximum number of powerful lights after rearrangement.Sample Input 1
5
10 1 3 23 3
Sample Output 1
4
Explanation: we can rearrange the lights as 1 3 10 23 3. In this lights at index 1, 2, 3 and 4 are powerful.
Sample Input 2
5
1 1 1 1 1
Sample Output 2
2, I have written this Solution Code: def lights(x):
sum = 0
count = 0
for i in x:
if i >= sum:
count += 1
sum += i
return count
if __name__ == '__main__':
n = int(input())
x = input().split()
for i in range(len(x)):
x[i] = int(x[i])
x.sort()
print(lights(x)), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: For Christmas decoration, Jerry has set up N christmas lights in a row. The brightness of the i<sup>th</sup> light from the left is B[i]. A light at position i is powerful if its brightness is greater than or equal to the sum of brightness of all the lights to its left. Now, Tom wants the number of powerful lights to be maximum so he wants to rearrange the lights so that maximum number of lights are powerful. Find the maximum number of powerful lights, and make Tom and Jerry happy this Christmas.The first line of the input contains a single integer N.
The next line contain N integers denoting array B.
Constraints
1 <= N <= 100000
1 <= B[i] <= 10<sup>15</sup>Print a single integer denoting maximum number of powerful lights after rearrangement.Sample Input 1
5
10 1 3 23 3
Sample Output 1
4
Explanation: we can rearrange the lights as 1 3 10 23 3. In this lights at index 1, 2, 3 and 4 are powerful.
Sample Input 2
5
1 1 1 1 1
Sample Output 2
2, I have written this Solution Code: #pragma GCC optimize ("Ofast")
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define VV vector
#define pb push_back
#define bitc __builtin_popcountll
#define m_p make_pair
#define infi 1e18+1
#define eps 0.000000000001
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);
string char_to_str(char c){string tem(1,c);return tem;}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T>//usage rand<long long>()
T rand() {
return uniform_int_distribution<T>()(rng);
}
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template<class T>
using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// string to integer stoi()
// string to long long stoll()
// string.substr(position,length);
// integer to string to_string();
//////////////
auto clk=clock();
#define all(x) x.begin(),x.end()
#define S second
#define F first
#define sz(x) ((long long)x.size())
#define int long long
#define f80 __float128
#define pii pair<int,int>
/////////////
signed main(){
fastio;
#ifdef ANIKET_GOYAL
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
int n;
cin>>n;
int a[n];
for(int i=0;i<n;++i){
cin>>a[i];
}
sort(a,a+n);
int ans=0;
int v=0;
for(int i=0;i<n;++i){
if(a[i]>=v){
++ans;
v+=a[i];
}
}
cout<<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. The task is to find if the string A can be obtained by rotating the string B by 2 places.The first line of the input contains the string A.
The second line of the input contains the string B.
Constaint:-
1 <= |A|, |B| <= 100Print 1 if the string A can be obtained by rotating string B by two places, else print 0.Sample Input:
amazon
azonam
Sample Output:
1
Input: string1 = “amazon”, string2 = “azonam”
Output: Yes
// rotated anti-clockwise
Input: string1 = “amazon”, string2 = “onamaz”
Output: Yes
// rotated clockwise, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) throws IOException{
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
String string1 = rd.readLine();
String string2 = rd.readLine();
int size1 = string1.length();
int size2 = string2.length();
int result = check(string1, string2, size1, size2);
System.out.println(result);
}
public static int check(String string1, String string2, int size1, int size2){
boolean flag = true;
if(size1 != size2){
return 0;
}
if(size1 < 2){
if(string1.equals(string2)){
return 1;
}else{
return 0;
}
}
for(int x = 0; x < size2; x++){
char c = string2.charAt((x + size2 - 2) % size2);
char c3 = string1.charAt(x);
if(c != c3){
flag = false;
break;
}
}
if(flag == false){
for(int x = 0; x < size2; x++){
char c2 = string2.charAt((x + 2) % size2);
char c3 = string1.charAt(x);
if(c2 != c3){
flag = false;
break;
}
}
}
return (flag ? 1 : 0);
}
}, 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. The task is to find if the string A can be obtained by rotating the string B by 2 places.The first line of the input contains the string A.
The second line of the input contains the string B.
Constaint:-
1 <= |A|, |B| <= 100Print 1 if the string A can be obtained by rotating string B by two places, else print 0.Sample Input:
amazon
azonam
Sample Output:
1
Input: string1 = “amazon”, string2 = “azonam”
Output: Yes
// rotated anti-clockwise
Input: string1 = “amazon”, string2 = “onamaz”
Output: Yes
// rotated clockwise, 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
string rotate(int x,string s)
{
if(x>0)
{
string p="";
int ns=s.size();
for(int i=2;i<=ns+1;i++)
{
int j=(i+ns*5)%ns;
p+=s[j];
}
return p;
}else
{
x*=-1;
string p="";
int ns=s.size();
for(int i=-4;i<ns-4;i++)
{
int j=(i+ns*5)%ns;
p+=s[j];
}
return p;
}
}
signed main()
{
string a,b;
cin>>a>>b;
int na=a.size();
int nb=b.size();
if(na!=nb) {
cout<<0<<endl;
}else
{
a=rotate(2,a);
// cout<<a<<endl;
if(a==b) cout<<1<<endl;
else
{
a=rotate(-4,a);
if(a==b) cout<<1<<endl;
else cout<<0<<endl;
}
}
}, 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. The task is to find if the string A can be obtained by rotating the string B by 2 places.The first line of the input contains the string A.
The second line of the input contains the string B.
Constaint:-
1 <= |A|, |B| <= 100Print 1 if the string A can be obtained by rotating string B by two places, else print 0.Sample Input:
amazon
azonam
Sample Output:
1
Input: string1 = “amazon”, string2 = “azonam”
Output: Yes
// rotated anti-clockwise
Input: string1 = “amazon”, string2 = “onamaz”
Output: Yes
// rotated clockwise, I have written this Solution Code: a=input()
b=input()
if a[0]==b[len(b)-2] and a[1]==b[len(b)-1]:
print(1)
else:print(0), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a sorted array of N integers a[], and Q queries. For each query, you will be given one element K your task is to print the maximum element from the array which is less than or equal to the given element(Floor), and the minimum element from the array which is greater than or equal to the given element(Ceil).<b>In case of Java only</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>floorAndCeil()</b> that takes the array a[], integer N and integer k as arguments.
<b>Custom Input</b>
The first line of input contains a single integer N. The Second line of input contains N space-separated integers depicting the values of the array. The third line of input contains a single integer Q. The next Q line of input contains a single integer the value of K.
Constraints:-
1 <= N <= 100000
1 <= K, Arr[i] <= 1000000000000
1 <= Q <= 10000In a new line Print two space-separated integers depicting the values of Floor and Ceil of the given number. If the floor or ceil of the element does not exist print -1.Sample Input:-
5
2 5 6 11 15
5
2
4
8
1
16
Sample Output:-
2 2
2 5
6 11
-1 2
15 -1, I have written this Solution Code: n = int(input())
arr = list(map(int,input().split()))
t = int(input())
def findFloor(arr, l, h, x, res):
if(l<=h):
m = l+(h-l)//2
if(arr[m] == x):
return m
if(arr[m] > x):
return findFloor(arr, l, m-1, x, res)
if(arr[m] < x):
res = m
return findFloor(arr, m+1, h, x, res)
else:
return res
def findCeil(arr, l, h, x, res):
if(l<=h):
m = l+(h-l)//2
if(arr[m] == x):
return m
if(arr[m] < x):
return findCeil(arr, m+1, h, x, res)
res = m
return findCeil(arr, l, m-1, x, res)
else:
return res
for _ in range(t):
x = int(input())
f = findFloor(arr, 0, n-1, x, -1)
c = findCeil(arr, 0, n-1, x, -1)
floor = -1
ceil = -1
if(f!=-1):
floor = arr[f]
if(c!=-1):
ceil = arr[c]
print(floor,ceil), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a sorted array of N integers a[], and Q queries. For each query, you will be given one element K your task is to print the maximum element from the array which is less than or equal to the given element(Floor), and the minimum element from the array which is greater than or equal to the given element(Ceil).<b>In case of Java only</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>floorAndCeil()</b> that takes the array a[], integer N and integer k as arguments.
<b>Custom Input</b>
The first line of input contains a single integer N. The Second line of input contains N space-separated integers depicting the values of the array. The third line of input contains a single integer Q. The next Q line of input contains a single integer the value of K.
Constraints:-
1 <= N <= 100000
1 <= K, Arr[i] <= 1000000000000
1 <= Q <= 10000In a new line Print two space-separated integers depicting the values of Floor and Ceil of the given number. If the floor or ceil of the element does not exist print -1.Sample Input:-
5
2 5 6 11 15
5
2
4
8
1
16
Sample Output:-
2 2
2 5
6 11
-1 2
15 -1, I have written this Solution Code: static void floorAndCeil(int a[], int n, int x){
int it = lower(a,n,x);
if(it==0){
if(a[it]==x){
System.out.println(x+" "+x);
}
else{
System.out.println("-1 "+a[it]);
}
}
else if (it==n){
it--;
System.out.println(a[it]+" -1");
}
else{
if(a[it]==x){
System.out.println(x+" "+x);
}
else{
it--;
System.out.println(a[it]+" "+a[it+1]);
}
}
}
static int lower(int a[], int n,int k){
int l=0;
int h=n-1;
int m;
int ans=n;
while(l<=h){
m=l+h;
m/=2;
if(a[m]<k){
l=m+1;
}
else{
h=m-1;
ans=m;
}
}
return ans;
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a sorted array of N integers a[], and Q queries. For each query, you will be given one element K your task is to print the maximum element from the array which is less than or equal to the given element(Floor), and the minimum element from the array which is greater than or equal to the given element(Ceil).<b>In case of Java only</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>floorAndCeil()</b> that takes the array a[], integer N and integer k as arguments.
<b>Custom Input</b>
The first line of input contains a single integer N. The Second line of input contains N space-separated integers depicting the values of the array. The third line of input contains a single integer Q. The next Q line of input contains a single integer the value of K.
Constraints:-
1 <= N <= 100000
1 <= K, Arr[i] <= 1000000000000
1 <= Q <= 10000In a new line Print two space-separated integers depicting the values of Floor and Ceil of the given number. If the floor or ceil of the element does not exist print -1.Sample Input:-
5
2 5 6 11 15
5
2
4
8
1
16
Sample Output:-
2 2
2 5
6 11
-1 2
15 -1, 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 1001
#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;
cin>>n;
vector<int> v;
int x;
FOR(i,n){
cin>>x;
v.EB(x);}
int q;
cin>>q;
while(q--){
cin>>x;
auto it = lower_bound(v.begin(),v.end(),x);
if(it==v.begin()){
if(*it==x){
cout<<x<<" "<<x;
}
else{
cout<<-1<<" "<<*it;
}
}
else if (it==v.end()){
it--;
cout<<*it<<" -1";
}
else{
if(*it==x){
cout<<x<<" "<<x;
}
else{
it--;
cout<<*it<<" ";
it++;
cout<<*it;}
}
END;
}
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N integers, your task is to calculate the sum of bit difference in all pairs which can be formed.The first line of input contains a single integer N, the second line of input contains N space separated integers depicting values of the array.
Constraints:-
1 <= N <= 100000
0 <= Arr[i] <= 1000000000Print the sum of bit difference of all possible pairs.
Note:- Since the answer can be quite large print your answer modulo 10<sup>9</sup> + 7Sample Input:-
2
1 3
Sample Output:-
2
Explanation:-
(1, 1) = 0
(1, 3) = 1
(3, 1) = 1
(3, 3) = 0
Sample Input:-
2
1 2
Sample Output:-
4, 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 n=Integer.parseInt(br.readLine());
String str[]=br.readLine().split(" ");
int a[]=new int[n];
for(int i=0;i<n;i++){
a[i]=Integer.parseInt(str[i]);
}
long res=0;
for (int i=0;i<32;i++){
long cnt=0;
for (int j=0;j<n;j++)
if ((a[j] & (1 << i)) == 0)
cnt++;
res=(res+(cnt*(n-cnt)*2))%1000000007;
}
System.out.println(res%1000000007);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N integers, your task is to calculate the sum of bit difference in all pairs which can be formed.The first line of input contains a single integer N, the second line of input contains N space separated integers depicting values of the array.
Constraints:-
1 <= N <= 100000
0 <= Arr[i] <= 1000000000Print the sum of bit difference of all possible pairs.
Note:- Since the answer can be quite large print your answer modulo 10<sup>9</sup> + 7Sample Input:-
2
1 3
Sample Output:-
2
Explanation:-
(1, 1) = 0
(1, 3) = 1
(3, 1) = 1
(3, 3) = 0
Sample Input:-
2
1 2
Sample Output:-
4, I have written this Solution Code: def suBD(arr, n):
ans = 0 # Initialize result
for i in range(0, 64):
count = 0
for j in range(0, n):
if ( (arr[j] & (1 << i)) ):
count+= 1
ans += (count * (n - count)) * 2;
return (ans)%(10**9+7)
n=int(input())
arr = map(int,input().split())
arr=list(arr)
print(suBD(arr, n)), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given an array of N integers, your task is to calculate the sum of bit difference in all pairs which can be formed.The first line of input contains a single integer N, the second line of input contains N space separated integers depicting values of the array.
Constraints:-
1 <= N <= 100000
0 <= Arr[i] <= 1000000000Print the sum of bit difference of all possible pairs.
Note:- Since the answer can be quite large print your answer modulo 10<sup>9</sup> + 7Sample Input:-
2
1 3
Sample Output:-
2
Explanation:-
(1, 1) = 0
(1, 3) = 1
(3, 1) = 1
(3, 3) = 0
Sample Input:-
2
1 2
Sample Output:-
4, 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 101
#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;
cin>>N;
int a[55];
int A[N];
FOR(i,N){
cin>>A[i];}
for(int i=0;i<55;i++){
a[i]=0;
}
int ans=1,p=2;
for(int i=0;i<55;i++){
for(int j=0;j<N;j++){
if(ans&A[j]){a[i]++;}
}
ans*=p;
// out(ans);
}
ans=0;
for(int i=0;i<55;i++){
ans+=(a[i]*(N-a[i])*2);
ans%=MOD;
}
out(ans);
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: After saving the planet of Xander in 2014 from Ronan, the guardians of the galaxy decided to play a game on it. Between the vast furious oceans, they discover a row of buildings. The buildings are of different heights arranged at each index along a number line. Gamora starts at building 0 and a height of 0. Groot gets the task to <b>determine the minimum thrust that Gamora needs at the start of the game so that she can jump to the top of each building without her thrust going below zero</b>. Write a code to help Groot with his task.
The units of height relate directly to units of thrust. Gamora’s thrust level is calculated as follows:
• If gamora's thrust is less than the height of the building, her new thrust = gamora's thrust – (height – gamora's thrust)
• If gamora's thrust is greater than equal to the height of the building, her new thrust = gamora's thrust + (gamora's thrust - height)The first line contains an integer n, the number of buildings.
The second line n space-separated integers, arr[1], arr[2]…arr[n], the heights of the building.
<b>Constraints:-</b>
1 ≤ n ≤ 10<sup>5</sup>
1 ≤ arr[i] ≤ 10<sup>5</sup>The output contains a single integer denoting the minimum thrust Gamora needs at the start of the game.Sample Input:-
5
3 4 3 2 4
Sample Output:-
4
Explanation:-
If we take 3 then:-
at index 1:- 3 + 3-3 = 3
at index 2:- 3 - (4-3) = 2
at index 3:- 2 - (3-2) = 1
at index 4:- 1 - (2-1) = 0
Sample Input:-
3
4 4 4
Sample Output:-
4, I have written this Solution Code: import java.io.*;
import java.util.*;
class Main {
public static void main (String[] args) {
FastReader sc = new FastReader();
int n = sc.nextInt();
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i]= sc.nextLong();
}
long l = 0;
long r= 1000000000;
long x=0;
while (l!=r){
x= (l+r)/2;
if(checkThrust(arr,x)) {
r=x;
}
else {
l=x+1;
}
}
System.out.print(l);
}
static boolean checkThrust(long[] arr,long r){
long thrust = r;
for (int i = 0; i < arr.length; i++) {
thrust = 2*thrust-arr[i];
if(thrust>=1000000000000L) return true;
if(thrust<0) return false;
}
return true;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
if(st.hasMoreTokens()){
str = st.nextToken("\n");
}
else{
str = br.readLine();
}
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: After saving the planet of Xander in 2014 from Ronan, the guardians of the galaxy decided to play a game on it. Between the vast furious oceans, they discover a row of buildings. The buildings are of different heights arranged at each index along a number line. Gamora starts at building 0 and a height of 0. Groot gets the task to <b>determine the minimum thrust that Gamora needs at the start of the game so that she can jump to the top of each building without her thrust going below zero</b>. Write a code to help Groot with his task.
The units of height relate directly to units of thrust. Gamora’s thrust level is calculated as follows:
• If gamora's thrust is less than the height of the building, her new thrust = gamora's thrust – (height – gamora's thrust)
• If gamora's thrust is greater than equal to the height of the building, her new thrust = gamora's thrust + (gamora's thrust - height)The first line contains an integer n, the number of buildings.
The second line n space-separated integers, arr[1], arr[2]…arr[n], the heights of the building.
<b>Constraints:-</b>
1 ≤ n ≤ 10<sup>5</sup>
1 ≤ arr[i] ≤ 10<sup>5</sup>The output contains a single integer denoting the minimum thrust Gamora needs at the start of the game.Sample Input:-
5
3 4 3 2 4
Sample Output:-
4
Explanation:-
If we take 3 then:-
at index 1:- 3 + 3-3 = 3
at index 2:- 3 - (4-3) = 2
at index 3:- 2 - (3-2) = 1
at index 4:- 1 - (2-1) = 0
Sample Input:-
3
4 4 4
Sample Output:-
4, I have written this Solution Code: #include <bits/stdc++.h>
using namespace std;
const long long linf = 0x3f3f3f3f3f3f3f3fLL;
const int N = 111111;
int n;
int h[N];
int check(long long x) {
long long energy = x;
for(int i = 1; i <= n; i++) {
energy += energy - h[i];
if(energy >= linf) return 1;
if(energy < 0) return 0;
}
return 1;
}
int main() {
cin >> n;
for(int i = 1; i <= n; i++) {
cin >> h[i];
}
long long L = 0, R = linf;
long long ans=0;
while(L < R) {
long long M = (L + R) / 2;
if(check(M)) {
R = M;
ans=M;
} else {
L = M + 1;
}
}
cout << ans << endl;
return 0;
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Tono loves to do shopping. Today, she went to the market where there are N different types of products. She wants to buy exactly K of them at the minimum cost. Although she is super smart, she wants to check your smartness as well. Can you tell her the minimum cost required to buy exactly K products if she has already decided to buy product J?
<b>Note:</b> Tono does not buy the same product twice, and Tono will definitely buy product J (J is the <b>index</b> of the item).The first line of the input contains three integers, N, K, and J, denoting the number of products in the market, the number of products Tono needs to buy, and the product that Tono will definitely buy.
The next line contains N singly spaced integers, the cost of the N products C[1], C[2], ..., C[N].
<b>Constraints:</b>
1 <= N <= 200000
1 <= K <= N
1 <= J <= N
1 <= C[i] <= 1000
Output a single integer, the minimum amount Tono needs to pay.Sample Input 1:
5 3 4
1 2 3 4 5
Sample Output 1:
7
Sample Input 2:
5 1 3
2 4 3 1 1
Sample Output 2:
3
<b>Explanation:</b>
Tono needs to buy exactly 3 products, and she will definitely buy the 4th product. Thus, she will buy the 1st, 2nd, and the 4th product. The total cost she pays is 1+2+4=7.
, I have written this Solution Code: import java.util.*;
import java.io.*;
class Main {
public static void main(String[] args) throws IOException {
int n = io.nextInt(), k = io.nextInt(), j = io.nextInt() - 1;
int[] arr = new int[n];
for(int i = 0; i < n; i++) {
arr[i] = io.nextInt();
}
int cost = arr[j];
arr[j] = Integer.MAX_VALUE;
Arrays.sort(arr);
for(int i = 0; i < k - 1; i++) {
cost += arr[i];
}
io.println(cost);
io.close();
}
static IO io = new IO();
static class IO {
private byte[] buf;
private InputStream in;
private PrintWriter pw;
private int total, index;
public IO() {
buf = new byte[1024];
in = System.in;
pw = new PrintWriter(System.out);
}
public int next() throws IOException {
if(total < 0)
throw new InputMismatchException();
if(index >= total) {
index = 0;
total = in.read(buf);
if(total <= 0)
return -1;
}
return buf[index++];
}
public int nextInt() throws IOException {
int n = next(), integer = 0;
while(isWhiteSpace(n))
n = next();
int neg = 1;
if(n == '-') {
neg = -1;
n = next();
}
while(!isWhiteSpace(n)) {
if(n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = next();
}
else
throw new InputMismatchException();
}
return neg * integer;
}
public int[] nextIntArray(int n) throws IOException {
int[] arr = new int[n];
for(int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
public long nextLong() throws IOException {
long integer = 0l;
int n = next();
while(isWhiteSpace(n))
n = next();
int neg = 1;
if(n == '-') {
neg = -1;
n = next();
}
while(!isWhiteSpace(n)) {
if(n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = next();
}
else
throw new InputMismatchException();
}
return neg * integer;
}
public double nextDouble() throws IOException {
double doub = 0;
int n = next();
while(isWhiteSpace(n))
n = next();
int neg = 1;
if(n == '-') {
neg = -1;
n = next();
}
while(!isWhiteSpace(n) && n != '.') {
if(n >= '0' && n <= '9') {
doub *= 10;
doub += n - '0';
n = next();
}
else
throw new InputMismatchException();
}
if(n == '.') {
n = next();
double temp = 1;
while(!isWhiteSpace(n)) {
if(n >= '0' && n <= '9') {
temp /= 10;
doub += (n - '0') * temp;
n = next();
}
else
throw new InputMismatchException();
}
}
return doub * neg;
}
public String nextString() throws IOException {
StringBuilder sb = new StringBuilder();
int n = next();
while(isWhiteSpace(n))
n = next();
while(!isWhiteSpace(n)) {
sb.append((char)n);
n = next();
}
return sb.toString();
}
public String nextLine() throws IOException {
int n = next();
while(isWhiteSpace(n))
n = next();
StringBuilder sb = new StringBuilder();
while(!isEndOfLine(n)) {
sb.append((char)n);
n = next();
}
return sb.toString();
}
private boolean isWhiteSpace(int n) {
return n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1;
}
private boolean isEndOfLine(int n) {
return n == '\n' || n == '\r' || n == -1;
}
public void print(Object obj) {
pw.print(obj);
}
public void println(Object... obj) {
if(obj.length == 1)
pw.println(obj[0]);
else {
for(Object o: obj)
pw.print(o + " ");
pw.println();
}
}
public void flush() throws IOException {
pw.flush();
}
public void close() throws IOException {
pw.close();
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Tono loves to do shopping. Today, she went to the market where there are N different types of products. She wants to buy exactly K of them at the minimum cost. Although she is super smart, she wants to check your smartness as well. Can you tell her the minimum cost required to buy exactly K products if she has already decided to buy product J?
<b>Note:</b> Tono does not buy the same product twice, and Tono will definitely buy product J (J is the <b>index</b> of the item).The first line of the input contains three integers, N, K, and J, denoting the number of products in the market, the number of products Tono needs to buy, and the product that Tono will definitely buy.
The next line contains N singly spaced integers, the cost of the N products C[1], C[2], ..., C[N].
<b>Constraints:</b>
1 <= N <= 200000
1 <= K <= N
1 <= J <= N
1 <= C[i] <= 1000
Output a single integer, the minimum amount Tono needs to pay.Sample Input 1:
5 3 4
1 2 3 4 5
Sample Output 1:
7
Sample Input 2:
5 1 3
2 4 3 1 1
Sample Output 2:
3
<b>Explanation:</b>
Tono needs to buy exactly 3 products, and she will definitely buy the 4th product. Thus, she will buy the 1st, 2nd, and the 4th product. The total cost she pays is 1+2+4=7.
, I have written this Solution Code:
a=input().split()
b=input().split()
for j in [a,b]:
for i in range(0,len(j)):
j[i]=int(j[i])
n,k,j=a[0],a[1],a[2]
c_j=b[j-1]
b.sort()
if b[k-1]<=c_j:
b[k-1]=c_j
sum=0
for i in range(0,k):
sum+=b[i]
print(sum), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Tono loves to do shopping. Today, she went to the market where there are N different types of products. She wants to buy exactly K of them at the minimum cost. Although she is super smart, she wants to check your smartness as well. Can you tell her the minimum cost required to buy exactly K products if she has already decided to buy product J?
<b>Note:</b> Tono does not buy the same product twice, and Tono will definitely buy product J (J is the <b>index</b> of the item).The first line of the input contains three integers, N, K, and J, denoting the number of products in the market, the number of products Tono needs to buy, and the product that Tono will definitely buy.
The next line contains N singly spaced integers, the cost of the N products C[1], C[2], ..., C[N].
<b>Constraints:</b>
1 <= N <= 200000
1 <= K <= N
1 <= J <= N
1 <= C[i] <= 1000
Output a single integer, the minimum amount Tono needs to pay.Sample Input 1:
5 3 4
1 2 3 4 5
Sample Output 1:
7
Sample Input 2:
5 1 3
2 4 3 1 1
Sample Output 2:
3
<b>Explanation:</b>
Tono needs to buy exactly 3 products, and she will definitely buy the 4th product. Thus, she will buy the 1st, 2nd, and the 4th product. The total cost she pays is 1+2+4=7.
, 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(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 pb push_back
#define ll long long
#define ld long double
#define int long long
#define double long double
#define mp make_pair
#define F first
#define S second
typedef pair<int, int> pii;
typedef vector<int> vi;
#define pi 3.141592653589793238
const int MOD = 1e9+7;
const int INF = 1LL<<60;
const int N = 2e5+5;
// 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
void solve(){
int n, k, j; cin>>n>>k>>j;
vector<int> vect;
int ans = 0;
For(i, 1, n+1){
int a; cin>>a;
if(i!=j)
vect.pb(a);
else
ans += a;
}
sort(all(vect));
for(int i=0; i<k-1; i++){
ans += vect[i];
}
cout<<ans;
}
signed main()
{
fast
#ifdef SWAPNIL07
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int t=1;
// cin>>t;
while(t--){
solve();
cout<<"\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 size M*N, your task is to find the column having the maximum sum and print the sum.The first line of input contains two space-separated integers M and N. The following M lines of input contain N space-separated integers each depicting the values of the matrix.
Constraints:-
1 <= M, N <= 100
1 <= Matrix[][] <= 100000Print the maximum sum.Sample Input:-
3 3
1 2 3
4 5 6
7 8 9
Sample Output:-
18
Explanation:-
1 + 4 + 7 = 12
2 + 5 + 8 = 15
3 + 6 + 9 = 18
maximum = 18
Sample Input:-
3 2
1 4
9 6
9 1
Sample Output:-
19, I have written this Solution Code: m,n=map(int ,input().split())
matrix=[]
for i in range(m):
l1=[eval(x) for x in input().split()]
matrix.append(l1)
l2=[]
for coloumn in range(n):
sum1=0
for row in range(m):
sum1+= matrix[row][coloumn]
l2.append(sum1)
print(max(l2))
'''for row in range(n):
sum2=0
for col in range(m):
sum2 += matrix[row][col]
print(sum2)''', In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a matrix of size M*N, your task is to find the column having the maximum sum and print the sum.The first line of input contains two space-separated integers M and N. The following M lines of input contain N space-separated integers each depicting the values of the matrix.
Constraints:-
1 <= M, N <= 100
1 <= Matrix[][] <= 100000Print the maximum sum.Sample Input:-
3 3
1 2 3
4 5 6
7 8 9
Sample Output:-
18
Explanation:-
1 + 4 + 7 = 12
2 + 5 + 8 = 15
3 + 6 + 9 = 18
maximum = 18
Sample Input:-
3 2
1 4
9 6
9 1
Sample Output:-
19, I have written this Solution Code: // mat is the matrix/ 2d array
// the dimensions of array are:- a rows, b columns
function colMaxSum(mat,a,b) {
// write code here
// do not console.log
// return the answer as a number
let idx = -1;
// Variable to store max sum
let maxSum = Number.MIN_VALUE;
// Traverse matrix column wise
for (let i = 0; i < b; i++) {
let sum = 0;
// calculate sum of column
for (let j = 0; j < a; j++) {
sum += mat[j][i];
}
// Update maxSum if it is
// less than current sum
if (sum > maxSum) {
maxSum = sum;
// store index
idx = i;
}
}
let res;
res = [idx, maxSum];
// return result
return maxSum;
}
, In this Programming Language: JavaScript, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a matrix of size M*N, your task is to find the column having the maximum sum and print the sum.The first line of input contains two space-separated integers M and N. The following M lines of input contain N space-separated integers each depicting the values of the matrix.
Constraints:-
1 <= M, N <= 100
1 <= Matrix[][] <= 100000Print the maximum sum.Sample Input:-
3 3
1 2 3
4 5 6
7 8 9
Sample Output:-
18
Explanation:-
1 + 4 + 7 = 12
2 + 5 + 8 = 15
3 + 6 + 9 = 18
maximum = 18
Sample Input:-
3 2
1 4
9 6
9 1
Sample Output:-
19, 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 1001
#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[m];
for(int i=0;i<m;i++){
a[i]=0;
}
int x;
int sum=0;
FOR(i,n){
FOR(j,m){
cin>>x;
a[j]+=x;
sum=max(sum,a[j]);
}
}
out(sum);
}
, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a matrix of size M*N, your task is to find the column having the maximum sum and print the sum.The first line of input contains two space-separated integers M and N. The following M lines of input contain N space-separated integers each depicting the values of the matrix.
Constraints:-
1 <= M, N <= 100
1 <= Matrix[][] <= 100000Print the maximum sum.Sample Input:-
3 3
1 2 3
4 5 6
7 8 9
Sample Output:-
18
Explanation:-
1 + 4 + 7 = 12
2 + 5 + 8 = 15
3 + 6 + 9 = 18
maximum = 18
Sample Input:-
3 2
1 4
9 6
9 1
Sample Output:-
19, 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 m = sc.nextInt();
int n = sc.nextInt();
int a[][] = new int[m][n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
a[i][j]=sc.nextInt();
}
}
int sum=0;
int ans=0;
for(int i=0;i<n;i++){
sum=0;
for(int j=0;j<m;j++){
sum+=a[j][i];
}
if(sum>ans){ans=sum;}
}
System.out.print(ans);
}
}
, 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 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: Given a string of length N. You have to select two non- overlapping (no common index) non- empty substrings of odd lengths from that string such that both those substrings are palindrome. You want the product of lengths of those substring to be maximum.Input contains of a single String of length N.
Constraints
2 <= N <= 100000
String contains lowercase english letters.Print a single integer which is the maximum possible product of lengths of selected substrings.Sample input 1
aabaaba
Sample output 1
9
Explanation : we can select substring [2-4] = aba and [5-7] = aba the product of their lengths is 9.
Sample Input 2
aabababaaa
Sample Output 2
15
, I have written this Solution Code: import java.io.*;
import java.util.*;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Main {
public static void main (String[] args)
throws IOException
{
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
String str = read.readLine();
System.out.println(maxProduct(str));
}
public static long maxProduct(String str) {
StringBuilder sb = new StringBuilder(str);
int x = sb.length();
int[] dpl = new int[x];
int[] dpr = new int[x];
modifiedOddManacher(sb.toString(), dpl);
modifiedOddManacher(sb.reverse().toString(), dpr);
long max=1;
for(int i=0;i<x-1;i++)
max=Math.max(max, (1+(dpl[i]-1)*2L)*(1+(dpr[x-(i+1)-1]-1)*2L));
return max;
}
private static void modifiedOddManacher(String str, int[] dp){
int x = str.length();
int[] center = new int[x];
for(int l=0,r=-1,i=0;i<x;i++){
int radius = (i > r) ? 1 : Math.min(center[l+(r-i)], r-i+1);
while(i-radius>=0 && i+radius<x && str.charAt(i-radius)==str.charAt(i+radius)) {
dp[i+radius] = radius+1;
radius++;
}
center[i] = radius--;
if(i+radius>r){
l = i-radius;
r = i+radius;
}
}
for(int i=0, max=1;i<x;i++){
max = Math.max(max, dp[i]);
dp[i] = max;
}
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string of length N. You have to select two non- overlapping (no common index) non- empty substrings of odd lengths from that string such that both those substrings are palindrome. You want the product of lengths of those substring to be maximum.Input contains of a single String of length N.
Constraints
2 <= N <= 100000
String contains lowercase english letters.Print a single integer which is the maximum possible product of lengths of selected substrings.Sample input 1
aabaaba
Sample output 1
9
Explanation : we can select substring [2-4] = aba and [5-7] = aba the product of their lengths is 9.
Sample Input 2
aabababaaa
Sample Output 2
15
, I have written this Solution Code: s=input()
n = len(s)
hlen = [0]*n
center = right = 0
for i in range(n):
if i < right:
hlen[i] = min(right - i, hlen[2*center - i])
while 0 <= i-1-hlen[i] and i+1+hlen[i] < len(s) and s[i-1-hlen[i]] == s[i+1+hlen[i]]:
hlen[i] += 1
if right < i+hlen[i]:
center, right = i, i+hlen[i]
left = [0]*n
right = [0]*n
for i in range(n):
left[i+hlen[i]] = max(left[i+hlen[i]], 2*hlen[i]+1)
right[i-hlen[i]] = max(right[i-hlen[i]], 2*hlen[i]+1)
for i in range(1, n):
left[~i] = max(left[~i], left[~i+1]-2)
right[i] = max(right[i], right[i-1]-2)
for i in range(1, n):
left[i] = max(left[i-1], left[i])
right[~i] = max(right[~i], right[~i+1])
print(max(left[i-1]*right[i] for i in range(1, n))), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Given a string of length N. You have to select two non- overlapping (no common index) non- empty substrings of odd lengths from that string such that both those substrings are palindrome. You want the product of lengths of those substring to be maximum.Input contains of a single String of length N.
Constraints
2 <= N <= 100000
String contains lowercase english letters.Print a single integer which is the maximum possible product of lengths of selected substrings.Sample input 1
aabaaba
Sample output 1
9
Explanation : we can select substring [2-4] = aba and [5-7] = aba the product of their lengths is 9.
Sample Input 2
aabababaaa
Sample Output 2
15
, I have written this Solution Code: #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define VV vector
#define pb push_back
#define bitc __builtin_popcountl
#define m_p make_pair
#define inf 200000000000000
#define MAXN 1000001
#define eps 0.000000000001
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);
string char_to_str(char c){string tem(1,c);return tem;}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T>//usage rand<long long>()
T rand() {
return uniform_int_distribution<T>()(rng);
}
// string to integer stoi()
// string to long long stoll()
// string.substr(position,length);
// integer to string to_string();
//////////////
#define S second
#define F first
#define int long long
/////////////
int v1[100001]={};
int v2[100001]={};
signed main()
{
fastio;
#ifdef ANIKET_GOYAL
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
int n;
string s;
cin>>s;
n=s.length();
vector<int> d1(n);
for (int i = 0, l = 0, r = -1; i < n; i++) {
int k = (i > r) ? 1 : min(d1[l + r - i], r - i + 1);
while (0 <= i - k && i + k < n && s[i - k] == s[i + k]) {
k++;
}
d1[i] = k--;
if (i + k > r) {
l = i - k;
r = i + k;
}
}
int c=0;
for(int i=0;i<n;++i)
{
int x=2*d1[i]-1;
int j=i+d1[i]-1;
while(v1[j]<x&&j>=i)
{
v1[j]=x;
x-=2;
++c;
--j;
}
}
for(int i=1;i<n;++i)
{
v1[i]=max(v1[i],v1[i-1]);
}
for(int i=n-1;i>=0;--i)
{
int x=2*d1[i]-1;
int j=i-d1[i]+1;
while(v2[j]<x&&j<=i)
{
v2[j]=x;
x-=2;
++j;
++c;
}
}
for(int i=n-2;i>=0;--i)
{
v2[i]=max(v2[i],v2[i+1]);
}
int ans=0;
for(int i=1;i<n;++i)
{
ans=max(ans,v1[i-1]*v2[i]);
}
cout<<ans;
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Power Rangers have to trap a evil spirit monster into a cuboid shape box with dimensions A*B*C, where A, B and C are positive integers. The volume of the box should be exactly X cubic units (that is A*B*C should be equal to X). To allow minimum evil aura to leak from the box the surface area of the box should be minimized. Given X, find the minimum surface area of the optimal box.The first and the only line of input contains a single integer X.
Constraints:
1 <= X <= 1000000Print the minimum surface area of the optimal box.Sample Input 1
125
Sample Output 1
150
Explanation: Optimal dimensions are 5*5*5.
Sample Input 2
100
Sample Output 1
130
Explanation: Optimal dimensions are 5*4*5., I have written this Solution Code:
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args)throws Exception{ new Main().run();}
long mod=1000000000+7;
long tsa=Long.MAX_VALUE;
void solve() throws Exception
{
long X=nl();
div(X);
out.println(tsa);
}
long cal(long a,long b, long c)
{
return 2l*(a*b + b*c + c*a);
}
void div(long n)
{
for (long i=1; i*i<=n; i++)
{
if (n%i==0)
{
if (n/i == i)
{
all_div(i, i);
}
else
{
all_div(i, n/i);
all_div(n/i, i);
}
}
}
}
void all_div(long n , long alag)
{
ArrayList<Long> al = new ArrayList<>();
for (long i=1; i*i<=n; i++)
{
if (n%i==0)
{
if (n/i == i)
tsa=min(tsa,cal(i,i,alag));
else
{
tsa=min(tsa,cal(i,n/i,alag));
}
}
}
}
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
private SpaceCharFilter filter;
PrintWriter out;
int min(int... ar){int min=Integer.MAX_VALUE;for(int i:ar)min=Math.min(min, i);return min;}
long min(long... ar){long min=Long.MAX_VALUE;for(long i:ar)min=Math.min(min, i);return min;}
int max(int... ar) {int max=Integer.MIN_VALUE;for(int i:ar)max=Math.max(max, i);return max;}
long max(long... ar) {long max=Long.MIN_VALUE;for(long i:ar)max=Math.max(max, i);return max;}
void reverse(int a[]){for(int i=0;i<a.length>>1;i++){int tem=a[i];a[i]=a[a.length-1-i];a[a.length-1-i]=tem;}}
void reverse(long a[]){for(int i=0;i<a.length>>1;i++){long tem=a[i];a[i]=a[a.length-1-i];a[a.length-1-i]=tem;}}
String reverse(String s){StringBuilder sb=new StringBuilder(s);sb.reverse();return sb.toString();}
void shuffle(int a[]) {
ArrayList<Integer> al = new ArrayList<>();
for(int i=0;i<a.length;i++)
al.add(a[i]);
Collections.sort(al);
for(int i=0;i<a.length;i++)
a[i]=al.get(i);
}
long lcm(long a,long b)
{
return (a*b)/(gcd(a,b));
}
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
long expo(long p,long q)
{
long z = 1;
while (q>0) {
if (q%2 == 1) {
z = (z * p)%mod;
}
p = (p*p)%mod;
q >>= 1;
}
return z;
}
void run()throws Exception
{
in=System.in; out = new PrintWriter(System.out);
solve();
out.flush();
}
private int scan()throws IOException
{
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
private int ni() throws IOException
{
int c = scan();
while (isSpaceChar(c))
c = scan();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = scan();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = scan();
} while (!isSpaceChar(c));
return res * sgn;
}
private long nl() throws IOException
{
long num = 0;
int b;
boolean minus = false;
while ((b = scan()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = scan();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = scan();
}
}
private double nd() throws IOException{
return Double.parseDouble(ns());
}
private String ns() throws IOException {
int c = scan();
while (isSpaceChar(c))
c = scan();
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c))
res.appendCodePoint(c);
c = scan();
} while (!isSpaceChar(c));
return res.toString();
}
private String nss() throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
return br.readLine();
}
private char nc() throws IOException
{
int c = scan();
while (isSpaceChar(c))
c = scan();
return (char) c;
}
private boolean isWhiteSpace(int n)
{
if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
return true;
return false;
}
private boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhiteSpace(c);
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}, In this Programming Language: Java, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Power Rangers have to trap a evil spirit monster into a cuboid shape box with dimensions A*B*C, where A, B and C are positive integers. The volume of the box should be exactly X cubic units (that is A*B*C should be equal to X). To allow minimum evil aura to leak from the box the surface area of the box should be minimized. Given X, find the minimum surface area of the optimal box.The first and the only line of input contains a single integer X.
Constraints:
1 <= X <= 1000000Print the minimum surface area of the optimal box.Sample Input 1
125
Sample Output 1
150
Explanation: Optimal dimensions are 5*5*5.
Sample Input 2
100
Sample Output 1
130
Explanation: Optimal dimensions are 5*4*5., I have written this Solution Code: m =int(input())
def print_factors(x):
factors=[]
for i in range(1, x + 1):
if x % i == 0:
factors.append(i)
return(factors)
area=[]
factors=print_factors(m)
for a in factors:
for b in factors:
for c in factors:
if(a*b*c==m):
area.append((2*a*b)+(2*b*c)+(2*a*c))
print(min(area)), In this Programming Language: Python, Now tell me if this Code is compilable or not? | Compilable |
For this Question: Power Rangers have to trap a evil spirit monster into a cuboid shape box with dimensions A*B*C, where A, B and C are positive integers. The volume of the box should be exactly X cubic units (that is A*B*C should be equal to X). To allow minimum evil aura to leak from the box the surface area of the box should be minimized. Given X, find the minimum surface area of the optimal box.The first and the only line of input contains a single integer X.
Constraints:
1 <= X <= 1000000Print the minimum surface area of the optimal box.Sample Input 1
125
Sample Output 1
150
Explanation: Optimal dimensions are 5*5*5.
Sample Input 2
100
Sample Output 1
130
Explanation: Optimal dimensions are 5*4*5., I have written this Solution Code: #pragma GCC optimize ("Ofast")
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define VV vector
#define pb push_back
#define bitc __builtin_popcountll
#define m_p make_pair
#define infi 1e18+1
#define eps 0.000000000001
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);
string char_to_str(char c){string tem(1,c);return tem;}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template<class T>//usage rand<long long>()
T rand() {
return uniform_int_distribution<T>()(rng);
}
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template<class T>
using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
// string to integer stoi()
// string to long long stoll()
// string.substr(position,length);
// integer to string to_string();
//////////////
auto clk=clock();
#define all(x) x.begin(),x.end()
#define S second
#define F first
#define sz(x) ((long long)x.size())
#define int long long
#define f80 __float128
#define pii pair<int,int>
/////////////
signed main()
{
fastio;
#ifdef ANIKET_GOYAL
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
int x;
cin >> x;
int ans = 6*x*x;
for (int i=1;i*i*i<=x;++i)
if (x%i==0)
for (int j=i;j*j<=x/i;++j)
if (x/i % j==0) {
int k=x/i/j;
int cur=0;
cur=i*j+i*k+k*j;
cur*=2;
ans=min(ans,cur);
}
cout<<ans;
#ifdef ANIKET_GOYAL
// cout<<endl<<endl<<endl<<endl<<"Time elapsed: "<<(double)(clock()-clk)/CLOCKS_PER_SEC<<endl;
#endif
}, In this Programming Language: C++, Now tell me if this Code is compilable or not? | Compilable |