0% found this document useful (0 votes)
93 views

Litcode Labs

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
93 views

Litcode Labs

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

CS_JAVA_Familiarization Lab

import java.io.*;

import java.util.*;

import java.text.*;

import java.math.*;

import java.util.regex.*;

public class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

int a = input.nextInt();

int b = input.nextInt();

int ret = mul(a,b);

System.out.println(ret);

public static int mul(int x, int y) {

//Hint : Type return x * y below

return x*y;

}
CS_JAVA_Lab 1_0924

import java.io.*;

import java.util.*;

import java.text.*;

import java.math.*;

import java.util.regex.*;

import java.util.*;

public class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

// Read the size of the array

int n = input.nextInt();

// Initialize the array and read elements

int[] arr = new int[n];

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

arr[i] = input.nextInt();

// Call the function that performs the operations

doSomething(arr);

// Perform the required operation in this function

public static void doSomething(int[] arr) {

int n = arr.length; // Correct way to get array length

int positiveCount = 0, negativeCount = 0, zeroCount = 0;


// Traverse the array and count positives, negatives, and zeros

for (int num : arr) {

if (num > 0) {

positiveCount++;

} else if (num < 0) {

negativeCount++;

} else {

zeroCount++;

// Calculate the fractions and print with 3 decimal places

System.out.printf("%.3f\n", (double) positiveCount / n);

System.out.printf("%.3f\n", (double) negativeCount / n);

System.out.printf("%.3f\n", (double) zeroCount / n);

}
CS_JAVA_Lab 2_0924

import java.io.*;

import java.util.*;

import java.text.*;

import java.math.*;

import java.util.regex.*;

import java.io.*;

import java.util.*;

public class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

int availableHours = input.nextInt(); // First input: available hours

int devicesToTest = input.nextInt(); // Second input: total number of devices

doSomething(availableHours, devicesToTest); // Call the function

public static void doSomething(int availableHours, int devicesToTest) {

if (availableHours < 4) {

// If the available hours are less than 4, print "Invalid Input"

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

return;

// Each device takes 4 hours to be tested, so calculate how many devices can be tested

int devicesTested = availableHours / 4; // Integer division to get the floor value

int remainingDevices = devicesToTest - devicesTested; // Remaining devices to be tested

// Ensure remaining devices can't be negative (if all devices are tested)
if (remainingDevices < 0) {

remainingDevices = 0;

// If the number of tested devices exceeds the total devices, adjust the output

devicesTested = Math.min(devicesTested, devicesToTest);

// Output the number of tested devices and remaining devices

System.out.println(devicesTested);

System.out.println(remainingDevices);

}
CS_JAVA_Lab 3_0924

import java.io.*;

import java.util.*;

import java.text.*;

import java.math.*;

import java.util.regex.*;

public class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

// Read the input array as a single line of space-separated integers

String line = input.nextLine();

String[] tokens = line.split(" ");

// Check if array size is between 1 and 10

if (tokens.length < 1 || tokens.length > 10) {

System.out.println("Array size must be between 1 and 10");

return;

// Initialize array and check if all elements are integers between -10 and 10

int[] arr = new int[tokens.length];

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

try {

arr[i] = Integer.parseInt(tokens[i]);

if (arr[i] < -10 || arr[i] > 10) {

System.out.println("Array elements must be from -10 to 10");

return;

} catch (NumberFormatException e) {

System.out.println("Array elements must be integers");


return;

// Call the function to check for zero-sum subarray and print results

boolean hasZeroSumSubarray = hasZeroSumSubarray(arr);

System.out.println(hasZeroSumSubarray ? "True" : "False");

System.out.println(arr.length);

// Function to check for zero-sum subarray using prefix sum and HashSet

public static boolean hasZeroSumSubarray(int[] arr) {

// Create a set to store prefix sums

Set<Integer> prefixSums = new HashSet<>();

int prefixSum = 0;

// Add the initial prefix sum (zero) to handle the case where a subarray starting from index 0 has sum zero

prefixSums.add(0);

for (int num : arr) {

prefixSum += num;

// If the prefix sum has been seen before, there is a zero-sum subarray

if (prefixSums.contains(prefixSum)) {

return true;

// Add the current prefix sum to the set

prefixSums.add(prefixSum);

// If no zero-sum subarray is found, return false

return false;
}

CS_JAVA_Lab 4_0924

import java.io.*;

import java.util.*;

public class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

// Reading the input as a string to validate length and check if it's an integer

String inputString = input.nextLine();

// Validate if input is exactly 4 digits

if (inputString.length() < 4) {

System.out.println("Provided input is less than 4, enter four digit integers");

return;

} else if (inputString.length() > 4) {

System.out.println("Provided input is more than 4, enter four digit integers");

return;

// Check if input is a valid integer and if it is positive

try {

int number = Integer.parseInt(inputString);

if (number < 0) {

System.out.println("Enter positive 4-digit integer");

return;
}

// If everything is valid, proceed to encryption

int encryptedNumber = encryptNumber(number);

System.out.println(encryptedNumber);

} catch (NumberFormatException e) {

System.out.println("Enter only integer value");

// Function to encrypt the 4-digit number

public static int encryptNumber(int number) {

// Extract each digit

int[] digits = new int[4];

for (int i = 3; i >= 0; i--) {

digits[i] = number % 10; // Get the last digit

number /= 10; // Remove the last digit

// Encrypt each digit

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

digits[i] = (digits[i] + 5) % 10;

// Swap the first digit with the third, and the second with the fourth

int temp = digits[0];

digits[0] = digits[2];

digits[2] = temp;

temp = digits[1];

digits[1] = digits[3];

digits[3] = temp;
// Reconstruct the number

int encryptedNumber = 0;

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

encryptedNumber = encryptedNumber * 10 + digits[i];

return encryptedNumber;

CS_JAVA_Lab 5_0924

import java.io.*;

import java.util.*;

public class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

// Reading multiple numbers from input into an array

String[] numbers = input.nextLine().split(" ");

// Create a StringBuilder to store the resulting PIN

StringBuilder pin = new StringBuilder();

// Process each number


for (String num : numbers) {

int cumulativeSum = findCumulativeSum(Integer.parseInt(num));

// Convert cumulative sum to alphabet if it's odd, otherwise use the number itself

if (cumulativeSum % 2 != 0) {

pin.append(convertToAlphabet(cumulativeSum)); // Convert to alphabet

} else {

pin.append(cumulativeSum); // Keep even number as it is

// Print the resulting PIN

System.out.println(pin.toString());

// Function to calculate the cumulative sum until it becomes a single digit

public static int findCumulativeSum(int num) {

while (num >= 10) {

int sum = 0;

while (num > 0) {

sum += num % 10; // Add each digit to the sum

num /= 10;

num = sum; // Set the new number as the sum of digits

return num; // Return the single digit

// Function to convert an odd number to its corresponding alphabet

public static char convertToAlphabet(int num) {

return (char) ('a' + num - 1); // 1 -> 'a', 3 -> 'c', 5 -> 'e', etc.

}
CS_JAVA_Lab 6_0924
import java.io.*;

import java.util.*;

public class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

// Input: Single integer

int num = input.nextInt();

// Find and print the largest special prime less than num

int largestSpecialPrime = findLargestSpecialPrime(num);

System.out.println(largestSpecialPrime);

// Function to find the largest special prime less than a given number

public static int findLargestSpecialPrime(int limit) {

for (int i = limit - 1; i > 1; i--) {

if (isPrime(i) && isSpecialPrime(i)) {

return i;

return -1; // No special prime found (unlikely)

// Function to check if a number is prime

public static boolean isPrime(int num) {

if (num <= 1) {

return false;

for (int i = 2; i * i <= num; i++) {


if (num % i == 0) {

return false;

return true;

// Function to check if all concatenations of digits of a number are prime

public static boolean isSpecialPrime(int num) {

String strNum = Integer.toString(num);

// Check for all concatenations

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

int subNum = Integer.parseInt(strNum.substring(0, i));

if (!isPrime(subNum)) {

return false; // Not prime at some stage

return true; // All stages are prime

}
CS_JAVA_Lab 7_0924
import java.io.*;

import java.util.*;

public class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

// Input: divisor

int k = input.nextInt();

// Input: array elements

int n = input.nextInt();

int[] arr = new int[n];

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

arr[i] = input.nextInt();

// Call the function to get the count of divisible sum pairs

int result = divisibleSumPairs(k, arr);

// Output the result

System.out.println(result);

// Function to calculate divisible sum pairs

public static int divisibleSumPairs(int k, int[] arr) {

int count = 0;

// Check each pair (i, j) with i < j

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

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


if ((arr[i] + arr[j]) % k == 0) {

count++;

return count;

CS_JAVA_Lab 8_0924
import java.io.*;

import java.util.*;

public class Main {

public static void main(String[] args) {

// Scanner to take input

Scanner input = new Scanner(System.in);

// Read the entire line of inputs as integers

String[] sightings = input.nextLine().split(" ");

int[] arr = new int[sightings.length];

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

arr[i] = Integer.parseInt(sightings[i]);

// Call the function to find the most common plant

int result = mostCommonPlant(arr);


// Print the result

System.out.println(result);

public static int mostCommonPlant(int[] arr) {

// Create a HashMap to store plant frequencies

HashMap<Integer, Integer> freqMap = new HashMap<>();

// Track the most frequent plant and its frequency

int maxFreq = 0;

int mostCommonPlant = Integer.MAX_VALUE; // Use MAX_VALUE to find the smallest ID in case of ties

// Count the frequency of each plant ID

for (int plantID : arr) {

freqMap.put(plantID, freqMap.getOrDefault(plantID, 0) + 1);

// Update most common plant

int currentFreq = freqMap.get(plantID);

// Check if we have a new max frequency or if we need to update for a tie

if (currentFreq > maxFreq || (currentFreq == maxFreq && plantID < mostCommonPlant)) {

maxFreq = currentFreq;

mostCommonPlant = plantID;

return mostCommonPlant;

}
CS_JAVA_Lab 9_0924
import java.util.*;

public class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

// Read Charlie's scores

String[] charlieInput = input.nextLine().split(" ");

int[] charlie = new int[charlieInput.length];

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

charlie[i] = Integer.parseInt(charlieInput[i]);

// Read Dave's scores

String[] daveInput = input.nextLine().split(" ");

int[] dave = new int[daveInput.length];

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

dave[i] = Integer.parseInt(daveInput[i]);

// Function to compare scores

int[] result = compareTriplets(charlie, dave);

// Output the results: Charlie's points and Dave's points

System.out.println(result[0] + " " + result[1]);

public static int[] compareTriplets(int[] c, int[] d) {

// Initialize scores for Charlie and Dave

int charliePoints = 0;

int davePoints = 0;
// Compare each corresponding score

for (int i = 0; i < Math.min(c.length, d.length); i++) {

if (c[i] > d[i]) {

charliePoints++;

} else if (c[i] < d[i]) {

davePoints++;

// Return the points as an array [charliePoints, davePoints]

return new int[]{charliePoints, davePoints};

CS_JAVA_Lab 10_0924
import java.util.*;

public class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

// Step 1: Input array size

int n = input.nextInt();

// Step 2: Input number of queries

int q = input.nextInt();

// Initialize the array with 0's, note the array is 1-indexed, but we use 0-indexed internally.

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


// Step 3: Process each query

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

int start = input.nextInt() - 1; // 1-indexed input, convert to 0-index

int end = input.nextInt() - 1; // 1-indexed input, convert to 0-index

int value = input.nextInt();

// Add value to start index

arr[start] += value;

// Subtract value after end index if within bounds

if (end + 1 < n) {

arr[end + 1] -= value;

// Step 4: Apply prefix sum to calculate the actual values

int maxValue = Integer.MIN_VALUE;

int currentSum = 0;

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

currentSum += arr[i];

if (currentSum > maxValue) {

maxValue = currentSum;

// Step 5: Output the maximum value in the array

System.out.println(maxValue);

}
CS_JAVA_Lab 11_0924
import java.util.*;

public class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

// Step 1: Input size for three arrays

int n1 = input.nextInt(); // Size of first array

int n2 = input.nextInt(); // Size of second array

int n3 = input.nextInt(); // Size of third array

// Step 2: Initialize and input the three arrays

int[] arr1 = new int[n1];

int[] arr2 = new int[n2];

int[] arr3 = new int[n3];

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

arr1[i] = input.nextInt();

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

arr2[i] = input.nextInt();

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

arr3[i] = input.nextInt();

// Step 3: Find common elements

findCommonElements(arr1, arr2, arr3);

}
public static void findCommonElements(int[] arr1, int[] arr2, int[] arr3) {

int i = 0, j = 0, k = 0;

boolean found = false;

// Step 4: Traverse through all arrays using three pointers

while (i < arr1.length && j < arr2.length && k < arr3.length) {

// If elements are equal in all three arrays

if (arr1[i] == arr2[j] && arr1[i] == arr3[k]) {

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

found = true;

i++;

j++;

k++;

// Move pointer for the smallest element

else if (arr1[i] < arr2[j]) {

i++;

} else if (arr2[j] < arr3[k]) {

j++;

} else {

k++;

// If no common elements found, print "No Elements"

if (!found) {

System.out.println("No Elements");

}
CS_JAVA_Lab 12_0924

import java.util.*;

class CustomStack {

private StringBuilder text;

private Stack<String> history;

public CustomStack() {

this.text = new StringBuilder();

this.history = new Stack<>();

// Inserts a string at the current cursor position

public void insert(String value) {

history.push(text.toString()); // Save current state for undo

text.append(value);

// Deletes the last `value` characters from the text

public void delete(int value) {

history.push(text.toString()); // Save current state for undo

if (value <= text.length()) {

text.delete(text.length() - value, text.length());

} else {

text.setLength(0); // If value is greater, clear text

// Retrieves the character at index `value` (1-based index)

public void get(int value) {

if (value > 0 && value <= text.length()) {


System.out.println(text.charAt(value - 1));

// Reverts the last command

public void undo() {

if (!history.isEmpty()) {

text = new StringBuilder(history.pop()); // Restore previous state

public class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

CustomStack editor = new CustomStack();

// Read input commands

String commands = input.nextLine();

String[] commandArray = commands.split(",");

for (String command : commandArray) {

String[] parts = command.split(" ");

int cmdType = Integer.parseInt(parts[0]);

switch (cmdType) {

case 1: // Insert command

editor.insert(parts[1]);

break;

case 2: // Delete command

editor.delete(Integer.parseInt(parts[1]));

break;

case 3: // Get command


editor.get(Integer.parseInt(parts[1]));

break;

case 4: // Undo command

editor.undo();

break;

CS_JAVA_Lab 13_0924

import java.util.*;

class CustomQueue {

private Stack<Integer> stack1;

private Stack<Integer> stack2;

public CustomQueue() {

stack1 = new Stack<>();

stack2 = new Stack<>();

// Enqueue operation

public void enqueue(int x) {

stack1.push(x);

// Dequeue operation

public void dequeue() {


if (stack2.isEmpty()) {

while (!stack1.isEmpty()) {

stack2.push(stack1.pop());

if (!stack2.isEmpty()) {

stack2.pop();

// Print front operation

public int printFront() {

if (stack2.isEmpty()) {

while (!stack1.isEmpty()) {

stack2.push(stack1.pop());

return stack2.isEmpty() ? -1 : stack2.peek();

public class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

CustomQueue queue = new CustomQueue();

String commands = input.nextLine();

String[] commandArray = commands.split(",");

for (String command : commandArray) {

String[] parts = command.split(" ");

int cmdType = Integer.parseInt(parts[0]);


switch (cmdType) {

case 1: // Enqueue command

queue.enqueue(Integer.parseInt(parts[1]));

break;

case 2: // Dequeue command

queue.dequeue();

break;

case 3: // Print front command

int front = queue.printFront();

if (front != -1) {

System.out.println(front);

break;

CS_JAVA_Lab 14_0924

import java.util.*;

public class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

// Read input strings

String start = input.next();

String end = input.next();


// Call the function to determine if transformation is possible

boolean result = canTransform(start, end);

System.out.println(result);

public static boolean canTransform(String start, String end) {

// Check if both strings have the same length

if (start.length() != end.length()) {

return false;

// Count characters in both strings

int[] countStart = new int[3]; // count of L, R, and X in start

int[] countEnd = new int[3]; // count of L, R, and X in end

for (char c : start.toCharArray()) {

countStart[getIndex(c)]++;

for (char c : end.toCharArray()) {

countEnd[getIndex(c)]++;

// Compare counts of L and R

return countStart[0] == countEnd[0] && countStart[1] == countEnd[1];

private static int getIndex(char c) {

// Return index based on character

switch (c) {

case 'L': return 0; // index for L

case 'R': return 1; // index for R

case 'X': return 2; // index for X

default: return -1; // should not happen


}

For CS_JAVA_Lab 15_0924

import java.io.*;

import java.util.*;

public class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

int n = input.nextInt();

int m = input.nextInt();

int ret = doSomething(n, m);

System.out.println(ret);

public static int doSomething(int n, int m) {

final int MOD = 1000000007;

// Handle cases where m is 0 or 1 directly

if (m == 0) return 0;

if (m == 1) return 1;

long[] row_combinations = new long[m + 1];

row_combinations[0] = 1; // 1 way to build a wall of width 0

if (m >= 1) row_combinations[1] = 1; // 1 way to build a wall of width 1

if (m >= 2) row_combinations[2] = 2; // 2 ways to build a wall of width 2

if (m >= 3) row_combinations[3] = 4; // 4 ways to build a wall of width 3


// Build row combinations up to the current wall's width

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

row_combinations[i] = (row_combinations[i - 1] + row_combinations[i - 2] + row_combinations[i - 3] +


row_combinations[i - 4]) % MOD;

// Compute total combinations for constructing a wall of height N of varying widths

long[] total = new long[m + 1];

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

total[i] = pow(row_combinations[i], n, MOD);

// Find the number of unstable wall configurations for a wall of height N of varying widths

long[] unstable = new long[m + 1];

unstable[0] = 0;

unstable[1] = 0;

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

long result = 0;

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

result = (result + (total[j] - unstable[j] + MOD) % MOD * total[i - j]) % MOD;

unstable[i] = result;

// Print the number of stable wall combinations

return (int) ((total[m] - unstable[m] + MOD) % MOD);

public static long pow(long a, int b, int mod) {

long result = 1;

while (b > 0) {
if ((b & 1) == 1) {

result = (result * a) % mod;

a = (a * a) % mod;

b >>= 1;

return result;

CS_JAVA_Lab 16_0924

import java.util.*;

public class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

// Read the target sweetness

int targetSweetness = input.nextInt();

input.nextLine(); // Move to the next line

// Read the sweetness values of the candies

String[] candyStrings = input.nextLine().split(" ");

PriorityQueue<Integer> candies = new PriorityQueue<>();

// Add each candy's sweetness to the min-heap

for (String candy : candyStrings) {

candies.offer(Integer.parseInt(candy));

}
int steps = calculateStepsToReachTarget(candies, targetSweetness);

System.out.println(steps);

public static int calculateStepsToReachTarget(PriorityQueue<Integer> candies, int target) {

int steps = 0;

// Continue combining until we reach or exceed the target sweetness

while (candies.size() > 1) {

// Take the two least sweet candies

int leastSweet = candies.poll();

int secondLeastSweet = candies.poll();

// Create a new candy with the combined sweetness

int newCandy = leastSweet + 2 * secondLeastSweet;

candies.offer(newCandy); // Add the new candy back to the heap

steps++; // Increment the step count

// Check if we have reached or exceeded the target sweetness

if (newCandy >= target) {

return steps; // Return the steps if we reach the target

// If we exit the loop, check if the remaining candy meets the target

if (!candies.isEmpty() && candies.peek() >= target) {

return steps; // Return steps if target reached

return -1; // If we could not reach the target

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy