HSE HackerRank Coding Patterns
HSE (HackerRank Software Engineering Assessment) is one of the toughest ILP exams — conducted on the HackerRank platform. REST APIs and Java coding are known to be important. Exact format may vary by batch. This page gives you coding templates and patterns to prepare.
- Ready-to-paste Java templates for every input pattern
- The Scanner trap that catches 80% of students
- Type conversion cheat sheet (always needed)
- Output formatting for exact decimal precision
- 10 full practice problems with complete solutions
1. How HackerRank Works
HackerRank runs your Java code against multiple hidden test cases. Your job is simple:
| Step | What You Do |
|---|---|
| 1. Read | Read input from stdin using Scanner |
| 2. Process | Apply the logic to solve the problem |
| 3. Print | Print output to stdout using System.out.println() |
- Output must match EXACTLY — no extra spaces, no extra newlines, no debug prints
- Time limit: typically 2-10 seconds. Brute force may time out on large inputs
- Memory limit: typically 256 MB. Don't create unnecessary objects
- Class name must be
Solution— HackerRank expects this exact name - No package declaration — do NOT write
packageat the top - Remove all debug prints before submitting — any extra output fails the test
2. HackerRank Java Template (MEMORIZE THIS)
This is the skeleton you type first for every HSE problem. Memorize it cold.
import java.util.*; import java.io.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // Step 1: Read input // Step 2: Process / solve // Step 3: Print output sc.close(); } }
Solution (capital S). Not Main, not solution, not your name. HackerRank won't compile otherwise.
java.util.* gives you Scanner, ArrayList, HashMap, Arrays, Collections — everything you'll need. java.io.* gives you BufferedReader and I/O classes for the API/JSON pattern. Just always import both. No penalty for unused imports.
3. Input Reading Patterns (CRITICAL)
This section alone will save you from 80% of HSE failures. Most students know the logic but can't read input correctly.
Read a Single Integer
int n = sc.nextInt();
Read a Single Long
long n = sc.nextLong();
Read a Single Double
double d = sc.nextDouble();
Read a Single Word (no spaces)
String word = sc.next(); // reads until whitespace
Read an Entire Line (with spaces)
String line = sc.nextLine(); // reads entire line including spaces
When you call nextInt(), it reads the number but leaves the newline character (\n) in the buffer. If you then call nextLine(), it reads that leftover newline — giving you an empty string!
// BROKEN — nextLine() reads the leftover \n int n = sc.nextInt(); String name = sc.nextLine(); // name = "" (empty!) // FIXED — consume the leftover \n first int n = sc.nextInt(); sc.nextLine(); // eat the leftover newline String name = sc.nextLine(); // now reads correctly
Rule: After EVERY nextInt(), nextDouble(), or next() that's followed by nextLine(), add a dummy sc.nextLine(); to consume the leftover newline.
Read N Integers into an Array
int n = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); }
Read a Line of Space-Separated Integers
String line = sc.nextLine(); String[] parts = line.split(" "); int[] arr = new int[parts.length]; for (int i = 0; i < parts.length; i++) { arr[i] = Integer.parseInt(parts[i]); }
Read Multiple Lines of Input
int n = sc.nextInt(); sc.nextLine(); // consume leftover newline! String[] lines = new String[n]; for (int i = 0; i < n; i++) { lines[i] = sc.nextLine(); }
Read Until End of File (EOF)
while (sc.hasNext()) { String line = sc.nextLine(); // process each line } // Or for integers: while (sc.hasNextInt()) { int num = sc.nextInt(); // process each number }
Input format: First line has N (number of students). Next N lines each have a name and a score separated by space.
// Input: // 3 // Alice 85 // Bob 92 // Charlie 78 int n = sc.nextInt(); sc.nextLine(); // consume newline after the integer! for (int i = 0; i < n; i++) { String line = sc.nextLine(); String[] parts = line.split(" "); String name = parts[0]; int score = Integer.parseInt(parts[1]); }
4. Type Conversion Patterns (Always Needed)
Almost every HSE problem requires converting between types. Memorize these — you'll use them every single time.
| Conversion | Code | Watch Out |
|---|---|---|
| String → int | Integer.parseInt(str) | Throws NumberFormatException if str is not a valid number |
| String → double | Double.parseDouble(str) | Same — throws exception on invalid input |
| String → long | Long.parseLong(str) | Use for large numbers that overflow int |
| int → String | String.valueOf(n) | Also works: Integer.toString(n) or "" + n |
| double → int | (int) doubleVal | TRUNCATES! 3.9 → 3, not 4. Use Math.round() to round. |
| int → double | (double) intVal | Or just use in a double expression: intVal * 1.0 |
| char → int (digit) | ch - '0' | '5' - '0' = 5. Only works for digit chars '0'-'9' |
| int → char (digit) | (char) (n + '0') | 5 + '0' = '5'. Only for single digits 0-9 |
| char → int (ASCII) | (int) ch | 'A' = 65, 'a' = 97, '0' = 48 |
| String → char[] | str.toCharArray() | Returns a new array — modifying it doesn't change the original String |
| char[] → String | new String(charArr) | Also: String.valueOf(charArr) |
double d = 3.99; int i = (int) d; // i = 3 (TRUNCATED, not rounded!) int j = (int) Math.round(d); // j = 4 (rounded correctly)
If the problem says "round to nearest integer", use Math.round(). If it says "floor" or just cast, use (int).
int a = 7, b = 2; System.out.println(a / b); // prints 3 (NOT 3.5!) System.out.println((double) a / b); // prints 3.5 (correct) System.out.println(a * 1.0 / b); // prints 3.5 (also correct)
Rule: When you need decimal results from integer division, cast at least one operand to double BEFORE dividing.
5. Floating Point Precision (Frequently Tested)
Many HSE problems ask you to print results to a specific number of decimal places. Get this wrong and every test case fails.
Method 1: String.format() — RECOMMENDED
double value = 3.14159265; String result = String.format("%.2f", value); // "3.14" System.out.println(result);
Method 2: System.out.printf()
double value = 3.14159265; System.out.printf("%.2f%n", value); // prints 3.14 System.out.printf("%.4f%n", value); // prints 3.1416 (rounds!)
Method 3: Math.round() for manual rounding
double value = 3.14159; double rounded = Math.round(value * 100.0) / 100.0; // 3.14
| Format | Input: 3.14159 | Output |
|---|---|---|
%.1f | 3.14159 | 3.1 |
%.2f | 3.14159 | 3.14 |
%.3f | 3.14159 | 3.142 |
%.4f | 3.14159 | 3.1416 |
%d | (int) 42 | 42 |
%s | "hello" | hello |
%n is platform-independent newline. \n may cause issues on some systems. In HackerRank, both usually work — but %n is safer.
6. String Manipulation Patterns
String problems are the most common in HSE. Know these methods cold.
| Operation | Code | Returns |
|---|---|---|
| Length | str.length() | int — number of characters |
| Get char at index | str.charAt(i) | char at position i (0-based) |
| Substring | str.substring(start, end) | Characters from start to end-1 (end is exclusive!) |
| Uppercase | str.toUpperCase() | New string, all uppercase |
| Lowercase | str.toLowerCase() | New string, all lowercase |
| Trim spaces | str.trim() | Removes leading/trailing whitespace only |
| Remove all spaces | str.replaceAll("\\s+", "") | Removes ALL whitespace |
| Split | str.split(" ") | String[] array split by delimiter |
| Join | String.join(", ", arr) | Joins array with delimiter |
| Contains | str.contains("sub") | boolean |
| Starts with | str.startsWith("pre") | boolean |
| Index of | str.indexOf("sub") | int (-1 if not found) |
| Replace | str.replace("old", "new") | New string with replacements |
| Equals (case-sensitive) | str1.equals(str2) | boolean |
| Equals (ignore case) | str1.equalsIgnoreCase(str2) | boolean |
Reverse a String
String reversed = new StringBuilder(str).reverse().toString();
Check Palindrome
String clean = str.toLowerCase().replaceAll("[^a-z0-9]", ""); String reversed = new StringBuilder(clean).reverse().toString(); boolean isPalindrome = clean.equals(reversed);
Count Character Occurrences
int count = 0; for (char c : str.toCharArray()) { if (c == target) count++; }
Count Vowels
int vowels = 0; for (char c : str.toLowerCase().toCharArray()) { if ("aeiou".indexOf(c) != -1) vowels++; }
String a = new String("hello"); String b = new String("hello"); System.out.println(a == b); // false (compares references!) System.out.println(a.equals(b)); // true (compares content)
ALWAYS use .equals() for String comparison. == checks if they're the same object in memory, not the same text.
7. Array Patterns
Find Maximum
int max = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] > max) max = arr[i]; }
Find Minimum
int min = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] < min) min = arr[i]; }
Sum of Array
int sum = 0; for (int num : arr) { sum += num; }
Average of Array
double avg = 0; for (int num : arr) avg += num; avg /= arr.length; // avg is double, so no integer division issue
Reverse an Array
for (int i = 0, j = arr.length - 1; i < j; i++, j--) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }
Sort an Array
Arrays.sort(arr); // ascending order // For descending, sort then reverse — or use Integer[] with Comparator: Integer[] boxed = Arrays.stream(arr).boxed().toArray(Integer[]::new); Arrays.sort(boxed, Collections.reverseOrder());
Find Second Largest (Single Pass)
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE; for (int num : arr) { if (num > first) { second = first; first = num; } else if (num > second && num != first) { second = num; } }
Remove Duplicates (Using HashSet)
Set<Integer> unique = new LinkedHashSet<>(); for (int num : arr) unique.add(num); // unique now contains only distinct values in insertion order
8. Common Problem Types in HSE
Almost every HSE problem falls into one of these categories. Know the template for each.
- String Processing — transform, count, validate, extract from strings
- Array/Number Processing — find patterns, compute results from arrays
- JSON/API Processing — fetch data from URL, parse JSON, extract fields
- Math Problems — factorial, fibonacci, primes, digit manipulation
Pattern 1: String Processing
Input is typically a string. You transform it, count characters, validate format, or extract parts.
// Template: Read string, process, print result Scanner sc = new Scanner(System.in); String input = sc.nextLine(); // Examples of what they ask: // - Count vowels/consonants // - Reverse words in a sentence // - Check if palindrome // - Check if two strings are anagrams // - Find longest word // - Remove duplicate characters
Pattern 2: Array/Number Processing
Input is N followed by N numbers. You compute something from the array.
// Template: Read array, process, print result Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); // Examples of what they ask: // - Find second largest // - Find pairs that sum to target // - Sort in custom order // - Find duplicates // - Compute running average
Pattern 3: Math Problems
// Factorial long factorial(int n) { long result = 1; for (int i = 2; i <= n; i++) result *= i; return result; } // Fibonacci (first N terms) int a = 0, b = 1; for (int i = 0; i < n; i++) { System.out.print(a + " "); int temp = a + b; a = b; b = temp; } // Prime check boolean isPrime(int n) { if (n < 2) return false; for (int i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) return false; } return true; } // GCD (Euclidean algorithm) int gcd(int a, int b) { while (b != 0) { int temp = b; b = a % b; a = temp; } return a; } // LCM int lcm(int a, int b) { return a / gcd(a, b) * b; // divide first to avoid overflow } // Sum of digits int sumOfDigits(int n) { int sum = 0; n = Math.abs(n); // handle negative while (n > 0) { sum += n % 10; n /= 10; } return sum; } // Reverse a number int reverseNumber(int n) { int rev = 0; while (n != 0) { rev = rev * 10 + n % 10; n /= 10; } return rev; }
9. JSON / API Processing (VERY IMPORTANT for HSE)
This pattern catches everyone off-guard. HSE can give you a URL and ask you to fetch data from an API, parse the JSON response, and extract specific fields. Here's the complete template.
Complete HTTP GET + JSON Parse Template
import java.util.*; import java.io.*; import java.net.*; public class Solution { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); String city = sc.nextLine().trim(); // Step 1: Build the URL String urlStr = "https://api.example.com/data?city=" + URLEncoder.encode(city, "UTF-8"); // Step 2: Make HTTP GET request URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); // Step 3: Read the response BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getInputStream()) ); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // Step 4: Parse JSON manually (no external library) String json = response.toString(); // Extract a simple field value from JSON // For {"name":"Alice","age":25} // Find "name":" int start = json.indexOf("\"name\":\"") + 8; int end = json.indexOf("\"", start); String name = json.substring(start, end); System.out.println(name); sc.close(); } }
HackerRank may or may not have org.json available. If it does, use JSONObject and JSONArray. If not, use manual string parsing with indexOf() and substring() as shown above.
If org.json IS Available (Easier)
import org.json.*; // Parse a JSON object JSONObject json = new JSONObject(response.toString()); String name = json.getString("name"); int age = json.getInt("age"); double score = json.getDouble("score"); // Parse a JSON array JSONArray items = json.getJSONArray("items"); for (int i = 0; i < items.length(); i++) { JSONObject item = items.getJSONObject(i); System.out.println(item.getString("title")); } // Handle nested objects JSONObject address = json.getJSONObject("address"); String street = address.getString("street"); // Handle pagination (common pattern) int page = 1; int totalPages = 1; while (page <= totalPages) { URL pageUrl = new URL(baseUrl + "&page=" + page); // ... fetch and parse ... totalPages = json.getInt("total_pages"); page++; }
10. Constructor Patterns (from FA, Tested in HSE)
Constructor questions in HSE usually appear as output prediction — they give you code with inheritance and constructors, and you predict what gets printed.
Key Rules
- If you don't write any constructor, Java adds a default no-arg constructor automatically
- If you write ANY constructor (even parameterized), Java does NOT add the default one
this()calls another constructor in the same class — must be the FIRST statementsuper()calls the parent constructor — must be the FIRST statement- If you don't write
super(), Java addssuper()(no-arg) automatically - Constructor calls go UP the chain (child → parent → grandparent) but EXECUTE top-down
Output Prediction Example
class Animal { Animal() { System.out.println("Animal"); } } class Dog extends Animal { Dog() { System.out.println("Dog"); } } class Puppy extends Dog { Puppy() { System.out.println("Puppy"); } } // new Puppy() prints: // Animal (grandparent first) // Dog (parent second) // Puppy (child last)
class Parent { Parent(int x) { System.out.println("Parent: " + x); } } class Child extends Parent { Child() { System.out.println("Child"); } // COMPILE ERROR! }
Parent has no no-arg constructor, but Child's constructor doesn't call super(value). Java tries to insert super() automatically — but there's no no-arg constructor in Parent. Compilation error.
11. Exception Handling Patterns
Basic try-catch
try { int result = Integer.parseInt("abc"); // throws NumberFormatException } catch (NumberFormatException e) { System.out.println("Invalid number: " + e.getMessage()); }
Multiple catch blocks (ORDER MATTERS)
try { int[] arr = {1, 2, 3}; System.out.println(arr[5]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Index out of range"); } catch (Exception e) { System.out.println("Some other error"); } // Specific exceptions MUST come BEFORE general ones // Putting Exception first = compile error (unreachable catch)
finally block
try { int x = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } finally { System.out.println("Always executes"); // ALWAYS runs }
finally block executes even if there's a return statement in try or catch. The only exception: System.exit(0) — that kills the JVM before finally runs.
| Exception | When It Happens |
|---|---|
NumberFormatException | Integer.parseInt("abc") |
ArrayIndexOutOfBoundsException | Accessing arr[10] when arr has 5 elements |
NullPointerException | Calling method on a null reference |
ArithmeticException | Division by zero (integer only — double gives Infinity) |
StringIndexOutOfBoundsException | str.charAt(100) when str has 5 chars |
ClassCastException | Invalid type casting |
StackOverflowError | Infinite recursion |
12. Collections Shortcuts
ArrayList
ArrayList<Integer> list = new ArrayList<>(); list.add(10); // add element list.add(0, 5); // insert at index 0 list.get(0); // get element at index → 5 list.set(0, 99); // replace element at index list.remove(0); // remove by index list.size(); // number of elements list.contains(10); // true/false Collections.sort(list); // sort ascending Collections.reverse(list); // reverse Collections.max(list); // maximum Collections.min(list); // minimum Collections.frequency(list, 10); // count of 10
HashMap
HashMap<String, Integer> map = new HashMap<>(); map.put("Alice", 90); // add key-value map.get("Alice"); // get value → 90 map.getOrDefault("Bob", 0); // get or return default map.containsKey("Alice"); // true map.containsValue(90); // true map.remove("Alice"); // remove entry map.size(); // number of entries // Iterate over entries for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } // Character frequency — MOST COMMON USE CASE HashMap<Character, Integer> freq = new HashMap<>(); for (char c : str.toCharArray()) { freq.put(c, freq.getOrDefault(c, 0) + 1); }
HashSet
HashSet<Integer> set = new HashSet<>(); set.add(10); // add (ignores duplicates) set.contains(10); // true set.remove(10); // remove set.size(); // count of unique elements
13. Output Formatting
| Method | Behavior | Use When |
|---|---|---|
System.out.println(x) | Prints x + newline | Most common — one result per line |
System.out.print(x) | Prints x, NO newline | Printing on the same line (space-separated output) |
System.out.printf() | Formatted print | Decimal precision, alignment, padding |
printf Format Specifiers
System.out.printf("Name: %s, Age: %d, GPA: %.2f%n", name, age, gpa); // %s → string // %d → integer (int, long) // %f → floating point (double, float) // %.2f → float with 2 decimal places // %n → platform-independent newline // %10d → right-align integer in 10-char width // %-10s → left-align string in 10-char width
Building Output with StringBuilder
// For multiple outputs, StringBuilder is faster than string concatenation StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb.append(arr[i]); if (i < n - 1) sb.append(" "); // no trailing space } System.out.println(sb.toString());
If the expected output is 1 2 3 and you print 1 2 3 (with trailing space) — it FAILS. Always handle the last element separately or use the if (i < n-1) check before adding separators.
14. Common Traps and Gotchas
| # | Trap | Fix |
|---|---|---|
| 1 | == vs .equals() for strings | ALWAYS use .equals() for string content comparison |
| 2 | Integer division: 7/2 = 3 | Cast to double: (double)7/2 = 3.5 |
| 3 | Scanner nextInt() + nextLine() | Add dummy sc.nextLine() after nextInt() |
| 4 | Array index starts at 0 | arr[0] is first, arr[n-1] is last |
| 5 | String is immutable | str.toUpperCase() returns NEW string — doesn't modify original |
| 6 | Off-by-one in loops | i < n runs n times (0 to n-1). i <= n runs n+1 times. |
| 7 | NullPointerException | Always check if (str != null) before calling methods on it |
| 8 | Trailing space/newline in output | No extra separators after last element |
| 9 | (int) 3.9 = 3 (truncation) | Use Math.round() if you need rounding |
| 10 | Overflow with int | Use long for factorial, large sums. int max is ~2.1 billion. |
→ HackerRank FA Subjective Mock Practice
15. 10 Practice Problems with Complete Solutions
These are the exact patterns that appear in TCS ILP exams. Type out each solution by hand at least once — don't just read them.
Problem 1: Average of N Numbers (2 Decimal Places)
Read an integer N, then read N integers. Print their average rounded to 2 decimal places.
Input:
5 10 20 30 40 50
Output:
30.00
import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int sum = 0; for (int i = 0; i < n; i++) { sum += sc.nextInt(); } double avg = (double) sum / n; System.out.printf("%.2f%n", avg); sc.close(); } }
Key patterns used: Reading N integers, integer-to-double cast for division, printf for 2 decimal places.
Problem 2: Palindrome Check (Case Insensitive)
Read a string and check if it's a palindrome (ignore case). Print "Yes" or "No".
Input:
RaceCar
Output:
Yes
import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine().toLowerCase(); String rev = new StringBuilder(str).reverse().toString(); System.out.println(str.equals(rev) ? "Yes" : "No"); sc.close(); } }
Key patterns used: toLowerCase() for case insensitivity, StringBuilder.reverse(), .equals() for comparison, ternary operator.
Problem 3: Character Frequency
Read a string and print the frequency of each character in order of first appearance. Format: char:count, one per line. Ignore spaces.
Input:
hello world
Output:
h:1 e:1 l:3 o:2 w:1 r:1 d:1
import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine().replaceAll("\\s+", ""); // LinkedHashMap preserves insertion order LinkedHashMap<Character, Integer> freq = new LinkedHashMap<>(); for (char c : str.toCharArray()) { freq.put(c, freq.getOrDefault(c, 0) + 1); } for (Map.Entry<Character, Integer> entry : freq.entrySet()) { System.out.println(entry.getKey() + ":" + entry.getValue()); } sc.close(); } }
Key patterns used: LinkedHashMap for ordered frequency counting, getOrDefault(), entrySet() iteration.
Problem 4: Second Largest in Array
Read N, then read N integers. Print the second largest number.
Input:
5 12 35 1 10 34
Output:
34
import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int first = Integer.MIN_VALUE; int second = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { int num = sc.nextInt(); if (num > first) { second = first; first = num; } else if (num > second && num != first) { second = num; } } System.out.println(second); sc.close(); } }
Key patterns used: Single-pass with two tracking variables, Integer.MIN_VALUE initialization, handling duplicates.
Problem 5: Reverse Words in a Sentence
Read a sentence and print it with words in reverse order.
Input:
Hello World Java
Output:
Java World Hello
import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String[] words = sc.nextLine().split(" "); StringBuilder sb = new StringBuilder(); for (int i = words.length - 1; i >= 0; i--) { sb.append(words[i]); if (i > 0) sb.append(" "); } System.out.println(sb.toString()); sc.close(); } }
Key patterns used: split() to tokenize, reverse iteration, StringBuilder for output, no trailing space.
Problem 6: JSON/API Data Extraction (Template)
Given a city name as input, fetch weather data from the API URL https://jsonmock.hackerrank.com/api/weather?name=CITY. Print the weather description from the response.
Response format: {"data":[{"name":"Dallas","weather":"12 degree","status":["Wind: 2Kmph"]}]}
Input:
Dallas
Output:
12 degree
import java.util.*; import java.io.*; import java.net.*; public class Solution { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); String city = sc.nextLine().trim(); // Build URL String urlStr = "https://jsonmock.hackerrank.com/api/weather?name=" + URLEncoder.encode(city, "UTF-8"); // Make HTTP request URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getInputStream()) ); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // Manual JSON parsing — extract "weather" value String json = response.toString(); String key = "\"weather\":\""; int start = json.indexOf(key) + key.length(); int end = json.indexOf("\"", start); String weather = json.substring(start, end); System.out.println(weather); sc.close(); } }
Key patterns used: HTTP GET with HttpURLConnection, BufferedReader for response, manual JSON parsing with indexOf + substring. This template works without any external JSON library.
Problem 7: Sum of Digits
Read an integer and print the sum of its digits. Handle negative numbers.
Input:
12345
Output:
15
import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = Math.abs(sc.nextInt()); int sum = 0; while (n > 0) { sum += n % 10; // get last digit n /= 10; // remove last digit } System.out.println(sum); sc.close(); } }
Key patterns used: % 10 to extract last digit, / 10 to remove it, Math.abs() for negative handling.
Problem 8: Anagram Check
Read two strings and check if they are anagrams (same characters, different order, case insensitive). Print "Anagrams" or "Not Anagrams".
Input:
Listen Silent
Output:
Anagrams
import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); char[] a = sc.nextLine().toLowerCase().toCharArray(); char[] b = sc.nextLine().toLowerCase().toCharArray(); Arrays.sort(a); Arrays.sort(b); if (Arrays.equals(a, b)) { System.out.println("Anagrams"); } else { System.out.println("Not Anagrams"); } sc.close(); } }
Key patterns used: Convert to char arrays, sort both, compare with Arrays.equals(). Sorting makes anagram check trivial.
Problem 9: Find Duplicates in Array
Read N integers and print the duplicate elements in the order they first repeat. If no duplicates, print "No duplicates".
Input:
7 4 2 7 2 4 9 7
Output:
2 4 7
import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); Set<Integer> seen = new HashSet<>(); Set<Integer> duplicates = new LinkedHashSet<>(); for (int i = 0; i < n; i++) { int num = sc.nextInt(); if (!seen.add(num)) { // add returns false if already exists duplicates.add(num); } } if (duplicates.isEmpty()) { System.out.println("No duplicates"); } else { StringBuilder sb = new StringBuilder(); for (int d : duplicates) { if (sb.length() > 0) sb.append(" "); sb.append(d); } System.out.println(sb.toString()); } sc.close(); } }
Key patterns used: HashSet.add() returns false for duplicates, LinkedHashSet preserves insertion order, StringBuilder for clean output.
Problem 10: Temperature Conversion
Read a temperature in Celsius (double). Convert to Fahrenheit using F = C * 9/5 + 32. Print the result to 2 decimal places.
Input:
36.5
Output:
97.70
import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); double celsius = sc.nextDouble(); double fahrenheit = celsius * 9.0 / 5.0 + 32; System.out.printf("%.2f%n", fahrenheit); sc.close(); } }
Key patterns used: 9.0/5.0 instead of 9/5 to avoid integer division, printf with %.2f for 2 decimal places.
Quick Reference: Copy-Paste Starters
import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); // solve here sc.close(); } }
import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); // solve here sc.close(); } }
import java.util.*; import java.io.*; import java.net.*; public class Solution { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); String input = sc.nextLine().trim(); URL url = new URL("https://api.example.com/data?q=" + input); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getInputStream())); StringBuilder resp = new StringBuilder(); String line; while ((line = reader.readLine()) != null) resp.append(line); reader.close(); String json = resp.toString(); // parse json and print result sc.close(); } }
- Class name is
Solution(capital S)? - No
packagedeclaration at the top? - No debug
System.out.println()left in the code? - Output format matches exactly (spaces, newlines, decimal places)?
- Did you handle the Scanner trap (
nextInt()beforenextLine())? - Using
(double)cast before division if you need decimal results? - No trailing space or extra newline in the output?
- Tested with the sample input and output matches?