You are on page 1of 118

---------

1. Write a Program to give the following output for the given input:

Solution: -‘

import java.util.Scanner;

public class ExpandString {

public static void main(String[] args){

Scanner in = new Scanner(System.in);

System.out.println("Enter the string: ");

String str = in.nextLine();

for(int j=0; j<str.length(); j++){

char a = str.charAt(j);

int b = ((int)str.charAt(++j)-48);

//System.out.println(a);

if(j+1 >= str.length()){

for(int i=0; i<b; i++)

System.out.print(a);

break;
}

if (((int)str.charAt(j+1)-48)>-1 && ((int)str.charAt(j+1)-48)<10){

b = (b*10) + ((int)str.charAt(++j)-48);

//System.out.println(b);

for(int i=0; i<b; i++)

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{

public static void assign(int a[], int n) {

Vector<Integer> evenArr = new Vector<Integer>();

Vector<Integer> oddArr = new Vector<Integer>();


for (int i = 0; i < n; i++) {

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);

public static void main(String args[]) {

int n, sum = 0;

Scanner s = new Scanner(System.in);

System.out.print("Enter no. of elements you want in array:");

n = s.nextInt();

int a[] = new int[n];

System.out.println("Enter all the elements:");

for(int i = 0; i < n; i++)

a[i] = s.nextInt();

sum = sum + a[i];

}
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 {

public static void pattern(String str,int len){

// i and j are the indexes

// of characters to be

// displayed in the ith

// iteration i = 0 initially

// and go upto length of string

// j = length of string initially

// in each iteration of i,

// we increment i and decrement j,

// we print character only

// of k==i or k==j

for (int i = 0; i < len; i++) {

int j = len - 1 - i;

for (int k = 0; k < len; k++){

if (k == i || k == j)

System.out.print(str.charAt(k));

else

System.out.print(" ");

System.out.println("");

}
public static void main (String[] args){

Scanner s = new Scanner(System.in);

System.out.print("Enter Any String:");

String str = s.nextLine();

int len = str.length();

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{

// Returns true if s1 is substring of s2

public static int isSubstring(String s1, String s2){


int m = s2.length();

int n = s1.length();

/* A loop to slide pat[] one by one */

for (int i = 0; i <= m-n; i++){

int j;

/* For current index i, check for

pattern match */

for (j = 0; j < n; j++)

if (s2.charAt(i + j) != s1.charAt(j))

break;

if (j == n)

return i;

return -1;

public static void main(String args[]){

Scanner s = new Scanner(System.in);

System.out.print("Enter The First String :");

String s1 = s.nextLine();

System.out.print("Enter The Another String to Check:");

String s2 = s.nextLine();

int res = isSubstring(s2, s1);

if (res == -1)
System.out.println(res);

else

System.out.println("Present at index" + res);

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{

private static int[] mergeArraysRemoveDuplicates(int[] arrayA, int[] arrayB){

return IntStream.concat(IntStream.of(arrayA), IntStream.of(arrayB))

.distinct()

.sorted()

.toArray();

public static void main(String[] args){

int[] arrayA = new int[] {7, -5, 3, 8, -4, 11, -19, 21};

int[] arrayB = new int[] {6, 13, -7, 0, 11, -4, 3, -5};

int[] mergedArray = mergeArraysRemoveDuplicates(arrayA, arrayB);

System.out.println("Array A : "+Arrays.toString(arrayA));
System.out.println("Array B : "+Arrays.toString(arrayB));

System.out.println("Sorted Merged Array With No Duplicates : ");

System.out.println(Arrays.toString(mergedArray));

6. Using Recursion reverse the string such as

Solution :

import java.util.regex.Pattern;

public class ReverseString {

// Method to reverse words of a String

static String reverseWords(String str){

// Specifying the pattern to be searched

Pattern pattern = Pattern.compile("\\s");

// splitting String str with a pattern

// (i.e )splitting the string whenever their

// is whitespace and store in temp array.

String[] temp = pattern.split(str);

String result = "";

// Iterate over the temp array and store

// the string in reverse order.

for (int i = 0; i < temp.length; i++) {


if (i == temp.length - 1)

result = temp[i] + result;

else

result = " " + temp[i] + result;

return result;

// Driver methods to test above method

public static void main(String[] args) {

String s1 = "Welcome to geeksforgeeks";

System.out.println(reverseWords(s1));

String s2 = "I love Java Programming";

System.out.println(reverseWords(s2));

7. Print the word with odd letters:

Solution :

import java.util.Scanner;

class CrossPattern {

public static void pattern(String str,int len){


// i and j are the indexes

// of characters to be

// displayed in the ith

// iteration i = 0 initially

// and go upto length of string

// j = length of string initially

// in each iteration of i,

// we increment i and decrement j,

// we print character only

// of k==i or k==j

for (int i = 0; i < len; i++) {

int j = len - 1 - i;

for (int k = 0; k < len; k++){

if (k == i || k == j)

System.out.print(str.charAt(k));

else

System.out.print(" ");

System.out.println("");

public static void main (String[] args){

Scanner s = new Scanner(System.in);

System.out.print("Enter Any String:");


String str = s.nextLine();

int len = str.length();

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.

And print the start and ending index as


Start index : <1,2>
End index: <3, 2>
Solution :

import java.io.*;

import java.util.*;
class SearchString2D{

// Rows and columns in given grid

static int R, C;

// For searching in all 8 direction

static int[] x = { -1, -1, -1, 0, 0, 1, 1, 1 };

static int[] y = { -1, 0, 1, -1, 1, -1, 0, 1 };

// This function searches in all 8-direction from point

// (row, col) in grid[][]

static boolean search2D(char[][] grid, int row,

int col, String word)

// If first character of word doesn't match with

// given starting point in grid.

if (grid[row][col] != word.charAt(0))

return false;

int len = word.length();

// Search word in all 8 directions

// starting from (row,col)

for (int dir = 0; dir < 8; dir++){

// Initialize starting point


// for current direction

int k, rd = row + x[dir], cd = col + y[dir];

// First character is already checked,

// match remaining characters

for (k = 1; k < len; k++){

// If out of bound break

if (rd >= R || rd < 0 || cd >= C || cd < 0)

break;

// If not matched, break

if (grid[rd][cd] != word.charAt(k))

break;

// Moving in particular direction

rd += x[dir];

cd += y[dir];

// If all character matched, then value of must

// be equal to length of word

if (k == len)

return true;

return false;

// Searches given word in a given


// matrix in all 8 directions

public static void patternSearch(char[][] grid, String word){

// Consider every point as starting

// point and search given word

for (int row = 0; row < R; row++) {

for (int col = 0; col < C; col++){

if (search2D(grid, row, col, word))

System.out.println("pattern found at " + row +

", " + col);

public static void main(String args[]){

R = 3;

C = 13;

char[][] grid = {{'G','E','E','K','S','F','O','R','G','E','E','K','S'},

{'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.

11. Given a two dimensional array of string like


Where the first string is “child”, second string is “Father”. And given “ronaldo” we have to find his
no of grandchildren Here “ronaldo” has 2 grandchildren. So our output should be 2.

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{

public static void main(String args[]){

String s1=null;

String s2=null;

Scanner SC=new Scanner(System.in);

System.out.print("Enter string1: ");

s1=SC.nextLine();

System.out.print("Enter string2: ");

s2=SC.nextLine();

//compare strings
if(s1.length()!=s2.length()){

System.out.println("Strings are not same, lengths are different!!!");

return;

boolean flg=true;

for(int i=0; i<s1.length();i++){

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

16. [ [‘Lava’ , ‘kusha] ,


[‘Rama’ , ‘Lava’] ,
[‘Lava ‘,’Ravanan’] ,
[‘Abi’ , ‘Lava’] ]
First string is the child & the second string is the parent. Print the no. of grand children available
for the
given I/P.
I/P: Ravanan
O/P: 2

17. To find the odd numbers in between the range.


Input:
2
15
Output:
3,5,7,9,11,13

Solution:

import java.util.Scanner;

class OddnoRange {

public static void main(String args[]){

Scanner sc = new Scanner(System.in);

System.out.println("Enter Starting Number");

int n = sc.nextInt();

System.out.println("Enter Ending Limit Number");

int r = sc.nextInt();

System.out.print("Odd Numbers from "+n+" to "+r+" are: ");

for (int i = n; i <= r; i++) {

if (i % 2 != 0) {

System.out.print(i + " ");

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{

//each element having its index

// in the input array and number of factors

int index, no_of_fact;

public SortByFactors(int i, int countFactors){

index = i;

no_of_fact = countFactors;

// method to count factors for

// a given number n

static int countFactors(int n){

int count = 0;

int sq = (int)Math.sqrt(n);

// if the number is a perfect square

if (sq * sq == n)

count++;

// count all other factors

for (int i=1; i<Math.sqrt(n); i++){

// if i is a factor then n/i will be

// another factor. So increment by 2

if (n % i == 0)

count += 2;
}

return count;

// function to print numbers after sorting them in

// decreasing order of number of factors

static void printOnBasisOfFactors(int arr[], int n){

SortByFactors num[] = new SortByFactors[n];

// for each element of input array create a

// structure element to store its index and

// factors count

for (int i=0; i<n; i++){

num[i] = new SortByFactors(i,countFactors(arr[i]));

// sort the array of structures as defined

Arrays.sort(num,new Comparator<SortByFactors>() {

@Override

// compare method for the elements

// of the structure

public int compare(SortByFactors e1, SortByFactors e2) {

// if two elements have the same number

// of factors then sort them in increasing

// order of their index in the input array

if (e1.no_of_fact == e2.no_of_fact)

return e1.index < e2.index ? -1 : 1;

// sort in decreasing order of number of factors

return e1.no_of_fact > e2.no_of_fact ? -1 : 1;


}

});

// access index from the structure element and correponding

// to that index access the element from arr

for (int i=0; i<n; i++)

System.out.print(arr[num[i].index]+" ");

public static void main(String[] args){

int arr[] = {5, 11, 10, 20, 9, 16, 23};

printOnBasisOfFactors(arr, arr.length);

19.  To output the number in words (0-999)


Input: 234
Output: Two hundred and Thirty Four

Solution:

import java.util.Scanner;

public class Number2Words{

public static void main(String[] args) {

int number = 0;

Scanner scanner = new Scanner(System.in);

System.out.print("Please type a number between 0 and 999 OR type -1 to exit: ");

number = scanner.nextInt();

while(number!=-1){

if(number>=0 && number<=999){

if(number==0){

System.out.print("NUMBER AFTER CONVERSION:\tZERO");


} else {

System.out.print("NUMBER AFTER CONVERSION:\t");

numberToWord(((number / 100) % 10), " HUNDRED");

numberToWord((number % 100), " ");

} else{

System.out.print("NUMBER OUT OF RANGE");

System.out.print("\nPlease type a number between 0 and 999 OR type -1 to exit: ");

number = scanner.nextInt();

public static void numberToWord(int num, String val) {

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"};

if (num > 19) {

System.out.print(tens[num / 10] + " " + ones[num % 10]);

} else {

System.out.print(ones[num]);

if (num > 0) {

System.out.print(val);

}
}

20.  To find the print the pattern:Ip: n=5


Op:
1
11
21
1211
111221

Solution :

import java.util.Scanner;

public class RowPattern{

public static void main(String[] args){

int i,j,n,k=1;

System.out.print("Input number of rows : ");

Scanner in = new Scanner(System.in);

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{

// Function to print alternate sorted values

static void alternateSort(int arr[], int n){

Arrays.sort(arr);

// Printing the last element of array

// first and then first element and then

// second last element and then second

// element and so on.

int i = 0, j = n-1;

while (i < j) {

System.out.print(arr[j--] + " ");

System.out.print(arr[i++] + " ");

// If the total element in array is odd

// then print the last middle element.

if (n % 2 != 0)
System.out.print(arr[i]);

public static void main (String[] args) {

int arr[] = {1, 12, 4, 6, 7, 10};

int n = arr.length;

alternateSort(arr, n);

23.

Remove unbalanced parentheses in a given expression.

Solution :

import java.util.*;

class InvalidExpressions{

// method checks if character is parenthesis(open

// or closed)

static boolean isParenthesis(char c) {

return ((c == '(') || (c == ')'));

// method returns true if string contains valid

// parenthesis
static boolean isValidString(String str) {

int cnt = 0;

for (int i = 0; i < str.length(); i++) {

if (str.charAt(i) == '(')

cnt++;

else if (str.charAt(i) == ')')

cnt--;

if (cnt < 0)

return false;

return (cnt == 0);

// method to remove invalid parenthesis

static void removeInvalidParenthesis(String str){

if (str.isEmpty())

return;

// visit set to ignore already visited string

HashSet<String> visit = new HashSet<String>();

// queue to maintain BFS

Queue<String> q = new LinkedList<>();

String temp;

boolean level = false;

// pushing given string as

// starting node into queue

q.add(str);
visit.add(str);

while (!q.isEmpty()) {

str = q.peek(); q.remove();

if (isValidString(str)) {

System.out.println(str);

// If answer is found, make level true

// so that valid string of only that level

// are processed.

level = true;

if (level)

continue;

for (int i = 0; i < str.length(); i++) {

if (!isParenthesis(str.charAt(i)))

continue;

// Removing parenthesis from str and

// pushing into queue,if not visited already

temp = str.substring(0, i) + str.substring(i + 1);

if (!visit.contains(temp)) {

q.add(temp);

visit.add(temp);

} }

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("Enter Any String");

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{

// Function to find n'th number in a number system with only 3 and 4

static void find(int n){

// An array of strings to store first n numbers. arr[i] stores i'th number

String[] arr = new String[n+1];

// arr[0] stores the empty string (String with 0 digits)

arr[0] = "";

// size indicates number of current elements in arr[], m indicates

// number of elements added to arr[] in previous iteration

int size = 1, m = 1;

// Every iteration of following loop generates and adds 2*m numbers to

// arr[] using the m numbers generated in previous iteration

while (size <= n){

// Consider all numbers added in previous iteration, add a prefix


// "3" to them and add new numbers to arr[]

for (int i=0; i<m && (size+i)<=n; i++)

arr[size + i] = "3" + arr[size - m + i];

// Add prefix "4" to numbers of previous iteration and add new

// numbers to arr[]

for (int i=0; i<m && (size + m + i)<=n; i++)

arr[size + m + i] = "4" + arr[size - m + i];

// Update no. of elements added in previous iteration

m = m << 1; // Or m = m*2;

// Update size

size = size + m;

System.out.println(arr[n]);

public static void main (String[] args){

for (int i=0; i<16; i++)

find(i);

25.Check whether a given mathematical expression is valid.

Solution:
import java.util.Scanner;

class ExpressionCheck{

// A utility function to check if

// a given character is operand

static boolean isOperand(char c){

return (c >= '0' && c <= '9');

// utility function to find value of and operand

static int value(char c){

return (int)(c - '0');

// This function evaluates simple expressions.

// It returns -1 if the given

// expression is invalid.

static int evaluate(String exp){

// Base Case: Given expression is empty

if (exp.length() == 0) return -1;

// The first character must be

// an operand, find its value

int res = value(exp.charAt(0));

// Traverse the remaining characters in pairs

for (int i = 1; i<exp.length(); i += 2){

// The next character must be an operator, and


// next to next an operand

char opr = exp.charAt(i), opd = exp.charAt(i+1);

// If next to next character is not an operand

if (isOperand(opd) == false) return -1;

// Update result according to the operator

if (opr == '+') res += value(opd);

else if (opr == '-') res -= value(opd);

else if (opr == '*') res *= value(opd);

else if (opr == '/') res /= value(opd);

// If not a valid operator

else

return -1;

return res;

public static void main(String[] args){

Scanner sc = new Scanner(System.in);

System.out.println("Enter Any Mathematical Calculation");

String expr1 =sc.nextLine();

int res = evaluate(expr1);

if(res == -1) System.out.println(expr1+" is Invalid");

else System.out.println("Value of "+expr1+" is "+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{

public static void main(String args[]) throws Exception{

Scanner sc=new Scanner(System.in);

System.out.println("Enter Any Word");

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{

public static void main(String[] args) {

//Initialize array

int [] a = new int [] {1, 2, 8, 3, 2, 2, 2, 5, 1};

//Array fr will store frequencies of element

int [] fr = new int [a.length];

int visited = -1;

for(int i = 0; i < a.length; i++){


int count = 1;

for(int j = i+1; j < a.length; j++){

if(a[i] == a[j]){

count++;

//To avoid counting same element again

fr[j] = visited;

if(fr[i] != visited)

fr[i] = count;

//Displays the frequency of each element present in array

System.out.println("---------------------");

System.out.println(" Element | Frequency");

System.out.println("---------------------");

for(int i = 0; i < fr.length; i++){

if(fr[i] != visited)

System.out.println(" " + a[i] + " | " + fr[i]);

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{

public static void main(String[] args) throws IOException {

Scanner sc = new Scanner(System.in);

System.out.print("Enter The Starting Number");

int a =sc.nextInt();

System.out.print("Enter The Ending Range");

int b = sc.nextInt();

System.out.println("Perfect Numbers between "+a+ " and "+b);

for (int i = a; i <= b; i++) {

int number = i;

int sqrt = (int) Math.sqrt(number);

if (sqrt * sqrt == number) {

System.out.println(+sqrt*sqrt+", ");

29.Alternately sort an unsorted array..

Solution:

import java.util.*;
class AlternateSorting{

// Function to print alternate sorted values

static void alternateSort(int arr[], int n){

Arrays.sort(arr);

// Printing the last element of array

// first and then first element and then

// second last element and then second

// element and so on.

int i = 0, j = n-1;

while (i < j){

System.out.print(arr[j--] + " ");

System.out.print(arr[i++] + " ");

// If the total element in array is odd

// then print the last middle element.

if (n % 2 != 0)

System.out.print(arr[i]);

/* Driver program to test above functions */

public static void main (String[] args){

Scanner sc = new Scanner(System.in);

System.out.println("Enter The Array Size : ");

int a = sc.nextInt();

int[] b=new int[a];

for(int i=0;i<a;i++){
System.out.println("Enter The Value : ");

b[i]=sc.nextInt();

alternateSort(b, a);

30.

Given an array and a threshold value find the o/p

31.

Given two binary numbers add the two numbers in binary form without converting them to
decimal value.

Solution :

public class BinaryAddition{


// This function adds two

// binary strings and return

// result as a third string

static String addBinary(String a, String b){

// Initialize result

String result = "";

// Initialize digit sum

int s = 0;

// Traverse both strings starting

// from last characters

int i = a.length() - 1, j = b.length() - 1;

while (i >= 0 || j >= 0 || s == 1) {

// Comput sum of last

// digits and carry

s += ((i >= 0)? a.charAt(i) - '0': 0);

s += ((j >= 0)? b.charAt(j) - '0': 0);

// If current digit sum is

// 1 or 3, add 1 to result

result = (char)(s % 2 + '0') + result;

// Compute carry

s /= 2;

// Move to next digits

i--; j--;

}
return result;

public static void main(String args[]){

String a = "1101", b="100";

System.out.print(addBinary(a, b));

32.

Write a program to print the below pattern

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>

using namespace std;

int main(int argc, char** argv){

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;

printf("Row and coloumn : ");

scanf("%d %d",&r1,&c1);

printf("Elements to array : ");

for(i=0;i<r1;i++)

for(j=0;j<c1;j++)

scanf("%d",&a[i][j]);

printf("Row and coloumn : ");

scanf("%d %d",&r2,&c2);

printf("Elements to array : ");

for(i=0;i<r2;i++)

for(j=0;j<c2;j++)

scanf("%d",&b[i][j]);

printf("Array A Elements : \n");

for(i=0;i<r1;i++){

for(j=0;j<c1;j++)
printf("%d ",a[i][j]);

printf("\n");

printf("Array B Elements : \n");

for(i=0;i<r2;i++){

for(j=0;j<c2;j++)

printf("%d ",b[i][j]);

printf("\n");

if(r2==c1 && c2==r1){

for(i=c1-1;i>=0;i--)

for(j=0;j<r1;j++)

if(a[j][i]!=b[c1-1-i][j])

goto NEXT1;

printf("\nTRUE (90 Deg)\n");

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;

printf("\nTRUE (180 Deg)\n");

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;

printf("\nTRUE (270 Deg)\n");

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{

// Return sum of two number represented by

// the arrays. Size of a[] is greater than

// b[]. It is made sure be the wrapper

// function
static int calSumUtil(int a[], int b[],int n, int m){

// array to store sum.

int[] sum= new int[n];

int i = n - 1, j = m - 1, k = n - 1;

int carry = 0, s = 0;

// Until we reach beginning of array.

// we are comparing only for second

// array because we have already compare

// the size of array in wrapper function.

while (j >= 0){

// find sum of corresponding element

// of both array.

s = a[i] + b[j] + carry;

sum[k] = (s % 10);

// Finding carry for next sum.

carry = s / 10;

k--;

i--;

j--;

// If second array size is less

// the first array size.

while (i >= 0){

// Add carry to first array elements.


s = a[i] + carry;

sum[k] = (s % 10);

carry = s / 10;

i--;

k--;

int ans = 0;

// If there is carry on adding 0 index

// elements append 1 to total sum.

if (carry == 1)

ans = 10;

// Converting array into number.

for ( i = 0; i <= n - 1; i++) {

ans += sum[i];

ans *= 10;

return ans / 10;

// Wrapper Function

static int calSum(int a[], int b[], int n,int m){

// Making first array which have

// greater number of element

if (n >= m)

return calSumUtil(a, b, n, m);

else
return calSumUtil(b, a, m, n);

public static void main(String[] args){

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.

.Given sorted array check if two numbers sum in it is a given


value
Input
Array = {1 3 4 8 10 } N = 7
output
true

Solution:

import java.io.*;

import java.util.*;

import java.lang.Math;

class CloseSum {

// Prints the pair with sum cloest to x

static void printClosest(int arr[], int n, int x){

int res_l=0, res_r=0; // To store indexes of result pair

// Initialize left and right indexes and difference between

// pair sum and x


int l = 0, r = n-1, diff = Integer.MAX_VALUE;

// While there are elements between l and r

while (r > l){

// Check if this pair is closer than the closest pair so far

if (Math.abs(arr[l] + arr[r] - x) < diff){

res_l = l;

res_r = r;

diff = Math.abs(arr[l] + arr[r] - x);

// If this pair has more sum, move to smaller values.

if (arr[l] + arr[r] > x)

r--;

else // Move to larger values

l++;

System.out.println(" The closest pair is "+arr[res_l]+" and "+ arr[res_r]);

public static void main(String[] args){

int arr[] = {10, 22, 28, 29, 30, 40}, x = 54;

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.

Write function to find multiplication of 2 numbers using +


operator You must use minimum possible iterations.
Input: 3 , 4
Output 12
Solution:

class RecursionAddition{

/* function to multiply two numbers x and y*/

static int multiply(int x, int y) {

/* 0 multiplied with anything gives 0 */

if (y == 0)

return 0;

/* Add x one by one */

if (y > 0)

return (x + multiply(x, y - 1));

/* the case where y is negative */

if (y < 0)

return -multiply(x, -y);

return -1;

code
public static void main(String[] args) {

System.out.print("\n" + multiply(5, -11));

}
}
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{

public static void main (String[] args) {

int [] a = {-2, -3, 4, -1, -2, 1, 5, -3};

System.out.println("Maximum contiguous sum is " + maxSubArraySum(a));

static int maxSubArraySum(int a[]) {

int size = a.length;

int max_so_far = Integer.MIN_VALUE, max_ending_here = 0;

for (int i = 0; i < size; i++) {

max_ending_here = max_ending_here + a[i];

if (max_so_far < max_ending_here)

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;

public class Main

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

int a=sc.nextInt();

int ch[]=new int[a];

int b[]=new int[a];

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;

public class SubSet_sum_problem{

// dp[i][j] is going to store true if sum j is

// possible with array elements from 0 to i.

static boolean[][] dp;

static void display(ArrayList<Integer> v){

System.out.println(v);
}

// A recursive function to print all subsets with the

// help of dp[][]. Vector p[] stores current subset.

static void printSubsetsRec(int arr[], int i, int sum,ArrayList<Integer> p){

// If we reached end and sum is non-zero. We print

// p[] only if arr[0] is equal to sun OR dp[0][sum]

// is true.

if (i == 0 && sum != 0 && dp[0][sum]){

p.add(arr[i]);

display(p);

p.clear();

return;

// If sum becomes 0

if (i == 0 && sum == 0){

display(p);

p.clear();

return;

// If given sum can be achieved after ignoring

// current element.

if (dp[i-1][sum]){

// Create a new vector to store path


ArrayList<Integer> b = new ArrayList<>();

b.addAll(p);

printSubsetsRec(arr, i-1, sum, b);

// If given sum can be achieved after considering

// current element.

if (sum >= arr[i] && dp[i-1][sum-arr[i]]){

p.add(arr[i]);

printSubsetsRec(arr, i-1, sum-arr[i], p);

// Prints all subsets of arr[0..n-1] with sum 0.

static void printAllSubsets(int arr[], int n, int sum){

if (n == 0 || sum < 0)

return;

// Sum 0 can always be achieved with 0 elements

dp = new boolean[n][sum + 1];

for (int i=0; i<n; ++i){

dp[i][0] = true;

// Sum arr[0] can be achieved with single element


if (arr[0] <= sum)

dp[0][arr[0]] = true;

// Fill rest of the entries in dp[][]

for (int i = 1; i < n; ++i)

for (int j = 0; j < sum + 1; ++j)

dp[i][j] = (arr[i] <= j) ? (dp[i-1][j] ||

dp[i-1][j-arr[i]])

: dp[i - 1][j];

if (dp[n-1][sum] == false){

System.out.println("There are no subsets with" +

" sum "+ sum);

return;

// Now recursively traverse dp[][] to find all

// paths from dp[n-1][sum]

ArrayList<Integer> p = new ArrayList<>();

printSubsetsRec(arr, n-1, sum, p);

public static void main(String args[]){

int arr[] = {1, 2, 3, 4, 5};

int n = arr.length;
int sum = 10;

printAllSubsets(arr, n, sum);

}
}
41.

input : aaabbcc
output : abc
Solution:

import java.util.*;

class RemoveDuplicateChar{

static String removeDuplicate(char str[], int n){

// Used as index in the modified string

int index = 0;

// Traverse through all characters

for (int i = 0; i < n; i++){

// Check if str[i] is present before it

int j;

for (j = 0; j < i; j++){

if (str[i] == str[j]) {

break;

// If not present, then add it to


// result.

if (j == i){

str[index++] = str[i];

return String.valueOf(Arrays.copyOf(str, index));

public static void main(String[] args){

char str[] = "geeksforgeeks".toCharArray();

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;

// A Binary Tree node

class Node {

String dataString;

Node left;

Node right;

Node(String dataString) {

this.dataString = dataString;

//Be default left and right child are null.


}

public String getDataString() {

return dataString;

public class ArrayToAllInterpretations {

// Method to create a binary tree which stores all interpretations

// of arr[] in lead nodes

public static Node createTree(int data, String pString, int[] arr) {

// Invalid input as alphabets maps from 1 to 26

if (data > 26)

return null;

// Parent String + String for this node

String dataToStr = pString + alphabet[data];

Node root = new Node(dataToStr);

// if arr.length is 0 means we are done

if (arr.length != 0) {

data = arr[0];

// new array will be from index 1 to end as we are consuming

// first index with this node

int newArr[] = Arrays.copyOfRange(arr, 1, arr.length);

// left child

root.left = createTree(data, dataToStr, newArr);

// right child will be null if size of array is 0 or 1

if (arr.length > 1) {
data = arr[0] * 10 + arr[1];

// new array will be from index 2 to end as we

// are consuming first two index with this node

newArr = Arrays.copyOfRange(arr, 2, arr.length);

root.right = createTree(data, dataToStr, newArr);

return root;

// To print out leaf nodes

public static void printleaf(Node root) {

if (root == null)

return;

if (root.left == null && root.right == null)

System.out.print(root.getDataString() + " ");

printleaf(root.left);

printleaf(root.right);

// The main function that prints all interpretations of array

static void printAllInterpretations(int[] arr){

// Step 1: Create Tree

Node root = createTree(0, "", arr);

// Step 2: Print Leaf nodes

printleaf(root);

System.out.println(); // Print new line


}

// 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",

"s", "t", "u", "v", "w", "x", "v", "z"};

// Driver method to test above methods

public static void main(String args[]) {

// aacd(1,1,3,4) amd(1,13,4) kcd(11,3,4)

// Note : 1,1,34 is not valid as we don't have values corresponding

// to 34 in alphabet

int[] arr = {1, 1, 3, 4};

printAllInterpretations(arr);

// aaa(1,1,1) ak(1,11) ka(11,1)

int[] arr2 = {1, 1, 1};

printAllInterpretations(arr2);

// bf(2,6) z(26)

int[] arr3 = {2, 6};

printAllInterpretations(arr3);

// ab(1,2), l(12)

int[] arr4 = {1, 2};

printAllInterpretations(arr4);

// a(1,0} j(10)

int[] arr5 = {1, 0};

printAllInterpretations(arr5);
// "" empty string output as array is empty

int[] arr6 = {};

printAllInterpretations(arr6);

// abba abu ava lba lu

int[] arr7 = {1, 2, 2, 1};

printAllInterpretations(arr7);

45.

Find the minimum number of times required to represent a number as sum of squares.

Solution:

class MinCountSquares {

// Returns count of minimum squares that sum to n

static int getMinSquares(int n){

// base cases

if (n <= 3)

return n;

// getMinSquares rest of the table using recursive


// formula

int res = n; // Maximum squares required is

// n (1*1 + 1*1 + ..)

// Go through all smaller numbers

// to recursively find minimum

for (int x = 1; x <= n; x++){

int temp = x * x;

if (temp > n)

break;

else

res = Math.min(res, 1 + getMinSquares(n - temp));

return res;

public static void main(String args[]){

System.out.println(getMinSquares(6));

46.In a matrix find the number of rectangles filled with 1s.

Solution:
def findend(i,j,a,output,index):

x = len(a)

y = len(a[0])

# flag to check column edge case,

# initializing with 0

flagc = 0

# flag to check row edge case,

# initializing with 0

flagr = 0

for m in range(i,x):

# loop breaks where first 1 encounters

if a[m][j] == 1:

flagr = 1 # set the flag

break

# pass because already processed

if a[m][j] == 5:

pass

for n in range(j, y):

# loop breaks where first 1 encounters

if a[m][n] == 1:

flagc = 1 # set the flag

break

# fill rectangle elements with any

# number so that we can exclude

# next time
a[m][n] = 5

if flagr == 1:

output[index].append( m-1)

else:

# when end point touch the boundary

output[index].append(m)

if flagc == 1:

output[index].append(n-1)

else:

# when end point touch the boundary

output[index].append(n)

def get_rectangle_coordinates(a):

# retrieving the column size of array

size_of_array = len(a)

# output array where we are going

# to store our output

output = []

# It will be used for storing start

# and end location in the same index

index = -1

for i in range(0,size_of_array):

for j in range(0, len(a[0])):

if a[i][j] == 0:

# storing initial position


# of rectangle

output.append([i, j])

# will be used for the

# last position

index = index + 1

findend(i, j, a, output, index)

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.

 Find the frequency of all numbers in an array.


Note: use dynamic memory allocation.
For example, if the input is {1, 2, 45, 67, 1, 88}, do not calculate the frequency of all
elements from 1 to 88.
Solution:

import java.io.*;

import java.util.*;

class FrequencyCheckArray{

static HashMap <Integer, Integer> hm = new HashMap<Integer, Integer>();

static void countFreq(int a[], int n){

// Insert elements and their

// frequencies in hash map.

for (int i=0; i<n; i++)

if (hm.containsKey(a[i]) )

hm.put(a[i], hm.get(a[i]) + 1);

else hm.put(a[i] , 1);

// Return frequency of x (Assumes that

// countFreq() is called before)

static int query(int x){

if (hm.containsKey(x))

return hm.get(x);

return 0;

public static void main (String[] args) {

int a[] = {1, 3, 2, 4, 2, 1};

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.

Input: he knows malayalam


Output: he knows
Solution:

class RemovePalindromeString{

// function to check if 'str' is palindrome

static boolean isPalindrome(String str){

int i = 0, j = str.length() - 1;

// traversing from both the ends

while (i < j){

// not palindrome

if (str.charAt(i++) != str.charAt(j--))

return false;

// palindrome

return true;

}
// function to remove all the palindromic words

// from the given sentence

static String removePalinWords(String str){

// 'final_str' to store the final string and

// 'word' to one by one store each word of 'str'

String final_str = "", word = "";

// add space at the end of 'str'

str = str + " ";

int n = str.length();

// traversing 'str'

for (int i = 0; i < n; i++){

// accumulating characters of the current word

if (str.charAt(i) != ' ')

word = word + str.charAt(i);

else{

// if 'word' is not palindrome then a

// add it to 'final_str'

if (!(isPalindrome(word)))

final_str += word + " ";

// reset

word = "";

}
// required final string

return final_str;

// Driver code

public static void main (String[] args){

String str = "Text contains malayalam and level words";

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:

public class ReverseAddPalindrome{

/* Iterative function to reverse digits of num*/

long reversDigits(long num){

long rev_num = 0;

while (num > 0){

rev_num = rev_num*10 + num%10;

num = num/10;

}
return rev_num;

/* Function to check whether he number is

palindrome or not */

boolean isPalindrome(long num){

return (reversDigits(num) == num);

/* Reverse and Add Function */

void ReverseandAdd(long num){

long rev_num = 0;

while (num <= 4294967295l){

// Reversing the digits of the number

rev_num = reversDigits(num);

// Adding the reversed number with the original

num = num + rev_num;

// Checking whether the number is palindrome or not

if(isPalindrome(num)){

System.out.println(num);

break;

else if (num > 4294967295l){

System.out.println("No palindrome exist");

}
}

public static void main(String[] args){

ReverseAddPalindrome ob = new ReverseAddPalindrome();

ob.ReverseandAdd(195l);

ob.ReverseandAdd(265l);

}
}
Another:

import java.util.*;

public class Main

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

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

static boolean isVowel(char c) {

return (c == 'a' || c == 'A' || c == 'e'

|| c == 'E' || c == 'i' || c == 'I'

|| c == 'o' || c == 'O' || c == 'u'

|| c == 'U');

// Function to reverse order of vowels

static String reverseVowel(String str1) {

int j = 0;

// Storing the vowels separately

char[] str = str1.toCharArray();

String vowel = "";

for (int i = 0; i < str.length; i++) {

if (isVowel(str[i])) {

j++;

vowel += str[i];

// Placing the vowels in the reverse

// order in the string

for (int i = 0; i < str.length; i++) {

if (isVowel(str[i])) {
str[i] = vowel.charAt(--j);

return String.valueOf(str);

public static void main(String[] args) {

String str = "hello world";

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.

 Print longest sequence between same character


Input: abcccccbba
Output: 8 (from a to a)
Input: aaaaaaaa
Output: 6
Solution:

class MaxCharString{

static int maximumChars(String str){

int n = str.length();

int res = -1;

for (int i = 0; i < n - 1; i++)

for (int j = i + 1; j < n; j++)

if (str.charAt(i) == str.charAt(j))

res = Math.max(res,
Math.abs(j - i - 1));

return res;

public static void main(String[] args){

String str = "abba";

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;

public class SortOddEven{

// To do two way sort. First sort even numbers in

// ascending order, then odd numbers in descending

// order.

static void twoWaySort(Integer arr[], int n){

// Current indexes from left and right

int l = 0, r = n - 1;

// Count of odd numbers


int k = 0;

while (l < r) {

// Find first odd number from left side.

while (arr[l] % 2 != 0) {

l++;

k++;

// Find first even number from right side.

while (arr[r] % 2 == 0 && l < r)

r--;

// Swap odd number present on left and even

// number right.

if (l < r) {

// swap arr[l] arr[r]

int temp = arr[l];

arr[l] = arr[r];

arr[r] = temp;

// Sort odd number in descending order

Arrays.sort(arr, 0, k, Collections.reverseOrder());

// Sort even number in ascending order

Arrays.sort(arr, k, n);
}

public static void main(String[] args){

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;

public class Main

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

int a=sc.nextInt();

int i,j;

int b[]=new int[a];

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 :

public class SumArrayEqual{

// Finds an element in an array such that

// left and right side sums are equal

static int findElement(int arr[], int n){

// Forming prefix sum array from 0

int[] prefixSum = new int[n];

prefixSum[0] = arr[0];

for (int i = 1; i < n; i++)


prefixSum[i] = prefixSum[i - 1] + arr[i];

// Forming suffix sum array from n-1

int[] suffixSum = new int[n];

suffixSum[n - 1] = arr[n - 1];

for (int i = n - 2; i >= 0; i--)

suffixSum[i] = suffixSum[i + 1] + arr[i];

// Find the point where prefix and suffix

// sums are same.

for (int i = 1; i < n - 1; i++)

if (prefixSum[i] == suffixSum[i])

return arr[i];

return -1;

public static void main(String args[]){

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  

 Output: 2 5 9You should solve this question in O(n) time.

Solution:

import java.io.*;

import java.util.*;

import java.lang.*;

class PreviousGreatest{

static void prevGreater(int arr[],int n){

// Previous greater for

// first element never

// exists, so we print -1.

System.out.print("-1, ");

// Let us process

// remaining elements.

for (int i = 1; i < n; i++){

// Find first element on

// left side that is

// greater than arr[i].

int j;

for (j = i-1; j >= 0; j--){

if (arr[i] < arr[j]){

System.out.print(arr[j] + ", ");

break;

}
if (j == -1)

System.out.print("-1, ");

public static void main(String[] args){

int arr[] = {10, 4, 2, 20, 40, 12, 30};

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:

public class SumOfDigits{

static int totalDigits(int n){

// number_of_digits store total

// digits we have to write

int number_of_digits = 0;
// In the loop we are decreasing

// 0, 9, 99 ... from n till

// ( n - i + 1 ) is greater than 0

// and sum them to number_of_digits

// to get the required sum

for (int i = 1; i <= n; i *= 10)

number_of_digits += (n - i + 1);

return number_of_digits;

public static void main(String[] args){

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{

public static void psuedoBinary(int n){

// Repeat below steps until n > 0

while (n != 0){
// calculate m (A number that has same

// number of digits as n, but has 1 in

// place of non-zero digits 0 in place

// of 0 digits)

int temp = n, m = 0, p = 1;

while(temp != 0){

int rem = temp % 10;

temp = temp / 10;

if (rem != 0)

m += p;

p *= 10;

System.out.print(m + " ");

// subtract m from n

n = n - m;

System.out.println(" ");

public static void main(String[] args){

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:

public class ReverseStringPreserveSpace{

// Function to reverse the string

// and preserve the space position

static void reverses(String str) {

char[] inputArray = str.toCharArray();

char[] result = new char[inputArray.length];

// Mark spaces in result

for (int i = 0; i < inputArray.length; i++) {

if (inputArray[i] == ' ') {

result[i] = ' ';

// Traverse input string from beginning

// and put characters in result from end

int j = result.length - 1;

for (int i = 0; i < inputArray.length; i++) {

// Ignore spaces in input string

if (inputArray[i] != ' ') {

// ignore spaces in result.

if (result[j] == ' ') {

j--;

result[j] = inputArray[i];

j--;
}

System.out.println(String.valueOf(result));

public static void main(String[] args){

reverses("internship at geeks for geeks");

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:

public class RemoveDuplicates{

static final int NO_OF_CHARS = 256;

/* Returns an array of size 256 containg count

of characters in the passed char array */

static int[] getCharCountArray(String str){

int count[] = new int[NO_OF_CHARS];

for (int i = 0; i<str.length(); i++)

count[str.charAt(i)]++;

return count;

/* removeDirtyChars takes two string as arguments: First

string (str) is the one from where function removes dirty

characters. Second string is the string which contain all


dirty characters which need to be removed from first string */

static String removeDirtyChars(String str, String mask_str){

int count[] = getCharCountArray(mask_str);

int ip_ind = 0, res_ind = 0;

char arr[] = str.toCharArray();

while (ip_ind != arr.length){

char temp = arr[ip_ind];

if(count[temp] == 0){

arr[res_ind] = arr[ip_ind];

res_ind ++;

ip_ind++;

str = new String(arr);

/* After above step string is ngring.

Removing extra "iittg" after string*/

return str.substring(0, res_ind);

public static void main(String[] args){

String str = "geeksforgeeks";

String mask_str = "mask";

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{

/* prints element and NGE pair for

all elements of arr[] of size n */

static void printNGE(int arr[], int n){

int next, i, j;

for (i=0; i<n; i++){

next = -1;

for (j = i+1; j<n; j++){

if (arr[i] < arr[j]){

next = arr[j];

break;

System.out.println(arr[i]+" -- "+next);

}}

public static void main(String args[]){

int arr[]= {11, 13, 21, 3};

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.*;

// User defined Pair class

class Pair {

int first, second;

class TopRepeatedElement {

// Function to print top three repeated numbers

static void top3Repeated(int[] arr, int n){

// There should be atleast two elements

if (n < 3){

System.out.print("Invalid Input");

return;

// Count Frequency of each element

TreeMap<Integer, Integer> freq = new TreeMap<>();

for (int i = 0; i < n; i++)

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

// of Pair type is INT_MIN

Pair x = new Pair();

Pair y = new Pair();

Pair z = new Pair();

x.first = y.first = z.first = Integer.MIN_VALUE;

for (Map.Entry curr : freq.entrySet()) {

// If frequency of current element

// is not zero and greater than

// frequency of first largest element

if (Integer.parseInt(String.valueOf(curr.getValue())) > x.first) {

// Update second and third largest

z.first = y.first;

z.second = y.second;

y.first = x.first;

y.second = x.second;

// Modify values of x Number

x.first = Integer.parseInt(String.valueOf(curr.getValue()));

x.second = Integer.parseInt(String.valueOf(curr.getKey()));

// If frequency of current element is

// not zero and frequency of current

// element is less than frequency of

// first largest element, but greater

// than y element
else if (Integer.parseInt(String.valueOf(curr.getValue())) > y.first) {

// Modify values of third largest

z.first = y.first;

z.second = y.second;

// Modify values of second largest

y.first = Integer.parseInt(String.valueOf(curr.getValue()));

y.second = Integer.parseInt(String.valueOf(curr.getKey()));

// If frequency of current element

// is not zero and frequency of

// current element is less than

// frequency of first element and

// second largest, but greater than

// third largest.

else if (Integer.parseInt(String.valueOf(curr.getValue())) > z.first) {

// Modify values of z Number

z.first = Integer.parseInt(String.valueOf(curr.getValue()));

z.second = Integer.parseInt(String.valueOf(curr.getKey()));

System.out.print("Three largest elements are " + x.second + " "

+ y.second + " " + z.second);

public static void main(String args[]){

int[] arr = { 3, 4, 2, 3, 16, 3, 15,

16, 15, 15, 16, 2, 3 };


int n = arr.length;

top3Repeated(arr, n);

66.

Given a number, convert it into corresponding alphabet.

Solution:

class NumberToChar{

public static String getCharForNumber(int i){

// return null for bad input

if(i < 0){

return null;

// convert to base 26

String s = Integer.toString(i, 26);

char[] characters = s.toCharArray();

String result = "";

for(char c : characters){

// convert the base 26 character back to a base 10 integer

int x = Integer.parseInt(Character.valueOf(c).toString(), 26);

// append the ASCII value to the result


result += String.valueOf((char)(x + 'A'));

return result;

public static void main(String args[]){

System.out.println("The Converted Char ==> "+getCharForNumber(0));

67.Given a Roman numeral, find its corresponding decimal value.

Solution :

import java.util.*;

public class RomanToNumber{

// This function returns value of a Roman symbol

int value(char r){

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;

// Finds decimal value of a given romal numeral

int romanToDecimal(String str){

// Initialize result

int res = 0;

for (int i=0; i<str.length(); i++){

// Getting value of symbol s[i]

int s1 = value(str.charAt(i));

// Getting value of symbol s[i+1]

if (i+1 <str.length()){

int s2 = value(str.charAt(i+1));

// Comparing both values

if (s1 >= s2){

// Value of current symbol is greater

// or equalto the next symbol

res = res + s1;

else{

res = res + s2 - s1;

i++; // Value of current symbol is

// less than the next symbol


}

else{

res = res + s1;

i++;

return res;

public static void main(String args[]){

RomanToNumber ob = new RomanToNumber();

// Considering inputs given are valid

String str = "MCMIV";

System.out.println("Integer form of Roman Numeral is " + ob.romanToDecimal(str));

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:

public class Permutation{


public static void main(String[] args){

String str = "ABC";

int n = str.length();

Permutation permutation = new Permutation();

permutation.permute(str, 0, n-1);

private void permute(String str, int l, int r){

if (l == r)

System.out.println(str);

else{

for (int i = l; i <= r; i++){

str = swap(str,l,i);

permute(str, l+1, r);

str = swap(str,l,i);

public String swap(String a, int i, int j){

char temp;

char[] charArray = a.toCharArray();

temp = charArray[i] ;

charArray[i] = charArray[j];

charArray[j] = temp;

return String.valueOf(charArray);

}
}

69.Write a program to rotate an n*n matrix 90,180,270,360 degree.


is the solution for rotating a matrix 90 degree. For rotating the matrix 180,270,360 degree, u
need to call the same method 2,3,4 times based on the input.

Solution:

import java.util.*;

class RotateMatrix {

// After transpose we swap elements of

// column one by one for finding left

// rotation of matrix by 90 degree

static void reverseColumns(int arr[][]){

for (int i = 0; i < arr[0].length; i++)

for (int j = 0, k = arr[0].length - 1;j < k;j++,k--){

int temp = arr[j][i];

arr[j][i] = arr[k][i];

arr[k][i] = temp;

static void transpose(int arr[][]){

for (int i = 0; i < arr.length; i++)

for (int j = i; j < arr[0].length; j++) {

int temp = arr[j][i];

arr[j][i] = arr[i][j];

arr[i][j] = temp;

}
}

// Function for print matrix

static void printMatrix(int arr[][]){

for (int i = 0; i < arr.length; i++) {

for (int j = 0; j < arr[0].length; j++)

System.out.print(arr[i][j] + " ");

System.out.println("");

// Function to anticlockwise rotate

// matrix by 90 degree

static void rotate90(int arr[][]){

transpose(arr);

reverseColumns(arr);

public static void main(String[] args){

int arr[][] = { { 1, 2, 3, 4 },

{ 5, 6, 7, 8 },

{ 9, 10, 11, 12 },

{ 13, 14, 15, 16 } };

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();

printf("enter the number:");

gets(a); //get the input as a string

i=strlen(a); //length of string

while(a[j]!='\0'){

b[j]=a[j]-48; //stores converted value into integer array

j++;

for(k=0;k<3;k++){ //check three possibilities

if(k==0){ //checks with first element

c[0]=b[0];

m=1,n=0;
}

else if(k==2){ //checks with addition of first and second element

c[0]=b[0]+b[1];

m=2,n=0;

else{ //checks with subtraction of first and second element

c[0]=b[0]-b[1];

m=2,n=0;

check: //check is the label

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

printf("\nGiven number is monodigit:");

for(j=0;j<n+1;j++)

printf("%d",c[j]);

if(l==3) //prints when three possibilities fails

printf("It is not monodigit");


}

getch();

71.

Solve the equation X power Y with given values.

72.

Find the distance between two given points and round it to the nearest number.

Solution:

class DistanceBetweenNumbers{

// Function to calculate distance

static double distance(int x1, int y1, int x2, int y2){

// Calculating distance

return Math.sqrt(Math.pow(x2 - x1, 2) +

Math.pow(y2 - y1, 2) * 1.0);

public static void main (String[] args){

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.

Given a 2D matrix, find the sum of all the elements.

Solution :

import java.io.*;

class SumOfMatrixArray{

// Get the size m and n

static int m = 4;

static int n = 4;

// Function to calculate sum of each row

static void row_sum(int arr[][]){

int i,j,sum = 0;

System.out.print( "\nFinding Sum of each row:\n\n");

// finding the row sum

for (i = 0; i < 4; ++i) {


for (j = 0; j < 4; ++j) {

// Add the element

sum = sum + arr[i][j];

// Print the row sum

System.out.println( "Sum of the row "+ i +" = "+sum);

// Reset the sum

sum = 0;

static void column_sum(int arr[][]){

int i,j,sum = 0;

System.out.print( "\nFinding Sum of each column:\n\n");

// finding the column sum

for (i = 0; i < 4; ++i) {

for (j = 0; j < 4; ++j) {

// Add the element

sum = sum + arr[j][i];

// Print the column sum

System.out.println("Sum of the column "+ i + " = " + sum);

// Reset the sum

sum = 0;

}
public static void main (String[] args) {

int i,j;

int [][]arr = new int[m][n];

// Get the matrix elements

int x = 1;

for (i = 0; i < m; i++)

for (j = 0; j < n; j++)

arr[i][j] = x++;

// Get each row sum

row_sum(arr);

// Get each column sum

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>

long int power(long int x,long int y,long int z);

int main(){

long int x=2;

long int y=10;


long int z=200000;

printf("%ld",power(x,y,z));

return 0;

long int power(long int x,long int y,long int z){

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{

// Returns minimum number of platforms reqquired

static int findPlatform(int arr[], int dep[], int n){

// Sort arrival and departure arrays

Arrays.sort(arr);

Arrays.sort(dep);

// plat_needed indicates number of platforms

// needed at a time

int plat_needed = 1, result = 1;

int i = 1, j = 0;

// Similar to merge in merge sort to process

// all events in sorted order

while (i < n && j < n){

// If next event in sorted order is arrival,

// increment count of platforms needed

if (arr[i] <= dep[j]){

plat_needed++;

i++;

// Update result if needed

if (plat_needed > result)

result = plat_needed;

}
// Else decrement count of platforms needed

else{

plat_needed--;

j++;

return result;

// Driver program to test methods of graph class

public static void main(String[] args){

int arr[] = {900, 940, 950, 1100, 1500, 1800};

int dep[] = {910, 1200, 1120, 1130, 1900, 2000};

int n = arr.length;

System.out.println("Minimum Number of Platforms Required = "

+ findPlatform(arr, dep, n));

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;

printf("enter the first array size : ");

scanf("%d",&size1);

printf("enter the first array values : \n");

for(i=0;i<size1;i++){

scanf("%d",&arr1[i]);

printf("enter the second array size : ");

scanf("%d",&size2);

printf("enter the second array values : \n");

for(i=0;i<size2;i++){

scanf("%d",&arr2[i]);

printf("...intersection of the array....\n");

for(i=0;i<size2;i++){

for(j=0;j<size1;j++){

if(arr2[i]==arr1[j]){

printf("%d ",arr2[i]);

printf("\n...union of the array...\n");


for(i=0;i<size1;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.

Rotate the matrix elements

Solution :

import java.lang.*;

import java.util.*;

class RotateMatrixAllForm{
static int R = 4;

static int C = 4;

// A function to rotate a matrix

// mat[][] of size R x C.

// Initially, m = R and n = C

static void rotatematrix(int m,int n, int mat[][]){

int row = 0, col = 0;

int prev, curr;

/*

row - Staring row index

m - ending row index

col - starting column index

n - ending column index

i - iterator

*/

while (row < m && col < n){

if (row + 1 == m || col + 1 == n)

break;

// Store the first element of next

// row, this element will replace

// first element of current row

prev = mat[row + 1][col];

// Move elements of first row

// from the remaining rows


for (int i = col; i < n; i++){

curr = mat[row][i];

mat[row][i] = prev;

prev = curr;

row++;

// Move elements of last column

// from the remaining columns

for (int i = row; i < m; i++){

curr = mat[i][n-1];

mat[i][n-1] = prev;

prev = curr;

n--;

// Move elements of last row

// from the remaining rows

if (row < m){

for (int i = n-1; i >= col; i--){

curr = mat[m-1][i];

mat[m-1][i] = prev;

prev = curr;

m--;

// Move elements of first column


// from the remaining rows

if (col < n){

for (int i = m-1; i >= row; i--){

curr = mat[i][col];

mat[i][col] = prev;

prev = curr;

col++;

for (int i = 0; i < R; i++){

for (int j = 0; j < C; j++)

System.out.print( mat[i][j] + " ");

System.out.print("\n");

public static void main(String[] args){

// Test Case 1

int a[][] = { {1, 2, 3, 4},

{5, 6, 7, 8},

{9, 10, 11, 12},

{13, 14, 15, 16} };

// Tese Case 2

/* int a[][] = new int {{1, 2, 3},


{4, 5, 6},

{7, 8, 9}

};*/

rotatematrix(R, C, a);

}}

80.Find the largest possible prime number with given no


Input
5
4691
Output:
9461

Solution:

class LargestPrimeNumber{

// check if character is prime

public static boolean isPrime(char c){

return (c == '2' || c == '3' || c == '5' || c == '7');

// replace with previous prime character

public static void decrease(StringBuilder s, int i){

if (s.charAt(i) <= '2'){

// if 2 erase s[i] and replace next with 7

s.deleteCharAt(i);

s.setCharAt(i, '7');

else if (s.charAt(i) == '3')

s.setCharAt(i, '2');

else if (s.charAt(i) <= '5')


s.setCharAt(i, '3');

else if (s.charAt(i) <= '7')

s.setCharAt(i, '5');

else

s.setCharAt(i, '7');

return;

public static String primeDigits(StringBuilder s){

for (int i = 0; i < s.length(); i++){

// find first non prime char

if (!isPrime(s.charAt(i))){

// find first char greater than 2

while (i >= 0 && s.charAt(i) <= '2')

i--;

// like 20

if (i < 0){

i = 0;

decrease(s, i);

// like 7721

else

decrease(s, i);

// replace remaining with 7

for (int j = i + 1; j < s.length(); j++)

s.setCharAt(j, '7');
break;

return s.toString();

public static void main(String[] args){

StringBuilder s = new StringBuilder("45");

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));

You might also like