DeltaX
• DeltaX Coding question
1 Function Optimization
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int M = scanner.nextInt();
int[] A = new int[N];
for(int i=0; i<N; i++){
A[i] = scanner.nextInt();
Arrays.sort(A);
int minFunctionValue = Integer.MAX_VALUE;
for(int i=0; i<=N-M; i++){
int currentFuctionValue = A[i+M-1] - A[i];
if(currentFunctionValue < minFunctionValue){
minFunctionValue = currentFunctionValue;
System.out.println(minFunctionValue);
2. Ticket Encoding Sequence
public class TicketCodeGenerator {
// Function to generate the ticket code for a given N
static String generateTicketCode(int N) {
// Initialize the first ticket code as "A"
StringBuilder ticketCode = new StringBuilder("A");
for (int i = 2; i <= N; i++) {
// Initialize a new ticket code
StringBuilder newTicketCode = new StringBuilder();
// Initialize the current character
char currentChar = ticketCode.charAt(0);
// Initialize the character count
int charCount = 0;
// Loop through the characters in the previous ticket code
for (int j = 0; j < ticketCode.length(); j++) {
if (ticketCode.charAt(j) == currentChar) {
// Increment character count if the character is the same
charCount++;
} else {
// If a different character is encountered, add the character
// count and current character to the new ticket code
newTicketCode.append(charCount).append(currentChar);
// Update the current character
currentChar = ticketCode.charAt(j);
// Reset character count to 1
charCount = 1;
// Add the character count and current character to the new ticket code
// for the last character group
newTicketCode.append(charCount).append(currentChar);
// Update the ticket code for the next iteration
ticketCode = newTicketCode;
return ticketCode.toString();
// Driver code
public static void main(String[] args) {
int N = 4;
// Generate the ticket code for N
String ticketCode = generateTicketCode(N);
// Output the ticket code
System.out.println(ticketCode);
3. Covid-19 Testing
import java.util.*;
public class CovidTestingRooms {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read input
int N = scanner.nextInt(); // Total number of available rooms
int K = scanner.nextInt(); // Number of rooms to be opened
int[] rooms = new int[N];
for (int i = 0; i < N; i++) {
rooms[i] = scanner.nextInt();
// Sort the room numbers
Arrays.sort(rooms);
// Binary search for the largest minimum distance
int left = 0;
int right = rooms[N-1] - rooms[0];
int result = 0;
while (left <= right) {
int mid = left + (right - left) / 2;
if (canAllocate(rooms, mid, K)) {
result = mid;
left = mid + 1;
} else {
right = mid - 1;
System.out.println(result);
scanner.close();
// Check if it's possible to allocate K rooms with minimum distance 'distance'
private static boolean canAllocate(int[] rooms, int distance, int K) {
int count = 1;
int lastPosition = rooms[0];
for (int i = 1; i < rooms.length; i++) {
if (rooms[i] - lastPosition >= distance) {
count++;
lastPosition = rooms[i];
if (count >= K) {
return true;
return false;
4.Roman Numbers
import java.util.Scanner;
public class RomanNumeralConverter {
// Function to get the value of a Roman numeral character
private static int romanToInt(char r) {
switch (r) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return 0;
}
}
// Function to check if the given string is a valid Roman numeral and convert it to integer
private static int romanToInt(String s) {
int n = s.length();
int result = 0;
for (int i = 0; i < n; i++) {
int current = romanToInt(s.charAt(i));
int next = (i + 1 < n) ? romanToInt(s.charAt(i + 1)) : 0;
// Rule 5: If the current value is less than the next value, subtract current from result
if (current < next) {
result -= current;
} else {
result += current;
return result;
// Function to validate the Roman numeral
private static boolean isValidRomanNumeral(String s) {
int n = s.length();
int countI = 0, countX = 0, countC = 0, countM = 0;
char lastChar = '\0';
for (int i = 0; i < n; i++) {
char current = s.charAt(i);
char next = (i + 1 < n) ? s.charAt(i + 1) : '\0';
int currentVal = romanToInt(current);
int nextVal = romanToInt(next);
// Rule 2 and Rule 3: No numeral can be repeated more than 3 times, and V, L, D cannot be
repeated
if (current == lastChar) {
if (current == 'V' || current == 'L' || current == 'D') return false;
if (current == 'I') countI++;
if (current == 'X') countX++;
if (current == 'C') countC++;
if (current == 'M') countM++;
if (countI > 3 || countX > 3 || countC > 3 || countM > 3) return false;
} else {
// Reset the count for the current character
if (current == 'I') countI = 1;
if (current == 'X') countX = 1;
if (current == 'C') countC = 1;
if (current == 'M') countM = 1;
// Rule 5: When a numeral is placed before another numeral of greater value
if (currentVal < nextVal) {
if (current != 'I' && current != 'X' && current != 'C') return false;
if (current == 'I' && next != 'V' && next != 'X') return false;
if (current == 'X' && next != 'L' && next != 'C') return false;
if (current == 'C' && next != 'D' && next != 'M') return false;
lastChar = current;
return true;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a Roman numeral: ");
String input = scanner.nextLine();
if (isValidRomanNumeral(input)) {
System.out.println("Numeric equivalent: " + romanToInt(input));
} else {
System.out.println("Invalid");
scanner.close();
4. Mailing list
import java.util.Scanner;
public class EmailValidator {
public static boolean isValidEmail(String email) {
email = email.trim();
// Check for the presence of exactly one '@' symbol
int atIndex = email.indexOf('@');
if (atIndex == -1 || email.indexOf('@', atIndex + 1) != -1) {
return false;
// Split into username and domain
String username = email.substring(0, atIndex).trim();
String domain = email.substring(atIndex + 1).trim();
// Validate username: should not contain spaces and can contain alphanumeric characters, '.',
'_', '-'
if (!username.matches("[a-zA-Z0-9._-]+")) {
return false;
}
// Validate domain: should not be empty, and should contain at least one '.'
if (domain.isEmpty() || !domain.contains(".")) {
return false;
// Domain can contain alphanumeric characters, '.', and '-'
if (!domain.matches("[a-zA-Z0-9.-]+")) {
return false;
// Ensure that domain part does not start or end with a '.' or '-'
if (domain.startsWith(".") || domain.endsWith(".") || domain.startsWith("-") ||
domain.endsWith("-")) {
return false;
return true;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.nextLine(); // Consume the remaining newline
for (int i = 0; i < n; i++) {
String email = scanner.nextLine();
if (isValidEmail(email)) {
System.out.println("True");
} else {
System.out.println("False");
}
scanner.close();
5.Fake Phone Numbers
import java.util.Scanner;
public class PhoneNumberValidator {
public static boolean isValidPhoneNumber(String phoneNumber) {
// Remove all spaces from the phone number
phoneNumber = phoneNumber.replaceAll("\\s", "");
// Check if the number starts with +91, 0, 7, 8, or 9
if (!phoneNumber.startsWith("+91") && !phoneNumber.startsWith("0") &&
!phoneNumber.startsWith("7") && !phoneNumber.startsWith("8") &&
!phoneNumber.startsWith("9")) {
return false;
// Remove the prefix (+91 or 0)
if (phoneNumber.startsWith("+91")) {
phoneNumber = phoneNumber.substring(3);
} else if (phoneNumber.startsWith("0")) {
phoneNumber = phoneNumber.substring(1);
// Check if the remaining number contains only digits and is of length 10
if (phoneNumber.length() != 10) {
return false;
for (char c : phoneNumber.toCharArray()) {
if (!Character.isDigit(c)) {
return false;
return true;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
for (int i = 0; i < n; i++) {
String phoneNumber = scanner.nextLine();
System.out.println(isValidPhoneNumber(phoneNumber));
6. JSON FORMATTER
public class JsonPrettifier {
/**
* Method to prettify JSON string by adding appropriate indentation.
* @param jsonInput The input JSON string to prettify.
* @return The prettified JSON string with proper indentation.
*/
public static String prettifyJson(String jsonInput) {
// Indentation level.
int indent = 0;
// Result string.
StringBuilder result = new StringBuilder();
// Iterate over the characters in the JSON string.
for (char x : jsonInput.toCharArray()) {
// If we encounter a '{', we increase the indentation level.
if (x == '{') {
indent += 2;
result.append(x);
result.append('\n');
result.append(" ".repeat(Math.max(0, indent)));
// If we encounter a '[', we add newline character, add '[', and then increase
the indentation level.
else if (x == '[') {
result.append('\n');
result.append(" ".repeat(Math.max(0, indent)));
indent += 2;
result.append(x);
result.append('\n');
result.append(" ".repeat(Math.max(0, indent)));
// If we encounter a '}' or ']', we decrease the indentation level.
else if (x == '}' || x == ']') {
indent -= 2;
result.append('\n');
result.append(" ".repeat(Math.max(0, indent)));
result.append(x);
// If we encounter a ',', we add a newline and indent the next line.
else if (x == ',') {
result.append(x);
result.append('\n');
result.append(" ".repeat(Math.max(0, indent)));
// Otherwise, we just add the character to the output string.
else {
result.append(x);
return result.toString();
/**
* Main method to demonstrate JSON prettifying.
*/
public static void main(String[] args) {
// Example
String jsonInput = "{\"username\":\"Jonas\",\"devices\":[\"iPhone 13
Pro\",\"Samsung Galaxy S30\"]}";
String prettified = prettifyJson(jsonInput);
System.out.println(prettified); // Pretty print the JSON string.
}
7. PuzzleVille
import java.util.*;
public class CombinationFinder {
// Function to find all unique combinations
private static void findCombinations(List<Integer> arr, int target, int index, List<Integer> current,
List<List<Integer>> result) {
if (target == 0) {
result.add(new ArrayList<>(current));
return;
for (int i = index; i < arr.size(); ++i) {
if (i > index && arr.get(i).equals(arr.get(i - 1))) continue;
if (arr.get(i) > target) break;
current.add(arr.get(i));
findCombinations(arr, target - arr.get(i), i + 1, current, result);
current.remove(current.size() - 1);
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int K = scanner.nextInt();
List<Integer> A = new ArrayList<>();
for (int i = 0; i < N; ++i) {
A.add(scanner.nextInt());
}
Collections.sort(A);
List<List<Integer>> result = new ArrayList<>();
List<Integer> current = new ArrayList<>();
findCombinations(A, K, 0, current, result);
System.out.println(result.size());
scanner.close();
8. fake Number
import java.util.ArrayList;
import java.util.List;
public class PhoneNumberValidator {
public static boolean isValidPhoneNumber(String number) {
int length = number.length();
String digits;
// Check if the number starts with +91, 0, 7, 8, or 9
if (number.startsWith("+91")) {
if (length != 15 || number.charAt(3) != ' ' || number.charAt(9) != ' ') {
return false;
digits = number.substring(4, 9) + number.substring(10, 15);
} else if (number.charAt(0) == '0') {
if (length != 12 || number.charAt(6) != ' ') {
return false;
}
digits = number.substring(1, 6) + number.substring(7, 12);
} else if (number.charAt(0) == '7' || number.charAt(0) == '8' || number.charAt(0) == '9') {
if (length != 10) {
return false;
digits = number;
} else {
return false;
// Check if the digits part is exactly 10 digits long
if (digits.length() != 10) {
return false;
// Check if all characters in the digits part are digits
for (char ch : digits.toCharArray()) {
if (!Character.isDigit(ch)) {
return false;
return true;
public static void main(String[] args) {
List<String> phoneNumbers = new ArrayList<>();
phoneNumbers.add("+91 12345 67890");
phoneNumbers.add("012345 67890");
phoneNumbers.add("9123456789");
phoneNumbers.add("+91 1234567890"); // Invalid
phoneNumbers.add("01234567890"); // Invalid
phoneNumbers.add("8123456789");
for (String number : phoneNumbers) {
if (isValidPhoneNumber(number)) {
System.out.println(number + " is valid.");
} else {
System.out.println(number + " is invalid.");
9. Donation
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class MaxDonation {
public static int maxDonation(int n, List<Integer> d) {
int maxDonation = 0;
int maxElement = d.stream().max(Integer::compare).orElse(0);
for (int amt = 1; amt <= maxElement; ++amt) {
int currSum = 0;
int maxSum = 0;
for (int i = 0; i < n; ++i) {
if (d.get(i) >= amt) {
currSum += amt;
} else {
currSum = 0;
maxSum = Math.max(maxSum, currSum);
maxDonation = Math.max(maxDonation, maxSum);
return maxDonation;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
List<Integer> d = new ArrayList<>();
for (int i = 0; i < n; ++i) {
d.add(scanner.nextInt());
System.out.println(maxDonation(n, d));
scanner.close();
10. Get that Query parameter
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class QueryParameterExtractor {
public static Map<String, String> parseQueryParameters(String url) {
Map<String, String> params = new HashMap<>();
// Find the index of '?'
int queryIndex = url.indexOf('?');
if (queryIndex == -1 || queryIndex == url.length() - 1) {
return params; // No query parameters
// Extract the query string
String queryString = url.substring(queryIndex + 1);
// Split the query string by '&' to get each key-value pair
String[] pairs = queryString.split("&");
for (String pair : pairs) {
// Split each pair by '='
String[] keyValue = pair.split("=");
if (keyValue.length == 2) {
String key = keyValue[0].trim();
String value = keyValue[1].trim();
params.put(key, value);
return params;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read URL
String url = scanner.nextLine().trim();
// Read number of query parameter names
int n = scanner.nextInt();
scanner.nextLine(); // Consume the remaining newline
// Read each query parameter name
String[] keys = new String[n];
for (int i = 0; i < n; i++) {
keys[i] = scanner.nextLine().trim();
// Parse the URL to get the query parameters
Map<String, String> queryParams = parseQueryParameters(url);
// Output the values for the given keys
for (String key : keys) {
if (queryParams.containsKey(key)) {
System.out.println(queryParams.get(key));
} else {
System.out.println("-1");
scanner.close();
11. Bus Route Connectivity
import java.util.*;
public class BusRouteConnectivity {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read the number of stops for each route
int n = scanner.nextInt();
int m = scanner.nextInt();
// Read the stops for route A
List<Integer> routeA = new ArrayList<>();
for (int i = 0; i < n; i++) {
routeA.add(scanner.nextInt());
// Read the stops for route B
List<Integer> routeB = new ArrayList<>();
for (int i = 0; i < m; i++) {
routeB.add(scanner.nextInt());
// Read the source and destination stops
int x = scanner.nextInt();
int y = scanner.nextInt();
scanner.close();
// Convert routes to sets for faster lookups
Set<Integer> stopsA = new HashSet<>(routeA);
Set<Integer> stopsB = new HashSet<>(routeB);
// Check direct connectivity
if (stopsA.contains(x) && stopsA.contains(y)) {
System.out.println("No");
return;
if (stopsB.contains(x) && stopsB.contains(y)) {
System.out.println("No");
return;
// Check if there is a possible route through merging
boolean canTravel = false;
// Check if there is an overlap in stops where travel can be merged
for (Integer stopA : stopsA) {
if (stopsB.contains(stopA)) {
// There is a common stop where the routes merge
if (stopsA.contains(x) && stopsB.contains(y)) {
canTravel = true;
break;
if (stopsB.contains(x) && stopsA.contains(y)) {
canTravel = true;
break;
if (canTravel) {
System.out.println("Yes");
} else {
System.out.println("No");