Hackerearth-Java
1. Challenge : Welcome to Java!
Welcome to the world of Java! In this challenge, we practice printing to stdout.
The code stubs in your editor declare a Solution class and a main method. Complete the main method by copying the two lines of code below and pasting them inside the body of your main method.
System.out.println("Hello, World.");
System.out.println("Hello, Java.");
Input Format
There is no input for this challenge.
Output Format
You must print two lines of output:
- Print
Hello, World.
on the first line. - Print
Hello, Java.
on the second line.
Sample Output
Hello, World. Hello, Java.
Solution:
public class WelcomeToJava { public static void main(String[] args) { System.out.println("Hello, World."); System.out.println("Hello, Java."); } }
2. Challenge : Java Stdin and Stdout I
Most HackerRank challenges require you to read input from stdin (standard input) and write output to stdout (standard output).
One popular way to read input from stdin is by using the Scanner class and specifying the Input Stream as System.in. For example:
Scanner scanner = new Scanner(System.in);
String myString = scanner.next();
int myInt = scanner.nextInt();
scanner.close();
System.out.println("myString is: " + myString);
System.out.println("myInt is: " + myInt);
The code above creates a Scanner object named scanner and uses it to read a String and an int. It then closes the Scannerobject because there is no more input to read, and prints to stdout using System.out.println(String). So, if our input is:
Hi 5
Our code will print:
myString is: Hi
myInt is: 5
Alternatively, you can use the BufferedReader class.
Task
In this challenge, you must read 3 integers from stdin and then print them to stdout. Each integer must be printed on a new line. To make the problem a little easier, a portion of the code is provided for you in the editor below.
Input Format
There are 3 lines of input, and each line contains a single integer.
Sample Input
42
100
125
Sample Output
42 100 125
Solution:
public class JavaStdinAndStdoutI { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); sc.close(); System.out.println(a); System.out.println(b); System.out.println(c); } }
3. Challenge : Java If-Else
In this challenge, we test your knowledge of using if-else conditional statements to automate decision-making processes. An if-else statement has the following logical flow:
Source: Wikipedia
Task
Given an integer, n, perform the following conditional actions:
- If n is odd, print
Weird
- If n is even and in the inclusive range of 2 to 5, print
Not Weird
- If n is even and in the inclusive range of 6 to 20, print
Weird
- If n is even and greater than 20, print
Not Weird
Complete the stub code provided in your editor to print whether or not n is weird.
Input Format
A single line containing a positive integer, n.
Constraints
-
1 ≤ n ≤ 100
Output Format
Print Weird
if the number is weird; otherwise, print Not Weird
.
Sample Input 0
3
Sample Output 0
Weird
Sample Input 1
24
Sample Output 1
Not Weird
Solution:
public class JavaIfElse { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String ans = ""; if (n % 2 == 1) { ans = "Weird"; } else { if (n >= 6 && n <= 20) { ans = "Weird"; } else { ans = "Not Weird"; } } System.out.println(ans); sc.close(); } }
4. Challenge : Java Stdin and Stdout II
In this challenge, you must read an integer, a double, and a String from stdin, then print the values according to the instructions in the Output Format section below. To make the problem a little easier, a portion of the code is provided for you in the editor.
Note: We recommend completing Java Stdin and Stdout I before attempting this challenge.
Input Format
There are three lines of input:
- The first line contains an integer.
- The second line contains a double.
- The third line contains a String.
Output Format
There are three lines of output:
- On the first line, print
String:
followed by the unaltered String read from stdin. - On the second line, print
Double:
followed by the unaltered double read from stdin. - On the third line, print
Int:
followed by the unaltered integer read from stdin.
To make the problem easier, a portion of the code is already provided in the editor.
Note: If you use the nextLine() method immediately following the nextInt() method, recall that nextInt() reads integer tokens; because of this, the last newline character for that line of integer input is still queued in the input buffer and the next nextLine()will be reading the remainder of the integer line (which is empty).
Sample Input
42
3.1415
Welcome to HackerRank's Java tutorials!
Sample Output
String: Welcome to HackerRank's Java tutorials! Double: 3.1415 Int: 42
Solution:
public class JavaStdinAndStdoutII { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int i = sc.nextInt(); double d = sc.nextDouble(); sc.nextLine(); String s = sc.nextLine(); sc.close(); System.out.println("String: " + s); System.out.println("Double: " + d); System.out.println("Int: " + i); } }
5. Java Output Formatting
Java’s System.out.printf function can be used to print formatted output. The purpose of this exercise is to test your understanding of formatting output using printf.
To get you started, a portion of the solution is provided for you in the editor; you must format and print the input to complete the solution.
Input Format
Every line of input will contain a String followed by an integer.
Each String will have a maximum of 10 alphabetic characters, and each integer will be in the inclusive range from 0 to 999.
Output Format
In each line of output there should be two columns:
The first column contains the String and is left justified using exactly 15 characters.
The second column contains the integer, expressed in exactly 3 digits; if the original input has less than three digits, you must pad your output’s leading digits with zeroes.
Sample Input
java 100
cpp 65
python 50
Sample Output
================================ java 100 cpp 065 python 050 ================================
Solution:
public class JavaOutputFormatting { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("================================"); for (int i = 0; i < 3; i++) { String s1 = sc.next(); int x = sc.nextInt(); System.out.printf("%-15s%03d\n", s1, x); } System.out.println("================================"); sc.close(); } }
6. Challenge : Java Loops I
Objective
In this challenge, we’re going to use loops to help us do some simple math.
Task
Given an integer, N, print its first 10 multiples. Each multiple N x i (where 1≤ i ≤ 10) should be printed on a new line in the form: N x i = result
.
Input Format
A single integer, N.
Constraints
-
2 ≤ N ≤ 20
Output Format
Print 10 lines of output; each line i (where 1≤ i ≤ 10) contains the result of N x i in the form: N x i = result
.
Sample Input
2
Sample Output
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
Solution:
public class JavaLoopsI { public static void main(String[] args) { Scanner in = new Scanner(System.in); int N = in.nextInt(); for (int i = 1; i <= 10; i++) { System.out.println(N + " x " + i + " = " + N * i); } in.close(); } }
7. Challenge : Java Loops II
We use the integers a, b, and n to create the following series:
Input Format
The first line contains an integer, q, denoting the number of queries.
Each line i of the q subsequent lines contains three space-separated integers describing the respective ai , bi , and ni values for that query.
Constraints
-
0 ≤ q ≤ 500
-
0 ≤ a, b ≤ 50
-
1 ≤ n ≤ 15
Output Format
For each query, print the corresponding series on a new line. Each series must be printed in order as a single line of n space-separated integers.
Sample Input
2
0 2 10
5 3 5
Sample Output
2 6 14 30 62 126 254 510 1022 2046
8 14 26 50 98
public class JavaLoopsII { public static void main(String[] argh) { Scanner in = new Scanner(System.in); int t = in.nextInt(); for (int i = 0; i < t; i++) { int a = in.nextInt(); int b = in.nextInt(); int n = in.nextInt(); int temp = a; for (int j = 0; j < n; j++) { temp += (Math.pow(2, j) * b); System.out.print(temp + " "); } System.out.println(); } in.close(); } }
8. Challenge : Java Datatypes
Java has 8 primitive data types; char, boolean, byte, short, int, long, float, and double. For this exercise, we’ll work with the primitives used to hold integer values (byte, short, int, and long):
- A byte is an 8-bit signed integer.
- A short is a 16-bit signed integer.
- An int is a 32-bit signed integer.
- A long is a 64-bit signed integer.
Given an input integer, you must determine which primitive data types are capable of properly storing that input.
To get you started, a portion of the solution is provided for you in the editor.
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Input Format
The first line contains an integer, T, denoting the number of test cases.
Each test case, T, is comprised of a single line with an integer, n, which can be arbitrarily large or small.
Output Format
For each input variable n and appropriate primitive dataType, you must determine if the given primitives are capable of storing it. If yes, then print:
n can be fitted in:
* dataType
If there is more than one appropriate data type, print each one on its own line and order them by size (i.e.: byte < shot < int < long).
If the number cannot be stored in one of the four aforementioned primitives, print the line:
n can't be fitted anywhere.
Sample Input
5
-150
150000
1500000000
213333333333333333333333333333333333
-100000000000000
Sample Output
-150 can be fitted in:
* short
* int
* long
150000 can be fitted in:
* int
* long
1500000000 can be fitted in:
* int
* long
213333333333333333333333333333333333 can't be fitted anywhere.
-100000000000000 can be fitted in:
* long
Solution:
public class JavaDatatypes { public static void main(String[] argh) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int i = 0; i < t; i++) { try { long x = sc.nextLong(); System.out.println(x + " can be fitted in:"); if (x >= -128 && x <= 127) System.out.println("* byte"); if (x >= -(Math.pow(2, 16 - 1)) && x <= (Math.pow(2, 16 - 1) - 1)) System.out.println("* short"); if (x >= -(Math.pow(2, 32 - 1)) && x <= (Math.pow(2, 32 - 1) - 1)) System.out.println("* int"); if (x >= -(Math.pow(2, 64 - 1)) && x <= (Math.pow(2, 64 - 1) - 1)) System.out.println("* long"); } catch (Exception e) { System.out.println(sc.next() + " can't be fitted anywhere."); } } sc.close(); } }
9. Challenge : Java End-of-File
“In computing, End Of File (commonly abbreviated EOF) is a condition in a computer operating system where no more data can be read from a data source.” — (Wikipedia: End-of-file)
The challenge here is to read n lines of input until you reach EOF, then number and print all n lines of content.
Hint: Java’s Scanner.hasNext() method is helpful for this problem.
Input Format
Read some unknown n lines of input from stdin(System.in) until you reach EOF; each line of input contains a non-empty String.
Output Format
For each line, print the line number, followed by a single space, and then the line content received as input.
Sample Input
Hello world
I am a file
Read me until end-of-file.
Sample Output
1 Hello world
2 I am a file
3 Read me until end-of-file.
Solution:
public class JavaEndOfFile { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int i = 1; while (sc.hasNext()) { System.out.println(i++ + " " + sc.nextLine()); } sc.close(); } }
10. Challenge : Java Static Initializer Block
Static initialization blocks are executed when the class is loaded, and you can initialize static variables in those blocks.
It’s time to test your knowledge of Static initialization blocks. You can read about it here.
You are given a class Solution with a main method. Complete the given code so that it outputs the area of a parallelogram with breadth B and height H. You should read the variables from the standard input.
If B ≤ 0 or H ≤ 0, the output should be “java.lang.Exception: Breadth and height must be positive” without quotes.
Input Format
There are two lines of input. The first line contains B: the breadth of the parallelogram. The next line contains H: the height of the parallelogram.
Constraints
-
-100 ≤ B ≤ 100
-
-100 ≤ H ≤ 100
Output Format
If both values are greater than zero, then the main method must output the area of the parallelogram. Otherwise, print “java.lang.Exception: Breadth and height must be positive” without quotes.
Sample input 1
1
3
Sample output 1
3
Sample input 2
-1
2
Sample output 2
java.lang.Exception: Breadth and height must be positive
Solution:
public class JavaStaticInitializerBlock { static Scanner sc = new Scanner(System.in); static int B = sc.nextInt(); static int H = sc.nextInt(); static boolean flag; static { try { if (B > 0 && H > 0) { flag = true; } else { throw new Exception("Breadth and height must be positive"); } } catch (Exception e) { System.out.println(e); } } }
11. Challenge : Java Int to String
You are given an integer n, you have to convert it into a string.
Please complete the partially completed code in the editor. If your code successfully converts n into a string s the code will print “Good job“. Otherwise it will print “Wrong answer“.
n can range between -100 to 100 inclusive.
Sample Input 0
100
Sample Output 0
Good job
Solution:
public class JavaStaticInitializerBlock { static Scanner sc = new Scanner(System.in); static int B = sc.nextInt(); static int H = sc.nextInt(); static boolean flag; static { try { if (B > 0 && H > 0) { flag = true; } else { throw new Exception("Breadth and height must be positive"); } } catch (Exception e) { System.out.println(e); } } }
12. Challenge : Java Date and Time
The Calendar class is an abstract class that provides methods for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting the date of the next week.
You are given a date. You just need to write the method, getDay, which returns the day on that date. To simplify your task, we have provided a portion of the code in the editor.
For example, if you are given the date August 14th 2017, the method should return MONDAY as the day on that date.
Input Format
A single line of input containing the space separated month, day and year, respectively, in MM DD YYYY format.
Constraints
- 2000 < year < 3000
Output Format
Output the correct day in capital letters.
Sample Input
08 05 2015
Sample Output
WEDNESDAY
Solution:
public class JavaDateAndTime { public static void main(String[] args) { Scanner in = new Scanner(System.in); int month = in.nextInt(); int day = in.nextInt(); int year = in.nextInt(); LocalDate dt = LocalDate.of(year, month, day); System.out.println(dt.getDayOfWeek()); in.close(); } }
13. Challenge : Java String Introduction
“A string is traditionally a sequence of characters, either as a literal constant or as some kind of variable.” — Wikipedia: String (computer science)
This exercise is to test your understanding of Java Strings. A sample String declaration:
String myString = "Hello World!"
The elements of a String are called characters. The number of characters in a String is called the length, and it can be retrieved with the String.length() method.
Given two strings of lowercase English letters, A and B, perform the following operations:
- Sum the lengths of A and B.
- Determine if A is lexicographically larger than B (i.e.: does come before A in the dictionary?).
- Capitalize the first letter in A and B and print them on a single line, separated by a space.
Input Format
The first line contains a string A. The second line contains another string B. The strings are comprised of only lowercase English letters.
Output Format
There are three lines of output:
For the first line, sum the lengths of A and B.
For the second line, write Yes
if A is lexicographically greater than B otherwise print No
instead.
For the third line, capitalize the first letter in both A and B and print them on a single line, separated by a space.
Sample Input 0
hello
java
Sample Output 0
9
No
Hello Java
Solution:
public class JavaStringsIntroduction { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String A = sc.next(); String B = sc.next(); System.out.println(A.length() + B.length()); int l = A.length() > B.length() ? B.length() : A.length(); String str = ""; for (int i = 0; i < l; i++) { if ((int) (A.toLowerCase()).charAt(i) > (int) (B.toLowerCase()).charAt(i)) { str = "Yes"; break; } else if ((A.toLowerCase()).charAt(i) < (B.toLowerCase()).charAt(i)) { str = "No"; break; } } if (str == "") { if (A.length() > B.length()) { str = "Yes"; } else { str = "No"; } } System.out.println(str); System.out.println((A.toUpperCase()).charAt(0) + A.substring(1, A.length()) + " " + (B.toUpperCase()).charAt(0) + B.substring(1, B.length())); sc.close(); } }
14. Challenge : Java Substring
Given a string, s, and two indices, start and end, print a substring consisting of all characters in the inclusive range from start to end – 1. You’ll find the String class’ substring method helpful in completing this challenge.
Input Format
The first line contains a single string denoting s.
The second line contains two space-separated integers denoting the respective values of start and end.
Constraints
-
1 ≤ |s| ≤ 100
-
0 ≤ start < end ≤ n
- String s consists of English alphabetic letters (i.e., [a – zA – Z]) only.
Output Format
Print the substring in the inclusive range from start to end – 1.
Sample Input
Helloworld
3 7
Sample Output
lowo
Solution:
public class JavaSubstring { public static void main(String[] args) { Scanner in = new Scanner(System.in); String S = in.next(); int start = in.nextInt(); int end = in.nextInt(); System.out.println(S.substring(start, end)); in.close(); } }
15. Challenge : Java Substring Comparisons
We define the following terms:
-
Lexicographical Order, also known as alphabetic or dictionary order, orders characters as follows:
A < B < … < Y < Z < a < b < … < y < zFor example,
ball < cat
,dog < dorm
,Happy < happy
,Zoo < ball
. - A substring of a string is a contiguous block of characters in the string. For example, the substrings of
abc
area
,b
,c
,ab
,bc
, andabc
.
Given a string, s, and an integer, k, complete the function so that it finds the lexicographically smallest and largest substrings of length k.
Input Format
The first line contains a string denoting s.
The second line contains an integer denoting k.
Constraints
-
1 ≤ |s| ≤ 1000
- s consists of English alphabetic letters only (i.e.,
[a-zA-Z]
).
Output Format
Return the respective lexicographically smallest and largest substrings as a single newline-separated string.
Sample Input 0
welcometojava
3
Sample Output 0
ava
wel
Solution:
public class JavaSubstringComparisons { public static void main(String[] args) { Scanner sc = new Scanner(System.in); ArrayList<String> list = new ArrayList<String>(); String s = sc.next(); int k = sc.nextInt(); for (int i = 0; i <= s.length() - k; i++) { String tmp = s.substring(i, k + i); list.add(tmp); } Collections.sort(list); System.out.println(list.get(0)); System.out.println(list.get(list.size() - 1)); sc.close(); } }
16. Challenge : Java String Reversal
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward.(Wikipedia)
Given a string A, print Yes
if it is a palindrome, print No
otherwise.
Constraints
- A will consist at most 50 lower case english letters.
Sample Input
madam
Sample Output
Yes
Solution:
public class JavaStringReverse { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String A = sc.next(); sc.close(); boolean found = true; for (int i = 0; i < A.length() / 2; i++) { if (A.charAt(i) != A.charAt(A.length() - 1 - i)) { found = false; break; } } System.out.println(found ? "Yes" : "No"); } }
17. Challenge : Java Anagrams
Two strings, a and b, are called anagrams if they contain all the same characters in the same frequencies. For example, the anagrams of CAT
are CAT
, ACT
, TAC
, TCA
, ATC
, and CTA
.
Complete the function in the editor. If a and b are case-insensitive anagrams, print “Anagrams”; otherwise, print “Not Anagrams” instead.
Input Format
The first line contains a string denoting a.
The second line contains a string denoting b.
Constraints
-
1 ≤ length(a),length(b) ≤ 50
- Strings a and b consist of English alphabetic characters.
- The comparison should NOT be case sensitive.
Output Format
Print “Anagrams” if a and b are case-insensitive anagrams of each other; otherwise, print “Not Anagrams” instead.
Sample Input 0
anagram
margana
Sample Output 0
Anagrams
Solution:
public class JavaAnagrams { static boolean isAnagram(String a, String b) { if (a.length() != b.length()) { return false; } else { for (int i = 0; i < a.length(); i++) { char ch = a.toLowerCase().charAt(i); b = b.toLowerCase(); if (b.indexOf(ch) != -1) { b = b.replaceFirst(ch + "", ""); } else { return false; } } return b.length() == 0; } } public static void main(String[] args) { Scanner scan = new Scanner(System.in); String a = scan.next(); String b = scan.next(); scan.close(); boolean ret = isAnagram(a, b); System.out.println((ret) ? "Anagrams" : "Not Anagrams"); } }
18. Challenge : Java String Tokens
Given a string, s, matching the regular expression [A-Za-z !,?._'@]+
, split the string into tokens. We define a token to be one or more consecutive English alphabetic letters. Then, print the number of tokens, followed by each token on a new line.
Note: You may find the String.split method helpful in completing this challenge.
Input Format
A single string, s.
Constraints
-
1 ≤ length of s ≤ 4 . 105
- s is composed of any of the following: English alphabetic letters, blank spaces, exclamation points (
!
), commas (,
), question marks (?
), periods (.
), underscores (_
), apostrophes ('
), and at symbols (@
).
Output Format
On the first line, print an integer, n, denoting the number of tokens in string s (they do not need to be unique). Next, print each of the n tokens on a new line in the same order as they appear in input string s.
Sample Input
He is a very very good boy, isn't he?
Sample Output
10 He is a very very good boy isn t he
Solution:
public class JavaStringTokens { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String s = scan.nextLine(); scan.close(); boolean found = false; for (int i = 0; i < s.length(); i++) { int t = s.charAt(i); if (65 <= t && t <= 90 || t >= 97 && t <= 112) { found = true; break; } } if (found) { String[] str = s.split("[, '@_.?!]+"); int length = str.length; if (str[0].length() == 0 || str[str.length - 1].length() == 0) { length--; } System.out.println(length); for (String s1 : str) if (s1.length() != 0) System.out.println(s1); } else { System.out.println(0); } } }
19. Challenge : Pattern Syntax Checker
Using Regex, we can easily match or search for patterns in a text. Before searching for a pattern, we have to specify one using some well-defined syntax.
In this problem, you are given a pattern. You have to check whether the syntax of the given pattern is valid.
Note: In this problem, a regex is only valid if you can compile it using the Pattern.compile method.
Input Format
The first line of input contains an integer N, denoting the number of test cases. The next N lines contain a string of any printable characters representing the pattern of a regex.
Output Format
For each test case, print Valid
if the syntax of the given pattern is correct. Otherwise, print Invalid
. Do not print the quotes.
Sample Input
3
([A-Z])(.+)
[AZ[a-z](a-z)
batcatpat(nat
Sample Output
Valid Invalid Invalid
Solution:
public class PatternSyntaxChecker { public static void main(String[] args) { Scanner in = new Scanner(System.in); int testCases = Integer.parseInt(in.nextLine()); while (testCases > 0) { String pattern = in.nextLine(); try { Pattern.compile(pattern); System.out.println("Valid"); } catch (Exception e) { System.out.println("Invalid"); } } in.close(); } }
20. Challenge : Valid Username Regular Expression
You are updating the username policy on your company’s internal networking platform. According to the policy, a username is considered valid if all the following constraints are satisfied:
- The username consists of 8 to 30 characters inclusive. If the username consists of less than 8 or greater than 30 characters, then it is an invalid username.
- The username can only contain alphanumeric characters and underscores (
_
). Alphanumeric characters describe the character set consisting of lowercase characters [a – z], uppercase characters [A – Z], and digits [0 – 9]. - The first character of the username must be an alphabetic character, i.e., either lowercase character [a – z] or uppercasecharacter [A – Z].
For example:
Username | Validity |
---|---|
Julia | INVALID; Username length < 8 characters |
Samantha | VALID |
Samantha_21 | VALID |
1Samantha | INVALID; Username begins with non-alphabetic character |
Samantha?10_2A | INVALID; ‘?’ character not allowed |
Update the value of regularExpression field in the UsernameValidator class so that the regular expression only matches with valid usernames.
Input Format
The first line of input contains an integer n, describing the total number of usernames. Each of the next n lines contains a string describing the username. The locked stub code reads the inputs and validates the username.
Constraints
-
1 ≤ n ≤ 100
- The username consists of any printable characters.
Output Format
For each of the usernames, the locked stub code prints Valid
if the username is valid; otherwise Invalid
each on a new line.
Sample Input 0
8
Julia
Samantha
Samantha_21
1Samantha
Samantha?10_2A
JuliaZ007
[email protected]
_Julia007
Sample Output 0
Invalid Valid Valid Invalid Invalid Valid Invalid Invalid
Solution:
class UsernameValidator { public static final String regularExpression = "^[A-Za-z]\\w{7,29}$";; } public class ValidUsernameRegularExpression { private static final Scanner scan = new Scanner(System.in); public static void main(String[] args) { int n = Integer.parseInt(scan.nextLine()); while (n-- != 0) { String userName = scan.nextLine(); if (userName.matches(UsernameValidator.regularExpression)) { System.out.println("Valid"); } else { System.out.println("Invalid"); } } } }
21. Challenge : Tag Content Extrator
In a tag-based language like XML or HTML, contents are enclosed between a start tag and an end tag like <tag>contents</tag>
. Note that the corresponding end tag starts with a /
.
Given a string of text in a tag-based language, parse this text and retrieve the contents enclosed within sequences of well-organized tags meeting the following criterion:
-
The name of the start and end tags must be same. The HTML code
<h1>Hello World</h2>
is not valid, because the text starts with anh1
tag and ends with a non-matchingh2
tag. -
Tags can be nested, but content between nested tags is considered not valid. For example, in
<h1><a>contents</a>invalid</h1>
,contents
is valid butinvalid
is not valid. -
Tags can consist of any printable characters.
Input Format
The first line of input contains a single integer, N (the number of lines).
The N subsequent lines each contain a line of text.
Constraints
-
1 ≤ N ≤ 100
- Each line contains a maximum of 104 printable characters.
- The total number of characters in all test cases will not exceed 106.
Output Format
For each line, print the content enclosed within valid tags.
If a line contains multiple instances of valid content, print out each instance of valid content on a new line; if no valid content is found, print None
.
Sample Input
4
<h1>Nayeem loves counseling</h1>
<h1><h1>Sanjay has no watch</h1></h1><par>So wait for a while</par>
<Amee>safat codes like a ninja</amee>
<SA premium>Imtiaz has a secret crush</SA premium>
Sample Output
Nayeem loves counseling Sanjay has no watch So wait for a while None Imtiaz has a secret crush
Solution:
public class TagContentExtractor { public static void main(String[] args) { Scanner in = new Scanner(System.in); int testCases = Integer.parseInt(in.nextLine()); while (testCases > 0) { String line = in.nextLine(); String regex = "<(.+)>([^<>]+)(</\\1>)"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(line); int counter = 0; while (m.find()) { if (m.group(2).length() != 0) { System.out.println(m.group(2)); counter++; } } if (counter == 0) System.out.println("None"); testCases--; } in.close(); } }
22. Challenge : Java Regex
Write a class called MyRegex which will contain a string pattern. You need to write a regular expression and assign it to the pattern such that it can be used to validate an IP address. Use the following definition of an IP address:
IP address is a string in the form "A.B.C.D", where the value of A, B, C, and D may range from 0 to 255. Leading zeros are allowed. The length of A, B, C, or D can't be greater than 3.
Some valid IP address:
000.12.12.034
121.234.12.12
23.45.12.56
Some invalid IP address:
000.12.234.23.23
666.666.23.23
.213.123.23.32
23.45.22.32.
I.Am.not.an.ip
In this problem you will be provided strings containing any combination of ASCII characters. You have to write a regular expression to find the valid IPs.
Just write the MyRegex class which contains a String pattern. The string should contain the correct regular expression.
(MyRegex class MUST NOT be public)
Sample Input
000.12.12.034
121.234.12.12
23.45.12.56
00.12.123.123123.123
122.23
Hello.IP
Sample Output
true true true false false false
Solution:
class MyRegex { static String zeroTo255 = "(\\d{1,2}|(0|1)\\d{2}|2[0-4]\\d|25[0-5])"; public static String pattern = zeroTo255 + "\\." + zeroTo255 + "\\." + zeroTo255 + "\\." + zeroTo255; } public class JavaRegex { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { String IP = in.next(); System.out.println(IP.matches(new MyRegex().pattern)); } in.close(); } }
23. Challenge : Java Regex 2 – Duplicate Words
In this challenge, we use regular expressions (RegEx) to remove instances of words that are repeated more than once, but retain the first occurrence of any case-insensitive repeated word. For example, the words love
and to
are repeated in the sentence I love Love to To tO code
. Can you complete the code in the editor so it will turn I love Love to To tO code
into I love to code
?
To solve this challenge, complete the following three lines:
- Write a RegEx that will match any repeated word.
- Complete the second compile argument so that the compiled RegEx is case-insensitive.
- Write the two necessary arguments for replaceAll such that each repeated word is replaced with the very first instance the word found in the sentence. It must be the exact first occurrence of the word, as the expected output is case-sensitive.
Note: This challenge uses a custom checker; you will fail the challenge if you modify anything other than the three locations that the comments direct you to complete. To restore the editor’s original stub code, create a new buffer by clicking on the branch icon in the top left of the editor.
Input Format
The following input is handled for you the given stub code:
The first line contains an integer, n, denoting the number of sentences.
Each of the n subsequent lines contains a single sentence consisting of English alphabetic letters and whitespace characters.
Constraints
- Each sentence consists of at most 104 English alphabetic letters and whitespaces.
-
1 ≤ n ≤ 100
Output Format
Stub code in the editor prints the sentence modified by the replaceAll line to stdout. The modified string must be a modified version of the initial sentence where all repeat occurrences of each word are removed.
Sample Input
5
Goodbye bye bye world world world
Sam went went to to to his business
Reya is is the the best player in eye eye game
in inthe
Hello hello Ab aB
Sample Output
Goodbye bye world Sam went to his business Reya is the best player in eye game in inthe Hello Ab
Solution:
public class JavaRegex2DuplicateWords { public static void main(String[] args) { String regex = "\\b(\\w+)(\\b\\W+\\b\\1\\b)*"; Pattern p = Pattern.compile(regex, Pattern.MULTILINE + Pattern.CASE_INSENSITIVE); Scanner in = new Scanner(System.in); int numSentences = Integer.parseInt(in.nextLine()); while (numSentences-- > 0) { String input = in.nextLine(); Matcher m = p.matcher(input); // Check for subsequences of input that match the compiled pattern while (m.find()) { input = input.replaceAll(m.group(), m.group(1)); } // Prints the modified sentence. System.out.println(input); } in.close(); } }
24. Challenge : Java BigInteger
In this problem, you have to add and multiply huge numbers! These numbers are so big that you can’t contain them in any ordinary data types like a long integer.
Use the power of Java’s BigInteger class and solve this problem.
Input Format
There will be two lines containing two numbers, a and b.
Constraints
a and b are non-negative integers and can have maximum 200 digits.
Output Format
Output two lines. The first line should contain a + b, and the second line should contain a x b. Don’t print any leading zeros.
Sample Input
1234
20
Sample Output
1254 24680
Solution:
public class JavaBigInteger { public static void main(String[] args) { Scanner sc = new Scanner(System.in); BigInteger a = new BigInteger(sc.next()); BigInteger b = new BigInteger(sc.next()); System.out.println(a.add(b)); System.out.println(a.multiply(b)); sc.close(); } }
25. Challenge : Java BigDecimal
Java’s BigDecimal class can handle arbitrary-precision signed decimal numbers. Let’s test your knowledge of them!
Given an array, s, of n real number strings, sort them in descending order — but wait, there’s more! Each number must be printed in the exact same format as it was read from stdin, meaning that .1 is printed as .1, and 0.1 is printed as 0.1. If two numbers represent numerically equivalent values (e.g., .1 = 0.1), then they must be listed in the same order as they were received as input).
Complete the code in the unlocked section of the editor below. You must rearrange array s‘s elements according to the instructions above.
Input Format
The first line consists of a single integer, n, denoting the number of integer strings.
Each line i of the n subsequent lines contains a real number denoting the value of si .
Constraints
-
1 ≤ n ≤ 200
- Each si has at most 300 digits.
Output Format
Locked stub code in the editor will print the contents of array s to stdout. You are only responsible for reordering the array’s elements.
Sample Input
9
-100
50
56.6
90
0.12
.12
02.34
000.000
Sample Output
90 56.6 50 02.34 0.12 .12 000.000 -100
Solution:
public class JavaBigDecimal { public static void main(String[] args) { // Input Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String[] s = new String[n + 2]; for (int i = 0; i < n; i++) { s[i] = sc.next(); } sc.close(); // Write your code here Arrays.sort(s, 0, n, Collections.reverseOrder(new Comparator<String>() { public int compare(String s1, String s2) { BigDecimal b1 = new BigDecimal(s1); BigDecimal b2 = new BigDecimal(s2); return b1.compareTo(b2); } })); // Output for (int i = 0; i < n; i++) { System.out.println(s[i]); } } }
26. Challenge : Java Primality Test
A prime number is a natural number greater than 1 whose only positive divisors are 1 and itself. For example, the first six prime numbers are 2, 3, 5, 7, 11, and 13.
Given a large integer, n, use the Java BigInteger class’ isProbablePrime method to determine and print whether it’s prime
ornot prime
.
Input Format
A single line containing an integer, n (the number to be checked).
Constraints
- n contains at most 100 digits.
Output Format
If n is a prime number, print prime
; otherwise, print not prime
.
Sample Input
13
Sample Output
prime
Solution:
public class JavaPrimalityTest { public static void main(String[] args) { Scanner in = new Scanner(System.in); BigInteger n = in.nextBigInteger(); in.close(); System.out.println(n.isProbablePrime(100) ? "prime" : "not prime"); } }
27. Challenge : Java 1D Array
An array is a simple data structure used to store a collection of data in a contiguous block of memory. Each element in the collection is accessed using an index, and the elements are easy to find because they’re stored sequentially in memory.
Because the collection of elements in an array is stored as a big block of data, we typically use arrays when we know exactly how many pieces of data we’re going to have. For example, you might use an array to store a list of student ID numbers, or the names of state capitals. To create an array of integers named myArray that can hold four integer values, you would write the following code:
int[] myArray = new int[4];
This sets aside a block of memory that’s capable of storing 4 integers. Each integer storage cell is assigned a unique indexranging from 0 to one less than the size of the array, and each cell initially contains a 0. In the case of myArray, we can store integers at indices 0, 1, 2, and 3. Let’s say we wanted the last cell to store the number 12; to do this, we write:
myArray[3] = 12;
Similarly, we can print the contents of the last cell with the following code:
System.out.println(myArray[3]);
The code above prints the value stored at index 3 of myArray, which is 12 (the value we previously stored there). It’s important to note that while Java initializes each cell of an array of integers with a 0, not all languages do this.
Task
The code in your editor does the following:
- Reads an integer from stdin and saves it to a variable, n, denoting some number of integers.
- Reads n integers corresponding to a0,a1,…,an-1 from stdin and saves each integer ai to a variable, val.
- Attempts to print each element of an array of integers named a.
Write the following code in the unlocked portion of your editor:
- Create an array, a, capable of holding n integers.
- Modify the code in the loop so that it saves each sequential value to its corresponding location in the array. For example, the first value must be stored in a0, the second value must be stored in a1, and so on.
Good luck!
Input Format
The first line contains a single integer, n, denoting the size of the array.
Each line i of the n subsequent lines contains a single integer denoting the value of element ai.
Output Format
You are not responsible for printing any output to stdout. Locked code in the editor loops through array a and prints each sequential element on a new line.
Sample Input
5
10
20
30
40
50
Sample Output
10 20 30 40 50
Solution:
public class Java1DArray { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); // Declare array a here int a[]=new int[n]; for(int i = 0 ; i < n; i++){ int val = scan.nextInt(); a[i]=val; // Fill array a here } scan.close(); // Prints each sequential element in array a for (int i = 0; i < a.length; i++) { System.out.println(a[i]); } } }
28. Challenge : Java 2D Array
You are given a 6 * 6 2D array. An hourglass in an array is a portion shaped like this:
a b c
d
e f g
For example, if we create an hourglass using the number 1 within an array full of zeros, it may look like this:
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
Actually, there are many hourglasses in the array above. The three leftmost hourglasses are the following:
1 1 1 1 1 0 1 0 0
1 0 0
1 1 1 1 1 0 1 0 0
The sum of an hourglass is the sum of all the numbers within it. The sum for the hourglasses above are 7, 4, and 2, respectively.
In this problem you have to print the largest sum among all the hourglasses in the array.
Input Format
There will be exactly 6 lines, each containing 6 integers seperated by spaces. Each integer will be between –9 and 9 inclusive.
Output Format
Print the answer to this problem on a single line.
Sample Input
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0
Sample Output
19
Solution:
public class Java2DArray { public static void main(String[] args) { Scanner in = new Scanner(System.in); int arr[][] = new int[6][6]; for (int i = 0; i < 6; i++) { for (int j = 0; j < 6; j++) { arr[i][j] = in.nextInt(); } } int maxSum = Integer.MIN_VALUE, sum = 0; ; for (int i = 0; i < 6; i++) { for (int j = 0; j < 6; j++) { if ((i + 2 < 6) && (j + 2) < 6) { sum = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i + 1][j + 1] + arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2]; if (sum > maxSum) maxSum = sum; } } } System.out.println(maxSum); in.close(); } }
29. Challenge : Java Subarray
We define the following:
- A subarray of an n-element array is an array composed from a contiguous block of the original array’s elements. For example, if array = [1,2,3], then the subarrays are [1], [2], [3], [1,2], [2,3], and [1,2,3]. Something like [1,3] would notbe a subarray as it’s not a contiguous subsection of the original array.
- The sum of an array is the total sum of its elements.
- An array’s sum is negative if the total sum of its elements is negative.
- An array’s sum is positive if the total sum of its elements is positive.
Given an array of n integers, find and print its number of negative subarrays on a new line.
Input Format
The first line contains a single integer, n, denoting the length of array A = [a0,a1,…,an-1]. The second line contains n space-separated integers describing each respective element, ai, in array A.
Constraints
-
1 ≤ n ≤ 100
-
-104 ≤ ai ≤ 104
Output Format
Print the number of subarrays of A having negative sums.
Sample Input
5
1 -2 4 -5 1
Sample Output
9
Solution:
public class JavaSubarray { 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 count = 0; for (int i = 0; i < n; i++) { int sum = a[i]; if (sum < 0) count++; for (int j = i + 1; j < n && i + 1 < n; j++) { sum += a[j]; if (sum < 0) { count++; } } } System.out.println(count); sc.close(); } }
30. Challenge : Java Arraylist
Sometimes it’s better to use dynamic size arrays. Java’s Arraylist can provide you this feature. Try to solve this problem using Arraylist.
You are given n lines. In each line there are zero or more integers. You need to answer a few queries where you need to tell the number located in yth position of xth line.
Take your input from System.in.
Input Format
The first line has an integer n. In each of the next n lines there will be an integer d denoting number of integers on that line and then there will be d space-separated integers. In the next line there will be an integer q denoting number of queries. Each query will consist of two integers x and y.
Constraints
-
1 ≤ n ≤ 20000
-
0 ≤ d ≤ 50000
-
1 ≤ q ≤ 1000
-
1 ≤ x ≤ n
Each number will fit in signed integer.
Total number of integers in n lines will not cross 105 .
Output Format
In each line, output the number located in yth position of xth line. If there is no such position, just print “ERROR!”
Sample Input
5
5 41 77 74 22 44
1 12
4 37 34 36 52
3 20 22 33
5
1 3
3 4
3 1
4 3
5 5
Sample Output
74 52 37 ERROR! ERROR!
Solution:
public class JavaArraylist { public static void main(String[] args) { Scanner sc = new Scanner(System.in); List<ArrayList<Integer>> listOfList = new ArrayList<ArrayList<Integer>>(); int n = sc.nextInt(); for (int i = 0; i < n; i++) { int m = sc.nextInt(); ArrayList<Integer> list = new ArrayList<Integer>(); for (int j = 0; j < m; j++) { list.add(sc.nextInt()); } listOfList.add(list); } int q = sc.nextInt(); for (int k = 0; k < q; k++) { int r = sc.nextInt(); int c = sc.nextInt(); try { int v = listOfList.get(r - 1).get(c - 1); System.out.println(v); } catch (Exception e) { System.out.println("ERROR!"); } } sc.close(); } }
31. Challenge : Java Map
You are given a phone book that consists of people’s names and their phone number. After that you will be given some person’s name as query. For each query, print the phone number of that person.
Input Format
The first line will have an integer n denoting the number of entries in the phone book. Each entry consists of two lines: a name and the corresponding phone number.
After these, there will be some queries. Each query will contain a person’s name. Read the queries until end-of-file.
Constraints:
A person’s name consists of only lower-case English letters and it may be in the format ‘first-name last-name’ or in the format ‘first-name’. Each phone number has exactly 8 digits without any leading zeros.
1 ≤ n ≤ 100000
1 ≤ Query ≤ 100000
Output Format
For each case, print “Not found” if the person has no entry in the phone book. Otherwise, print the person’s name and phone number. See sample output for the exact format.
To make the problem easier, we provided a portion of the code in the editor. You can either complete that code or write completely on your own.
Sample Input
3
uncle sam
99912222
tom
11122222
harry
12299933
uncle sam
uncle tom
harry
Sample Output
uncle sam=99912222 Not found harry=12299933
Solution:
public class JavaMap { public static void main(String[] argh) { Scanner in = new Scanner(System.in); Map<String, Integer> hmap = new HashMap<String, Integer>(); int n = in.nextInt(); in.nextLine(); for (int i = 0; i < n; i++) { String name = in.nextLine(); int phone = in.nextInt(); hmap.put(name, phone); in.nextLine(); } while (in.hasNext()) { String s = in.nextLine(); if (hmap.containsKey(s)) { System.out.println(s + "=" + hmap.get(s)); } else { System.out.println("Not found"); } } in.close(); } }
32. Challenge : Java Hashset
In computer science, a set is an abstract data type that can store certain values, without any particular order, and no repeated values(Wikipedia). {1,2,3} is an example of a set, but {1,2,2} is not a set. Today you will learn how to use sets in java by solving this problem.
You are given n pairs of strings. Two pairs (a,b) and (c,d) are identical if a =c and b = d. That also implies (a,b) is notsame as (b,a). After taking each pair as input, you need to print number of unique pairs you currently have.
Complete the code in the editor to solve this problem.
Input Format
In the first line, there will be an integer T denoting number of pairs. Each of the next T lines will contain two strings seperated by a single space.
Constraints:
-
1 ≤ T ≤ 100000
- Length of each string is atmost 5 and will consist lower case letters only.
Output Format
Print T lines. In the ith line, print number of unique pairs you have after taking ith pair as input.
Sample Input
5
john tom
john mary
john tom
mary anna
mary anna
Sample Output
1 2 2 3 3
Solution:
public class JavaHashset { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); String[] pair_left = new String[t]; String[] pair_right = new String[t]; for (int i = 0; i < t; i++) { pair_left[i] = sc.next(); pair_right[i] = sc.next(); } // Write your code here Set<String> set = new HashSet<String>(); for (int i = 0; i < t; i++) { set.add(pair_left[i] + "_" + pair_right[i]); System.out.println(set.size()); } sc.close(); } }
33. Challenge : Java Comparator
Comparators are used to compare two objects. In this challenge, you’ll create a comparator and use it to sort an array.
The Player class is provided for you in your editor. It has 2 fields: a name String and a score integer.
Given an array of n Player objects, write a comparator that sorts them in order of decreasing score; if 2 or more players have the same score, sort those players alphabetically by name. To do this, you must create a Checker class that implements the Comparator interface, then write an int compare(Player a, Player b) method implementing the Comparator.compare(T o1, T o2)method.
Input Format
Input from stdin is handled by the locked stub code in the Solution class.
The first line contains an integer, n, denoting the number of players.
Each of the n subsequent lines contains a player’s name and score, respectively.
Constraints
-
0 ≤ score ≤ 1000
- 2 players can have the same name.
- Player names consist of lowercase English letters.
Output Format
You are not responsible for printing any output to stdout. The locked stub code in Solution will create a Checker object, use it to sort the Player array, and print each sorted element.
Sample Input
5
amy 100
david 100
heraldo 50
aakansha 75
aleksa 150
Sample Output
aleksa 150 amy 100 david 100 aakansha 75 heraldo 50
Solution:
class Player { String name; int score; Player(String name, int score) { this.name = name; this.score = score; } } // Write your Checker class here class Checker implements Comparator<Player> { public int compare(Player o1, Player o2) { if (o1.score == o2.score) { return ((o1.name).compareTo(o2.name)); } else { return ((o2.score - o1.score)); } } } public class JavaComparator { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); Player[] player = new Player[n]; Checker checker = new Checker(); for (int i = 0; i < n; i++) { player[i] = new Player(scan.next(), scan.nextInt()); } scan.close(); Arrays.sort(player, checker); for (int i = 0; i < player.length; i++) { System.out.printf("%s %s\n", player[i].name, player[i].score); } } }
34. Challenge : Java Sort
You are given a list of student information: ID, FirstName, and CGPA. Your task is to rearrange them according to their CGPA in decreasing order. If two student have the same CGPA, then arrange them according to their first name in alphabetical order. If those two students also have the same first name, then order them according to their ID. No two students have the same ID.
Hint: You can use comparators to sort a list of objects. See the oracle docs to learn about comparators.
Input Format
The first line of input contains an integer N, representing the total number of students. The next N lines contains a list of student information in the following structure:
ID Name CGPA
Constraints
2 ≤ N ≤ 1000
0 ≤ ID ≤ 100000
5 ≤ |Name| ≤ 30
0 ≤ CGPA ≤ 4.00
The name contains only lowercase English letters. The ID contains only integer numbers without leading zeros. The CGPA will contain, at most, 2 digits after the decimal point.
Output Format
After rearranging the students according to the above rules, print the first name of each student on a separate line.
Sample Input
5
33 Rumpa 3.68
85 Ashis 3.85
56 Samiha 3.75
19 Samara 3.75
22 Fahim 3.76
Sample Output
Ashis Fahim Samara Samiha Rumpa
Solution:
class Student { private int id; private String fname; private double cgpa; public Student(int id, String fname, double cgpa) { super(); this.id = id; this.fname = fname; this.cgpa = cgpa; } public int getId() { return id; } public String getFname() { return fname; } public double getCgpa() { return cgpa; } } // Complete the code public class JavaSort { public static void main(String[] args) { Scanner in = new Scanner(System.in); int testCases = Integer.parseInt(in.nextLine()); List<Student> studentList = new ArrayList<Student>(); while (testCases > 0) { int id = in.nextInt(); String fname = in.next(); double cgpa = in.nextDouble(); Student st = new Student(id, fname, cgpa); studentList.add(st); testCases--; } Collections.sort(studentList, new Comparator<Student>() { public int compare(Student s1, Student s2) { if (s1.getCgpa() == s2.getCgpa()) { if (s1.getFname().equals(s2.getFname())) { return s1.getId() - s2.getId(); } else { return s1.getFname().compareTo(s2.getFname()); } } else { return (int) (s2.getCgpa() * 1000 - s1.getCgpa() * 1000); } } }); for (Student st : studentList) { System.out.println(st.getFname()); } in.close(); } }
35. Challenge : Java List
For this problem, we have 2 types of queries you can perform on a List:
-
Insert y at index x:
Insert x y
-
Delete the element at index x:
Delete x
Given a list, L, of N integers, perform Q queries on the list. Once all queries are completed, print the modified list as a single line of space-separated integers.
Input Format
The first line contains an integer, N (the initial number of elements in L).
The second line contains N space-separated integers describing L.
The third line contains an integer,Q (the number of queries).
The 2Q subsequent lines describe the queries, and each query is described over two lines:
- If the first line of a query contains the String Insert, then the second line contains two space separated integers x y, and the value y must be inserted into L at index x.
- If the first line of a query contains the String Delete, then the second line contains index x, whose element must be deleted from L.
Constraints
-
1 ≤ N ≤ 4000
-
1 ≤ Q ≤ 4000
- Each element in is a 32-bit integer.
Output Format
Print the updated list L as a single line of space-separated integers.
Sample Input
5
12 0 1 78 12
2
Insert
5 23
Delete
Sample Output
0 1 78 12 23
Solution:
public class JavaList { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); List<Integer> L = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { L.add(sc.nextInt()); } int Q = sc.nextInt(); for (int i = 0; i < Q; i++) { String op = sc.next(); if (op.equalsIgnoreCase("INSERT")) { int index = sc.nextInt(); int item = sc.nextInt(); L.add(index, item); } else { L.remove(sc.nextInt()); } } for (Integer integer : L) { System.out.print(integer + " "); } sc.close(); } }
36. Challenge : Java Generics
Generic methods are a very efficient way to handle multiple datatypes using a single method. This problem will test your knowledge on Java Generic methods.
Let’s say you have an integer array and a string array. You have to write a single method printArray that can print all the elements of both arrays. The method should be able to accept both integer arrays or string arrays.
You are given code in the editor. Complete the code so that it prints the following lines:
1
2
3
Hello
World
Do not use method overloading because your answer will not be accepted.
Solution:
public class JavaGenerics { // Write your code here public <T> void printArray(T[] in) { for (T t : in) { System.out.println(t); } } }
37. Challenge : Java Stack
In computer science, a stack or LIFO (last in, first out) is an abstract data type that serves as a collection of
elements, with two principal operations: push, which adds an element to the collection, and pop, which removes the
last element that was added.(Wikipedia)
A string containing only parentheses is balanced if the following is true: 1. if it is an empty string 2. if A and B are correct, AB is correct, 3. if A is correct, (A) and {A} and [A] are also correct.
Examples of some correctly balanced strings are: “{}()”, “[{()}]”, “({()})”
Examples of some unbalanced strings are: “{}(“, “({)}”, “[[“, “}{” etc.
Given a string, determine if it is balanced or not.
Input Format
There will be multiple lines in the input file, each having a single non-empty string. You should read input till end-of-file.
The part of the code that handles input operation is already provided in the editor.
Output Format
For each case, print ‘true’ if the string is balanced, ‘false’ otherwise.
Sample Input
{}()
({()})
{}(
[]
Sample Output
true true false true
Solution:
public class JavaStack { private static boolean matchParenthisis(String str) { Stack<Character> st = new Stack<Character>(); char[] ch = str.toCharArray(); for (char c : ch) { if (c == '{' || c == '[' || c == '(') { st.push(c); } else { if (c == ']' && !st.isEmpty() && st.pop() == '[') { continue; } else if (c == '}' && !st.isEmpty() && st.pop() == '{') { continue; } else if (c == ')' && !st.isEmpty() && st.pop() == '(') { continue; } else { return false; } } } return st.isEmpty(); } public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { String s = in.next(); System.out.println(matchParenthisis(s)); } in.close(); } }
38. Challenge : Java Dequeue
In computer science, a double-ended queue (dequeue, often abbreviated to deque, pronounced deck) is an abstract data type that generalizes a queue, for which elements can be added to or removed from either the front (head) or back (tail).
Deque interfaces can be implemented using various types of collections such as LinkedList
or ArrayDeque
classes. For example, deque can be declared as:
Deque deque = new LinkedList<>();
or
Deque deque = new ArrayDeque<>();
You can find more details about Deque here.
In this problem, you are given N integers. You need to find the maximum number of unique integers among all the possible contiguous subarrays of size M.
Note: Time limit is 3 second for this problem.
Input Format
The first line of input contains two integers N and M: representing the total number of integers and the size of the subarray, respectively. The next line contains N space separated integers.
Constraints
1 ≤ N ≤ 100000
1 ≤ M ≤ 100000
M ≤ N
The numbers in the array will range between [0, 10000000].
Output Format
Print the maximum number of unique integers among all possible contiguous subarrays of size M.
Sample Input
6 3
5 3 5 2 3 2
Sample Output
3
Solution:
public class JavaDequeue { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Deque<Integer> dq = new ArrayDeque<Integer>(); HashSet<Integer> s = new HashSet<Integer>(); int n = sc.nextInt(); int m = sc.nextInt(); int max = 0; for (int i = 0; i < n; i++) { int tmp = sc.nextInt(); dq.add(tmp); s.add(tmp); if (dq.size() == m) { max = Math.max(s.size(), max); int item = dq.remove(); if (!dq.contains(item)) { s.remove(item); } } } System.out.println(max); sc.close(); } }
39. Challenge : Java Bitset
Java’s BitSet class implements a vector of bit values (i.e.: false (0) or true (1)) that grows as needed, allowing us to easily manipulate bits while optimizing space (when compared to other collections). Any element having a bit value of 1 is called a set bit.
Given 2 BitSets, B1 and B2, of size N where all bits in both BitSets are initialized to 0, perform a series of M operations. After each operation, print the number of set bits in the respective BitSets as two space-separated integers on a new line.
Input Format
The first line contains 2 space-separated integers, N (the length of both BitSets B1 and B2) and M (the number of operations to perform), respectively.
The M subsequent lines each contain an operation in one of the following forms:
In the list above, <set> is the integer 1 or 2, where 1 denotes B1 and 2 denotes B2.
<index> is an integer denoting a bit’s index in the BitSet corresponding to <set>.
For the binary operations AND, OR, and XOR, operands are read from left to right and the BitSet resulting from the operation replaces the contents of the first operand. For example:
AND 2 1
B2 is the left operand, and B1 is the right operand. This operation should assign the result of B2 ∧ B1 to B2 .
Constraints
-
1 ≤ N ≤ 1000
-
1 ≤ M ≤ 10000
Output Format
After each operation, print the respective number of set bits in BitSet B1 and BitSet B2 as 2 space-separated integers on a new line.
Sample Input
5 4
AND 1 2
SET 1 4
FLIP 2 2
OR 2 1
Sample Output
0 0 1 0 1 1 1 2
Solution:
public class JavaBitSet { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int M = sc.nextInt(); BitSet b1 = new BitSet(N); BitSet b2 = new BitSet(N); for (int i = 0; i < M; i++) { String op = sc.next(); int x = sc.nextInt(); int y = sc.nextInt(); switch (op) { case "AND": if (x == 1) { b1.and(b2); } else { b2.and(b1); } break; case "OR": if (x == 1) { b1.or(b2); } else { b2.or(b1); } break; case "FLIP": if (x == 1) { b1.flip(y); } else { b2.flip(y); } break; case "SET": if (x == 1) { b1.set(y); } else { b2.set(y); } break; case "XOR": if (x == 1) { b1.xor(b2); } else { b2.xor(b1); } break; } System.out.println(b1.cardinality() + " " + b2.cardinality()); } sc.close(); } }
40. Challenge : Priority Queue
In computer science, a priority queue is an abstract data type which is like a regular queue, but where additionally each element has a “priority” associated with it. In a priority queue, an element with high priority is served before an element with low priority. – Wikipedia
In this problem we will test your knowledge on Java Priority Queue.
There are a number of students in a school who wait to be served. Two types of events, ENTER and SERVED, can take place which are described below.
- ENTER: A student with some priority enters the queue to be served.
- SERVED: The student with the highest priority is served (removed) from the queue.
A unique id is assigned to each student entering the queue. The queue serves the students based on the following criteria (priority criteria):
- The student having the highest Cumulative Grade Point Average (CGPA) is served first.
- Any students having the same CGPA will be served by name in ascending case-sensitive alphabetical order.
- Any students having the same CGPA and name will be served in ascending order of the id.
Create the following two classes:
- The Student class should implement:
- The constructor
Student(int id, String name, double cgpa)
. - The method
int getID()
to return the id of the student. - The method
String getName()
to return the name of the student. - The method
double getCGPA()
to return the CGPA of the student.
- The constructor
- The Priorities class should implement the method
List<Student> getStudents(List<String> events)
to process all the given events and return all the students yet to be served in the priority order.
Input Format
The first line contains an integer, n, describing the total number of events. Each of the n subsequent lines will be of the following two forms:
ENTER name CGPA id
: The student to be inserted into the priority queue.SERVED
: The highest priority student in the queue was served.
The locked stub code in the editor reads the input and tests the correctness of the Student and Priorities classes implementation.
Constraints
-
2 ≤ n ≤ 1000
-
0 ≤ CGPA ≤ 4.00
-
1 ≤ id≤ 105
-
2 ≤ |name| ≤ 30
Output Format
The locked stub code prints the names of the students yet to be served in the priority order. If there are no such student, then the code prints EMPTY
.
Sample Input 0
12
ENTER John 3.75 50
ENTER Mark 3.8 24
ENTER Shafaet 3.7 35
SERVED
SERVED
ENTER Samiha 3.85 36
SERVED
ENTER Ashley 3.9 42
ENTER Maria 3.6 46
ENTER Anik 3.95 49
ENTER Dan 3.95 50
SERVED
Sample Output 0
Dan Ashley Shafaet Maria
Solution:
public class JavaPriorityQueue { static class Student { private int token; private String fname; private double cgpa; public Student(int id, String fname, double cgpa) { super(); this.token = id; this.fname = fname; this.cgpa = cgpa; } public int getToken() { return token; } public String getFname() { return fname; } public double getCgpa() { return cgpa; } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); PriorityQueue<Student> data = new PriorityQueue<Student>(new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { if (o1.getCgpa() < o2.getCgpa()) { return 1; } else if (o1.getCgpa() > o2.getCgpa()) { return -1; } else { if (o1.getFname().compareTo(o2.getFname()) == 0) { if (o1.getToken() > o2.getToken()) { return 1; } else if (o1.getToken() < o2.getToken()) { return -1; } else { return 0; } } else { return o1.getFname().compareTo(o2.getFname()); } } } }); for (int i = 0; i < t; i++) { String op = sc.next(); switch (op) { case "ENTER": String name = sc.next(); double cgpa = sc.nextDouble(); int id = sc.nextInt(); Student s = new Student(id, name, cgpa); data.add(s); break; case "SERVED": if (data.isEmpty()) { break; } data.remove(); } } if (data.isEmpty()) System.out.println("EMPTY"); else { while (!data.isEmpty()) { Student st = data.poll(); System.out.println(st.getFname()); } } sc.close(); } }
41. Challenge : Java 1D Array (Part 2)
Let’s play a game on an array! You’re standing at index 0 of an n-element array named game. From some index i(where 0 ≤ i ≤ n), you can perform one of the following moves:
- Move Backward: If cell i – 1 exists and contains a 0, you can walk back to cell i – 1.
- Move Forward:
- If cell i + 1 contains a zero, you can walk to cell i + 1.
- If cell i + leap contains a zero, you can jump to cell i + leap.
- If you’re standing in cell n – 1 or the value of i + leap ≥ n, you can walk or jump off the end of the array and win the game.
In other words, you can move from index i to index i + 1, i – 1, or i + leap as long as the destination index is a cell containing a 0. If the destination index is greater than n – 1, you win the game.
Given leap and game, complete the function in the editor below so that it returns true if you can win the game (or false if you cannot).
Input Format
The first line contains an integer, q, denoting the number of queries (i.e., function calls).
The 2 . q subsequent lines describe each query over two lines:
- The first line contains two space-separated integers describing the respective values of n and leap.
- The second line contains n space-separated binary integers (i.e., zeroes and ones) describing the respective values of game0,game1,…,gamen-1.
Constraints
-
1 ≤ q ≤ 5000
-
2 ≤ n ≤ 100
-
0 ≤ leap ≤ 100
- It is guaranteed that the value of game[0] is always 0.
Output Format
Return true if you can win the game; otherwise, return false.
Sample Input
4
5 3
0 0 0 0 0
6 5
0 0 0 1 1 1
6 3
0 0 1 1 1 0
3 1
0 1 0
Sample Output
YES YES NO NO
Solution:
public class Java1DArrayPart2 { public static boolean canWin(int leap, int[] game) { return canWin(leap, game, 0); } public static boolean canWin(int leap, int[] g, int i) { if (i < 0 || g[i] == 1) { return false; } if (i + leap >= g.length || i == g.length - 1) { return true; } g[i] = 1; return canWin(leap, g, i + 1) || canWin(leap, g, i + leap) || canWin(leap, g, i - 1); } public static void main(String[] args) { Scanner scan = new Scanner(System.in); int q = scan.nextInt(); while (q-- > 0) { int n = scan.nextInt(); int leap = scan.nextInt(); int[] game = new int[n]; for (int i = 0; i < n; i++) { game[i] = scan.nextInt(); } System.out.println((canWin(leap, game)) ? "YES" : "NO"); } scan.close(); } }
42. Challenge : Java Inheritance I
Using inheritance, one class can acquire the properties of others. Consider the following Animal class:
class Animal{
void walk(){
System.out.println("I am walking");
}
}
This class has only one method, walk. Next, we want to create a Bird class that also has a fly method. We do this using extendskeyword:
class Bird extends Animal {
void fly() {
System.out.println("I am flying");
}
}
Finally, we can create a Bird object that can both fly and walk.
public class Solution{
public static void main(String[] args){
Bird bird = new Bird();
bird.walk();
bird.fly();
}
}
The above code will print:
I am walking
I am flying
This means that a Bird object has all the properties that an Animal object has, as well as some additional unique properties.
The code above is provided for you in your editor. You must add a sing method to the Bird class, then modify the main method accordingly so that the code prints the following lines:
I am walking I am flying I am singing
Solution:
class Animal{ void walk(){ System.out.println("I am walking"); } } class Bird extends Animal{ void fly(){ System.out.println("I am flying"); } //code need to be added void sing(){ System.out.println("I am singing"); } } public class JavaInheritanceI { public static void main(String args[]){ Bird bird = new Bird(); bird.walk(); bird.fly(); bird.sing(); } }
43. Challenge : Java Inheritance II
Write the following code in your editor below:
- A class named Arithmetic with a method named add that takes 2 integers as parameters and returns an integer denoting their sum.
- A class named Adder that inherits from a superclass named Arithmetic.
Your classes should not be public .
Input Format
You are not responsible for reading any input from stdin; a locked code stub will test your submission by calling the addmethod on an Adder object and passing it 2 integer parameters.
Output Format
You are not responsible for printing anything to stdout. Your add method must return the sum of its parameters.
Sample Output
The main method in the Solution class above should print the following:
My superclass is: Arithmetic
42 13 20
Solution:
class Arithmetic { int add(int a, int b) { return a + b; } } class Adder extends Arithmetic { } public class JavaInheritanceII { public static void main(String[] args) { // Create a new Adder object Adder a = new Adder(); // Print the name of the superclass on a new line System.out.println("My superclass is: " + a.getClass().getSuperclass().getName()); // Print the result of 3 calls to Adder's `add(int,int)` method as 3 // space-separated integers: System.out.print(a.add(10, 32) + " " + a.add(10, 3) + " " + a.add(10, 10) + "\n"); } }
44. Challenge : Java Abstract Class
A Java abstract class is a class that can’t be instantiated. That means you cannot create new instances of an abstract class. It works as a base for subclasses. You should learn about Java Inheritance before attempting this challenge.
Following is an example of abstract class:
abstract class Book{
String title;
abstract void setTitle(String s);
String getTitle(){
return title;
}
}
If you try to create an instance of this class like the following line you will get an error:
Book new_novel=new Book();
You have to create another class that extends the abstract class. Then you can create an instance of the new class.
Notice that setTitle method is abstract too and has no body. That means you must implement the body of that method in the child class.
In the editor, we have provided the abstract Book class and a Main class. In the Main class, we created an instance of a class called MyBook. Your task is to write just the MyBook class.
Your class mustn’t be public.
Sample Input
A tale of two cities
Sample Output
The title is: A tale of two cities
Solution:
abstract class Book { String title; abstract void setTitle(String s); String getTitle() { return title; } } // Write MyBook class here class MyBook extends Book { void setTitle(String s) { super.title = s; } } public class JavaAbstractClass { public static void main(String[] args) { // Book new_novel=new Book(); This line prHMain.java:25: error: Book is // abstract; cannot be instantiated Scanner sc = new Scanner(System.in); String title = sc.nextLine(); MyBook new_novel = new MyBook(); new_novel.setTitle(title); System.out.println("The title is: " + new_novel.getTitle()); sc.close(); } }
45. Challenge : Java Interface
A Java interface can only contain method signatures and fields. The interface can be used to achieve polymorphism. In this problem, you will practice your knowledge on interfaces.
You are given an interface AdvancedArithmetic which contains a method signature int divisor_sum(int n). You need to write a class called MyCalculator which implements the interface.
divisorSum function just takes an integer as input and return the sum of all its divisors. For example divisors of 6 are 1, 2, 3 and 6, so divisor_sum should return 12. The value of n will be at most 1000.
Read the partially completed code in the editor and complete it. You just need to write the MyCalculator class only. Your class shouldn’t be public.
Sample Input
6
Sample Output
I implemented: AdvancedArithmetic 12
Solution:
interface AdvancedArithmetic { int divisor_sum(int n); } // Write your code here class MyCalculator implements AdvancedArithmetic { public int divisor_sum(int n) { int sum = 0, i = 1; while (n != 0 && i <= n) { if (n % i == 0) { sum += i; } i++; } return sum; } } public class JavaInterface { public static void main(String[] args) { MyCalculator my_calculator = new MyCalculator(); System.out.print("I implemented: "); ImplementedInterfaceNames(my_calculator); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); System.out.print(my_calculator.divisor_sum(n) + "\n"); sc.close(); } /* * ImplementedInterfaceNames method takes an object and prints the name of the * interfaces it implemented */ static void ImplementedInterfaceNames(Object o) { Class[] theInterfaces = o.getClass().getInterfaces(); for (int i = 0; i < theInterfaces.length; i++) { String interfaceName = theInterfaces[i].getName(); System.out.println(interfaceName); } } }
46. Challenge : Java Method Overriding
When a subclass inherits from a superclass, it also inherits its methods; however, it can also override the superclass methods (as well as declare and implement new ones). Consider the following Sports class:
class Sports{
String getName(){
return "Generic Sports";
}
void getNumberOfTeamMembers(){
System.out.println( "Each team has n players in " + getName() );
}
}
Next, we create a Soccer class that inherits from the Sports class. We can override the getName method and return a different, subclass-specific string:
class Soccer extends Sports{
@Override
String getName(){
return "Soccer Class";
}
}
Note: When overriding a method, you should precede it with the @Override
annotation. The parameter(s) and return type of an overridden method must be exactly the same as those of the method inherited from the supertype.
Task
Complete the code in your editor by writing an overridden getNumberOfTeamMembers method that prints the same statement as the superclass’ getNumberOfTeamMembers method, except that it replaces n with 11 (the number of players on a Soccer team).
Output Format
When executed, your completed code should print the following:
Generic Sports Each team has n players in Generic Sports Soccer Class Each team has 11 players in Soccer Class
Solution:
class Sports { String getName() { return "Generic Sports"; } // Write your overridden getNumberOfTeamMembers method here void getNumberOfTeamMembers() { System.out.println("Each team has n players in " + getName()); } } class Soccer extends Sports { @Override String getName() { return "Soccer Class"; } } public class JavaMethodOverriding { public static void main(String[] args) { Sports c1 = new Sports(); Soccer c2 = new Soccer(); System.out.println(c1.getName()); c1.getNumberOfTeamMembers(); System.out.println(c2.getName()); c2.getNumberOfTeamMembers(); } }
47. Challenge : Java Method Overriding 2
When a method in a subclass overrides a method in superclass, it is still possible to call the overridden method using superkeyword. If you write super.func() to call the function func(), it will call the method that was defined in the superclass.
You are given a partially completed code in the editor. Modify the code so that the code prints the following text:
Hello I am a motorcycle, I am a cycle with an engine.
My ancestor is a cycle who is a vehicle with pedals.
Solution:
class BiCycle { String define_me() { return "a vehicle with pedals."; } } class MotorCycle extends BiCycle { String define_me() { return "a cycle with an engine."; } MotorCycle() { System.out.println("Hello I am a motorcycle, I am " + define_me()); String temp = super.define_me(); // Fix this line System.out.println("My ancestor is a cycle who is " + temp); } } public class JavaMethodOverriding2SuperKeyword { public static void main(String[] args) { new MotorCycle(); } }
48. Challenge : Java Instaneof Keyword
The Java instanceof operator is used to test if the object or instance is an instanceof the specified type.
In this problem we have given you three classes in the editor:
- Student class
- Rockstar class
- Hacker class
In the main method, we populated an ArrayList with several instances of these classes. count method calculates how many instances of each type is present in the ArrayList. The code prints three integers, the number of instance of Student class, the number of instance of Rockstar class, the number of instance of Hacker class.
But some lines of the code are missing, and you have to fix it by modifying only 3 lines! Don’t add, delete or modify any extra line.
To restore the original code in the editor, click on the top left icon in the editor and create a new buffer.
Sample Input
5
Student
Student
Rockstar
Student
Hacker
Sample Output
3 1 1
Solution:
class Student { } class Rockstar { } class Hacker { } public class JavaInstanceofkeyword { static String count(ArrayList mylist) { int a = 0, b = 0, c = 0; for (int i = 0; i < mylist.size(); i++) { Object element = mylist.get(i); if (element instanceof Student) a++; if (element instanceof Rockstar) b++; if (element instanceof Hacker) c++; } String ret = Integer.toString(a) + " " + Integer.toString(b) + " " + Integer.toString(c); return ret; } public static void main(String[] args) { ArrayList mylist = new ArrayList(); Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int i = 0; i < t; i++) { String s = sc.next(); if (s.equals("Student")) mylist.add(new Student()); if (s.equals("Rockstar")) mylist.add(new Rockstar()); if (s.equals("Hacker")) mylist.add(new Hacker()); } System.out.println(count(mylist)); sc.close(); } }
49. Challenge : Java Iterator
Java Iterator class can help you to iterate through every element in a collection. Here is a simple example:
import java.util.*;
public class Example{
public static void main(String []args){
ArrayList mylist = new ArrayList();
mylist.add("Hello");
mylist.add("Java");
mylist.add("4");
Iterator it = mylist.iterator();
while(it.hasNext()){
Object element = it.next();
System.out.println((String)element);
}
}
}
In this problem you need to complete a method func. The method takes an ArrayList as input. In that ArrayList there is one or more integer numbers, then there is a special string “###”, after that there are one or more other strings. A sample ArrayListmay look like this:
element[0]=>42
element[1]=>10
element[2]=>"###"
element[3]=>"Hello"
element[4]=>"Java"
You have to modify the func method by editing at most 2 lines
so that the code only prints the elements after the special string “###”. For the sample above the output will be:
Hello
Java
Note: The stdin doesn’t contain the string “###”, it is added in the main method.
To restore the original code in the editor, click the top left icon on the editor and create a new buffer.
Solution:
public class JavaIterator { static Iterator func(ArrayList mylist) { Iterator it = mylist.iterator(); while (it.hasNext()) { Object element = it.next(); if (element instanceof String)// Hints: use instanceof operator break; } return it; } @SuppressWarnings({ "unchecked" }) public static void main(String[] args) { ArrayList mylist = new ArrayList(); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); for (int i = 0; i < n; i++) { mylist.add(sc.nextInt()); } mylist.add("###"); for (int i = 0; i < m; i++) { mylist.add(sc.next()); } Iterator it = func(mylist); while (it.hasNext()) { Object element = it.next(); System.out.println((String) element); } sc.close(); } }
50. Challenge : Java Exception Handling (Try-Catch)
Exception handling is the process of responding to the occurrence, during computation, of exceptions – anomalous or exceptional conditions requiring special processing – often changing the normal flow of program execution. (Wikipedia)
Java has built-in mechanism to handle exceptions. Using the try statement we can test a block of code for errors. The catchblock contains the code that says what to do if exception occurs.
This problem will test your knowledge on try-catch block.
You will be given two integers x and y as input, you have to compute x/y. If x and y are not 32 bit signed integers or if y is zero, exception will occur and you have to report it. Read sample Input/Output to know what to report in case of exceptions.
Sample Input 0:
10
3
Sample Output 0:
3
Sample Input 1:
10
Hello
Sample Output 1:
java.util.InputMismatchException
Sample Input 2:
10
Sample Output 2:
java.lang.ArithmeticException: / by zero
Sample Input 3:
23.323
Sample Output 3:
java.util.InputMismatchException
Solution:
public class JavaExceptionHandlingTryCatch { public static void main(String[] args) { Scanner sc = new Scanner(System.in); try { int x = sc.nextInt(); int y = sc.nextInt(); int z = x / y; System.out.println(z); } catch (ArithmeticException e) { System.out.println(e); } catch (InputMismatchException e) { System.out.println(e.getClass().getName()); } finally { sc.close(); } } }
51. Challenge : Java Varargs – Simple Addition
You are given a class Solution and its main method in the editor.
Your task is to create the class Add and the required methods so that the code prints the sum of the numbers passed to the function add.
Note: Your add method in the Add class must print the sum as given in the Sample Output
Input Format
There are six lines of input, each containing an integer.
Output Format
There will be only four lines of output. Each line contains the sum of the integers passed as the parameters to add in the mainmethod.
Sample Input
1
2
3
4
5
6
Sample Output
1+2=3 1+2+3=6 1+2+3+4+5=15 1+2+3+4+5+6=21
Solution:
public class JavaVarargsSimpleAddition { public void add(int... a) { String b = ""; int c = 0; for (int i : a) { b += i + "+"; c += i; } System.out.print(b.substring(0, b.length() - 1)); System.out.println("=" + c); } }
52. Challenge : Java Reflection – Attributes
JAVA reflection is a very powerful tool to inspect the attributes of a class in runtime. For example, we can retrieve the list of public fields of a class using getDeclaredMethods().
In this problem, you will be given a class Solution in the editor. You have to fill in the incompleted lines so that it prints all the methods of another class called Student in alphabetical order. We will append your code with the Student class before running it. The Student class looks like this:
class Student{
private String name;
private String id;
private String email;
public String getName() {
return name;
}
public void setId(String id) {
this.id = id;
}
public void setEmail(String email) {
this.email = email;
}
public void anothermethod(){ }
......
......
some more methods
......
}
You have to print all the methods of the student class in alphabetical order like this:
anothermethod
getName
setEmail
setId
......
......
some more methods
......
There is no sample input/output for this problem. If you press “Run Code”, it will compile it, but it won’t show any outputs.
Hint: See the oracle docs for more details about JAVA Reflection Methods and Fields
Solution:
class Student { private String name; private String id; private String email; public String getName() { return name; } public void setId(String id) { this.id = id; } public void setEmail(String email) { this.email = email; } public void anothermethod() { } } public class JavaReflectionAttributes { public static void main(String[] args) { Class student = new Student().getClass(); Method[] methods = student.getDeclaredMethods(); ArrayList<String> methodList = new ArrayList<>(); for (Method m : methods) { methodList.add(m.getName()); } Collections.sort(methodList); for (String name : methodList) { System.out.println(name); } } }
53. Challenge : Can you Access?
You are given a class Solution and an inner class Inner.Private. The main method of class Solution takes an integer num as input. The powerof2 in class Inner.Private checks whether a number is a power of 2. You have to call the method powerof2 of the class Inner.Private from the main method of the class Solution.
Constraints
1 ≤ num ≤ 230
Sample Input
8
Sample Output
8 is power of 2 An instance of class: Solution.Inner.Private has been created
Solution:
public class CanYouAccess { public static void main(String[] args) throws Exception { DoNotTerminate.forbidExit(); try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int num = Integer.parseInt(br.readLine().trim()); Object o;// Must be used to hold the reference of the instance of the class // Solution.Inner.Private // Inner i= new Inner(); // Private p=new Private(); /**main code starts from here*/ CanYouAccess.Inner si = new CanYouAccess.Inner(); o = si.new Private(); System.out.println(num + " is " + ((CanYouAccess.Inner.Private) o).powerof2(num)); /**main code end here*/ System.out.println("An instance of class: " + o.getClass().getCanonicalName() + " has been created"); } // end of try catch (DoNotTerminate.ExitTrappedException e) { System.out.println("Unsuccessful Termination!!"); } }// end of main static class Inner { private class Private { private String powerof2(int num) { return ((num & num - 1) == 0) ? "power of 2" : "not a power of 2"; } } }// end of Inner }// end of Solution class DoNotTerminate { // This class prevents exit(0) public static class ExitTrappedException extends SecurityException { private static final long serialVersionUID = 1L; } public static void forbidExit() { final SecurityManager securityManager = new SecurityManager() { @Override public void checkPermission(Permission permission) { if (permission.getName().contains("exitVM")) { throw new ExitTrappedException(); } } }; System.setSecurityManager(securityManager); } }
54. Challenge : Java Factory Pattern
According to Wikipedia, a factory is simply an object that returns another object from some other method call, which is assumed to be “new”.
In this problem, you are given an interface Food. There are two classes Pizza and Cake which implement the Food interface, and they both contain a method getType().
The main function in the Main class creates an instance of the FoodFactory class. The FoodFactory class contains a method getFood(String) that returns a new instance of Pizza or Cake according to its parameter.
You are given the partially completed code in the editor. Please complete the FoodFactory class.
Sample Input 1
cake
Sample Output 1
The factory returned class Cake
Someone ordered a Dessert!
Sample Input 2
pizza
Sample Output 2
The factory returned class Pizza Someone ordered Fast Food!
Solution:
interface Food { public String getType(); } class Pizza implements Food { public String getType() { return "Someone ordered a Fast Food!"; } } class Cake implements Food { public String getType() { return "Someone ordered a Dessert!"; } } class FoodFactory { public Food getFood(String order) { /** * main code starts from here */ if (order.equalsIgnoreCase("Pizza")) { return new Pizza(); } else if (order.equalsIgnoreCase("Cake")) { return new Cake(); } return null; /** main code end herer */ }// End of getFood method }// End of factory class public class JavaFactoryPattern { public static void main(String args[]) { Do_Not_Terminate.forbidExit(); Scanner sc = null; try { sc = new Scanner(System.in); // creating the factory FoodFactory foodFactory = new FoodFactory(); // factory instantiates an object Food food = foodFactory.getFood(sc.nextLine()); System.out.println("The factory returned " + food.getClass()); System.out.println(food.getType()); } catch (Do_Not_Terminate.ExitTrappedException e) { System.out.println("Unsuccessful Termination!!"); } finally { sc.close(); } } } class Do_Not_Terminate { public static class ExitTrappedException extends SecurityException { private static final long serialVersionUID = 1L; } public static void forbidExit() { final SecurityManager securityManager = new SecurityManager() { @Override public void checkPermission(Permission permission) { if (permission.getName().contains("exitVM")) { throw new ExitTrappedException(); } } }; System.setSecurityManager(securityManager); } }
55. Challenge : Java Singleton Pattern
“The singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.”
– Wikipedia: Singleton Pattern
Complete the Singleton class in your editor which contains the following components:
- A private Singleton non parameterized constructor.
- A public String instance variable named .
- Write a static method named getSingleInstance that returns the single instance of the Singleton class.
Once submitted, our hidden Solution class will check your code by taking a String as input and then using your Singleton class to print a line.
Input Format
You will not be handling any input in this challenge.
Output Format
You will not be producing any output in this challenge.
Sample Input
hello world
Sample Output
Hello I am a singleton! Let me say hello world to you
Solution:
public class JavaSingletonPattern { public String str = ""; private static final JavaSingletonPattern instance=null; private JavaSingletonPattern() { } public static JavaSingletonPattern getSingleInstance() { if (instance == null) return new JavaSingletonPattern(); return instance; } }
56. Challenge : Covariant Return Types
Java allows for Covariant Return Types, which means you can vary your return type as long you are returning a subclass of your specified return type.
Method Overriding allows a subclass to override the behavior of an existing superclass method and specify a return type that is some subclass of the original return type. It is best practice to use the @Override
annotation when overriding a superclass method.
Implement the classes and methods detailed in the diagram below:
You will be given a partially completed code in the editor where the main method takes the name of a state (i.e., WestBengal
, or AndhraPradesh
) and prints the national flower of that state using the classes and methods written by you.
Note: Do not use access modifiers in your class declarations.
Resources
Covariant Return Type
Java Covariant Type
Input Format
The locked code reads a single string denoting the name of a subclass of State (i.e., WestBengal
, Karnataka
, or AndhraPradesh
), then tests the methods associated with that subclass. You are not responsible for reading any input from stdin.
Output Format
Output is handled for you by the locked code, which creates the object corresponding to the input string’s class name and then prints the name returned by that class’ national flower’s whatsYourName method. You are not responsible for printing anything to stdout.
Sample Input 0
AndhraPradesh
Sample Output 0
Lily
Solution:
public class CovariantReturnTypes { /** * main code starts from here** */ class Flower{ public String whatsYourName(){ return "I have many names and types."; } } class Jasmine extends Flower{ public String whatsYourName(){ return "Jasmine"; } } class Lily extends Flower{ public String whatsYourName(){ return "Lily"; } } class Lotus extends Flower{ public String whatsYourName(){ return "Lotus"; } } class State{ Flower yourNationalFlower(){ return new Flower(); } } class WestBengal extends State{ Jasmine yourNationalFlower(){ return new Jasmine(); } } class Karnataka extends State{ Lotus yourNationalFlower(){ return new Lotus(); } } class AndhraPradesh extends State{ Lily yourNationalFlower(){ return new Lily(); } /** * main code ends here */ } }
57. Challenge : Prime Checker
You are given a class Solution and its main method in the editor. Your task is to create a class Prime. The class Prime should contain a single method checkPrime.
The locked code in the editor will call the checkPrime method with one or more integer arguments. You should write the checkPrime method in such a way that the code prints only the prime numbers.
Please read the code given in the editor carefully. Also please do not use method overloading!
Note: You may get a compile time error in this problem due to the statement below:
BufferedReader br=new BufferedReader(new InputStreamReader(in));
This was added intentionally, and you have to figure out a way to get rid of the error.
Input Format
There are only five lines of input, each containing one integer.
Output Format
There will be only four lines of output. Each line contains only prime numbers depending upon the parameters passed to checkPrime in the main method of the class Solution. In case there is no prime number, then a blank line should be printed.
Sample Input
2
1
3
4
5
Sample Output
2 2 2 3 2 3 5
Solution:
public class PrimeChecker { public void checkPrime(int... num) { String str = ""; for (int n : num) { boolean found = true; if (n <= 3 && n > 1) { str += n + " "; } else { for (int i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) { found = false; break; } } if (found && n != 1) { str += n + " "; } } } System.out.println(str); } }
58. Challenge : Java Annotations
Java annotation can be used to define the metadata of a Java class or class element. We can use Java annotation at the compile time to instruct the compiler about the build process. Annotation is also used at runtime to get insight into the properties of class elements.
Java annotation can be added to an element in the following way:
@Entity
Class DemoClass{
}
We can also set a value to the annotation member. For example:
@Entity(EntityName="DemoClass")
Class DemoClass{
}
In Java, there are several built-in annotations. You can also define your own annotations in the following way:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface FamilyBudget {
String userRole() default "GUEST";
}
Here, we define an annotation FamilyBudget, where userRole is the only member in that custom annotation. The userRole takes only String type values, and the default is “GUEST”. If we do not define the value for this annotation member, then it takes the default. By using @Target, we can specify where our annotation can be used. For example, the FamilyBudget annotation can only be used with the method in a class. @Retention defines whether the annotation is available at runtime. To learn more about Java annotation, you can read the tutorial and oracle docs.
Take a look at the following code segment:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface FamilyBudget {
String userRole() default "GUEST";
}
class FamilyMember {
public void seniorMember(int budget, int moneySpend) {
System.out.println("Senior Member");
System.out.println("Spend: " + moneySpend);
System.out.println("Budget Left: " + (budget - moneySpend));
}
public void juniorUser(int budget, int moneySpend) {
System.out.println("Junior Member");
System.out.println("Spend: " + moneySpend);
System.out.println("Budget Left: " + (budget - moneySpend));
}
}
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int testCases = Integer.parseInt(in.nextLine());
while (testCases > 0) {
String role = in.next();
int spend = in.nextInt();
try {
Class annotatedClass = FamilyMember.class;
Method[] methods = annotatedClass.getMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(FamilyBudget.class)) {
FamilyBudget family = method
.getAnnotation(FamilyBudget.class);
String userRole = family.userRole();
int budgetLimit = family.budgetLimit();
if (userRole.equals(role)) {
if(spend<=budgetLimit){
method.invoke(FamilyMember.class.newInstance(),
budgetLimit, spend);
}else{
System.out.println("Budget Limit Over");
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
testCases--;
}
}
}
Here, we partially define an annotation,FamilyBudget and a class, FamilyMember. In this problem, we give the user role and the amount of money that a user spends as inputs. Based on the user role, you have to call the appropriate method in the FamilyMember class. If the amount of money spent is over the budget limit for that user role, it prints Budget Limit Over
.
Your task is to complete the FamilyBudget annotation and the FamilyMember class so that the Solution class works perfectly with the defined constraints.
Note: You must complete the 5 incomplete lines in the editor. You are not allowed to change, delete or modify any other lines. To restore the original code, click on the top-left button on the editor and create a new buffer.
Input Format
The first line of input contains an integer N representing the total number of test cases. Each test case contains a string and an integer separated by a space on a single line in the following format:
UserRole MoneySpend
Constraints
2 ≤ N ≤ 10
0 ≤ MoneySpend ≤ 200
|UserRole| = 6
Name contains only lowercase English letters.
Output Format
Based on the user role and budget outputs, output the contents of the certain method. If the amount of money spent is over the budget limit, then output Budget Limit Over
.
Sample Input
3
SENIOR 75
JUNIOR 45
SENIOR 40
Sample Output
Senior Member Spend: 75 Budget Left: 25 Junior Member Spend: 45 Budget Left: 5 Senior Member Spend: 40 Budget Left: 60
Solution:
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @interface FamilyBudget { String userRole() default "GUEST"; int moneySpend() default 100; } class FamilyMember { @FamilyBudget(userRole = "SENIOR") public void seniorMember(int budget, int moneySpend) { System.out.println("Senior Member"); System.out.println("Spend: " + moneySpend); System.out.println("Budget Left: " + (budget - moneySpend)); } @FamilyBudget(userRole = "JUNIOR", moneySpend = 50) public void juniorUser(int budget, int moneySpend) { System.out.println("Junior Member"); System.out.println("Spend: " + moneySpend); System.out.println("Budget Left: " + (budget - moneySpend)); } } public class JavaAnnotations { public static void main(String[] args) { Scanner in = new Scanner(System.in); int testCases = Integer.parseInt(in.nextLine()); while (testCases > 0) { String role = in.next(); int spend = in.nextInt(); try { Class annotatedClass = FamilyMember.class; Method[] methods = annotatedClass.getMethods(); for (Method method : methods) { if (method.isAnnotationPresent(FamilyBudget.class)) { FamilyBudget family = method.getAnnotation(FamilyBudget.class); String userRole = family.userRole(); int budgetLimit = family.moneySpend(); if (userRole.equals(role)) { if (budgetLimit >= spend) { method.invoke(FamilyMember.class.newInstance(), budgetLimit, spend); } else { System.out.println("Budget Limit Over"); } } } } } catch (Exception e) { e.printStackTrace(); } testCases--; } in.close(); } }
59. Challenge : Java Lambda Expressions
This Java 8 challenge tests your knowledge of Lambda expressions!
Write the following methods that return a lambda expression performing a specified action:
- PerformOperation isOdd(): The lambda expression must return true if a number is odd or false if it is even.
- PerformOperation isPrime(): The lambda expression must return true if a number is prime or false if it is composite.
- PerformOperation isPalindrome(): The lambda expression must return true if a number is a palindrome or false if it is not.
Input Format
Input is handled for you by the locked stub code in your editor.
Output Format
The locked stub code in your editor will print T lines of output.
Sample Input
The first line contains an integer, T (the number of test cases).
The T subsequent lines each describe a test case in the form of 2 space-separated integers:
The first integer specifies the condition to check for (1 for Odd/Even,2 for Prime, or 3 for Palindrome). The second integer denotes the number to be checked.
5
1 4
2 5
3 898
1 3
2 12
Sample Output
EVEN PRIME PALINDROME ODD COMPOSITE
Solution:
interface PerformOperation { boolean check(int a); } class MyMath { public static boolean checker(PerformOperation p, int num) { return p.check(num); } // Write your code here public static PerformOperation isOdd() { return n -> ((n & 1) == 1); } public static PerformOperation isPrime() { return n -> { if (n < 2) { return false; } else { int k = (int) Math.sqrt(n); for (int i = 2; i <= k; i++) { if (n % i == 0) return false; } return true; } }; } public static PerformOperation isPalindrome() { return n -> { String org = n + ""; String newString = new StringBuffer(org).reverse().toString(); return org.equals(newString); }; } } public class JavaLambdaExpressions { public static void main(String[] args) throws IOException { MyMath ob = new MyMath(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine()); PerformOperation op; boolean ret = false; String ans = null; while (T-- > 0) { String s = br.readLine().trim(); StringTokenizer st = new StringTokenizer(s); int ch = Integer.parseInt(st.nextToken()); int num = Integer.parseInt(st.nextToken()); if (ch == 1) { op = ob.isOdd(); ret = ob.checker(op, num); ans = (ret) ? "ODD" : "EVEN"; } else if (ch == 2) { op = ob.isPrime(); ret = ob.checker(op, num); ans = (ret) ? "PRIME" : "COMPOSITE"; } else if (ch == 3) { op = ob.isPalindrome(); ret = ob.checker(op, num); ans = (ret) ? "PALINDROME" : "NOT PALINDROME"; } System.out.println(ans); } } }
60. Challenge : Java MD5
MD5 (Message-Digest algorithm 5) is a widely-used cryptographic hash function with a 128-bit hash value. Here are some common uses for MD5:
- To store a one-way hash of a password.
- To provide some assurance that a transferred file has arrived intact.
MD5 is one in a series of message digest algorithms designed by Professor Ronald Rivest of MIT (Rivest, 1994); however, the security of MD5 has been severely compromised, most infamously by the Flame malware in 2012. The CMU Software Engineering Institute essentially considers MD5 to be “cryptographically broken and unsuitable for further use”.
Given an alphanumeric string, s, denoting a password, compute and print its MD5 encryption value.
Input Format
A single alphanumeric string denoting s.
Constraints
-
6 ≤ |s| ≤ 20
- String s consists of English alphabetic letters (i.e., [a – zA – Z] and/or decimal digits (i.e., 0 through 9) only.
Output Format
Print the MD5 encryption value of s on a new line.
Sample Input 0
HelloWorld
Sample Output 0
68e109f0f40ca72a15e05cc22786f8e6
Sample Input 1
Javarmi123
Sample Output 1
2da2d1e0ce7b4951a858ed2d547ef485
Solution:
public class JavaMD5 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); System.out.println(getMD5(s)); sc.close(); } private static String getMD5(String s) { StringBuffer sb = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] result = md.digest(s.getBytes()); for (int i = 0; i < result.length; i++) { String hex = Integer.toHexString(0xff & result[i]); if (hex.length() == 1) sb.append('0'); sb.append(hex); } } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sb.toString(); } }
61. Challenge : Java SHA-256
Cryptographic hash functions are mathematical operations run on digital data; by comparing the computed hash (i.e., the output produced by executing a hashing algorithm) to a known and expected hash value, a person can determine the data’s integrity. For example, computing the hash of a downloaded file and comparing the result to a previously published hash result can show whether the download has been modified or tampered with. In addition, cryptographic hash functions are extremely collision-resistant; in other words, it should be extremely difficult to produce the same hash output from two different input values using a cryptographic hash function.
Secure Hash Algorithm 2 (SHA-2) is a set of cryptographic hash functions designed by the National Security Agency (NSA). It consists of six identical hashing algorithms (i.e., SHA-256, SHA-512, SHA-224, SHA-384, SHA-512/224, SHA-512/256) with a variable digest size. SHA-256 is a 256-bit (32 byte) hashing algorithm which can calculate a hash code for an input of up to 264 – 1 bits. It undergoes 64 rounds of hashing and calculates a hash code that is a 64 -digit hexadecimal number.
Given a string, s, print its SHA-256 hash value.
Input Format
A single alphanumeric string denoting s.
Constraints
-
6 ≤ |s| ≤ 20
- String s consists of English alphabetic letters (i.e., [a – zA – Z] and/or decimal digits (i.e., 0 through 9) only.
Output Format
Print the SHA-256 encryption value of s on a new line.
Sample Input 0
HelloWorld
Sample Output 0
872e4e50ce9990d8b041330c47c9ddd11bec6b503ae9386a99da8584e9bb12c4
Sample Input 1
Javarmi123
Sample Output 1
f1d5f8d75bb55c777207c251d07d9091dc10fe7d6682db869106aacb4b7df678
Solution:
public class JavaSHA256 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); System.out.println(getSHAHEX(s)); sc.close(); } private static String getSHAHEX(String s) { StringBuffer sb = new StringBuffer(); try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] result = digest.digest(s.getBytes()); for (int i = 0; i < result.length; i++) { String hex = Integer.toHexString(0xff & result[i]); if (hex.length() == 1) sb.append('0'); sb.append(hex); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return sb.toString(); } }
62. Challenge : Java Visitor Pattern
Note: In this problem you must NOT generate any output on your own. Any such solution will be considered as being against the rules and its author will be disqualified. The output of your solution must be generated by the uneditable code provided for you in the solution template.
An important concept in Object-Oriented Programming is the open/closed principle, which means writing code that is open to extension but closed to modification. In other words, new functionality should be added by writing an extension for the existing code rather than modifying it and potentially breaking other code that uses it. This challenge simulates a real-life problem where the open/closed principle can and should be applied.
A Tree class implementing a rooted tree is provided in the editor. It has the following publicly available methods:
getValue()
: Returns the value stored in the node.getColor()
: Returns the color of the node.getDepth()
: Returns the depth of the node. Recall that the depth of a node is the number of edges between the node and the tree’s root, so the tree’s root has depth 0 and each descendant node’s depth is equal to the depth of its parent node +1.
In this challenge, we treat the internal implementation of the tree as being closed to modification, so we cannot directly modify it; however, as with real-world situations, the implementation is written in such a way that it allows external classes to extend and build upon its functionality. More specifically, it allows objects of the TreeVis class (a Visitor Design Pattern) to visit the tree and traverse the tree structure via the accept
method.
There are two parts to this challenge.
Part I: Implement Three Different Visitors
Each class has three methods you must write implementations for:
-
getResult()
: Return an integer denoting the result, which is different for each class:- The SumInLeavesVisitor implementation must return the sum of the values in the tree’s leaves only.
- The ProductRedNodesVisitor implementation must return the product of values stored in all red nodes, including leaves, computed modulo 109 + 7. Note that the product of zero values is equal to 1.
- The FancyVisitor implementation must return the absolute difference between the sum of values stored in the tree’s non-leaf nodes at even depth and the sum of values stored in the tree’s green leaf nodes. Recall that zero is an even number.
-
visitNode(TreeNode node)
: Implement the logic responsible for visiting the tree’s non-leaf nodes such that the getResultmethod returns the correct result for the implementing class’ visitor. visitLeaf(TreeLeaf leaf)
: Implement the logic responsible for visiting the tree’s leaf nodes such that the getResultmethod returns the correct result for the implementing class’ visitor.
Part II: Read and Build the Tree
Read the n-node tree, where each node is numbered from 1 to n. The tree is given as a list of node values (), a list of node colors (), and a list of edges. Construct this tree as an instance of the Tree class. The tree is always rooted at node number .
Your implementations of the three visitor classes will be tested on the tree you built from the given input.
Input Format
The first line contains a single integer, , denoting the number of nodes in the tree. The second line contains space-separated integers describing the respective values of x1,x2,…,xn. The third line contains n space-separated binary integers describing the respective values of c1,c2,…,cn. Each ci denotes the color of the ith node, where 0 denotes red and 1 denotes green.
Each of the n – 1 subsequent lines contains two space-separated integers, ui and vi , describing an edge between nodes ui and vi .
Constraints
-
2 ≤ n ≤ 105
-
1 ≤ xi ≤ 103
-
ci ∈ {0,1}
-
1 ≤ vi,ui ≤ n
- It is guaranteed that the tree is rooted at node 1.
Output Format
Do not print anything to stdout, as this is handled by locked stub code in the editor. The three getResult()
methods provided for you must return an integer denoting the result for that class’ visitor (defined above). Note that the value returned by ProductRedNodesVisitor‘s getResult method must be computed modulo 109 + 7.
Sample Input
5
4 7 2 5 12
0 1 0 0 1
1 2
1 3
3 4
3 5
Sample Output
24 40 15
Solution:
enum Color { RED, GREEN } abstract class Tree { private int value; private Color color; private int depth; public Tree(int value, Color color, int depth) { this.value = value; this.color = color; this.depth = depth; } public int getValue() { return value; } public Color getColor() { return color; } public int getDepth() { return depth; } public abstract void accept(TreeVis visitor); } class TreeNode extends Tree { private ArrayList<Tree> children = new ArrayList<>(); public TreeNode(int value, Color color, int depth) { super(value, color, depth); } public void accept(TreeVis visitor) { visitor.visitNode(this); for (Tree child : children) { child.accept(visitor); } } public void addChild(Tree child) { children.add(child); } } class TreeLeaf extends Tree { public TreeLeaf(int value, Color color, int depth) { super(value, color, depth); } public void accept(TreeVis visitor) { visitor.visitLeaf(this); } } abstract class TreeVis { public abstract int getResult(); public abstract void visitNode(TreeNode node); public abstract void visitLeaf(TreeLeaf leaf); } class SumInLeavesVisitor extends TreeVis { private int result = 0; public int getResult() { return result; } public void visitNode(TreeNode node) { // do nothing } public void visitLeaf(TreeLeaf leaf) { result += leaf.getValue(); } } class ProductOfRedNodesVisitor extends TreeVis { private long result = 1; private final int M = 1000000007; public int getResult() { return (int) result; } public void visitNode(TreeNode node) { if (node.getColor() == Color.RED) { result = (result * node.getValue()) % M; } } public void visitLeaf(TreeLeaf leaf) { if (leaf.getColor() == Color.RED) { result = (result * leaf.getValue()) % M; } } } class FancyVisitor extends TreeVis { private int nonLeafEvenDepthSum = 0; private int greenLeavesSum = 0; public int getResult() { return Math.abs(nonLeafEvenDepthSum - greenLeavesSum); } public void visitNode(TreeNode node) { if (node.getDepth() % 2 == 0) { nonLeafEvenDepthSum += node.getValue(); } } public void visitLeaf(TreeLeaf leaf) { if (leaf.getColor() == Color.GREEN) { greenLeavesSum += leaf.getValue(); } } } public class JavaVisitorPattern { static int[] values; static Color[] colors; static ArrayList<Integer>[] edges; // each edges[i] holds arrayList of all nodes connnected to node i @SuppressWarnings("unchecked") public static Tree solve() { int n; TreeNode root; Scanner sc = new Scanner(System.in); n = sc.nextInt(); values = new int[n]; colors = new Color[n]; for (int i = 0; i < n; i++) values[i] = sc.nextInt(); for (int i = 0; i < n; i++) colors[i] = sc.nextInt() == 0 ? Color.RED : Color.GREEN; // initialize arraylists edges = (ArrayList<Integer>[]) new ArrayList[n + 1]; for (int i = 1; i <= n; i++) edges[i] = new ArrayList<Integer>(); // read the n- 1 edges and store them in both directions for (int i = 0; i < n - 1; i++) { int edgeNode1 = sc.nextInt(); int edgeNode2 = sc.nextInt(); edges[edgeNode1].add(edgeNode2); edges[edgeNode2].add(edgeNode1); } sc.close(); root = new TreeNode(values[0], colors[0], 0); // root is always internal addChildren(root, 1); return root; } public static void addChildren(Tree node, Integer nodeNumber) { // for all edges coming out of this node for (Integer otherNodeNumber : edges[nodeNumber]) { Tree otherNode; if (edges[otherNodeNumber].size() > 1) // new internal node otherNode = new TreeNode(values[otherNodeNumber - 1], colors[otherNodeNumber - 1], node.getDepth() + 1); else // new leaf otherNode = new TreeLeaf(values[otherNodeNumber - 1], colors[otherNodeNumber - 1], node.getDepth() + 1); ((TreeNode) node).addChild(otherNode); edges[otherNodeNumber].remove(nodeNumber); // remove reverse edge if (otherNode instanceof TreeNode) addChildren(otherNode, otherNodeNumber); } } public static void main(String[] args) { Tree root = solve(); SumInLeavesVisitor vis1 = new SumInLeavesVisitor(); ProductOfRedNodesVisitor vis2 = new ProductOfRedNodesVisitor(); FancyVisitor vis3 = new FancyVisitor(); root.accept(vis1); root.accept(vis2); root.accept(vis3); int res1 = vis1.getResult(); int res2 = vis2.getResult(); int res3 = vis3.getResult(); System.out.println(res1); System.out.println(res2); System.out.println(res3); } }
Responses