Zoho Level1
Zoho Level1
Zoho Level1
1. Write a Program to give the following output for the given input:
Solution: -‘
import java.util.Scanner;
char a = str.charAt(j);
int b = ((int)str.charAt(++j)-48);
//System.out.println(a);
System.out.print(a);
break;
}
b = (b*10) + ((int)str.charAt(++j)-48);
//System.out.println(b);
System.out.print(a);
2. Write a program to sort the elements in odd positions in descending order and elements in ascending
order
Solution:
import java.io.*;
import java.util.*;
class SortOddElements{
if (i % 2 != 1) {
evenArr.add(a[i]);
else {
oddArr.add(a[i]);
Collections.sort(oddArr);
Collections.sort(evenArr, Collections.reverseOrder());
System.out.println(evenArr);
System.out.println(oddArr);
int n, sum = 0;
n = s.nextInt();
a[i] = s.nextInt();
}
System.out.println("Sum:"+sum);
int A[] = a;
int c = A.length;
assign(A, c);
3. Write a program to print the following output for the given input. You can assume the
string is of odd length
Solution:
import java.util.Scanner;
class CrossPattern {
// of characters to be
// iteration i = 0 initially
// in each iteration of i,
// of k==i or k==j
int j = len - 1 - i;
if (k == i || k == j)
System.out.print(str.charAt(k));
else
System.out.print(" ");
System.out.println("");
}
public static void main (String[] args){
pattern(str, len);
4. Find if a String2 is substring of String1. If it is, return the index of the first occurrence. else
return -1.
Solution :
import java.util.Scanner;
class CheckSubString{
int n = s1.length();
int j;
pattern match */
if (s2.charAt(i + j) != s1.charAt(j))
break;
if (j == n)
return i;
return -1;
String s1 = s.nextLine();
String s2 = s.nextLine();
if (res == -1)
System.out.println(res);
else
5. Given two sorted arrays, merge them such that the elements are not repeated
Solution :
import java.util.Arrays;
import java.util.stream.IntStream;
class MergeArrayRemoveDuplicates{
.distinct()
.sorted()
.toArray();
int[] arrayA = new int[] {7, -5, 3, 8, -4, 11, -19, 21};
int[] arrayB = new int[] {6, 13, -7, 0, 11, -4, 3, -5};
System.out.println("Array A : "+Arrays.toString(arrayA));
System.out.println("Array B : "+Arrays.toString(arrayB));
System.out.println(Arrays.toString(mergedArray));
Solution :
import java.util.regex.Pattern;
else
return result;
System.out.println(reverseWords(s1));
System.out.println(reverseWords(s2));
Solution :
import java.util.Scanner;
class CrossPattern {
// of characters to be
// iteration i = 0 initially
// in each iteration of i,
// of k==i or k==j
int j = len - 1 - i;
if (k == i || k == j)
System.out.print(str.charAt(k));
else
System.out.print(" ");
System.out.println("");
pattern(str, len);
8. Given a set of numbers like <10, 36, 54,89,12> we want to find sum of weights based on
the following conditions
1. 5 if a perfect square
2. 4 if multiple of 4 and divisible by 6
3. 3 if even number
And sort the numbers based on the weight and print it as follows
<10,its_weight>,<36,its weight><89,its weight>
Should display the numbers based on increasing order.
9. Save the string “WELCOMETOZOHOCORPORATION” in a two dimensional array and
search for substring like “too” in the two dimensional string both from left to right and from top to
bottom.
import java.io.*;
import java.util.*;
class SearchString2D{
static int R, C;
if (grid[row][col] != word.charAt(0))
return false;
break;
if (grid[rd][cd] != word.charAt(k))
break;
rd += x[dir];
cd += y[dir];
if (k == len)
return true;
return false;
R = 3;
C = 13;
{'G','E','E','K','S','Q','U','I','Z','G','E','E','K'},
{'I','D','E','Q','A','P','R','A','C','T','I','C','E'}};
patternSearch(grid, "GEEKS");
System.out.println();
patternSearch(grid, "EEE");
10. Given a 9×9 sudoku we have to evaluate it for its correctness. We have to check both the
sub matrix correctness and the whole sudoku correctness.
12. Arrange the numbers in descending order depending on the no. of factors available for each
number.
I/P: {6,8,9}
O/P: {8,6,9} or {6,8,9}
Reason: factors of 8 (1,2,4,8), factors of 6 (1,2,3,6), factors of 9 (1,3,9).
13. Two strings of equal length are given print the mismatched ones.
I/P: a b c d e f g h i
a b d e e g g i i
O/P: cd , de //when two char are mismatched they should be printed together.
f , g
h , i
Solution:
import java.util.Scanner;
class CompareStringDuplicate{
String s1=null;
String s2=null;
s1=SC.nextLine();
s2=SC.nextLine();
//compare strings
if(s1.length()!=s2.length()){
return;
boolean flg=true;
if(s1.charAt(i)!=s2.charAt(i)){
System.out.print(s1.charAt(i)+","+s2.charAt(i));
break;
14. Get a number and check whether its palindrome do not use arrays and string manipulations
I/P: 5
O/P: 101-Palindrome
Reason: binary representation of 5 is 101 & it is a palindrome.
I/P: 10
O/P: Binary representation of 10 is 1010 –Not a palindrome
Solution:
15. For any given matrix find the path from the start to the end which gives the maximum sum.
Traverse only right or down.
Example: starting index is 15 (left top) and ending index is 10 (bottom right)
15 25 30
45 25 60
70 75 10
O/P:15->45->70->75->10 sum is 215
Solution:
import java.util.Scanner;
class OddnoRange {
int n = sc.nextInt();
int r = sc.nextInt();
if (i % 2 != 0) {
18. To find the factors of the numbers given in an array and to sort the numbers in descending
order according to the factors present in it.
Input:
Given array : 8, 2, 3, 12, 16
Output:
12, 16, 8, 2, 3
Solution :
import java.util.Arrays;
import java.util.Comparator;
class SortByFactors{
index = i;
no_of_fact = countFactors;
// a given number n
int count = 0;
int sq = (int)Math.sqrt(n);
if (sq * sq == n)
count++;
if (n % i == 0)
count += 2;
}
return count;
// factors count
Arrays.sort(num,new Comparator<SortByFactors>() {
@Override
// of the structure
if (e1.no_of_fact == e2.no_of_fact)
});
System.out.print(arr[num[i].index]+" ");
printOnBasisOfFactors(arr, arr.length);
Solution:
import java.util.Scanner;
int number = 0;
number = scanner.nextInt();
while(number!=-1){
if(number==0){
} else{
number = scanner.nextInt();
String ones[] = {" ", " ONE", " TWO", " THREE", " FOUR", " FIVE", " SIX", " SEVEN", "
EIGHT", " NINE", " TEN", " ELEVEN", " TWELVE", " THIRTEEN", " FOURTEEN", " FIFTEEN", "
SIXTEEN", " SEVENTEEN", " EIGHTEEN", " NINETEEN"
};
String tens[] = {" ", " ", " TWENTY", " THIRTY", " FOURTY", " FIFTY", " SIXTY", "
SEVENTY", " EIGHTY", " NINETY"};
} else {
System.out.print(ones[num]);
if (num > 0) {
System.out.print(val);
}
}
Solution :
import java.util.Scanner;
int i,j,n,k=1;
n = in.nextInt();
for(i=1;i<=n;i++){
for(j=1;j<=i;j++)
System.out.print(k++);
System.out.println("");
21. A man his driving car from home to office with X petrol. There are N number of petrol bunks
in the city with only few capacities and each petrol is located in different places For one km one
liter will consume. So he fill up petrol in his petrol tank in each petrol bunks. Output the
remaining petrol if he has or tell him that he cannot travel if he is out of petrol.
Input:
Petrol in car: 2 Liters
Petrol bunks: A B C
Distance from petrol each petrol bunks: 1, 5, 3
Capacities of each petrol bunk: 6, 4, 2
Output:
Remaining petrol in car is 5 liters
22.
Alternate sorting: Given an array of integers, rearrange the array in such a way that the first
element is first maximum and second element is first minimum.
Solution:
import java.io.*;
import java.util.Arrays;
class SortArray{
Arrays.sort(arr);
int i = 0, j = n-1;
while (i < j) {
if (n % 2 != 0)
System.out.print(arr[i]);
int n = arr.length;
alternateSort(arr, n);
23.
Solution :
import java.util.*;
class InvalidExpressions{
// or closed)
// parenthesis
static boolean isValidString(String str) {
int cnt = 0;
if (str.charAt(i) == '(')
cnt++;
cnt--;
if (cnt < 0)
return false;
if (str.isEmpty())
return;
String temp;
q.add(str);
visit.add(str);
while (!q.isEmpty()) {
if (isValidString(str)) {
System.out.println(str);
// are processed.
level = true;
if (level)
continue;
if (!isParenthesis(str.charAt(i)))
continue;
if (!visit.contains(temp)) {
q.add(temp);
visit.add(temp);
} }
String s1 =sc.nextLine();
removeInvalidParenthesis(s1);
24.
Form a number system with only 3 and 4. Find the nth number of the number system.
Eg.) The numbers are: 3, 4, 33, 34, 43, 44, 333, 334, 343, 344, 433, 434, 443, 444, 3333, 3334,
3343, 3344, 3433, 3434, 3443, 3444 ….
Solution:
import java.io.*;
class NumberSystemThreeAndFour{
arr[0] = "";
int size = 1, m = 1;
// numbers to arr[]
m = m << 1; // Or m = m*2;
// Update size
size = size + m;
System.out.println(arr[n]);
find(i);
Solution:
import java.util.Scanner;
class ExpressionCheck{
// expression is invalid.
else
return -1;
return res;
}
26.Given an odd length word which should be printed from the middle of the word.
The output should be in the following pattern.
Example:
Solution:
import java.util.*;
class MiddlePattern{
String str=sc.nextLine();
int n=str.length();
int middle=(n+1)/2;
char[] ch=str.toCharArray();
String s="";
for(int j=middle;j<=n;j++){
s+=ch[j-1];
System.out.println(s+"$");
System.out.println(" ");
}
for(int k=0;k<middle-1;k++){
s+=ch[k];
System.out.println(s+"$");
System.out.println(" ");
System.out.println();
27.
Given an array of positive integers. The output should be the number of occurrences of each
number.
Example:
Input: {2, 3, 2, 6, 1, 6, 2}
Output:
1–1
2–3
3–1
6–2
Solution:
class ElementFrequency{
//Initialize array
if(a[i] == a[j]){
count++;
fr[j] = visited;
if(fr[i] != visited)
fr[i] = count;
System.out.println("---------------------");
System.out.println("---------------------");
if(fr[i] != visited)
System.out.println("---------------------");
28.Given two numbers a and b both < 200 we have to find the square numbers which lie
between a and b(inclusive)
Solution:
import java.io.IOException;
import java.util.Scanner;
class PerfectSquares{
int a =sc.nextInt();
int b = sc.nextInt();
int number = i;
System.out.println(+sqrt*sqrt+", ");
Solution:
import java.util.*;
class AlternateSorting{
Arrays.sort(arr);
int i = 0, j = n-1;
if (n % 2 != 0)
System.out.print(arr[i]);
int a = sc.nextInt();
for(int i=0;i<a;i++){
System.out.println("Enter The Value : ");
b[i]=sc.nextInt();
alternateSort(b, a);
30.
31.
Given two binary numbers add the two numbers in binary form without converting them to
decimal value.
Solution :
// Initialize result
int s = 0;
// 1 or 3, add 1 to result
// Compute carry
s /= 2;
i--; j--;
}
return result;
System.out.print(addBinary(a, b));
32.
33.
Given bigger NxN matrix and a smaller MxM matrix print TRUE if the smaller matrix can be
found in the bigger matrix else print FALSE
#include <iostream>
int i,j,x=0,y=0,count=0;
int n,m,flag=0;
cin>>n>>m;
int a[n][n],b[m][m];
for(i=0;i<n;i++)
for(j=0;j<n;j++)
cin>>a[i][j];
for(i=0;i<m;i++)
for(j=0;j<m;j++)
cin>>b[i][j];
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(a[i][j]==b[x][y])
count++;
if(y<m)
y++;
if(y>=m){
x++;
y=0;
if(count==m*m)
flag=1;
if(flag==1)
cout<<"TRUE";
else
cout<<"FALSE";
return 0;
34.
Given two matrices a and b both of size NxN find if matrix a can be transformed to matrix b by
rotating it 90deg , 180deg , 270deg if so print TRUE else print FALSE
Solution:
#include<stdio.h>
int main(void){
int a[20][20],b[20][20],i,j,r1,c1,r2,c2;
scanf("%d %d",&r1,&c1);
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
scanf("%d",&a[i][j]);
scanf("%d %d",&r2,&c2);
for(i=0;i<r2;i++)
for(j=0;j<c2;j++)
scanf("%d",&b[i][j]);
for(i=0;i<r1;i++){
for(j=0;j<c1;j++)
printf("%d ",a[i][j]);
printf("\n");
for(i=0;i<r2;i++){
for(j=0;j<c2;j++)
printf("%d ",b[i][j]);
printf("\n");
for(i=c1-1;i>=0;i--)
for(j=0;j<r1;j++)
if(a[j][i]!=b[c1-1-i][j])
goto NEXT1;
return;
if(r2==r1&&c2==c1){
for(i=r1-1;i>=0;i--)
for(j=c1-1;j>=0;j--)
if(a[i][j]!=b[r1-1-i][c1-1-j])
goto NEXT2;
return;
NEXT1:
if(r2==c1 &&c2==r1){
for(i=0;i<c1;i++)
for(j=r1-1;j>=0;j--)
if(a[j][i]!=b[i][r1-1-j])
goto NEXT2;
return;
NEXT2:
printf("\nFALSE\n");
return 0;
35.
Adding 2 numbers
Given 2 huge numbers as separate digits, store them in array and process them and
calculate the sum of 2 numbers and store the result in an array and print the sum.
Input:
Number of digits:12
928135673116
Number of digits:9
784621997
Output :
928920295113
Solution:
import java.io.*;
class AddTwoArrays{
// function
static int calSumUtil(int a[], int b[],int n, int m){
int i = n - 1, j = m - 1, k = n - 1;
int carry = 0, s = 0;
// of both array.
sum[k] = (s % 10);
carry = s / 10;
k--;
i--;
j--;
sum[k] = (s % 10);
carry = s / 10;
i--;
k--;
int ans = 0;
if (carry == 1)
ans = 10;
ans += sum[i];
ans *= 10;
// Wrapper Function
if (n >= m)
else
return calSumUtil(b, a, m, n);
int a[] = { 9, 3, 9 };
int b[] = { 6, 1 };
int n = a.length;
int m = b.length;
System.out.println(calSum(a, b, n, m));
36.
Solution:
import java.io.*;
import java.util.*;
import java.lang.Math;
class CloseSum {
res_l = l;
res_r = r;
r--;
l++;
int n = arr.length;
printClosest(arr, n, x);
37.
Compiuting value of sin (x)
Input x = 30 n = 10
output = 0.5
Hint : The equation sin(x) = x – x^3 / 3! + x^5 / 5! – ….
38.
class RecursionAddition{
if (y == 0)
return 0;
if (y > 0)
if (y < 0)
return -1;
code
public static void main(String[] args) {
}
}
39. Given array find maximum sum of contiguous sub array
{-2 -3 4 -1 -2 1 5 -3}
output 7 elements [ 4 -1 -2 1 5]
Solution:
import java.io.*;
import java.util.*;
class ContiguousArray{
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here = 0;
return max_so_far;
}
Another method:
import java.util.*;
import java.util.Arrays;
import java.util.stream.IntStream;
//import org.apache.commons.lang.ArrayUtils;
int a=sc.nextInt();
for(int i=0;i<a;i++){
ch[i]=sc.nextInt();
//int b=0;
for(int i=0;i<a;i++){
for(int j=i+1;j<a;j++){
if(ch[i]==ch[j]){
ch[j]=0;
}
int s=0;
//System.out.println(ch);
for(int i=0;i<a;i++){
s=s+ch[i];
System.out.println(s);
40.
be maintained.
Input :
8 3 4 7 9 N=7
Output
{3 4 } { Given unsorted array find all combination of the element for a given
sum. Order should 7}
Solution :
import java.util.ArrayList;
System.out.println(v);
}
// is true.
p.add(arr[i]);
display(p);
p.clear();
return;
// If sum becomes 0
display(p);
p.clear();
return;
// current element.
if (dp[i-1][sum]){
b.addAll(p);
// current element.
p.add(arr[i]);
if (n == 0 || sum < 0)
return;
dp[i][0] = true;
dp[0][arr[0]] = true;
dp[i-1][j-arr[i]])
: dp[i - 1][j];
if (dp[n-1][sum] == false){
return;
int n = arr.length;
int sum = 10;
printAllSubsets(arr, n, sum);
}
}
41.
input : aaabbcc
output : abc
Solution:
import java.util.*;
class RemoveDuplicateChar{
int index = 0;
int j;
if (str[i] == str[j]) {
break;
if (j == i){
str[index++] = str[i];
int n = str.length;
System.out.println(removeDuplicate(str, n));
}
}
42.
Evaluate the expression and sort and print the output. Getting the input is the tricky part
Input:
Number of input : 4
2*3
2^2^2
35
3*1
Output:
3*1
2*3
2^2^2
35
43.
Given a 6 blocks, of different height h1, …, h6 . Make 2 towers using 3 Blocks for
each tower in desired height h1, h2. Print the blocks to be used in ascending
order
Input:
1 2 5 4 3 6
height of tower: 6 15
Output :
123&456
44.
Given a number, print all the code that can be formed with z={a=1, .., z=26}.
1123
{1, 1, 2, 3} = aabc
{11, 2, 3} = kbc
{1, 1, 23} = aaw
{11, 23} = kw
Solution:
import java.util.Arrays;
class Node {
String dataString;
Node left;
Node right;
Node(String dataString) {
this.dataString = dataString;
return dataString;
return null;
if (arr.length != 0) {
data = arr[0];
// left child
if (arr.length > 1) {
data = arr[0] * 10 + arr[1];
return root;
if (root == null)
return;
printleaf(root.left);
printleaf(root.right);
printleaf(root);
// For simplicity I am taking it as string array. Char Array will save space
private static final String[] alphabet = {"", "a", "b", "c", "d", "e",
"f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r",
// to 34 in alphabet
printAllInterpretations(arr);
printAllInterpretations(arr2);
// bf(2,6) z(26)
printAllInterpretations(arr3);
// ab(1,2), l(12)
printAllInterpretations(arr4);
// a(1,0} j(10)
printAllInterpretations(arr5);
// "" empty string output as array is empty
printAllInterpretations(arr6);
printAllInterpretations(arr7);
45.
Find the minimum number of times required to represent a number as sum of squares.
Solution:
class MinCountSquares {
// base cases
if (n <= 3)
return n;
int temp = x * x;
if (temp > n)
break;
else
return res;
System.out.println(getMinSquares(6));
Solution:
def findend(i,j,a,output,index):
x = len(a)
y = len(a[0])
# initializing with 0
flagc = 0
# initializing with 0
flagr = 0
for m in range(i,x):
if a[m][j] == 1:
break
if a[m][j] == 5:
pass
if a[m][n] == 1:
break
# next time
a[m][n] = 5
if flagr == 1:
output[index].append( m-1)
else:
output[index].append(m)
if flagc == 1:
output[index].append(n-1)
else:
output[index].append(n)
def get_rectangle_coordinates(a):
size_of_array = len(a)
output = []
index = -1
for i in range(0,size_of_array):
if a[i][j] == 0:
output.append([i, j])
# last position
index = index + 1
print (output)
tests = [
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 0, 0, 0, 1],
[1, 0, 1, 0, 0, 0, 1],
[1, 0, 1, 1, 1, 1, 1],
[1, 0, 1, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1] ]
get_rectangle_coordinates(tests)
47.
Two strings of equal length will be given. Print all the adjacent pairs which are not equal.
Input: asdfghij and adsfgijh
Output: sd-ds, hij-ijh
48.
import java.io.*;
import java.util.*;
class FrequencyCheckArray{
if (hm.containsKey(a[i]) )
if (hm.containsKey(x))
return hm.get(x);
return 0;
int n = a.length;
countFreq(a, n);
System.out.println(query(2));
System.out.println(query(3));
System.out.println(query(5));
}
}
49.
From the input sentence given, find the strings which are not palindrome and print it.
class RemovePalindromeString{
int i = 0, j = str.length() - 1;
// not palindrome
if (str.charAt(i++) != str.charAt(j--))
return false;
// palindrome
return true;
}
// function to remove all the palindromic words
int n = str.length();
// traversing 'str'
else{
// add it to 'final_str'
if (!(isPalindrome(word)))
// reset
word = "";
}
// required final string
return final_str;
// Driver code
System.out.print(removePalinWords(str));
}
}
50.
Take a 2 or 3 digit input number, reverse it and add it to the original number until the
obtained number is a palindrome or 5 iterations are completed.
Input : n = 32
Output : 55
23 + 32 = 55 which is a palindrome.
Input : 39
Output : 363
Solution:
long rev_num = 0;
num = num/10;
}
return rev_num;
palindrome or not */
long rev_num = 0;
rev_num = reversDigits(num);
if(isPalindrome(num)){
System.out.println(num);
break;
}
}
ob.ReverseandAdd(195l);
ob.ReverseandAdd(265l);
}
}
Another:
import java.util.*;
int a=sc.nextInt();
int d=a;
int s,t=0,i;
while(d>0){
s=d%10;
t=t*10+s;
d=d/10;
System.out.println(t);
int b;
for(i=0;i<5;i++){
a=a+t;
b=a;
int q=0,w=0;
while(b>0){
q=b%10;
w=w*10+q;
b=b/10;
if(w==a){
System.out.println(w);
System.exit(0);
}
}
51.
Given a string, reverse only vowels in it; leaving rest of the string as it is.
Input : abcdef
Output : ebcdaf
Solution :
class ReverseVowels{
// utility function to check for vowel
|| c == 'U');
int j = 0;
if (isVowel(str[i])) {
j++;
vowel += str[i];
if (isVowel(str[i])) {
str[i] = vowel.charAt(--j);
return String.valueOf(str);
System.out.println(reverseVowel(str));
}}
52.
Write a program to check if the given words are present in matrix given below. The words can
be left to right, top to bottom and the diagonals (in top to bottom direction)
53
Write a program to form lines using given set of words. The line formation should follow
below rules.
i) Total characters in a single line excluding the space between the words and the
favorite character should not exceed the given number.
ii) Favorite character is case insensitive.
iii) Words should not be broken up. Complete words alone should be used in a single
line. A word should be used in one line only.
54.
55.
class MaxCharString{
int n = str.length();
if (str.charAt(i) == str.charAt(j))
res = Math.max(res,
Math.abs(j - i - 1));
return res;
System.out.println(maximumChars(str));
}
}
.
56.
sort the array odd numbers in ascending and even numbers in descending.
I/p 5 8 11 6 2 1 7
O/p 1 5 7 11 8 6 2
Solution :
import java.util.Arrays;
import java.util.Collections;
// order.
int l = 0, r = n - 1;
while (l < r) {
while (arr[l] % 2 != 0) {
l++;
k++;
r--;
// number right.
if (l < r) {
arr[l] = arr[r];
arr[r] = temp;
Arrays.sort(arr, 0, k, Collections.reverseOrder());
Arrays.sort(arr, k, n);
}
Integer arr[] = { 1, 3, 2, 7, 5, 4 };
twoWaySort(arr, arr.length);
System.out.println(Arrays.toString(arr));
}
}
Another:
import java.util.*;
import java.util.Arrays;
int a=sc.nextInt();
int i,j;
for(i=0;i<a;i++){
b[i]=sc.nextInt();
Arrays.sort(b);
for(j=0;j<a;j++){
if(b[j]%2!=0){
System.out.print(b[j]+" ");
}
for(j=a-1;j>0;j--){
if(b[j]%2==0){
System.out.print(b[j]+" ");
57.
array of numbers were given to find a number which has same sum of numbers in it’s
either side.
I/p 1, 2, 3, 7, 6
O/p 7(has 1+ 2+3 in left 6 in right)
Solution :
prefixSum[0] = arr[0];
if (prefixSum[i] == suffixSum[i])
return arr[i];
return -1;
int arr[] = { 1, 4, 2, 5 };
int n = arr.length;
System.out.println(findElement(arr, n));
}
}
58.
you’re given an array. Print the elements of the array which are greater than its previous
elements in the array.
Input : 2, -3, -4, 5, 9, 7, 8
Solution:
import java.io.*;
import java.util.*;
import java.lang.*;
class PreviousGreatest{
System.out.print("-1, ");
// Let us process
// remaining elements.
int j;
break;
}
if (j == -1)
System.out.print("-1, ");
int n = arr.length;
prevGreater(arr, n);
59.You’re given an even number n. If n=4, you have to print the following pattern :
4444
4334
4334
4444
If n=6, then the pattern should be like this :
666666
655556
654456
654456
655556
666666
Solution:
import java.util.*;
import java.lang.*;
import java.io.*;
class NumberPattern{
public static void main(String args[]) {
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();int limit=0;
int s=n;
int a[][]= new int[n][n];
int l=0;int r=n-1;
while(limit<n){
for(int i=l;i<=r;i++){
for(int j=l;j<=r;j++)
if(i==l || i==r || j==l || j==r)
a[i][j]=n;
}
l++;r--;n--;limit++;
}
for(int i=0;i<s;i++){
for(int j=0;j<s;j++)
System.out.print(a[i][j]);
System.out.println();
}
}
}
60.
You’re given a number n. If write all the numbers from 1 to n in a paper, we have to find the
number of characters written on the paper.For example if n=13, the output should be 18 if n =
101, the output should be 195
Solution:
int number_of_digits = 0;
// In the loop we are decreasing
// ( n - i + 1 ) is greater than 0
number_of_digits += (n - i + 1);
return number_of_digits;
int n = 13;
System.out.println(totalDigits(n));
61.
A number is called as binary-decimal if all the digits in the number should be either ‘1’ or
‘0’. Any number can be written as a sum of binary-decimals. Our task is to find the
minimum number of binary-decimals to represent a number.
Input : 32
Output : 10 11 11
Input : 120
Output : 10 110
Solution:
import java.util.*;
import java.lang.*;
class PsuedoBinary{
while (n != 0){
// calculate m (A number that has same
// of 0 digits)
int temp = n, m = 0, p = 1;
while(temp != 0){
if (rem != 0)
m += p;
p *= 10;
// subtract m from n
n = n - m;
System.out.println(" ");
int n = 31;
psuedoBinary(n);
62.
You’re given a string as an input. You have to reverse the string by keeping the
punctuation and spaces. You have to modify the source string itself with creating an
another string.
Input :A man, in the boat says : I see 1-2-3 in the sky
Output :
y kse, ht ni3 21ee slsy : a sta o-b-e ht nin amA
Solution:
int j = result.length - 1;
j--;
result[j] = inputArray[i];
j--;
}
System.out.println(String.valueOf(result));
63.
Given two Strings s1 and s2, remove all the characters from s1 which is present in s2.
Input: s1=”expErIence”, s2=”En”
output: s1=”exprIece”
Solution:
count[str.charAt(i)]++;
return count;
if(count[temp] == 0){
arr[res_ind] = arr[ip_ind];
res_ind ++;
ip_ind++;
System.out.println(removeDirtyChars(str, mask_str));
}
64.
Find the next greater element for each element in given array.
input: array[]={6, 3, 9, 10, 8, 2, 1, 15, 7};
output: {7, 5, 10, 15, 9, 3, 2, _, 8}
If we are solving this question using sorting, we need to use any O(nlogn) sorting algorithm.
Solution:
class NextGreatestElement{
int next, i, j;
next = -1;
next = arr[j];
break;
System.out.println(arr[i]+" -- "+next);
}}
int n = arr.length;
printNGE(arr, n);
}
65.
Given an array with repeated numbers, Find the top three repeated numbers.
input: array[]={3, 4, 2, 3, 16, 3, 15, 16, 15, 15, 16, 2, 3}
output: 3, 16, 15
Solution :
import java.io.*;
import java.util.*;
class Pair {
class TopRepeatedElement {
if (n < 3){
System.out.print("Invalid Input");
return;
if (freq.containsKey(arr[i]))
freq.put(arr[i], 1 + freq.get(arr[i]));
else
freq.put(arr[i], 1);
// Initialize first value of each variable
z.first = y.first;
z.second = y.second;
y.first = x.first;
y.second = x.second;
x.first = Integer.parseInt(String.valueOf(curr.getValue()));
x.second = Integer.parseInt(String.valueOf(curr.getKey()));
// than y element
else if (Integer.parseInt(String.valueOf(curr.getValue())) > y.first) {
z.first = y.first;
z.second = y.second;
y.first = Integer.parseInt(String.valueOf(curr.getValue()));
y.second = Integer.parseInt(String.valueOf(curr.getKey()));
// third largest.
z.first = Integer.parseInt(String.valueOf(curr.getValue()));
z.second = Integer.parseInt(String.valueOf(curr.getKey()));
top3Repeated(arr, n);
66.
Solution:
class NumberToChar{
return null;
// convert to base 26
for(char c : characters){
return result;
Solution :
import java.util.*;
if (r == 'I')
return 1;
if (r == 'V')
return 5;
if (r == 'X')
return 10;
if (r == 'L')
return 50;
if (r == 'C')
return 100;
if (r == 'D')
return 500;
if (r == 'M')
return 1000;
return -1;
// Initialize result
int res = 0;
int s1 = value(str.charAt(i));
if (i+1 <str.length()){
int s2 = value(str.charAt(i+1));
else{
else{
i++;
return res;
68.
Write a program to print all permutations of a given string. Note here you need to take all
combinations as well, say for the input ABC the output should be as follows:
Solution:
int n = str.length();
permutation.permute(str, 0, n-1);
if (l == r)
System.out.println(str);
else{
str = swap(str,l,i);
str = swap(str,l,i);
char temp;
temp = charArray[i] ;
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}
}
Solution:
import java.util.*;
class RotateMatrix {
arr[j][i] = arr[k][i];
arr[k][i] = temp;
arr[j][i] = arr[i][j];
arr[i][j] = temp;
}
}
System.out.println("");
// matrix by 90 degree
transpose(arr);
reverseColumns(arr);
int arr[][] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
rotate90(arr);
printMatrix(arr);
70.
Write a program to convert a number into a mono-digit number.
Conditions:
a) You are allowed to add and subtract the consecutive digits (starting from left).
b) You are allowed to do only one operation on a digit.
c) You cannot perform any operation on a resultant digit of the previous operation.
d) Your code should also find if a given number cannot be converted to a mono digit
number.
Solution:
#include<stdio.h>
void main(){
int i,j=0,b[20],k=0,c[20],m=1,n=0,l=0;
char a[20];
clrscr();
while(a[j]!='\0'){
j++;
c[0]=b[0];
m=1,n=0;
}
c[0]=b[0]+b[1];
m=2,n=0;
c[0]=b[0]-b[1];
m=2,n=0;
for(j=m;j<i;j++) { n++; //increments the monodigit array position if(c[0]==b[j]) //single digit is equal
to c[0] { c[n]=b[j]; //store the monodigit value into array m=j+1; //increments the index by one goto
check; } else if(c[0]==b[j]+b[j+1]) //addition of two consecutive are equal to c[0] { c[n]=b[j]+b[j+1];
m=j+2; goto check; } else if(c[0]==b[j]-b[j+1]) //subtraction of two consecutive are equal to c[0]
{ c[n]=b[j]-b[j+1]; m=j+2; goto check; } else //breaks from loop when all conditions fails { l++; break; } }
if(m>i-1) //prints the monodigit
for(j=0;j<n+1;j++)
printf("%d",c[j]);
getch();
71.
72.
Find the distance between two given points and round it to the nearest number.
Solution:
class DistanceBetweenNumbers{
static double distance(int x1, int y1, int x2, int y2){
// Calculating distance
System.out.println(Math.round(distance(3, 4, 4, 3)*100000.0)/100000.0);
}
}
73.Count the numbers of characters in the given string treating ‘$’ as escape sequence. If ‘$’ is
preceeded by ”, consider it as normal ‘$’ and not the escape sequence. If ” occurs, treat it as
single ”.
74.
Solution :
import java.io.*;
class SumOfMatrixArray{
static int m = 4;
static int n = 4;
int i,j,sum = 0;
sum = 0;
int i,j,sum = 0;
sum = 0;
}
public static void main (String[] args) {
int i,j;
int x = 1;
arr[i][j] = x++;
row_sum(arr);
column_sum(arr);
75.Solve the equation (XpowerY/Z!) + (Z/(X!+Z)) with given values of X, Y, Z. X and Z cannot be
negative.
Solution :
#include<stdio.h>
#include<stdlib.h>
int main(){
printf("%ld",power(x,y,z));
return 0;
long int k;
if(y==0)
return 1;
if(y==1)
return x%z;
if(y%2==0){
k=power(x,y/2,z);
k=k%z;
return((k*k)%z);
else{
k=power(x,y/2,z);
k=k%z;
k=(k)%z;
x=x%z;
return((k*k*x)%z);
76.
Batman, Spiderman and Superman are going to start a business. The total investment is
1000M$. Anyone can add new investment to their existing investment. They can transfer
investments between themselves. The program should be in OOP style and should have a
menu for user to do all operations. (Something similar to below example.)
77.
With the starting and ending time of work given find the minimum no of workers needed
Output:
2
Solution:
import java.util.*;
class MinimumNoOfPlatforms{
Arrays.sort(arr);
Arrays.sort(dep);
// needed at a time
int i = 1, j = 0;
plat_needed++;
i++;
result = plat_needed;
}
// Else decrement count of platforms needed
else{
plat_needed--;
j++;
return result;
int n = arr.length;
78.
Find the union intersection of two list and also find except (remove even elements from list1 and
odd elements from list2)
Input
Solution :
#include<stdio.h>
main(){
int arr1[100],arr2[100],i,j,size1,size2,k=0,l=0,arr3[100],temp;
scanf("%d",&size1);
for(i=0;i<size1;i++){
scanf("%d",&arr1[i]);
scanf("%d",&size2);
for(i=0;i<size2;i++){
scanf("%d",&arr2[i]);
for(i=0;i<size2;i++){
for(j=0;j<size1;j++){
if(arr2[i]==arr1[j]){
printf("%d ",arr2[i]);
arr3[k++]=arr1[i];
for(j=0;j<size2;j++){
arr3[k++]=arr2[j];
for(i=0;i<size1+size2;i++){
for(j=i+1;j<size1+size2;j++){
if(arr3[i]<arr3[j]){
temp=arr3[i];
arr3[i]=arr3[j];
arr3[j]=temp;
for(i=0;i<size1+size2;i++){
if(arr3[i]!=arr3[i+1]){
printf("%d ",arr3[i]);
printf("\n...except values...\n");
for(i=0;i<size1;i++){
if((arr1[i]%2)!=0){
printf("%d ",arr1[i]);
}
}
for(j=0;j<size2;j++){
if((arr2[j]%2)==0){
printf("%d ",arr2[j]);
} } }
79.
Solution :
import java.lang.*;
import java.util.*;
class RotateMatrixAllForm{
static int R = 4;
static int C = 4;
// mat[][] of size R x C.
// Initially, m = R and n = C
/*
i - iterator
*/
if (row + 1 == m || col + 1 == n)
break;
curr = mat[row][i];
mat[row][i] = prev;
prev = curr;
row++;
curr = mat[i][n-1];
mat[i][n-1] = prev;
prev = curr;
n--;
curr = mat[m-1][i];
mat[m-1][i] = prev;
prev = curr;
m--;
curr = mat[i][col];
mat[i][col] = prev;
prev = curr;
col++;
System.out.print("\n");
// Test Case 1
{5, 6, 7, 8},
// Tese Case 2
{7, 8, 9}
};*/
rotatematrix(R, C, a);
}}
Solution:
class LargestPrimeNumber{
s.deleteCharAt(i);
s.setCharAt(i, '7');
s.setCharAt(i, '2');
s.setCharAt(i, '5');
else
s.setCharAt(i, '7');
return;
if (!isPrime(s.charAt(i))){
i--;
// like 20
if (i < 0){
i = 0;
decrease(s, i);
// like 7721
else
decrease(s, i);
s.setCharAt(j, '7');
break;
return s.toString();
System.out.println(primeDigits(s));
s = new StringBuilder("1000");
System.out.println(primeDigits(s));
s = new StringBuilder("7721");
System.out.println(primeDigits(s));
s = new StringBuilder("7221");
System.out.println(primeDigits(s));
s = new StringBuilder("74545678912345689748593275897894708927680");
System.out.println(primeDigits(s));