diff --git a/Anna_Smith.json b/Anna_Smith.json new file mode 100644 index 0000000..f1692af --- /dev/null +++ b/Anna_Smith.json @@ -0,0 +1,6 @@ +{ + "firstName": "Anna", + "lastName": "Smith", + "monthlyIncome": 2000, + "nbHoursPerWeek": 40 +} \ No newline at end of file diff --git a/Billy_Leech.json b/Billy_Leech.json new file mode 100644 index 0000000..599f774 --- /dev/null +++ b/Billy_Leech.json @@ -0,0 +1 @@ +{"firstName":"Billy","lastName":"Leech","monthlyIncome":920,"nbHoursPerWeek":40} \ No newline at end of file diff --git a/Coding_Ninjas/src/main/java/BonusProblems_StacksandQueues/MaximumrectangularArea.java b/Coding_Ninjas/src/main/java/BonusProblems_StacksandQueues/MaximumrectangularArea.java deleted file mode 100755 index 58f66e4..0000000 --- a/Coding_Ninjas/src/main/java/BonusProblems_StacksandQueues/MaximumrectangularArea.java +++ /dev/null @@ -1,95 +0,0 @@ -package BonusProblems_StacksandQueues; - -import java.util.Scanner; -import java.util.Stack; - -public class MaximumrectangularArea { - /* - You are given a binary matrix. You have to print the maximum area possible for a sub-matrix with all 1's. -Input Format: -The first line of input contains two integers N (number of rows) and M (number of columns) of the binary matrix. -The second line of input contains N*M space-separated elements of the binary matrix. -Output Format: -The only output line contains a single integer which will be the maximum area possible of sub-matrix of all 1's. -Sample Input: -4 5 -0 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 -Sample Output: -10 -Explanation: -The matrix for the above Sample Input is: -0 1 0 0 0 -1 1 1 1 1 -1 1 1 1 1 -1 0 0 0 0 - -The maximum size rectangle in this binary matrix is: -1 1 1 1 1 -1 1 1 1 1 - -So, the area of the rectangle is=5*2=10 - - */ - - public static void main(String[] args) { - Scanner s = new Scanner(System.in); - int N = s.nextInt(); - int M =s.nextInt(); - int[][] arr = new int[N][M]; - for (int i=0;i res = new Stack<>(); - int top_one ; - int maxA = 0; - int area =0; - int i=0; - while (i0) { - if (n > 4) { - int m = n / 4; - int j = 0, start = 0; - int temp = 0; - while (j < m) { - int small = Integer.MAX_VALUE, SecSmall = Integer.MAX_VALUE; - for (int i = start; i < 4 + (4 * j); i++) { - if (arr[i] < small) { - SecSmall = small; - small = arr[i]; - } else if (arr[i] == small) { - continue; - } else if (arr[i] > small) { - if (arr[i] < SecSmall) { - SecSmall = arr[i]; - } - } - } - start = 4 + (4 * j); - temp = temp + SecSmall; - j++; - } - System.out.println(temp); - } else { - int small = Integer.MAX_VALUE, SecSmall = Integer.MAX_VALUE; - for (int i = 0; i < n; i++) { - if (arr[i] < small) { - SecSmall = small; - small = arr[i]; - } else if (arr[i] == small) { - continue; - } else if (arr[i] > small) { - if (arr[i] < SecSmall) { - SecSmall = arr[i]; - } - } - } - System.out.println(SecSmall); - } - t--; - } - } -} diff --git a/Coding_Ninjas/src/main/java/FullTest2/AppleCost.java b/Coding_Ninjas/src/main/java/FullTest2/AppleCost.java deleted file mode 100755 index fc07280..0000000 --- a/Coding_Ninjas/src/main/java/FullTest2/AppleCost.java +++ /dev/null @@ -1,54 +0,0 @@ -package FullTest2; - -import java.util.Arrays; -import java.util.Scanner; - -public class AppleCost { -/* -You went to a fruit store to purchase some apples. Each apple has its own price. There is an offer going on at the store that buy three apples and get the least cost one for free. -For example, let the prices of the apples be: 10 3 2 4 6 4 9. If you arrange them into groups: (10, 3, 2), (4, 6, 4) and (9), you would get the apples priced 2 from the first group for free and the apple priced 4 from the second group. You won’t get anything for free from the third group because it contains only one apple. -Your task is to minimize the cost of apples. -Input Format: -The first line of input contains the integer N, the number of apples to be bought. -Each of the following N lines contains a single integer Ci, the price of each apple. -Constraints: -1 ≤ N ≤ 100000 -1 ≤ Ci ≤ 100000 -Time limit : 1 sec -Output Format: -The first and only line of output must contain the required minimal price. -Sample Input 1: -4 -3 -2 -3 -2 -Sample Output 1: -8 -Explanation: -Make 2 triplets (3,3,2) and (2) in first group 2 is for free so total cost is 3+3+2=6. - */ - public static void main(String[] args) { - Scanner s = new Scanner(System.in); - int n = s.nextInt(); - int apples[] = new int[n]; - for(int i=0;i=0){ - price+=apples[grp+1]+apples[grp+2]; - grp-=3; - } - grp+=2; - if(grp>0){ - price+=apples[0]+apples[1]; - }else if(grp == 0){ - price+=apples[0]; - } - System.out.println(price); - } -} diff --git a/Coding_Ninjas/src/main/java/FullTest2/BatmanVsJoker.java b/Coding_Ninjas/src/main/java/FullTest2/BatmanVsJoker.java deleted file mode 100755 index d116197..0000000 --- a/Coding_Ninjas/src/main/java/FullTest2/BatmanVsJoker.java +++ /dev/null @@ -1,53 +0,0 @@ -package FullTest2; - -import java.util.Scanner; -import java.util.Stack; - -public class BatmanVsJoker { - /* - Gotham has been attacked by Joker . Bruce Wayne has deployed automatic machine gun at each tower of Gotham. -All the towers in Gotham are in straight line. -You are given no of towers 'n' followed by height of 'n' towers. -For every tower(p), find the height of the closest tower (towards the right), greater than the height of tower(p). -Now , Print sum of all such heights (mod 1000000007). -Note : If for a tower(k) , no such tower exsits then take its height as 0. -Input Format: -First line contains 'n' denoting no of towers. -This is followed by 'n' spaced integers h1,h2.....h(n) representing height of towers. -Output Format: -On a single line, output the sum(mod 1000000007). -Constraints: -1<=n<=100000 -0<=h[i]<=100000 -Sample Input: -9 -112 133 161 311 122 512 1212 0 19212 -Sample Output: -41265 - - - */ - - public static void main(String[] args) { - - Scanner s = new Scanner(System.in); - int n = s.nextInt(); - int[] arr = new int[n]; - for(int i =0;i ss = new Stack(); - int sum =0,mod = 1000000007; - for(int i=0;iss.peek()){ - while(!ss.isEmpty() && arr[i]>ss.peek()){ - ss.pop(); - sum=(sum+arr[i])%mod; - } - } - ss.push(arr[i]); - } - System.out.println(sum); - } -} diff --git a/Coding_Ninjas/src/main/java/FullTest2/HappyNumber.java b/Coding_Ninjas/src/main/java/FullTest2/HappyNumber.java deleted file mode 100755 index 5f4e12d..0000000 --- a/Coding_Ninjas/src/main/java/FullTest2/HappyNumber.java +++ /dev/null @@ -1,47 +0,0 @@ -package FullTest2; - -public class HappyNumber { - /* - Given a number n, find if it is a happy number or not. A number is called happy if a - sequence of steps leads to 1 where in each sequence of step the number is replaced by - sum of square of its digit, i.e., if we start with Happy Number and keep replacing it - with digits square sum, we reach 1. -Input Format -Line 1 : An integer n. -Output Format -true, if number is a happy number, otherwise false. -Input Constraints -1 <= n <= 10^4 -Sample Input 1: -13 -Sample Output 1: -true -Sample Output 1 explanation -1^2 + 3^2 = 10 -1^2 + 0^2 = 1 -Since we reached 1, 13 is happy number -Sample Input 2: -14 -Sample Output 2: -false - */ - public static void main(String[] args) { - - - } - public static boolean findHappyNumber(int n) { - - - if(n==1) { - return true; - } - if(n == 2 || n == 3 || n == 4 || n == 5 || n == 6 || n == 7 || n == 8 || n == 9 || n == 0) return false; - int n1=0; - while (n!=0){ - n1=n1+(n%10)*(n%10); - n=n/10; - } - return findHappyNumber(n1); - - } -} diff --git a/Coding_Ninjas/src/main/java/FullTest2/LaLiga.java b/Coding_Ninjas/src/main/java/FullTest2/LaLiga.java deleted file mode 100755 index eade6d1..0000000 --- a/Coding_Ninjas/src/main/java/FullTest2/LaLiga.java +++ /dev/null @@ -1,28 +0,0 @@ -package FullTest2; - -import java.util.Scanner; - -public class LaLiga { - /* - This is Super - Sunday for football fans. It is the final night. It is Barcelona vs Real Madrid. Moreover, the talking point of this year's La liga is Sevilla becoming the last team to qualify for the playoffs with just 12 points. -The question is if 'N' teams are playing in the La Liga, what is the minimum number of points at which a team may qualify for a play off? -Note: 1. You have to workaround a solution in the premises of the format, where a winning team is awarded 2 points and losing team is awarded 0 points. 4 teams qualify for the playoffs, after league stage where each team plays all the other teams once. -2. We have to assume all the matches arrive to a result. (no draw) -Input format: -The first and only line of input contains N, that denotes number of teams which are participating in the League. The value of N lies in the range: [5, 100000]. -Constraints: -Time Limit: 1 second -Output format: -The first and only line of output contains minimum number of points at which a team may qualify for the play offs . -Sample Input 1: -8 -Sample Output 1: -8 - */ - - public static void main(String[] args) { - Scanner s = new Scanner(System.in); - int n = s.nextInt(); - System.out.println((n-4)*2); - } -} diff --git a/Coding_Ninjas/src/main/java/Group2Set6/AllPossible.java b/Coding_Ninjas/src/main/java/Group2Set6/AllPossible.java deleted file mode 100755 index 8626d9c..0000000 --- a/Coding_Ninjas/src/main/java/Group2Set6/AllPossible.java +++ /dev/null @@ -1,55 +0,0 @@ -package Group2Set6; - -public class AllPossible { - /* - Given two integers a and b. You need to find and return the count of possible ways in which we can represent the number a as the sum of unique integers raise to the power b. -For example: if a = 10 and b = 2, only way to represent 10 as sum of unique integers raised to power 2 is- -10 = 1^2 + 3^2 -Hence, answer is 1. -Note : x^y represents x raise to the power y -Input Format: -The first line of input contains two space separated integers, that denote the value of a and b. -Output Format: -The first and only line of output contains count of ways in which a can be represented as sum of unique integers raised to power b. -Constraints : -1 <= a <= 10^4 -1 <= b <= 20 -Time Limit: 1 second -Sample Input 1 : -10 2 -Sample Output 1 : -1 -Sample Input 2 : -100 2 -Sample Output 2 : -3 -Explanation: -Following are the three ways: -1. 100 = 10^2 -2. 100 = 8^2 + 6^2 -3. 100 = 7^2+5^2+4^2+3^2+1^2 - */ - static int res = 0; - static int Possiblity(int num, int x, int k, int n) { - if (x == 0) - res++; - int r = (int)Math.floor(Math.pow(num, 1.0 / n)); - for (int i = k + 1; i <= r; i++) { - int a = x - (int)Math.pow(i, n); - if (a >= 0) - Possiblity(num, x - (int)Math.pow(i, n), i, n); - } - return res; - } - - // Wrapper over checkRecursive() - static int check(int x, int n) - { - return Possiblity(x, x, 0, n); - } - - public static void main(String[] args) - { - System.out.println(check(100, 2)); - } -} diff --git a/Coding_Ninjas/src/main/java/Group2Set6/GameNumber.java b/Coding_Ninjas/src/main/java/Group2Set6/GameNumber.java deleted file mode 100755 index ce2ea1f..0000000 --- a/Coding_Ninjas/src/main/java/Group2Set6/GameNumber.java +++ /dev/null @@ -1,31 +0,0 @@ -package Group2Set6; - -public class GameNumber { - /* - Mirko and Slavko are playing a game. Mirko’s turn is first and he chooses a non-empty set of pairs of numbers between 1 and N (inclusive) under the condition that the numbers that comprise a pair are mutually relatively prime. The numbers that comprise a pair must be different. For example, for N = 5, Mirko could have chosen the following set of pairs: {{1, 2}, {3, 4}, {2, 5}, {3, 5}}. -Slavko’s turn is second and his goal is to find a partition for Mirko’s set of pairs. Mirko’s set of pairs has a partition if an integer x from the set {2, 3, ..., N} exists such that, for each pair {a, b}, one of the following holds: -• a, b < x -• a, b ≥ x -For example, a set of pairs {{1, 2}, {3, 4}} has a partition x = 3. If a partition exists, Slavko will surely find it. -Mirko wins if Slavko can’t find a partition for his set. Determine how many different sets of pairs exists that Mirko can initially choose and be sure of his victory. Given the fact that the total number of sets can be very large, output the number modulo 1000000000. -Input Format: -The first line of input contains the integer N. -Constraints: -1 ≤ N ≤ 20 -Time limit : 1 sec -Output Format: -The first and only line of output must contain the required number. -Sample Input 1: -2 -Sample Output 1: -1 -Sample Input 2: -3 -Sample Output 2: -5 -Explanation: -Clarification of the first example: The only set of pairs that meets the given requirements is {{1, 2}}. -Clarification of the second example: An example of a set that meets the given requirements is {{1, 3}, {1, 2}}. - */ - -} diff --git a/Coding_Ninjas/src/main/java/Group2Set6/GetAllSubarrayToP.java b/Coding_Ninjas/src/main/java/Group2Set6/GetAllSubarrayToP.java deleted file mode 100755 index 955e289..0000000 --- a/Coding_Ninjas/src/main/java/Group2Set6/GetAllSubarrayToP.java +++ /dev/null @@ -1,30 +0,0 @@ -package Group2Set6; - -public class GetAllSubarrayToP { - /* - A sequence of integers N1, N2, N3, .... Nm. This sequence can generate an integer P, only if it is possible to find another sequence of integers: O1, O2, O3 .... Om such that: -Equation (1) -> O1 * N1 + O2 * N2 + .... Om * Nm = P -For this problem, you are given a sequence of n integers, T1, T2, T3, T4 ... Tn, and on this sequence, you are asked x queries. In each query, you are given an integer P, the solution to each query is count of all subarrays (each subarray is defined by indices [i, j], where i and j are inclusive) such that the integers in the subarray T[i], T[i+1] .... T[j] generates P, according to the equation 1. -Input Format: -The first line of input contains a single integer, that denotes the value of n. The value of n lies in the range: [1, 100000]. The following line of input contains n space separated integers. The value of each integer lies in the range [1, 1000000000]. The following line of input contains number of queries, that denotes the value of x. The value of x lies in the range [1, 100000]. The following x lines, contain a single integer P. The value P lies in the range [1, 1000000]. -Constraints: -Time Limit: 1 second -Output format: -There are x lines of output in each query. For each of the x lines, print the count of subarrays that generate P. -Sample Input 1: -4 -2 4 3 6 -3 -1 -2 -3 -Sample Output 1: -4 -6 -6 -Explanation: -For the first query, the four subarrays are: [4,3], [2, 4, 3], [4, 3, 6], [2, 4, 3, 6]. -For the second query, the six subarrays are: [4,3], [2, 4, 3], [4, 3, 6], [2, 4, 3, 6], [2], [2, 4]. -For the first query, the four subarrays are: [4,3], [2, 4, 3], [4, 3, 6], [2, 4, 3, 6], [3], [3, 6]. - */ -} diff --git a/Coding_Ninjas/src/main/java/Group2Set6/MaxSubArray.java b/Coding_Ninjas/src/main/java/Group2Set6/MaxSubArray.java deleted file mode 100755 index 9998a22..0000000 --- a/Coding_Ninjas/src/main/java/Group2Set6/MaxSubArray.java +++ /dev/null @@ -1,52 +0,0 @@ -package Group2Set6; - -public class MaxSubArray { - /* - You are given an array (ARR) of length N, consisting of integers. You have to find the sum of the subarray (including empty subarray) having maximum sum among all subarrays. -A subarray is a contiguous segment of an array. In other words, a subarray can be formed by removing 0 or more integers from the beginning, and 0 or more integers from the end of an array. -Note : -The sum of an empty subarray is 0. -Input Format : -The first line of input contains an integer N, representing the length of the array. - -The second line of input contains N single space-separated integers, denoting the elements of the array. -Output Format : -In the only output line, output the maximum subarray sum. -Note : -You are not required to print the output explicitly, it has already been taken care of. Just implement the function. -Constraints : -1 <= N <= 10^6 --10^6 <= A[i] <= 10^6 - -where N is the length of the array. -A[i] represents the numbers present in the array. - -Time limit: 1sec -Sample Input 1 : -9 -1 2 7 -4 3 2 -10 9 1 -Sample Output 1 : -11 -Explanation for Sample 1 : -The subarray yielding maximum sum is [1, 2, 7, -4, 3, 2]. -Sample Input 2 : -6 -10 20 -30 40 -50 60 -Sample Input 2 : -60 - */ - public static long maxSubarraySum(int[] arr, int n) { - // write your code here - long MAX = 0, Dmax = 0; - - for (int i = 0; i < n; i++) - { - Dmax = Dmax + arr[i]; - if (MAX < Dmax) - MAX = Dmax; - if (Dmax < 0) - Dmax = 0; - } - return MAX; - } -} diff --git a/Coding_Ninjas/src/main/java/Group2Set6/SumOfPowerOf3.java b/Coding_Ninjas/src/main/java/Group2Set6/SumOfPowerOf3.java deleted file mode 100755 index 40ee154..0000000 --- a/Coding_Ninjas/src/main/java/Group2Set6/SumOfPowerOf3.java +++ /dev/null @@ -1,59 +0,0 @@ -package Group2Set6; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -public class SumOfPowerOf3 { - /* - Given an integer n, return true if it is possible to represent n as the sum of distinct powers of three. Otherwise, return false. -Input Format: -First line of input contains an integer T, which represents the number of test cases. -Next T lines of input contains an integer n. -Constraints: -1 <= T <= 1000 -1 <= n <= 10^4 -Output Format: - Print true if it is possibe to represent n as explained, otherwise print false. -Sample Input 1: -1 -91 -Sample Output 1: -true -Explanation: -3^0 + 3^2 + 3^4 -Sample Input 2: -2 -12 -21 -Sample Output 2: -true -false - - */ - - static public boolean checkPowersOfThree(int n) { - - while (n > 0) { - if (n % 3 == 2) { - return false; - } - - n /= 3; - } - return true; - } - static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - - public static void main(String[] args) throws IOException { - - int t = Integer.parseInt(br.readLine().trim()); - while (t != 0) - { - int n = Integer.parseInt(br.readLine().trim()); - System.out.println(checkPowersOfThree(n)); - t--; - } - - } -} diff --git a/Coding_Ninjas/src/main/java/Group2Set6/WalkingStyle.java b/Coding_Ninjas/src/main/java/Group2Set6/WalkingStyle.java deleted file mode 100755 index 0c4ad65..0000000 --- a/Coding_Ninjas/src/main/java/Group2Set6/WalkingStyle.java +++ /dev/null @@ -1,26 +0,0 @@ -package Group2Set6; - -public class WalkingStyle { - /* - Mr. P is quite upset today and he is walking in some unique way. He starts from the origin (0, 0), and in exactly 1 second, he can either move up 1 unit, move right 1 unit, or stay still. In other words, from position (x,y) , Mr. P can spend one second to move to: -->(x+1,y) -->(x,y+1) -->(x,y) -After T seconds, a villager who sees him reports that Mr. P lies on or inside a square of side-length s with coordinates (X,Y), (X+s,Y), (X,Y+s), (X+s,Y+s). Calculate how many points with integer coordinates on or inside this square could be the Mr. P's position after exactly T seconds -Input Format: -The first and only line of input contains four space-separated integers: X, Y, s, and T. -Constraints: -0 ≤ X,Y ≤ 100 -1 ≤ s ≤ 100 -0 ≤ T ≤ 400 -Time limit : 1 sec -Output Format: -Print the number of points with integer coordinates that could be the Mr. P's position after T seconds. -Sample Input 1: -2 2 3 6 -Sample Output 1: -6 - */ - - -} diff --git a/Coding_Ninjas/src/main/java/Group2_set4/BreakNumber.java b/Coding_Ninjas/src/main/java/Group2_set4/BreakNumber.java deleted file mode 100755 index 2d85be5..0000000 --- a/Coding_Ninjas/src/main/java/Group2_set4/BreakNumber.java +++ /dev/null @@ -1,73 +0,0 @@ -package Group2_set4; - -import java.util.Scanner; - -public class BreakNumber { - /* - Given an integer n, break it into smaller numbers such that their summation is equal to n. Print all such combinations in different lines. -Note : [1, 2, 1] and [1,1, 2] are same, so print the particular sequence with increasing order. Order of different combinations doesn't matter. -Input format : -Integer n -Output format : -Print all possible combinations in different lines -Constraints : -1 <= n <= 100 -Input : -4 -Output : -1 1 1 1 -1 1 2 -1 3 -2 2 -4 - */ - static Scanner s = new Scanner(System.in); - - public static void main(String[] args) { - int number = s.nextInt(); - printCombination(number); - } - public static void printCombination(int num){ - //Write your code here - printAllUniqueParts(num); - - } - - static void printArray(int p[], int n) - { - for (int i = 0; i < n; i++) { - System.out.print(p[i] + " "); - } - System.out.println(); - } - - static void printAllUniqueParts(int n) { - int[] p = new int[n]; - int k = 0; - p[k] = n; - - - while (true) { - - printArray(p, k + 1); - - int rem_val = 0; - while (k >= 0 && p[k] == 1) { - rem_val += p[k]; - k--; - } - if (k < 0) return; - - p[k]--; - rem_val++; - while (rem_val > p[k]) { - p[k + 1] = p[k]; - rem_val = rem_val - p[k]; - k++; - } - - p[k + 1] = rem_val; - k++; - } - } -} diff --git a/Coding_Ninjas/src/main/java/Group2_set4/Demo.java b/Coding_Ninjas/src/main/java/Group2_set4/Demo.java deleted file mode 100755 index 751c84c..0000000 --- a/Coding_Ninjas/src/main/java/Group2_set4/Demo.java +++ /dev/null @@ -1,59 +0,0 @@ -package Group2_set4; - -import java.util.Scanner; - -public class Demo { - static Scanner s = new Scanner(System.in); - - public static void main(String[] args) { - int number = s.nextInt(); - printCombination(number); - } - public static void printCombination(int num){ - //Write your code here - printAllUniqueParts(num); - - } - static void printArray(int p[], int n) - { - for (int i = 0; i < n; i++) { - System.out.print(p[i] + " "); - } - System.out.println(); - } - static void printAllUniqueParts(int n) { - int[] p = new int[n]; - int k = n-1; - p[k] = 0; - - - - while (true) { - - while (k>=0 && p[k]==0){ - p[k]=1; - k--; - } - printArray(p, n-k ); - -// int rem_val = 0; -// while (k >= 0 && p[k] == 1) { -// rem_val += p[k]; -// k--; -// } -// -// -// if (k < 0) return; -// -// p[k]--; -// rem_val++; -// while (rem_val > p[k]) { -// p[k + 1] = p[k]; -// rem_val = rem_val - p[k]; -// k++; -// } -// p[k + 1] = rem_val; -// k++; - } - } -} diff --git a/Coding_Ninjas/src/main/java/Group2_set4/GroupSum.java b/Coding_Ninjas/src/main/java/Group2_set4/GroupSum.java deleted file mode 100755 index 6e57db6..0000000 --- a/Coding_Ninjas/src/main/java/Group2_set4/GroupSum.java +++ /dev/null @@ -1,33 +0,0 @@ -package Group2_set4; - -import java.util.Scanner; - -public class GroupSum { - - static boolean subsetSumToKIdentical(int input[], int n, int k) { - for (int i = 0; i < (n - 1); i++) { - for (int j = (i + 1); j < n; j++) { - if (input[i] + input[j] == k) { - return true; - } - } - } - - return false; - } - - public static void main(String [] args) { - - Scanner s = new Scanner(System.in); - int n = s.nextInt(); - int input[] = new int[n]; - for(int i = 0;i < n; i++) - input[i] = s.nextInt(); - int k = s.nextInt(); - if(subsetSumToKIdentical(input,n,k)) - System.out.println("true"); - else - System.out.println("false"); - } - -} diff --git a/Coding_Ninjas/src/main/java/Group2_set4/PossibleCombination.java b/Coding_Ninjas/src/main/java/Group2_set4/PossibleCombination.java deleted file mode 100755 index fb4c901..0000000 --- a/Coding_Ninjas/src/main/java/Group2_set4/PossibleCombination.java +++ /dev/null @@ -1,32 +0,0 @@ -package Group2_set4; - -public class PossibleCombination { - - - static void cobination(int arr[], int data[], int start, int end, int indices, int N) { - if (indices == N) { - for (int j=0; j= N-indices; i++) { - data[indices] = arr[i]; - cobination(arr, data, i+1, end, indices+1, N); - } - } - - static void PossibleComb(int arr[], int n, int N) { - - int data[]=new int[N]; - cobination(arr, data, 0, n-1, 0, N); - } - public static void main (String[] args) { - int arr[] = {1,2,3,4,5,6,7,8,9,10,11,12,13}; - int r = 12; - int n = arr.length; - PossibleComb(arr, n, r); - } -} diff --git a/Coding_Ninjas/src/main/java/Group2_set4/WaterNJugs.java b/Coding_Ninjas/src/main/java/Group2_set4/WaterNJugs.java deleted file mode 100755 index 1a6ee9b..0000000 --- a/Coding_Ninjas/src/main/java/Group2_set4/WaterNJugs.java +++ /dev/null @@ -1,59 +0,0 @@ -package Group2_set4; - -import java.util.Scanner; - -public class WaterNJugs { - /* - - */ - - static String solve(int a, int b, int c) { - if(c%gcd(a,b)==0 && c<=Math.max(a,b)) - return "YES"; - - return "NO"; - - } - -// static int gcd(int a,int b){ -//// if(b==0) -//// return a; -//// return gcd(b,a%b); -// int tmp; -// while(a%b!=0) -// { -// tmp=a%b; -// a=b; -// b=tmp; -// } -// return b; -// } - - public static String WaternJug(int john, int zeus, int peter) { - if(john + zeus < peter) - return "No"; - if(peter%gcd(john,zeus) == 0) - return "Yes"; - return "No"; - } - - public static int gcd(int a,int b){ - if(a==0){ - return b; - } - return gcd(b%a,a); - } - - public static void main(String[] args) { - Scanner s = new Scanner(System.in); - int n =s.nextInt(); - while (n!=0){ - int a = s.nextInt(); - int b = s.nextInt(); - int c = s.nextInt(); - System.out.println(WaternJug(a,b,c)); - n--; - } - - } -} diff --git a/Coding_Ninjas/src/main/java/Group3/FishEvolution.java b/Coding_Ninjas/src/main/java/Group3/FishEvolution.java deleted file mode 100755 index 36e2bd7..0000000 --- a/Coding_Ninjas/src/main/java/Group3/FishEvolution.java +++ /dev/null @@ -1,191 +0,0 @@ -package Group3; - -/* Fish Evolution -Send Feedback -Namita has magical fishes. Her fishes has the capability to evolve to become bigger fish. So, if the smaller fish touches a bigger or equivalent fish, then the bigger or equivalent fish disappears into water and the smaller fish evolves to become as large as the larger fish. Therefore, to avoid stray evolutions, she has kept her fishes in separate cells, arranged in a linear order. Now, she wants to evolve only one fish and she wants to choose the fish which will evolve maximum number of times. She wants your help in this. To make it more interesting, she has added signs of evolution with the fish cells. A cell assigned with +1 can only evolve with fishes on its right side and a cell assigned with -1 can only evolve with fishes on its left side. Can you complete this challenge? -Remember that the fishes are mindlessly evolving. This means that they evolve with the first big fish that comes in their way. Consider the following case. Here, Fish with size 5 can evolve in right direction. -5 12 10 11 13 -Fish with size 5 will evolve 2 times like 5 -> 12 -> 13 and not 3 times like 5->10->11->13. -Note: If there is more than one fish which can evolve the maximum number of times, select the one with the greater size. -Input Format: -First line of input contains an integer t, representing the number of test cases. -For each test case, the first line contains an integer n, representing the number of fishes. -Second line of each case contains n space separated integers, representing the size of fishes. -Third line of each test case contains n space separated integers, being +1 or -1, representing the signs of evolution. -Constraints: -1 <= t <= 150 -1 <= n <= 10^4 -1 <= arr[i] <= 10^4 -directions[i] = -1 or 1 -Time Limit : 1 second -Output Format: -For each test case, you have to print the size of fish which will evolve maximum number of times, along with the direction it is going to evolve in. (Left for -1 and Right for +1) -Sample Input 1: -1 -10 -5 1 4 12 10 8 11 9 18 88 -1 1 -1 -1 1 -1 1 -1 -1 -1 -Sample Output 1: -1 Right -Explanation: -1 can evolve 4 times with 4, 12, 18, 88 -Sample Input 2: -1 -12 -30 20 5 2 4 12 10 8 11 3 18 88 -1 1 1 1 -1 -1 1 1 1 -1 -1 -1 -Sample Output 2: -3 Left -Explanation: -2 can evolve 4 times with 4 -> 12 -> 18 -> 88 -3 can also evolve 4 times with 11 -> 12 -> 20 -> 30 -3 is greater than 2, hence the answer is 3 Left. - */ - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.Stack; -import java.util.StringTokenizer; - -class FastInput { - BufferedReader br; - StringTokenizer st; - - public FastInput() - { - br = new BufferedReader( - new InputStreamReader(System.in)); - } - - String next() - { - while (st == null || !st.hasMoreElements()) { - try { - st = new StringTokenizer(br.readLine()); - } - catch (IOException e) { - e.printStackTrace(); - } - } - return st.nextToken(); - } - - int nextInt() { return Integer.parseInt(next()); } - - long nextLong() { return Long.parseLong(next()); } - - double nextDouble() - { - return Double.parseDouble(next()); - } - - String nextLine() - { - String str = ""; - try { - str = br.readLine(); - } - catch (IOException e) { - e.printStackTrace(); - } - return str; - } -} -class Pair{ - int first; - int second; - Pair(int first, int second){ - this.first = first; - this.second = second; - } -} -public class FishEvolution { - public static void main(String[] args) { - FastInput s = new FastInput(); - int t = s.nextInt(); - for(int i = 0; i < t; i++) { - int n = s.nextInt(); - int[] fish = new int[n]; - int[] dir = new int[n]; - for (int j = 0; j < n; j++) fish[j] = s.nextInt(); - for (int j = 0; j < n; j++) dir[j] = s.nextInt(); - // System.out.println(Arrays.toString(dir)); - Stack st = new Stack<>(); - int maxValue = 0; int num = 0, fishNum = -1; - boolean directionLeft = true; - for(int j = 0; j < n; j++) { - // System.out.println(j); - if(dir[j]==-1){ - // System.out.print(j+" start "); - if(!st.isEmpty()&& st.peek().first< fish[j]){ - if(st.size()>num){ - fishNum = st.peek().first; - num = st.size(); - maxValue = st.peek().second; - }else if(st.size()==num && st.peek().second>maxValue){ - - fishNum = st.peek().first; - maxValue = st.peek().second; - } - while(!st.isEmpty() && st.peek().firstnum){ - fishNum = st.peek().first; - num = st.size(); - maxValue = st.peek().second; - }else if(st.size()==num && st.peek().second>maxValue){ - fishNum = st.peek().first; - maxValue = st.peek().second; - } - } - st.clear(); - - for (int j = n-1; j < 0; j--) { - if(dir[j]==1){ - if(!st.isEmpty()&& st.peek().first< fish[j]){ - if(st.size()>num){ - directionLeft = false; - - fishNum = st.peek().first; - num = st.size(); - maxValue = st.peek().second; - }else if(st.size()==num && st.peek().second>maxValue){ - directionLeft = false; - fishNum = st.peek().first; - maxValue = st.peek().second; - } - while(!st.isEmpty() && st.peek().firstnum){ - fishNum = st.peek().first; - num = st.size(); - maxValue = st.peek().second; - }else if(st.size()==num && st.peek().second>maxValue){ - fishNum = st.peek().first; - maxValue = st.peek().second; - } - } - st.clear(); - - if(!directionLeft) System.out.println(fishNum+" Right"); - System.out.println(fishNum+" Left"); - - } - } -} diff --git a/Coding_Ninjas/src/main/java/Group3/IsomorphicTree.java b/Coding_Ninjas/src/main/java/Group3/IsomorphicTree.java deleted file mode 100755 index aaeb626..0000000 --- a/Coding_Ninjas/src/main/java/Group3/IsomorphicTree.java +++ /dev/null @@ -1,201 +0,0 @@ -package Group3; - -import java.util.Scanner; - -/* Isomorphic Trees -Send Feedback -Given two binary trees. Check whether these two trees are isomorphic or not. -Isomorphic trees are the ones which can be made identical by series of flips i.e. by swapping left and right children of a number of nodes. -Example -Input -Output - True -Input format : -Line 1 : Elements in level order form (separated by space) -(If any node does not have left or right child, take -1 in its place) -Output Format : -True or False -Sample Input 1: - 5 35 10 2 3 5 2 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 - 9 11 12 2 5 3 2 -1 -1 -1 -1 -1 -1 -1 -1 -Sample Output 1: - False -Sample Input 1: - 2 35 10 2 3 -1 -1 -1 -1 -1 -1 - 9 10 35 -1 -1 3 2 -1 -1 -1 -1 -Sample Output 1: - True - */ -class BinaryTreeNode { - public T data; - public BinaryTreeNode left; - public BinaryTreeNode right; - public BinaryTreeNode next; - - public BinaryTreeNode(T data) { - this.data = data; - left = null; - right = null; - next = null; - } - - public T getData() { - return data; - } - - public void setData(T data) { - this.data = data; - } - - public BinaryTreeNode getLeft() { - return left; - } - - public void setLeft(BinaryTreeNode left) { - this.left = left; - } - - public BinaryTreeNode getRight() { - return right; - } - - public void setRight(BinaryTreeNode right) { - this.right = right; - } - -} - -class Node { - public Node down; - public Node right; - T data; - Node next; - - Node(T data) { - this.data = data; - } - -} - -class QueueUnderFlowException extends Exception { - -} - -class QueueUsingLinkedList { - Node front; - Node rear; - int size; - - public QueueUsingLinkedList() { - front = null; - rear = null; - size = 0; - } - - public void enqueue(T data) { - Node nyaNode = new Node<>(data); - if (front == null) { - front = nyaNode; - rear = nyaNode; - } else { - rear.next = nyaNode; - rear = rear.next; - } - size++; - } - - public T dequeue() throws QueueUnderFlowException { - if (front == null) { - throw new QueueUnderFlowException(); - } - Node temp = front; - front = front.next; - size--; - return temp.data; - } - - public int size() { - return size; - } - - public boolean isEmpty() { - return size == 0 ? true : false; - } - - public void printQueue() { - Node temp = front; - while (temp != null) { - System.out.print(temp.data + "-->"); - temp = temp.next; - } - } -} -public class IsomorphicTree { - static boolean isIsomorphic(BinaryTreeNode n1, BinaryTreeNode n2) { - if(n1==null && n2 == null) return true; - if(n1==null||n2==null) return false; - if(n1.data!=n2.data) return false; - BinaryTreeNode swap; - swap = n1.left; - n1.left = n1.right; - n1.right = swap; - if(!isIsomorphic(n1.left, n2.left)) return false; - if(!isIsomorphic(n1.right, n2.right)) return false; - return true; - } - - static boolean isIsomorphic1(BinaryTreeNode n1, BinaryTreeNode n2) - { - // Both roots are NULL, trees isomorphic by definition - if (n1 == null && n2 == null) - return true; - - // Exactly one of the n1 and n2 is NULL, trees not isomorphic - if (n1 == null || n2 == null) - return false; - - if (n1.data != n2.data) - return false; - - return (isIsomorphic(n1.left, n2.left) && isIsomorphic(n1.right, n2.right)) || - (isIsomorphic(n1.left, n2.right) && isIsomorphic(n1.right, n2.left)); - } - static Scanner s = new Scanner(System.in); - - static BinaryTreeNode prepareTree() throws QueueUnderFlowException { - - int data = s.nextInt(); - BinaryTreeNode root = new BinaryTreeNode<>(data); - QueueUsingLinkedList> queue = new QueueUsingLinkedList(); - queue.enqueue(root); - - while (!queue.isEmpty()) { - BinaryTreeNode currentNode = queue.dequeue(); - - int leftData = s.nextInt(); - if (leftData != -1) { - BinaryTreeNode leftNode = new BinaryTreeNode<>( - leftData); - currentNode.setLeft(leftNode); - queue.enqueue(currentNode.getLeft()); - - } - - int rightData = s.nextInt(); - if (rightData != -1) { - currentNode.setRight(new BinaryTreeNode<>(rightData)); - queue.enqueue(currentNode.getRight()); - } - } - return root; - } - - public static void main(String[] args) throws QueueUnderFlowException { - // TODO Auto-generated method stub - BinaryTreeNode root1 = prepareTree(); - BinaryTreeNode root2 = prepareTree(); - System.out.println(isIsomorphic1(root1, root2)); - - } - -} diff --git a/Coding_Ninjas/src/main/java/Group3/LinkedLIst.java b/Coding_Ninjas/src/main/java/Group3/LinkedLIst.java deleted file mode 100755 index f2f1933..0000000 --- a/Coding_Ninjas/src/main/java/Group3/LinkedLIst.java +++ /dev/null @@ -1,92 +0,0 @@ -package Group3; - -import java.util.Scanner; - - -/* Linked List Matrix -Send Feedback -Given a Matrix mat of N*N size, write a program that constructs a 2D linked list representation of the given matrix. -Input : 2D matrix -1 2 3 -4 5 6 -7 8 9 -Output : -1 -> 2 -> 3 -> NULL -| | | -v v v -4 -> 5 -> 6 -> NULL -| | | -v v v -7 -> 8 -> 9 -> NULL -| | | -v v v -NULL NULL NULL -Input Format : - The first line takes an integer N as input. - The next line input n*n integers denoting the matrix. -Output format: -Print the matrix using the linked list header. -Sample Input: -3 -1 2 3 4 5 6 7 8 9 -Sample Output: -1 2 3 -4 5 6 -7 8 9 - */ -//class Node{ -// int data; -// Node right,down; -// Node(int data){ -// this.data=data; -// right=null; -// down=null; -// } -//} -public class LinkedLIst { - - - static Node construct(int arr[][],int n){ - if(n<=0) return null; - - Node[][] mat = new Node[n][n]; - for (int i = 0; i < n; i++) { - for (int j = 0; j < n; j++) { - mat[i][j] = new Node(arr[i][j]); - - if(i!=0) mat[i-1][j].down = mat[i][j]; - if(j!=0) mat[i][j-1].right = mat[i][j]; - } - } - - return mat[0][0]; - - } - static void display(Node head) - { - Node rp; - Node dp=head; - while(dp!=null){ - rp=dp; - while(rp!=null){ - System.out.print(rp.data+" "); - rp=rp.right; - } - dp=dp.down; - System.out.println(); - } - - } - public static void main (String[] args) { - Scanner s=new Scanner(System.in); - int n=s.nextInt(); - int [][]arr=new int[n][n]; - for(int i=0;i { - T val; - TreeNode left; - TreeNode right; - - TreeNode(T data) { - this.val = data; - left = null; - right = null; - } -} -public class BstToGreaterSum { - - static Scanner s = new Scanner(System.in); - - private static void printLevelOrder(TreeNode root) { - if (root == null) { - return; - } - Queue> q = new LinkedList<>(); - q.add(root); - while (!q.isEmpty()) { - TreeNode curr = q.poll(); - System.out.print(curr.val + " "); - if (curr.left != null) { - q.add(curr.left); - } - if (curr.right != null) { - q.add(curr.right); - } - - } - } - - private static TreeNode takeInput() { - int rootData = s.nextInt(); - if (rootData == -1) { - return null; - } - - TreeNode root = new TreeNode(rootData); - Queue> q = new LinkedList<>(); - q.add(root); - - while (!q.isEmpty()) { - TreeNode currentNode = q.poll(); - int leftChild = s.nextInt(); - - if (leftChild != -1) { - TreeNode leftNode = new TreeNode(leftChild); - currentNode.left = leftNode; - q.add(leftNode); - } - - int rightChild = s.nextInt(); - - if (rightChild != -1) { - TreeNode rightNode = new TreeNode(rightChild); - currentNode.right = rightNode; - q.add(rightNode); - } - } - - return root; - } - - public static void main(String[] args) { - int t = s.nextInt(); - while (t > 0) { - - TreeNode root = takeInput(); - TreeNode bstToGreaterSum = convertBstToGreaterSum(root); - printLevelOrder(root); - System.out.println(); - t--; - } - // s.close(); - - } - static int greaterSum = 0; - public static class Sum { - int sum = 0; - } - public static TreeNode convertBstToGreaterSum(TreeNode root) { - Sum ss = new Sum(); - Helper(root,ss); - return root; - } - static void Helper(TreeNode root, Sum s) { - if (root == null) - return; - Helper(root.right,s); - s.sum = s.sum + root.val; - root.val = s.sum - root.val; - Helper(root.left,s); - } -} diff --git a/Coding_Ninjas/src/main/java/Group3/set2/ValidStackPermutation.java b/Coding_Ninjas/src/main/java/Group3/set2/ValidStackPermutation.java deleted file mode 100755 index 2b9f5ac..0000000 --- a/Coding_Ninjas/src/main/java/Group3/set2/ValidStackPermutation.java +++ /dev/null @@ -1,130 +0,0 @@ -package Group3.set2; - -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.Queue; -import java.util.Stack; -/* -You have been given two arrays having an equal number of elements. You have to find whether one array is the valid stack permutation of the other. An array is said to be a valid stack permutation of the other if and only if after applying some push and pop operations onto the sequence of elements in that array, will result in the other array. -Example: -Consider array : 2 4 6. -Valid stack permutations are as follows: -2 4 6 - push ‘2’ - pop ‘2’ - push ‘4’ - pop ‘4’ - push ‘6’ - pop ‘6’ -2 6 4 - push ‘2’ - pop ‘2’ - push ‘4’ - pop ‘6’ - push ‘6’ - pop ‘4’ -4 2 6 - push ‘2’ - pop ‘4’ - push ‘4’ - pop ‘2’ - push ‘6’ - pop ‘6’ -4 6 2 - push ‘2’ - pop ‘4’ - push ‘4’ - pop ‘6’ - push ‘6’ - pop ‘6’ -6 4 2 - push ‘2’ - pop ‘4’ - push ‘6’ - pop ‘6’ - push ‘4’ - pop ‘6’ - -Now, If the other array is [2,4,6], [2,6,4], [4,2,6], [4,6,2], or [6,4,2] then the answer is “YES” otherwise “NO”. -Note: -Please note that the arrays will only contain unique elements. -Input Format: -The first line contains a single integer ‘T’ representing the number of test cases. - -The first line of each test case will contain an integer ‘N’ which represents the total number of elements in both arrays. - -The second line of each test case contains the ‘N’ space-separated integers which represent the elements of the 'FIRST' array. - -The third line of each test case contains the ‘N’ space-separated integers which represent the elements of the 'OTHER' array. -Output Format: -For each test case, print “YES” if the first array is a valid stack permutation of the other. Otherwise, print “NO”. -Note: -You don’t need to print anything; It has already been taken care of. -Constraints: -1 <= T <= 10 -1 <= N <= 10000 -0 <= FIRST[i], OTHER[i] <= 10^5 - -Where 'FIRST[i]' and 'OTHER[i]' denote the value of the i-th element of the input arrays. - -Time limit: 1 sec -Sample Input 1: -2 -3 -2 4 6 -4 6 2 -3 -2 4 6 -6 2 4 -Sample Output 1: -YES -NO -Explanation of Sample Output 1: -In test case 1, The explanation is already given in the example. - -In test case 2, The explanation is already given in the example. -Sample Input 2: -2 -3 -2 4 6 -2 3 4 -1 -5 -5 -Sample Output 2: -NO -YES -Explanation for Sample Output 2: -In test case 1, the 'FIRST' array does not contain 3 but the 'OTHER' array contains 3. So, the other is not the valid stack permutation. - -In test case 2, the only array containing ‘5’ as an element is the valid stack permutation of the array [5]. - */ -public class ValidStackPermutation { - public static boolean validStackPermutation(ArrayList first, ArrayList other){ - // Write your code here. - Queue input = new LinkedList<>(); - Queue output = new LinkedList<>(); - for (int i=0;i temp = new Stack<>(); - while (!input.isEmpty()){ - int x = input.poll(); - if (x == output.peek()){ - output.poll(); - while (!temp.isEmpty()){ - if (temp.peek() == output.peek()){ - temp.pop(); - output.poll(); - }else { - break; - } - } - }else { - temp.push(x); - } - } - return (input.isEmpty() && temp.isEmpty()); - } -} diff --git a/Coding_Ninjas/src/main/java/Group3/set2/WinnerOftheCircularGame.java b/Coding_Ninjas/src/main/java/Group3/set2/WinnerOftheCircularGame.java deleted file mode 100755 index 9c67d29..0000000 --- a/Coding_Ninjas/src/main/java/Group3/set2/WinnerOftheCircularGame.java +++ /dev/null @@ -1,86 +0,0 @@ -package Group3.set2; - -import java.util.LinkedList; -import java.util.Scanner; - -public class WinnerOftheCircularGame { - /* - There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend. -The rules of the game are as follows: -1. Start at the 1st friend. -2. Count the next k friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once. -3. The last friend you counted leaves the circle and loses the game. -4. If there is still more than one friend in the circle, go back to step 2 starting from the friend immediately clockwise of the friend who just lost and repeat. -5. Else, the last friend in the circle wins the game. -Given the number of friends, n, and an integer k, return the winner of the game. -Input Format: -First and only line of input contains two space separated integers representing n and k respectively. -Constraints: -1 <= k <= n <= 500 -Output Format: -Print the winner of the game. -Sample Input: -5 2 -Sample Output: -3 -Explanation -Here are the steps of the game: -1) Start at friend 1. -2) Count 2 friends clockwise, which are friends 1 and 2. -3) Friend 2 leaves the circle. Next start is friend 3. -4) Count 2 friends clockwise, which are friends 3 and 4. -5) Friend 4 leaves the circle. Next start is friend 5. -6) Count 2 friends clockwise, which are friends 5 and 1. -7) Friend 1 leaves the circle. Next start is friend 3. -8) Count 2 friends clockwise, which are friends 3 and 5. -9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner. - */ - - static Scanner s=new Scanner(System.in); - - public static void main(String[] args) { - int n, k; - n = s.nextInt(); - k = s.nextInt(); - int ans = findTheWinner(n, k); - System.out.println(ans); - } - static public int findTheWinner(int n, int k) { - LinkedList friends = new LinkedList<>(); - for(int i=1; i<=n; i++) - friends.add(i); - - int index = 0; - while(friends.size() > 1){ - int i = 0; - while(i <= k-1){ - if(index == friends.size()) - index = 0; - i++; - index++; - } - if(index == 0) - friends.remove(friends.size()-1); - else - friends.remove(index-1); - - index--; - } - return friends.get(0); - } - //or using recursion - static public int findTheWinner1(int n, int k) { - if(n==1){ - return 1; - } - return (findTheWinner(n-1,k)+k-1)%n+1; - } -} -class ListNode { - public t data; - public ListNode next; - public ListNode(t data) - { - this.data=data; - } -} \ No newline at end of file diff --git a/Coding_Ninjas/src/main/java/Group3/set2/sortedListToBST.java b/Coding_Ninjas/src/main/java/Group3/set2/sortedListToBST.java deleted file mode 100755 index b0f3148..0000000 --- a/Coding_Ninjas/src/main/java/Group3/set2/sortedListToBST.java +++ /dev/null @@ -1,238 +0,0 @@ -package Group3.set2; - -import java.util.ArrayList; -import java.util.Scanner; - -/* -You have been given a singly linked list in which nodes are present in increasing order. Your task is to construct a Balanced Binary Search Tree with the same data elements as the given Linked List. -A Balanced BST is defined as a BST in which the height of two subtrees of every node differs no more than 1. -Input Format : -The first line of input contains an integer ‘T’ denoting the number of test cases to run. Then the test case follows. - -The only line of each test case contains the elements of the singly linked list separated by a single space and terminated by -1. Hence, -1 would never be a list element. -Output Format : -For each test case, print the nodes of the tree in the level order form separated by single spaces (Print -1 for NULL nodes). Refer to the below example for further clarification. - -Print the output for every test case in a separate line. -For Example -Consider the Binary Search Tree- -alt text -The above BST will be printed as- -12 10 14 -1 -1 -1 16 -1 -1 - -Explanation : -Level 1 : -The root node of the tree is 12 - -Level 2 : -Left child of 12 = 10 -Right child of 12 = 14 - -Level 3 : -Left child of 10 = null(-1) -Right child of 10 = null (-1) -Left child of 14 = null(-1) -Right child of 16 = 16 - -Level 4 : -Left child of 16 = null (-1) -Right child of 16 = null (-1) - -The first not-null node (of the previous level) is treated as the parent of the first two nodes of the current level. The second not-null node (of the previous level) is treated as the parent node for the next two nodes of the current level and so on. - -The output for each test case ends when all nodes at the last level are null (-1). -Note : -You do not need to print anything, it has already been taken care of. Just implement the given function. -Constraints : -1 <= T <= 100 -0 <= N <= 1000 -1 <= Data <= 10^9 -Data != -1 - -Time Limit: 1sec -Sample Input 1 : -2 -1 2 3 4 5 -1 -5 7 8 -1 -Sample Output 1: -3 2 5 1 -1 4 -1 -1 -1 -1 -1 -7 5 8 -1 -1 -1 -1 -Explanation for Sample Input 1: -Test Case 1: The balanced BST corresponding to the linked list is- -alt text -Level order traversal of above BST is 3 2 5 1 -1 4 -1 -1 -1 -1 -1 - -Test Case 2: The balanced BST corresponding to the linked list is- -alt text -Level order traversal of above BST is 7 5 8 -1 -1 -1 -1 -Sample Input 2 : -2 -10 12 14 16 -1 --1 -Sample Output 2 : -12 10 14 -1 -1 -1 16 -1 -1 --1 - */ -public class sortedListToBST { - - static class Node { - T data; - Node next; - - Node(T data) { - this.data = data; - this.next = null; - } - } - - static class TreeNode { - T data; - TreeNode left; - TreeNode right; - - TreeNode(T data) { - this.data = data; - this.left = null; - this.right = null; - } - } - public static TreeNode sortedListToBST(Node head) { - return divideList(head); - } - - - public static Node getMid(Node head){ - Node slow = head; - Node fast = head; - Node prev = null; - - while(fast != null && fast.next != null){ - prev = slow; - slow = slow.next; - fast = fast.next.next; - } - - return prev; - } - - public static TreeNode divideList(Node head){ - if(head == null){ - return null; - } - if(head.next == null){ - return new TreeNode(head.data); - } - - Node mid = getMid(head); - - Nodenext = mid.next; - mid.next = null; - - TreeNode root = new TreeNode(next.data); - root.left = divideList(head); - root.right = divideList(next.next); - - return root; - } - - public static ArrayList in = new ArrayList(); - public static ArrayList check = new ArrayList(); - - static Scanner s = new Scanner(System.in); - - public static Node takeLLInput() { - - check.clear(); - int data = s.nextInt(); - - Node head = null, tail = null; - - while (data != -1) { - check.add(data); - Node newNode = new Node(data); - - if (head == null) { - head = newNode; - tail = newNode; - } else { - tail.next = newNode; - tail = newNode; - } - - data = s.nextInt(); - } - - return head; - } - - - public static void print(TreeNode poi) - { - if(poi==null) - return; - if(poi.left!=null) - print(poi.left); - in.add(poi.data); - if(poi.right!=null) - print(poi.right); - - } - - public static boolean isValid(TreeNode root,Height height) - { - if(root==null) - { - height.height=0; - return true; - } - - Height lheight = new Height(), rheight = new Height(); - - boolean l = isValid(root.left, lheight); - boolean r = isValid(root.right, rheight); - int lh = lheight.height, rh = rheight.height; - - height.height = (lh > rh ? lh : rh) + 1; - - if (Math.abs(lh - rh) >= 2) - return false; - else - return l && r; - } - - public static void main(String[] args) { - - int t = s.nextInt(); - - while (t-- > 0) { - - Node head = takeLLInput(); - - TreeNode root = sortedListToBST(head); - TreeNode poi=root; - in.clear(); - print(poi); - - - - if(in.equals(check)==false) - { - System.out.println("INCORRECT"); - continue; - } - - Height h = new Height(); - if(isValid(root,h)==false) - { - System.out.println("INCORRECT"); - continue; - } - System.out.println("CORRECT"); - - } - - } -} -class Height { - int height = 0; -} diff --git a/Coding_Ninjas/src/main/java/Group3/warOnNinjas.java b/Coding_Ninjas/src/main/java/Group3/warOnNinjas.java deleted file mode 100755 index 689a8bd..0000000 --- a/Coding_Ninjas/src/main/java/Group3/warOnNinjas.java +++ /dev/null @@ -1,293 +0,0 @@ -package Group3; - -import java.util.ArrayList; -import java.util.Scanner; - -/* -public class WarOnNinjaLand { - static class Node - { - int id; - boolean isRationalised; - ArrayList adlist = new ArrayList<>(); - Node(int id) - { - this.id = id; - this.isRationalised = false; - } - } - static class Tree - { - ArrayList nodelist = new ArrayList<>(); - public Node getNode(int i) - { - Node node = new Node(i); - nodelist.add(node); - return node; - } - public void addEdge(Node u, Node v) - { - u.adlist.add(v); - v.adlist.add(u); - } - public int createTree(int[] arr) - { - Queue q = new LinkedList<>(); - q.add(getNode(nodelist.size())); - - int i = 1; - while(!q.isEmpty()) - { - Node nd = q.remove(); - int val = arr[i]; - for(int j=1;j<=val;j++) - { - Node node = new Node(nodelist.size()); - nodelist.add(node); - q.add(node); - addEdge(nd, node); - } - i+=val; - i++; - } - - q = new LinkedList<>(); - for(Node node: nodelist) - { - if(node.adlist.size()==1) { - q.add(node.adlist.get(0)); - } - } - - int count = 0; - - while(!q.isEmpty()) - { - Node cur = q.remove(); - if(!cur.isRationalised) - { - cur.isRationalised = true; - count++; - System.out.println(cur.id); - for(Node nd: cur.adlist) - { - if(nd.isRationalised) - continue; - nd.isRationalised = true; - boolean hasLeaf = false; - for(Node adnd: nd.adlist) - { - if(adnd.adlist.size()==1) - hasLeaf = true; - } - if(hasLeaf) - { - q.add(nd); - nd.isRationalised = false; - continue; - } - for(Node adnd : nd.adlist) - if(!adnd.isRationalised) - q.add(adnd); - } - } - } - - return count; - } - } - public static void main(String[] args) throws IOException { - Scanner sc = new Scanner(System.in); - - String line = sc.nextLine(); - String[] linearr = line.split(" "); - int[] arr = new int[linearr.length]; - for(int i=0;isc.nextInt()) - { - System.out.println(noh+" Mission Unsuccessful"); - } - else System.out.println(noh+" Mission Successful"); - } -} - */ -class TreeNode { - T data; - ArrayList> children; - - TreeNode(T data){ - this.data = data; - children = new ArrayList>(); - } -} -public class warOnNinjas { - static class QueueEmptyException extends Exception { - } - - static class QueueUsingLL { - - class Node { - T data; - Node next; - Node(T data){ - this.data = data; - } - } - - private Node head; - private Node tail; - private int size = 0; - - public int size(){ - return size; - } - - public boolean isEmpty(){ - if(size == 0){ - return true; - } - return false; - } - - public T front() throws QueueEmptyException{ - if(size == 0){ - QueueEmptyException e = new QueueEmptyException(); - throw e; - } - - return head.data; - } - public void enqueue(T element){ - Node newNode = new Node(element); - - if(head == null){ - head = newNode; - tail = newNode; - } - else{ - tail.next = newNode; - tail = newNode; - } - - size++; - } - - public T dequeue() throws QueueEmptyException{ - if(head == null){ - QueueEmptyException e = new QueueEmptyException(); - throw e; - } - if(head == tail){ - tail = null; - } - T temp = head.data; - head = head.next; - size--; - return temp; - } - } - - static int minLandingCover(TreeNode root) { - //Write your code here - int sum=0; - if (dfs(root,sum)==0){ - sum++; - }else { - sum= dfs(root,sum); - } - return sum; - - } - - static int dfs(TreeNode root,int sum){ - if (root == null){ - return 1; - } - if (root.children.size()==0){ - return 0; - } - ArrayList arr = new ArrayList<>(); - int ans=0; - for (int i=0;i takeInputLevelWise(){ - QueueUsingLL> pendingNodes = new QueueUsingLL>(); // Queue of nodes that are entered themselves but their children aren't added yet - int rootData = s.nextInt(); - TreeNode root = new TreeNode(rootData); - pendingNodes.enqueue(root); - while(!pendingNodes.isEmpty()){ - TreeNode currentNode; - try { - currentNode = pendingNodes.dequeue(); - int numChild = s.nextInt(); - for(int i = 0 ; i < numChild; i++){ - int currentChild = s.nextInt(); - TreeNode childNode = new TreeNode(currentChild); - pendingNodes.enqueue(childNode); - currentNode.children.add(childNode); - } - } catch (QueueEmptyException e) { - } - } - return root; - } - - - public static void main(String[] args) { - - TreeNode root = takeInputLevelWise(); - int allowed; - allowed = s.nextInt(); - int final_ans = minLandingCover(root); - printAns(allowed, final_ans); - - } - -} diff --git a/Coding_Ninjas/src/main/java/Group4/Pradyumana.java b/Coding_Ninjas/src/main/java/Group4/Pradyumana.java deleted file mode 100755 index 76aa24a..0000000 --- a/Coding_Ninjas/src/main/java/Group4/Pradyumana.java +++ /dev/null @@ -1,67 +0,0 @@ -package Group4; - -import TriesAndHuffman.Trie; - -import java.util.Scanner; - -public class Pradyumana { - /* Help Pradyumana! -Send Feedback -Pradyumn is tired of using auto - correct feature in his smartphone. He needs to correct his auto - correct -more times than the auto - correct corrects him. Pradyumn is thinking to make his own app for mobile which -will restrict auto - correct feature, instead it will provide auto - completion. Whenever Pradyumn types -factorial, auto - correct changes it to fact. Pradyumn's App will show options such as fact, factorial, -factory. Now, he can chose from any of these options. As Pradyumn is busy with his front - end work of his -App. He asks you to help him. He said "You will be given set of words(words may repeat too but counted as one only). -Now, as user starts the app, he will make queries(in lowercase letters only). So, you have to print all the words -of dictionary which have the prefix same as given by user as input. And if no such words are available, add this -word to your dictionary." As you know, Pradyumn want this app to be as smart as him :P So, implement a program for -him such that he can release it on Fun Store. - -Input Format: - -Single integer N which denotes the size of words which are input as dictionary -N lines of input, where each line is a string of consisting lowercase letter -Single integer Q which denotes the number of queries. -Q number of lines describing the query string on each line given by user - -Constraints: -1 ≤ N ≤ 30000 -sum(len(string[i])) ≤ 2∗10^5 -1 ≤ Q ≤ 10^3 -Output Format: -If auto - completions exists, output all of them in lexicographical order else output "No suggestions" without quotes - -Sample Input 1: -3 -fact -factorial -factory -2 -fact -pradyumn - -Sample Output 1: -fact -factorial -factory -No suggestions - */ - - public static void main(String[] args) { - Scanner s = new Scanner(System.in); - int n = s.nextInt(); - Trie t = new Trie(); - String[] words = new String[n]; - for(int i = 0; i < n; i++) { - words[i]=s.next(); - t.add(words[i]); - } - int m =s.nextInt(); - String[] word1 = new String[m]; - for (int i=0;i= 0 and 0 < j <= M -Also, you are allowed to jump from valley i to valley j if height[i] > height[j] and height[i] > height[k] for -valleys k between valley i and valley j. Ninja can start from any valley and start jumping. Determine the maximum -number of valleys he can visit. -Note: Ninja is not allowed to jump to the right of Nth valley and left of 1st valley. (Stay within boundaries). -Input Format: -First line contains an integer t, representing number of test cases -Second line contains two space separated integers N and M. -Third line contains N space separated integers denoting the heights of N valleys. -Constraints: -1 <= N <= 10^4 -1 <= Height[i] <= 10^5 -1 <= M <= N -Time Limit: 1.5 seconds -Output Format: -Determine the maximum number of valleys Ninja can visit. -Sample Input 1: -1 -11 2 -6 4 14 6 8 13 9 7 10 6 12 -Sample Output 1: -4 -Explanation 1: -You can start at valley 11 with height 12. You can jump from valley 11 --> 9 --> 7 --> 8. - */ - public static void main(String[] args) { - Scanner s = new Scanner(System.in); - int N = s.nextInt(); - int M = s.nextInt(); - // ArrayList arr = new ArrayList<>(N); - int[] arr = new int[N]; - for (int i = 0; i < N; i++) arr[i] = s.nextInt(); - if (arr[0] < arr[N - 1]) { - int n = N - 1; - int cnt = 0; - while (n >= 0) { - if (arr[n] > arr[n - 1]) { - if (arr[n] > arr[n - 2]) { - n -= 2; - cnt++; - } else { - n -= 1; - cnt++; - } - } else if (arr[n] > arr[n + 1]) { - if (arr[n] > arr[n + 2]) { - n += 2; - cnt++; - } else { - n += 1; - cnt++; - } - } else if (arr[n] < arr[n - 1]&& arr[n] < arr[n + 1]) { - System.out.println(cnt+1); - return; - } - } - - } else { - int cnt = 0; - int i = 0; - while (i < N - 1) { - if (arr[i] > arr[i + 1]) { - if (arr[i] > arr[i + 2]) { - i += 2; - cnt++; - } else { - i += 1; - cnt++; - } - } else if (arr[i] > arr[i - 1]) { - if (arr[i] > arr[i - 2]) { - i -= 2; - cnt++; - } else { - i -= 1; - cnt++; - } - } else if (arr[i] < arr[i - 1]&& arr[i] < arr[i + 1]) { - System.out.println(cnt+1); - return; - } - } - - - } - } -} diff --git a/Coding_Ninjas/src/main/java/Group4/WhiteBlack.java b/Coding_Ninjas/src/main/java/Group4/WhiteBlack.java deleted file mode 100755 index 60f1f8d..0000000 --- a/Coding_Ninjas/src/main/java/Group4/WhiteBlack.java +++ /dev/null @@ -1,282 +0,0 @@ -package Group4; - -/* White Subtree -Send Feedback -You are given a tree consisting of n vertices. A tree is a connected undirected graph with n−1 edges. Each vertex v of this tree has a colour assigned to it (av=1 if the vertex v is white and 0 if the vertex v is black). -You have to solve the following problem for each vertex v: What is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex v? -The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntw (white vertices) and cntb (black vertices), you have to maximize cntw−cntb. -Input Format: -First line of input will contain T(number of test cases), each test case follows as. -Line 1: contain an integer N (number of vertex in the tree) -Line 2: contian N space separated integers where Ith integer denote the colour of the Ith vertex(1 for white and 0 for black). -Next N - 1 lines will contain two space-separated integers v and u denoting the edge between vertex u and v -Constraints: -1 <= T <= 50 -1 <= N <= 10^5 -0 <= arr[i] <= 1 -Output Format: -for each test case print n space-separated integers res1,res2,…,resn, where resi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex i in new line -Sample Input 1: -1 -9 -0 1 1 1 0 0 0 0 1 -1 2 -1 3 -3 4 -3 5 -2 6 -4 7 -6 8 -5 9 -Sample Output 1: -2 2 2 2 2 1 1 0 2 - */ - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.StringTokenizer; - -class FastInput { - BufferedReader br; - StringTokenizer st; - - public FastInput() - { - br = new BufferedReader( - new InputStreamReader(System.in)); - } - - String next() - { - while (st == null || !st.hasMoreElements()) { - try { - st = new StringTokenizer(br.readLine()); - } - catch (IOException e) { - e.printStackTrace(); - } - } - return st.nextToken(); - } - - int nextInt() { return Integer.parseInt(next()); } - - long nextLong() { return Long.parseLong(next()); } - - double nextDouble() - { - return Double.parseDouble(next()); - } - - String nextLine() - { - String str = ""; - try { - str = br.readLine(); - } - catch (IOException e) { - e.printStackTrace(); - } - return str; - } -} - -public class WhiteBlack { -// public static int max(ArrayList> graph, int start,int[] max, int[] check){ -// -// } - - - public static void main(String[] args) { - FastInput s = new FastInput(); - int t = s.nextInt(); - for (int i = 0; i < t; i++) { - ArrayList> graph = new ArrayList<>(); - int n = s.nextInt(); - graph.add(new ArrayList<>()); - for (int j = 1; j < n+1; j++) { - graph.add(new ArrayList()); - graph.get(j).add(s.nextInt()); - } - for (int j = 1; j < n; j++) { - int index = s.nextInt(); - int to = s.nextInt(); - graph.get(index).add(to); - graph.get(to).add(index); - } - for (int j = 1; j < n+1; j++) { - System.out.print(j+" --> "); - System.out.println(graph.get(j).subList(0, graph.get(j).size())); - } - for (int j = 1; j < n+1; j++) { - int count = 0; - int color = graph.get(j).get(0)==0?1:0; - - for(int j2 = 1; j2 adj[]; - static void DFS(int s,int b[],int w[],int parent,int a[]){ - Iterator itr=adj[s].listIterator(); - while(itr.hasNext()) - { - int n=itr.next(); - if(n!=parent){ - DFS(n,b,w,s,a); - } - } - if(a[s]==1) - w[s]++; - else b[s]++; - Iterator itr1=adj[s].listIterator(); - while(itr1.hasNext()) - { - int n=itr1.next(); - if(n!=parent){ - if(w[n]>b[n]) - { - w[s]=w[s]+w[n]; - b[s]=b[s]+b[n]; - } - } - } - } - static void solve(int s,int b[],int w[],int parent,int a[],int ans[]){ - Iterator itr=adj[s].listIterator(); - while(itr.hasNext()) - { - int n=itr.next(); - if(n!=parent){ - if(w[s]>b[s]) - { - int x=b[s],y=w[s]; - if(w[n]>b[n]){ - x=b[s]-b[n]; - y=w[s]-w[n];} - if(y>x){ - b[n]=b[n]+x; - w[n]=w[n]+y; - } - } - ans[n]=w[n]-b[n]; - solve(n,b,w,s,a,ans); - } - } - } - public static void main(String[] args) - { - FastReader s=new FastReader(); - int n=s.nextInt(); - int a[]=new int[n+1]; - for(int i=1;i<=n;i++) - a[i]=s.nextInt(); - adj=new LinkedList[n+1]; - for(int i=0;i<=n;i++) - adj[i]=new LinkedList<>(); - for(int i=0;i 0) { - int r = in.nextInt(); - String s = in.next(); - System.out.println(search(s, r)); - - } - - - } - -} - diff --git a/Coding_Ninjas/src/main/java/Group4/set2/LostRepresentative.java b/Coding_Ninjas/src/main/java/Group4/set2/LostRepresentative.java deleted file mode 100755 index 3a31bff..0000000 --- a/Coding_Ninjas/src/main/java/Group4/set2/LostRepresentative.java +++ /dev/null @@ -1,186 +0,0 @@ -package Group4.set2; - -import java.io.DataInputStream; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.Queue; -import java.util.StringTokenizer; -/* -The Government Public School of Wadiya city is holding a congress of students. The number of representations from each grade is equal to the grade number. From the first grade, the congress has only 1 representative, from the second grade, the congress has only 2 representatives and so on and so forth. All the representatives are told to assemble in the main ground. All the same grade representatives are standing together. -A representative of grade P comes to the stage and says that he is unable to find his group of representatives. The organisers are busy with other tasks. You have to find the group for the lost representative. -The main ground is a huge N*N matrix. You are given this matrix as input. Each representative occupies a cell. An occupied cell is represented by integer 1 and an unoccupied cell by integer 0. All the representatives of the same grade are connected to each other and disconnected from other grade representatives. An occupied cell is said to be connected to those occupied cells which are reachable from its cell. A representative can move across to other occupied cells with which it shares its edges. -For example: -Alt Text -In this diagram of a part of the ground, red coloured cells represents the connected group of sixth grade students, yellow cell represents the connected group of first grade student and green represents the connected group of fourth grade students. -You will be given the matrix and you have to find the starting cell of the connected group of the lost representative. -Starting Cell is the one with the lowest row value. (If row number of two or more cells is same, then starting cell among them is the one with lowest column value) -It may be possible that the representative may be confused, and the grade he says he is from is actually not present. In that case, print starting cell as -1 -1. -Input Format: -First line of input contains integer t, representing the number of test cases. -First line of each test case contains integer n, representing the size of the matrix. -The second line onwards, the next 'N' lines or rows represent the ith row values. -Each of the ith rows constitutes 'N' column values separated by a single space. -Last line of each test case contains integer p, representing the grade of the lost representative. -Constraints: -1 <= N <= 1000 -1 <= p <= 100 -Output Format: -For each test case, you need to print the starting cell of the connected group of the lost representative. -Sample Input 1: -1 -5 -1 1 0 0 0 -0 1 0 0 1 -1 1 0 1 1 -0 0 0 0 0 -1 1 0 0 1 -3 -Sample Output 1: -1 4 -Explanation: -The lost representative is from the 3rd grade. In the given matrix, the 3rd grade is represented by the cluster of 1s where the starting cell of this cluster is 1,4. - */ - -public class LostRepresentative { - static class Cell { - int x; - int y; - - Cell(int x, int y) { - this.x = x; - this.y = y; - } - } - - public static boolean isValid(int n, int i, int j) { - return (i >= 0 && i < n && j >= 0 && j < n); - } - - public static void main(String[] args) throws IOException { - Test sc = new Test(); - int t = sc.nextInt(); - while (t-- > 0) { - int n = sc.nextInt(); - int[][] mat = new int[n][n]; - for (int i = 0; i < n; i++) { - mat[i] = sc.nextIntArray(n); - } - boolean[][] isVisited = new boolean[n][n]; - HashMap hash = new HashMap<>(); - for (int i = 0; i < n; i++) { - for (int j = 0; j < n; j++) { - if (!isVisited[i][j] && mat[i][j] == 1) { - Cell startcell = new Cell(i, j); - Queue q = new LinkedList<>(); - q.add(startcell); - isVisited[i][j] = true; - int count = 1; - - while (!q.isEmpty()) { - Cell thiscell = q.remove(); - if (isValid(n, thiscell.x + 1, thiscell.y) && mat[thiscell.x + 1][thiscell.y] == 1 && !isVisited[thiscell.x + 1][thiscell.y]) { - q.add(new Cell(thiscell.x + 1, thiscell.y)); - count++; - isVisited[thiscell.x + 1][thiscell.y] = true; - } - if (isValid(n, thiscell.x - 1, thiscell.y) && mat[thiscell.x - 1][thiscell.y] == 1 && !isVisited[thiscell.x - 1][thiscell.y]) { - q.add(new Cell(thiscell.x - 1, thiscell.y)); - count++; - isVisited[thiscell.x - 1][thiscell.y] = true; - } - if (isValid(n, thiscell.x, thiscell.y + 1) && mat[thiscell.x][thiscell.y + 1] == 1 && !isVisited[thiscell.x][thiscell.y + 1]) { - q.add(new Cell(thiscell.x, thiscell.y + 1)); - count++; - isVisited[thiscell.x][thiscell.y + 1] = true; - } - if (isValid(n, thiscell.x, thiscell.y - 1) && mat[thiscell.x][thiscell.y - 1] == 1 && !isVisited[thiscell.x][thiscell.y - 1]) { - q.add(new Cell(thiscell.x, thiscell.y - 1)); - count++; - isVisited[thiscell.x][thiscell.y - 1] = true; - } - } - - hash.put(count, startcell); - } - } - } - - int r = sc.nextInt(); - if (hash.containsKey(r)) - System.out.println((hash.get(r).x) + " " + (hash.get(r).y)); - else System.out.println("-1 -1"); - } - - sc.close(); - } - - static class Test { - final private int BUFFER_SIZE = 1 << 18; - final private DataInputStream din; - final private byte[] buffer; - private PrintWriter pw; - private int bufferPointer, bytesRead; - StringTokenizer st; - - public Test() { - din = new DataInputStream(System.in); - buffer = new byte[BUFFER_SIZE]; - bufferPointer = bytesRead = 0; - } - - public void println(String a) { - pw.println(a); - } - - public void print(String a) { - pw.print(a); - } - - public int[] nextIntArray(int n) throws IOException { - int[] arr = new int[n]; - for (int i = 0; i < n; i++) { - arr[i] = nextInt(); - } - - return arr; - } - - - public int nextInt() throws IOException { - int ret = 0; - byte c = read(); - while (c <= ' ') - c = read(); - boolean neg = (c == '-'); - if (neg) - c = read(); - do { - ret = ret * 10 + c - '0'; - } while ((c = read()) >= '0' && c <= '9'); - - if (neg) - return -ret; - return ret; - } - - private void fillBuffer() throws IOException { - bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); - if (bytesRead == -1) - buffer[0] = -1; - } - - private byte read() throws IOException { - if (bufferPointer == bytesRead) - fillBuffer(); - return buffer[bufferPointer++]; - } - - public void close() throws IOException { - if (din != null) din.close(); - if (pw != null) pw.close(); - } - } - -} diff --git a/Coding_Ninjas/src/main/java/Group4/set2/MatrixGym.java b/Coding_Ninjas/src/main/java/Group4/set2/MatrixGym.java deleted file mode 100755 index e9394d7..0000000 --- a/Coding_Ninjas/src/main/java/Group4/set2/MatrixGym.java +++ /dev/null @@ -1,47 +0,0 @@ -package Group4.set2; - -public class MatrixGym { - /* - Ninja has put on some extra weight during lockdown. He has decided to join a gym to shed this extra weight off. He joined the Matrix Gym, where the trainer has planned an elaborate exercise for him. It is upto Ninja to decide how many calories he wants to burn during his workout, whereas the trainer designs the exercise. The basic idea of each day remains the same. Ninja has to perform his exercise by crossing his Matrix Gym, which is a 2-D Grid consisting of hurdle cells (represented by “ # ”) and clear cells (represented by “ . “ ). He has to avoid the hurdles, and by entering each clear cell he burns 5 calories. He begins from the top-left corner of the grid. It is given that starting position has no hurdle. He has to reach the bottom-right cell which is also hurdle free. You have to find out if a path exists through which Ninja can burn his decided amount of calories. Ninja can take only one step at a time. Also, when Ninja is standing at (i, j), he can move to (i, j+1) and (i+1, j) only (right and bottom cells). If such a path is possible, print “Yes”, otherwise print “No”. If more than one path is present in the gym through which the calories can be burnt, find the path which burns the maximum calories, and print the extra amount of calories burnt by Ninja. -Input Format: -The first line of input contains an integer N which denotes the number of rows in the grid. -The following line of input contains N space separated strings deciding the structure of hurdle and clear cells in the grid -The third line contains the number of calories to be burnt. -Constraints: -1 <= N <= 10^5 -1 <= calories <= 10^5 -Output Format: -For each query, you have to print “Yes” along with additional calories burnt (if any) if the path is found, otherwise you have to print “No”. -Sample Input 1: -3 -..## #.## #... -15 -Sample Output 1: -Yes 10 -Explanation: -For the given input the grid formed is [ ‘..##’ , ‘#.##’ , ‘#...’ ] -For this grid, Ninja can easily travel from cell (0,0) which is his starting point, till cell (2,3) which is his end point, and burn 25 calories in the process. -He had decided to burn 15 calories. Hence additional calories burnt are 25-15 = 10 -Sample Input 2: -4 -...## .#..# .##.# ..#.. -30 -Sample Output 2: -Yes 5 -Explanation: -For the given input the grid formed is [ ‘...##’ , ‘.#..#’ , ‘.##.#’ , ‘..#..’ ]. -For this grid, Ninja can easily travel from cell (0,0) which is his starting point, till cell (3,4) which is his end point, and burn 25 calories in the process. -He had decided to burn 15 calories. Hence additional calories burnt are 35-30 = 5 -Sample Input 3: -4 -...## .#..# .##.# ..#.. -35 -Sample Output 3: -Yes -Explanation: -For the given input the grid formed is [ ‘...##’ , ‘.#..#’ , ‘.##.#’ , ‘..#..’ ] -For this grid, Ninja can easily travel from cell (0,0) which is his starting point, till cell (3,4) which is his end point, and burn 25 calories in the process. -He had decided to burn 15 calories. Hence additional calories burnt are 35-35 = 0 - */ - -} diff --git a/Coding_Ninjas/src/main/java/Group4/set2/SameProduct.java b/Coding_Ninjas/src/main/java/Group4/set2/SameProduct.java deleted file mode 100755 index 557709f..0000000 --- a/Coding_Ninjas/src/main/java/Group4/set2/SameProduct.java +++ /dev/null @@ -1,62 +0,0 @@ -package Group4.set2; - -import java.util.HashMap; -import java.util.Map; -import java.util.Scanner; -/* -Given an array of distinct positive integers, return the number of tuples (a, b, c, d) such that a * b = c * d where a, b, c, and d are elements of the array, and a != b != c != d. -Input Format: -First line of input contains an integer N, representing the number of elements in array -Second line of input contains N space separated integers -Output Format: -Print the required count -Sample Input 1: -4 -2 3 4 6 -Sample Output 1: -8 -Explanation: -There are 8 valid tuples: -(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3) -(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2) - */ -public class SameProduct { - public static void main(String[] args) { - // Take input as instructed - Scanner s = new Scanner(System.in); - int n = s.nextInt(); - int arr[] = new int[n]; - for(int i =0;i map=new HashMap<>(); - for(int i=0;i m:map.entrySet()){ - int value=m.getValue(); - /*if count of the pair multiplication is greater than 2 than tuple is found - now if count is say 3 so P1,P2,P3 are three pairs means P1 consists of two - elements and similary P2 and P3. Now we can arrange P1,P2 and P3 in two positions - using 6 ways simple combinations and let's say P1,P2 and P1 and P2 consists of two - elements each which can further be arranged in 4 ways */ - if(value>=2){ - int changes=(value)*(value-1); - count=count+(4*changes); - } - } - return count; - - } -} diff --git a/Coding_Ninjas/src/main/java/Group4/sypINUP.java b/Coding_Ninjas/src/main/java/Group4/sypINUP.java deleted file mode 100755 index db4f3a4..0000000 --- a/Coding_Ninjas/src/main/java/Group4/sypINUP.java +++ /dev/null @@ -1,67 +0,0 @@ -/* Spy Among Us -Send Feedback -The Director of RAW (Research and Analysis Wing) has uncovered intel that one of the agents under him is actually a mole (spy for the competitor). -Ninja is the most trusted agent under him. He assigns Ninja the task of figuring out who the mole is. -Ninja is an excellent detective who has figured out a simple algorithm to find out who the mole is. The mole will be a person who trusts nobody in the team, yet is trusted by everyone else. He gives each agent a code-name from 1 to N. -Find out the mole and return his code-name. If not found, return -1. -Input Format: -First line of input contains two space separated integers representing total number of agents (N), and the number of trust relationships (T) -Next T lines contain two space separated integers x and y, representing that x has complete faith over y. -Constraints: -1 <= N <= 1000 -1 <= T <= 10000 -Output Format: -Code-name of the mole. -Sample Input: -4 5 -1 3 -1 4 -2 3 -2 4 -4 3 -Sample Output: -3 - */ -package Group4; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -public class sypINUP { - - static public int findMole(int N, int[][] trust) { - int mole = -1; - boolean[] check = new boolean[N+1]; - check[0] = true; - for (int i = 0; i < trust.length; i++) { - check[trust[i][0]] = true; - } - for (int i = 0; i < check.length; i++) { - if(check[i]==false) mole = i; - } - - - return mole; - // Write your code here - - } - static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - public static void main(String[] args) throws IOException{ - String[] strNums = br.readLine().trim().split(" "); - int N = Integer.parseInt(strNums[0]); - int T = Integer.parseInt(strNums[1]); - - int[][] trust = new int[T][2]; - - for (int i = 0; i < T; i++) - { - String[] strNums1 = br.readLine().trim().split(" "); - int x = Integer.parseInt(strNums1[0]); - int y = Integer.parseInt(strNums1[1]); - trust[i][0] = x; - trust[i][1] = y; - } - - System.out.println(findMole(N, trust)); - } - -} diff --git a/Coding_Ninjas/src/main/java/Group4/whiteSubtreee.java b/Coding_Ninjas/src/main/java/Group4/whiteSubtreee.java deleted file mode 100755 index bff2473..0000000 --- a/Coding_Ninjas/src/main/java/Group4/whiteSubtreee.java +++ /dev/null @@ -1,198 +0,0 @@ -package Group4; - -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.InputMismatchException; - -public class whiteSubtreee { - static class InputReader { - private final InputStream stream; - private final byte[] buf = new byte[8192]; - private int curChar, snumChars; - public InputReader(InputStream st) { - this.stream = st; - } - public int read() { - if (snumChars == -1) - throw new InputMismatchException(); - if (curChar >= snumChars) { - curChar = 0; - try { - snumChars = stream.read(buf); - } - catch (IOException e) { - throw new InputMismatchException(); - } - if (snumChars <= 0) - return -1; - } - return buf[curChar++]; - } - public int ni() { - int c = read(); - while (isSpaceChar(c)) { - c = read(); - } - int sgn = 1; - if (c == '-') { - sgn = -1; - c = read(); - } - int res = 0; - do { - res *= 10; - res += c - '0'; - c = read(); - } while (!isSpaceChar(c)); - return res * sgn; - } - public long nl() { - int c = read(); - while (isSpaceChar(c)) { - c = read(); - } - int sgn = 1; - if (c == '-') { - sgn = -1; - c = read(); - } - long res = 0; - do { - res *= 10; - res += c - '0'; - c = read(); - } while (!isSpaceChar(c)); - return res * sgn; - } - public int[] nia(int n) { - int a[] = new int[n]; - for (int i = 0; i < n; i++) { - a[i] = ni(); - } - return a; - } - public String rs() { - int c = read(); - while (isSpaceChar(c)) { - c = read(); - } - StringBuilder res = new StringBuilder(); - do { - res.appendCodePoint(c); - c = read(); - } while (!isSpaceChar(c)); - return res.toString(); - } - public String nextLine() { - int c = read(); - while (isSpaceChar(c)) - c = read(); - StringBuilder res = new StringBuilder(); - do { - res.appendCodePoint(c); - c = read(); - } while (!isEndOfLine(c)); - return res.toString(); - } - public boolean isSpaceChar(int c) { - return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; - } - - private boolean isEndOfLine(int c) { - return c == '\n' || c == '\r' || c == -1; - } - } - public static class Key { - - private final int x; - private final int y; - - public Key(int x, int y) { - this.x = x; - this.y = y; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Key)) return false; - Key key = (Key) o; - return x == key.x && y == key.y; - } - - @Override - public int hashCode() { - int result = x; - result = 31 * result + y; - return result; - } - - } - - static PrintWriter w = new PrintWriter(System.out); - static long mod=998244353L,mod1=1000000007; - static int co[][]; - static void dsort(){ - Arrays.parallelSort(co,(o1, o2)->o1[0]!=o2[0]?o1[0]-o2[0]:o1[1]-o2[1]); - } - static class Pair{ - int w,b; - public Pair(int w,int b){ - this.b=b; - this.w=w; - } - } - static int c[],dp[],n,ans[]; - static ArrayList[] arr; - static int dfs(int i,int p){ - int di=-1; - if(c[i]==1)di=1; - for(int j:arr[i]){ - if(j!=p){ - di+=(Math.max(0,dfs(j,i))); - } - } - - return dp[i] =di; - } - static void dfs1(int i,int p){ - for(int j:arr[i]){ - if(j!=p){ - if(dp[j]<0){ - dp[j]+=Math.max(0,dp[i]); - } - else{ - dp[j]+=Math.max(0,dp[i]-dp[j]); - } - dfs1(j,i); - } - } - } - public static void main (String[] args)throws IOException { - InputReader sc=new InputReader(System.in); - n=sc.ni(); - c=new int[n+1]; - dp=new int[n+1]; - ans=new int[n+1]; - arr=new ArrayList[n+1]; - for(int i=1;i<=n;i++){ - c[i]=sc.ni(); - arr[i]=new ArrayList<>(); - } - for(int i=0;iarr[i+1]){ - return i+1; - } - } - return 0; - } -} diff --git a/Coding_Ninjas/src/main/java/Lecture10_Arrays2/Assignment/PushZerosToEnd.java b/Coding_Ninjas/src/main/java/Lecture10_Arrays2/Assignment/PushZerosToEnd.java deleted file mode 100755 index ee24a35..0000000 --- a/Coding_Ninjas/src/main/java/Lecture10_Arrays2/Assignment/PushZerosToEnd.java +++ /dev/null @@ -1,83 +0,0 @@ -package Lecture10_Arrays2.Assignment; - -public class PushZerosToEnd { - /* - You have been given a random integer array/list(ARR) of size N. You have been required to push all the zeros that are present in the array/list to the end of it. Also, make sure to maintain the relative order of the non-zero elements. -Note: -Change in the input array/list itself. You don't need to return or print the elements. - -You need to do this in one scan of array only. Don't use extra space. - - -Input format : -The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. - -First line of each test case or query contains an integer 'N' representing the size of the array/list. - -Second line contains 'N' single space separated integers representing the elements in the array/list. -Output Format : -For each test case, print the elements of the array/list in the desired order separated by a single space. - -Output for every test case will be printed in a separate line. -Constraints : -1 <= t <= 10^2 -0 <= N <= 10^5 -Time Limit: 1 sec -Sample Input 1: -1 -7 -2 0 0 1 3 0 0 -Sample Output 1: -2 1 3 0 0 0 0 - Explanation for the Sample Input 1 : -All the zeros have been pushed towards the end of the array/list. Another important fact is that the order of the non-zero elements have been maintained as they appear in the input array/list. -Sample Input 2: -2 -5 -0 3 0 2 0 -5 -9 0 0 8 2 -Sample Output 2: -3 2 0 0 0 -9 8 2 0 0 - */ - - public static void main(String[] args) { - int[] arr = new int[]{0,3,0,2,0}; - pushZerosAtEnd1(arr); - - for (int i:arr){ - System.out.print(i +" "); - } - } - - public static void pushZerosAtEnd(int[] arr) { - for (int i=0;i=arr.length && arr.length!=0){ - d %= arr.length; - } - reverse(arr,0,arr.length-1); - reverse(arr,0,arr.length-d-1); - reverse(arr,arr.length-d,arr.length-1); - } - public static void swap(int[] arr,int strt,int end){ - int temp = arr[strt]; - arr[strt]= arr[end]; - arr[end] = temp; - } - public static void reverse(int[] arr,int strt,int end){ - while (strt=0 && k>=0){ - sum = arr1[j]+arr2[k]+extra; - output[i]=sum%10; - extra = sum>9 ? 1:0; - k--; - j--; - i--; - } - while (j>=0){ - sum = extra+arr1[j]; - output[i]= sum%10; - extra= sum/10; - j--; - i--; - } - while (k>=0){ - sum = extra+arr2[k]; - output[i]= sum%10; - extra= sum/10; - k--; - i--; - } - output[i]=extra; - } - - } diff --git a/Coding_Ninjas/src/main/java/Lecture10_Arrays2/BubbleSort.java b/Coding_Ninjas/src/main/java/Lecture10_Arrays2/BubbleSort.java deleted file mode 100755 index ab81700..0000000 --- a/Coding_Ninjas/src/main/java/Lecture10_Arrays2/BubbleSort.java +++ /dev/null @@ -1,74 +0,0 @@ -package Lecture10_Arrays2; - -import java.util.Scanner; - -public class BubbleSort { - /* - Provided with a random integer array/list(ARR) of size N, you have been required to sort this array using 'Bubble Sort'. -Note: -Change in the input array/list itself. You don't need to return or print the elements. -Input format : -The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. - -First line of each test case or query contains an integer 'N' representing the size of the array/list. - -Second line contains 'N' single space separated integers representing the elements in the array/list. -Output format : -For each test case, print the elements of the array/list in sorted order separated by a single space. - -Output for every test case will be printed in a separate line. -Constraints : -1 <= t <= 10^2 -0 <= N <= 10^3 -Time Limit: 1 sec -Sample Input 1: -1 -7 -2 13 4 1 3 6 28 -Sample Output 1: -1 2 3 4 6 13 28 -Sample Input 2: -2 -5 -9 3 6 2 0 -4 -4 3 2 1 -Sample Output 2: -0 2 3 6 9 -1 2 3 4 - */ - public static void main(String[] args) { - int[] inputs = Takeinput(); - bubbleSort(inputs); - printArray(inputs); - - } - static int[] Takeinput(){ - Scanner s = new Scanner(System.in); - int n = s.nextInt(); - int[] arr = new int[n]; - for (int i=0;iarr[j+1]){ - int temp = arr[j]; - arr[j] = arr[j+1]; - arr[j+1]=temp; - } - } - } - } - -} diff --git a/Coding_Ninjas/src/main/java/Lecture10_Arrays2/CodeBinarySearch.java b/Coding_Ninjas/src/main/java/Lecture10_Arrays2/CodeBinarySearch.java deleted file mode 100755 index ba44893..0000000 --- a/Coding_Ninjas/src/main/java/Lecture10_Arrays2/CodeBinarySearch.java +++ /dev/null @@ -1,73 +0,0 @@ -package Lecture10_Arrays2; - -import java.util.Scanner; - -public class CodeBinarySearch { - /* - You have been given a sorted(in ascending order) integer array/list(ARR) of size N and an element X. Write a function to search this element in the given input array/list using 'Binary Search'. Return the index of the element in the input array/list. In case the element is not present in the array/list, then return -1. -Input format : -The first line contains an Integer 'N' which denotes the size of the array/list. - -Second line contains 'N' single space separated integers representing the elements in the array/list. - -Third line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.. - -All the 't' lines henceforth, will take the value of X to be searched for in the array/list. -Output Format : -For each test case, print the index at which X is present, -1 otherwise. - -Output for every test case will be printed in a separate line. -Constraints : -1 <= t <= 10^4 -0 <= N <= 10^6 -0 <= X <= 10^9 -Time Limit: 1 sec -Sample Input 1: -7 -1 3 7 9 11 12 45 -1 -3 -Sample Output 1: -1 -Sample Input 2: -7 -1 2 3 4 5 6 7 -2 -9 -7 -Sample Output 2: --1 -6 - */ - - public static void main(String[] args) { - int[] inputs = Takeinputs(); - int x = 9; - System.out.println(binarySearch(inputs,x)); - - } - static int[] Takeinputs(){ - Scanner s = new Scanner(System.in); - int n = s.nextInt(); - int[] arr = new int[n]; - for (int i=0;ix){ - end = mid-1; - }else { - strt = mid+1; - } - } - return -1; - } -} diff --git a/Coding_Ninjas/src/main/java/Lecture10_Arrays2/InsertionSort.java b/Coding_Ninjas/src/main/java/Lecture10_Arrays2/InsertionSort.java deleted file mode 100755 index a52f008..0000000 --- a/Coding_Ninjas/src/main/java/Lecture10_Arrays2/InsertionSort.java +++ /dev/null @@ -1,73 +0,0 @@ -package Lecture10_Arrays2; - -import java.util.Scanner; - -public class InsertionSort { - /* -Provided with a random integer array/list(ARR) of size N, you have been required to sort this array using 'Insertion Sort'. - Note: -Change in the input array/list itself. You don't need to return or print the elements. - Input format : -The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. - -First line of each test case or query contains an integer 'N' representing the size of the array/list. - -Second line contains 'N' single space separated integers representing the elements in the array/list. -Output Format : -For each test case, print the elements of the array/list in sorted order separated by a single space. - -Output for every test case will be printed in a separate line. -Constraints : -1 <= t <= 10^2 -0 <= N <= 10^3 -Time Limit: 1 sec -Sample Input 1: -1 -7 -2 13 4 1 3 6 28 -Sample Output 1: -1 2 3 4 6 13 28 -Sample Input 2: -2 -5 -9 3 6 2 0 -4 -4 3 2 1 -Sample Output 2: -0 2 3 6 9 -1 2 3 4 - */ - - public static void main(String[] args) { - int[] inputs = Takeinput(); - insertionSort(inputs); - printArray(inputs); - - } - static int[] Takeinput(){ - Scanner s = new Scanner(System.in); - int n = s.nextInt(); - int[] arr = new int[n]; - for (int i=0;i=0 && arr[j]>curr;j--){ - arr[j+1]=arr[j]; - arr[j]=curr; - } - } - } -} diff --git a/Coding_Ninjas/src/main/java/Lecture10_Arrays2/Mergesort.java b/Coding_Ninjas/src/main/java/Lecture10_Arrays2/Mergesort.java deleted file mode 100755 index cf134a0..0000000 --- a/Coding_Ninjas/src/main/java/Lecture10_Arrays2/Mergesort.java +++ /dev/null @@ -1,96 +0,0 @@ -package Lecture10_Arrays2; - -import java.util.Scanner; - -public class Mergesort { - /* - You have been given two sorted arrays/lists(ARR1 and ARR2) of size N and M respectively, merge them into a third array/list such that the third array is also sorted. -Input Format : -The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. - -First line of each test case or query contains an integer 'N' representing the size of the first array/list. - -Second line contains 'N' single space separated integers representing the elements of the first array/list. - -Third line contains an integer 'M' representing the size of the second array/list. - -Fourth line contains 'M' single space separated integers representing the elements of the second array/list. -Output Format : -For each test case, print the sorted array/list(of size N + M) in a single row, separated by a single space. - -Output for every test case will be printed in a separate line. -Constraints : -1 <= t <= 10^2 -0 <= N <= 10^5 -0 <= M <= 10^5 -Time Limit: 1 sec -Sample Input 1 : -1 -5 -1 3 4 7 11 -4 -2 4 6 13 -Sample Output 1 : -1 2 3 4 4 6 7 11 13 -Sample Input 2 : -2 -3 -10 100 500 -7 -4 7 9 25 30 300 450 -4 -7 45 89 90 -0 -Sample Output 2 : -4 7 9 10 25 30 100 300 450 500 -7 45 89 90 - - */ - public static void main(String[] args) { - int[] inputs ={1 ,3 ,4 ,7 ,11}; - int[] input1 = {2,4,6,13}; - printArray(MergeTwoSorted(inputs,input1)); - - } - static int[] Takeinput(){ - Scanner s = new Scanner(System.in); - int n = s.nextInt(); - int[] arr = new int[n]; - for (int i=0;i arr[j]){ - min = arr[j]; - index = j; - } - } - int temp = arr[i]; - arr[i]=arr[index]; - arr[index] = temp; - } - } -} diff --git a/Coding_Ninjas/src/main/java/Lecture10_BonusProb/DistributionProblem.java b/Coding_Ninjas/src/main/java/Lecture10_BonusProb/DistributionProblem.java deleted file mode 100755 index 5bbd14e..0000000 --- a/Coding_Ninjas/src/main/java/Lecture10_BonusProb/DistributionProblem.java +++ /dev/null @@ -1,64 +0,0 @@ -package Lecture10_BonusProb; - -import java.util.Scanner; - -public class DistributionProblem { - /* - - Anuj is one of the finest instructors at Coding Ninjas. He takes a batch of m students. He has been given n number of chocolate cartons. Each carton can have a variable number of chocolates. He has been given a task to distribute the chocolates to his students on the occasion of Holi. Now, here is the tricky part, he needs to distribute the chocolates in such a way that: -1. Each student gets one carton of chocolate. -2. The difference between the chocolate carton with the maximum number of chocolates and the carton with the minimum number of chocolates given to the students is minimum. -Input format: -The first line of input contains number of chocolate cartons, n. The following line contains n space separated integers. The following line of input contains number of children to whom those n carton are to be distributed, m. -Output format: -The first and only line of output contains the minimum difference possible between the student with maximum number of chocolates and the one with the minimum number of chocolates. -Constraints : -1 <= n <= 100 -1 <= m <= n -Sample Input 1 : -7 -7 3 2 4 9 12 56 -3 -Sample Output 1 : -2 -Sample Input 2 : -6 -1 2 3 4 78 80 -3 -Sample Output 2 : -2 - - - */ - public static void main(String[] args) { - Scanner s = new Scanner(System.in); - int k = s.nextInt(); - int[] arr = new int[k]; - for (int i =0;i0){ - min = Math.min(arr[k],min); - max = Math.max(arr[k],max); - k++; - mm--; - } - int minus = max-min; - minD = Math.min(minus,minD); - i++; - } - return minD; - } -} diff --git a/Coding_Ninjas/src/main/java/Lecture10_BonusProb/SuccessorProblem.java b/Coding_Ninjas/src/main/java/Lecture10_BonusProb/SuccessorProblem.java deleted file mode 100755 index 3f1b21e..0000000 --- a/Coding_Ninjas/src/main/java/Lecture10_BonusProb/SuccessorProblem.java +++ /dev/null @@ -1,35 +0,0 @@ -package Lecture10_BonusProb; - -public class SuccessorProblem { - /* - 1. CodingNinjas has given you a number. You have to print number, preceded by given number in lexicographically sorted permutation of all digits of given number. -2. If the number is last element of lexicographically sorted permutation of all digits of given number, then print the first element of the sorted list. -3. For Example: 123 -> 132 and 5243 -> 5324 and 321 -> 123 -Explanation: The lexicographically sorted list of permutation of all digits of ‘123’ is: -123 -132 -213 -231 -312 -321. -And the number which succeeds 123 in this list is 132 and hence, the answer. Similarly, since 321 is the last element of this list, I have to return 123, which is first element of the list. -Input Format: -The first and only line of input contains an integer. -Output Format: -The only line of output must contain number, preceded by given number in lexicographically sorted permutation of all digits of given number. -Constraints: -0 <= n <= 10^9 -Sample Input 1: -123 -Sample Output 1: -132 -Sample Input 2 : -402356 -Sample Output 2 : -402365 - - */ - public static void main(String[] args) { - - } -} diff --git a/Coding_Ninjas/src/main/java/Lecture13_TimeComplexity/ArrayEquilibriumIndex.java b/Coding_Ninjas/src/main/java/Lecture13_TimeComplexity/ArrayEquilibriumIndex.java deleted file mode 100755 index 2a74e50..0000000 --- a/Coding_Ninjas/src/main/java/Lecture13_TimeComplexity/ArrayEquilibriumIndex.java +++ /dev/null @@ -1,63 +0,0 @@ -package Lecture13_TimeComplexity; - -public class ArrayEquilibriumIndex { - /* - For a given array/list(ARR) of size 'N,' find and return the 'Equilibrium Index' of the array/list. -Equilibrium Index of an array/list is an index 'i' such that the sum of elements at indices [0 to (i - 1)] is equal to the sum of elements at indices [(i + 1) to (N-1)]. One thing to note here is, the item at the index 'i' is not included in either part. -If more than one equilibrium indices are present, then the index appearing first in left to right fashion should be returned. Negative one(-1) if no such index is present. -Example: -Let's consider an array/list Arr = [2, 3, 10, -10, 4, 2, 9] of size, N = 7. - -There exist two equilibrium indices, one at 2 and another at 3. - -At index 2, the sum of all the elements to the left, [2 + 3] is 5, and the elements to its right, [-10 + 4 + 2 + 9] is also 5. Hence index 2 is an equilibrium index according to the condition we want to achieve. Mind it that we haven't included the item at index 2, which is 10, to either of the parts. - -Similarly, we can see at index 3, the elements to its left sum up to 15 and to the right, sum up to 15 either. - -Since index 2 comes early in the order, left to right, the answer would be 2. -Input Format : -The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. - -The first line of each test case or query contains an integer 'N' representing the size of the first array/list. - -The second line contains 'N' single space separated integers representing the elements of the array/list -Output Format : -For each test case, print the 'Equilibrium Index'. - -Output for every test case will be printed in a separate line. -Constraints : -1 <= t <= 10^2 -0 <= N <= 10^6 - -Time Limit: 1 sec -Sample Input 1 : -1 -5 -1 4 9 3 2 -Sample Output 1 : -2 -Sample Input 2 : -2 -3 -1 4 6 -3 -1 -1 4 -Sample Output 2 : --1 -2 - */ - public static int arrayEquilibriumIndex(int[] arr){ - int right =0,left =0; - for(int i=0;i st = new Stack<>(); - for (int i=0;i st = new Stack<>(); - for (int i=0;i st = new Stack<>(); - span[0] = 1; - st.push(0); - for (int i=1;i input[st.peek()]){ - st.pop(); - } - if (st.isEmpty()) - span[i] = i+1; - else span[i] = i-st.peek(); - st.push(i); - } - return span; - } -} diff --git a/Coding_Ninjas/src/main/java/Lecture22_Stacks/BracketBalanced.java b/Coding_Ninjas/src/main/java/Lecture22_Stacks/BracketBalanced.java deleted file mode 100755 index efd24b0..0000000 --- a/Coding_Ninjas/src/main/java/Lecture22_Stacks/BracketBalanced.java +++ /dev/null @@ -1,80 +0,0 @@ -package Lecture22_Stacks; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.Arrays; -import java.util.List; -import java.util.Stack; - -public class BracketBalanced { - /* - For a given a string expression containing only round brackets or parentheses, check if - they are balanced or not. Brackets are said to be balanced if the bracket which opens last, - closes first. -Example: -Expression: (()()) -Since all the opening brackets have their corresponding closing brackets, we say it is balanced -and hence the output will be, 'true'. -You need to return a boolean value indicating whether the expression is balanced or not. -Note: -The input expression will not contain spaces in between. -Input Format: -The first and the only line of input contains a string expression without any spaces in between. - Output Format: -The only line of output prints 'true' or 'false'. -Note: -You don't have to print anything explicitly. It has been taken care of. Just implement the function. -Constraints: -1 <= N <= 10^7 - Where N is the length of the expression. - -Time Limit: 1sec -Sample Input 1 : -(()()()) -Sample Output 1 : -true -Sample Input 2 : -()()(() -Sample Output 2 : -false -Explanation to Sample Input 2: -The initial two pairs of brackets are balanced. But when you see, the opening bracket at the fourth -index doesn't have its corresponding closing bracket which makes it imbalanced and in turn, making -the whole expression imbalanced. Hence the output prints 'false'. - */ - static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - - public static void main(String[] args) throws IOException,NumberFormatException { - String Expression = br.readLine().trim(); - System.out.println(isBalanced(Expression)); - } - - private static final List leftBraces = Arrays.asList('{','[','('); - private static final List rightBraces = Arrays.asList('}',']',')'); - - private static boolean isLeft(char exp){ - return leftBraces.contains(exp); - } - private static boolean isRight(char exp){ - return rightBraces.contains(exp); - } - - private static boolean isMatched(char left,char right){ - return leftBraces.indexOf(left) == rightBraces.indexOf(right); - } - public static boolean isBalanced(String express){ - Stack stack = new Stack(); - for (char ch : express.toCharArray()){ - if (isLeft(ch)){ - stack.push(ch); - } - if (isRight(ch)){ - if (stack.isEmpty()) return false; - char top = stack.pop(); - if (!isMatched(top,ch)) return false; - } - } - return stack.isEmpty(); - } -} diff --git a/Coding_Ninjas/src/main/java/Lecture22_Stacks/ReverseStack.java b/Coding_Ninjas/src/main/java/Lecture22_Stacks/ReverseStack.java deleted file mode 100755 index b9d9f7e..0000000 --- a/Coding_Ninjas/src/main/java/Lecture22_Stacks/ReverseStack.java +++ /dev/null @@ -1,84 +0,0 @@ -package Lecture22_Stacks; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.Stack; - -public class ReverseStack { - /* - You have been given two stacks that can store integers as the data. Out of the two given stacks, one is populated and the other one is empty. You are required to write a function that reverses the populated stack using the one which is empty. -For Example: -Alt txt -Input Format : -The first line of input contains an integer N, denoting the total number of elements in the stack. - -The second line of input contains N integers separated by a single space, representing the order in which the elements are pushed into the stack. -Output Format: -The only line of output prints the order in which the stack elements are popped, all of them separated by a single space. -Note: -You are not required to print the expected output explicitly, it has already been taken care of. Just make the changes in the input stack itself. -Constraints: -1 <= N <= 10^3 --2^31 <= data <= 2^31 - 1 - -Time Limit: 1sec -Sample Input 1: -6 -1 2 3 4 5 10 -Note: -Here, 10 is at the top of the stack. -Sample Output 1: -1 2 3 4 5 10 -Note: -Here, 1 is at the top of the stack. -Sample Input 2: -5 -2 8 15 1 10 -Sample Output 2: -2 8 15 1 10 - */ - static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - - public static Stack takeInput() throws NumberFormatException, IOException { - int size = Integer.parseInt(br.readLine().trim()); - Stack input = new Stack<>(); - - if (size == 0) { - return input; - } - - String[] values = br.readLine().trim().split(" "); - - for(int i = 0; i < size; i++) { - input.push(Integer.parseInt(values[i])); - } - - return input; - } - - public static void main(String[] args) throws NumberFormatException, IOException { - Stack input = takeInput(); - Stack empty = new Stack<>(); - - reverseStack(input, empty); - - while(!input.isEmpty()) { - System.out.print(input.pop() + " "); - } - - } - - private static void reverseStack(Stack input, Stack extra) { - if (input.isEmpty()) return; - int Last = input.pop(); - reverseStack(input,extra); - while (!input.isEmpty()){ - extra.push(input.pop()); - } - input.push(Last); - while (!extra.isEmpty()){ - input.push(extra.pop()); - } - } -} diff --git a/Coding_Ninjas/src/main/java/Lecture22_Stacks/StackEmptyException.java b/Coding_Ninjas/src/main/java/Lecture22_Stacks/StackEmptyException.java deleted file mode 100755 index f1b87b7..0000000 --- a/Coding_Ninjas/src/main/java/Lecture22_Stacks/StackEmptyException.java +++ /dev/null @@ -1,5 +0,0 @@ -package Lecture22_Stacks; - -public class StackEmptyException extends Exception{ - private static final long serialVersionUID = 1L; -} diff --git a/Coding_Ninjas/src/main/java/Lecture22_Stacks/StackFullException.java b/Coding_Ninjas/src/main/java/Lecture22_Stacks/StackFullException.java deleted file mode 100755 index 98db7e5..0000000 --- a/Coding_Ninjas/src/main/java/Lecture22_Stacks/StackFullException.java +++ /dev/null @@ -1,6 +0,0 @@ -package Lecture22_Stacks; - -public class StackFullException extends Exception { - - private static final long serialVersionUID = 1L; -} diff --git a/Coding_Ninjas/src/main/java/Lecture22_Stacks/StackLL.java b/Coding_Ninjas/src/main/java/Lecture22_Stacks/StackLL.java deleted file mode 100755 index 2f69f30..0000000 --- a/Coding_Ninjas/src/main/java/Lecture22_Stacks/StackLL.java +++ /dev/null @@ -1,194 +0,0 @@ -package Lecture22_Stacks; - -import java.util.Scanner; - -/* -Implement a Stack Data Structure specifically to store integer data using a Singly Linked List. -The data members should be private. -You need to implement the following public functions : -1. Constructor: -It initialises the data members as required. -2. push(data) : -This function should take one argument of type integer. It pushes the element into the stack and returns nothing. -3. pop() : -It pops the element from the top of the stack and in turn, returns the element being popped or deleted. In case the stack is empty, it returns -1. -4. top : -It returns the element being kept at the top of the stack. In case the stack is empty, it returns -1. -5. size() : -It returns the size of the stack at any given instance of time. -6. isEmpty() : -It returns a boolean value indicating whether the stack is empty or not. -Operations Performed on the Stack: -Query-1(Denoted by an integer 1): Pushes an integer data to the stack. - -Query-2(Denoted by an integer 2): Pops the data kept at the top of the stack and returns it to the caller. - -Query-3(Denoted by an integer 3): Fetches and returns the data being kept at the top of the stack but doesn't remove it, unlike the pop function. - -Query-4(Denoted by an integer 4): Returns the current size of the stack. - -Query-5(Denoted by an integer 5): Returns a boolean value denoting whether the stack is empty or not. -Input Format: -The first line contains an integer 'q' which denotes the number of queries to be run against each operation in the stack. -Then the test cases follow. - -Every 'q' lines represent an operation that needs to be performed. - -For the push operation, the input line will contain two integers separated by a single space, representing the type of the operation in integer and the integer data being pushed into the stack. - -For the rest of the operations on the stack, the input line will contain only one integer value, representing the query being performed on the stack. - Output Format: -For Query-1, you do not need to return anything. -For Query-2, prints the data being popped from the stack. -For Query-3, prints the data kept on the top of the stack. -For Query-4, prints the current size of the stack. -For Query-5, prints 'true' or 'false'(without quotes). - -Output for every query will be printed in a separate line. -Note: -You are not required to print anything explicitly. It has already been taken care of. Just implement the function. - Constraints: -1 <= q <= 10^5 -1 <= x <= 5 --2^31 <= data <= 2^31 - 1 and data != -1 - -Where 'q' is the total number of queries being performed on the stack, 'x' is the range for every query and data represents the integer pushed into the stack. - -Time Limit: 1 second -Sample Input 1: -6 -1 13 -1 47 -4 -5 -2 -3 -Sample Output 1: -2 -false -47 -13 -Sample Input 2: -4 -5 -2 -1 10 -5 -Sample Output 2: -true --1 -false - Explanation of Sample Input 2: -There are 4 queries in total. -The first one is Query-5: It tells whether the stack is empty or not. Since the stack is empty at this point, the output is 'true'. - -The second one is Query-2: It pops the data from the stack. Since at this point in time, no data exist in the stack hence, it prints -1. - -The third one is Query-1: It pushes the specified data 10 into the stack and since the function doesn't return anything, nothing is printed. - -The fourth one is Query-5: It tells whether the stack is empty at this point or not. Since the stack has one element and hence it is not empty, false is printed. - */ -class Node { - int data; - Node next; - - public Node(int data) { - this.data = data; - this.next = null; - } - -} -public class StackLL { - private static Scanner s = new Scanner(System.in); - - public static void main(String[] args) { - Stack1 stack = new Stack1(); - - int q = s.nextInt(); - - while (q > 0) { - int choice, input; - choice = s.nextInt(); - - switch(choice) { - case 1: - input = s.nextInt(); - stack.push(input); - break; - - case 2: - System.out.println(stack.pop()); - break; - - case 3: - System.out.println(stack.top()); - break; - - case 4: - System.out.println(stack.getSize()); - break; - - default: - System.out.println((stack.isEmpty()) ? "true" : "false"); - } - - q -= 1; - } - - } - - -} -class Stack1 { - - //Define the data members - private Node head; - private int size; - - public Stack1() { - head = null; - size = 0; - } - - - - /*----------------- Public Functions of Stack -----------------*/ - - - public int getSize() { - return size; - } - - public boolean isEmpty() { - return size == 0; - } - - public void push(int element) { - Node newNode = new Node(element); - if(head == null){ - head = newNode; - }else{ - newNode.next = head; - head = newNode; - } - size++; - } - - public int pop() { - if(isEmpty()){ - return -1; - } - int data = head.data; - head = head.next; - size--; - return data; - - } - - public int top() { - if(isEmpty()){ - return -1; - } - return head.data; - } -} diff --git a/Coding_Ninjas/src/main/java/Lecture22_Stacks/StackUse.java b/Coding_Ninjas/src/main/java/Lecture22_Stacks/StackUse.java deleted file mode 100755 index 84ab277..0000000 --- a/Coding_Ninjas/src/main/java/Lecture22_Stacks/StackUse.java +++ /dev/null @@ -1,20 +0,0 @@ -package Lecture22_Stacks; - -public class StackUse { - public static void main(String[] args) throws StackFullException, StackEmptyException { -// StackUsingArray stack = new StackUsingArray(); -// stack.push(10); -// System.out.println(stack.top()); -// System.out.println(stack.pop()); -// System.out.println(stack.size()); -// System.out.println(stack.isEmpty()); - - StackUsingLL stack = new StackUsingLL<>(); - stack.push(12); - stack.push(15); - System.out.println(stack.top()); - System.out.println(stack.pop()); - System.out.println(stack.size()); - System.out.println(stack.isEmpty()); - } -} diff --git a/Coding_Ninjas/src/main/java/Lecture22_Stacks/StackUsingArray.java b/Coding_Ninjas/src/main/java/Lecture22_Stacks/StackUsingArray.java deleted file mode 100755 index c699c03..0000000 --- a/Coding_Ninjas/src/main/java/Lecture22_Stacks/StackUsingArray.java +++ /dev/null @@ -1,58 +0,0 @@ -package Lecture22_Stacks; - -public class StackUsingArray { - - private int data[]; - private int topIndex; - - - public StackUsingArray(){ - data = new int[2]; - topIndex = -1; - } - - public StackUsingArray(int size){ - data = new int[size]; - topIndex = -1; - } -//0(1) - public int size(){ - return topIndex+1; - } -//O(1) - public void push(int ele) throws StackFullException{ - if (topIndex == data.length-1){ - // throw new StackFullException(); - } - data[++topIndex] = ele; - } - - private void Capacitydouble(){ - int temp[] = data; - data = new int[2*temp.length]; - for (int i =0;i{ - - private Node head; - private int size; - - - public StackUsingLL(){ - head = null; - size =0; - } - - public int size(){ - return size; - } - - public void push(T ele){ - Node newHead = new Node(ele); - newHead.next = head; - head = newHead; - size++; - } - - public T top() throws StackEmptyException { - if (head == null){ - throw new StackEmptyException(); - } - return head.data; - } - - public T pop() throws StackEmptyException { - if (head == null){ - throw new StackEmptyException(); - } - T temp = head.data; - head = head.next; - size--; - return temp; - } - - public boolean isEmpty(){ - return size == 0; - } -} diff --git a/Coding_Ninjas/src/main/java/Lecture23_Queues/Assignment/ReverseFirstKelementa.java b/Coding_Ninjas/src/main/java/Lecture23_Queues/Assignment/ReverseFirstKelementa.java deleted file mode 100755 index 5c3bc12..0000000 --- a/Coding_Ninjas/src/main/java/Lecture23_Queues/Assignment/ReverseFirstKelementa.java +++ /dev/null @@ -1,108 +0,0 @@ -package Lecture23_Queues.Assignment; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.LinkedList; -import java.util.Queue; -import java.util.Stack; - -public class ReverseFirstKelementa { - /* - For a given queue containing all integer data, reverse the first K elements. -You have been required to make the desired change in the input queue itself. -Example: -alt txt -For the above input queue, if K = 4 then after reversing the first 4 elements, the queue will be updated as: -alt txt -Input Format : -The first line of input would contain two integers N and K, separated by a single space. They denote the -total number of elements in the queue and the count with which the elements need to be reversed respectively. - -The second line of input contains N integers separated by a single space, representing the order in -which the elements are enqueued into the queue. -Output Format: -The only line of output prints the updated order in which the queue elements are dequeued, all of them -separated by a single space. -Note: -You are not required to print the expected output explicitly, it has already been taken care of. Just make -the changes in the input queue itself. -Contraints : -1 <= N <= 10^6 -1 <= K <= N --2^31 <= data <= 2^31 - 1 - - Time Limit: 1sec -Sample Input 1: -5 3 -1 2 3 4 5 -Sample Output 1: -3 2 1 4 5 -Sample Input 2: -7 7 -3 4 2 5 6 7 8 -Sample Output 2: -8 7 6 5 2 4 3 - */ - - static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - - public static Input takeInput() throws NumberFormatException, IOException { - String[] n_k = br.readLine().trim().split(" "); - - int n = Integer.parseInt(n_k[0]); - int k = Integer.parseInt(n_k[1]); - - String[] values = br.readLine().trim().split(" "); - - Queue queue = new LinkedList<>(); - - for (int i = 0; i < n; i++) { - queue.add(Integer.parseInt(values[i])); - } - - return new Input(n, k, queue); - - } - - public static void main(String[] args) throws NumberFormatException, IOException { - Input input = takeInput(); - - int n = input.n; - int k = input.k; - Queue queue = input.queue; - - queue = reverseKElements(queue, k); - - - while (!queue.isEmpty()) { - System.out.print(queue.poll() + " "); - } - } - - private static Queue reverseKElements(Queue input, int k) { - if (input.isEmpty() || k>input.size() || k<=0) return input; - Stack st = new Stack<>(); - for (int i=0;i queue; - - public Input(int n, int k, Queue queue) { - this.queue = queue; - this.n = n; - this.k = k; - } - -} - diff --git a/Coding_Ninjas/src/main/java/Lecture23_Queues/Assignment/ReverseQueue.java b/Coding_Ninjas/src/main/java/Lecture23_Queues/Assignment/ReverseQueue.java deleted file mode 100755 index ad1c2c6..0000000 --- a/Coding_Ninjas/src/main/java/Lecture23_Queues/Assignment/ReverseQueue.java +++ /dev/null @@ -1,99 +0,0 @@ -package Lecture23_Queues.Assignment; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.LinkedList; -import java.util.Queue; - -public class ReverseQueue { - /* - You have been given a queue that can store integers as the data. You are required to write a function - that reverses the populated queue itself without using any other data structures. -Example: -Alt txt -Alt txt -Input Format: -The first list of input contains an integer 't' denoting the number of test cases/queries to be run. -Then the test cases follow. - -The first line input for each test case/query contains an integer N, denoting the total number of elements in the queue. - -The second line of input contains N integers separated by a single space, representing the order in which -the elements are enqueued into the queue. -Output Format: -For each test case/query, the only line of output prints the order in which the queue elements are dequeued, -all of them separated by a single space. - -Output for every test case/query will be printed on a new line. -Note: -You are not required to print the expected output explicitly, it has already been taken care of. Just make -the changes in the input queue itself. -Constraints: -1 <= t <= 100 -1 <= N <= 10^4 --2^31 <= data <= 2^31 - 1 - -Time Limit: 1sec -Sample Input 1: -1 -6 -1 2 3 4 5 10 -Note: -Here, 1 is at the front and 10 is at the rear of the queue. -Sample Output 1: -10 5 4 3 2 1 -Sample Input 2: -2 -5 -2 8 15 1 10 -3 -10 20 30 -Sample Output 2: -10 1 15 8 2 -30 20 10 - */ - - static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - - public static Queue takeInput() throws NumberFormatException, IOException { - - int n = Integer.parseInt(br.readLine().trim()); - - String[] values = br.readLine().trim().split(" "); - - Queue queue = new LinkedList<>(); - - for (int i = 0; i < n; i++) { - queue.add(Integer.parseInt(values[i])); - } - - return queue; - - } - - public static void main(String[] args) throws NumberFormatException, IOException { - - int t = Integer.parseInt(br.readLine().trim()); - - while (t > 0) { - Queue queue = takeInput(); - reverseQueue(queue); - - while (!queue.isEmpty()) { - System.out.print(queue.poll() + " "); - } - - System.out.println(); - - t -= 1; - } - } - - private static void reverseQueue(Queue input) { - if (input.isEmpty()) return; - int temp = input.poll(); - reverseQueue(input); - input.add(temp); - } -} diff --git a/Coding_Ninjas/src/main/java/Lecture23_Queues/QueueCollection.java b/Coding_Ninjas/src/main/java/Lecture23_Queues/QueueCollection.java deleted file mode 100755 index 660efb7..0000000 --- a/Coding_Ninjas/src/main/java/Lecture23_Queues/QueueCollection.java +++ /dev/null @@ -1,43 +0,0 @@ -package Lecture23_Queues; - -public class QueueCollection { - public static void main(String[] args) throws QueueEmptyException { -// Queue qq = new LinkedList<>(); -// qq.add(10); -// qq.add(200); -// qq.add(30); -// qq.add(400); -// qq.add(50); -// System.out.println(qq.size()); -// System.out.println(qq.poll()); -// System.out.println(qq.peek()); -// System.out.println(qq.size()); -// System.out.println(qq.element()); - -// QueueUsingStack qq = new QueueUsingStack<>(); -// qq.enqueue(10); -// qq.enqueue(20); -// qq.enqueue(30); -// qq.enqueue(40); -// System.out.println(qq.size()); -// System.out.println(qq.isEmpty()); -// System.out.println(qq.dequeue()); -// System.out.println(qq.dequeue()); -// System.out.println(qq.front()); -// System.out.println(qq.dequeue()); -// System.out.println(qq.dequeue()); - - StacksUsing2Queues st2 = new StacksUsing2Queues(); - st2.push(10); - st2.push(200); - st2.push(30); - st2.push(400); - System.out.println(st2.size()); - System.out.println(st2.isEmpty()); - System.out.println(st2.top()); - System.out.println(st2.pop()); - System.out.println(st2.pop()); - System.out.println(st2.top()); - System.out.println(st2.size()); - } -} diff --git a/Coding_Ninjas/src/main/java/Lecture23_Queues/QueueEmptyException.java b/Coding_Ninjas/src/main/java/Lecture23_Queues/QueueEmptyException.java deleted file mode 100755 index d566520..0000000 --- a/Coding_Ninjas/src/main/java/Lecture23_Queues/QueueEmptyException.java +++ /dev/null @@ -1,4 +0,0 @@ -package Lecture23_Queues; - -public class QueueEmptyException extends Exception{ -} diff --git a/Coding_Ninjas/src/main/java/Lecture23_Queues/QueueFullException.java b/Coding_Ninjas/src/main/java/Lecture23_Queues/QueueFullException.java deleted file mode 100755 index 9352d35..0000000 --- a/Coding_Ninjas/src/main/java/Lecture23_Queues/QueueFullException.java +++ /dev/null @@ -1,5 +0,0 @@ -package Lecture23_Queues; - -public class QueueFullException extends Exception{ - -} diff --git a/Coding_Ninjas/src/main/java/Lecture23_Queues/QueueUse.java b/Coding_Ninjas/src/main/java/Lecture23_Queues/QueueUse.java deleted file mode 100755 index 03c2c6c..0000000 --- a/Coding_Ninjas/src/main/java/Lecture23_Queues/QueueUse.java +++ /dev/null @@ -1,16 +0,0 @@ -package Lecture23_Queues; - -public class QueueUse { - public static void main(String[] args) throws QueueFullException, QueueEmptyException { - QueueUsingArray queue = new QueueUsingArray(); - queue.enqueue(10); - queue.enqueue(20); - queue.enqueue(40); - System.out.println(queue.size()); - System.out.println(queue.Front()); - System.out.println(queue.dequeue()); - System.out.println(queue.size()); - System.out.println(queue.Front()); - - } -} diff --git a/Coding_Ninjas/src/main/java/Lecture23_Queues/QueueUsingArray.java b/Coding_Ninjas/src/main/java/Lecture23_Queues/QueueUsingArray.java deleted file mode 100755 index ef62e46..0000000 --- a/Coding_Ninjas/src/main/java/Lecture23_Queues/QueueUsingArray.java +++ /dev/null @@ -1,80 +0,0 @@ -package Lecture23_Queues; - -public class QueueUsingArray { - - private int[] data; - private int front; - private int rear,size; - public QueueUsingArray(){ - data = new int[5]; - front = -1; - rear = -1; - size=0; - } - public QueueUsingArray(int Capacity){ - data = new int[Capacity]; - front = -1 ; - rear = -1; - size=0; - } - - public void enqueue(int ele) throws QueueFullException { - if (size >= data.length-1){ - // throw new QueueFullException(); - doubleCapacity(); - } - if (size == 0) front =0; - //***----- if circular queue ---*** - // if (rear == data.length) rear =0; - //--------------or--------- - // rear = (rear+1)%data.length; - //data[rear] = ele - data[++rear]=ele; - size++; - - } - - private void doubleCapacity(){ - int temp[] = data; - data = new int[2 * temp.length]; - int index=0; - for (int i = front;i{ - private Node front; - private Node rear; - private int size; - - public QueueUsingLL(){ - front = null; - rear = null; - size =0; - } - - public int size(){ - return size; - } - - public boolean isEmpty(){ - return size == 0; - } - - public void enqueue(T data){ - Node newNode = new Node<>(data); - if (size == 0){ - front=newNode; - rear = newNode; - size++; - }else { - rear.next = newNode; - rear = newNode; - size++; - } - } - - public T Front() throws QueueEmptyException { - if (front == null) - throw new QueueEmptyException(); - return front.data; - } - - public T dequeue() throws QueueEmptyException { - if (front == null) - throw new QueueEmptyException(); - T temp = front.data; - front = front.next; - size--; - return temp; - - } - -} diff --git a/Coding_Ninjas/src/main/java/Lecture23_Queues/QueueUsingStack.java b/Coding_Ninjas/src/main/java/Lecture23_Queues/QueueUsingStack.java deleted file mode 100755 index 5a9d205..0000000 --- a/Coding_Ninjas/src/main/java/Lecture23_Queues/QueueUsingStack.java +++ /dev/null @@ -1,50 +0,0 @@ -package Lecture23_Queues; - -import java.util.Stack; - -public class QueueUsingStack { - private Stack s1; - private Stack s2; - - public QueueUsingStack() { - s1 = new Stack<>(); - s2 = new Stack<>(); - } - - public int size(){ - return s1.size(); - } - - public boolean isEmpty(){ - return s1.isEmpty(); - } - - public void enqueue(T ele){ - s1.push(ele); - } - - public T front() throws QueueEmptyException { - if (isEmpty()) throw new QueueEmptyException(); - while (!s1.isEmpty()){ - s2.push(s1.pop()); - } - T temp = s2.peek(); - while (!s2.isEmpty()){ - s1.push(s2.pop()); - } - return temp; - } - - public T dequeue() throws QueueEmptyException { - if (isEmpty()) throw new QueueEmptyException(); - while (!s1.isEmpty()){ - s2.push(s1.pop()); - } - T temp = s2.pop(); - while (!s2.isEmpty()){ - s1.push(s2.pop()); - } - return temp; - } - -} diff --git a/Coding_Ninjas/src/main/java/Lecture23_Queues/StacksUsing2Queues.java b/Coding_Ninjas/src/main/java/Lecture23_Queues/StacksUsing2Queues.java deleted file mode 100755 index 96dc0e9..0000000 --- a/Coding_Ninjas/src/main/java/Lecture23_Queues/StacksUsing2Queues.java +++ /dev/null @@ -1,65 +0,0 @@ -package Lecture23_Queues; - -import java.util.LinkedList; -import java.util.Queue; - -public class StacksUsing2Queues { - private Queue q1; - private Queue q2; - public StacksUsing2Queues() { - //Implement the Constructor - q1 = new LinkedList<>(); - q2 = new LinkedList<>(); - } - public int size(){ - return q1.size(); - } - - public boolean isEmpty(){ - return q1.isEmpty(); - } - - public void push(int ele){ - q1.add(ele); - } - - public int top(){ - if(isEmpty()){ - return -1; - } - while(q1.size()>1) { - q2.add(q1.poll()); - } - int temp = q1.peek(); - q2.add(q1.poll()); - Queue t = q1; - q1 = q2; - q2 = t; - return temp; - - } - - public int pop(){ - if (isEmpty()) return -1; - while (!q1.isEmpty()){ - q2.add(q1.poll()); - } - int temp = q2.poll(); - while (!q2.isEmpty()){ - q1.add(q2.poll()); - } - return temp; - -// if(isEmpty()){ -// return -1; -// } -// while(q1.size()>1) { -// q2.add(q1.poll()); -// } -// int temp = q1.poll(); -// Queue t = q1; -// q1 = q2; -// q2 = t; -// return temp; - } -} diff --git a/Coding_Ninjas/src/main/java/Lecture5_Patterns1/AlphaPattern.java b/Coding_Ninjas/src/main/java/Lecture5_Patterns1/AlphaPattern.java deleted file mode 100755 index b42acea..0000000 --- a/Coding_Ninjas/src/main/java/Lecture5_Patterns1/AlphaPattern.java +++ /dev/null @@ -1,53 +0,0 @@ -package Lecture5_Patterns1; - -import java.util.Scanner; - -public class AlphaPattern { - /* - Print the following pattern for the given N number of rows. -Pattern for N = 3 - A - BB - CCC -Input format : -Integer N (Total no. of rows) -Output format : -Pattern in N lines -Constraints -0 <= N <= 26 -Sample Input 1: -7 -Sample Output 1: -A -BB -CCC -DDDD -EEEEE -FFFFFF -GGGGGGG -Sample Input 2: -6 -Sample Output 2: -A -BB -CCC -DDDD -EEEEE -FFFFFF - */ - public static void main(String[] args) { - Scanner s = new Scanner(System.in); - int N = s.nextInt(); - s.close(); - int i=65,j=0; - while (j0){ - System.out.print(j); - j--; - } - System.out.println(); - i++; - } - } -} diff --git a/Coding_Ninjas/src/main/java/Lecture5_Patterns1/SquarePattern.java b/Coding_Ninjas/src/main/java/Lecture5_Patterns1/SquarePattern.java deleted file mode 100755 index 924f40a..0000000 --- a/Coding_Ninjas/src/main/java/Lecture5_Patterns1/SquarePattern.java +++ /dev/null @@ -1,59 +0,0 @@ -package Lecture5_Patterns1; - -import java.util.Scanner; - -public class SquarePattern { - /* - - Print the following pattern for the given N number of rows. -Pattern for N = 4 -4444 -4444 -4444 -4444 - -Input format : - -Integer N (Total no. of rows) -Output format : -Pattern in N lines -Constraints -0 <= N <= 50 - -Sample Input 1: -7 -Sample Output 1: -7777777 -7777777 -7777777 -7777777 -7777777 -7777777 -7777777 -Sample Input 1: -6 -Sample Output 1: -666666 -666666 -666666 -666666 -666666 -666 cfvcvf666 - */ - public static void main(String[] args) { - Scanner s = new Scanner(System.in); - int N = s.nextInt(); - s.close(); - int i=0; - while (i=1){ - System.out.print(currcol); - currcol--; - } - System.out.print('*'); - System.out.println(); - i++; - } - //Secong Half - while (j<=N-1){ - int curCol = 1; - System.out.print('*'); - while (curCol<=(N-1-j+1)){ - System.out.print(curCol); - curCol++; - } - curCol = curCol-2; - while (curCol>=1){ - System.out.print(curCol); - curCol--; - } - System.out.print('*'); - System.out.println(); - j++; - } - System.out.println('*'); - } -} diff --git a/Coding_Ninjas/src/main/java/Lecture6_Patterns2/Assignment/OddSquare.java b/Coding_Ninjas/src/main/java/Lecture6_Patterns2/Assignment/OddSquare.java deleted file mode 100755 index a6625e4..0000000 --- a/Coding_Ninjas/src/main/java/Lecture6_Patterns2/Assignment/OddSquare.java +++ /dev/null @@ -1,58 +0,0 @@ -package Lecture6_Patterns2.Assignment; - -import java.util.Scanner; - -public class OddSquare { - /* - Write a program to print the pattern for the given N number of rows. -For N = 4 -1357 -3571 -5713 -7135 -Input Format : -A single integer: N -Output Format : -Required Pattern -Constraints : -0 <= N <= 50 -Sample Input 1 : -3 -Sample Output 1 : -135 -351 -513 -Sample Input 2 : - 5 -Sample Output 2 : -13579 -35791 -57913 -79135 -91357 - - */ - public static void main(String[] args) { - Scanner s = new Scanner(System.in); - int N = s.nextInt(); - s.close(); - int i=1; - while (i<=N){ - int j=i; - while (j<=N){ - int sum = 2*j-1; - System.out.print(sum); - j++; - } - int k=1; - while (k1 && j61->67->100" is the list - which represents the last 4 nodes. When we move this list to the front then the remaining part of the initial - list which is, "10->6->77" is attached after 100. Hence, the new list formed with an updated head pointing to 90. - */ -// class Node{ -// T data; -// FindaNodeinLinkedList.Node next; -// public Node(T data){ -// this.data = data; -// } -// } - - public static int Length(Node head){ - int count =1; - Node temp = head; - while(temp.next!=null){ - count++; - temp = temp.next; - } - return count; - } - public static Node appendLastNToFirst(Node head, int n){ - if (head == null){ - return head; - } - if (n == 0){ - return head; - } - - Node nextH = head; - int i = Length(head)-n-1; - int pos=0; - while (pos<=i){ - pos++; - nextH = nextH.next; - } - Node temp = nextH.next,newH = temp; - while (newH.next!=null){ - newH=newH.next; - } - newH.next = nextH; - return temp; - } -} diff --git a/Coding_Ninjas/src/main/java/LinekedList1/Assignment/EliminateduplicatesfromLL.java b/Coding_Ninjas/src/main/java/LinekedList1/Assignment/EliminateduplicatesfromLL.java deleted file mode 100755 index 2379b9b..0000000 --- a/Coding_Ninjas/src/main/java/LinekedList1/Assignment/EliminateduplicatesfromLL.java +++ /dev/null @@ -1,50 +0,0 @@ -package LinekedList1.Assignment; - -public class EliminateduplicatesfromLL { - /* - You have been given a singly linked list of integers where the elements are sorted in ascending order. Write a function that removes the consecutive duplicate values such that the given list only contains unique elements and returns the head to the updated list. - Input format : -The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. - -The first and the only line of each test case or query contains the elements(in ascending order) of the singly linked list separated by a single space. - Remember/Consider : -While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element. - Output format : -For each test case/query, print the resulting singly linked list of integers in a row, separated by a single space. - -Output for every test case will be printed in a seperate line. -Constraints : -1 <= t <= 10^2 -0 <= M <= 10^5 -Time Limit: 1sec - -Where 'M' is the size of the singly linked list. -Sample Input 1 : -1 -1 2 3 3 3 3 4 4 4 5 5 7 -1 -Sample Output 1 : -1 2 3 4 5 7 -Sample Input 2 : -2 -10 20 30 40 50 -1 -10 10 10 10 -1 -Sample Output 2 : -10 20 30 40 50 -10 - */ - - public static Node removeDuplicates(Node head){ - if (head == null){ - return head; - } - Node newHead = head; - while (newHead != null && newHead.next != null) { - if (newHead.data.equals(newHead.next.data)){ - newHead.next=newHead.next.next; - }else { - newHead=newHead.next; - } - } - return head; - } -} diff --git a/Coding_Ninjas/src/main/java/LinekedList1/Assignment/FindaNodeinLinkedList.java b/Coding_Ninjas/src/main/java/LinekedList1/Assignment/FindaNodeinLinkedList.java deleted file mode 100755 index 186a76c..0000000 --- a/Coding_Ninjas/src/main/java/LinekedList1/Assignment/FindaNodeinLinkedList.java +++ /dev/null @@ -1,81 +0,0 @@ -package LinekedList1.Assignment; - - -class Node{ - T data; - Node next; - public Node(T data){ - this.data = data; - } -} -public class FindaNodeinLinkedList { - /* - You have been given a singly linked list of integers. Write a function that returns the index/position of integer data denoted by 'N' (if it exists). Return -1 otherwise. -Note : -Assume that the Indexing for the singly linked list always starts from 0. -Input format : -The first line contains an Integer 'T' which denotes the number of test cases. - -The first line of each test case or query contains the elements of the singly linked list separated by a single space. - -The second line contains the integer value 'N'. It denotes the data to be searched in the given singly linked list. -Remember/Consider : -While specifying the list elements for input, -1 indicates the end of the singly linked list and hence -1 would never be a list element. -Output format : -For each test case, return the index/position of 'N' in the singly linked list. Return -1, otherwise. - -Output for every test case will be printed in a separate line. -Note: -You do not need to print anything; it has already been taken care of. Just implement the given function. - Constraints : -1 <= T <= 10^2 -0 <= M <= 10^5 - -Where 'M' is the size of the singly linked list. - -Time Limit: 1 sec -Sample Input 1 : -2 -3 4 5 2 6 1 9 -1 -5 -10 20 30 40 50 60 70 -1 -6 -Sample Output 1 : -2 --1 - Explanation for Sample Output 1: -In test case 1, 'N' = 5 appears at position 2 (0-based indexing) in the given linked list. - -In test case 2, we can see that 'N' = 6 is not present in the given linked list. -Sample Input 2 : -2 -1 -1 -2 -3 4 5 2 6 1 9 -1 -6 -Sample Output 2 : --1 -4 - Explanation for Sample Output 2: -In test case 1, we can see that 'N' = 2 is not present in the given linked list. - -In test case 2, 'N' = 6 appears at position 4 (0-based indexing) in the given linked list. - */ - - - public static int findNode(Node head, int n){ - if (head == null){ - return -1; - } - Node temp = head; - int i=0; - while (temp!=null){ - if (temp.data == n){ - return i; - } - i++; - temp=temp.next; - } - return -1; - } -} diff --git a/Coding_Ninjas/src/main/java/LinekedList1/Assignment/PalindromeLinkedList.java b/Coding_Ninjas/src/main/java/LinekedList1/Assignment/PalindromeLinkedList.java deleted file mode 100755 index c0a235b..0000000 --- a/Coding_Ninjas/src/main/java/LinekedList1/Assignment/PalindromeLinkedList.java +++ /dev/null @@ -1,132 +0,0 @@ -package LinekedList1.Assignment; - -import java.util.Scanner; - -public class PalindromeLinkedList { - /* - You have been given a head to a singly linked list of integers. Write a function check to whether the list given is a 'Palindrome' or not. - Input format : -The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. - -First and the only line of each test case or query contains the the elements of the singly linked list separated by a single space. - Remember/Consider : -While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element. - Output format : -For each test case, the only line of output that print 'true' if the list is Palindrome or 'false' otherwise. - Constraints : -1 <= t <= 10^2 -0 <= M <= 10^5 -Time Limit: 1sec - -Where 'M' is the size of the singly linked list. -Sample Input 1 : -1 -9 2 3 3 2 9 -1 -Sample Output 1 : -true -Sample Input 2 : -2 -0 2 3 2 5 -1 --1 -Sample Output 2 : -false -true -Explanation for the Sample Input 2 : -For the first query, it is pretty intuitive that the the given list is not a palindrome, hence the output is 'false'. - -For the second query, the list is empty. An empty list is always a palindrome , hence the output is 'true'. - */ - - public static Node Input(){ - Scanner s = new Scanner(System.in); - int data = s.nextInt(); - Node head = null,tail=null; - while (data!=-1){ - Node Chead = new Node<>(data); - if (head==null){ - head = Chead; - tail = Chead; - }else { - tail.next = Chead; - tail = Chead; - } - data =s.nextInt(); - } - - return head; - } - - public static Node reverse(Node head){ - Node curr = head; - Node prev = null; - Node frwd = null; - - while (curr!=null){ - frwd = curr.next; - curr.next = prev; - prev = curr; - curr = frwd; - } - return prev; - -// if (head.next==null){ -// return head; -// } -// Node store = head.next; -// Node rev = reverse(head.next); -// store.next = head; -// head.next = null; -// return head; - } - - - // Time Complexity o(n) - //Space Complexity O(1) - - - public static boolean isPalindrome(Node head){ - if (head == null && head.next == null){ - return true; - } - //Center - // for breaking into two parts - Node slow = head; - Node fast = head; - while(fast.next!=null && fast.next.next!=null){ - fast = fast.next.next; - slow = slow.next; - } - Node Sechead = slow.next; - slow.next = null; - Sechead = reverse(Sechead); - // compare two lists - Node First = Sechead; - Node Second = head; - while (First!=null){ - if (!First.data.equals(Second.data)){ - return false; - } - First = First.next; - Second = Second.next; - } - - //Now rejoin the two lists to its original form - First = head; - Second = reverse(Second); - while (First.next!=null){ - First = First.next; - } - First.next = Second; - return true; - - - - } -public static void main(String[] args) { - - - Node head = Input(); - System.out.println(isPalindrome(head)); -} - -} diff --git a/Coding_Ninjas/src/main/java/LinekedList1/Assignment/PrintReverseLinkedList.java b/Coding_Ninjas/src/main/java/LinekedList1/Assignment/PrintReverseLinkedList.java deleted file mode 100755 index a3b79c7..0000000 --- a/Coding_Ninjas/src/main/java/LinekedList1/Assignment/PrintReverseLinkedList.java +++ /dev/null @@ -1,46 +0,0 @@ -package LinekedList1.Assignment; - -public class PrintReverseLinkedList { - /* - You have been given a singly linked list of integers. Write a function to print the list in a reverse order. -To explain it further, you need to start printing the data from the tail and move towards the head of the list, printing the head data at the end. -Note : -You can’t change any of the pointers in the linked list, just print it in the reverse order. - Input format : -The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. - -The first and the only line of each test case or query contains the elements of the singly linked list separated by a single space. -Remember/Constraints : -While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element. -Output format : -For each test case, print the singly linked list of integers in a reverse fashion, in a row, separated by a single space. - -Output for every test case will be printed in a seperate line. - Constraints : -1 <= t <= 10^2 -0 <= M <= 10^3 -Time Limit: 1sec - -Where 'M' is the size of the singly linked list. -Sample Input 1 : -1 -1 2 3 4 5 -1 -Sample Output 1 : -5 4 3 2 1 -Sample Input 2 : -2 -1 2 3 -1 -10 20 30 40 50 -1 -Sample Output 2 : -3 2 1 -50 40 30 20 10 - */ - - public static void printReverse(Node root){ - if (root == null){ - return; - } - printReverse(root.next); - System.out.print(root.data+" "); - } -} diff --git a/Coding_Ninjas/src/main/java/LinekedList1/DeleteNode.java b/Coding_Ninjas/src/main/java/LinekedList1/DeleteNode.java deleted file mode 100755 index a7789ee..0000000 --- a/Coding_Ninjas/src/main/java/LinekedList1/DeleteNode.java +++ /dev/null @@ -1,81 +0,0 @@ -package LinekedList1; - -public class DeleteNode { - /* - You have been given a linked list of integers. Your task is to write a function that deletes a node from a given position, 'POS'. -Note : -Assume that the Indexing for the linked list always starts from 0. - -If the position is greater than or equal to the length of the linked list, you should return the same linked list without any change. -Illustration : -The following images depict how the deletion has been performed. -Image-I : -Alt txt -Image-II : -Alt txt -Input format : -The first line contains an Integer 'T' which denotes the number of test cases or queries to be run. Then the test cases follow. - -The first line of each test case or query contains the elements of the linked list separated by a single space. - -The second line of each test case contains the integer value of 'POS'. It denotes the position in the linked list from where the node has to be deleted. - Remember/Consider : -While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element -Output format : -For each test case/query, print the resulting linked list of integers in a row, separated by a single space. - -Output for every test case will be printed in a separate line. -Note: -You are not required to print the output, it has already been taken care of. Just implement the function. -Constraints : -1 <= T <= 10^2 -0 <= N <= 10^5 -POS >= 0 - -Time Limit: 1sec -Sample Input 1 : -1 -3 4 5 2 6 1 9 -1 -3 -Sample Output 1 : -3 4 5 6 1 9 -Sample Input 2 : -2 -3 4 5 2 6 1 9 -1 -0 -10 20 30 40 50 60 -1 -7 -Sample Output 2 : -4 5 2 6 1 9 -10 20 30 40 50 60 - */ - public static int length(Node head) { - int cnt = 0; - Node temp = head; - while (temp != null) { - temp = temp.next; - cnt++; - } - return cnt; - } - - public static Node Deletenode(Node head,int pos){ - if (head == null){ - return head; - } - if (pos>length(head)){ - return head; - } - if (pos == 0){ - return head.next; - } - Node curr = head,prev=null; - int i=1; - while (i<=pos){ - prev = curr; - curr = curr.next; - } - prev.next=curr.next; - return head; - } -} diff --git a/Coding_Ninjas/src/main/java/LinekedList1/InsertNode.java b/Coding_Ninjas/src/main/java/LinekedList1/InsertNode.java deleted file mode 100755 index e9b5953..0000000 --- a/Coding_Ninjas/src/main/java/LinekedList1/InsertNode.java +++ /dev/null @@ -1,77 +0,0 @@ -package LinekedList1; - -public class InsertNode { - /* - You have been given a singly linked list of integers, an integer value called 'data' and a - position with the name 'pos.' - Write a function to add a node to the list with the 'data' at the specified position, 'pos.' -Note : -Assume that the Indexing for the singly linked list always starts from 0. - -If the position is greater than the length of the singly linked list, you should return the same linked list without -any change. - Illustration : -The following images depict how the insertion has been taken place. -Image-I : -Alt txt -Image-II : -Alt txt -Image-III : -Alt txt -Image-IV : -Alt txt -Input format : -The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test -cases follow. - -The first line of each test case or query contains the elements of the linked list separated by a single space. - -The second line contains the two integer values of 'data' and 'pos' separated by a single space, respectively -Reminder/Consider : -While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would -never be a list element. -Output format : -For each test case, print the resulting singly linked list of integers in a row, separated by a single space. - -Output for every test case will be printed in a seperate line. - Constraints : -1 <= t <= 10^2 -0 <= N <= 10^5 -pos >= 0 -Time Limit: 1sec -Sample Input 1 : -1 -3 4 5 2 6 1 9 -1 -3 100 -Sample Output 1 : -3 4 5 100 2 6 1 9 -Sample Input 2 : -2 -3 4 5 2 6 1 9 -1 -0 20 -10 98 7 66 8 -1 -5 99 -Sample Output 2 : -20 3 4 5 2 6 1 9 -10 98 7 66 8 99 - */ - public static Node insert(Node head,int pos,int data){ - Node Chead = new Node<>(data); - if (pos==0){ - Chead.next = head; - return Chead; - }else { - int c=0; - Node prev = head; - while (c takeInput() throws IOException { - LinkedListNode head = null, tail = null; - - String[] datas = br.readLine().trim().split("\\s"); - - int i = 0; - while(i < datas.length && !datas[i].equals("-1")) { - int data = Integer.parseInt(datas[i]); - LinkedListNode newNode = new LinkedListNode(data); - if(head == null) { - head = newNode; - tail = newNode; - } - else { - tail.next = newNode; - tail = newNode; - } - i += 1; - } - - return head; - } - - public static void print(LinkedListNode head){ - while(head != null){ - System.out.print(head.data + " "); - head = head.next; - } - System.out.println(); - } - - public static int length(LinkedListNode head){ - int cnt=0; - LinkedListNode temp = head; - while (temp!=null){ - temp=temp.next; - cnt++; - } - return cnt; - } - public static void main(String[] args) throws NumberFormatException, IOException { - - int t = Integer.parseInt(br.readLine().trim()); - while (t > 0) { - - LinkedListNode head = takeInput(); - System.out.println(length(head)); - System.out.println(); - t -= 1; - } - } -} diff --git a/Coding_Ninjas/src/main/java/LinekedList1/LinkedListNode.java b/Coding_Ninjas/src/main/java/LinekedList1/LinkedListNode.java deleted file mode 100755 index a7dacdb..0000000 --- a/Coding_Ninjas/src/main/java/LinekedList1/LinkedListNode.java +++ /dev/null @@ -1,10 +0,0 @@ -package LinekedList1; - -public class LinkedListNode { - T data; - LinkedListNode next; - - public LinkedListNode(T data) { - this.data = data; - } -} diff --git a/Coding_Ninjas/src/main/java/LinekedList1/LinkedListUse.java b/Coding_Ninjas/src/main/java/LinekedList1/LinkedListUse.java deleted file mode 100755 index 91db698..0000000 --- a/Coding_Ninjas/src/main/java/LinekedList1/LinkedListUse.java +++ /dev/null @@ -1,31 +0,0 @@ -package LinekedList1; - -public class LinkedListUse { - - public static Node createLinkedList(){ - Node n1 = new Node(10); - Node n2 = new Node(20); - Node n3 = new Node(30); - Node n4 = new Node(40); - n1.next = n2; - n2.next = n3; - n3.next = n4; - return n1; - } - public static void PrintLinkedList(Node node){ - Node temp = node; - while (temp!=null){ - System.out.print(temp.data+" "); - temp = temp.next; - } - } - public static void main(String[] args) { - Node n1 = new Node(10); - System.out.println(n1.data); - System.out.println(n1); - System.out.println(n1.next); - - Node nn = createLinkedList(); - PrintLinkedList(nn); - } -} diff --git a/Coding_Ninjas/src/main/java/LinekedList1/Node.java b/Coding_Ninjas/src/main/java/LinekedList1/Node.java deleted file mode 100755 index 3242456..0000000 --- a/Coding_Ninjas/src/main/java/LinekedList1/Node.java +++ /dev/null @@ -1,10 +0,0 @@ -package LinekedList1; - -public class Node { - public T data; - public Node next; - public Node(T data){ - this.data = data; - - } -} diff --git a/Coding_Ninjas/src/main/java/LinekedList1/PrintithNode.java b/Coding_Ninjas/src/main/java/LinekedList1/PrintithNode.java deleted file mode 100755 index e3f11a9..0000000 --- a/Coding_Ninjas/src/main/java/LinekedList1/PrintithNode.java +++ /dev/null @@ -1,72 +0,0 @@ -package LinekedList1; - -public class PrintithNode { - /* - For a given a singly linked list of integers and a position 'i', print the node data at the 'i-th' position. - Note : -Assume that the Indexing for the singly linked list always starts from 0. - -If the given position 'i', is greater than the length of the given singly linked list, then don't print anything. -Input format : -The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. - -The first line of each test case or query contains the elements of the singly linked list separated by a single space. - -The second line contains the value of 'i'. It denotes the position in the given singly linked list. - Remember/Consider : -While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element. -Output format : -For each test case, print the node data at the 'i-th' position of the linked list(if exists). - -Output for every test case will be printed in a seperate line. - Constraints : -1 <= t <= 10^2 -0 <= N <= 10^5 -i >= 0 -Time Limit: 1sec -Sample Input 1 : -1 -3 4 5 2 6 1 9 -1 -3 -Sample Output 1 : -2 -Sample Input 2 : -2 -3 4 5 2 6 1 9 -1 -0 -9 8 4 0 7 8 -1 -3 -Sample Output 2 : -3 -0 - - */ - public static int length(LinkedListNode head){ - int count=0; - //LinkedListNode temp = head; - while(head!=null) { - count++; - head = head.next; - } - return count; - } - - public static void printIthNode(LinkedListNode head, int i){ - //Your code goes here - LinkedListNode temp = head; - int cnt=0; - int l = length(head); - if (i>l){ - return; - } - while (temp!=null){ - if (cnt==i){ - System.out.println(temp.data); - return; - } - temp=temp.next; - cnt++; - } - - } -} diff --git a/Coding_Ninjas/src/main/java/LinekedList1/RemoveDuplicateFromArray.java b/Coding_Ninjas/src/main/java/LinekedList1/RemoveDuplicateFromArray.java deleted file mode 100755 index 27e4201..0000000 --- a/Coding_Ninjas/src/main/java/LinekedList1/RemoveDuplicateFromArray.java +++ /dev/null @@ -1,25 +0,0 @@ -package LinekedList1; - -import java.util.ArrayList; - -public class RemoveDuplicateFromArray { - public static ArrayList removeconsecutiveElements(int[] arr){ - ArrayList res = new ArrayList(); - res.add(arr[0]); - for (int i=1;i< arr.length;i++){ - if (arr[i-1]!=arr[i]){ - res.add(arr[i]); - } - } - return res; - } - - public static void main(String[] args) { - int[] arr = {10,10,20,20,30,40,10}; - ArrayList ress = removeconsecutiveElements(arr); - for (int i=0;i Input(){ - Scanner s = new Scanner(System.in); - int data = s.nextInt(); - Node head = null,tail=null; - while (data!=-1){ - Node Chead = new Node<>(data); - if (head==null){ - head = Chead; - tail = Chead; - }else { - tail.next = Chead; - tail = Chead; - } - data =s.nextInt(); - } - return head; - } - - public static void main(String[] args) { - Node head = Input(); - LinkedListUse.PrintLinkedList(head); - } -} diff --git a/Coding_Ninjas/src/main/java/LinkedList2/Assignment/BubbleSort_LL.java b/Coding_Ninjas/src/main/java/LinkedList2/Assignment/BubbleSort_LL.java deleted file mode 100755 index 7368ee8..0000000 --- a/Coding_Ninjas/src/main/java/LinkedList2/Assignment/BubbleSort_LL.java +++ /dev/null @@ -1,85 +0,0 @@ -package LinkedList2.Assignment; - -public class BubbleSort_LL { - /* - - Given a singly linked list of integers, sort it using 'Bubble Sort.' -Note : -No need to print the list, it has already been taken care. Only return the new head to the list. -Input format : -The first and the only line of each test case or query contains the elements of the singly linked list separated by a single space. -Remember/Consider : -While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element -Output format : -For each test case/query, print the elements of the sorted singly linked list. - -Output for every test case will be printed in a seperate line. -Constraints : -0 <= M <= 10^3 -Where M is the size of the singly linked list. - -Time Limit: 1sec -Sample Input 1 : -10 9 8 7 6 5 4 3 -1 -Sample Output 1 : - 3 4 5 6 7 8 9 10 - Sample Output 2 : -10 -5 9 90 5 67 1 89 -1 -Sample Output 2 : --5 1 5 9 10 67 89 90 - - */ - - class LinkedListNode { - T data; - LinkedListNode next; - - public LinkedListNode(T data) { - this.data = data; - } - } - - public static int length(LinkedListNode head){ - int count=0; - while(head!=null){ - count++; - head=head.next; - } - return count; - } -// O(n^2) - public static LinkedListNode bubbleSort(LinkedListNode head) { - LinkedListNode orginalHead= head; - int n=length(head); - for(int i=0;i prev=null,curr=orginalHead; - for(int j=0;j curr2= curr.next; - LinkedListNode temp= curr2.next; - curr2.next= curr; - curr.next=temp; - prev=curr2; - orginalHead= curr2; - - } - else{ - LinkedListNode curr2= curr.next; - LinkedListNode temp= curr2.next; - prev.next=curr2; - curr2.next=curr; - curr.next=temp; - prev= curr2; - } - } - } - } - return orginalHead; - } -} diff --git a/Coding_Ninjas/src/main/java/LinkedList2/Assignment/DeleteEveryNnodes.java b/Coding_Ninjas/src/main/java/LinkedList2/Assignment/DeleteEveryNnodes.java deleted file mode 100755 index 004c6bb..0000000 --- a/Coding_Ninjas/src/main/java/LinkedList2/Assignment/DeleteEveryNnodes.java +++ /dev/null @@ -1,92 +0,0 @@ -package LinkedList2.Assignment; - -public class DeleteEveryNnodes { - /* - You have been given a singly linked list of integers along with two integers, 'M,' and 'N.' Traverse the linked list such that you retain the 'M' nodes, then delete the next 'N' nodes. Continue the same until the end of the linked list. -To put it in other words, in the given linked list, you need to delete N nodes after every M nodes. -Note : -No need to print the list, it has already been taken care. Only return the new head to the list. -Input format : -The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. - -The first line of each test case or query contains the elements of the singly linked list separated by a single space. - -The second line of input contains two integer values 'M,' and 'N,' respectively. A single space will separate them. - Remember/Consider : -While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element -Output format : -For each test case/query, print the elements of the updated singly linked list. - -Output for every test case will be printed in a seperate line. -Constraints : -1 <= t <= 10^2 -0 <= P <= 10^5 -Where P is the size of the singly linked list. -0 <= M <= 10^5 -0 <= N <= 10^5 - -Time Limit: 1sec -Sample Input 1 : -1 -1 2 3 4 5 6 7 8 -1 -2 2 -Sample Output 1 : -1 2 5 6 -Sample Input 2 : -2 -10 20 30 40 50 60 -1 -0 1 -1 2 3 4 5 6 7 8 -1 -2 3 -Sample Output 2 : -1 2 6 7 -Explanation of Sample Input 2 : -For the first query, we delete one node after every zero elements hence removing all the items of the list. Therefore, nothing got printed. - -For the second query, we delete three nodes after every two nodes, resulting in the final list, 1 -> 2 -> 6 -> 7. - - */ - class LinkedListNode { - T data; - LinkedListNode next; - - public LinkedListNode(T data) { - this.data = data; - } - } - - public static LinkedListNode skipMdeleteN(LinkedListNode head, int m, int n) { - //Your code goes here - if(head ==null || n ==0){ - return head; - } - if(m==0 ) { - return null; - } - - LinkedListNode orginal=head; - LinkedListNode temp1=head,temp2=head; - while(head!=null) { - temp1=head; - for(int i=1;i { - T data; - LinkedListNode next; - - public LinkedListNode(T data) { - this.data = data; - } - } - public static LinkedListNode evenAfterOdd(LinkedListNode head) { - //Your code goes here - if(head == null){ - return head; - } - LinkedListNode headOdd=null,tailOdd=null,headEven=null,tailEven=null; - while(head!=null) { - - if(head.data%2==0) { - - if(headEven==null) { - headEven=head; - tailEven=head; - }else { - tailEven.next=head; - tailEven=head; - } - - - } - else { - - if(headOdd==null) { - headOdd=head; - tailOdd=head; - }else { - tailOdd.next=head; - tailOdd=head; - } - - } - head=head.next; - - } - if(headOdd==null) { - return headEven; - } - if(headEven==null) { - return headOdd; - } - tailOdd.next=headEven; - tailEven.next=null; - return headOdd; - } -} diff --git a/Coding_Ninjas/src/main/java/LinkedList2/Assignment/FindaNoderecursively.java b/Coding_Ninjas/src/main/java/LinkedList2/Assignment/FindaNoderecursively.java deleted file mode 100755 index 4fa2bc6..0000000 --- a/Coding_Ninjas/src/main/java/LinkedList2/Assignment/FindaNoderecursively.java +++ /dev/null @@ -1,68 +0,0 @@ -package LinkedList2.Assignment; - -public class FindaNoderecursively { - /* - Given a singly linked list of integers and an integer n, find and return the index for the first occurrence of 'n' in the linked list. -1 otherwise. -Follow a recursive approach to solve this. -Note : -Assume that the Indexing for the linked list always starts from 0. - Input format : -The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. - -The first line of each test case or query contains the elements of the singly linked list separated by a single space. - -The second line of input contains a single integer depicting the value of 'n'. -Remember/Consider : -While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element - Output format : -For each test case/query, print the elements of the updated singly linked list. - -Output for every test case will be printed in a seperate line. - Constraints : -1 <= t <= 10^2 -0 <= M <= 10^5 -Where M is the size of the singly linked list. - -Time Limit: 1sec -Sample Input 1 : -1 -3 4 5 2 6 1 9 -1 -100 -Sample Output 1 : --1 -Sample Input 2 : -2 -10 20010 30 400 600 -1 -20010 -100 200 300 400 9000 -34 -1 --34 -Sample Output 2 : -1 -5 - */ - class LinkedListNode { - T data; - LinkedListNode next; - - public LinkedListNode(T data) { - this.data = data; - } - } - - public static int findNodeRec(LinkedListNode head, int n) { - //Your code goes here - if (head == null){ - return -1; - } - if (head.data == n){ - return 0; - } - int count = findNodeRec(head.next,n); - if (count == -1){ - return -1; - } - return 1 + count; - } - -} - diff --git a/Coding_Ninjas/src/main/java/LinkedList2/Assignment/KReverse.java b/Coding_Ninjas/src/main/java/LinkedList2/Assignment/KReverse.java deleted file mode 100755 index b36b2dc..0000000 --- a/Coding_Ninjas/src/main/java/LinkedList2/Assignment/KReverse.java +++ /dev/null @@ -1,80 +0,0 @@ -package LinkedList2.Assignment; - -public class KReverse { - /* - Given a singly linked list of integers, reverse the nodes of the linked list 'k' at a time and return its modified list. - 'k' is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of 'k,' then left-out nodes, in the end, should be reversed as well. -Example : -Given this linked list: 1 -> 2 -> 3 -> 4 -> 5 - -For k = 2, you should return: 2 -> 1 -> 4 -> 3 -> 5 - -For k = 3, you should return: 3 -> 2 -> 1 -> 5 -> 4 - Note : -No need to print the list, it has already been taken care. Only return the new head to the list. - Input format : -The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. - -The first line of each test case or query contains the elements of the singly linked list separated by a single space. - -The second line of input contains a single integer depicting the value of 'k'. - Remember/Consider : -While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element -Output format : -For each test case/query, print the elements of the updated singly linked list. - -Output for every test case will be printed in a separate line. -Constraints : -1 <= t <= 10^2 -0 <= M <= 10^5 -Where M is the size of the singly linked list. -0 <= k <= M - -Time Limit: 1sec -Sample Input 1 : -1 -1 2 3 4 5 6 7 8 9 10 -1 -4 -Sample Output 1 : -4 3 2 1 8 7 6 5 10 9 -Sample Input 2 : -2 -1 2 3 4 5 -1 -0 -10 20 30 40 -1 -4 -Sample Output 2 : -1 2 3 4 5 -40 30 20 10 - */ -class LinkedListNode { - T data; - LinkedListNode next; - - public LinkedListNode(T data) { - this.data = data; - } - } - - -// Time Complexity - O(n) - // Space Complexity - O(n/k) - public static LinkedListNode kReverse(LinkedListNode head, int k) { - if (k==0 || k ==1){ - return head; - } - LinkedListNode Current =head; - LinkedListNode prev=null,frwd = null; - int cnt =0; - while (cnt { - T data; - LinkedListNode next; - - public LinkedListNode(T data) { - this.data = data; - } - } - - public static LinkedListNode swapNodes(LinkedListNode head, int I, int J) { - if(head == null){ - return head; - } - LinkedListNode prev1=null,curr1=head,curr2=head,prev2=null; - - for(int i=1;i<=I;i++){ - prev1=curr1; - curr1=curr1.next; - } - for(int i=1;i<=J;i++){ - prev2=curr2; - curr2=curr2.next; - } - if(prev1==null){ - head=curr2; - } - else{ - prev1.next=curr2; - } - - LinkedListNode temp=curr2.next; - if(prev2!=curr1) - curr2.next=curr1.next; - else - curr2.next=curr1; - if(prev2==null){ - head=curr1; - } - else{ - prev2.next=curr1; - } - curr1.next=temp; - return head; - - } -} diff --git a/Coding_Ninjas/src/main/java/LinkedList2/DeleteNodeRecursively.java b/Coding_Ninjas/src/main/java/LinkedList2/DeleteNodeRecursively.java deleted file mode 100755 index 7ab96e5..0000000 --- a/Coding_Ninjas/src/main/java/LinkedList2/DeleteNodeRecursively.java +++ /dev/null @@ -1,62 +0,0 @@ -package LinkedList2; - -public class DeleteNodeRecursively { -/* -Given a singly linked list of integers and position 'i', delete the node present at the 'i-th' position in the linked list recursively. - Note : -Assume that the Indexing for the linked list always starts from 0. - -No need to print the list, it has already been taken care. Only return the new head to the list. - input format : -The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. - -The first line of each test case or query contains the elements of the singly linked list separated by a single space. - -The second line of input contains a single integer depicting the value of 'i'. -Remember/Consider : -While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element -Output format : -For each test case/query, print the elements of the updated singly linked list. - -Output for every test case will be printed in a seperate line. -Constraints : -1 <= t <= 10^2 -0 <= M <= 10^5 -Where M is the size of the singly linked list. -0 <= i < M - -Time Limit: 1sec -Sample Input 1 : -1 -3 4 5 2 6 1 9 -1 -3 -Sample Output 1 : -3 4 5 6 1 9 -Sample Input 2 : -2 -30 -1 -0 -10 20 30 50 60 -1 -4 -Sample Output 2 : -10 20 30 50 - - */ - public static Node DeleteR(Node head,int pos){ - if (head == null){ - return head; - } - if (pos == 0){ - return head.next; - }else { - head.next = DeleteR(head.next,pos-1); - return head; - } - } - - public static void main(String[] args) { - Node head = PrintRecursion.Input(); - head = DeleteR(head,3); - PrintRecursion.printR(head); - } -} diff --git a/Coding_Ninjas/src/main/java/LinkedList2/InsertR.java b/Coding_Ninjas/src/main/java/LinkedList2/InsertR.java deleted file mode 100755 index 2311960..0000000 --- a/Coding_Ninjas/src/main/java/LinkedList2/InsertR.java +++ /dev/null @@ -1,18 +0,0 @@ -package LinkedList2; - -public class InsertR { - - public static Node insertRecursive(Node head,int pos,int data){ - if (head == null && pos>0){ - return head; - } - if (pos == 0){ - Node newNode = new Node<>(data); - newNode.next = head; - return newNode; - }else { - head.next = insertRecursive(head.next,pos-1,data); - return head; - } - } -} diff --git a/Coding_Ninjas/src/main/java/LinkedList2/MergeTwoSortedLL.java b/Coding_Ninjas/src/main/java/LinkedList2/MergeTwoSortedLL.java deleted file mode 100755 index 193fb49..0000000 --- a/Coding_Ninjas/src/main/java/LinkedList2/MergeTwoSortedLL.java +++ /dev/null @@ -1,88 +0,0 @@ -package LinkedList2; - -public class MergeTwoSortedLL { - /* - You have been given two sorted(in ascending order) singly linked lists of integers. -Write a function to merge them in such a way that the resulting singly linked list is also sorted(in ascending order) and return the new head to the list. -Note : -Try solving this in O(1) auxiliary space. - -No need to print the list, it has already been taken care. -Input format : -The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. - -The first line of each test case or query contains the elements of the first sorted singly linked list separated by a single space. - -The second line of the input contains the elements of the second sorted singly linked list separated by a single space. -Remember/Consider : -While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element -Output : -For each test case/query, print the resulting sorted singly linked list, separated by a single space. - -Output for every test case will be printed in a seperate line. -Constraints : -1 <= t = 10^2 -0 <= N <= 10 ^ 4 -0 <= M <= 10 ^ 4 -Where N and M denote the sizes of the singly linked lists. - -Time Limit: 1sec -Sample Input 1 : -1 -2 5 8 12 -1 -3 6 9 -1 -Sample Output 1 : -2 3 5 6 8 9 12 -Sample Input 2 : -2 -2 5 8 12 -1 -3 6 9 -1 -10 40 60 60 80 -1 -10 20 30 40 50 60 90 100 -1 -Sample Output 2 : -2 3 5 6 8 9 12 -10 10 20 30 40 40 50 60 60 60 80 90 100 - */ - public static Node mergeTwoSortedLinkedLists(Node head1, Node head2) { - //Your code goes here - Node head =null,tail =null; - if(head1 == null && head2 == null){ - return head; - } - if (head1 !=null && head2 == null){ - return head1; - } - if (head2!=null && head1 == null){ - return head2; - } - while (head1!=null && head2!=null){ - if(head1.data<=head2.data){ - if (head == null){ - head =head1; - tail = head; - }else { - tail.next = head1; - tail = head1; - } - head1 = head1.next; - }else { - if (head == null){ - head = head2; - tail = head2; - }else { - tail.next = head2; - tail = head2; - } - head2 = head2.next; - } - } - - if (head1 == null){ - tail.next = head2; - } - if (head2 == null){ - tail.next = head1; - } - return head; - } -} diff --git a/Coding_Ninjas/src/main/java/LinkedList2/PrintRecursion.java b/Coding_Ninjas/src/main/java/LinkedList2/PrintRecursion.java deleted file mode 100755 index 8c89e17..0000000 --- a/Coding_Ninjas/src/main/java/LinkedList2/PrintRecursion.java +++ /dev/null @@ -1,46 +0,0 @@ -package LinkedList2; - - -import java.util.Scanner; - class Node{ - T data; - Node next; - Node(T data){ - this.data= data; - } -} -public class PrintRecursion { - - public static Node Input(){ - Scanner s = new Scanner(System.in); - int data = s.nextInt(); - Node head = null,tail=null; - while (data!=-1){ - Node Chead = new Node<>(data); - if (head==null){ - head = Chead; - }else { - tail.next = Chead; - } - tail = Chead; - data =s.nextInt(); - } - s.close(); - return head; - } - public static void printR(Node head){ - if (head == null){ - return; - } - System.out.print(head.data+ " "); - printR(head.next); - // if u want reverse right the print statement after recursion - - } - - public static void main(String[] args) { - Node head = Input(); - printR(head); - } - -} diff --git a/Coding_Ninjas/src/main/java/MAXIMUMSUBAARRAY.java b/Coding_Ninjas/src/main/java/MAXIMUMSUBAARRAY.java deleted file mode 100755 index 5185d12..0000000 --- a/Coding_Ninjas/src/main/java/MAXIMUMSUBAARRAY.java +++ /dev/null @@ -1,48 +0,0 @@ -import java.util.Scanner; - -public class MAXIMUMSUBAARRAY { - /* - This problem was asked by Amazon. -Given an array of numbers, find the maximum sum of any contiguous subarray of the array. -For example, given the array [34, -50, 42, 14, -5, 86], the maximum sum would be 137, since we would take elements 42, 14, -5, and 86. -Given the array [-5, -1, -8, -9], the maximum sum would be -1. -Follow up: Do this in O(N) time. -Input Format: -The first line of input contains size of array, which is denoted by N and second line of input contains N space separated integers. -Output Format: -The first and only line of output should print the maximum subarray sum, as described in the description. - */ - 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;i0){ - int i = 1,j=n; - while (j > 0) { - if (i<=temp){ - System.out.print(i); - i++; - } - j--; - } - int star=1; - while (star<=numstar){ - System.out.print("*"); - star++; - } - int k=n,l=n; - while(k>0){ - if (k<=temp){ - System.out.print(k); - } - k--; - } - System.out.println(); - temp--; - numstar+=2; - } - } -} diff --git a/Coding_Ninjas/src/main/java/OneStrings.java b/Coding_Ninjas/src/main/java/OneStrings.java deleted file mode 100755 index 6301d27..0000000 --- a/Coding_Ninjas/src/main/java/OneStrings.java +++ /dev/null @@ -1,77 +0,0 @@ -public class OneStrings { - /* - You are given a binary string ‘STR’, containing only zeroes and ones. -Your task is to determine the total number of substrings having only ones. -Input Format: -The first line contains an integer ‘T’, which denotes the number of test cases to be run. Then, the T test cases follow. - -The first line of each test case contains a single string, 'STR', -Output Format: -For each test case, print a single line containing a single integer, denoting the total number of substrings containing only ones. - -The output for each test case will be printed in a separate line. -Note: -You do not need to print anything. It has already been taken care of. Just implement the given function. -Constraints: -1 <= T <= 10 -1 <= |STR| <= 10 ^ 5 - -Where ‘T’ denotes the number of test cases and |STR| represents the total length of the string, ‘STR’. - -Time Limit: 1 sec. -Sample Input 1: -1 -1101 -Sample Output 1: -4 -Explanation for sample input 1: -In the given test case, there are 3 required substrings of length 1, at indices, 0, 1, and 3. There is also a required substring of length 2 starting at index 0. -So, there are a total of 4 substrings having only ones. -Sample Input 2: -1 -111 -Sample Output 2: -6 -Explanation for sample input 2: -In the given test case, there are 3 required substrings of length 1, at indices, 0, 1, and 2. There are 2 required substrings of length 2, starting at indices, 0 and 1. There is also a required substring of length 3 starting at index 0. -So, there are a total of 6 substrings containing only ones. - */ - static int findOneStrings(String str) { - int res = 0, count = 0; - for(int i = 0; i < str.length(); i++) { - count = str.charAt(i) == '1' ? count + 1 : 0; - res = (res + count); - } - return res; - } - - // Driver code -// public static void main(String[] args) -// { -// String s = "1011"; -// -// System.out.println(findOneStrings(s)); -// } - public static void main(String[] args) - { - Test object = new Test(); - } - -} -class Test - { - int a; - int b; - Test() - { - this(10, 20); - System.out.print("constructor one "); - } - Test(int a, int b) - { - this.a = a; - this.b = b; - System.out.print("constructor two "); - } - } - diff --git a/Coding_Ninjas/src/main/java/Set1/AllPossibleways.java b/Coding_Ninjas/src/main/java/Set1/AllPossibleways.java deleted file mode 100755 index 8092a38..0000000 --- a/Coding_Ninjas/src/main/java/Set1/AllPossibleways.java +++ /dev/null @@ -1,26 +0,0 @@ -package Set1; - -public class AllPossibleways { - static int cnt = 0; - - static int Allways(int num, int x, int k, int n) { - if (x == 0) cnt++; - int l = (int) Math.floor(Math.pow(num, 1.0 / n)); - - for (int i = k + 1; i <= l; i++) { - int a = x - (int) Math.pow(i, n); - if (a >= 0) - Allways(num, x - (int) Math.pow(i, n), i, n); - } - return cnt; - } - - // Wrapper over checkRecursive() - static int allWays(int x, int n) { - return Allways(x, x, 0, n); - } - - public static void main(String[] args) { - System.out.println(allWays(100, 2)); - } -} diff --git a/Coding_Ninjas/src/main/java/Set1/BinaryPlay.java b/Coding_Ninjas/src/main/java/Set1/BinaryPlay.java deleted file mode 100755 index 947d2be..0000000 --- a/Coding_Ninjas/src/main/java/Set1/BinaryPlay.java +++ /dev/null @@ -1,40 +0,0 @@ -package Set1; - -public class BinaryPlay { - static public int binarySequence(int N, int X) { - String str1 = "0"; - String str2 = "0"; - for (int j = 0; j < N-1; j++) { - for (int i = 0; i < str1.length(); i++) { - if(str1.charAt(i)=='0') str2+='1'; - if(str1.charAt(i)=='1') str2+='0'; - } - str1= str2; - System.out.println(str1); - - if(str1.length()>=X){ - break; - } - // System.out.println(a); - } - return str1.charAt(X-1)-'0'; -// String str1 = "0", str2="0"; -// int a = str1.length(); -// int i=0; -// while(i=X) break; -// } -// return str1.charAt(X-1)-'0'; - } - public static void main(String[] args) { - System.out.println(binarySequence(4, 5)); - } -} diff --git a/Coding_Ninjas/src/main/java/Set1/Power.java b/Coding_Ninjas/src/main/java/Set1/Power.java deleted file mode 100755 index 5ceb38b..0000000 --- a/Coding_Ninjas/src/main/java/Set1/Power.java +++ /dev/null @@ -1,57 +0,0 @@ -package Set1; - -import java.util.Scanner; - -public class Power { -// public static int Power(int a, int[] b){ -// -// int l = b.length; -// int mod = 1337; -// int[] pwr = new int[l]; -// pwr[l-1] = a%mod; -// for(int i=l-2; i>=0; i--){ -// pwr[i] = power(pwr[i+1],10,mod); -// } -// int res = 1; -// for(int i=0; i> quadruplets(int[] nums, int x) - { - int l = nums.length; - HashMap map = new HashMap<>(); - List> newList = new ArrayList<>(); - for(int i=0;i sorted = sort(nums[i],nums[j],nums[k],nums[m]); - if(map.containsKey(sorted.toString())) continue; - else{ - newList.add(sorted); - map.put(sorted.toString(),true); - } - } - } - } - } - } - return newList; - } - - static List sort(int i,int j,int k,int m){ - List ll = new ArrayList<>(); - int[] arr = {i,j,k,m}; - Arrays.sort(arr); - for(int x=0;x> answer = quadruplets(arr, x); - - for (int p = 0; p < answer.size(); p++) - { - for (int q = 0; q < 4; q++) - { - System.out.print(answer.get(p).get(q) + " "); - } - System.out.println(); - } - } -} diff --git a/Coding_Ninjas/src/main/java/Set1/Set3/BinaryConswithout1s.java b/Coding_Ninjas/src/main/java/Set1/Set3/BinaryConswithout1s.java deleted file mode 100755 index dab2eb3..0000000 --- a/Coding_Ninjas/src/main/java/Set1/Set3/BinaryConswithout1s.java +++ /dev/null @@ -1,105 +0,0 @@ -package Set1.Set3; - -import java.util.Scanner; - -public class BinaryConswithout1s { -/* -You have been given an integer K. -Your task is to generate all binary strings of length K such that there are no consecutive 1s in the string. This means that the binary string should not contain any instance of 1’s coming one after another. -A binary string is that string which contains only ‘0’ and ‘1’. -For Example: -Let ‘K=3’, hence the length of the binary string would be 3. We can have the following binary strings with no consecutive 1s: -000 001 010 100 101 -Note -1. Each string must be a binary string. -2. There should be no consecutive ‘1’ in the string. -3. Return an array/sequence of all the strings in an array in a lexicographically increasing order. -Input format: -The first line of input contains ‘T’ the number of test cases. - -The first and only line of each test case contains a single integer K denoting the length of the binary string to be generated. -Output Format -For each test case, print all possible binary strings without consecutive ‘1’ of the length K in lexicographically increasing order. -Note: -You don't need to print anything; it has already been taken care of. Just implement the given function. -Constraints: -1 <= T <= 10 -0 <= K <= 22 - -Time limit: 1 second -Sample Input 1: -2 -4 -3 -Sample Output 1: -0000 0001 0010 0100 0101 1000 1001 1010 -000 001 010 100 101 -Explanation of sample input 1: -Test case 1: - -For K = 4 we get the following Strings: - -0000 0001 0010 0100 0101 1000 1001 1010 - -Note that none of the strings has consecutive 1s. Also, note that they are in a lexicographically increasing order. - -Test case 2: - -We can see that for K = 3 we get the following Strings: - -000 001 010 100 101 - -Note that none of the strings has consecutive 1s. Also, note that they are in a lexicographically increasing order. -Sample Input 2: -2 -2 -5 -Sample Output 2: -00 01 10 -00000 00001 00010 00100 00101 01000 01001 01010 10000 10001 10010 10100 10101 - */ - static void strings_form(int k, char s[], int n) - { - if(n==k) - { - s[n]='\0'; - System.out.print(s); - System.out.print(" "); - return; - } - if(s[n-1]=='1') - { - s[n]='0'; - strings_form(k,s,n+1); - } - if(s[n-1]=='0') - { - s[n]='0'; - strings_form(k,s,n+1); - s[n]='1'; - strings_form(k,s,n+1); - } - } - static void print_strings(int n) { - if(n<=0) - { - return; - } - char s[] = new char[n+1]; - s[0]= '0'; - strings_form(n,s,1); - s[0]= '1'; - strings_form(n,s,1); - } - public static void main(String[] args) - { - Scanner sr= new Scanner(System.in); - int n = sr.nextInt(); - print_strings(n); - } - /* - public static ArrayList generateString(int k) { - // Write your code here. - } - */ -} diff --git a/Coding_Ninjas/src/main/java/Set1/Set3/ModuloProduct.java b/Coding_Ninjas/src/main/java/Set1/Set3/ModuloProduct.java deleted file mode 100755 index 7acbf28..0000000 --- a/Coding_Ninjas/src/main/java/Set1/Set3/ModuloProduct.java +++ /dev/null @@ -1,62 +0,0 @@ -package Set1.Set3; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -public class ModuloProduct { - /* - Ninja got an easy assignment from his professor but he is unable to solve this. So he needs your help to complete the assignment. -In the assignment, he is given two integers A and B and he needs to output the product of all numbers from 1 to A modulo B, where 1 and A are inclusive. -For example, if A=5 and B=7, the answer will be ( 1 * 2 * 3 * 4 * 5 ) % 7 = 1 so the final answer is 1. -Input format: -The first line of input will contain an integer T, that denote the number of test cases. -Every test case will consist of one single line and that line will contain two integers: A and B. -Constraints: -1<=T<=50 -1<=A<=10^9 -1<=B<=10^5 -Time Limit: 1 second -Output format: -For every test case, print the output in a newline. -Sample Input 1 -4 -8 10 -5 140 -18 19 -20 21 -Sample Output 1: -0 -120 -18 -0 - - */ - public static void main(String[] args) throws IOException,NumberFormatException{ - BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); - //Scanner s = new Scanner(System.in); -// int n=Integer.parseInt(br.readLine()); - int n =Integer.parseInt(br.readLine().trim()); - while (n>0) { - int arr[] = new int[2]; - String[] strNums; - strNums = br.readLine().split("\\s"); - for (int i = 0; i < arr.length; i++) { - arr[i] = Integer.parseInt(strNums[i]); - } - int a = arr[0]; - int b = arr[1]; - long prd = 1; - if (a>=b){ - prd=0; - System.out.println(prd); - continue; - } - for (int i=1;i<=a;i++){ - prd=(prd* i)% b; - } - System.out.println(prd); - } - n--; - } -} diff --git a/Coding_Ninjas/src/main/java/Set1/Set3/roomarrangements.java b/Coding_Ninjas/src/main/java/Set1/Set3/roomarrangements.java deleted file mode 100755 index fcebe2b..0000000 --- a/Coding_Ninjas/src/main/java/Set1/Set3/roomarrangements.java +++ /dev/null @@ -1,38 +0,0 @@ -package Set1.Set3; -/* -This year politicians and economists have been invited to participate in Stanford Institute for Theoretical Economics (SITE 2021) conference as guests. You have to accommodate them in r rooms such that- -No room may remain empty. -A room may contain either only politicians or only economists, not both. -No economists are allowed to stay alone in a room. -Find the number of ways to place them. Note though, that all the rooms are identical. But each of the economists and politicians are unique. -Since the number of ways can be very large, print the answer modulo 998,244,353. -Input Format: -The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. -The first and only line of each test case contains three space-separated integers p, q and r denoting the number of politicians, economists and rooms. -Output Format: -For each test case, output the number of ways to place them modulo 998,244,353. -Constraints -1≤T≤100 -1≤p,q,r≤100 -Sample Input: -4 -2 1 4 -2 4 4 -2 5 4 -2 8 4 -Sample Output: -0 -3 -10 -609 -Explanation: - Test case 1: 4 rooms and 3 people. A room would remain empty. - Test case 2: There are 4 rooms and 6 people. There are 3 possible ways to distribute these 6 people in 3 rooms. - -{Politician 1}, {Politician 2}, {Economist 1, Economist 2}, {Economist 3, Economist 4} -{Politician 1}, {Politician 2}, {Economist 1, Economist 3}, {Economist 2, Economist 4} -{Politician 1}, {Politician 2}, {Economist 1, Economist 4}, {Economist 2, Economist 3} - Please note that the rooms are identical. - */ -public class roomarrangements { -} diff --git a/Coding_Ninjas/src/main/java/Set1/Test2/FindM.java b/Coding_Ninjas/src/main/java/Set1/Test2/FindM.java deleted file mode 100755 index d747b9b..0000000 --- a/Coding_Ninjas/src/main/java/Set1/Test2/FindM.java +++ /dev/null @@ -1,32 +0,0 @@ -package Set1.Test2; - -import java.util.Scanner; - -public class FindM { - public static void main(String[] args) { - Scanner s = new Scanner(System.in); - int matrixRow = s.nextInt(); - String[] input = new String[matrixRow]; - for(int i=0;i= R || rd < 0 || cd >= C || cd < 0) - break; - - // If not matched, break - if (grid[rd][cd] != word.charAt(k)) - break; - - // Moving in particular direction - rd += x[dir]; - cd += y[dir]; - } - - // If all character matched, then value of must - // be equal to length of word - if (k == len) - return true; - } - return false; - } - - // Searches given word in a given - // matrix in all 8 directions - static int findPath(char[][] grid, String word) { - int cnt=0; - // Consider every point as starting - // point and search given word - for (int row = 0; row < R; row++) - { - for (int col = 0; col < C; col++) - { - if (search2D(grid, row, col, word)) { - System.out.println("pattern found at " + row + ", " + col); - cnt++; - } - } - } - return cnt; - } - - // Driver code - static Scanner s = new Scanner(System.in); - - public static void main(String[] args) { - int matrixRow = s.nextInt(); - String[] input = new String[matrixRow]; - for(int i=0;i path, int M, int N) { -// return (next.x >= 0 && next.x < M) && (next.y >= 0 && next.y < N) && -// !path.contains(next); -// } -// static int cnt=0; -// public static void DFS(char[][] mat, String word, Node next, -// List path, int index) { -// int i = next.x; -// int j = next.y; -// if (mat[i][j] != word.charAt(index)) { -// return; -// } -// path.add(Node.of(i, j)); -// if (index == word.length() - 1) { -// cnt++; -//// System.out.println(path); -// } else { -// for (int k = 0; k < row.length; k++) { -// next = Node.of(i + row[k], j + col[k]); -// if (isValid(next, path, mat.length, mat[0].length)) { -// DFS(mat, word, next, path, index + 1); -// } -// } -// } -// path.remove(path.size() - 1); -// } -// -// public static int findAllOccurences(char[][] mat, String word) { -// // base case -// if (mat == null || mat.length == 0 || word == null) { -// return cnt; -// } -// -// List path = new ArrayList<>(); -// for (int i = 0; i < mat.length; i++) { -// for (int j = 0; j < mat[0].length; j++) { -// DFS(mat, word, Node.of(i, j), path, 0); -// } -// } -// return cnt; -// } -// -// public static void main(String[] args) -// { -//// char mat[][] = -//// { -//// "DEMXB".toCharArray(), -//// "AOEPE".toCharArray(), -//// "DDCOD".toCharArray(), -//// "EBEDS".toCharArray(), -//// "CPYEN".toCharArray() -//// -//// }; -//// -// String word = "to"; -// Scanner s = new Scanner(System.in); -// int matrixRow = s.nextInt(); -// String[] input = new String[matrixRow]; -// for(int i=0;i= '0' && c <= '9'); - - if (neg) - return -ret; - return ret; - } - - public long nextLong() throws IOException - { - long ret = 0; - byte c = read(); - while (c <= ' ') - c = read(); - boolean neg = (c == '-'); - if (neg) - c = read(); - do { - ret = ret * 10 + c - '0'; - } - while ((c = read()) >= '0' && c <= '9'); - if (neg) - return -ret; - return ret; - } - - public double nextDouble() throws IOException - { - double ret = 0, div = 1; - byte c = read(); - while (c <= ' ') - c = read(); - boolean neg = (c == '-'); - if (neg) - c = read(); - - do { - ret = ret * 10 + c - '0'; - } - while ((c = read()) >= '0' && c <= '9'); - - if (c == '.') - { - while ((c = read()) >= '0' && c <= '9') - { - ret += (c - '0') / (div *= 10); - } - } - - if (neg) - return -ret; - return ret; - } - - private void fillBuffer() throws IOException - { - bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); - if (bytesRead == -1) - buffer[0] = -1; - } - - private byte read() throws IOException - { - if (bufferPointer == bytesRead) - fillBuffer(); - return buffer[bufferPointer++]; - } - - public void close() throws IOException - { - if (din == null) - return; - din.close(); - } - } - - public static class Item implements Comparable { - int l, r; - @Override public int compareTo(Item item) { - if (this.r < item.r) { - return -1; - } else if (this.r > item.r) { - return 1; - } else { - return 0; - } - } - } - - static int bit[][], n; - - static void update(int idx, char ch) { - for (; idx <= n; idx += (idx & -idx)) { - ++bit[idx][ch - 'a']; - } - } - - static int[] read(int idx) { - int temp[] = new int[26]; - for (; idx > 0; idx -= (idx & -idx)) { - for (int i = 0; i < 26; ++i) { - temp[i] += bit[idx][i]; - } - } - return temp; - } - - public static void main(String args[]) throws IOException { - Reader rd = new Reader(); - BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); - int q, l, r, i, oddCount; - char arr[] = rd.readLine().toCharArray(); - q = rd.nextInt(); - n = arr.length; - bit = new int[n + 1][26]; - for (i = 1; i <= n; ++i) { - update(i, arr[i - 1]); - } - while (--q >= 0) { - l = rd.nextInt(); - r = rd.nextInt(); - int left[] = read(l - 1); - int right[] = read(r); - for (i = oddCount = 0; i < 26; ++i) { - right[i] -= left[i]; - if ((right[i] & 1) != 0) { - ++oddCount; - } - } - if (oddCount <= 1) { - bw.write("Yes\n"); - } else { - bw.write("No\n"); - } - - } - bw.close(); - } -} diff --git a/Coding_Ninjas/src/main/java/Set1/Test2/Solution.java b/Coding_Ninjas/src/main/java/Set1/Test2/Solution.java deleted file mode 100755 index fdf5666..0000000 --- a/Coding_Ninjas/src/main/java/Set1/Test2/Solution.java +++ /dev/null @@ -1,95 +0,0 @@ -package Set1.Test2; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.Scanner; - -class Node -{ - public int x, y; - - private Node(int x, int y) { - this.x = x; - this.y = y; - } - - public static Node of(int x, int y) { - return new Node(x, y); - } - - @Override - public boolean equals(Object o) { - Node node = (Node) o; - return x == node.x && y == node.y; - } - - @Override - public int hashCode() { - return Objects.hash(x, y); - } - - @Override - public String toString() { - return ("(" + x + ", " + y + ")"); - } -} -public class Solution { - private static final int[] row = { -1, 0, 0, 1 }; - private static final int[] col = { 0,-1, 1, 0 }; - static int cnt=0; - public static boolean isValid(Node next, List path, int M, int N) { - return (next.x >= 0 && next.x < M) && (next.y >= 0 && next.y < N) && - !path.contains(next); - } - public static void DFS(char[][] mat, String word, Node next, List path, int index) { - int i = next.x; - int j = next.y; - if (mat[i][j] != word.charAt(index)) { - return; - } - path.add(Node.of(i, j)); - if (index == word.length() - 1) { - cnt++; - System.out.println(path); - } else { - for (int k = 0; k < row.length; k++) { - next = Node.of(i + row[k], j + col[k]); - if (isValid(next, path, mat.length, mat[0].length)) { - DFS(mat, word, next, path, index + 1); - } - } - } - path.remove(path.size() - 1); - } - public static int findPath(char[][] inputMatrix, String target) { - if (inputMatrix == null || inputMatrix.length == 0 || target == null) { - return cnt; - } - - List path = new ArrayList<>(); - for (int i = 0; i < inputMatrix.length; i++) { - for (int j = 0; j < inputMatrix[0].length; j++) { - DFS(inputMatrix, target, Node.of(i, j), path, 0); - } - } - return cnt; - } - static Scanner s = new Scanner(System.in); - - public static void main(String[] args) { - int matrixRow = s.nextInt(); - String[] input = new String[matrixRow]; - for(int i=0;i= nrow || y >= ncol) - return cnt; - - // If grid matches with a letter while - // recursion - if (mat[x][y] == pat.charAt(level)) - { - - // Marking this cell as visited - char temp = mat[x][y]; - mat[x][y] = '#'; - - // finding subpattern in 4 directions - int res = findmatch(mat, pat, x - 1, y, nrow, ncol, level + 1) | - findmatch(mat, pat, x + 1, y, nrow, ncol, level + 1) | - findmatch(mat, pat, x, y - 1, nrow, ncol, level + 1) | - findmatch(mat, pat, x, y + 1, nrow, ncol, level + 1); - - // marking this cell - // as unvisited again - mat[x][y] = temp; - return res; - } - else // Not matching then false - return cnt; - } - - // Function to check if the word exists in the grid or not - static int checkMatch(char mat[][], String pat, int nrow, int ncol) - { - int cnt=0; - int l = pat.length(); - - // if total characters in matrix is - // less then pattern lenghth - if (l > nrow * ncol) - return cnt; - - // Traverse in the grid - for (int i = 0; i < nrow; i++) - { - for (int j = 0; j < ncol; j++) - { - - // If first letter matches, then recur and check - if (mat[i][j] == pat.charAt(0)) { - int cc = findmatch(mat, pat, i, j, nrow, ncol, 0); - cnt+=cc; - } - } - } - return cnt; - } - - // Driver Code - - } - public static void main(String[] args) { - Scanner s = new Scanner(System.in); - int matrixRow = s.nextInt(); - String[] input = new String[matrixRow]; - for(int i=0;i0){ - System.out.println(pfr(str, s.nextInt(), s.nextInt())); - n--; - } -// String ss = "heleltronrocop"; -// int a=1,b=3; -// String st=""; -// for (int j=a;j<=b;j++){ -// st+= ss.charAt(j); -// } -// System.out.println(st); - } - static String pfr(String word,int a,int b){ - String st =newString(word,a,b); - char[] ch = st.toCharArray(); - int len = ch.length; - if (len%2 == 0){ - int c = len/2; - int sum=0,sum1=0; - for (int i=0;i 0) { - int n = s.nextInt(); - - ArrayList res = generateString(n); - for (String i : res) { - System.out.print(i + " "); - } - System.out.println(); - } - } - public static void generateStringHelper(int k, char str[], int n, ArrayList ans) { - if (n == k) { - ans.add(new String(str)); - return; - } - if (str[n - 1] == '1') { - str[n] = '0'; - generateStringHelper(k, str, n + 1, ans); - } - if (str[n - 1] == '0') { - str[n] = '0'; - generateStringHelper(k, str, n + 1, ans); - str[n] = '1'; - generateStringHelper(k, str, n + 1, ans); - } - } - - public static ArrayList generateString(int k) { - ArrayList result = new ArrayList<>(); - if (k == 0) { - return result; - } - char str[] = new char[k]; - str[0] = '0'; - generateStringHelper(k, str, 1, result); - str[0] = '1'; - generateStringHelper(k, str, 1, result); - Arrays.sort(str); - return result; - } -} diff --git a/Coding_Ninjas/src/main/java/Set1/Test5/Flags.java b/Coding_Ninjas/src/main/java/Set1/Test5/Flags.java deleted file mode 100755 index 96615dc..0000000 --- a/Coding_Ninjas/src/main/java/Set1/Test5/Flags.java +++ /dev/null @@ -1,39 +0,0 @@ -package Set1.Test5; - -public class Flags { - /* - A flag can consists of only three different colors of stripes, White(W), Blue(B) and Red(R). Given an integer N, find and return the number of ways to create such flags having N stripes consisting of these three color stripes only with the following constraints - -1. Stripes of the same color cannot be placed next to each other. -2. A blue stripe must always be placed between a white and a red or between a red and a white one. Hence blue stripe cannot be placed at starting or at ending. -3. Its not necessary to use all three colors. -Input Format : -Single Integer N -Output Format : -Single Integer representing number of ways to create a flag -Constraints : -1 <= N <= 30 -Sample Input 1 : -3 -Sample Output 1 : -4 -Sample Output 1 Explanation : -Possible flags with 3 stripes are : WRW, WBR, RWR, RBW -Sample Input 2 : -4 -Sample Output 2 : -6 -Sample Output 2 Explanation : -Possible flags with 4 stripes are : WRWR, WRBW, WBRW, RWRW, RWBR, RBWR - */ - public static long find_Ways(int N) - { - if(N == 1 || N == 2){ - return 2; - } - long result = find_Ways(N-1)+find_Ways(N-2); - return result; - - } - -} - diff --git a/Coding_Ninjas/src/main/java/Set1/Test5/GroupSum.java b/Coding_Ninjas/src/main/java/Set1/Test5/GroupSum.java deleted file mode 100755 index cc859cc..0000000 --- a/Coding_Ninjas/src/main/java/Set1/Test5/GroupSum.java +++ /dev/null @@ -1,43 +0,0 @@ -package Set1.Test5; - -public class GroupSum { - /* - Given an integer array A of size N and an integer k, check if it is possible to choose a group of some of the integers in the array such that the group sums to the given target k. -There is one with this additional constraint - -if there are numbers in the array that are adjacent and having identical values, they must either all be chosen, or none of them chosen. -Return true or false. -For example, with the array {1, 2, 2, 2, 5, 2}, either all three 2's in the middle must be chosen or not, all as a group. - -Input Format : -Line 1 : Integer N -Line 2 : Elements of array (separated by space) -Line 3 : Integer k -Output Format : -true or false -Constraints : -1 <= N <= 30 -1 <= Ai <= 10^4 -Sample Input 1 : -4 -2 4 4 8 -14 -Sample Output 1 : -false -Sample Input 2 : -5 -2 4 4 1 8 -16 -Sample Output 2 : -true - */ - public static boolean subsetSumToKIdentical(int input[], int n,int k){ - for (int i = 0; i < (n - 1); i++) { - for (int j = (i + 1); j < n; j++) { - if (input[i] + input[j] == k) { - return true; - } - } - } - return false; - } -} diff --git a/Coding_Ninjas/src/main/java/Test1/CheckAp.java b/Coding_Ninjas/src/main/java/Test1/CheckAp.java deleted file mode 100755 index ab26992..0000000 --- a/Coding_Ninjas/src/main/java/Test1/CheckAp.java +++ /dev/null @@ -1,40 +0,0 @@ -package Test1; - -import java.util.Scanner; - -public class CheckAp { - /* - Given input consists of n numbers. Check whether those n numbers form an arithmetic progression or not. Print true or false. -Input format : -Line 1 : n -Line 2 : n numbers -Sample Input 1 : -6 -2 6 10 14 18 22 -Sample Output 1 : -true -Sample Input 2 : -6 -2 6 10 15 19 23 -Sample Output 2 : -false - */ - public static void main(String[] args) { - Scanner s = new Scanner(System.in); - int N=s.nextInt(); - int n1 = s.nextInt(); - int n2 = s.nextInt(); - int diff= n2-n1; - n1=n2; - for (int i =3;i<=N;i++){ - n2=s.nextInt(); - int d = n2-n1; - if (diff!=d){ - System.out.println("false"); - return; - } - n1=n2; - } - System.out.println("true"); - } -} diff --git a/Coding_Ninjas/src/main/java/Test1/NumberStar_pattern_1.java b/Coding_Ninjas/src/main/java/Test1/NumberStar_pattern_1.java deleted file mode 100755 index 2eae80a..0000000 --- a/Coding_Ninjas/src/main/java/Test1/NumberStar_pattern_1.java +++ /dev/null @@ -1,41 +0,0 @@ -package Test1; - -import java.util.Scanner; - -public class NumberStar_pattern_1 { - /* - Print the following pattern for given number of rows. -Input format : -Integer N (Total number of rows) -Output Format : -Pattern in N lines -Sample Input : - 5 -Sample Output : - 5432* - 543*1 - 54*21 - 5*321 - *4321 - - */ - public static void main(String[] args) { - Scanner s = new Scanner(System.in); - int N=s.nextInt(); - s.close(); - int i=1; - while (i<=N){ - int k=N; - while (k >=1){ - if (i == k){ - System.out.print('*'); - }else { - System.out.print(k); - } - k--; - } - System.out.println(); - i++; - } - } -} diff --git a/Coding_Ninjas/src/main/java/Test1/Palindrome_number.java b/Coding_Ninjas/src/main/java/Test1/Palindrome_number.java deleted file mode 100755 index 78221b6..0000000 --- a/Coding_Ninjas/src/main/java/Test1/Palindrome_number.java +++ /dev/null @@ -1,31 +0,0 @@ -package Test1; - -import java.util.Scanner; - -public class Palindrome_number { - /* - Write a program to determine if given number is palindrome or not. Print true if it is palindrome, false otherwise. -Palindrome are the numbers for which reverse is exactly same as the original one. For eg. 121 -Sample Input 1 : -121 -Sample Output 1 : -true -Sample Input 2 : -1032 -Sample Output 2 : -false - */ - public static void main(String[] args) { - Scanner s = new Scanner(System.in); - int n = s.nextInt(); - s.close(); - int num = n; - int rev=0,rem; - while (n!=0){ - rem = n%10; - rev=rev*10+rem; - n=n/10; - } - System.out.println((rev == num) ? true : false); - } -} diff --git a/Coding_Ninjas/src/main/java/TriesAndHuffman/Trie.java b/Coding_Ninjas/src/main/java/TriesAndHuffman/Trie.java deleted file mode 100755 index 94f1fdd..0000000 --- a/Coding_Ninjas/src/main/java/TriesAndHuffman/Trie.java +++ /dev/null @@ -1,119 +0,0 @@ -package TriesAndHuffman; - - -class TrieNode{ - char data; - boolean isTerminating; - TrieNode children[]; - - public TrieNode(char data){ - this.data = data; - isTerminating = false; - children = new TrieNode[26]; - } - - public TrieNode() { - - children = new TrieNode[26]; - isTerminating = false; - for (int i = 0; i < 26; i++) - { - children[i] = null; - } - } -} -public class Trie { - - public TrieNode root; - // public static void main(String[] args) { -// Scanner s = new Scanner(System.in); -// int n = s.nextInt(); -// -// String[] words = new String[n]; -// for(int i = 0; i < n; i++) { -// words[i]=s.next(); -// add(words[i]); -// } -// for (int i=0;ichildren[index] != NULL) - { - current = root->children[index]; - } - else - { - current = new trienode(); - root->children[index] = current; - current = root->children[index]; - } - */ - -// TrieNode child; -// int childIndex = word.charAt(0)-'a'; -// if (root.children!=null){ -// child = root.children[childIndex]; -// }else { -// child = new TrieNode(); -// root.children[childIndex]=child; -// child = root.children[childIndex]; -// } - add(child,word.substring(1)); - } - - public void printer(TrieNode root,String s){ - TrieNode current = root; - for (int i = 0; i < s.length(); i++) { - int index = s.charAt(i) - 'a'; - if (current.children[index]==null){ - System.out.println("No Suggestions"); - add(root,s); - return; - - }else { - current=current.children[index]; - } - } - helper(current,s); - } - - public void helper(TrieNode current,String prefix){ - boolean check = true; - if (current.isTerminating) { - System.out.println(prefix) ; - } - for (int i=0;i<26;i++){ - TrieNode temp = current; - if (temp.children[i]!=null){ - char suffix= (char) (i+ (int)'a'); - helper(current.children[i],prefix+suffix ); - } - } - } - - - -} diff --git a/Coding_Ninjas/src/main/java/com/cleo/Calculator.java b/Coding_Ninjas/src/main/java/com/cleo/Calculator.java deleted file mode 100644 index 39f03bf..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/Calculator.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.cleo; -import javax.swing.*; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -public class Calculator extends JFrame implements ActionListener { - @Override - public void actionPerformed(ActionEvent e) { - - } - - private static final long serialVersionUID = 1L; - JPanel[] row = new JPanel[5]; - JButton[] button = new JButton[19]; - String[] buttonString = {"7", "8", "9", "+", "4", "5", "6", "- ", "1", "2", "3", "*", ".", "/", "C", "?", "+/-", "=", "0"}; - - int[] dimW = {430, 70, 150, 140}; - int[] dimH = {50, 60}; - Dimension displayDimension = new Dimension(dimW[0], dimH[0]); - Dimension regularDimension = new Dimension(dimW[1], dimH[1]); - Dimension rColumnDimension = new Dimension(dimW[2], dimH[1]); - Dimension zeroButDimension = new Dimension(dimW[3], dimH[1]); - boolean[] function = new boolean[4]; - double[] temporary = {0, 0}; - JTextArea display = new JTextArea(2, 25); - Font font = new Font("Times new Roman", Font.BOLD, 20); - - Calculator() { - super("Calculator"); - // setDesign(); - setSize(500, 350); - setResizable(false); - setDefaultCloseOperation(EXIT_ON_CLOSE); - GridLayout grid = new GridLayout(5, 5); - setLayout(grid); - - for (int i = 0; i < 4; i++) { - function[i] = false; - } - FlowLayout f1 = new FlowLayout(FlowLayout.CENTER); - FlowLayout f2 = new FlowLayout(FlowLayout.CENTER, 1, 1); - for (int i = 0; i < 5; i++) { - row[i] = new JPanel(); - } - row[0].setLayout(f1); - for (int i = 1; i < 5; i++) - row[i].setLayout(f2); - - for (int i = 0; i < 19; i++) { - button[i] = new JButton(); - button[i].setText(buttonString[i]); - button[i].setBackground(Color.white); - button[i].setFont(font); - button[i].addActionListener(this); - } - } -} \ No newline at end of file diff --git a/Coding_Ninjas/src/main/java/com/cleo/Group3/FishEvolution.java b/Coding_Ninjas/src/main/java/com/cleo/Group3/FishEvolution.java deleted file mode 100644 index 5260416..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/Group3/FishEvolution.java +++ /dev/null @@ -1,193 +0,0 @@ -package com.cleo.Group3; - - -/** - * Fish Evolution -Send Feedback -Namita has magical fishes. Her fishes has the capability to evolve to become bigger fish. So, if the smaller fish touches a bigger or equivalent fish, then the bigger or equivalent fish disappears into water and the smaller fish evolves to become as large as the larger fish. Therefore, to avoid stray evolutions, she has kept her fishes in separate cells, arranged in a linear order. Now, she wants to evolve only one fish and she wants to choose the fish which will evolve maximum number of times. She wants your help in this. To make it more interesting, she has added signs of evolution with the fish cells. A cell assigned with +1 can only evolve with fishes on its right side and a cell assigned with -1 can only evolve with fishes on its left side. Can you complete this challenge? -Remember that the fishes are mindlessly evolving. This means that they evolve with the first big fish that comes in their way. Consider the following case. Here, Fish with size 5 can evolve in right direction. -5 12 10 11 13 -Fish with size 5 will evolve 2 times like 5 -> 12 -> 13 and not 3 times like 5->10->11->13. -Note: If there is more than one fish which can evolve the maximum number of times, select the one with the greater size. -Input Format: -First line of input contains an integer t, representing the number of test cases. -For each test case, the first line contains an integer n, representing the number of fishes. -Second line of each case contains n space separated integers, representing the size of fishes. -Third line of each test case contains n space separated integers, being +1 or -1, representing the signs of evolution. -Constraints: -1 <= t <= 150 -1 <= n <= 10^4 -1 <= arr[i] <= 10^4 -directions[i] = -1 or 1 -Time Limit : 1 second -Output Format: -For each test case, you have to print the size of fish which will evolve maximum number of times, along with the direction it is going to evolve in. (Left for -1 and Right for +1) -Sample Input 1: -1 -10 -5 1 4 12 10 8 11 9 18 88 -1 1 -1 -1 1 -1 1 -1 -1 -1 -Sample Output 1: -1 Right -Explanation: -1 can evolve 4 times with 4, 12, 18, 88 -Sample Input 2: -1 -12 -30 20 5 2 4 12 10 8 11 3 18 88 -1 1 1 1 -1 -1 1 1 1 -1 -1 -1 -Sample Output 2: -3 Left -Explanation: -2 can evolve 4 times with 4 -> 12 -> 18 -> 88 -3 can also evolve 4 times with 11 -> 12 -> 20 -> 30 -3 is greater than 2, hence the answer is 3 Left. - */ - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.Stack; -import java.util.StringTokenizer; - -class FastInput { - BufferedReader br; - StringTokenizer st; - - public FastInput() - { - br = new BufferedReader( - new InputStreamReader(System.in)); - } - - String next() - { - while (st == null || !st.hasMoreElements()) { - try { - st = new StringTokenizer(br.readLine()); - } - catch (IOException e) { - e.printStackTrace(); - } - } - return st.nextToken(); - } - - int nextInt() { return Integer.parseInt(next()); } - - long nextLong() { return Long.parseLong(next()); } - - double nextDouble() - { - return Double.parseDouble(next()); - } - - String nextLine() - { - String str = ""; - try { - str = br.readLine(); - } - catch (IOException e) { - e.printStackTrace(); - } - return str; - } -} -class Pair{ - int first; - int second; - Pair(int first, int second){ - this.first = first; - this.second = second; - } -} -public class FishEvolution { - public static void main(String[] args) { - FastInput s = new FastInput(); - int t = s.nextInt(); - for(int i = 0; i < t; i++) { - int n = s.nextInt(); - int[] fish = new int[n]; - int[] dir = new int[n]; - for (int j = 0; j < n; j++) fish[j] = s.nextInt(); - for (int j = 0; j < n; j++) dir[j] = s.nextInt(); - // System.out.println(Arrays.toString(dir)); - Stack st = new Stack<>(); - int maxValue = 0; int num = 0, fishNum = -1; - boolean directionLeft = true; - for(int j = 0; j < n; j++) { - // System.out.println(j); - if(dir[j]==-1){ - // System.out.print(j+" start "); - if(!st.isEmpty()&& st.peek().first< fish[j]){ - if(st.size()>num){ - fishNum = st.peek().first; - num = st.size(); - maxValue = st.peek().second; - }else if(st.size()==num && st.peek().second>maxValue){ - - fishNum = st.peek().first; - maxValue = st.peek().second; - } - while(!st.isEmpty() && st.peek().firstnum){ - fishNum = st.peek().first; - num = st.size(); - maxValue = st.peek().second; - }else if(st.size()==num && st.peek().second>maxValue){ - fishNum = st.peek().first; - maxValue = st.peek().second; - } - } - st.clear(); - - for (int j = n-1; j < 0; j--) { - if(dir[j]==1){ - if(!st.isEmpty()&& st.peek().first< fish[j]){ - if(st.size()>num){ - directionLeft = false; - - fishNum = st.peek().first; - num = st.size(); - maxValue = st.peek().second; - }else if(st.size()==num && st.peek().second>maxValue){ - directionLeft = false; - fishNum = st.peek().first; - maxValue = st.peek().second; - } - while(!st.isEmpty() && st.peek().firstnum){ - fishNum = st.peek().first; - num = st.size(); - maxValue = st.peek().second; - }else if(st.size()==num && st.peek().second>maxValue){ - fishNum = st.peek().first; - maxValue = st.peek().second; - } - } - st.clear(); - - if(!directionLeft) System.out.println(fishNum+" Right"); - System.out.println(fishNum+" Left"); - - } - } -} \ No newline at end of file diff --git a/Coding_Ninjas/src/main/java/com/cleo/Group3/IsomorphicTree.java b/Coding_Ninjas/src/main/java/com/cleo/Group3/IsomorphicTree.java deleted file mode 100644 index e8f1e2b..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/Group3/IsomorphicTree.java +++ /dev/null @@ -1,202 +0,0 @@ -package com.cleo.Group3; - - -import java.util.Scanner; - -/* Isomorphic Trees -Send Feedback -Given two binary trees. Check whether these two trees are isomorphic or not. -Isomorphic trees are the ones which can be made identical by series of flips i.e. by swapping left and right children of a number of nodes. -Example -Input -Output - True -Input format : -Line 1 : Elements in level order form (separated by space) -(If any node does not have left or right child, take -1 in its place) -Output Format : -True or False -Sample Input 1: - 5 35 10 2 3 5 2 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 - 9 11 12 2 5 3 2 -1 -1 -1 -1 -1 -1 -1 -1 -Sample Output 1: - False -Sample Input 1: - 2 35 10 2 3 -1 -1 -1 -1 -1 -1 - 9 10 35 -1 -1 3 2 -1 -1 -1 -1 -Sample Output 1: - True - */ -class BinaryTreeNode { - public T data; - public BinaryTreeNode left; - public BinaryTreeNode right; - public BinaryTreeNode next; - - public BinaryTreeNode(T data) { - this.data = data; - left = null; - right = null; - next = null; - } - - public T getData() { - return data; - } - - public void setData(T data) { - this.data = data; - } - - public BinaryTreeNode getLeft() { - return left; - } - - public void setLeft(BinaryTreeNode left) { - this.left = left; - } - - public BinaryTreeNode getRight() { - return right; - } - - public void setRight(BinaryTreeNode right) { - this.right = right; - } - -} - -class Node { - public Node down; - public Node right; - T data; - Node next; - - Node(T data) { - this.data = data; - } - -} - -class QueueUnderFlowException extends Exception { - -} - -class QueueUsingLinkedList { - Node front; - Node rear; - int size; - - public QueueUsingLinkedList() { - front = null; - rear = null; - size = 0; - } - - public void enqueue(T data) { - Node nyaNode = new Node<>(data); - if (front == null) { - front = nyaNode; - rear = nyaNode; - } else { - rear.next = nyaNode; - rear = rear.next; - } - size++; - } - - public T dequeue() throws QueueUnderFlowException { - if (front == null) { - throw new QueueUnderFlowException(); - } - Node temp = front; - front = front.next; - size--; - return temp.data; - } - - public int size() { - return size; - } - - public boolean isEmpty() { - return size == 0 ? true : false; - } - - public void printQueue() { - Node temp = front; - while (temp != null) { - System.out.print(temp.data + "-->"); - temp = temp.next; - } - } -} -public class IsomorphicTree { - static boolean isIsomorphic(BinaryTreeNode n1, BinaryTreeNode n2) { - if(n1==null && n2 == null) return true; - if(n1==null||n2==null) return false; - if(n1.data!=n2.data) return false; - BinaryTreeNode swap; - swap = n1.left; - n1.left = n1.right; - n1.right = swap; - if(!isIsomorphic(n1.left, n2.left)) return false; - if(!isIsomorphic(n1.right, n2.right)) return false; - return true; - } - - static boolean isIsomorphic1(BinaryTreeNode n1, BinaryTreeNode n2) - { - // Both roots are NULL, trees isomorphic by definition - if (n1 == null && n2 == null) - return true; - - // Exactly one of the n1 and n2 is NULL, trees not isomorphic - if (n1 == null || n2 == null) - return false; - - if (n1.data != n2.data) - return false; - - return (isIsomorphic(n1.left, n2.left) && isIsomorphic(n1.right, n2.right)) || - (isIsomorphic(n1.left, n2.right) && isIsomorphic(n1.right, n2.left)); - } - static Scanner s = new Scanner(System.in); - - static BinaryTreeNode prepareTree() throws QueueUnderFlowException { - - int data = s.nextInt(); - BinaryTreeNode root = new BinaryTreeNode<>(data); - QueueUsingLinkedList> queue = new QueueUsingLinkedList(); - queue.enqueue(root); - - while (!queue.isEmpty()) { - BinaryTreeNode currentNode = queue.dequeue(); - - int leftData = s.nextInt(); - if (leftData != -1) { - BinaryTreeNode leftNode = new BinaryTreeNode<>( - leftData); - currentNode.setLeft(leftNode); - queue.enqueue(currentNode.getLeft()); - - } - - int rightData = s.nextInt(); - if (rightData != -1) { - currentNode.setRight(new BinaryTreeNode<>(rightData)); - queue.enqueue(currentNode.getRight()); - } - } - return root; - } - - public static void main(String[] args) throws QueueUnderFlowException { - // TODO Auto-generated method stub - BinaryTreeNode root1 = prepareTree(); - BinaryTreeNode root2 = prepareTree(); - System.out.println(isIsomorphic1(root1, root2)); - - } - -} \ No newline at end of file diff --git a/Coding_Ninjas/src/main/java/com/cleo/Group3/LinkedList.java b/Coding_Ninjas/src/main/java/com/cleo/Group3/LinkedList.java deleted file mode 100644 index 1af7528..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/Group3/LinkedList.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.cleo.Group3; - -import java.util.Scanner; - - -/* Linked List Matrix -Send Feedback -Given a Matrix mat of N*N size -, write a program that constructs a 2D linked list representation of the given matrix. -Input : 2D matrix -1 2 3 -4 5 6 -7 8 9 -Output : -1 -> 2 -> 3 -> NULL -| | | -v v v -4 -> 5 -> 6 -> NULL -| | | -v v v -7 -> 8 -> 9 -> NULL -| | | -v v v -NULL NULL NULL -Input Format : - The first line takes an integer N as input. - The next line input n*n integers denoting the matrix. -Output format: -Print the matrix using the linked list header. -Sample Input: -3 -1 2 3 4 5 6 7 8 9 -Sample Output: -1 2 3 -4 5 6 -7 8 9 - */ -//class Node{ -// int data; -// Node right,down; -// Node(int data){ -// this.data=data; -// right=null; -// down=null; -// } -//} -public class LinkedList { - - - static Node construct(int arr[][],int n){ - if(n<=0) return null; - - Node[][] mat = new Node[n][n]; - for (int i = 0; i < n; i++) { - for (int j = 0; j < n; j++) { - mat[i][j] = new Node(arr[i][j]); - - if(i!=0) mat[i-1][j].down = mat[i][j]; - if(j!=0) mat[i][j-1].right = mat[i][j]; - } - } - - return mat[0][0]; - - } - static void display(Node head) - { - Node rp; - Node dp=head; - while(dp!=null){ - rp=dp; - while(rp!=null){ - System.out.print(rp.data+" "); - rp=rp.right; - } - dp=dp.down; - System.out.println(); - } - - } - public static void main (String[] args) { - Scanner s=new Scanner(System.in); - int n=s.nextInt(); - int [][]arr=new int[n][n]; - for(int i=0;i adlist = new ArrayList<>(); - Node(int id) - { - this.id = id; - this.isRationalised = false; - } - } - static class Tree - { - ArrayList nodelist = new ArrayList<>(); - public Node getNode(int i) - { - Node node = new Node(i); - nodelist.add(node); - return node; - } - public void addEdge(Node u, Node v) - { - u.adlist.add(v); - v.adlist.add(u); - } - public int createTree(int[] arr) - { - Queue q = new LinkedList<>(); - q.add(getNode(nodelist.size())); - - int i = 1; - while(!q.isEmpty()) - { - Node nd = q.remove(); - int val = arr[i]; - for(int j=1;j<=val;j++) - { - Node node = new Node(nodelist.size()); - nodelist.add(node); - q.add(node); - addEdge(nd, node); - } - i+=val; - i++; - } - - q = new LinkedList<>(); - for(Node node: nodelist) - { - if(node.adlist.size()==1) { - q.add(node.adlist.get(0)); - } - } - - int count = 0; - - while(!q.isEmpty()) - { - Node cur = q.remove(); - if(!cur.isRationalised) - { - cur.isRationalised = true; - count++; - System.out.println(cur.id); - for(Node nd: cur.adlist) - { - if(nd.isRationalised) - continue; - nd.isRationalised = true; - boolean hasLeaf = false; - for(Node adnd: nd.adlist) - { - if(adnd.adlist.size()==1) - hasLeaf = true; - } - if(hasLeaf) - { - q.add(nd); - nd.isRationalised = false; - continue; - } - for(Node adnd : nd.adlist) - if(!adnd.isRationalised) - q.add(adnd); - } - } - } - - return count; - } - } - public static void main(String[] args) throws IOException { - Scanner sc = new Scanner(System.in); - - String line = sc.nextLine(); - String[] linearr = line.split(" "); - int[] arr = new int[linearr.length]; - for(int i=0;isc.nextInt()) - { - System.out.println(noh+" Mission Unsuccessful"); - } - else System.out.println(noh+" Mission Successful"); - } -} - */ -class TreeNode { - T data; - ArrayList> children; - - TreeNode(T data){ - this.data = data; - children = new ArrayList>(); - } -} -public class WarOnNinjas { - static class QueueEmptyException extends Exception { - } - - static class QueueUsingLL { - - class Node { - T data; - Node next; - Node(T data){ - this.data = data; - } - } - - private Node head; - private Node tail; - private int size = 0; - - public int size(){ - return size; - } - - public boolean isEmpty(){ - if(size == 0){ - return true; - } - return false; - } - - public T front() throws QueueEmptyException{ - if(size == 0){ - QueueEmptyException e = new QueueEmptyException(); - throw e; - } - - return head.data; - } - public void enqueue(T element){ - Node newNode = new Node(element); - - if(head == null){ - head = newNode; - tail = newNode; - } - else{ - tail.next = newNode; - tail = newNode; - } - - size++; - } - - public T dequeue() throws QueueEmptyException{ - if(head == null){ - QueueEmptyException e = new QueueEmptyException(); - throw e; - } - if(head == tail){ - tail = null; - } - T temp = head.data; - head = head.next; - size--; - return temp; - } - } - - static int minLandingCover(TreeNode root) { - //Write your code here - int sum=0; - if (dfs(root,sum)==0){ - sum++; - }else { - sum= dfs(root,sum); - } - return sum; - - } - - static int dfs(TreeNode root,int sum){ - if (root == null){ - return 1; - } - if (root.children.size()==0){ - return 0; - } - ArrayList arr = new ArrayList<>(); - int ans=0; - for (int i=0;i takeInputLevelWise(){ - QueueUsingLL> pendingNodes = new QueueUsingLL>(); // Queue of nodes that are entered themselves but their children aren't added yet - int rootData = s.nextInt(); - TreeNode root = new TreeNode(rootData); - pendingNodes.enqueue(root); - while(!pendingNodes.isEmpty()){ - TreeNode currentNode; - try { - currentNode = pendingNodes.dequeue(); - int numChild = s.nextInt(); - for(int i = 0 ; i < numChild; i++){ - int currentChild = s.nextInt(); - TreeNode childNode = new TreeNode(currentChild); - pendingNodes.enqueue(childNode); - currentNode.children.add(childNode); - } - } catch (QueueEmptyException e) { - } - } - return root; - } - - - public static void main(String[] args) { - - TreeNode root = takeInputLevelWise(); - int allowed; - allowed = s.nextInt(); - int final_ans = minLandingCover(root); - printAns(allowed, final_ans); - - } - -} \ No newline at end of file diff --git a/Coding_Ninjas/src/main/java/com/cleo/Main.java b/Coding_Ninjas/src/main/java/com/cleo/Main.java deleted file mode 100644 index c4969e3..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/Main.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.cleo; - -public class Main { - public static void main(String[] args) { - Integer f=1; - Integer s=1; - if(f==s) - System.out.println("Values are same"); - else - System.out.println("Values are not same"); - float x= 100; - byte b = 127; - System.out.println(x); - System.out.println((int)b+1); - System.out.println("Hello world!"); - - } -} \ No newline at end of file diff --git a/Coding_Ninjas/src/main/java/com/cleo/Test.java b/Coding_Ninjas/src/main/java/com/cleo/Test.java deleted file mode 100644 index 67d7764..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/Test.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.cleo; - -import java.util.HashMap; -import java.util.Map; - -public class Test { - - - private static int reverse(int num){ - if(num/10==0) - return num; - int reversed=0; - while(num!=0){ - reversed=reversed*10+num%10; - num/=10; - } - return reversed; - - } - public static boolean isPalindrome(int x) { - if(x<0) - return false; - - if(x/10==0) - return true; - - return x==reverse(x); - - - - - - } - - public int[] twoSum(int[] nums, int target) { - Map map = new HashMap<>(); - for (int i = 0; i < nums.length; i++) { - if(map.containsKey(target-nums[i])){ - return new int[]{i,map.get(target-nums[i])}; - } - map.put(nums[i],i); - } - return new int[]{-1,-1}; - - } - - public static void main(String[] args) { - System.out.println("Hi my is Deven Kalra"); - System.out.println("Welcome back to macbook"); - System.out.println(isPalindrome(121)); - - } -} diff --git a/Coding_Ninjas/src/main/java/com/cleo/fullTest2/BinomialExpansion.java b/Coding_Ninjas/src/main/java/com/cleo/fullTest2/BinomialExpansion.java deleted file mode 100644 index 9a8d51a..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/fullTest2/BinomialExpansion.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.cleo.fullTest2; - -import java.util.Scanner; - -public class BinomialExpansion { - - public static void main(String[] args) { - Scanner in = new Scanner(System.in); - int A = in.nextInt(),X= in.nextInt(),n= in.nextInt(); - int count=0; - // double term1=A,term2=X; - int term = (int)Math.pow(A, n); - System.out.print(term + " "); - for (int i = 1; i <= n; i++) { - term = term * X * (n - i + 1) - / (i * A); - System.out.print(term + " "); - } - } -} diff --git a/Coding_Ninjas/src/main/java/com/cleo/fullTest2/Node.java b/Coding_Ninjas/src/main/java/com/cleo/fullTest2/Node.java deleted file mode 100644 index 1e9c3cf..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/fullTest2/Node.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.cleo.fullTest2; - -public class Node{ - int data; - Node next; - Node (int key) - { - data=key; - next=null; - } -} diff --git a/Coding_Ninjas/src/main/java/com/cleo/fullTest2/SortArrayBasedOnFrequency.java b/Coding_Ninjas/src/main/java/com/cleo/fullTest2/SortArrayBasedOnFrequency.java deleted file mode 100644 index fa2320f..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/fullTest2/SortArrayBasedOnFrequency.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.cleo.fullTest2; - -import java.util.*; - -public class SortArrayBasedOnFrequency { - - private static int[] sortArray(int[] arr, int N){ - Arrays.sort(arr); - Map frequencyMap = new HashMap<>(); - PriorityQueue pq = new PriorityQueue<>((a,b) -> Objects.equals(frequencyMap.get(a), frequencyMap.get(b)) - ? b - a: frequencyMap.get(a) - frequencyMap.get(b)); - - for(int element:arr) - frequencyMap.compute(element,(k,v)->v==null?1:++v); - - - for (int j : arr) { - pq.offer(j); - } - int n = arr.length; - int [] result = new int[n]; - for (int i = 0; i < n; i++) { - result[i] = pq.poll(); - } - return result; - - } - public static void main(String[] args) { - Scanner in = new Scanner(System.in); - int N = in.nextInt(); - int[] arr = new int[N]; - for (int i = 0; i < N; i++) { - arr[i]= in.nextInt(); - } - int[] result=sortArray(arr,N); - for (int i = N-1; i >=0; i--) { - System.out.print(result[i]+" "); - } - - } -} diff --git a/Coding_Ninjas/src/main/java/com/cleo/fullTest2/SwapNodesInKPairs.java b/Coding_Ninjas/src/main/java/com/cleo/fullTest2/SwapNodesInKPairs.java deleted file mode 100644 index 6b25dc4..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/fullTest2/SwapNodesInKPairs.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.cleo.fullTest2; - - -public class SwapNodesInKPairs { - - private static int length(Node head){ - int size=0; - while(head!=null){ - head=head.next; - size++; - } - return size; - } - - - - public static Node reverseList(Node head, Node newHead){ - if (head==null) return newHead; - Node temp = head.next; - head.next = newHead; - newHead = head; - return reverseList(temp,newHead); - } - - public static Node reverse(Node head, int k) { - if (head==null) return null; - Node temp = head; - for (int i =0;i=0){ - cost+=input[i]+input[i-1]; - i-=3; - } - if(i>=0) - while(i>=0){ - cost+=input[i]; - i--; - } - return cost; - } - public static void main(String[] args) { - Scanner in = new Scanner(System.in); - int N = in.nextInt(); - int[] input = new int[N]; - for (int i = 0; i < N; i++) { - input[i]=in.nextInt(); - } - Arrays.sort(input); - if(N==1) - System.out.println(input[0]); - else if(N==2) - System.out.println(Arrays.stream(input).sum()); - else{ - System.out.println(calcuateCost(input,N-1)); - } - } -} diff --git a/Coding_Ninjas/src/main/java/com/cleo/fullTest3/Calculator.java b/Coding_Ninjas/src/main/java/com/cleo/fullTest3/Calculator.java deleted file mode 100644 index 15cb4fb..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/fullTest3/Calculator.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.cleo.fullTest3; - -import java.util.Scanner; - -public class Calculator { - public static int findMin(int X, int Y) { - int ans = 0; - while (Y > X) { - ans++; - if (Y % 2 == 1) - Y++; - else - Y /= 2; - } - return ans + X - Y; - } - public static void main(String[] args) { - Scanner scanner = new Scanner(System.in); - int count = 0; - int x = scanner.nextInt(); - int y = scanner.nextInt(); - System.out.println(findMin(x,y)); - } -} diff --git a/Coding_Ninjas/src/main/java/com/cleo/fullTest3/MakeArraySumEven.java b/Coding_Ninjas/src/main/java/com/cleo/fullTest3/MakeArraySumEven.java deleted file mode 100644 index c238e0f..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/fullTest3/MakeArraySumEven.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.cleo.fullTest3; - -import java.util.Scanner; - -public class MakeArraySumEven { - public static void main (String[] args) { - // Write your code here - // Take input and print desired output - Scanner in = new Scanner(System.in); - int count = 0; - int N = in.nextInt(); - for (int i = 0; i < N; i++) { - int num= in.nextInt(); - if(num%2!=0) - count++; - } - if(count%2==0) - System.out.println(N-count); - else - System.out.println(count); - - - - } -} diff --git a/Coding_Ninjas/src/main/java/com/cleo/fullTest3/PrintSuperPrimes.java b/Coding_Ninjas/src/main/java/com/cleo/fullTest3/PrintSuperPrimes.java deleted file mode 100644 index 545fcfc..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/fullTest3/PrintSuperPrimes.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.cleo.fullTest3; - -import java.util.HashMap; -import java.util.Map; -import java.util.Scanner; - -public class PrintSuperPrimes { - - private static final Map primeMap = new HashMap<>(); - - private static boolean checkPrime(int num){ - if(num<=1) - return false; - if(num%2==0&&num!=2) - return false; - if(num==2) - return true; - for (int i = 3; i <=(int)Math.sqrt(num) ; i++) { - if(num%i==0) - return false; - } - return true; - } - private static void superPrimes(int N){ - int prime=1; - int i=1; - while(i<=N){ - if(checkPrime(i)) - primeMap.put(prime++,i); - i++; - - - - } - for ( i = 1; i <=N ; i++) { - if(primeMap.get(i)!=null&&checkPrime(i)) - System.out.print(primeMap.get(i)+ " "); - - } - - - - - } - public static void main(String[] args) { - int N = new Scanner(System.in).nextInt(); - superPrimes(N); - - } -} diff --git a/Coding_Ninjas/src/main/java/com/cleo/graphs/GetPathBFS.java b/Coding_Ninjas/src/main/java/com/cleo/graphs/GetPathBFS.java deleted file mode 100644 index 6c4c0d3..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/graphs/GetPathBFS.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.cleo.graphs; - -import java.util.ArrayList; -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.io.IOException; -import java.util.*; -public class GetPathBFS { - public static void BFTraversal(int[][] adjMatrix, int v1, int v2) { - Queue queue = new LinkedList<>(); - ArrayList arrayList = new ArrayList<>(); - HashMap hashMap = new HashMap<>(); - boolean[] visited = new boolean[adjMatrix.length]; - queue.add(v1); - visited[v1] = true; - hashMap.put(v1,-1); - while (!queue.isEmpty()) { - if (queue.peek() == v2) { - int i = queue.peek(); - while (i != -1) { - arrayList.add(i); - i = hashMap.get(i); - } - for (int j :arrayList) System.out.print(j+" "); - return; - } - for (int i = 0; i < visited.length; i++) { - if (adjMatrix[queue.peek()][i] == 1 && !visited[i]) { - queue.add(i); - visited[i] = true; - hashMap.put(i,queue.peek()); - } - } - queue.poll(); - } - } - - - public static void main(String[] args) throws NumberFormatException, IOException { - Scanner scanner = new Scanner(System.in); - int n = scanner.nextInt(); - int e = scanner.nextInt(); - if (n == 0) return; - int[][] adjMatrix = new int[n][n]; - for (int i = 0; i < e; i++) { - int v1 = scanner.nextInt(); - int v2 = scanner.nextInt(); - adjMatrix[v1][v2] = 1; - adjMatrix[v2][v1] = 1; - } - int v1 = scanner.nextInt(); - int v2 = scanner.nextInt(); - if (v1 < 0 || v1 >= adjMatrix.length || v2 < 0 || v2 >= adjMatrix.length) { - return; - } - BFTraversal(adjMatrix,v1,v2); - } -} \ No newline at end of file diff --git a/Coding_Ninjas/src/main/java/com/cleo/graphs/Get_Path_DFS.java b/Coding_Ninjas/src/main/java/com/cleo/graphs/Get_Path_DFS.java deleted file mode 100644 index c83d689..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/graphs/Get_Path_DFS.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.cleo.graphs; - -import java.io.IOException; -import java.util.*; - -public class Get_Path_DFS { - - private static final Map> graph = new HashMap<>(); - - // private static List path = new ArrayList<>(); - public static List dfsUtil(int source, int destination,boolean[] visited,List temp){ - if(source==destination){ - System.out.println(temp); - List result=new ArrayList<>(); - result.add(source); - return result; - } - - if(!visited[source]){ - temp.add(source); - visited[source]=true; - List connections = graph.get(source); - if(connections!=null){ - for(int conn:connections){ - dfsUtil(conn,destination,visited,temp); - - - } - } - } - return temp; - - - } - - public static void main(String[] args) throws NumberFormatException, IOException { - - /* Write Your Code Here - * Complete the Rest of the Program - * You have to take input and print the output yourself - */ - Scanner in = new Scanner(System.in); - int N = in.nextInt(); - int E = in.nextInt(); - for (int i = 0; i < N; i++) { - graph.put(i,new ArrayList<>()); - } - for (int i = 0; i < E; i++) { - int v1 = in.nextInt(); - int v2 = in.nextInt(); - graph.get(v1).add(v2); - graph.get(v2).add(v1); - - } - int source = in.nextInt(); - int destination = in.nextInt(); - boolean[] visited = new boolean[N]; - List result= new ArrayList<>(); - result= dfsUtil(source,destination,visited,result); - - if(!result.isEmpty()){ - for(int r:result){ - System.out.print(r+ " "); - } - System.out.println(); - } - - - } -} diff --git a/Coding_Ninjas/src/main/java/com/cleo/graphs/Graphs.java b/Coding_Ninjas/src/main/java/com/cleo/graphs/Graphs.java deleted file mode 100644 index 211908f..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/graphs/Graphs.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.cleo.graphs; - -import java.util.*; - -public class Graphs { - - - public static void dftraversal(int adjMatrix[][], int currentVertex, boolean visited[]){ - visited[currentVertex] = true; - System.out.print(currentVertex + " "); - for(int i = 0; i < adjMatrix.length; i++){ - if(adjMatrix[currentVertex][i] == 1 && visited[i] == false) { -// i is neighbor of currentVertex - dftraversal(adjMatrix, i, visited); - } - } - } - - - public static void dftraversal(int adjMatrix[][]){ - boolean visited[]= new boolean[adjMatrix. length]; - for(int i=0;i pendingVertices = new LinkedList<>(); - boolean visited[] = new boolean[adjMatrix. length]; - visited[0] = true; - pendingVertices.add(0); - - while(! pendingVertices.isEmpty()){ - int currentVertex = pendingVertices.poll(); - System.out.print(currentVertex +" "); - for(int i = 0; i < adjMatrix.length; i++){ - if(adjMatrix[currentVertex][i] == 1 && !visited[i]){ -// i is unvisited neighbor of currentVertex - pendingVertices.add(i); - visited[i] = true; - } - } - } - } - - public static ArrayList getPathBFS(int adjMatrix[][], int s, int e){ - Queue pendingVertices = new LinkedList<>(); - HashMap map = new HashMap<>(); - boolean visited[] = new boolean[adjMatrix.length]; - visited[s] = true; - pendingVertices.add(s); - map.put(s, -1); - boolean pathFound = false; - - while(!pendingVertices.isEmpty()){ - int currentVertex = pendingVertices.poll(); - for(int i = 0; i < adjMatrix.length; i++){ - if(adjMatrix[currentVertex][i] == 1 && !visited[i]){ - pendingVertices.add(i); - visited[i] = true; - map.put(i, currentVertex); - if(i == e) { -// Path found - pathFound = true; - break; - } - } - } - } - if(pathFound){ - ArrayList path = new ArrayList<>(); - int currentVertex = e; - while( currentVertex != -1){ - path.add(currentVertex); - int parent = map.get(currentVertex); - currentVertex = parent; - } - path.add(s); - return path; - }else{ - return null; - } - } - - public static void main(String[] args) { - Scanner s = new Scanner(System.in); - int n = s.nextInt(); - int e = s.nextInt(); - int adjMatrix[][] = new int[n][n]; - for(int i = 0; i = 0; i--) - { - - // Decreasing Part - int m = n; - for (int j = 0; j < i; j++) - { - System.out.print(m); - m--; - } - - // Constant Part. - for (int k = 0; - k < s - 2 * i; k++) - { - System.out.print(n - i); - } - - // Decreasing Part - m = n - i + 1; - for (int l = 0; l < i; l++) - { - System.out.print(m); - m++; - } - System.out.println(); - } - - } - - public static void main(String[] args) { -printV2(4); - } -} diff --git a/Coding_Ninjas/src/main/java/com/cleo/skillTest1/SpecialSumOfArray.java b/Coding_Ninjas/src/main/java/com/cleo/skillTest1/SpecialSumOfArray.java deleted file mode 100644 index 56a6c49..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/skillTest1/SpecialSumOfArray.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.cleo.skillTest1; - -public class SpecialSumOfArray { - - public static int sum(int[] arr) - { - //Write code here - int sum=0; - for(int num:arr){ - sum=sum+num; - sum=sum/10+sum%10; - - - - - - } - return sum; - } - - public static void main(String[] args) { - int[] arr = {9,9,9}; - System.out.println(sum(arr)); - } -} diff --git a/Coding_Ninjas/src/main/java/com/cleo/skillTest1/TotalStrings.java b/Coding_Ninjas/src/main/java/com/cleo/skillTest1/TotalStrings.java deleted file mode 100644 index 067c2af..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/skillTest1/TotalStrings.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.cleo.skillTest1; - -public class TotalStrings { - static int countStrUtil(int[][][] dp, int n, - int bCount, int cCount) - { - - // Base cases - if (bCount < 0 || cCount < 0) - { - return 0; - } - if (n == 0) - { - return 1; - } - if (bCount == 0 && cCount == 0) - { - return 1; - } - - // if we had saw this combination previously - if (dp[n][bCount][cCount] != -1) - { - return dp[n][bCount][cCount]; - } - - // Three cases, we choose, a or b or c - // In all three cases n decreases by 1. - int res = countStrUtil(dp, n - 1, bCount, cCount); - res += countStrUtil(dp, n - 1, bCount - 1, cCount); - res += countStrUtil(dp, n - 1, bCount, cCount - 1); - - return (dp[n][bCount][cCount] = res); - } - - // A wrapper over countStrUtil() - static int countStr(int n, int bCount, int cCount) - { - int[][][] dp = new int[n + 1][2][3]; - for (int i = 0; i < n + 1; i++) - { - for (int j = 0; j < 2; j++) - { - for (int k = 0; k < 3; k++) - { - dp[i][j][k] = -1; - } - } - } - return countStrUtil(dp, n,bCount,cCount); - } - - public static int countStrings(int n){ - - // Write your code here - //return countStr(n,1,2); - long a = 1 + (n * 2L) + (n * (((long) n * n) - 1) / 2); - long divisor=1000000007; - return (int) (a%divisor); - } - - public static void main(String[] args) { - System.out.println(countStrings(190)); - } -} diff --git a/Coding_Ninjas/src/main/java/com/cleo/skillTest2/BreakNumbers.java b/Coding_Ninjas/src/main/java/com/cleo/skillTest2/BreakNumbers.java deleted file mode 100644 index ac19088..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/skillTest2/BreakNumbers.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.cleo.skillTest2; - -import java.util.Scanner; -import java.util.stream.IntStream; - -public class BreakNumbers { - - public static void printCombination(int num){ - //Write your code here - printAllUniqueParts(num); - - } - - static void printArray(int p[], int n) - { - for (int i = n-1; i >=0; i--) { - System.out.print(p[i] + " "); - } - System.out.println(); - } - - static void printAllUniqueParts(int n) { - int[] p = new int[n]; - int k = 0; - p[k] = n; - - - while (true) { - - printArray(p, k + 1); - - int rem_val = 0; - while (k >= 0 && p[k] == 1) { - rem_val += p[k]; - k--; - } - if (k < 0) return; - - p[k]--; - rem_val++; - while (rem_val > p[k]) { - p[k + 1] = p[k]; - rem_val = rem_val - p[k]; - k++; - } - - p[k + 1] = rem_val; - k++; - } - } - static Scanner s = new Scanner(System.in); - - public static void main(String[] args) { - int number = s.nextInt(); - printCombination(number); - } -} diff --git a/Coding_Ninjas/src/main/java/com/cleo/skillTest2/Combinations.java b/Coding_Ninjas/src/main/java/com/cleo/skillTest2/Combinations.java deleted file mode 100644 index 2888ca4..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/skillTest2/Combinations.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.cleo.skillTest2; - -import java.util.Arrays; -import java.util.Scanner; - -public class Combinations { - private static void generateCombinationsSumN(int[] arr, int[] output,int start,int end,int index,int N){ - if(index==N){ - for (int i = 0; i < N; i++) - System.out.print(output[i]+" "); - System.out.println(); - return; - - - } - for (int i=start; i<=end && end-i+1 >= N-index; i++) { - output[index] = arr[i]; - generateCombinationsSumN(arr, output, i+1, end, index+1, N); - } - } - public static void printCombination(int[] arr){ - //Write your code here - int[] output = new int[arr.length]; - int num=arr.length; - generateCombinationsSumN(arr,output,0,num-1,0,12); - } - - public static void main(String[] args) { - - Scanner in = new Scanner(System.in); - int num= in.nextInt(); - int[] arr = new int[num]; - for (int i = 0; i < num; i++) { - arr[i]= in.nextInt(); - } - printCombination(arr); - } - -} diff --git a/Coding_Ninjas/src/main/java/com/cleo/skillTest2/Test.java b/Coding_Ninjas/src/main/java/com/cleo/skillTest2/Test.java deleted file mode 100644 index 7ea634d..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/skillTest2/Test.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.cleo.skillTest2; - -public class Test { - int a; - int b; - Test() - { - this(10, 20); - System.out.print("constructor one "); - } - Test(int a, int b) - { - this.a = a; - this.b = b; - System.out.print("constructor two "); - } - } -class new_test{ - public static void main(String[] args) - { - Test object = new Test(); - } -} diff --git a/Coding_Ninjas/src/main/java/com/cleo/skillTest2/WaterNJugs.java b/Coding_Ninjas/src/main/java/com/cleo/skillTest2/WaterNJugs.java deleted file mode 100644 index bb9eef5..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/skillTest2/WaterNJugs.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.cleo.skillTest2; - -import java.util.Scanner; - -public class WaterNJugs { - - private static int gcd(int a, int b){ - if(a==0){ - return b; - } - return gcd(b%a,a); - } - private static String canJugBeFilled(int a, int b, int c){ - if(a+b0) { - int a = in.nextInt(); - int b = in.nextInt(); - int c = in.nextInt(); - int m = c * b; - int bigger = Math.max(c, m); - int smaller = Math.min(c, m); - - System.out.println(canJugBeFilled(a, b, c)); - } - - - } - - -} diff --git a/Coding_Ninjas/src/main/java/com/cleo/skillTest3/Main.java b/Coding_Ninjas/src/main/java/com/cleo/skillTest3/Main.java deleted file mode 100644 index e0bb837..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/skillTest3/Main.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.cleo.skillTest3; - -public class Main { - - public static void main(String[] args) { - System.out.println("Hi"); - } -} diff --git a/Coding_Ninjas/src/main/java/com/cleo/skillTest3/set4/BracketScore.java b/Coding_Ninjas/src/main/java/com/cleo/skillTest3/set4/BracketScore.java deleted file mode 100644 index e934e8d..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/skillTest3/set4/BracketScore.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.cleo.skillTest3.set4; - -import java.util.Stack; - -public class BracketScore { - - static public int scoreOfParentheses(String S) { - // Write your code here - int ans = 0; - Stack valueStack = new Stack<>(); - Stack operatorStack = new Stack<>(); - Character add = '+', - multiply = '*'; - int n = S.length(); - for(int i = 0; i < n; i++){ - char currChar = S.charAt(i); - if(currChar == '('){ - if (ans!=0) { - valueStack.push(ans); - operatorStack.push(add); - ans = 0; - } - valueStack.push(3); - operatorStack.push(multiply); - } - else{ - Integer value = valueStack.pop(); - Character op = operatorStack.pop(); - while(op.equals(add)){ - ans = ans + value; - value = valueStack.pop(); - op = operatorStack.pop(); - } - if(op.equals(multiply)){ - if(ans==0){ - ans = value; - } - else{ - ans = ans * value; - } - } - } - } - while(!valueStack.isEmpty()){ - Integer value = valueStack.pop(); - Character op = operatorStack.pop(); - if(op.equals(add)){ - ans = ans + value; - } - else{ - if(ans==0){ - ans = value; - } - else{ - ans = ans * value; - } - } - } - return ans; - } - - public static void main(String[] args) { - System.out.println(scoreOfParentheses("(()(()))")); - } -} diff --git a/Coding_Ninjas/src/main/java/com/cleo/skillTest3/set4/MaximumSumBST.java b/Coding_Ninjas/src/main/java/com/cleo/skillTest3/set4/MaximumSumBST.java deleted file mode 100644 index 2c9aa46..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/skillTest3/set4/MaximumSumBST.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.cleo.skillTest3.set4; - -class BinaryTreeNode { - T data; - BinaryTreeNode left; - BinaryTreeNode right; - - public BinaryTreeNode(T data) { - this.data = data; - this.left = null; - this.right = null; - } -} - -class Pair { - T minimum; - U maximum; - - public Pair(T minimum, U maximum) { - this.minimum = minimum; - this.maximum = maximum; - } - -} - -public class MaximumSumBST { - static public int maxSumBST(BinaryTreeNode root) { - // Write your code here - if (root == null) return 0; - int[] A = new int[ 4 ]; - fun(root, A); - return A[ 1 ]; - } - - public static void fun(BinaryTreeNode root, int[] A) { - int rootData = root.data.intValue(); - if (root.left == null && root.right == null) { - A[ 0 ] = 1; // isBST; 1 if true; 0 if false - A[ 1 ] = rootData; // maxSum - A[ 2 ] = rootData; // minimum node - A[ 3 ] = rootData; // maximum node - return; - } - if (root.left == null) { - fun(root.right, A); - if (A[ 0 ] == 1 && rootData < A[ 2 ]) { - A[ 1 ] += rootData; // update maxSum - A[ 2 ] = rootData; // minimum node - } else { - A[ 0 ] = 0; // not a BST - } - return; - } - if (root.right == null) { - fun(root.left, A); - if (A[ 0 ] == 1 && rootData > A[ 3 ]) { - A[ 1 ] += rootData; // update maxSum - A[ 3 ] = rootData; // maximum node - } else { - A[ 0 ] = 0; // not a BST - } - return; - } - fun(root.left, A); - int leftBST = A[ 0 ], - leftMaxSum = A[ 1 ], - leftMin = A[ 2 ], - leftMax = A[ 3 ]; - fun(root.right, A); - int rightBST = A[ 0 ], - rightMaxSum = A[ 1 ], - rightMin = A[ 2 ], - rightMax = A[ 3 ]; - if ((leftBST & rightBST) == 1 && rootData > leftMax && rootData < rightMin) { - A[ 1 ] = leftMaxSum + rootData + rightMaxSum; - A[ 2 ] = leftMin; - A[ 3 ] = rightMax; - } else { - A[ 0 ] = 0; // not a BST - A[ 1 ] = (leftMaxSum > rightMaxSum ? leftMaxSum : rightMaxSum); - } - - } - - public static void main(String[] args) { - - } -} diff --git a/Coding_Ninjas/src/main/java/com/cleo/skillTest4/AdjacentBitCounts.java b/Coding_Ninjas/src/main/java/com/cleo/skillTest4/AdjacentBitCounts.java deleted file mode 100644 index c4e3100..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/skillTest4/AdjacentBitCounts.java +++ /dev/null @@ -1,220 +0,0 @@ -package com.cleo.skillTest4; - -import java.util.Scanner; - -public class AdjacentBitCounts { - /*code in c++ ***************************************************** - -#include -using namespace std; -typedef long long ll; -#define m 1000000007 -ll dp[101][101][2]; -ll f(int n, int k, int start) -{ - if (dp[n][k][start] >= 0) - { - return dp[n][k][start]; - } - if (n == 1) - { - if (k == 0) - { - dp[n][k][start] = 1; - return 1; - } - else - { - dp[n][k][start] = 0; - return 0; - } - } - if (k < 0) - { - dp[n][k][start] = 0; - return 0; - } - if (start == 1) - { - ll sum1 = f(n - 1, k - 1, 1); - ll sum2 = f(n - 1, k, 0); - dp[n][k][start] = (sum1 + sum2) % m; - } - else - { - ll sum1 = f(n - 1, k, 1) % m; - ll sum2 = f(n - 1, k, 0) % m; - dp[n][k][start] = (sum1 + sum2) % m; - } - return dp[n][k][start]; -} -ll adjbc(int n, int k) -{ - ll sum1 = f(n, k, 1) % m; - ll sum2 = f(n, k, 0) % m; - return (sum1 + sum2) % m; -} -int main() -{ - int p; - cin >> p; - for (int i = 0; i <= 101; i++) - { - for (int j = 0; j <= 101; j++) - { - for (int k = 0; k < 2; k++) - { - dp[i][j][k] = -1; - } - } - } - while (p--) - { - int dataset_number, n, k; - cin >> dataset_number >> n >> k; - cout << dataset_number << " " << adjbc(n, k) << endl; - } - return 0; -} - - */ - /* -* For a string of n bits x1, x2, x3, …, xn the adjacent bit count of the string (AdjBC(x)) is given by - - - - x1x2 + x2x3 + x3x4 + … + xn-1xn - - - -which counts the number of times a 1 bit is adjacent to another 1 bit. For example: - - - -AdjBC(011101101) = 3 - -AdjBC(111101101) = 4 - -AdjBC(010101010) = 0 - -Write a program which takes as input integers n and k and returns the number of bit strings x of n bits (out of 2ⁿ) that satisfy AdjBC(x) = k. For example, for 5 bit strings, there are 6 ways of getting AdjBC(x) = 2: - - - -11100, 01110, 00111, 10111, 11101, 11011 - - - -Input: A decimal integer giving the number (n) of bits in the bit strings, and a decimal integer (k) giving the desired adjacent bit count. The number of bits (n) will not be greater than 100 and the parameters n and k will be chosen so that the result will fit in a signed 32-bit integer. - - -Output: the number of n-bit strings with adjacent bit count equal to k. - - O(n ^ 2) - O(n ^ 2) -* */ - - - - public static int getAdjBCStringCountDP(int n, int k) { - int[][] rightZero = new int[n + 1][k + 1]; - int[][] rightOne = new int[n + 1][k + 1]; - //base case - rightZero[1][0] = 1; - rightOne[1][0] = 1; - //induction rule - for (int size = 2; size <= n; size++) { - rightZero[size][0] = rightZero[size - 1][0] + rightOne[size - 1][0]; - rightOne[size][0] = rightZero[size - 1][0]; - } - - for (int size = 2; size <= n; size++) { - for (int bit = 1; bit <= k; bit++) { - rightZero[size][bit] = rightZero[size - 1][bit] + rightOne[size - 1][bit]; - rightOne[size][bit] = rightZero[size - 1][bit] + rightOne[size - 1][bit - 1]; - } - } - - return rightZero[n][k] + rightOne[n][k]; - } - - public static int getAdjBCStringCountRecursion(int n, int k) { - return rightZero(n, k) + rightOne(n, k); - } - - private static int rightZero(int n, int k) { - //base case - if (n == 1) { - if (k == 0) { - return 1; - } else { - return 0; - } - } - if (k > n - 2) { // 11111 0 -> n = 6, max = 4 - return 0; - } - return rightZero(n - 1, k) + rightOne(n - 1, k); - } - - private static int rightOne(int n, int k) { - //bae case - if (n == 1) { - if (k == 0) { - return 1; - } else { - return 0; - } - } - if (k > n - 1) {// 11111 1 -> n = 6, max = 5 - return 0; - } - return rightZero(n - 1, k) + rightOne(n - 1, k - 1); - } - - public static int getAdjBCStringCountBruteForce(int n, int k) { - int[] sol = new int[1]; - helper(n, k, 1, 0, 233, sol); - return sol[0]; - } - - private static void helper(int n, int k, int index, int oneCount, int prev, int[] count) { - //base case - if (index > n) { - if (oneCount == k) count[0]++; - return; - } - - //0 at this index - if (index == 1) { - helper(n, k, index + 1, oneCount, 0, count); - helper(n, k, index + 1, oneCount, 1, count); - } else { - if (prev == 1) { - //take 0 - helper(n, k, index + 1, oneCount, 0, count); - //take 1 - helper(n, k, index + 1, oneCount + 1, 1, count); - } else {//prev = 0 - //take 0 - helper(n, k, index + 1, oneCount, 0, count); - helper(n, k, index + 1, oneCount, 1, count); - } - } - } - - - - public static void main(String[] args) { - Scanner in = new Scanner(System.in); - int T= in.nextInt(); - while(T-->0){ - int N= in.nextInt(),K= in.nextInt(); - System.out.println(getAdjBCStringCountBruteForce(N,K)); - - - } - - } - } - diff --git a/Coding_Ninjas/src/main/java/com/cleo/skillTest4/CodeBreaker.java b/Coding_Ninjas/src/main/java/com/cleo/skillTest4/CodeBreaker.java deleted file mode 100644 index 95fddbf..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/skillTest4/CodeBreaker.java +++ /dev/null @@ -1,141 +0,0 @@ -package com.cleo.skillTest4; - -import java.io.BufferedOutputStream; -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.util.StringTokenizer; -public class CodeBreaker { - static Trie root; - - static class Trie { - Trie ch[] = new Trie[26]; - int id; - int Minval; - boolean isEnd; - - Trie() { - Minval = 1000001; - isEnd = false; - for (int i = 0; i < 26; i++) - ch[i] = null; - this.id = -1; - } - } - - static void insert(String value, int index) { - Trie node = root; - for (int i = 0; i < value.length(); i++) { - int ind = value.charAt(i) - 'a'; - if (node.ch[ind] == null) { - node.ch[ind] = new Trie(); - - node.ch[ind].Minval = index; - } - - node = node.ch[ind]; - } - node.isEnd = true; - if (node.id == -1) - node.id = index; - } - - static String search(String value, int r) { - Trie node = root; - String s = ""; - int ind = 0; - for (int i = 0; i < value.length(); i++) { - ind = value.charAt(i) - 'a'; - if (node.ch[ind] != null) { - if (node.ch[ind].Minval <= r) { - s += value.charAt(i); - } else - break; - } else { - break; - - } - node = node.ch[ind]; - } - - while (node != null) { - if (node.isEnd == true && node.id <= r) - return s; - else { - for (int i = 0; i < 26; i++) { - if (node.ch[i] != null && node.ch[i].Minval <= r) { - node = node.ch[i]; - s += (char) (i + 'a'); - break; - } - } - } - } - - return s; - - } - - public static class FastReader { - BufferedReader br; - StringTokenizer st; - - public FastReader() { - br = new BufferedReader(new InputStreamReader(System.in)); - } - - String next() { - while (st == null || !st.hasMoreTokens()) { - try { - st = new StringTokenizer(br.readLine()); - } catch (Exception r) { - r.printStackTrace(); - } - } - return st.nextToken(); - } - - int nextInt() { - return Integer.parseInt(next()); - } - - double nextDouble() { - return Double.parseDouble(next()); - } - - long nextLong() { - return Long.parseLong(next()); - } - - String nextLine() { - String str = ""; - try { - str = br.readLine(); - } catch (Exception r) { - r.printStackTrace(); - } - return str; - } - } - - public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); - - public static void main(String[] args) { - FastReader in = new FastReader(); - root = new Trie(); - int n = in.nextInt(); - for (int i = 1; i <= n; i++) - insert(in.next(), i); - - int q = in.nextInt(); - while (q-- > 0) { - int r = in.nextInt(); - String s = in.next(); - System.out.println(search(s, r)); - - } - - - } - -} diff --git a/Coding_Ninjas/src/main/java/com/cleo/skillTest4/JumpingNinja.java b/Coding_Ninjas/src/main/java/com/cleo/skillTest4/JumpingNinja.java deleted file mode 100644 index b2d3f30..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/skillTest4/JumpingNinja.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.cleo.skillTest4; - - -import java.util.Scanner; - -public class JumpingNinja { - /* Jumping Ninja -Send Feedback -Given the heights of N valleys arranged in consecutive manner and an integer M. In one step, Ninja can jump from valley -i to valley -1. i + j where, i + j < number of valleys and 0 < j <= M -2. i - j where, i - j >= 0 and 0 < j <= M -Also, you are allowed to jump from valley i to valley j if height[i] > height[j] and height[i] > height[k] for -valleys k between valley i and valley j. Ninja can start from any valley and start jumping. Determine the maximum -number of valleys he can visit. -Note: Ninja is not allowed to jump to the right of Nth valley and left of 1st valley. (Stay within boundaries). -Input Format: -First line contains an integer t, representing number of test cases -Second line contains two space separated integers N and M. -Third line contains N space separated integers denoting the heights of N valleys. -Constraints: -1 <= N <= 10^4 -1 <= Height[i] <= 10^5 -1 <= M <= N -Time Limit: 1.5 seconds -Output Format: -Determine the maximum number of valleys Ninja can visit. -Sample Input 1: -1 -11 2 -6 4 14 6 8 13 9 7 10 6 12 -Sample Output 1: -4 -Explanation 1: -You can start at valley 11 with height 12. You can jump from valley 11 --> 9 --> 7 --> 8. - */ - public static void main(String[] args) { - Scanner s = new Scanner(System.in); - int N = s.nextInt(); - int M = s.nextInt(); - // ArrayList arr = new ArrayList<>(N); - int[] arr = new int[N]; - for (int i = 0; i < N; i++) arr[i] = s.nextInt(); - if (arr[0] < arr[N - 1]) { - int n = N - 1; - int cnt = 0; - while (n >= 0) { - if (arr[n] > arr[n - 1]) { - if (arr[n] > arr[n - 2]) { - n -= 2; - cnt++; - } else { - n -= 1; - cnt++; - } - } else if (arr[n] > arr[n + 1]) { - if (arr[n] > arr[n + 2]) { - n += 2; - cnt++; - } else { - n += 1; - cnt++; - } - } else if (arr[n] < arr[n - 1]&& arr[n] < arr[n + 1]) { - System.out.println(cnt+1); - return; - } - } - - } else { - int cnt = 0; - int i = 0; - while (i < N - 1) { - if (arr[i] > arr[i + 1]) { - if (arr[i] > arr[i + 2]) { - i += 2; - cnt++; - } else { - i += 1; - cnt++; - } - } else if (arr[i] > arr[i - 1]) { - if (arr[i] > arr[i - 2]) { - i -= 2; - cnt++; - } else { - i -= 1; - cnt++; - } - } else if (arr[i] < arr[i - 1]&& arr[i] < arr[i + 1]) { - System.out.println(cnt+1); - return; - } - } - - - } - } -} \ No newline at end of file diff --git a/Coding_Ninjas/src/main/java/com/cleo/skillTest4/LostRepresentative.java b/Coding_Ninjas/src/main/java/com/cleo/skillTest4/LostRepresentative.java deleted file mode 100644 index 064fe01..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/skillTest4/LostRepresentative.java +++ /dev/null @@ -1,182 +0,0 @@ -package com.cleo.skillTest4; - - -import java.io.*; -import java.util.*; -/* -The Government Public School of Wadiya city is holding a congress of students. The number of representations from each grade is equal to the grade number. From the first grade, the congress has only 1 representative, from the second grade, the congress has only 2 representatives and so on and so forth. All the representatives are told to assemble in the main ground. All the same grade representatives are standing together. -A representative of grade P comes to the stage and says that he is unable to find his group of representatives. The organisers are busy with other tasks. You have to find the group for the lost representative. -The main ground is a huge N*N matrix. You are given this matrix as input. Each representative occupies a cell. An occupied cell is represented by integer 1 and an unoccupied cell by integer 0. All the representatives of the same grade are connected to each other and disconnected from other grade representatives. An occupied cell is said to be connected to those occupied cells which are reachable from its cell. A representative can move across to other occupied cells with which it shares its edges. -For example: -Alt Text -In this diagram of a part of the ground, red coloured cells represents the connected group of sixth grade students, yellow cell represents the connected group of first grade student and green represents the connected group of fourth grade students. -You will be given the matrix and you have to find the starting cell of the connected group of the lost representative. -Starting Cell is the one with the lowest row value. (If row number of two or more cells is same, then starting cell among them is the one with lowest column value) -It may be possible that the representative may be confused, and the grade he says he is from is actually not present. In that case, print starting cell as -1 -1. -Input Format: -First line of input contains integer t, representing the number of test cases. -First line of each test case contains integer n, representing the size of the matrix. -The second line onwards, the next 'N' lines or rows represent the ith row values. -Each of the ith rows constitutes 'N' column values separated by a single space. -Last line of each test case contains integer p, representing the grade of the lost representative. -Constraints: -1 <= N <= 1000 -1 <= p <= 100 -Output Format: -For each test case, you need to print the starting cell of the connected group of the lost representative. -Sample Input 1: -1 -5 -1 1 0 0 0 -0 1 0 0 1 -1 1 0 1 1 -0 0 0 0 0 -1 1 0 0 1 -3 -Sample Output 1: -1 4 -Explanation: -The lost representative is from the 3rd grade. In the given matrix, the 3rd grade is represented by the cluster of 1s where the starting cell of this cluster is 1,4. - */ - -public class LostRepresentative { - static class Cell { - int x; - int y; - - Cell(int x, int y) { - this.x = x; - this.y = y; - } - } - - public static boolean isValid(int n, int i, int j) { - return (i >= 0 && i < n && j >= 0 && j < n); - } - - public static void main(String[] args) throws IOException { - Test sc = new Test(); - int t = sc.nextInt(); - while (t-- > 0) { - int n = sc.nextInt(); - int[][] mat = new int[n][n]; - for (int i = 0; i < n; i++) { - mat[i] = sc.nextIntArray(n); - } - boolean[][] isVisited = new boolean[n][n]; - HashMap hash = new HashMap<>(); - for (int i = 0; i < n; i++) { - for (int j = 0; j < n; j++) { - if (!isVisited[i][j] && mat[i][j] == 1) { - Cell startcell = new Cell(i, j); - Queue q = new LinkedList<>(); - q.add(startcell); - isVisited[i][j] = true; - int count = 1; - - while (!q.isEmpty()) { - Cell thiscell = q.remove(); - if (isValid(n, thiscell.x + 1, thiscell.y) && mat[thiscell.x + 1][thiscell.y] == 1 && !isVisited[thiscell.x + 1][thiscell.y]) { - q.add(new Cell(thiscell.x + 1, thiscell.y)); - count++; - isVisited[thiscell.x + 1][thiscell.y] = true; - } - if (isValid(n, thiscell.x - 1, thiscell.y) && mat[thiscell.x - 1][thiscell.y] == 1 && !isVisited[thiscell.x - 1][thiscell.y]) { - q.add(new Cell(thiscell.x - 1, thiscell.y)); - count++; - isVisited[thiscell.x - 1][thiscell.y] = true; - } - if (isValid(n, thiscell.x, thiscell.y + 1) && mat[thiscell.x][thiscell.y + 1] == 1 && !isVisited[thiscell.x][thiscell.y + 1]) { - q.add(new Cell(thiscell.x, thiscell.y + 1)); - count++; - isVisited[thiscell.x][thiscell.y + 1] = true; - } - if (isValid(n, thiscell.x, thiscell.y - 1) && mat[thiscell.x][thiscell.y - 1] == 1 && !isVisited[thiscell.x][thiscell.y - 1]) { - q.add(new Cell(thiscell.x, thiscell.y - 1)); - count++; - isVisited[thiscell.x][thiscell.y - 1] = true; - } - } - - hash.put(count, startcell); - } - } - } - - int r = sc.nextInt(); - if (hash.containsKey(r)) - System.out.println((hash.get(r).x) + " " + (hash.get(r).y)); - else System.out.println("-1 -1"); - } - - sc.close(); - } - - static class Test { - final private int BUFFER_SIZE = 1 << 18; - final private DataInputStream din; - final private byte[] buffer; - private PrintWriter pw; - private int bufferPointer, bytesRead; - StringTokenizer st; - - public Test() { - din = new DataInputStream(System.in); - buffer = new byte[BUFFER_SIZE]; - bufferPointer = bytesRead = 0; - } - - public void println(String a) { - pw.println(a); - } - - public void print(String a) { - pw.print(a); - } - - public int[] nextIntArray(int n) throws IOException { - int[] arr = new int[n]; - for (int i = 0; i < n; i++) { - arr[i] = nextInt(); - } - - return arr; - } - - - public int nextInt() throws IOException { - int ret = 0; - byte c = read(); - while (c <= ' ') - c = read(); - boolean neg = (c == '-'); - if (neg) - c = read(); - do { - ret = ret * 10 + c - '0'; - } while ((c = read()) >= '0' && c <= '9'); - - if (neg) - return -ret; - return ret; - } - - private void fillBuffer() throws IOException { - bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); - if (bytesRead == -1) - buffer[0] = -1; - } - - private byte read() throws IOException { - if (bufferPointer == bytesRead) - fillBuffer(); - return buffer[bufferPointer++]; - } - - public void close() throws IOException { - if (din != null) din.close(); - if (pw != null) pw.close(); - } - } - -} \ No newline at end of file diff --git a/Coding_Ninjas/src/main/java/com/cleo/skillTest4/WhiteSubTree.java b/Coding_Ninjas/src/main/java/com/cleo/skillTest4/WhiteSubTree.java deleted file mode 100644 index 49dde6d..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/skillTest4/WhiteSubTree.java +++ /dev/null @@ -1,199 +0,0 @@ -package com.cleo.skillTest4; - - -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.InputMismatchException; - -public class WhiteSubTree { - static class InputReader { - private final InputStream stream; - private final byte[] buf = new byte[8192]; - private int curChar, snumChars; - public InputReader(InputStream st) { - this.stream = st; - } - public int read() { - if (snumChars == -1) - throw new InputMismatchException(); - if (curChar >= snumChars) { - curChar = 0; - try { - snumChars = stream.read(buf); - } - catch (IOException e) { - throw new InputMismatchException(); - } - if (snumChars <= 0) - return -1; - } - return buf[curChar++]; - } - public int ni() { - int c = read(); - while (isSpaceChar(c)) { - c = read(); - } - int sgn = 1; - if (c == '-') { - sgn = -1; - c = read(); - } - int res = 0; - do { - res *= 10; - res += c - '0'; - c = read(); - } while (!isSpaceChar(c)); - return res * sgn; - } - public long nl() { - int c = read(); - while (isSpaceChar(c)) { - c = read(); - } - int sgn = 1; - if (c == '-') { - sgn = -1; - c = read(); - } - long res = 0; - do { - res *= 10; - res += c - '0'; - c = read(); - } while (!isSpaceChar(c)); - return res * sgn; - } - public int[] nia(int n) { - int a[] = new int[n]; - for (int i = 0; i < n; i++) { - a[i] = ni(); - } - return a; - } - public String rs() { - int c = read(); - while (isSpaceChar(c)) { - c = read(); - } - StringBuilder res = new StringBuilder(); - do { - res.appendCodePoint(c); - c = read(); - } while (!isSpaceChar(c)); - return res.toString(); - } - public String nextLine() { - int c = read(); - while (isSpaceChar(c)) - c = read(); - StringBuilder res = new StringBuilder(); - do { - res.appendCodePoint(c); - c = read(); - } while (!isEndOfLine(c)); - return res.toString(); - } - public boolean isSpaceChar(int c) { - return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; - } - - private boolean isEndOfLine(int c) { - return c == '\n' || c == '\r' || c == -1; - } - } - public static class Key { - - private final int x; - private final int y; - - public Key(int x, int y) { - this.x = x; - this.y = y; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Key)) return false; - Key key = (Key) o; - return x == key.x && y == key.y; - } - - @Override - public int hashCode() { - int result = x; - result = 31 * result + y; - return result; - } - - } - - static PrintWriter w = new PrintWriter(System.out); - static long mod=998244353L,mod1=1000000007; - static int co[][]; - static void dsort(){ - Arrays.parallelSort(co,(o1, o2)->o1[0]!=o2[0]?o1[0]-o2[0]:o1[1]-o2[1]); - } - static class Pair{ - int w,b; - public Pair(int w,int b){ - this.b=b; - this.w=w; - } - } - static int c[],dp[],n,ans[]; - static ArrayList arr[]; - static int dfs(int i,int p){ - int di=-1; - if(c[i]==1)di=1; - for(int j:arr[i]){ - if(j!=p){ - di+=(Math.max(0,dfs(j,i))); - } - } - - return dp[i] =di; - } - static void dfs1(int i,int p){ - for(int j:arr[i]){ - if(j!=p){ - if(dp[j]<0){ - dp[j]+=Math.max(0,dp[i]); - } - else{ - dp[j]+=Math.max(0,dp[i]-dp[j]); - } - dfs1(j,i); - } - } - } - public static void main (String[] args)throws IOException { - InputReader sc=new InputReader(System.in); - n=sc.ni(); - c=new int[n+1]; - dp=new int[n+1]; - ans=new int[n+1]; - arr=new ArrayList[n+1]; - for(int i=1;i<=n;i++){ - c[i]=sc.ni(); - arr[i]=new ArrayList<>(); - } - for(int i=0;i map = new HashMap<>(); - int max = Integer.MIN_VALUE; - HashMap map = new HashMap<>(); - for (int i = 0; i < s.length(); i++) { - if (map.containsKey(s.charAt(i)) == false) { - map.put(s.charAt(i), i); - } else { - int distance = i - map.get(s.charAt(i)); - if (distance > max) { - max = distance; - } - } - } - if (max == Integer.MIN_VALUE) { - return -1; - } else { - return max - 1; - } - } - - - public static void main(String[] args) { - /* Your class should be named Main. - * Read input as specified in the question. - * Print output as specified in the question. - */ - - // Write your code here - InputStream inputStream = System.in; - InputReader in = new InputReader(inputStream); - int N = in.nextInt(); - while(N-->0){ - String s = in.next(); - System.out.println(maxCharactersBetweenSameCharacters(s)); - } - - } - static class InputReader { - public BufferedReader reader; - public StringTokenizer tokenizer; - - public InputReader(InputStream stream) { - reader = new BufferedReader(new InputStreamReader(stream), 32768); - tokenizer = null; - } - - public String next() { - while (tokenizer == null || !tokenizer.hasMoreTokens()) { - try { - tokenizer = new StringTokenizer(reader.readLine()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - return tokenizer.nextToken(); - } - - public int nextInt() { - return Integer.parseInt(next()); - } - } - - -} - - diff --git a/Coding_Ninjas/src/main/java/com/cleo/test7/HelpAroma.java b/Coding_Ninjas/src/main/java/com/cleo/test7/HelpAroma.java deleted file mode 100644 index e5b2a38..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/test7/HelpAroma.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.cleo.test7; - -import java.util.HashMap; -import java.util.Map; -import java.util.Scanner; - -public class HelpAroma { - - private static boolean areAnagrams(String s1, String s2){ - Map map = new HashMap<>(); - for(char c: s1.toCharArray()){ - map.compute(c,(k,v)->v==null?1:++v); - } - for(char c:s2.toCharArray()){ - if(map.get(c)!=null&&map.get(c)!=0) - map.put(c,map.get(c)-1); - else - return false; - } - return true; - } - public static void main(String[] args) { - Scanner in = new Scanner(System.in); - String s= in.nextLine(); - int N = in.nextInt(); - while(N-->0) { - String s1 = (s.substring(in.nextInt() - 1, in.nextInt())); - String s2 = (s.substring(in.nextInt() - 1, in.nextInt())); - if (s1.length() != s2.length()) { - System.out.println(false); - } else - - System.out.println(areAnagrams(s1, s2)); - } - - } -} diff --git a/Coding_Ninjas/src/main/java/com/cleo/test7/MaximumInvitations.java b/Coding_Ninjas/src/main/java/com/cleo/test7/MaximumInvitations.java deleted file mode 100644 index 68a8827..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/test7/MaximumInvitations.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.cleo.test7; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.Arrays; -import java.util.StringTokenizer; -import java.util.function.Function; - -public class MaximumInvitations { - private static int perimeter(int width, int height){ - return width*2+height*2; - } - private static int calculateMaxAreaOfTable(char[][] room, int n, int m) { - int[] count = new int[m]; - int max = 0; - for (int i = 0; i < n; i++) { - for (int j = 0; j < m; j++) { - if (room[i][j] == '.') { - count[j]++; - } else { - count[j] = 0; - } - - } - for (int j = 0; j < m; j++) { - int h = count[j]; - int w = 1; - if (h > 0) { - for (int k = j + 1; k < m; k++) { - if (count[k] < h) - break; - w++; - - } - for (int k = j - 1; k > 0; k--) { - if (count[k] < h) - break; - w++; - } - } - max = Math.max(max, perimeter(w,h)); - } - - } - return max - 1; - - } - - public static void main(String[] args) { - /* Your class should be named Main. - * Read input as specified in the question. - * Print output as specified in the question. - */ - - // Write your code here - InputStream inputStream = System.in; - InputReader in = new InputReader(inputStream); - int n = in.nextInt(); - int m= in.nextInt(); - char[][] room=new char[n][m]; - for (int i = 0; i < n; i++) { - room[i]=in.next().toCharArray(); - } - System.out.println(calculateMaxAreaOfTable(room,n,m)); - - - - } - static class InputReader { - public BufferedReader reader; - public StringTokenizer tokenizer; - - public InputReader(InputStream stream) { - reader = new BufferedReader(new InputStreamReader(stream), 32768); - tokenizer = null; - } - - public String next() { - while (tokenizer == null || !tokenizer.hasMoreTokens()) { - try { - tokenizer = new StringTokenizer(reader.readLine()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - return tokenizer.nextToken(); - } - - public int nextInt() { - return Integer.parseInt(next()); - } - } - -} diff --git a/Coding_Ninjas/src/main/java/com/cleo/test7/TeamSelection.java b/Coding_Ninjas/src/main/java/com/cleo/test7/TeamSelection.java deleted file mode 100644 index f6ae5e4..0000000 --- a/Coding_Ninjas/src/main/java/com/cleo/test7/TeamSelection.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.cleo.test7; - -import java.util.Scanner; - -public class TeamSelection { - - private static void generateCombinations(int[] arr, int N, int current, String result){ - if(N==0){ - System.out.println(result); - return; - } - if(current==arr.length) - return; - generateCombinations(arr,N-1,current+1,result+arr[current]+" "); - generateCombinations(arr,N,current+1,result); - } - public static void main(String[] args) { - Scanner s = new Scanner (System.in); - int [] arr = new int [s.nextInt()]; - for(int i=0; i= boardSize || y < 0 || y >= boardSize ||board[x][y] != EMPTY){ - return INVALIDMOVE; - } - - board[x][y] = symbol; - count++; - -// Check Row - if(board[x][0] == board[x][1] && board[x][0] == board[x][2]){ - return symbol == p1Symbol ? PLAYER1WINS :PLAYER2WINS; - } -// Check Col - if(board[0][y] == board[1][y] && board[0][y] == board[2][y]){ - return symbol == p1Symbol ? PLAYER1WINS :PLAYER2WINS; - } -// First Diagonal - if(board[0][0] != EMPTY && board[0][0] == board[1][1] && board[0][0] == board[2][2]){ - return symbol == p1Symbol ? PLAYER1WINS :PLAYER2WINS; - } -// Second Diagonal - if(board[0][2] != EMPTY && board[0][2] == board[1][1] && board[0][2] == board[2][0]){ - return symbol == p1Symbol ? PLAYER1WINS :PLAYER2WINS; - } - - if(count == boardSize * boardSize){ - return DRAW; - } - return INCOMPLETE; - } - public void print() { - System.out.println("---------------"); - for(int i =0; i < boardSize; i++){ - for(int j =0; j < boardSize; j++){ - System.out.print("| " + board[i][j] + " |"); - } - System.out.println(); - } - System.out.println(); - System.out.println("---------------"); - } -} \ No newline at end of file diff --git a/Coding_Ninjas/src/main/java/tictactoe/Player.java b/Coding_Ninjas/src/main/java/tictactoe/Player.java deleted file mode 100644 index 72f4e12..0000000 --- a/Coding_Ninjas/src/main/java/tictactoe/Player.java +++ /dev/null @@ -1,33 +0,0 @@ -package tictactoe; - -public class Player { - - private String name; - private char symbol; - - public Player(String name, char symbol) { - setName(name); - setSymbol(symbol); - } - - public void setName(String name) { - - if(!name.isEmpty()) { - this.name = name; - } - } - - public String getName() { - return this.name; - } - - public void setSymbol(char symbol) { - if(symbol != '\0') { - this. symbol = symbol; - } - } - - public char getSymbol() { - return this.symbol; - } -} \ No newline at end of file diff --git a/Coding_Ninjas/src/main/java/tictactoe/TicTacToe.java b/Coding_Ninjas/src/main/java/tictactoe/TicTacToe.java deleted file mode 100644 index e5e7aa9..0000000 --- a/Coding_Ninjas/src/main/java/tictactoe/TicTacToe.java +++ /dev/null @@ -1,82 +0,0 @@ -package tictactoe; - -import java.util.Scanner; - -public class TicTacToe { - - private Player player1, player2; - private Board board; - private int numPlayers; - - public static void main(String args[]){ - TicTacToe t = new TicTacToe(); - t.startGame(); - } - - public void startGame(){ - Scanner s = new Scanner(System.in); -// Take Players input - player1 = takePlayerInput(++numPlayers); - player2 = takePlayerInput(++numPlayers); - while(player1.getSymbol() == player2.getSymbol()){ - System.out.println("Symbol Already taken !! Pick another symbol !!"); - player2.setSymbol(s.next().charAt(0)); - } - -// Create the Board - board = new Board(player1.getSymbol(), player2.getSymbol()); - -// Play the game - boolean player1Turn = true; - int status = Board.INCOMPLETE; - while(status == Board.INCOMPLETE || status == Board.INVALIDMOVE){ - if(player1Turn){ - System.out.println("Player 1 - " + player1.getName() + "'s turn"); - System.out.println("Enter x: "); - int x = s.nextInt(); - System.out.println("Enter y: "); - int y = s.nextInt(); - - status = board.move(player1.getSymbol(), x, y); - - if(status == Board.INVALIDMOVE){ - System.out.println("Invalid move !! Please try again !!"); - continue; - } - }else{ - System.out.println("Player 2 - " + player2.getName() + "'s turn"); - System.out.println("Enter x: "); - int x = s.nextInt(); - System.out.println("Enter y: "); - - int y = s.nextInt(); - status = board.move(player2.getSymbol(), x, y); - - if(status == Board.INVALIDMOVE){ - System.out.println("Invalid move !! Please try again !!"); - continue; - } - } - player1Turn=!player1Turn; - board.print(); - } - if(status == Board.PLAYER1WINS){ - System.out.println("Player 1 - " + player1.getName() +"wins !!"); - - }else if(status == Board.PLAYER2WINS){ - System.out.println("Player 2 - " + player2.getName() +"wins !!"); - } else { - System.out.println("Draw !!"); - } - } - - private Player takePlayerInput(int num){ - Scanner s = new Scanner(System.in); - System.out.println("Enter Player " + num + " name: "); - String name = s.nextLine(); - System.out.println("Enter Player " + num + " symbol: "); - char symbol = s.next().charAt(0); - Player p = new Player(name, symbol); - return p; - } -} \ No newline at end of file diff --git a/Coding_Ninjas/src/main/resources/NestedLists.html b/Coding_Ninjas/src/main/resources/NestedLists.html deleted file mode 100644 index cbfd71d..0000000 --- a/Coding_Ninjas/src/main/resources/NestedLists.html +++ /dev/null @@ -1,124 +0,0 @@ - - - - Best Coding Practices - - - - -

Best Coding Practices for Hassle-free Programming

-

- - Just like with any other activity, the world of coding is also governed by informal rules. Most of these rules are - formulated over decades. Programming languages often remain in usage for longer than their founders expect. -

- -

- - Programmers find innovative ways to recreate these languages for different purposes. Thus, some static do’s and - don’ts are always of use in the fluid zone called coding. Normally, a great code has three common features: - maintainability, dependability, and usability. It should also be adaptable enough to be efficient even in changing - environments. However, before coding even begins, a few prerequisites need to be fulfilled in order to provide a - solid foundation on which readable code can be written. -

- -

PREREQUISITES

-

- - This is easily the most important step of all. In absence of these, a code may be inefficient even if it is - completed. The prerequisites that need to be in place for an efficient code covers matters like design and - architecture. An important question is how development is structured. What is the specific purpose of the software? - The problem that the code is meant to solve must be clear to the developer. What is the design of the individual - components? Such basic requirements have to be fulfilled when a good code is being written. -

-

- - Hoare makes a good point when it comes to assessing software design and architecture. Either a code is so simple - that there are obviously no errors, or a code is so complex that there are no obvious errors. Software design is - also of importance to clients, who can decide if their needs are being adequately addressed. If there are some - things that architecture cannot take care of, then those are handled in the software design phase. A detailed design - is a good guide for coding. -

-

- The next step is to measure existing programming languages against the requirements to decide on an appropriate one. - If needed, a mixed routine can be adopted. -

-

- Once these are met, it becomes easier to follow some established good coding practices. -

-
    - -
  • COMMENTING

    -

    - - Commenting is one such practice that is often ignored by programmers, especially for codes that are written by - multiple programmers. However, comments reduce the cost of knowledge transfer. Name of the module, purpose of the - module, description of the module, original author, modifications and authors who modified code with a description - on why it was modified were components of an early commenting practice. -

    -
  • -
  • GOOD NAMING CONVENTIONS

    -

    - - Using good naming conventions is the next step to good coding. Often developers use Y1 or X1 as variables, and then - do not replace them with meaningful names. To prevent this confusion and utter waste of time, descriptive names - should be used. -

    - -
  • -
  • -

    SIMPLICITY AND COMPACTNESS

    -

    - - The key to a good code is also simplicity. To achieve a certain result, developers may use complex logic but this - should be minimised while writing a good code. The next developer who uses the code may use it for a different - purpose and may not even completely understand or utilise the complex logic. Simple code does not always depend on - the length of the code. The code must also be conceptually simple. An added advantage is if the code is also - suitably compact. More code can be viewed on a page and programmer keystrokes can be reduced. -

    -
  • -
  • -

    PORTABILITY

    -

    - - Another feature of a good code is portability. If the code contains values referring to ‘absolute parameters’ - such as file names, URLs or IP addresses, it will not run on a host that is of a different design. A good programmer - will parametrize these variables and configure them so the application can also be run and maintained in a different - environment. -

    -
  • -
  • -

    TESTING

    -

    - - Testing is also a necessary part in the process of coding. Test cases must be planned while the code is being - written, and they are developed while an application is coded. -

    -
  • -
  • -

    DEBUGGING THE CODE

    -

    - - While writing a code, it is necessary to check for errors throughout. Though it is fine for smaller programs to be - debugged after they have been written, this becomes a bottleneck for longer programmes. The best practice, - therefore, is to debug each module as soon as it has been created. -

    -
  • -
  • -

    DEPLOYMENT

    -

    - - Once the code has been written, it has to be deployed. The installation files should be kept to a minimum and - updated regularly. Unused code or anything that is not necessary should not be installed. -

    -

    - - The best practices for coding are, most of all, designed to reduce risk whenever there are chances of it. For a - beginner, a few of these will not be completely applicable. But as a hard-boiled programmer writing numerous codes, - all these guidelines will come in handy. Since codes can run up to millions of lines at times, outdated advice like - ‘keep it simple’ or ‘less is more’ is priceless and should always be remembered. -

    -
  • -
- - \ No newline at end of file diff --git a/Coding_Ninjas/src/main/resources/blog.html b/Coding_Ninjas/src/main/resources/blog.html deleted file mode 100644 index b5ac5e7..0000000 --- a/Coding_Ninjas/src/main/resources/blog.html +++ /dev/null @@ -1,124 +0,0 @@ - - - - Best Coding Practices - - - - -

Best Coding Practices for Hassle-free Programming

-

- - Just like with any other activity, the world of coding is also governed by informal rules. Most of these rules are - formulated over decades. Programming languages often remain in usage for longer than their founders expect. -

- -

- - Programmers find innovative ways to recreate these languages for different purposes. Thus, some static do’s and - don’ts are always of use in the fluid zone called coding. Normally, a great code has three common features: - maintainability, dependability, and usability. It should also be adaptable enough to be efficient even in changing - environments. However, before coding even begins, a few prerequisites need to be fulfilled in order to provide a - solid foundation on which readable code can be written. -

- -

PREREQUISITES

-

- - This is easily the most important step of all. In absence of these, a code may be inefficient even if it is - completed. The prerequisites that need to be in place for an efficient code covers matters like design and - architecture. An important question is how development is structured. What is the specific purpose of the software? - The problem that the code is meant to solve must be clear to the developer. What is the design of the individual - components? Such basic requirements have to be fulfilled when a good code is being written. -

-

- - Hoare makes a good point when it comes to assessing software design and architecture. Either a code is so simple - that there are obviously no errors, or a code is so complex that there are no obvious errors. Software design is - also of importance to clients, who can decide if their needs are being adequately addressed. If there are some - things that architecture cannot take care of, then those are handled in the software design phase. A detailed design - is a good guide for coding. -

-

- The next step is to measure existing programming languages against the requirements to decide on an appropriate one. - If needed, a mixed routine can be adopted. -

-

- Once these are met, it becomes easier to follow some established good coding practices. -

-
    - -
  • COMMENTING

    -

    - - Commenting is one such practice that is often ignored by programmers, especially for codes that are written by - multiple programmers. However, comments reduce the cost of knowledge transfer. Name of the module, purpose of the - module, description of the module, original author, modifications and authors who modified code with a description - on why it was modified were components of an early commenting practice. -

    -
  • -
  • GOOD NAMING CONVENTIONS

    -

    - - Using good naming conventions is the next step to good coding. Often developers use Y1 or X1 as variables, and then - do not replace them with meaningful names. To prevent this confusion and utter waste of time, descriptive names - should be used. -

    - -
  • -
  • -

    SIMPLICITY AND COMPACTNESS

    -

    - - The key to a good code is also simplicity. To achieve a certain result, developers may use complex logic but this - should be minimised while writing a good code. The next developer who uses the code may use it for a different - purpose and may not even completely understand or utilise the complex logic. Simple code does not always depend on - the length of the code. The code must also be conceptually simple. An added advantage is if the code is also - suitably compact. More code can be viewed on a page and programmer keystrokes can be reduced. -

    -
  • -
  • -

    PORTABILITY

    -

    - - Another feature of a good code is portability. If the code contains values referring to ‘absolute parameters’ - such as file names, URLs or IP addresses, it will not run on a host that is of a different design. A good programmer - will parametrize these variables and configure them so the application can also be run and maintained in a different - environment. -

    -
  • -
  • -

    TESTING

    -

    - - Testing is also a necessary part in the process of coding. Test cases must be planned while the code is being - written, and they are developed while an application is coded. -

    -
  • -
  • -

    DEBUGGING THE CODE

    -

    - - While writing a code, it is necessary to check for errors throughout. Though it is fine for smaller programs to be - debugged after they have been written, this becomes a bottleneck for longer programmes. The best practice, - therefore, is to debug each module as soon as it has been created. -

    -
  • -
  • -

    DEPLOYMENT

    -

    - - Once the code has been written, it has to be deployed. The installation files should be kept to a minimum and - updated regularly. Unused code or anything that is not necessary should not be installed. -

    -

    - - The best practices for coding are, most of all, designed to reduce risk whenever there are chances of it. For a - beginner, a few of these will not be completely applicable. But as a hard-boiled programmer writing numerous codes, - all these guidelines will come in handy. Since codes can run up to millions of lines at times, outdated advice like - ‘keep it simple’ or ‘less is more’ is priceless and should always be remembered. -

    -
  • -
- - \ No newline at end of file diff --git a/Coding_Ninjas/src/main/resources/imagesOnBlog.html b/Coding_Ninjas/src/main/resources/imagesOnBlog.html deleted file mode 100644 index 965c1c9..0000000 --- a/Coding_Ninjas/src/main/resources/imagesOnBlog.html +++ /dev/null @@ -1,9 +0,0 @@ - - - - - Title - - - - \ No newline at end of file diff --git a/Coding_Ninjas/src/main/resources/stupidity.html b/Coding_Ninjas/src/main/resources/stupidity.html deleted file mode 100644 index 61985be..0000000 --- a/Coding_Ninjas/src/main/resources/stupidity.html +++ /dev/null @@ -1,57 +0,0 @@ - - - - - Title - - -

My name is:Deven Kalra

-
-
    -
  • -

    My favorite books

    -
      - -
    • Harry Potter
    • -
    • The God of Small Things
    • -
    • The Prophet
    • -
    -
  • -
  • -

    My favorite books

    -
      - -
    • Harry Potter
    • -
    • The God of Small Things
    • -
    • The Prophet
    • -
    -
  • - - -
-
    -
  1. -

    My favorite books

    -
      - -
    1. Harry Potter
    2. -
    3. The God of Small Things
    4. -
    5. The Prophet
    6. -
    - - -
  2. - - -
  3. -

    My favorite books

    -
      - -
    1. Harry Potter
    2. -
    3. The God of Small Things
    4. -
    5. The Prophet
    6. -
    -
  4. -
- - \ No newline at end of file diff --git a/Coding_Ninjas/src/main/resources/unorderedList.html b/Coding_Ninjas/src/main/resources/unorderedList.html deleted file mode 100644 index 9eb0673..0000000 --- a/Coding_Ninjas/src/main/resources/unorderedList.html +++ /dev/null @@ -1,34 +0,0 @@ - - - - Learn Lists - - - -

- A front-end developer has to keep himself/herself updated continuously with the latest news and innovations in the field. You need to take a proactive stand and learn new things about front-end development from informative blogs and videos. Following are some of the most informative and useful learning sources for front-end developers - -

- - - - -
    -
  • Frontend Focus
  • -
  • CSS Weekly
  • -
  • Javascript Weekly
  • -
  • Web Design Weekly
  • -
-
-      This is
-      preformatted text.
-      It preserves      both spaces
-      and line breaks and shows the text in a monospace font.
-      
-

The pre tag is good for displaying computer code:

-
-      for i = 1 to 10
-            print i
-      next i
-
- - \ No newline at end of file diff --git a/Core_Java/src/main/java/com/cleo/revision/try_with/InputFile.java b/Core_Java/src/main/java/com/cleo/revision/try_with/InputFile.java index 2268d24..491a893 100644 --- a/Core_Java/src/main/java/com/cleo/revision/try_with/InputFile.java +++ b/Core_Java/src/main/java/com/cleo/revision/try_with/InputFile.java @@ -2,6 +2,11 @@ import java.io.*; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.Date; import java.util.StringTokenizer; @@ -46,8 +51,18 @@ public int nextInt() { } } - public static String getDataFromFileC() { + public static String getDataFromFileC() throws IOException { String file = System.getProperties().get("user.dir").toString()+"/resources/hi.js"; + File f = new File(file); + //boolean b =f.createNewFile(); + //LocalDateTime time = LocalDateTime.now().toLocalDate().; + var d = LocalDate.of(2001,1,3); + Date date = new Date(); + var m=date.toInstant().getEpochSecond(); + System.out.println(m); + boolean x=f.setLastModified(m); + System.out.println("Changed modification time:"+x); + try(BufferedReader reader = new BufferedReader(new FileReader(file))) { while (reader.read() != -1) { System.out.println(reader.readLine()); @@ -58,7 +73,7 @@ public static String getDataFromFileC() { return "Done"; } - public static void main(String[] args) { + public static void main(String[] args) throws IOException { ClassLoader classloader = Thread.currentThread().getContextClassLoader(); //InputStream in = new BufferedInputStream(classloader.getResourceAsStream("resources/hi.js")); diff --git a/Core_Java/src/main/java/com/cleo/revision/visitorPattern/EvalVisitor.java b/Core_Java/src/main/java/com/cleo/revision/visitorPattern/EvalVisitor.java index 5e56316..05f60c3 100644 --- a/Core_Java/src/main/java/com/cleo/revision/visitorPattern/EvalVisitor.java +++ b/Core_Java/src/main/java/com/cleo/revision/visitorPattern/EvalVisitor.java @@ -4,7 +4,12 @@ sealed interface Node{ int eval(); } -record Symbol(char x){ } +record Symbol(char x){ + @Override + public String toString() { + return String.valueOf(x); + } +} record BinOp(Node left, Node right){ } @@ -14,12 +19,39 @@ public int eval() { return -node; } } -interface NodeVisitor{ - T visit(IntNode node); - T visit(SubNode left,SubNode right); - T visit(AddNode left, AddNode right); - T visit(MulNode left, MulNode right); - T visit(DivNode left, DivNode right); +interface NodeVisitor{ + Integer visit(IntNode node); + Integer visit(SubNode left,SubNode right); + Integer visit(AddNode left, AddNode right); + Integer visit(MulNode left, MulNode right); + Integer visit(DivNode left, DivNode right); +} + +class Visitor implements NodeVisitor{ + @Override + public Integer visit(IntNode node) { + return node.eval(); + } + + @Override + public Integer visit(SubNode left, SubNode right) { + return left.eval() - right.eval(); + } + + @Override + public Integer visit(AddNode left, AddNode right) { + return left.eval()+ right.eval(); + } + + @Override + public Integer visit(MulNode left, MulNode right) { + return left.eval()* right.eval(); + } + + @Override + public Integer visit(DivNode left, DivNode right) { + return left.eval()/ right.eval(); + } } record IntNode(int node) implements Node{ @@ -30,9 +62,15 @@ public int eval() { } } record SubNode(Node left,Node right) implements Node{ + @Override public int eval() { - return left.eval() - right().eval(); + return left().eval()- right().eval(); + } + + @Override + public String toString() { + return String.valueOf(left().eval() - right().eval()); } } record AddNode(Node left,Node right) implements Node{ @@ -54,21 +92,34 @@ public int eval() { return left.eval()/right().eval(); } } +class ClassNotFoundException extends Exception{ + public ClassNotFoundException(String message){ + System.out.println(message); + } +} +public class EvalVisitor{ -public class EvalVisitor { public int eval(Node n) { - return switch (n){ - case IntNode(var i)->i; - case NegNode(var i)-> -i; - case AddNode(Node left,Node right) -> eval(left) + eval(right); - case MulNode(Node left,Node right) -> eval(left) * eval(right); - case DivNode(Node left,Node right) -> eval(left) / eval(right); - case SubNode(Node left,Node right) -> eval(left) - eval(right); + try { + return switch (n) { + case IntNode(var i) -> i; + case NegNode(var i) -> -i; + case AddNode(Node left, Node right) -> eval(left) + eval(right); + case MulNode(Node left, Node right) -> eval(left) * eval(right); + case DivNode(Node left, Node right) -> eval(left) / eval(right); + case SubNode(Node left, Node right) -> eval(left) - eval(right); + + + }; + } catch (Exception e) { + System.out.println(e); - default -> throw new IllegalStateException("Unknown type: " + n); - }; + } + return -1; } + + public static void main(String[] args) { EvalVisitor visitor = new EvalVisitor(); //Add(Add(2,Sub(2,3)); @@ -78,15 +129,18 @@ public static void main(String[] args) { * MulNode(x,2), */ EvalVisitor x = new EvalVisitor(); + //Redo without thinking of patterns... int first=x.eval(new MulNode(new IntNode(2),new IntNode(2))); int second = x.eval(new MulNode(new IntNode(3),new DivNode(new IntNode(3),new IntNode(2)))); - Integer third = new IntNode(1).eval(); + int third = new IntNode(1).eval(); System.out.println(first-second-third);//0 System.out.println(visitor.eval(new AddNode(new IntNode(2), new IntNode(3))));//5 + Visitor v = new Visitor(); + //v.visit(new AddNode(new IntNode(2)),new AddNode(3)) } } diff --git a/Core_Java/src/main/resources/h b/Core_Java/src/main/resources/h new file mode 100644 index 0000000..e2a0689 --- /dev/null +++ b/Core_Java/src/main/resources/h @@ -0,0 +1,2 @@ +asd +asdf \ No newline at end of file diff --git a/Employee_Management/src/main/java/com/cleo/hr/personnel/Employee.java b/Employee_Management/src/main/java/com/cleo/hr/personnel/Employee.java index 6bc6d11..093a91d 100644 --- a/Employee_Management/src/main/java/com/cleo/hr/personnel/Employee.java +++ b/Employee_Management/src/main/java/com/cleo/hr/personnel/Employee.java @@ -7,6 +7,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.Arrays; /* Models an employee form a business perspective @@ -30,7 +31,7 @@ public Employee(String fullName, int monthlyIncome){ public String getEmail() { return this.firstName + "." + this.lastName + - "@globomanticshr.com"; + "@cleo.com"; } @Override @@ -43,7 +44,8 @@ public String toString() { sb.append(getFullName()); sb.append(System.lineSeparator()); sb.append("POSITION: "); - String type = this.getClass().getTypeName(); + String type = this.getClass().getName(); + System.out.println(this.getClass().getName().split("\\.")[4]); type = type.substring(type.lastIndexOf('.') + 1); sb.append(type); sb.append(System.lineSeparator()); @@ -83,22 +85,7 @@ public void setNbHoursPerWeek(int nbHoursPerWeek) { this.nbHoursPerWeek = nbHoursPerWeek; } - /* public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } -*/ public String getFullName(){ return this.firstName + " " + this.lastName; } diff --git a/Magda_Iovan.json b/Magda_Iovan.json new file mode 100644 index 0000000..21d57c1 --- /dev/null +++ b/Magda_Iovan.json @@ -0,0 +1 @@ +{"firstName":"Magda","lastName":"Iovan","monthlyIncome":920,"nbHoursPerWeek":20} \ No newline at end of file diff --git a/Software_Construction/src/main/java/com/cleo/design_patterns/builderPattern/Main.java b/Software_Construction/src/main/java/com/cleo/design_patterns/builderPattern/Main.java index 2e134b2..3c39d14 100644 --- a/Software_Construction/src/main/java/com/cleo/design_patterns/builderPattern/Main.java +++ b/Software_Construction/src/main/java/com/cleo/design_patterns/builderPattern/Main.java @@ -14,9 +14,13 @@ enum Test{ONE,TWO,THREE}; tests.add(Test.ONE); System.out.println(tests); NyPizza pizza = new NyPizza.Builder(SMALL) - .addTopping(SAUSAGE).addTopping(ONION).build(); + .addTopping(SAUSAGE) + .addTopping(ONION) + .build(); Calzone calzone = new Calzone.Builder() - .addTopping(HAM).sauceInside().build(); + .addTopping(HAM) + .sauceInside() + .build(); // AccessibleObject.setAccessible(NyPizza.class,true); System.out.println(pizza); System.out.println(calzone); diff --git a/Steve_Jones.json b/Steve_Jones.json new file mode 100644 index 0000000..b3d6115 --- /dev/null +++ b/Steve_Jones.json @@ -0,0 +1,6 @@ +{ + "firstName" : "Steve", + "lastName" : "Jones", + "monthlyIncome" : 800, + "nbHoursPerWeek" : 20 +} \ No newline at end of file diff --git a/Coding_Ninjas/pom.xml b/demo/pom.xml similarity index 52% rename from Coding_Ninjas/pom.xml rename to demo/pom.xml index 6530781..ef79ba1 100644 --- a/Coding_Ninjas/pom.xml +++ b/demo/pom.xml @@ -3,30 +3,21 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - - - - org.apache.maven.plugins - maven-compiler-plugin - - 17 - 17 - - - - com.cleo Java_Coding_Interview 1.0-SNAPSHOT - Coding_Ninjas + demo - 18 - 18 + 24 + 24 UTF-8 + + + \ No newline at end of file diff --git a/demo/src/main/java/com/cleo/Main.java b/demo/src/main/java/com/cleo/Main.java new file mode 100644 index 0000000..cfc2689 --- /dev/null +++ b/demo/src/main/java/com/cleo/Main.java @@ -0,0 +1,17 @@ +package com.cleo; + +//TIP To Run code, press or +// click the icon in the gutter. +public class Main { + public static void main(String[] args) { + //TIP Press with your caret at the highlighted text + // to see how IntelliJ IDEA suggests fixing it. + System.out.println("Hello and welcome!"); + + for (int i = 1; i <= 5; i++) { + //TIP Press to start debugging your code. We have set one breakpoint + // for you, but you can always add more by pressing . + System.out.println("i = " + i); + } + } +} \ No newline at end of file diff --git a/demo/src/main/java/com/cleo/Test.java b/demo/src/main/java/com/cleo/Test.java new file mode 100644 index 0000000..e3585e8 --- /dev/null +++ b/demo/src/main/java/com/cleo/Test.java @@ -0,0 +1,45 @@ +package com.cleo; + + +import java.time.LocalDate; +import java.util.Date; +import java.util.Objects; + +public record Test(String a, String b) { + + /* @Override + public String a() { + return "Deven"; + + } + + @Override + public String b() { + return "Kalra" + }*/ + + + + + public String toString() { + if(a==null || b==null) + return null; + + /*Objects.requireNonNull(a,"a cannot be null"); + Objects.requireNonNull(b,"a cannot be null"); +*/ + + return a + " " + b; + } + + public static void main(String[] args) { + Test test = new Test("Deven","Kalra"); + Test test1 = new Test(null,null); + LocalDate date = LocalDate.now(); + System.out.println(date); + // System.out.println(date); + System.out.println(test1 ); + Date date1 = new Date(); + System.out.println(date.getYear() + " " + date1.toInstant()); + } +} diff --git a/pom.xml b/pom.xml index c5d6827..110a34c 100644 --- a/pom.xml +++ b/pom.xml @@ -34,6 +34,7 @@ Core_Java Software_Construction Blockchain + demo UTF-8 @@ -140,11 +141,7 @@ jmh-generator-annprocess 1.35 - - org.ow2.asm - asm - 9.3 - + nu.pattern