Prime #### Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime #### Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

# CoCubes Coding Questions and Programming Paper

## Cocubes Programming Questions with Answers Find all the latest Cocubes Coding Questions and Cocubes Programming Questions. With these programs you will get a lot of coding languages on how to solve different Cocubes Java Questions with Answers, Cocubes Programming Questions in Java.

You can use the following Languages –

1. C
2. C++
3. Java

## CoCubes Programming Round Details

There will be 3 questions in CoCubes Programming Section, for which the total time alloted is 45 mins. The difficulty level of questions is progressive, i.e; the first question will be very basic, the second question will be a bit advance and the third question will be difficult and tricky. So we will suggest that you should practice a good number of questions so that you can easily solve the first 2 questions with 10-15 mins, so that you have enough time for solving the last question

CoCubes Coding QuestionSuggested Avg. TimeDifficulty
Question 15-7 minsMedium
Question 215-18 minsMedium
Question 320-25 minsHigh

### Question 1

#### Printing all the Leaders in an Array

Write a program to print all the LEADERS in the array. An element is leader if it is greater than all the elements to its right side.

And the rightmost element is always a leader. For example int the array {16, 19, 4, 3, 8, 3}, leaders are 19, 8 and 3?

`#include <stdio.h>void findLeaders(int arr[], int size){    for (int i = 0; i < size; i++)    {        int j;        for (j = i+1; j < size; j++)        {            if (arr[i] <= arr[j])                break;        }           if (j == size)             printf("%d ",arr[i]);    }} int main(){      int len, i;    printf("Enter the length of the array : ");     scanf("%d",&len);    int arr[len];    printf("Enter the elements of the array : ");    for( i=0; i<len; i++)     {         scanf("%d",&arr[i]);    }    int n = sizeof(arr)/sizeof(arr);    findLeaders(arr, n);    return 0;}`
```#include<iostream>
using namespace std;

{
for (int i = 0; i < size; i++)
{
int j;
for (j = i+1; j < size; j++)
{
if (arr[i] <= arr[j])
break;
}
if (j == size)
cout << arr[i] << " ";
}
}

int main()
{
int len, i;
cout<< "Enter the length of the array\n";
cin >> len;
int arr[len];
cout<< "Enter the elements of the array\n";
for( i=0; i<len; i++)
{
cin>>arr[i];
}

int n = sizeof(arr)/sizeof(arr);
return 0;
}
```
```class LeadersInArray
{

/*Java Function to print leaders in an array */

void printLeaders (int arr[], int size)
{
for (int i = 0; i < size; i++)
{
int j;
for (j = i + 1; j < size; j++)
{
if (arr[i] <= arr[j])
break;
}
if (j == size)
System.out.print(arr[i] + " ");
}
}
/* Driver program to test above functions */
public static void main (String[]args)
{
int arr[] = new int[]{ 16, 17, 4, 3, 5, 2 };
int n = arr.length;
}

}
```

### Question 2

#### Maximum difference between two elements such that larger element appears after the smaller number

Given an array arr[] of integers, find out the difference between any two elements such that larger element appears after the smaller number in arr[].

Examples: If array is [2, 3, 10, 6, 4, 8, 1] then returned value should be 8 (Diff between 10 and 2). If array is [ 7, 9, 5, 6, 3, 2 ] then returned value should be 2 (Diff between 7 and 9)

Time Complexity: O(n^2)
Auxiliary Space: O(1)

Use two loops. In the outer loop, pick elements one by one and in the inner loop calculate the difference of the picked element with every other element in the array and compare the difference with the maximum difference calculated so far.

`#include<stdio.h>int maxDiff (int arr[], int arr_size){    int max_diff = arr - arr;    int i, j;    for (i = 0; i < arr_size; i++)    {        for (j = i + 1; j < arr_size; j++)         {             if (arr[j] - arr[i] > max_diff)                max_diff = arr[j] - arr[i];        }    }    return max_diff;}int main (){    int len, i;    printf( "Enter the length of the array\n");     scanf("%d",&len);    int arr[len];    printf( "Enter the elements of the array\n");    for( i=0; i<len; i++)     {         scanf("%d",&arr[i]);    }    printf ("Maximum difference is %d" , maxDiff (arr, len));    return 0;}`
```import java.util.*;

class MaximumDifference {
int maxDiff(int arr[], int arr_size) {
int max_diff = arr - arr;
int i, j;
for (i = 0; i < arr_size; i++) {
for (j = i + 1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff)
max_diff = arr[j] - arr[i];
}
}
return max_diff;
}

public static void main(String[] args) {
MaximumDifference maxdif = new MaximumDifference();
int arr[] = { 1, 2, 90, 10, 110 };
System.out.println("Maximum differnce is " + maxdif.maxDiff(arr, 5));
}
}

```

### Question 3

#### Longest Prefix Suffix

Given a string of character, find the length of longest proper prefix which is also a proper suffix.
Example:
S = abab
lps is 2 because, ab.. is prefix and ..ab is also a suffix.

Input:
First line is T number of test cases. 1<=T<=100.
Each test case has one line denoting the string of length less than 100000.

Expected time compexity is O(N).

Output:
Print length of longest proper prefix which is also a proper suffix.

Example:

• Input:
2
abab
aaaa
• Output:
2
2
`#include <stdio.h>int longest(char str[], int n){    int length = 0, i = n/2;    if( n < 2 )        return 1;    else    {        while( str[i]!='\0' )        {            //When we find the character like prefix in suffix,            //we will move the length and i to count the length of the similar prefix and suffix            if (str[i] == str[length])            {                ++length;                ++i;            }             else //When prefix and suffix not equal            {                if(length == 0)                    ++i;                else                    --length;            }        }    return length;        }}int main(){    char str[] = {"aaaa"};    int n = sizeof(str)/sizeof(str);    int length = longest(str, n);    printf("%d", length);    return 0;}`
```#include <bits/stdc++.h>
using namespace std;
int lps (string);
int main ()
{
int T;
cin >> T;
getchar ();
while (T--)
{
string s;
cin >> s;
printf ("%d \n ", lps (s));
}
return 0;
}

int lps (string s)
{
int n = s.size ();
int lps[n];
int i = 1, j = 0;
lps = 0;
while (i < n)
{
if (s[i] == s[j])
{
j++;
lps[i] = j;
i++;
}
else
{
if (j != 0)
j = lps[j - 1];
else
{
lps[i] = 0;
i++;
}
}
}
return lps[n - 1];
}

```
```
import java.util.*;
import java.lang.*;
import java.io.*;

class PreSuf
{
public static void main (String[]args)
{

Scanner s = new Scanner (System.in);
int t = s.nextInt ();
for (int i = 0; i < t; i++)
{
String s1 = s.next ();
int j = 1, k = 0, l = s1.length (), max = 0, len = 0;
int lps[] = new int[l];
while (j < l)
{
if (s1.charAt (j) == s1.charAt (len))
{
len++;
lps[j] = len;
j++;
}
else
{
if (len != 0)
{
len = lps[len - 1];
}
else
{
lps[j] = 0;
j++;
}
}
}

System.out.println (lps[l - 1]);
}
}
}
```

### Question 4

#### Find the number closest to n and divisible by m

Given two integers n and m. The problem is to find the number closest to n and divisible by m. If there are more than one such number, then output the one having maximum absolute value. If n is completely divisible by m, then output n only. Time complexity of O(1) is required.

Constraints: m != 0

We find value of n/m. Let this value be q. Then we find closest of two possibilities. One is q * m other is (m * (q + 1)) or (m * (q – 1)) depending on whether one of the given two numbers is negative or not.

Algorithm:

```closestNumber(n, m)
Declare q, n1, n2
q = n / m
n1 = m * q

if (n * m) > 0
n2 = m * (q + 1)
else
n2 = m * (q - 1)

if abs(n-n1) < abs(n-n2)
return n1
return n2  ```
`#include <stdio.h>#include <stdlib.h>int closestNumber (int n, int m){    // find the quotient    int q = n / m;    // 1st possible closest number    int n1 = m * q;    // 2nd possible closest number    int n2 = (n * m) > 0 ? (m * (q + 1)) : (m * (q - 1));    // if true, then n1 is the required closest number    if (abs (n - n1) < abs (n - n2))        return n1;    else        // else n2 is the required closest number        return n2;}int main (){    int n, m;    printf("Enter two numbers : ");    scanf("%d",&n);    scanf("%d",&m);    printf("%d",closestNumber(n,m));    return 0;}`
```#include <bits/stdc++.h>
using namespace std;
int closestNumber (int n, int m)
{
// find the quotient
int q = n / m;
// 1st possible closest number
int n1 = m * q;
// 2nd possible closest number
int n2 = (n * m) > 0 ? (m * (q + 1)) : (m * (q - 1));
// if true, then n1 is the required closest number
if (abs (n - n1) < abs (n - n2))
return n1;
// else n2 is the required closest number
return n2;
}

int main ()
{
int n, m;
cout<< "Enter the two numbers\n";
cin>> n;
cin>> m;
cout << closestNumber (n, m) << endl;
return 0;
}

```
```import java.util.*;
class Main
{

// function to find the number closest to n
// and divisible by m
static int closestNumber (int n, int m)
{
// find the quotient
int q = n / m;

// 1st possible closest number
int n1 = m * q;

// 2nd possible closest number
int n2 = (n * m) > 0 ? (m * (q + 1)) : (m * (q - 1));

// if true, then n1 is the required closest number
if (Math.abs (n - n1) < Math.abs (n - n2))
return n1;

// else n2 is the required closest number
return n2;
}

// Driver program to test above
public static void main (String args[])
{
Scanner sc=new Scanner (System.in);
int n=sc.nextInt();
int m=sc.nextInt();
System.out.println (closestNumber (n, m));
}
}

```

### Question 5

Given a string consisting of only 0, 1, A, B, C where
A = AND
B = OR
C = XOR
Calculate the value of the string assuming no order of precedence and evaluation is done from left to right.

Constraints – The length of string will be odd. It will always be a valid string.
Example, 1AA0 will not be given as an input.

Examples:

```Input : 1A0B1
Output : 1
1 AND 0 OR 1 = 1

Input : 1C1B1B0A0
Output : 0```
`#include <stdio.h>#include <string.h>int evaluateBoolExpr(char* s){    int n = strlen(s);    for (int i = 0; i <n; i += 2)    {        // If operator next to current operand        // is AND.        if (i + 1 < n && i + 2 < n)        {            if (s[i+1] == 'A')            {                if (s[i+2] == '0'||s[i] == '0')                    s[i+2] = '0';                else                    s[i+2] = '1';            }            // If operator next to current operand            // is OR.            else if ((i + 1) < n && s[i+1] == 'B')            {                if (s[i+2] == '1'||s[i] == '1')                    s[i+2] = '1';                else                    s[i+2] = '0';            }            // If operator next to current operand            // is XOR (Assuming a valid input)            else            {                if (s[i+2] == s[i])                    s[i+2] = '0';                                    else                    s[i+2] = '1';            }        }    }    return s[n-1] - '0';} int main(){    char str;    scanf("%[^\n]s",str);    int result = evaluateBoolExpr(str);    printf("%d",result);}`
```// Java program to evaluate value of an expression.
class Main
{

// Evaluates boolean expression
// and returns the result
static int evaluateBoolExpr (StringBuffer s)
{
int n = s.length ();

// Traverse all operands by jumping
// a character after every iteration.
for (int i = 0; i < n; i += 2)
{

// If operator next to current operand
// is AND.
if (i + 1 < n && i + 2 < n)
{
if (s.charAt (i + 1) == 'A')
{
if (s.charAt (i + 2) == '0'||s.charAt (i) == 0)
s.setCharAt (i + 2, '0');
else
s.setCharAt (i + 2, '1');
}

// If operator next to current operand
// is OR.
else if ((i + 1) < n && s.charAt (i + 1) == 'B')
{
if (s.charAt (i + 2) == '1'||s.charAt (i) == '1')
s.setCharAt (i + 2, '1');
else
s.setCharAt (i + 2, '0');
}

// If operator next to current operand
// is XOR (Assuming a valid input)
else
{
if (s.charAt (i + 2) == s.charAt (i))
s.setCharAt (i + 2, '0');
else
s.setCharAt (i + 2, '1');
}
}
}
return s.charAt (n - 1) - '0';
}

// Driver code
public static void main (String[]args)
{
String s = "1C1B1B0A0";
StringBuffer sb = new StringBuffer (s);
System.out.println (evaluateBoolExpr (sb));
}
}

```

#### Question 6

Make a function which accepts a string as an argument that may contain repetitive characters. Implement the function to modify and return the input string, such that each character once, along with the count of consecutive occurrence. Do not append count if the character occurs only once.

Note –

• The string will only contain lowercase English Alphabets
• If you have to manipulate the input string in place you cant use another string

Assumption –

No character will occur consecutively more than 9 times.

Example –

Input – aaaaabbbccccccccdaa

Output – a4b3c8da2

```import java.util.Scanner;
public class Main
{
public static void main (String[]args)
{
try (Scanner sc = new Scanner (System.in);
)
{
StringBuilder sb = new StringBuilder (sc.nextLine ());
int count = 1;
char current = sb.charAt (0), next;
for (int i = 1; i < sb.length (); i++)
{
next = sb.charAt (i);
if (next == current)
{
sb.deleteCharAt (i);
i = i - 1;
count++;
}
else
{
sb.insert (i, count);
count = 1;
current = next;
i = i + 1;
}
}
sb.append (count);
System.out.println (sb);
}
}
```

#### Question 7

Write a function which accepts a string str, implement the function to find and return the minimum characters required to append at the end of str to make it a palindrome

Assumptions –

• The string will only contain lowercase English Alphabets

Note –

• If string is already a palindrome then return NULL
• You have to find the minimum characters required to append at the end of the string to make it a palindrome

Example –

• Input –
abcdc
• Output –
ba
```import java.util.Scanner;
public class Main
{

public static void main (String[]args)
{
try (Scanner sc = new Scanner (System.in);
)
{
StringBuilder sb = new StringBuilder (sc.nextLine ());
StringBuilder s = new StringBuilder ();
Boolean finish = true;
while (finish)
{
if (isPalindrome (sb))
{
System.out.println("NULL");
finish = false;
}

else
{
s.append (sb.charAt (0));
sb = new StringBuilder (sb.substring (1));
}
}
System.out.println (s.reverse ());
}
}
public static Boolean isPalindrome (StringBuilder sb)
{
int l = sb.length () / 2;
int m = sb.length () - 1;
for (int i = 0; i <= l; i++)
{
if (!(sb.charAt (i) == sb.charAt (m - i)))
return false;
}
return true;
}

}

```

Check out this video below on Cocubes Preparation Tips by PrepInsta, know more about cut off marks pattern and companies using Cocubes and other Tips and Tricks