Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
67 views

Check Whether The Number Is Prime or No:: Print First Non Repeating Character From The String

The document contains code snippets and examples for several problems related to checking primality of numbers, finding the first non-repeating character in a string, printing prime numbers within a range, calculating niceness values of strings, and finding the first repeating character in a string. The problems are solved using techniques like checking for divisibility, counting character frequencies, and lexicographical string comparisons. Sample inputs and outputs are provided for testing the code snippets.

Uploaded by

Charitha Iddum
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

Check Whether The Number Is Prime or No:: Print First Non Repeating Character From The String

The document contains code snippets and examples for several problems related to checking primality of numbers, finding the first non-repeating character in a string, printing prime numbers within a range, calculating niceness values of strings, and finding the first repeating character in a string. The problems are solved using techniques like checking for divisibility, counting character frequencies, and lexicographical string comparisons. Sample inputs and outputs are provided for testing the code snippets.

Uploaded by

Charitha Iddum
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Check whether the number is prime or no:

import java.util.*;
class Test1
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int cnt=0;
for(int i=1;i<=a;i++)
{
if(a%i==0)
{
cnt++;
}
}
if(cnt==2)
{
System.out.println("Prime");
}
else
{
System.out.println("Not Prime");
}
}
}
Ip=3
Op=prime

Print first non repeating character from the string:


import java.util.*;
class Sri
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
char cnt[]=new char[256];
for (int i = 0; i < s.length(); i++)
{
cnt[s.charAt(i)]++;
}
int index = -1, i;
for (i = 0; i < s.length(); i++)
{
if (cnt[s.charAt(i)] == 1)
{
index = i;
break;
}
}
System.out.println(
index == -1
? "Either all characters are repeating or string "
+ "is empty"
: "First non-repeating character is "
+ s.charAt(index));
}
}
Ip= aaabcccdeeef
Op= First non repeating character is: b
(or)
Ip= aaabbbcccddd
Op= Either all characters are repeating or string is empty.

Print out the prime number series upto n number:


import java.util.*;
class Test2
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int cnt=0;
for(int i=1;i<=a;i++)
{
for(int j=1;j<=a;j++)
{
if(i%j==0)
{
cnt++;
}
}
if(cnt==2)
{
System.out.print(i + " " );
}
cnt=0;
}

}
}
(or)
import java.util.*;
class Test7
{
public static void main(String args[])
{
ArrayList<Integer> d = new ArrayList<Integer>();
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int cnt=0;
for(int i=1;i<=a;i++)
{
for(int j=1;j<=a;j++)
{
if(i%j==0)
{
cnt++;
}
}
if(cnt==2)
{
d.add(i);
}
cnt=0;
}
for(int i=0;i<d.size();i++)
{
System.out.println(d.get(i));
}
}
}
Ip=10
Op=2 3 5 7

Monk and Nice Strings:


Monk's best friend Micro's birthday is coming up. Micro likes Nice Strings very much, so Monk decided to gift him one.
Monk is having N nice strings, so he'll choose one from those. But before he selects one, he needs to know the Niceness
value of all of those. Strings are arranged in an array A, and the Niceness value of string at position i is defined as the
number of strings having position less than i which are lexicographically smaller than A[i]. Since nowadays, Monk is very
busy with the Code Monk Series, he asked for your help.
Note: Array's index starts from 1.

Input:
First line consists of a single integer denoting N.
N lines follow each containing a string made of lower case English alphabets.

Output:
Print N lines, each containing an integer, where the integer in ith line denotes Niceness value of string A[i].
Constraints:
1≤N≤1000
1≤|A[i]|≤10 ∀ i where 1≤i≤N, where |A[i]| denotes the length of ith string.
Sample Input
4
a
c
d
b
Sample Output
0
1
2
1
Explanation

Number of strings having index less than 1 which are less than "a" = 0
Number of strings having index less than 2 which are less than "c": ("a") = 1
Number of strings having index less than 3 which are less than "d": ("a", "c") = 2
Number of strings having index less than 4 which are less than "b": ("a") = 1

import java.util.*;

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

Scanner in = new Scanner(System.in);

        int N = Integer.parseInt(in.nextLine());
        String str[] = new String[N];

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


            str[i] = in.nextLine();

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


        {
            int niceness = 0;

            for(int j=0;j<i;j++)
            {
                if(str[j].compareTo(str[i]) < 0)
                    niceness++;
            }

            System.out.println(niceness);
        }

}
}

Print the prime number series present in between 2 values:


import java.util.*;
class Test3
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int x=sc.nextInt();
int a=sc.nextInt();
int cnt=0;
for(int i=x;i<=a;i++)
{
for(int j=1;j<=i;j++)
{
if(i%j==0)
{
cnt++;
}
}
if(cnt==2)
{
System.out.print(i + " " );
}
cnt=0;
}

}
}
Ip=10
20
Op=11 13 17 19

Print first repeating character from the string:


import java.util.*;
class Sri
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
char cnt[]=new char[256];
for (int i = 0; i < s.length(); i++)
{
cnt[s.charAt(i)]++;
}
int index = -1, i;
for (i = 0; i < s.length(); i++)
{
if (cnt[s.charAt(i)] > 1)
{
index = i;
break;
}
}
System.out.println(
index == -1
? "Either all characters are unique or string "
+ "is empty"
: "First repeating character is "
+ s.charAt(index));
}
}
Ip= abcdeeefghiii
Op= First repeating character is: e

Print Prime numbers in the list form:


import java.util.*;
class Test4
{
public static void main(String args[])
{
ArrayList<Integer> d = new ArrayList<Integer>();
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int cnt=0;
for(int i=1;i<=a;i++)
{
for(int j=1;j<=a;j++)
{
if(i%j==0)
{
cnt++;
}
}
if(cnt==2)
{
d.add(i);
}
cnt=0;
}
System.out.println(d);
}
}
(or)
import java.util.*;
class Test7
{
public static void main(String args[])
{
ArrayList<Integer> d = new ArrayList<Integer>();
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int cnt=0;
for(int i=1;i<=a;i++)
{
for(int j=1;j<=a;j++)
{
if(i%j==0)
{
cnt++;
}
}
if(cnt==2)
{
d.add(i);
}
cnt=0;
}
System.out.print(d.toString()); //output will be in the form of string format.
}
}
Ip=10
Op=[2,3,5,7]

Monk and Suffix Sort


Monk loves to play games. On his birthday, his friend gifted him a string S. Monk and his friend started playing a new
game called as Suffix Game. In Suffix Game, Monk's friend will ask him lexicographically kth smallest suffix of the string S.
Monk wants to eat the cake first so he asked you to play the game.
Input Format:
First line contains a string S (1≤|S|≤25) and an integer k (1≤k≤|S|).
Output Format:
Print the lexicographically kth smallest suffix of the string S.

Sample Input
aacb 3
Sample Output
b
Explanation

All the suffices of the string are:


aacb
acb
cb
b
After sorting the order of the suffices will be:
aacb
acb
b
cb

3rd smallest suffix will be b.

import java.io.*;
import java.util.*;

public class Solution {

public static BufferedReader br;

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


br = new BufferedReader(new InputStreamReader(System.in));
String[] s = br.readLine().split("\\s");
String input = s[0];
int N = Integer.parseInt(s[1]);
List<String> list = new ArrayList<>();
for (int i = 0; i < input.length(); i++) {
list.add(input.substring(i));
}
Collections.sort(list);
System.out.println(list.get(N - 1));
}
}

Print alternate prime numbers up to n number:


import java.util.*;
public class Test5
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
Alternate(n);
}
static int checkPrime(int n)
{
int cnt=0;
for(int i = 1; i<= n ; i++)
{
if(n % i == 0)
{
cnt++;
}
}
if(cnt==2)
return 1;
else
return 0;
}
static void Alternate(int n)
{
int temp = 2;
for(int i = 2; i <= n; i++)
{
if (checkPrime(i) == 1)
{
if (temp % 2 == 0)
System.out.print(i + " ");
temp ++;
}
}
}
}
(or)
import java.util.*;
class Test6
{
public static void main(String args[])
{
ArrayList<Integer> d = new ArrayList<Integer>();
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int cnt=0;
for(int i=1;i<=a;i++)
{
for(int j=1;j<=a;j++)
{
if(i%j==0)
{
cnt++;
}
}
if(cnt==2)
{
d.add(i);
}
cnt=0;
}
for(int i=0;i<d.size();i++)
{
if(i%2==0)
{
System.out.print(d.get(i) + " ");
}
}
}
}
Ip=20
Op=2 5 11 17

Monk being monitor:


Monk being the monitor of the class needs to have all the information about the class students. He is very busy
with many tasks related to the same, so he asked his friend Mishki for her help in one task. She will be given
heights of all the students present in the class and she needs to choose 2 students having
heights h1 and h2 respectively, such that h1>h2 and difference between the number of students having
height h1 and number of students having height h2 is maximum.

Note: The difference should be greater than 0.


As Mishki has never been a monitor of the class, help her in the same. If there exists such students, then print
the required difference else print "1" (without quotes).

Input:
The first line will consists of one integer T, which denotes the number of test cases.
For each test case:
One line consists of a integer N, denotes the number of students in the class.
Second line contains N space separated integers, where ith integer denotes the height of the ith student in the
class.

Output:

For each test case, if the required difference exists then print its value, otherwise print 1. Print the answer for
each test case in a new line.

Constraints:
1≤T≤10
1≤N≤105
1≤height of the student≤106
Sample Input
1
6
3 1 3 2 3 2
Sample Output
2
Explanation

Here T=1 and N = 6.

Number of students having height = 3 is 3.


Number of students having height = 2 is 2.
Number of students having height = 1 is 1.

Here Mishki can choose students with height=3 (h1) and height = 1 (h2) , as the difference between number of
students having height (h1) and number of students having height (h2) is maximum and greater than 0.

import java.util.*;

public class MonkBeingMonitor {

    public static void main(String[] args) {

        try (Scanner s = new Scanner(System.in)) {


            int testSize = s.nextInt();
            for (int i = 0; i < testSize; i++) {
                Map<Integer, Integer> hsm = new HashMap<Integer, Integer>();
                int classSize = s.nextInt();
                for (int j = 0; j < classSize; j++) {
                    Integer h = s.nextInt();
                    if (hsm.containsKey(h)) {
                        hsm.put(h, hsm.get(h) + 1);
                    } else {
                        hsm.put(h, 1);
                    }
                }
//              System.out.println(hsm);
                Integer min = Collections.min(hsm.entrySet(),
Comparator.comparingInt(Map.Entry::getValue)).getValue();
                Integer max = Collections.max(hsm.entrySet(),
Comparator.comparingInt(Map.Entry::getValue)).getValue();
                int diff = max - min;
                if (diff > 0)
                    System.out.println(diff);
                else
                    System.out.println(-1);
            }

        }
    }
}

Print prime numbers in reverse order:


import java.util.*;
class Test7
{
public static void main(String args[])
{
ArrayList<Integer> d = new ArrayList<Integer>();
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int cnt=0;
for(int i=1;i<=a;i++)
{
for(int j=1;j<=a;j++)
{
if(i%j==0)
{
cnt++;
}
}
if(cnt==2)
{
d.add(i);
}
cnt=0;
}
Collections.reverse(d);
System.out.print(d);
}
}
Ip=20
Op=[19,17,13,11,7,5,3,2]

Alternate prime numbers in reverse order:


import java.util.*;
class Test8
{
public static void main(String args[])
{
ArrayList<Integer> d = new ArrayList<Integer>();
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int cnt=0;
for(int i=1;i<=a;i++)
{
for(int j=1;j<=a;j++)
{
if(i%j==0)
{
cnt++;
}
}
if(cnt==2)
{
d.add(i);
}
cnt=0;
}
Collections.reverse(d);
for(int k=0;k<d.size();k++){
if((k%2)==0)
System.out.print(d.get(k) + " ");
}
}
}
Ip=20
Op=19 13 7 3

Concatenating prime numbers and composite numbers in one arraylist:


import java.util.*;
class Test8
{
public static void main(String args[])
{
ArrayList<Integer> d = new ArrayList<Integer>();
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int cnt=0;
for(int i=1;i<=a;i++)
{
for(int j=1;j<=a;j++)
{
if(i%j==0)
{
cnt++;
}
}
if(cnt==2)
{
d.add(i);
}
cnt=0;
}
ArrayList<Integer> b=new ArrayList<Integer>();
for(int i=1;i<=a;i++)
{
b.add(i);
}
d.addAll(b);
System.out.println(d);
}
}
Ip=10
Op=[2,3,5,7,1,2,3,4,5,6,7,8,9,10]

Concatenating two arraylists without duplicate values:


import java.util.*;
public class Test9
{
public static void main(String[] args) throws Exception
{
ArrayList<String> listOne = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e"));
ArrayList<String> listTwo = new ArrayList<>(Arrays.asList("a", "b", "c", "f", "g"));

//1

Set<String> set = new LinkedHashSet<>(listOne);


set.addAll(listTwo);
//List<String> combinedList = new ArrayList<>(set);

System.out.println(set);

//2

List<String> listTwoCopy = new ArrayList<>(listTwo);


listTwoCopy.removeAll(listOne);
listOne.addAll(listTwoCopy);

System.out.println(listOne);
}
}
Op=[a,b,c,d,e,f,g]

Print only n no of Prime numbers


import java.util.*;
public class Ppp
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int ct=0,n=0,i=1,j=1;
while(n<a)
{
j=1;
ct=0;
while(j<=i)
{
if(i%j==0)
ct++;
j++;
}
if(ct==2)
{
System.out.printf("%d ",i);
n++;
}
i++;
}
}
}
Ip=10
Op=2 3 5 7 11 13 17 19 23 29

Print n no of Fibnocci series:


import java.util.*;
class Test10
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int n1=0,n2=1;
System.out.print(n1 +" "+ n2);
for(int i=2;i<a;i++)
{
int temp=n1+n2;
n1=n2;n2=temp;
System.out.print(" "+ temp);
}
}
}
Ip=10
Op=0 1 1 2 3 5 8 13 21 34

Find the length of a string:


import java.util.*;
class Test0
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
System.out.println(s.length());
}
}
Ip=charitha
Op=8

Join 2 strings:
import java.util.*;
class Test0
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
String s1=sc.nextLine();
System.out.println(s.concat(s1));
}
}
Ip=charitha
Sri
Op=charitha Sri

Compare 2 strings:
import java.util.*;
class Test0
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
String s1=sc.nextLine();
System.out.println(s.equals(s1));
}
}
Ip=charitha
Charitha
Op=true

Find the number of times digit 3 occurs in each and every number from 0 to n.
import java.util.*;
public class Nooftimes
{
static int count_3s(int n)
{
int count = 0;
while (n > 0)
{
if (n % 10 == 3)
{
count++;
}
n = n / 10;
}
return count;
}
static int count(int n)
{
int count = 0 ;
for (int i = 2; i <= n; i++)
{
count += count_3s(i);
}
return count;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.print(count(n));
}
}
Ip=100
Op=20

Sort a string alphabetically:


import java.util.*;
class Sortstring
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
String str=input.nextLine();
char str1[]=str.toCharArray();
Arrays.sort(str1);
String result = new String(str1);
System.out.println(result);
}
}
Ip=charitha
Op=aachhirt

Print the following pattern:


1
12
123
1234
12345
import java.util.*;
class Sor
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(j);
}
System.out.println();
}
}
}

Check whether the number is abundant number or not:


import java.util.*;
public class Abundant
{
public static void main(String[] args)
{
int num, temp;
Scanner sc = new Scanner(System.in);
num = sc.nextInt();
int sum = 0;
for(int i = 1; i < num; i++)
{
if(num % i == 0)
{
sum = sum + i;
}
}
if(num < sum)
System.out.print("Abundant Number");
else
System.out.print("Not Abundant Number");
}
}
Ip=12
Op=Abundant

Reverse the Fibonacci series:


import java.util.*;
class Test13
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
ArrayList<Integer> d=new ArrayList<Integer>();
int a=sc.nextInt();
int n1=0,n2=1;
d.add(n1);
d.add(n2);
for(int i=2;i<a;i++)
{
int temp=n1+n2;
n1=n2;n2=temp;
d.add(temp);
}
Collections.reverse(d);
for(int i=0;i<d.size();i++)
{
System.out.print(d.get(i) + " ");
}
}
}
Ip=10
Op=34 21 13 8 5 3 2 1 1 0

Print the Alternate Fibonacci series in reverse order:


import java.util.*;
class Test13
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
ArrayList<Integer> d=new ArrayList<Integer>();
int a=sc.nextInt();
int n1=0,n2=1;
d.add(n1);
d.add(n2);
for(int i=2;i<a;i++)
{
int temp=n1+n2;
n1=n2;n2=temp;
d.add(temp);
}
Collections.reverse(d);
for(int i=0;i<d.size();i++)
{
if(i%2==0)
{
System.out.print(d.get(i) + " ");
}
}
}
}
Ip=10
Op=34 13 5 2 1

Print the alphabets from a to z:


import java.util.*;
class Test13
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
for(char i='a';i<='z';i++)
{
System.out.print(i +" ");
}
}
}
Op=a b c d e f g h i j k l m n o p q r s t u v w x y z

Reverse a string:

import java.util.*;
class Test13
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
StringBuilder sb=new StringBuilder(s);
System.out.println(sb.reverse());
}
}
Ip=charitha
Op=ahtirahc

Create Matrix:
import java.util.Scanner;
class Create {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int r = in.nextInt();
int c = in.nextInt();
int m[][] = new int[r][c];
for(int i=0; i < r; i++)
{
for(int j=0; j < c; j++)
{
m[i][j] = in.nextInt();
}
}
for(int i=0; i < r; i++)
{
for(int j=0; j < c; j++)
{
System.out.print(m[i][j] +" ");
}
System.out.println();
}
}
}
Ip=3
3
123456789
Op=1 2 3
456
789

Removing some random characters from the string which are given by the user:
import java.util.*;
class Test13
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
String s1=sc.nextLine();
char c[]=s.toCharArray();
char c1[]=s1.toCharArray();
List<char[]> d=Arrays.asList(c);
List<char[]> b=Arrays.asList(c1);
List<Character> listc = new ArrayList<Character>();
for (char cc : c)
{
listc.add(cc);
}
List<Character> listc1 = new ArrayList<Character>();
for (char cc1 : c1)
{
listc1.add(cc1);
}
System.out.println(listc);
System.out.println(listc1);
listc.removeAll(listc1);
System.out.println(listc);
for(int i=0;i<listc.size();i++)
{
System.out.print(listc.get(i));
}
}
}
Ip=charitha
arh
op=cit

Print a String character by character:


import java.util.*;
class Test16
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
char c[]=s.toCharArray();
for(int i=0;i<c.length;i++)
{
System.out.println(c[i]);
}
}
}
Ip=charitha
Op=c
h
a
r
i
t
h
a

Count character occurrence in a string:


import java.util.*;
class Test16
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
int freq=0;
char ch=sc.next().charAt(0);
char c[]=s.toCharArray();
for(int i=0;i<c.length;i++)
{
if(ch==c[i])
{
freq++;
}
}
System.out.println(freq);
}
}
Ip=charitha
a
op=2

Count vowels occurrence in string:


import java.util.*;
class Test16
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
int freq=0;
char ch[]={'a','e','i','o','u'};
char c[]=s.toCharArray();
for(int i=0;i<ch.length;i++)
{
for(int j=0;j<c.length;j++)
{
if(ch[i]==c[j])
{
freq++;
}
}
}
System.out.println(freq);
}
}
Ip=charitha
Op=3

Finding the index of a character in a string:


import java.util.*;
class Test16
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
char c[]=s.toCharArray();
char ch=sc.next().charAt(0);
for(int i=0;i<c.length;i++)
{
if(ch==c[i])
{
System.out.print((i+1) + " ");
}
}
}
}
Ip=charitha
a
op=3 8

Find the no of occurrences of the substring in the string:


import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
String strFind=sc.nextLine();
int count = 0, fromIndex = 0;
while ((fromIndex = str.indexOf(strFind, fromIndex)) != -1 )
{
System.out.println("Found at index: " + fromIndex);
count++;
fromIndex++;
}
System.out.println("Total occurrences: " + count);
}
}
Ip=this is the one of the exiting thing in the world.
The
Op=found at index:8
found at index:19
found at index:40
Total no of occurrences:3

String str = "TimsdsfTimsfdTim";


String match = "Tim"

/*index = str.contain(match) // returns 0 because first appearance of "Tim" start from 0 index
str = str.substring(index+1) // returns "imsdsfTimsfdTim"

index = str.contain(match) // returns 6 because first appearance of "Tim" in updated 'str' start from 6
str = str.substring(index+1) // returns "imsfdTim"

index = str.contain(match) // returns 5 because first appearance of "Tim" in updated 'str' start from 5
str = str.substring(index+1) // returns "im"

index = str.contain(match) // returns -1 because "Tim" is not present in updated 'str' */

Check whether the strings are anagrams or not:


import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String str1=sc.nextLine();
String str2=sc.nextLine();
String s1 = str1.replaceAll("\\s", "");
String s2 = str2.replaceAll("\\s", "");
boolean status = true;
if (s1.length() != s2.length())
{
status = false;
}
else
{
char[] ArrayS1 = s1.toLowerCase().toCharArray();
char[] ArrayS2 = s2.toLowerCase().toCharArray();
Arrays.sort(ArrayS1);
Arrays.sort(ArrayS2);
status = Arrays.equals(ArrayS1, ArrayS2);
}
if (status)
{
System.out.println(s1 + " and " + s2 + " are anagrams");
}
else
{
System.out.println(s1 + " and " + s2 + " are not anagrams");
}
}
}
Ip=peek
Keep
Op=peek and keep are anagrams

Find the largest number in the list:


Find the Smallest number in the list:
Find the second largest number in the list:
Find the Second smallest number in the list:
Sum of all the elements in the list and find even or odd:
Reverse the list:
import java.util.*;
public class Test16
{
public static void main (String[] args)
{
ArrayList<Integer> list = new ArrayList<Integer>();
Scanner sc=new Scanner(System.in);
while(sc.hasNextInt()){
list.add(sc.nextInt());
}
System.out.println(list);
/*System.out.println(Collections.max(list));

System.out.println(Collections.min(list));

int j=Collections.max(list);
list.remove(list.indexOf(j));
int max2 = Collections.max(list);
System.out.println(max2);

int i=Collections.min(list);
list.remove(list.indexOf(i));
int min2=Collections.min(list);
System.out.println(min2);*/
double sum=0;
for(int i=0;i<list.size();i++)
{
sum+=list.get(i);
}
System.out.println(sum);
if((sum%2)==0)
System.out.println("even");
else
System.out.println("odd");
Collections.reverse(list);
System.out.println(list);
}
}
Ip=1 2 3 4 5
done
op=[1,2,3,4,5]
5
1
4
2
15
Odd
[5,4,3,2,1]

Sort first half in ascending and second half in descending order in a list:
import java.util.*;
public class Test16
{
public static void main (String[] args)
{
ArrayList<Integer> list = new ArrayList<Integer>();
Scanner sc=new Scanner(System.in);
while(sc.hasNextInt()){
list.add(sc.nextInt());
}
List<Integer> first = new ArrayList<Integer>();
List<Integer> second = new ArrayList<Integer>();
int size = list.size();
for (int i = 0; i < size / 2; i++)
first.add(list.get(i));
for (int i = size / 2; i < size; i++)
second.add(list.get(i));
System.out.println(first);
System.out.println(second);
Collections.sort(first);
Collections.sort(second);
Collections.reverse(second);
first.addAll(second);
System.out.println(first);
}
}
Ip=3 5 6 2 9 1
done
Op=[3,5,6]
[2,9,1]
[3,5,6,9,2,1]

Count no of evens and odds and find arraytype:


import java.util.*;
public class Test16
{
public static void main (String[] args)
{
ArrayList<Integer> list = new ArrayList<Integer>();
Scanner sc=new Scanner(System.in);
while(sc.hasNextInt()){
list.add(sc.nextInt());
}
int even=0, odd=0;
for(int i=0;i<list.size();i++)
{
if((list.get(i))%2==0)
{
even++;
}
else
{
odd++;
}
}
System.out.println(odd);
System.out.println(even);
if(odd==list.size())
{
System.out.println("odd");
}
else if(even==list.size())
{
System.out.println("even");
}
else
{
System.out.println("Mixed");
}
}
}
Ip=3 4 6 2 9 1
done
op=3
3
Mixed

Mask part of string:


import java.util.*;
public class Mask
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
String strText=sc.nextLine();
int start=sc.nextInt();
int end=sc.nextInt();
char maskChar=sc.next().charAt(0);
if(strText == null || strText.equals(""))
System.out.println();

if(start < 0)
start = 0;

if( end > strText.length() )


end = strText.length();

if(start > end)


System.out.println("End index cannot be greater than start index");

int maskLength = end - start;

if(maskLength == 0)
System.out.println(strText);

StringBuilder sbMaskString = new StringBuilder(maskLength);

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


{
sbMaskString.append(maskChar);
}

System.out.println(strText.substring(0, start) + sbMaskString.toString() + strText.substring(start +


maskLength));
}
}
Ip=charitha
0
5
*
Op=*****tha

Removing html tags from string array:


import java.util.*;
public class Mask
{
public static void main(String[] args)
{
String[] str = {
"<a href=\"#\">HTML Link</a>",
"<table><tr><td>column1</td></tr></table>",
"<script>alert('javascript');</script>",
"<br />< BR >line break<bR/><br>",
"<!-- html comment --><b>bold text</b>",
"&nbsp;&nbsp;Jack &amp; Jones",
"&lt;script&gt;"
};
for(int i=0;i<str.length;i++)
{
System.out.println(str[i].replaceAll("<[^>]*>", ""));
}
}
}
op= HTML Link
column1
alert('javascript');
line break
bold text
&nbsp;&nbsp;Jack &amp; Jones
&lt;script&gt;

Remove duplicate elements from the list and write the duplicates from the list:
Write down the unique values from the list:
import java.util.*;
public class Mask
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
ArrayList<Integer> d= new ArrayList<Integer>();
while(sc.hasNextInt()){
d.add(sc.nextInt());
}
ArrayList<Integer> d1=new ArrayList<Integer>();
ArrayList<Integer> d2=new ArrayList<Integer>();
for(int ele : d)
{
if(!d1.contains(ele))
{
d1.add(ele);
}
else
{
d2.add(ele);
}
}
System.out.println(d1);
System.out.println(d2);
d1.removeAll(d2);
System.out.println(d1);
System.out.println(d1.get(d1.size()/2)); //to get the middle element in the arraylist.
}
}
Ip= 1234523
done
op= [1,2,3,4,5]
[2,3]
[1,4,5]
3
Conversion of string into list and max element and min element and reverse
string list:
import java.util.*;
class Test19
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
char c[]=s.toCharArray();
List<char[]> d=Arrays.asList(c);
List<Character> list = new ArrayList<Character>();
for (char ele : c)
{
list.add(ele);
}
System.out.println(list);
System.out.println(Collections.max(list));
System.out.println(Collections.min(list));
//Collections.reverse(list);
//System.out.println(list);
}
}
Ip= charitha
done
[c,h,a,r,i,t,h,a]
t
a
[a,h,t,i,r,a,h,c]

Print the second largest number even if there are duplicate values:
import java.util.*;
public class Test22
{
public static void main (String[] args)
{
ArrayList<Integer> list = new ArrayList<Integer>();
Scanner sc=new Scanner(System.in);
while(sc.hasNextInt()){
list.add(sc.nextInt());
}
Set<Integer> s=new HashSet<Integer>(list);
ArrayList<Integer> list1 = new ArrayList<Integer>(s);
int j=Collections.max(list1);
list1.remove(list1.indexOf(j));
System.out.println(Collections.max(list1));
}
}
Ip= 1234525
done
4

Toggle the string:


import java.util.*;
class toggle
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
String str=sc.nextLine();
char a[]=str.toCharArray();
for(int i=0;i<a.length;i++)
{
if(a[i]>='A' && a[i]<='Z')
{
a[i]=(char)((int)a[i]+32);
}
else if(a[i]>='a' && a[i]<='z')
{
a[i]=(char)((int)a[i]-32);
}
}
for(int i=0;i<a.length;i++)
System.out.print(a[i]);
}
}
Ip= chaRITHA
Op= CHAritha

Giving string values from the user side:


import java.util.*;
class toggle
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
ArrayList<String> d=new ArrayList<String>();
while(true)
{
String s=sc.nextLine();
if(!s.equals(""))
d.add(s);
else
break;
}
System.out.println(d);
}
}
Ip= cha
Sri
Roop
Op=[cha, sri, roop]

Counting valleys:
import java.util.Scanner;
public class Valley
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt(); in.nextLine();
String str = in.nextLine();
int alt=0, res=0;
char c[]=str.toCharArray();
for(int i=0;i<c.length;i++)
{
if(c[i]=='U')
{
alt++;
if(alt==0)
res++;
}
else
{
alt--;
}
}
System.out.println(res);
}
}

Check whether the given number is Armstrong or not:


import java.util.*;
class Valley {

public static void main(String[] args) {


Scanner in = new Scanner(System.in);
int n = in.nextInt();
int temp=n,digits=0,d=0,sum=0;
while(temp>0)
{
temp=temp/10;
digits++;
}
temp=n;
while(temp>0)
{
d=temp%10;
sum+=(Math.pow(d,digits));
temp=temp/10;
}
if(n==sum)
{
System.out.println("Armstrong");
}
else
{
System.out.println("Not Armstrong");
}

}
}
Ip= 153
Op= Armstrong

Display Armstrong numbers between two intervals:


Display nth element in the Armstrong series:
import java.util.*;
class Valley
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int n = in.nextInt();
for(int i=a;i<=n;i++)
{
int digits=0,d=0,sum=0,temp=i;
while(temp!=0)
{
temp=temp/10;
digits++;
}
temp=i;
while(temp!=0)
{
d=temp%10;
sum+=(Math.pow(d,digits));
temp=temp/10;
}
if(sum==i)
{
System.out.print(i +" ");
}
}
}
}
(or)

import java.util.*;
class Valley
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
ArrayList<Integer> b=new ArrayList<Integer>();
int a = in.nextInt();
int n = in.nextInt();
int c=in.nextInt();
c=c-1;;
for(int i=a;i<=n;i++)
{
int digits=0,d=0,sum=0,temp=i;
while(temp!=0)
{
temp=temp/10;
digits++;
}
temp=i;
while(temp!=0)
{
d=temp%10;
sum+=(Math.pow(d,digits));
temp=temp/10;
}
if(sum==i)
{
b.add(i);
}
}
System.out.println(b);
System.out.println(b.get(c));
}
}
Ip= 1
1000
Op= 1 2 3 4 5 6 7 8 9 153 370 371 407

Write a Java program to print the first 15 numbers of the Pell series.
In mathematics, the Pell numbers are an infinite sequence of integers. The sequence of Pell numbers starts with
0 and 1, and then each Pell number is the sum of twice the previous Pell number and the Pell number before
that.:
thus, 70 is the companion to 29, and 70 = 2 × 29 + 12 = 58 + 12.
The first few terms of the sequence are :
0, 1, 2, 5, 12, 29, 70, 169, 408, 985, 2378, 5741, 13860,…

import java.util.*;
class Pell
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a=0,b=1;
System.out.print(a +" "+ b);
for(int i=0;i<n;i++)
{
int c=(2*b)+a;
System.out.print(" " + c);
a=b;
b=c;
}
}
}

Check whether the given string is palindrome or not:


import java.util.*;
class toggle
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
String s=sc.nextLine();
char c[]=s.toCharArray();
boolean r=true;
int len=c.length;
for(int i=0;i<len;i++)
{
if(c[i]!=c[len-1])
r=false;
break;
}
System.out.println(s +" is palindrome: "+ r);
}
}
Ip= madam
Op= madam is a palindrome: true
Monk and rotations:
Monk loves to preform different operations on arrays, and so being the principal of Hackerearth
School, he assigned a task to his new student Mishki. Mishki will be provided with an integer array A of
size N and an integer K , where she needs to rotate the array in the right direction by K steps and then
print the resultant array. As she is new to the school, please help her to complete the task.

Input:
The first line will consists of one integer T denoting the number of test cases.
For each test case:
1) The first line consists of two integers N and K, N being the number of elements in the array
and K denotes the number of steps of rotation.
2) The next line consists of N space separated integers , denoting the elements of the array A.

Output:
Print the required array.

Constraints:
1≤T≤20
1≤N≤105
0≤K≤106
0≤A[i]≤106
Sample Input
1
52
12345
Sample Output
45123
Explanation
Here T is 1, which means one test case.
N=5 denoting the number of elements in the array and K=2, denoting the number of steps of rotations.
The initial array is: 1,2,3,4,5
In first rotation, 5 will come in the first position and all other elements will move to one position ahead
from their current position. Now, the resultant array will be 5,1,2,3,4
In second rotation, 4 will come in the first position and all other elements will move to one position
ahead from their current position. Now, the resultant array will be 4,5,1,2,3

import java.util.*;
class Test
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(sc.hasNext())
{
int n=sc.nextInt();
int k=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
for(int i=0;i<k;i++)
{
int last=a[n-1];
for(int j=n-1;j>0;j--)
{
a[j]=a[j-1];
}
a[0]=last;
}
for(int i=0;i<n;i++)
{
System.out.print(a[i] +" ");
}
}
}
}
Ip= 1
52
12345
Op= 4 5 1 2 3 // runs only for this test case
(or)
import java.util.*;
class Test
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();

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


int n = sc.nextInt();
int k = sc.nextInt();
k = k % n;
sc.nextLine();
String s = sc.nextLine();
String[] s1 =s.split(" ");

StringBuffer sb = new StringBuffer();

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


sb.append(s1[(n + j - k) % n] + " ");
}

System.out.print(sb);
System.out.println("");
}
}
}
Monk and Inversions:
Monk's best friend Micro, who happen to be an awesome programmer, got him an integer matrix M of
size N×N for his birthday. Monk is taking coding classes from Micro. They have just completed array
inversions and Monk was successful in writing a program to count the number of inversions in an
array. Now, Micro has asked Monk to find out the number of inversion in the matrix M. Number of
inversions, in a matrix is defined as the number of unordered pairs of cells {(i,j),(p,q)} such that M[i]
[j]>M[p][q] & i≤p & j≤q.
Monk is facing a little trouble with this task and since you did not got him any birthday gift, you need to
help him with this task.

Input:
First line consists of a single integer T denoting the number of test cases.
First line of each test case consists of one integer denoting N. Following N lines consists of N space
separated integers denoting the matrix M.

Output:
Print the answer to each test case in a new line.

Constraints:
1≤T≤100
1≤N≤20
1≤M[i][j]≤1000
Sample Input
2
3
123
456
789
2
43
14
Sample Output
0
2
Explanation
In first test case there is no pair of cells (x1,y1), (x2,y2), x1≤x2 & y1≤y2 having M[x1][y1]>M[x2][y2], so
the answer is 0.
In second test case M[1][1]>M[1][2] and M[1][1]>M[2][1], so the answer is 2.

import java.util.Scanner;
public class MonkAndInversions {

public static void main (String[] args){


Scanner in = new Scanner(System.in);
int t = in.nextInt();
while (t != 0){

int n = in.nextInt();
int[][] a = new int[n][n];
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
a[i][j] = in.nextInt();
}
}
int inversions = 0;

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


for (int l = 0; l < n; l++){
for (int j = 0; j <= i; j++){
for (int k = 0; k <= l; k++){
if (a[i][l] < a[j][k]){
inversions++;
}
}
}
}
}

System.out.println(inversions);

t--;
}
}
}

Beautiful days at the Movies:


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


int i = sc.nextInt();
int j = sc.nextInt();
int k = sc.nextInt();

int n= j-i+1;
int count=0;

while(i<=j){
int number= i;
int reverse= 0;

while(number!= 0){
reverse = (reverse*10)+(number%10);
number = number/10;
}
int diff= Math.abs(i-reverse);
if(diff % k==0||diff==0){
count++;
}
i++;
}
System.out.println(count);
}
}

Electronics shop:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution


{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int s = in.nextInt();
int n = in.nextInt();
int m = in.nextInt();
int[] a = new int[n];
for(int i=0; i < n; i++)
{
a[i] = in.nextInt();
}
int[] b = new int[m];
for(int j=0; j < m; j++)
{
b[j] = in.nextInt();
}
int k = -1;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
int v = a[i]+b[j];
if(v>k && v<= s)
{
k = v;
}
}
}
System.out.println(k);
}
}
Ip= 10 2 3
31
528
Op= 9

Angry Professor:
import java.util.*;
public class Test
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
for(int j=0;j<t;j++)
{
int n=sc.nextInt();
int k=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
int cnt=0;
for(int i=0;i<n;i++)
{
if(a[i]<=0)
{
cnt++;
}
}
if(cnt>=k)
{
System.out.println("NO");
}
else
{
System.out.println("YES");
}
}
}
}

Unique tree:
import java.util.*;
public class test
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
int b=0;
ArrayList<Integer> d=new ArrayList<Integer>();
for(int i=0;i<60;i++)
{
if(i%2==0)
{
b=b+1;
d.add(b);
}
else
{
b=b*2;
d.add(b);
}
}
for(int i=0;i<n;i++)
{
System.out.println(d.get(a[i]));
}
}
}

Complete the function that accepts a string parameter, and reverses each word
in the string. All spaces in the string should be retained.
import java.util.*;
public class Reversestring {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
String str =sc.nextLine();
System.out.println(reverseWords(str));

}
public static String reverseWords(final String original)
{
String[] arr=original.split(" ");
if(arr.length==0)
return original;
String result="";
for(String word:arr){
StringBuilder input = new StringBuilder();
result+=input.append(word).reverse().toString()+" ";
}

return result.trim();
}
}
Ip= Let’s reverse this string
Op= s’teL esrever siht gnirts

You might also like