CC40 Medium Code
CC40 Medium Code
CODES
2.1.2 Problem Solving (Java)
package q23516;
public class CTJ23516 {
public static int sumOfPrimes(int n1, int n2) {
if (n1 > n2) {
int temp = n1;
n1 = n2;
n2 = temp;
}
boolean[] isPrime = sieveOfEratosthenes(10000);
int sum = 0;
System.out.println(sumOfPrimes(n1, n2));
}
}
2.1.3 Car Race (Java)
package q10;
def count_ways(n):
if n == 0:
return 1
elif n == 1:
return 1
ways = [0] * (n + 1)
ways[0] = 1
ways[1] = 1
for i in range(2, n + 1):
ways[i] = ways[i - 1] + ways[i - 2]
return ways[n]
n = int(input().strip())
print(count_ways(n))
2.1.9 Well formed Parentheses (Java)
package q18113;
import java.util.Scanner;
public class CTJ18113 {
public static int countValidParentheses(int n) {
return countHelper(n, n);
}
private static int countHelper(int open, int close) {
if (open == 0 && close == 0) {
return 1;
}
int count = 0;
if (open > 0) {
count += countHelper(open - 1, close);
}
if (close > open) {
count += countHelper(open, close - 1);
}
return count;
}
scanner.close();
}
}
2.1.10 Zero (Java)
package q13428;
import java.util.Scanner;
return zeroCount;
}
package q18795;
import java.util.Scanner;
public class CTJ18795 {
public static int maxIntegerInGeneratedArray(int n) {
int[] nums = new int[n + 1];
if (n >= 0) {
nums[0] = 0;
}
if (n >= 1) {
nums[1] = 1;
}
for (int i = 1; i <= n / 2; i++) {
if (2 * i <= n) {
nums[2 * i] = nums[i];
}
if (2 * i + 1 <= n) {
nums[2 * i + 1] = nums[i] + nums[i + 1];
}
}
int max = nums[0];
for (int i = 1; i <= n; i++) {
if (nums[i] > max) {
max = nums[i];
}
}
return max;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("");
int n = scanner.nextInt();
int result = maxIntegerInGeneratedArray(n);
System.out.println(result);
scanner.close();
}
}
2.2.1 Remove given character (C)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
package q40;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CTJ40 {
public static int WordCount(String Str) {
String regex = "[a-zA-Z]+(?:-[a-zA-Z]+)*";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(Str);
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}
public static void main(String[] args) {
String Str = args[0];
System.out.println(WordCount (Str));
}
}
2.2.4 Rotation of strings (Java)
package q1632;
package q13217;
import java.util.*;
public class CTJ13217 {
public static int numDecodings(String s) {
if (s == null || s.length() == 0 || s.charAt(0) == '0') {
return 0;
}
int MOD = 1000000007;
int n = s.length();
int[] dp = new int[n + 1];
dp[0] = 1;
dp[1] = s.charAt(0) == '0' ? 0 : 1;
for (int i = 2; i <= n; i++) {
int oneDigit = Integer.parseInt(s.substring(i - 1, i));
if (oneDigit >= 1) {
dp[i] = (dp[i] + dp[i - 1]) % MOD;
}
int twoDigits = Integer.parseInt(s.substring(i - 2, i));
if (twoDigits >= 10 && twoDigits <= 26) {
dp[i] = (dp[i] + dp[i - 2]) % MOD;
}
}
return dp[n];
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
System.out.println(numDecodings(input));
}
}
2.2.7 Reverse words (Java)
package q3615;
package q14736;
import java.util.*;
public class CTJ14736 {
public static int firstNonRepeatingCharacter(String str) {
Map<Character, Integer> charCount = new LinkedHashMap<>();
for (char c : str.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
for (int i = 0; i < str.length(); i++) {
if (charCount.get(str.charAt(i)) == 1) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
System.out.println(firstNonRepeatingCharacter(input));
}
}
package q14430;
import java.util.*;
public class CTJ14430 {
private static void computeLPSArray(String pattern, int[] lps) {
int length = 0;
lps[0] = 0;
int i = 1;
while (i < pattern.length()) {
if (pattern.charAt(i) == pattern.charAt(length)) {
length++;
lps[i] = length;
i++;
} else {
if (length != 0) {
length = lps[length - 1];
} else {
lps[i] = 0;
i++;
}
}
}
}
private static void KMPSearch(String text, String pattern) {
int textLength = text.length();
int patternLength = pattern.length();
int[] lps = new int[patternLength];
computeLPSArray(pattern, lps);
int i = 0;
int j = 0;
boolean found = false;
while (i < textLength) {
if (pattern.charAt(j) == text.charAt(i)) {
i++;
j++;
}
if (j == patternLength) {
System.out.print((i - j) + " ");
j = lps[j - 1];
found = true;
} else if (i < textLength && pattern.charAt(j) != text.charAt(i)) {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
if (!found) {
System.out.print("-1");
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine().trim();
String pattern = scanner.nextLine().trim();
KMPSearch(text, pattern);
scanner.close();
}
}
2.3.1 Separation of +ve & -ve (Java)
package q1601;
import java.util.*;
import java.util.stream.*;
public class CTJ1601 {
public static List<Integer> posNegSeparation (List<Integer> Arr) {
List<Integer> negatives = new ArrayList<>();
List<Integer> positives = new ArrayList<>();
for (int num : Arr) {
if (num < 0) {
negatives.add(num);
} else {
positives.add(num);
}
}
negatives.addAll(positives);
return negatives;
}
public static void main(String[] args) {
List<Integer> Arr = Arrays.stream(args[0].split(",")).map(s -> Integer.parseInt(s)).collect(Collectors.toList());
System.out.println(posNegSeparation (Arr).stream().map(String::valueOf).collect(Collectors.joining(",")));
}
}
2.3.2 Reverse queries (Java)
package q44;
import java.util.*;
import java.util.stream.*;
public class CTJ44 {
public static List<Integer> ArrayOperations(List<Integer> Arr, List<Integer> Queries) {
int m = Queries.size() / 2;
for (int i = 0; i < m; i++) {
int start = Queries.get(2 * i);
int end = Queries.get(2 * i + 1);
reverseSubarray(Arr, start, end);
}
return Arr;
}
private static void reverseSubarray(List<Integer> Arr, int start, int end) {
while (start < end) {
int temp = Arr.get(start);
Arr.set(start, Arr.get(end));
Arr.set(end, temp);
start++;
end--;
}
}
public static void main(String[] args) {
List<Integer> Arr = Arrays.stream(args[0].split(",")).map(s -> Integer.parseInt(s)).collect(Collectors.toList());
List<Integer> Queries = Arrays.stream(args[1].split(",")).map(s -> Integer.parseInt(s)).collect(Collectors.toList());
System.out.println(ArrayOperations(Arr, Queries).stream().map(String::valueOf).collect(Collectors.joining(",")));
}
}
2.3.3 Bit Manipulation (Java)
package q14766;
import java.util.*;
import java.util.stream.*;
public class CTJ14766 {
public static int maxConsecutiveOnes(int[] B, int k) {
int left = 0, maxLength = 0, zerosCount = 0;
for (int right = 0; right < B.length; right++) {
if (B[right] == 0) {
zerosCount++;
}
while (zerosCount > k) {
if (B[left] == 0) {
zerosCount--;
}
left++;
}
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
int[] B = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int k = Integer.parseInt(scanner.nextLine());
System.out.println(maxConsecutiveOnes(B, k));
}
}
2.3.4 LCM equals (Java)
package q18117;
import java.util.Scanner;
public class CTJ18117 {
public static int lcm(int a, int b) {
return (a * (b / gcd(a, b)));
}
public static int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
public static int countSubarraysWithLCM(int[] A, int n, int k) {
int count = 0;
for (int i = 0; i < n; i++) {
int currentLcm = 1;
for (int j = i; j < n; j++) {
currentLcm = lcm(currentLcm, A[j]);
if (currentLcm > k) {
break;
}
if (currentLcm == k) {
count++;
}
}
}
return count;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] A = new int[n];
for (int i = 0; i < n; i++) {
A[i] = scanner.nextInt();
}
int k = scanner.nextInt();
int result = countSubarraysWithLCM(A, n, k);
System.out.println(result);
}
}
2.3.5 GCD equals (Java)
package q18116;
import java.util.*;
import java.util.stream.*;
public class CTJ18116 {
public static int countSubarraysWithGCD(int[] A, int k) {
int count = 0;
int n = A.length;
for (int start = 0; start < n; start++) {
int currentGCD = 0;
for (int end = start; end < n; end++) {
currentGCD = gcd(currentGCD, A[end]);
if (currentGCD == k) {
count++;
} else if (currentGCD < k) {
break;
}
}
}
return count;
}
private static int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
int[] A = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int k = Integer.parseInt(scanner.nextLine());
System.out.println(countSubarraysWithGCD(A, k));
}
}
2.3.6 B/w Two Sets (Java)
package q14919;
import java.util.*;
public class CTJ14919 {
public static int getNumbersBetween(int[] a, int[] b) {
int count = 0;
int lcm = findLCM(a);
int gcd = findGCD(b);
for (int i = lcm; i <= gcd; i += lcm) {
if (gcd % i == 0) {
count++;
}
}
return count;
}
private static int findLCM(int[] arr) {
int lcm = arr[0];
for (int i = 1; i < arr.length; i++) {
lcm = lcm(lcm, arr[i]);
}
return lcm;
}
private static int lcm(int a, int b) {
return (a * b) / findGCD(a, b);
}
private static int findGCD(int[] arr) {
int gcd = arr[0];
for (int i = 1; i < arr.length; i++) {
gcd = findGCD(gcd, arr[i]);
}
return gcd;
}
private static int findGCD(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
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];
int[] b = new int[m];
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
}
for (int j = 0; j < m; j++) {
b[j] = scanner.nextInt();
}
int result = getNumbersBetween(a, b);
System.out.println(result);
}
}
2.3.7 Finding Errors (Java)
package q95;
import java.util.*;
import java.util.stream.*;
public class CTJ95 {
public static int Finding_Errors(int N, int M, List<String> Products, List<Float> Product_Prices, List<String>
Product_Sold, List<Float> Sold_Price) {
Map<String, Float> productPriceMap = new HashMap<>();
for (int i = 0; i < N; i++) {
productPriceMap.put(Products.get(i), Product_Prices.get(i));
}
int errorCount = 0;
for (int j = 0; j < M; j++) {
String soldProduct = Product_Sold.get(j);
float soldPrice = Sold_Price.get(j);
Float correctPrice = productPriceMap.get(soldProduct);
if (correctPrice == null || !correctPrice.equals(soldPrice)) {
errorCount++;
}
}
return errorCount;
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
int M = Integer.parseInt(args[1]);
List<String> Products = Arrays.stream(args[2].split(",")).map(s -> s).collect(Collectors.toList());
List<Float> Product_Prices = Arrays.stream(args[3].split(",")).map(s -> Float.parseFloat(s)).collect(Collectors.toList());
List<String> Product_Sold = Arrays.stream(args[4].split(",")).map(s -> s).collect(Collectors.toList());
List<Float> Sold_Price = Arrays.stream(args[5].split(",")).map(s -> Float.parseFloat(s)).collect(Collectors.toList());
System.out.println(Finding_Errors(N, M, Products, Product_Prices, Product_Sold, Sold_Price));
}
}
2.3.8 Balancing array (Java)
package q26;
import java.util.*;
import java.util.stream.*;
public class CTJ26 {
public static int balancing_array(List<Long> Arr) {
long totalSum = 0;
long leftSum = 0;
for (long num : Arr) {
totalSum += num;
}
for (int i = 0; i < Arr.size(); i++) {
long rightSum = totalSum - leftSum - Arr.get(i);
if (leftSum == rightSum) {
return i;
}
leftSum += Arr.get(i);
}
return -1;
}
public static void main(String[] args) {
List<Long> Arr = Arrays.stream(args[0].split(",")).map(s -> Long.parseLong(s)).collect(Collectors.toList());
System.out.println(balancing_array(Arr));
}
}
2.3.10 Count of Triples (Java)
package q14887;
import java.util.HashMap;
import java.util.Scanner;
public class CTJ14887 {
public static int countMaxTriplets(int[] arr, int N, int M) {
HashMap<Integer, Integer> freqMap = new HashMap<>();
for (int num : arr) {
freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
}
int tripletCount = 0;
for (int num = 1; num <= M; num++) {
if (freqMap.containsKey(num)) {
int count = freqMap.get(num);
tripletCount += count / 3;
freqMap.put(num, count % 3);
}
}
for (int num = 1; num <= M - 2; num++) {
if (freqMap.containsKey(num) && freqMap.containsKey(num + 1) && freqMap.containsKey(num + 2)) {
int minCount = Math.min(freqMap.get(num), Math.min(freqMap.get(num + 1), freqMap.get(num + 2)));
tripletCount += minCount;
freqMap.put(num, freqMap.get(num) - minCount);
freqMap.put(num + 1, freqMap.get(num + 1) - minCount);
freqMap.put(num + 2, freqMap.get(num + 2) - minCount);
}
}
return tripletCount;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int M = scanner.nextInt();
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = scanner.nextInt();
}
int result = countMaxTriplets(arr, N, M);
System.out.println(result);
}
}
package q1598;
import java.util.*;
import java.util.stream.*;
public class CTJ1598 {
public static List<Integer> maxMin (List<Integer> Arr) {
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int num : Arr) {
if (num > max) {
max = num;
}
if (num < min) {
min = num;
}
}
List<Integer> result = new ArrayList<>();
result.add(max);
result.add(min);
return result;
}
public static void main(String[] args) {
List<Integer> Arr = Arrays.stream(args[0].split(",")).map(s -> Integer.parseInt(s)).collect(Collectors.toList());
System.out.println(maxMin (Arr).stream().map(String::valueOf).collect(Collectors.joining(",")));
}
}
package q1072;
public class CTJ1072 {
public static int LongestSubstring (String Str1) {
int maxLength = 1;
int currentLength = 1;
for (int i = 1; i < Str1.length(); i++) {
char prevChar = Str1.charAt(i - 1);
char currentChar = Str1.charAt(i);
if ((currentChar == (prevChar + 1)) ||
(prevChar == 'z' && currentChar == 'a')) {
currentLength++;
} else {
maxLength = Math.max(maxLength, currentLength);
currentLength = 1;
}
}
maxLength = Math.max(maxLength, currentLength);
return maxLength;
}
public static void main(String[] args) {
String Str1 = args[0];
System.out.println(LongestSubstring (Str1));
}
}
package q9288;
import java.util.*;
import java.util.stream.*;
public class CTJ9288 {
public static long countInversions(List<Long> A) {
long[] temp = new long[A.size()];
return mergeSortAndCount(A, temp, 0, A.size() - 1);
}
private static long mergeSortAndCount(List<Long> A, long[] temp, int left, int right) {
long count = 0;
if (left < right) {
int mid = (left + right) / 2;
count += mergeSortAndCount(A, temp, left, mid);
count += mergeSortAndCount(A, temp, mid + 1, right);
count += mergeAndCount(A, temp, left, mid, right);
}
return count;
}
private static long mergeAndCount(List<Long> A, long[] temp, int left, int mid, int right) {
int i = left;
int j = mid + 1;
int k = left;
long count = 0;
while (i <= mid && j <= right) {
if (A.get(i) <= A.get(j)) {
temp[k++] = A.get(i++);
} else {
temp[k++] = A.get(j++);
count += (mid - i + 1); // Count inversions
}
}
while (i <= mid) {
temp[k++] = A.get(i++);
}
while (j <= right) {
temp[k++] = A.get(j++);
}
for (i = left; i <= right; i++) {
A.set(i, temp[i]);
}
return count;
}
public static void main(String[] args) {
List<Long> A = Arrays.stream(args[0].split(",")).map(s -> Long.parseLong(s)).collect(Collectors.toList());
System.out.println(countInversions(A));
}
}
2.4.4 Find median different size (Java)
package q9266;
import java.util.*;
import java.util.stream.*;
public class CTJ9266 {
public static int findMediandifferentSize(List<Integer> A, List<Integer> B) {
int n = A.size();
int m = B.size();
int[] merged = new int[n + m];
int i = 0, j = 0, k = 0;
while (i < n && j < m) {
if (A.get(i) <= B.get(j)) {
merged[k++] = A.get(i++);
} else {
merged[k++] = B.get(j++);
}
}
while (i < n) {
merged[k++] = A.get(i++);
}
while (j < m) {
merged[k++] = B.get(j++);
}
int mid = (n + m) / 2;
if ((n + m) % 2 == 0) {
return (merged[mid - 1] + merged[mid]) / 2;
} else {
return merged[mid];
}
}
public static void main(String[] args) {
List<Integer> A = Arrays.stream(args[0].split(",")).map(s -> Integer.parseInt(s)).collect(Collectors.toList());
List<Integer> B = Arrays.stream(args[1].split(",")).map(s -> Integer.parseInt(s)).collect(Collectors.toList());
System.out.println( findMediandifferentSize(A, B));
}
}
2.4.5 String rotation check (Java)
package q1071;
public class CTJ1071 {
public static String StringRotationCheck(String Str1, String Str2) {
if (Str1.length() != Str2.length()) {
return "NO";
}
String concatenated = Str1 + Str1;
if (concatenated.contains(Str2)) {
return "YES";
}
return "NO";
}
public static void main(String[] args) {
String Str1 = args[0];
String Str2 = args[1];
System.out.println(StringRotationCheck(Str1, Str2));
}
}
2.4.7 Book Sort (Java)
package q78;
import java.util.*;
import java.util.stream.*;
public class CTJ78 {
public static List<Integer> BookSort(List<Integer> BookId) {
Map<Integer, Integer> frequencyMap = new HashMap<>();
for (int id : BookId) {
frequencyMap.put(id, frequencyMap.getOrDefault(id, 0) + 1);
}
List<Integer> sortedBookIds = new ArrayList<>(BookId);
sortedBookIds.sort((a, b) -> {
int freqComparison = Integer.compare(frequencyMap.get(a), frequencyMap.get(b));
if (freqComparison != 0) {
return freqComparison;
} else {
return Integer.compare(a, b);
}
});
return sortedBookIds;
}
public static void main(String[] args) {
List<Integer> BookId = Arrays.stream(args[0].split(",")).map(s -> Integer.parseInt(s)).collect(Collectors.toList());
System.out.println( BookSort(BookId).stream().map(String::valueOf).collect(Collectors.joining(",")));
}
}
2.4.8 Search in rotated array (Java)
package q1635;
import java.util.*;
import java.util.stream.*;
public class CTJ1635 {
public static int searchRotatedArray(List<Integer> Arr, int target) {
int left = 0;
int right = Arr.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (Arr.get(mid) == target) {
return mid;
}
if (Arr.get(left) <= Arr.get(mid)) {
if (Arr.get(left) <= target && target < Arr.get(mid)) {
right = mid - 1;
} else {
left = mid + 1;
}
} else {
if (Arr.get(mid) < target && target <= Arr.get(right)) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return -1;
}
public static void main(String[] args) {
List<Integer> Arr = Arrays.stream(args[0].split(",")).map(s -> Integer.parseInt(s)).collect(Collectors.toList());
int target = Integer.parseInt(args[1]);
System.out.println(searchRotatedArray(Arr, target));
}
}
2.4.9 Index mapping (Java)
package q1634;
import java.util.*;
import java.util.stream.*;
public class CTJ1634 {
public static List<Integer> indexmapping(List<Integer> Arr) {
List<Integer> result = new ArrayList<>();
for (int i = 0; i < Arr.size(); i++) {
if (Arr.get(i).equals(i)) {
result.add(i);
}
}
if (result.isEmpty()) {
result.add(-1);
}
return result;
}
public static void main(String[] args) {
List<Integer> Arr = Arrays.stream(args[0].split(",")).map(s -> Integer.parseInt(s)).collect(Collectors.toList());
System.out.println(indexmapping(Arr).stream().map(String::valueOf).collect(Collectors.joining(",")));
}
}
2.4.10 Find median of same size arrays (Java)
package q9265;
import java.util.*;
import java.util.stream.*;
public class CTJ9265 {
public static int findMedianSameSize(List<Integer> A, List<Integer> B) {
int n = A.size();
List<Integer> merged = new ArrayList<>(n * 2);
int i = 0, j = 0;
while (i < n && j < n) {
if (A.get(i) <= B.get(j)) {
merged.add(A.get(i));
i++;
} else {
merged.add(B.get(j));
j++;
}
}
while (i < n) {
merged.add(A.get(i));
i++;
}
while (j < n) {
merged.add(B.get(j));
j++;
}
int mid1 = merged.get(n - 1);
int mid2 = merged.get(n);
return (mid1 + mid2) / 2;
}
public static void main(String[] args) {
List<Integer> A = Arrays.stream(args[0].split(",")).map(s -> Integer.parseInt(s)).collect(Collectors.toList());
List<Integer> B = Arrays.stream(args[1].split(",")).map(s -> Integer.parseInt(s)).collect(Collectors.toList());
System.out.println( findMedianSameSize(A, B));
}
}
2.5.1 Duplicates (Java)
package q13629;
import java.util.*;
public class CTJ13629 {
static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
static class LinkedList {
Node head;
public void append(int data) {
if (head == null) {
head = new Node(data);
return;
}
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = new Node(data);
}
public void removeDuplicates() {
Set<Integer> seen = new HashSet<>();
Node current = head;
Node prev = null;
while (current != null) {
if (seen.contains(current.data)) {
prev.next = current.next;
} else {
seen.add(current.data);
prev = current;
}
current = current.next;
}
}
public void printList() {
Node current = head;
while (current != null) {
System.out.print(current.data + (current.next != null ? " " : " "));
current = current.next;
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
LinkedList list = new LinkedList();
for (int i = 0; i < N; i++) {
list.append(scanner.nextInt());
}
list.removeDuplicates();
list.printList();
scanner.close();
}
}
2.5.2 List Compression (Java)
package q13669;
import java.util.*;
class Node {
int val;
Node next;
Node(int val) {
this.val = val;
this.next = null;
}
}
public class CTJ13669 {
public static void CompressList(Node head) {
if (head == null) return;
Map<Integer, Integer> countMap = new HashMap<>();
Node current = head;
while (current != null) {
countMap.put(current.val, countMap.getOrDefault(current.val, 0) + 1);
current = current.next;
}
Node dummy = new Node(0);
Node prev = dummy;
current = head;
while (current != null) {
if (countMap.get(current.val) == 1) {
prev.next = current;
prev = prev.next;
}
current = current.next;
}
prev.next = null;
Node resultHead = dummy.next;
if (resultHead == null) {
System.out.println("null");
} else {
while (resultHead != null) {
System.out.print(resultHead.val + (resultHead.next != null ? " " : " "));
resultHead = resultHead.next;
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
Node head = null;
Node tail = null;
for (int i = 0; i < N; i++) {
int value = scanner.nextInt();
Node newNode = new Node(value);
if (head == null) {
head = newNode;
tail = head;
} else {
tail.next = newNode;
tail = tail.next;
}
}
CompressList(head);
scanner.close();
}
}
2.5.3 Clockwise (Java)
package q13670;
import java.util.Scanner;
class Node {
int val;
Node next;
Node(int val) {
this.val = val;
this.next = null;
}
}
public class CTJ13670 {
public static Node rotateClockwise(Node head, int k) {
if (head == null || head.next == null || k == 0) {
return head;
}
Node current = head;
int length = 1;
while (current.next != null) {
current = current.next;
length++;
}
current.next = head;
k = k % length;
if (k == 0) {
current.next = null;
return head;
}
int stepsToNewHead = length - k;
current = head;
for (int i = 0; i < stepsToNewHead - 1; i++) {
current = current.next;
}
Node newHead = current.next;
current.next = null;
return newHead;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
Node head = null;
Node tail = null;
for (int i = 0; i < N; i++) {
int value = scanner.nextInt();
Node newNode = new Node(value);
if (head == null) {
head = newNode;
tail = head;
} else {
tail.next = newNode;
tail = tail.next;
}
}
int k = scanner.nextInt();
head = rotateClockwise(head, k);
Node current = head;
while (current != null) {
System.out.print(current.val + (current.next != null ? " " : " "));
current = current.next;
}
System.out.println();
scanner.close();
}
}
2.5.4 Super merge (Java)
package q14734;
import java.util.*;
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class CTJ14734 {
public ListNode mergeKLists(List<ListNode> lists) {
if (lists == null || lists.size() == 0) {
return null;
}
PriorityQueue<ListNode> minHeap = new PriorityQueue<>(Comparator.comparingInt(node -> node.val));
for (ListNode head : lists) {
if (head != null) {
minHeap.add(head);
}
}
ListNode dummy = new ListNode(0);
ListNode current = dummy;
while (!minHeap.isEmpty()) {
ListNode smallestNode = minHeap.poll();
current.next = smallestNode;
current = current.next;
if (smallestNode.next != null) {
minHeap.add(smallestNode.next);
}
}
return dummy.next;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int K = scanner.nextInt();
List<ListNode> lists = new ArrayList<>();
for (int i = 0; i < K; i++) {
int size = scanner.nextInt();
ListNode dummyHead = new ListNode(0);
ListNode current = dummyHead;
for (int j = 0; j < size; j++) {
int value = scanner.nextInt();
current.next = new ListNode(value);
current = current.next;
}
lists.add(dummyHead.next);
}
CTJ14734 merger = new CTJ14734();
ListNode mergedHead = merger.mergeKLists(lists);
ListNode current = mergedHead;
while (current != null) {
System.out.print(current.val + (current.next != null ? " " : ""));
current = current.next;
}
System.out.println(" ");
}
}
2.5.5 List Addition (Java)
package q14742;
import java.util.Scanner;
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class CTJ14742 {
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode current = dummyHead;
int carry = 0;
while (l1 != null || l2 != null || carry > 0) {
int sum = carry;
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if (l2 != null) {
sum += l2.val;
l2 = l2.next;
}
carry = sum / 10;
current.next = new ListNode(sum % 10);
current = current.next;
}
return dummyHead.next;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int m = scanner.nextInt();
ListNode l1 = null, tail1 = null;
for (int i = 0; i < m; i++) {
int value = scanner.nextInt();
ListNode newNode = new ListNode(value);
if (l1 == null) {
l1 = newNode;
tail1 = l1;
} else {
tail1.next = newNode;
tail1 = tail1.next;
}
}
int n = scanner.nextInt();
ListNode l2 = null, tail2 = null;
for (int i = 0; i < n; i++) {
int value = scanner.nextInt();
ListNode newNode = new ListNode(value);
if (l2 == null) {
l2 = newNode;
tail2 = l2;
} else {
tail2.next = newNode;
tail2 = tail2.next;
}
}
ListNode result = addTwoNumbers(l1, l2);
while (result != null) {
System.out.print(result.val + (result.next != null ? " " : " "));
result = result.next;
}
System.out.println();
scanner.close();
}
}
2.5.6 Node swapping (Java)
package q14743;
import java.util.Scanner;
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class CTJ14743 {
public static ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = head.next;
ListNode prev = null;
while (head != null && head.next != null) {
ListNode first = head;
ListNode second = head.next;
first.next = second.next;
second.next = first;
if (prev != null) {
prev.next = second;
}
prev = first;
head = first.next;
}
return newHead;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
ListNode head = null, tail = null;
for (int i = 0; i < n; i++) {
int value = scanner.nextInt();
ListNode newNode = new ListNode(value);
if (head == null) {
head = newNode;
tail = head;
} else {
tail.next = newNode;
tail = tail.next;
}
}
ListNode result = swapPairs(head);
while (result != null) {
System.out.print(result.val + (result.next != null ? " " : " "));
result = result.next;
}
System.out.println();
scanner.close();
}
}
2.5.7 ACMICPC coding competetion (Java)
package q14748;
import java.util.Scanner;
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class CTJ14748 {
public static int maxTwinSum(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode secondHalf = reverseList(slow);
ListNode firstHalf = head;
int maxSum = 0;
while (secondHalf != null) {
maxSum = Math.max(maxSum, firstHalf.val + secondHalf.val);
firstHalf = firstHalf.next;
secondHalf = secondHalf.next;
}
return maxSum;
}
public static ListNode reverseList(ListNode head) {
ListNode prev = null;
while (head != null) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
ListNode head = null, tail = null;
for (int i = 0; i < n; i++) {
int value = scanner.nextInt();
ListNode newNode = new ListNode(value);
if (head == null) {
head = newNode;
tail = head;
} else {
tail.next = newNode;
tail = tail.next;
}
}
int result = maxTwinSum(head);
System.out.println(result);
scanner.close();
}
}
2.10.1 Minimum No. Of Platforms (Java)
package q1721;
import java.util.*;
import java.util.stream.*;
public class CTJ1721 {
public static int minimumNumberOfPlatforms(int n, List<Integer> arrival, List<Integer> departure) {
int[] arr = new int[n];
int[] dep = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = arrival.get(i);
dep[i] = departure.get(i);
}
Arrays.sort(arr);
Arrays.sort(dep);
int platformNeeded = 1;
int result = 1;
int i = 1;
int j = 0;
while (i < n && j < n) {
if (arr[i] <= dep[j]) {
platformNeeded++;
i++;
} else {
platformNeeded--;
j++;
}
result = Math.max(result, platformNeeded);
}
return result;
}
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
List<Integer> arrival = Arrays.stream(args[1].split(",")).map(s -> Integer.parseInt(s)).collect(Collectors.toList());
List<Integer> departure = Arrays.stream(args[2].split(",")).map(s -> Integer.parseInt(s)).collect(Collectors.toList());
System.out.println( minimumNumberOfPlatforms(n, arrival, departure));
}
}
2.11.6 Sandwitch inverted (Java)
package q18245;
import java.util.Scanner;
public class CTJ18245 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
for (int i = N / 2; i >= 1; i--) {
for (int j = 0; j < i; j++) {
System.out.print(i);
if (j < i - 1) {
System.out.print("*");
}
}
System.out.println();
}
for (int i = 1; i <= N / 2; i++) {
for (int j = 0; j < i; j++) {
System.out.print(i);
if (j < i - 1) {
System.out.print("*");
}
}
System.out.println();
}
}
}
2.11.8 Right Diamond Pattern (Java)
package q18243;
import java.util.Scanner;