├── .gitignore ├── Algorithms ├── Bit Manipulation │ ├── FlippingBits.m │ └── LonlyInteger.java ├── Greedy │ ├── Flowers.java │ ├── MarkAndToys.java │ ├── PriyankaandToys.java │ └── TwoArrays.java ├── Implementation │ ├── AngryProfessor.java │ ├── AppleAndOrange.java │ ├── BeautifulDaysAtTheMovies.java │ ├── BonAppetit.java │ ├── CavityMap.java │ ├── CeasarCipher.java │ ├── ChocolateFeast.java │ ├── CutTheSticks.java │ ├── DivisibleSumPairs.java │ ├── Encryption.java │ ├── EqualizeTheArray.playground │ │ ├── Contents.swift │ │ ├── contents.xcplayground │ │ └── playground.xcworkspace │ │ │ └── contents.xcworkspacedata │ ├── ExtraLongFactorial.java │ ├── FairRations.playground │ │ ├── Contents.swift │ │ ├── contents.xcplayground │ │ └── playground.xcworkspace │ │ │ └── contents.xcworkspacedata │ ├── FindDigits.java │ ├── FlatlandsSpaceStations.playground │ │ ├── Contents.swift │ │ ├── contents.xcplayground │ │ └── playground.xcworkspace │ │ │ └── contents.xcworkspacedata │ ├── GradingStudents.java │ ├── JumpingOnTheClouds.java │ ├── JumpingOnTheCloudsRevisited.java │ ├── Kangaroo.java │ ├── LibraryFine.java │ ├── LisaWorkBook.java │ ├── MatrixLayerRotation.java │ ├── MiniMaxSum.java │ ├── MiniumumDistances.playground │ │ ├── Contents.swift │ │ ├── contents.xcplayground │ │ └── playground.xcworkspace │ │ │ └── contents.xcworkspacedata │ ├── ModifiedKaprekarNumbers.java │ ├── RepeatedString.java │ ├── SaveThePrisoner.java │ ├── ServiceLane.java │ ├── SherlockAndTheBeast.java │ ├── SockMerchant.playground │ │ ├── Contents.swift │ │ ├── contents.xcplayground │ │ ├── playground.xcworkspace │ │ │ └── contents.xcworkspacedata │ │ └── timeline.xctimeline │ ├── StrangeCounter.java │ ├── TaumAndBday.java │ ├── TheBomberGame.java │ └── UtopianTree.m ├── Search │ ├── IceCreamParlor.java │ └── Pairs.java ├── Sorting │ ├── InsertionSort.java │ ├── InsertionSortPart2.java │ └── SherlockAndPairs.java ├── Strings │ ├── AlternatingCharacters.java │ ├── BeautifulBinaryString.java │ ├── CamelCase.java │ ├── FunnyStrings.java │ ├── GemStones.java │ ├── Pangrams.java │ └── TheLoveLetterMistery.java └── Warmup │ ├── CircularArrayRotation.java │ ├── DiagonalDifference.java │ ├── PlusMinus.java │ ├── SavethePrisoner.java │ ├── SimpleArraySum.java │ ├── SolveMeFirst.m │ ├── SolveMeSecond.c │ ├── StairCase.java │ ├── StrangeCounter.java │ ├── TimeConversion.java │ ├── VeryBigSum.java │ └── ViralAdvertising.java ├── Code Golf └── F.java ├── Contests ├── May World CodeSprint │ └── ComparetheTriplets.mm ├── CodeWhiz.java 2016 │ ├── ComparetheTriplets.java │ ├── CovariantReturnTypes.java │ ├── JavaLambdaExpressions.java │ ├── JavaList.java │ ├── JavaPrimalityTest.java │ ├── JavaSingleton.java │ ├── MaximumandMinimum.java │ └── ServetheStudents.java ├── EpicCode CodeSprint │ └── PerfectHiring.java ├── Indeed Prime CodeSprint │ ├── GretchenAndPlay.java │ └── TheUlitmateQuestion.java ├── OpenBracket CodeSprint │ ├── FraudulentActivityNotifications.java │ └── ViralAdvertising.java ├── TechHire CodeSprint │ ├── ComparetheTriplets.java │ ├── FindPrefix.java │ ├── HackerRankTournament.java │ └── PaintTheClassRoom.java ├── Week of Code - 16 │ └── SomeOfAbsolute.java ├── World CodeSprint │ └── MarsExploration.java └── Zenefits CodeSprint │ ├── EncryptionModule.java │ └── MiseryofJarJarBinks.java ├── Java ├── Advanced │ ├── CanYouAccess.java │ ├── JavaAnnotations.java │ ├── JavaFactory.java │ ├── JavaReflection.java │ ├── JavaVarargs.java │ └── PrimeChecker.java ├── Big Number │ ├── BigInteger.java │ └── JavaBigDecimal.java ├── Collections │ ├── Java1DArray.java │ ├── Java1DArrayHard.java │ ├── Java1DTestCase.txt │ ├── Java2DArray.java │ ├── JavaArrayList.java │ ├── JavaComparator.java │ ├── JavaDeque.java │ ├── JavaGenerics.java │ ├── JavaHashSet.java │ ├── JavaMap.java │ ├── JavaSort.java │ └── JavaStack.java ├── Exception Handling │ ├── JavaExceptionHandling.java │ └── JavaExceptionHandlingTryCatch.java ├── Introduction │ ├── JavaDatatypes.java │ ├── JavaEOF.java │ ├── JavaLoops.java │ ├── JavaStaticInitBlock.java │ └── WelcomeToJava.java ├── Object Oriented Programming │ ├── CalculatingVolume.java │ ├── JavaAbstractClass.java │ ├── JavaInheritance1.java │ ├── JavaInheritance2.java │ ├── JavaInstanceOf.java │ ├── JavaInterface.java │ ├── JavaIterator.java │ ├── JavaMethodOverriding.java │ └── JavaMethodOverriding2.java └── Strings │ ├── JavaAnagrams.java │ ├── JavaRegex.java │ ├── JavaRegex2.java │ ├── JavaRegex3.java │ ├── JavaStringCompare.java │ ├── JavaStringReverse.java │ ├── JavaStringToken.java │ ├── JavaStrings.java │ ├── PatternSyntaxChecker.java │ └── TagContentExtractor.java └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | ..bfg-report 2 | .idea 3 | **/.DS_Store 4 | -------------------------------------------------------------------------------- /Algorithms/Bit Manipulation/FlippingBits.m: -------------------------------------------------------------------------------- 1 | /* Flipping Bits 2 | 3 | You will be given a list of 32 bits unsigned integers. You are required to output the list of the unsigned integers you get by flipping bits in its binary representation (i.e. unset bits must be set, and set bits must be unset). 4 | 5 | Input Format 6 | 7 | The first line of the input contains the list size T, which is followed by T lines, each line having an integer from the list. 8 | 9 | Constraints 10 | 11 | 1≤T≤100 12 | 0≤integer<2^32 13 | Output Format 14 | 15 | Output one line per element from the list with the requested result. 16 | */ 17 | 18 | #import 19 | 20 | 21 | int main (int argc, const char * argv[]) { 22 | NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 23 | int numInput; 24 | scanf("%d", &numInput); 25 | for(int i=0;i alStr = new ArrayList(Arrays.asList(sc.nextLine().split(" "))); 28 | String answer=""; 29 | int pos = 0; 30 | while(alStr.size()>1){ 31 | answer = alStr.get(0); 32 | alStr.remove(0); 33 | if(!alStr.contains(answer)){ 34 | break; 35 | }else{ 36 | alStr.remove(answer); 37 | } 38 | pos++; 39 | 40 | } 41 | System.out.println(alStr.size()!=1?answer:alStr.get(0)); 42 | } 43 | } -------------------------------------------------------------------------------- /Algorithms/Greedy/Flowers.java: -------------------------------------------------------------------------------- 1 | /* Flowers 2 | You and your K-1 friends want to buy N flowers. Flower number i has cost ci. Unfortunately the seller does not want just one customer to buy a lot of flowers, so he tries to change the price of flowers for customers who have already bought some flowers. More precisely, if a customer has already bought x flowers, he should pay (x+1)*ci dollars to buy flower number i. 3 | You and your K-1 friends want to buy all N flowers in such a way that you spend the least amount of money. You can buy the flowers in any order. 4 | 5 | Input: 6 | 7 | The first line of input contains two integers N and K (K <= N). The next line contains N space separated positive integers c1,c2,...,cN. 8 | 9 | Output: 10 | 11 | Print the minimum amount of money you (and your friends) have to pay in order to buy all N flowers. 12 | */ 13 | 14 | 15 | import java.io.*; 16 | import java.util.*; 17 | 18 | public class Flowers { 19 | 20 | public static void main(String[] args) { 21 | /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ 22 | Scanner sc = new Scanner(System.in); 23 | ArrayList flowerPriceList = new ArrayList(); 24 | int numFlowers = sc.nextInt(); 25 | int numFriends = sc.nextInt(); 26 | for(int i = 0; icurrentToy+4){ 52 | count++; 53 | currentToy=numArray[i]; 54 | } 55 | } 56 | System.out.println(count); 57 | } 58 | } -------------------------------------------------------------------------------- /Algorithms/Greedy/TwoArrays.java: -------------------------------------------------------------------------------- 1 | /* 2 | Two Arrays 3 | 4 | You are given two integer arrays, A and B, each containing N integers. The size of the array is 5 | less than or equal to 1000. You are free to permute the order of the elements in the arrays. 6 | 7 | Now here's the real question: Is there an permutation A', B' possible of A and B, such that, A'i+B'i ≥ K 8 | for all i, where A'i denotes the ith element in the array A' and B'i denotes ith element in the array B'. 9 | 10 | 11 | Input Format 12 | The first line contains an integer, T, the number of test-cases. T test cases follow. Each test case has the following format: 13 | 14 | The first line contains two integers, N and K. The second line contains N space separated integers, d 15 | enoting array A. The third line describes array B in a same format. 16 | 17 | Output Format 18 | For each test case, if such an arrangement exists, output "YES", otherwise "NO" (without quotes). 19 | 20 | 21 | Constraints 22 | 1 <= T <= 10 23 | 1 <= N <= 1000 24 | 1 <= K <= 109 25 | 0 <= Ai, Bi ≤ 109 26 | 27 | 28 | Sample Input 29 | 30 | 2 31 | 3 10 32 | 2 1 3 33 | 7 8 9 34 | 4 5 35 | 1 2 2 1 36 | 3 3 3 4 37 | 38 | Sample Output 39 | 40 | YES 41 | NO 42 | */ 43 | 44 | import java.io.*; 45 | import java.util.*; 46 | import java.text.*; 47 | import java.math.*; 48 | import java.util.regex.*; 49 | 50 | public class TwoArrays { 51 | 52 | public static void main(String[] args) { 53 | 54 | Scanner sc = new Scanner(System.in); 55 | int numTestCases = Integer.parseInt(sc.nextLine()); 56 | for(int i = 0;i0) 17 | indicate the student arrived ai minutes late. 18 | 19 | Output Format 20 | 21 | For each test case, print the word YES if the class is canceled or NO if it is not. 22 | 23 | Constraints 24 | 25 | 1≤T≤10 26 | 1≤N≤1000 27 | 1≤K≤N 28 | −100≤ai≤100,where i∈[1,N] 29 | Note 30 | If a student arrives exactly on time (ai=0), the student is considered to have entered before the class started. 31 | 32 | Sample Input 33 | 34 | 2 35 | 4 3 36 | -1 -3 4 2 37 | 4 2 38 | 0 -1 2 1 39 | 40 | Sample Output 41 | 42 | YES 43 | NO 44 | */ 45 | 46 | import java.io.*; 47 | import java.util.*; 48 | import java.text.*; 49 | import java.math.*; 50 | import java.util.regex.*; 51 | 52 | public class AngryProfessor { 53 | 54 | public static void main(String[] args) { 55 | 56 | Scanner sc = new Scanner(System.in); 57 | int numCases=Integer.parseInt(sc.nextLine()); 58 | for(int i = 0;i=atLeastNumStudents?"NO":"YES"); 71 | } 72 | } 73 | } -------------------------------------------------------------------------------- /Algorithms/Implementation/AppleAndOrange.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Apple and Orange 4 | https://www.hackerrank.com/challenges/apple-and-orange 5 | 6 | */ 7 | 8 | 9 | import java.io.*; 10 | import java.util.*; 11 | import java.text.*; 12 | import java.math.*; 13 | import java.util.regex.*; 14 | 15 | public class Solution { 16 | 17 | public static boolean didHitHouse(int s, int t, int treePos, int d) 18 | { 19 | int fallenFruitPos = treePos + d; 20 | return s <= fallenFruitPos && fallenFruitPos <= t; 21 | } 22 | 23 | public static void main(String[] args) { 24 | Scanner in = new Scanner(System.in); 25 | int s = in.nextInt(); 26 | int t = in.nextInt(); 27 | int a = in.nextInt(); 28 | int b = in.nextInt(); 29 | int m = in.nextInt(); 30 | int n = in.nextInt(); 31 | 32 | int hitCount = 0; 33 | for(int apple_i=0; apple_i < m; apple_i++){ 34 | int distance = in.nextInt(); 35 | if (distance > 0) { 36 | if (didHitHouse(s, t, a, distance)) hitCount++; 37 | } 38 | } 39 | System.out.println(hitCount); 40 | 41 | hitCount = 0; 42 | for(int orange_i=0; orange_i < n; orange_i++){ 43 | int distance = in.nextInt(); 44 | if (distance < 0) { 45 | if (didHitHouse(s, t, b, distance)) hitCount++; 46 | } 47 | } 48 | System.out.println(hitCount); 49 | 50 | } 51 | } -------------------------------------------------------------------------------- /Algorithms/Implementation/BeautifulDaysAtTheMovies.java: -------------------------------------------------------------------------------- 1 | /* Beautiful Days at the Movies 2 | 3 | https://www.hackerrank.com/challenges/beautiful-days-at-the-movies 4 | 5 | */ 6 | 7 | import java.io.*; 8 | import java.util.*; 9 | import java.text.*; 10 | import java.math.*; 11 | import java.util.regex.*; 12 | 13 | public class BeautifulDaysAtTheMovies { 14 | 15 | public static int reverseNum(int num) 16 | { 17 | String numStr = "" + num; 18 | String reverseNumStr = ""; 19 | 20 | for(int i = numStr.length() - 1;i >= 0;i--){ 21 | reverseNumStr = reverseNumStr + numStr.charAt(i); 22 | } 23 | 24 | return Integer.parseInt(reverseNumStr); 25 | } 26 | 27 | public static boolean isNumBeautiful(int num, int k) 28 | { 29 | return Math.abs(num - reverseNum(num)) % k == 0; 30 | } 31 | 32 | public static void main(String[] args) 33 | { 34 | Scanner sc = new Scanner(System.in); 35 | int numOne = sc.nextInt(); 36 | int numTwo = sc.nextInt(); 37 | int k = sc.nextInt(); 38 | int total = 0; 39 | for(int i = numOne; i <= numTwo; i++){ 40 | if(isNumBeautiful(i,k)) total++; 41 | } 42 | System.out.println(total); 43 | } 44 | } -------------------------------------------------------------------------------- /Algorithms/Implementation/BonAppetit.java: -------------------------------------------------------------------------------- 1 | /* 2 | Bon Appétit 3 | https://www.hackerrank.com/challenges/bon-appetit 4 | */ 5 | import java.io.*; 6 | import java.util.*; 7 | import java.text.*; 8 | import java.math.*; 9 | import java.util.regex.*; 10 | 11 | public class BonAppetit { 12 | 13 | public static void main(String[] args) { 14 | 15 | Scanner sc = new Scanner(System.in); 16 | int numItems = sc.nextInt(); 17 | int nthItem = sc.nextInt(); 18 | int totalSum = 0; 19 | int[] items = new int[numItems]; 20 | 21 | for(int i = 0;i < numItems;i++){ 22 | items[i] = sc.nextInt(); 23 | totalSum += items[i]; 24 | } 25 | 26 | int annasCharge = sc.nextInt(); 27 | if(nthItem == 0){ 28 | if(totalSum == annasCharge){ 29 | System.out.println("Bon Appetit"); 30 | } else { 31 | System.out.println("" + (annasCharge - totalSum)); 32 | } 33 | } else { 34 | if(annasCharge == (totalSum - items[nthItem]) /2 ){ 35 | System.out.println("Bon Appetit"); 36 | }else{ 37 | System.out.println("" + (annasCharge - (totalSum - items[nthItem])/2)); 38 | } 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /Algorithms/Implementation/CavityMap.java: -------------------------------------------------------------------------------- 1 | /* Cavity Map 2 | You are given a square map of size n×n. Each cell of the map has a value denoting its depth. We will call a cell of the map a cavity if and only if this cell is not on the border of the map and each cell adjacent to it has strictly smaller depth. Two cells are adjacent if they have a common side (edge). 3 | 4 | You need to find all the cavities on the map and depict them with the uppercase character X. 5 | 6 | Input Format 7 | 8 | The first line contains an integer, n, denoting the size of the map. Each of the following n lines contains n positive digits without spaces. Each digit (1-9) denotes the depth of the appropriate area. 9 | 10 | Constraints 11 | 1≤n≤100 12 | Output Format 13 | 14 | Output n lines, denoting the resulting map. Each cavity should be replaced with character X. 15 | */ 16 | 17 | import java.io.*; 18 | import java.util.*; 19 | import java.text.*; 20 | import java.math.*; 21 | import java.util.regex.*; 22 | 23 | public class CavityMap { 24 | 25 | public static void printMapWithCavities(char[][]map, int mapSize) 26 | { 27 | 28 | for(int row = 1;row < mapSize-1;row++){ 29 | for(int column = 1; column < mapSize-1;column++){ 30 | int cellDepth = map[row][column]; 31 | if(cellDepth>map[row][column+1] && cellDepth>map[row][column-1] && cellDepth>map[row-1][column] && cellDepth>map[row+1][column]){ 32 | map[row][column] = 'X'; 33 | } 34 | } 35 | } 36 | for(int row = 0;row0); 60 | return candyAte; 61 | } 62 | } 63 | 64 | -------------------------------------------------------------------------------- /Algorithms/Implementation/CutTheSticks.java: -------------------------------------------------------------------------------- 1 | /* Cut The Sticks 2 | 3 | You are given N sticks, where the length of each stick is a positive integer. A cut operation is performed on the sticks such that all of them are reduced by the length of the smallest stick. 4 | 5 | Suppose we have six sticks of the following lengths: 6 | 7 | 5 4 4 2 2 8 8 | Then, in one cut operation we make a cut of length 2 from each of the six sticks. For the next cut 9 | operation four sticks are left (of non-zero length), whose lengths are the following: 10 | 11 | 3 2 2 6 12 | The above step is repeated until no sticks are left. 13 | 14 | Given the length of N sticks, print the number of sticks that are left before each subsequent cut operations. 15 | 16 | Note: For each cut operation, you have to recalcuate the length of smallest sticks (excluding zero-length sticks). 17 | 18 | Input Format 19 | The first line contains a single integer N. 20 | The next line contains N integers: a0, a1,...aN-1 separated by space, where ai represents the length of ith stick. 21 | 22 | Output Format 23 | For each operation, print the number of sticks that are cut, on separate lines. 24 | 25 | Constraints 26 | 1 ≤ N ≤ 1000 27 | 1 ≤ ai ≤ 1000 28 | 29 | Sample Input #00 30 | 31 | 6 32 | 5 4 4 2 2 8 33 | Sample Output #00 34 | 35 | 6 36 | 4 37 | 2 38 | 1 39 | Sample Input #01 40 | 41 | 8 42 | 1 2 3 4 3 3 2 1 43 | 44 | Sample Output #01 45 | 46 | 8 47 | 6 48 | 4 49 | 1 50 | */ 51 | 52 | import java.io.*; 53 | import java.util.*; 54 | import java.text.*; 55 | import java.math.*; 56 | import java.util.regex.*; 57 | 58 | public class Solution { 59 | 60 | public static void main(String[] args) { 61 | 62 | Scanner sc = new Scanner(System.in); 63 | ArrayList sticks = new ArrayList(); 64 | int numSticks = Integer.parseInt(sc.nextLine()); 65 | for(int i = 0;i0){ 69 | Collections.sort(sticks); 70 | int shortestStick = sticks.get(0); 71 | 72 | int pos = 0; 73 | System.out.println(sticks.size()); 74 | while(pos0){ 78 | sticks.set(pos,num); 79 | pos++; 80 | }else{ 81 | sticks.remove(pos); 82 | 83 | } 84 | 85 | } 86 | 87 | 88 | } 89 | } 90 | } -------------------------------------------------------------------------------- /Algorithms/Implementation/DivisibleSumPairs.java: -------------------------------------------------------------------------------- 1 | //https://www.hackerrank.com/challenges/divisible-sum-pairs 2 | 3 | /* 4 | You are given an array of n integers, a0,a1,....,a(n-1), and a positive integer, k. Find and print the number of (i,j) pairs where i < j and a(i) + a(j) is evenly divisible by k. 5 | 6 | Input Format 7 | 8 | The first line contains 2 space-separated integers, n and k, respectively. 9 | The second line contains n space-separated integers describing the respective values of a0, a1,...,a(n-1). 10 | 11 | Constraints 12 | - 2 <= n <= 100 13 | - 1 <= k <= 100 14 | - 1 <= ai <= 100 15 | Output Format 16 | 17 | Print the number of (i,j) pairs where i < j and ai + aj is evenly divisible by k. 18 | 19 | Sample Input 20 | 21 | 6 3 22 | 1 3 2 6 1 2 23 | 24 | Sample Output 25 | 26 | 5 27 | 28 | */ 29 | 30 | import java.util.Scanner; 31 | 32 | class DivisibleSumPairs { 33 | public static void main(String args[]) { 34 | Scanner sc = new Scanner(System.in); 35 | int n = sc.nextInt(); 36 | int k = sc.nextInt(); 37 | int a[] = new int[n]; 38 | for (int i = 0; i < n; i++) { 39 | a[i] = sc.nextInt(); 40 | } 41 | int cnt = 0; 42 | for (int i = 0; i < n - 1; i++) { 43 | for (int j = i + 1; j < n; j++) { 44 | if ((a[i] + a[j]) % k == 0) 45 | cnt++; 46 | } 47 | } 48 | System.out.println(cnt); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Algorithms/Implementation/Encryption.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | import java.text.*; 4 | import java.math.*; 5 | import java.util.regex.*; 6 | 7 | public class Encryption { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | String s = in.nextLine(); 12 | 13 | int rows = (int) Math.floor(Math.sqrt(s.length())); 14 | int columns = (int) Math.ceil(Math.sqrt(s.length())); 15 | if(rows*columns < s.length())rows ++; 16 | String[][] encryptArray = new String[rows][columns]; 17 | 18 | int r = 0; 19 | int c = 0; 20 | for(int i = 0; i < s.length();i++){ 21 | encryptArray[r][c] = ""+s.charAt(i); 22 | if(c == columns - 1){ 23 | c = -1; 24 | r++; 25 | } 26 | c++; 27 | } 28 | 29 | String encryptedString = ""; 30 | for(int k = 0;k < columns;k++){ 31 | for(int i = 0;i < rows;i++){ 32 | encryptedString = encryptedString + (encryptArray[i][k] != null?encryptArray[i][k]:""); 33 | } 34 | encryptedString +=" "; 35 | } 36 | 37 | System.out.println(encryptedString); 38 | } 39 | } 40 | 41 | -------------------------------------------------------------------------------- /Algorithms/Implementation/EqualizeTheArray.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Equalize the Array 4 | 5 | https://www.hackerrank.com/challenges/equality-in-a-array 6 | 7 | */ 8 | import Foundation 9 | 10 | public func getLine() -> String { 11 | var buf = String() 12 | var ch = getchar() 13 | // 10 is ascii code for newline 14 | while ch != EOF && ch != 10 { 15 | buf = buf + "\(ch)" 16 | ch = getchar() 17 | } 18 | return buf 19 | } 20 | 21 | public func readLn() -> [String] { 22 | return getLine().components(separatedBy: CharacterSet.whitespaces) 23 | } 24 | 25 | public func readLine() -> [Int] { 26 | let words: [String] = readLn() 27 | return words.map { Int($0)! } 28 | } 29 | 30 | let numIntegers: [Int] = readLine() 31 | let input: [Int] = readLine() 32 | 33 | var numDictionary = [Int : Int]() 34 | 35 | var maxNumOccurrences = 1 36 | 37 | var pos = 0 38 | 39 | for num in input { 40 | if let numPos = numDictionary[num] { 41 | numDictionary[num]! += 1 42 | if numDictionary[num]! > maxNumOccurrences { 43 | maxNumOccurrences = numDictionary[num]! 44 | } 45 | } else { 46 | numDictionary[num] = 1 47 | } 48 | pos+=1 49 | } 50 | 51 | print("\(input.count - maxNumOccurrences)") -------------------------------------------------------------------------------- /Algorithms/Implementation/EqualizeTheArray.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /Algorithms/Implementation/EqualizeTheArray.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Algorithms/Implementation/ExtraLongFactorial.java: -------------------------------------------------------------------------------- 1 | /* Extra Long Factorials 2 | 3 | You are given an integer N. Print the factorial of this number. 4 | 5 | N!=N×(N−1)×(N−2)×⋯×3×2×1 6 | Input 7 | Input consists of a single integer N, where 1≤N≤100. 8 | 9 | Output 10 | Print the factorial of N. 11 | 12 | Example 13 | For an input of 25, you would print 15511210043330985984000000. 14 | 15 | Note: Factorials of N>20 can't be stored even in a 64−bit long long variable. 16 | Big integers must be used for such calculations. Languages like Java, Python, Ruby etc. can handle 17 | big integers, but we need to write additional code in C/C++ to handle huge values. 18 | 19 | We recommend solving this challenge using BigIntegers. 20 | 21 | 22 | */ 23 | 24 | import java.io.*; 25 | import java.util.*; 26 | import java.math.BigInteger; 27 | 28 | public class ExtraLongFactorial { 29 | 30 | public static void main(String[] args) { 31 | 32 | Scanner sc = new Scanner(System.in); 33 | int factorialNum = sc.nextInt(); 34 | BigInteger bigInt = new BigInteger(""+factorialNum); 35 | for(int i = 1;i String { 10 | var buf = String() 11 | var ch = getchar() 12 | // 10 is ascii code for newline 13 | while ch != EOF && ch != 10 { 14 | buf = buf + "\(ch)" 15 | ch = getchar() 16 | } 17 | return buf 18 | } 19 | 20 | public func readLn() -> [String] { 21 | return getLine().components(separatedBy: CharacterSet.whitespaces) 22 | } 23 | 24 | public func readLine() -> [Int] { 25 | let words: [String] = readLn() 26 | return words.map { Int($0)! } 27 | } 28 | 29 | let numSubjects: [Int] = readLine() 30 | var numBreads: [Int] = readLine() 31 | 32 | var sum = 0 33 | var count = 0 34 | 35 | numBreads.map {sum+=$0} 36 | 37 | if(sum % 2 != 0) { 38 | print("NO") 39 | } else { 40 | for num in 0.. 2 | 3 | 4 | -------------------------------------------------------------------------------- /Algorithms/Implementation/FairRations.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Algorithms/Implementation/FindDigits.java: -------------------------------------------------------------------------------- 1 | /* Find Digits 2 | You are given an integer N. Find the digits in this number that exactly divide N (division that leaves 0 as remainder) and display their count. For N=24, there are 2 digits (2 & 4). Both of these digits exactly divide 24. So our answer is 2. 3 | 4 | Note 5 | 6 | If the same number is repeated twice at different positions, it should be counted twice, e.g., For N=122, 2 divides 122 exactly and occurs at ones' and tens' position. So for this case, our answer is 3. 7 | Division by 0 is undefined. 8 | Input Format 9 | 10 | The first line contains T (the number of test cases), followed by T lines (each containing an integer N). 11 | 12 | Constraints 13 | 1≤T≤15 14 | 0 String { 11 | var buf = String() 12 | var ch = getchar() 13 | // 10 is ascii code for newline 14 | while ch != EOF && ch != 10 { 15 | buf = buf + "\(ch)" 16 | ch = getchar() 17 | } 18 | return buf 19 | } 20 | 21 | public func readLn() -> [String] { 22 | return getLine().components(separatedBy: CharacterSet.whitespaces) 23 | } 24 | 25 | public func readLine() -> [Int] { 26 | let words: [String] = readLn() 27 | return words.map { Int($0)! } 28 | } 29 | 30 | let info: [Int] = readLine() 31 | var stationLocations: [Int] = readLine() 32 | 33 | var previousStationLocation = -1 34 | 35 | var maxDistance = 0 36 | 37 | var pos = 0 38 | 39 | if info[0] == info[1] { 40 | print(0) 41 | } else { 42 | stationLocations = stationLocations.sorted() 43 | for station in stationLocations { 44 | if previousStationLocation == -1 { 45 | previousStationLocation = station 46 | maxDistance = station 47 | } else { 48 | let distance = (station - previousStationLocation) / 2 49 | maxDistance = max(distance, maxDistance) 50 | previousStationLocation = station 51 | } 52 | } 53 | 54 | print(max(maxDistance,(info[0] - previousStationLocation - 1))) 55 | } -------------------------------------------------------------------------------- /Algorithms/Implementation/FlatlandsSpaceStations.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /Algorithms/Implementation/FlatlandsSpaceStations.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Algorithms/Implementation/GradingStudents.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.math.*; 3 | import java.text.*; 4 | import java.util.*; 5 | import java.util.regex.*; 6 | 7 | public class Solution { 8 | 9 | /* 10 | * Complete the gradingStudents function below. 11 | */ 12 | static int[] gradingStudents(int[] grades) { 13 | for(int i = 0; i < grades.length; i++) { 14 | for(int j = 40; j <= 100; j += 5) { 15 | if(j > grades[i]) { 16 | if(j - grades[i] <= 2) { 17 | grades[i] = j; 18 | } 19 | } 20 | } 21 | } 22 | return grades; 23 | } 24 | 25 | private static final Scanner scan = new Scanner(System.in); 26 | 27 | public static void main(String[] args) throws IOException { 28 | BufferedWriter bw = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); 29 | 30 | int n = Integer.parseInt(scan.nextLine().trim()); 31 | 32 | int[] grades = new int[n]; 33 | 34 | for (int gradesItr = 0; gradesItr < n; gradesItr++) { 35 | int gradesItem = Integer.parseInt(scan.nextLine().trim()); 36 | grades[gradesItr] = gradesItem; 37 | } 38 | 39 | int[] result = gradingStudents(grades); 40 | 41 | for (int resultItr = 0; resultItr < result.length; resultItr++) { 42 | bw.write(String.valueOf(result[resultItr])); 43 | 44 | if (resultItr != result.length - 1) { 45 | bw.write("\n"); 46 | } 47 | } 48 | 49 | bw.newLine(); 50 | 51 | bw.close(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Algorithms/Implementation/JumpingOnTheClouds.java: -------------------------------------------------------------------------------- 1 | /* 2 | Jumping on the Clouds 3 | https://www.hackerrank.com/challenges/jumping-on-the-clouds 4 | */ 5 | 6 | import java.io.*; 7 | import java.util.*; 8 | import java.text.*; 9 | import java.math.*; 10 | import java.util.regex.*; 11 | 12 | public class Solution { 13 | 14 | public static int minJumps(int[] cloudsArray) 15 | { 16 | int currentPos = 0; 17 | int jumpsCount = 0; 18 | 19 | while (currentPos < cloudsArray.length-1){ 20 | if(currentPos + 2 < cloudsArray.length && cloudsArray[currentPos + 2] == 0){ 21 | currentPos+=2; 22 | jumpsCount++; 23 | } else { 24 | currentPos++; 25 | jumpsCount++; 26 | } 27 | } 28 | return jumpsCount; 29 | } 30 | public static void main(String[] args) { 31 | Scanner in = new Scanner(System.in); 32 | int n = in.nextInt(); 33 | int c[] = new int[n]; 34 | for(int c_i=0; c_i < n; c_i++){ 35 | c[c_i] = in.nextInt(); 36 | } 37 | System.out.println(minJumps(c)); 38 | } 39 | } -------------------------------------------------------------------------------- /Algorithms/Implementation/JumpingOnTheCloudsRevisited.java: -------------------------------------------------------------------------------- 1 | /* 2 | Jumping On The Clouds Revisited 3 | https://www.hackerrank.com/challenges/jumping-on-the-clouds-revisited 4 | */ 5 | 6 | 7 | import java.io.*; 8 | import java.util.*; 9 | import java.text.*; 10 | import java.math.*; 11 | import java.util.regex.*; 12 | 13 | public class JumpingOnTheCloudsRevisited { 14 | 15 | public static int energyLeft(int[] cloudsArray, int jumpDistance) 16 | { 17 | int currentPos = 0; 18 | int energyLeft = 100; 19 | 20 | do{ 21 | currentPos = (currentPos + jumpDistance) % cloudsArray.length; 22 | energyLeft--; 23 | if(cloudsArray[currentPos] == 1) energyLeft-=2; 24 | }while (currentPos != 0); 25 | 26 | return energyLeft; 27 | } 28 | public static void main(String[] args) { 29 | Scanner in = new Scanner(System.in); 30 | int n = in.nextInt(); 31 | int k = in.nextInt(); 32 | int c[] = new int[n]; 33 | for(int c_i=0; c_i < n; c_i++){ 34 | c[c_i] = in.nextInt(); 35 | } 36 | System.out.println(energyLeft(c,k)); 37 | } 38 | } -------------------------------------------------------------------------------- /Algorithms/Implementation/Kangaroo.java: -------------------------------------------------------------------------------- 1 | /* 2 | Kangaroo 3 | https://www.hackerrank.com/challenges/kangaroo 4 | */ 5 | 6 | 7 | import java.io.*; 8 | import java.util.*; 9 | import java.text.*; 10 | import java.math.*; 11 | import java.util.regex.*; 12 | 13 | public class Kangaroo { 14 | 15 | public static String willTheyMeat(int firstPos, int firstDistance, int secondPos, int secondDistance) 16 | { 17 | if (firstPos == secondPos) return "YES"; 18 | 19 | while(firstPos < secondPos){ 20 | firstPos+=firstDistance; 21 | secondPos+=secondDistance; 22 | if(firstPos == secondPos) return "YES"; 23 | } 24 | 25 | return "NO"; 26 | } 27 | 28 | public static void main(String[] args) { 29 | Scanner in = new Scanner(System.in); 30 | int x1 = in.nextInt(); 31 | int v1 = in.nextInt(); 32 | int x2 = in.nextInt(); 33 | int v2 = in.nextInt(); 34 | 35 | if(x1 <= x2 && v1 >= v2){ 36 | System.out.println(willTheyMeat(x1,v1,x2,v2)); 37 | } else if (x2 <= x1 && v2 >= v1){ 38 | System.out.println(willTheyMeat(x2,v2,x1,v1)); 39 | } else { 40 | System.out.println("NO"); 41 | } 42 | 43 | } 44 | } -------------------------------------------------------------------------------- /Algorithms/Implementation/LibraryFine.java: -------------------------------------------------------------------------------- 1 | /* Library Fine 2 | 3 | The Head Librarian at a library wants you to create a program that calculates the fine for returning a 4 | book after the return date. You are given the actual and the expected return dates. Calculate the fine as follows: 5 | 6 | If the book is returned on or before the expected return date, no fine will be charged. In other words, the fine is 0. 7 | If the book is returned in the same calendar month as the expected return date, the fine = 15 Hackos × the number of late days. 8 | If the book is not returned in the same calendar month but in the same calendar year as the expected return date, 9 | the fine = 500 Hackos × the number of late months. 10 | If the book is not returned in the same calendar year, the fine is fixed at 10000 Hackos. 11 | Input 12 | You are given the actual and the expected return dates in D M Y format on two separate lines. The first line contains 13 | the D M Y values for the actual return date and the next line contains the D M Y values for the expected return date. 14 | Here's a sample: 15 | 16 | 9 6 2015 17 | 6 6 2015 18 | Constraints: 19 | 1≤D≤31 20 | 1≤M≤12 21 | 1≤Y≤3000 22 | The given date is a valid date on a Gregorian calendar. 23 | 24 | Output 25 | Print a single value representing the fine. 26 | The sample output for the above input would be 45. 27 | Since the actual return date is 3 days later than expected, the fine is calculated as 15×3=45 Hackos. 28 | */ 29 | 30 | import java.io.*; 31 | import java.util.*; 32 | 33 | public class LibraryFine { 34 | 35 | public static void main(String[] args) { 36 | 37 | int fine = 0; 38 | Scanner sc = new Scanner(System.in); 39 | String[] returnedDay = sc.nextLine().split(" "); 40 | String[] returnDay = sc.nextLine().split(" "); 41 | if(Integer.parseInt(returnDay[2]) numProblemsCurrentChapter){ 32 | numProblemsInCurrentPage = numProblemsCurrentChapter - ((j-1) * numProblemsPerPage); 33 | }else{ 34 | numProblemsInCurrentPage = numProblemsPerPage; 35 | } 36 | 37 | if(currentNumProblem >= j && (currentNumProblem+numProblemsInCurrentPage) <= j){ 38 | numSpecialProblems++; 39 | } 40 | currentNumProblem+=numProblemsPerPage; 41 | 42 | } 43 | 44 | } 45 | System.out.println(numSpecialProblems); 46 | } 47 | } -------------------------------------------------------------------------------- /Algorithms/Implementation/MiniMaxSum.java: -------------------------------------------------------------------------------- 1 | /* Mini-Max Sum 2 | 3 | https://www.hackerrank.com/challenges/mini-max-sum 4 | 5 | */ 6 | 7 | import java.io.*; 8 | import java.util.*; 9 | import java.text.*; 10 | import java.math.*; 11 | import java.util.regex.*; 12 | 13 | public class MiniMaxSum 14 | { 15 | 16 | public static void main(String[] args) { 17 | Scanner in = new Scanner(System.in); 18 | long total = 0; 19 | long max = 0; 20 | long min = Long.MAX_VALUE; 21 | while(in.hasNext()) { 22 | long num = in.nextLong(); 23 | min = Math.min(min, num); 24 | max = Math.max(max, num); 25 | total += num; 26 | } 27 | System.out.println(""+ (total - max) + " " + (total - min)); 28 | } 29 | } -------------------------------------------------------------------------------- /Algorithms/Implementation/MiniumumDistances.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | /* 2 | Minimum Distances 3 | https://www.hackerrank.com/challenges/minimum-distances/submissions/code/31473268 4 | 5 | */ 6 | 7 | import Foundation 8 | 9 | public func getLine() -> String { 10 | var buf = String() 11 | var ch = getchar() 12 | // 10 is ascii code for newline 13 | while ch != EOF && ch != 10 { 14 | buf = buf + "\(ch)" 15 | ch = getchar() 16 | } 17 | return buf 18 | } 19 | 20 | public func readLn() -> [String] { 21 | return getLine().components(separatedBy: CharacterSet.whitespaces) 22 | } 23 | 24 | public func readLine() -> [Int] { 25 | let words: [String] = readLn() 26 | return words.map { Int($0)! } 27 | } 28 | 29 | let info: [Int] = readLine() 30 | var stationLocations: [Int] = readLine() 31 | 32 | var previousStationLocation = -1 33 | 34 | var maxDistance = 0 35 | 36 | var pos = 0 37 | 38 | if info[0] == info[1] { 39 | print(0) 40 | } else { 41 | stationLocations = stationLocations.sorted() 42 | for station in stationLocations { 43 | if previousStationLocation == -1 { 44 | previousStationLocation = station 45 | maxDistance = station 46 | } else { 47 | let distance = (station - previousStationLocation) / 2 48 | maxDistance = max(distance, maxDistance) 49 | previousStationLocation = station 50 | } 51 | } 52 | 53 | print(max(maxDistance,(info[0] - previousStationLocation - 1))) 54 | } 55 | -------------------------------------------------------------------------------- /Algorithms/Implementation/MiniumumDistances.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /Algorithms/Implementation/MiniumumDistances.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Algorithms/Implementation/RepeatedString.java: -------------------------------------------------------------------------------- 1 | /* 2 | Reapeated Strings 3 | https://www.hackerrank.com/challenges/repeated-string 4 | */ 5 | import java.io.*; 6 | import java.util.*; 7 | import java.text.*; 8 | import java.math.*; 9 | import java.util.regex.*; 10 | 11 | public class RepeatedString { 12 | 13 | public static long calcNumAInString(String s, long numChar) 14 | { 15 | long count = 0; 16 | 17 | for(int i = 0;i < numChar;i++){ 18 | if(s.charAt(i) == 'a'){ 19 | count++; 20 | } 21 | } 22 | return count; 23 | } 24 | 25 | public static void main(String[] args) { 26 | Scanner in = new Scanner(System.in); 27 | String s = in.next(); 28 | long n = in.nextLong(); 29 | 30 | 31 | 32 | if(s.length() > n){ 33 | System.out.println(calcNumAInString(s,n)); 34 | }else{ 35 | long count = calcNumAInString(s,s.length()) * (n / s.length()); 36 | long numCharLeft = n % s.length(); 37 | count += calcNumAInString(s,numCharLeft); 38 | System.out.println(count); 39 | } 40 | 41 | } 42 | } -------------------------------------------------------------------------------- /Algorithms/Implementation/SaveThePrisoner.java: -------------------------------------------------------------------------------- 1 | //https://www.hackerrank.com/challenges/save-the-prisoner 2 | 3 | /* 4 | A jail has N prisoners, and each prisoner has a unique id number, S, ranging from 1 to N. There are M sweets that must be distributed to the prisoners. 5 | 6 | The jailer decides the fairest way to do this is by sitting the prisoners down in a circle (ordered by ascending ), and then, starting with some random S, 7 | distribute one candy at a time to each sequentially numbered prisoner until all M candies are distributed. 8 | For example, if the jailer picks prisoner S = 2, then his distribution order would be (2,3,4,5....,n-1,n,1,2,3,4...) until all sweets are distributed. 9 | 10 | But wait—there's a catch—the very last sweet is poisoned! Can you find and print the ID number of the last prisoner to receive a sweet so he can be warned? 11 | 12 | Input Format 13 | 14 | The first line contains an integer, T, denoting the number of test cases. 15 | The T subsequent lines each contain 3 space-separated integers: 16 | N(the number of prisoners), M(the number of sweets), and S(the prisoner ID), respectively. 17 | 18 | Constraints 19 | - 1 <= T <= 100 20 | - 1 <= N <= 10^9 21 | - 1 <= M <= 10^9 22 | - 1 <= S <= 10^9 23 | 24 | Output Format 25 | 26 | For each test case, print the ID number of the prisoner who receives the poisoned sweet on a new line. 27 | 28 | Sample Input 29 | 30 | 1 31 | 5 2 1 32 | 33 | Sample Output 34 | 35 | 2 36 | 37 | Explanation 38 | 39 | There are N = 5 prisoners and M = 2 sweets. Distribution starts at ID number S = 1, so prisoner 1 gets the first sweet and prisoner 2 gets the second (last) sweet. Thus, we must warn prisoner 2 about the poison, so we print 2 on a new line. 40 | */ 41 | import java.util.Scanner; 42 | 43 | public class SaveThePrisoner { 44 | 45 | public static void main(String[] args) { 46 | Scanner in = new Scanner(System.in); 47 | int t = in.nextInt(); 48 | while (t-- > 0) { 49 | int n = in.nextInt(); 50 | int m = in.nextInt(); 51 | int s = in.nextInt(); 52 | int last = s - 1; 53 | while (m != 0) { 54 | last++; 55 | m--; 56 | if (last > n) { 57 | last = 1; 58 | } 59 | } 60 | System.out.println(last); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Algorithms/Implementation/SherlockAndTheBeast.java: -------------------------------------------------------------------------------- 1 | /* Sherlock And The Beast 2 | 3 | Sherlock Holmes suspects his archenemy, Professor Moriarty, is once again plotting something diabolical. 4 | Sherlock's companion, Dr. Watson, suggests Moriarty may be responsible for MI6's recent issues with their supercomputer, The Beast. 5 | 6 | Shortly after resolving to investigate, Sherlock receives a note from Moriarty boasting about infecting 7 | The Beast with a virus; however, he also gives him a clue—a number, N. Sherlock determines the key to 8 | removing the virus is to find the largest Decent Number having N digits. 9 | 10 | A Decent Number has the following properties: 11 | 12 | Its digits can only be 3's and/or 5's. 13 | The number of 3's it contains is divisible by 5. 14 | The number of 5's it contains is divisible by 3. 15 | Moriarty's virus shows a clock counting down to The Beast's destruction, and time is running out fast. 16 | Your task is to help Sherlock find the key before The Beast is destroyed! 17 | 18 | Constraints 19 | 1≤T≤20 20 | 1≤N≤100000 21 | 22 | 23 | Input Format 24 | 25 | The first line is an integer, T, denoting the number of test cases. 26 | 27 | The T subsequent lines each contain an integer, N, detailing the number of digits in the number. 28 | 29 | Output Format 30 | 31 | Print the largest Decent Number having N digits; if no such number exists, tell Sherlock by printing -1. 32 | 33 | Sample Input 34 | 35 | 4 36 | 1 37 | 3 38 | 5 39 | 11 40 | 41 | Sample Output 42 | 43 | -1 44 | 555 45 | 33333 46 | 55555533333 47 | */ 48 | 49 | import java.io.*; 50 | import java.util.*; 51 | 52 | public class SherlockAndTheBeast 53 | { 54 | 55 | public static String createDescentNumber(int fives, int threes) 56 | { 57 | String []numArray = new String[fives+threes]; 58 | StringBuilder numString = new StringBuilder(); 59 | for(int i = 0;i= 0; i--){ 72 | if((i)%3 == 0 && (((n-i))%5) == 0){ 73 | num = createDescentNumber(i,n-i); 74 | break; 75 | }else if ((i)%5 == 0 && (((n-i))%3) == 0){ 76 | num = createDescentNumber(i,n-i); 77 | } 78 | } 79 | return num; 80 | } 81 | public static void main(String[] args) { 82 | 83 | Scanner sc = new Scanner(System.in); 84 | int numTestCases = Integer.parseInt(sc.nextLine()); 85 | 86 | for(int i = 0;i < numTestCases; i++){ 87 | int n = sc.nextInt(); 88 | System.out.println(descentNumber(n)); 89 | } 90 | } 91 | } -------------------------------------------------------------------------------- /Algorithms/Implementation/SockMerchant.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | /* 2 | Sock Merchant 3 | https://www.hackerrank.com/challenges/sock-merchant 4 | */ 5 | 6 | import Cocoa 7 | import Foundation 8 | 9 | var socksDict = [String:Int]() 10 | 11 | if var input = readLine(stripNewline: true) { 12 | let numOfSocks = Int(input) 13 | if let socksInput = readLine(stripNewline: true){ 14 | let socksArray = socksInput.characters.split(" ").map(String.init) 15 | for var color in socksArray { 16 | if socksDict[color] != nil { 17 | socksDict[color]! += 1 18 | } else { 19 | socksDict[color] = 1 20 | } 21 | } 22 | } 23 | 24 | var countPairs = 0 25 | for var count in socksDict.values { 26 | countPairs += count / 2 27 | } 28 | print(countPairs) 29 | } -------------------------------------------------------------------------------- /Algorithms/Implementation/SockMerchant.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /Algorithms/Implementation/SockMerchant.playground/playground.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Algorithms/Implementation/SockMerchant.playground/timeline.xctimeline: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Algorithms/Implementation/StrangeCounter.java: -------------------------------------------------------------------------------- 1 | //https://www.hackerrank.com/challenges/strange-code 2 | 3 | import java.util.Scanner; 4 | 5 | class StrangeCounter { 6 | public static void main(String args[]) throws Exception { 7 | Scanner in = new Scanner(System.in); 8 | long t = in.nextLong(); 9 | long n = 2; 10 | while (3 * (n - 1) < t) 11 | n = 2 * n; 12 | System.out.println((3 * (n - 1) - t + 1)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Algorithms/Implementation/TaumAndBday.java: -------------------------------------------------------------------------------- 1 | /* Taum and B'day 2 | Taum is planning to celebrate the birthday of his friend, Diksha. There are two types of gifts that Diksha wants from Taum: one is black and the other is white. To make her happy, Taum has to buy B number of black gifts and W number of white gifts. 3 | 4 | The cost of each black gift is X units. 5 | The cost of every white gift is Y units. 6 | The cost of converting each black gift into white gift or vice versa is Z units. 7 | Help Taum by deducing the minimum amount he needs to spend on Diksha's gifts. 8 | 9 | Input Format 10 | 11 | The first line will contain an integer T which will be the number of test cases. 12 | There will be T pairs of lines. The first line of each test case will contain the values of integers B and W. Another line of each test case will contain the values of integers X, Y, and Z. 13 | 14 | Constraints 15 | 1≤T≤10 16 | 0≤X,Y,Z,B,W≤10^9 17 | */ 18 | import java.io.*; 19 | import java.util.*; 20 | 21 | public class TaumAndBday { 22 | 23 | public static void main(String[] args) { 24 | /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ 25 | 26 | Scanner sc = new Scanner(System.in); 27 | int numCases = sc.nextInt(); 28 | 29 | for(int i = 0;i= 0 && grid[i - 1][j] != 'O') 51 | grid[i - 1][j] = '|'; 52 | if (j - 1 >= 0 && grid[i][j - 1] != 'O') 53 | grid[i][j - 1] = '|'; 54 | } 55 | } 56 | } 57 | for (int i = 0; i < row; i++) { 58 | for (int j = 0; j < col; j++) { 59 | if (grid[i][j] == '|') { 60 | grid[i][j] = '.'; 61 | } else if (grid[i][j] == '.') { 62 | grid[i][j] = 'O'; 63 | } 64 | } 65 | } 66 | return grid; 67 | } 68 | 69 | // Print Grid 70 | private static void printGrid(char[][] grid, int row, int col) { 71 | for (int i = 0; i < row; i++) { 72 | for (int j = 0; j < col; j++) { 73 | System.out.print(grid[i][j]); 74 | } 75 | System.out.println(); 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /Algorithms/Implementation/UtopianTree.m: -------------------------------------------------------------------------------- 1 | /* The Utopian Tree 2 | The Utopian Tree goes through 2 cycles of growth every year. The first growth cycle occurs during the spring, when it doubles in height. The second growth cycle occurs during the summer, when its height increases by 1 meter. 3 | 4 | Now, a new Utopian Tree sapling is planted at the onset of spring. Its height is 1 meter. Can you find the height of the tree after N growth cycles? 5 | 6 | Input Format 7 | 8 | The first line contains an integer, T, the number of test cases. 9 | T lines follow; each line contains an integer, N, that denotes the number of cycles for that test case. 10 | 11 | Constraints 12 | 1≤T≤10 13 | 0≤N≤60 14 | Output Format 15 | 16 | For each test case, print the height of the Utopian Tree after N cycles. Each line thus has to contain a single integer, only. 17 | 18 | Sample Input 19 | 20 | 3 21 | 0 22 | 1 23 | 4 24 | Sample Output 25 | 26 | 1 27 | 2 28 | 7 29 | Explanation 30 | 31 | There are 3 test cases. 32 | 33 | In the first case (N=0), the initial height (1) of the tree remains unchanged. 34 | 35 | In the second case (when N = 1, i.e. after the 1st cycle), the tree doubles its height as it's planted at the onset of spring. 36 | 37 | In the third case (N=4), the tree first doubles its height (2), then grows a meter (3), then doubles again (6), before growing another meter; at the end of the 4th cycle, its height is 7 meters. 38 | */ 39 | 40 | //Enter your code here. Read input from STDIN. Print output to STDOUT 41 | #import 42 | 43 | int calculateTreeSize(int treeCase) 44 | { 45 | int sum = 1; 46 | for(int i = 1;i<=treeCase;i++){ 47 | if(i%2==0){ 48 | sum=sum+1; 49 | }else{ 50 | sum=sum+sum; 51 | } 52 | } 53 | return sum; 54 | 55 | } 56 | int main (int argc, const char * argv[]) { 57 | NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 58 | int testCases; 59 | scanf("%d", &testCases); 60 | for(int i=0;i costArrayList = new ArrayList(); 47 | for(int j = 0; jintArrayList = new ArrayList(); 26 | for(int i = 0;i difference){ 40 | break; 41 | } 42 | currentPos++; 43 | 44 | } 45 | startPos++; 46 | } 47 | System.out.println(count); 48 | 49 | 50 | } 51 | } -------------------------------------------------------------------------------- /Algorithms/Sorting/InsertionSort.java: -------------------------------------------------------------------------------- 1 | /* Insertion Sort - Part I 2 | Sorting 3 | One common task for computers is to sort data. For example, people might want to see all their files on a computer sorted by size. Since sorting is a simple problem with many different possible solutions, it is often used to introduce the study of algorithms. 4 | 5 | Insertion Sort 6 | These challenges will cover Insertion Sort, a simple and intuitive sorting algorithm. We will first start with an already sorted list. 7 | 8 | Insert element into sorted list 9 | Given a sorted list with an unsorted number V in the rightmost cell, can you write some simple code to insert V into the array so that it remains sorted? 10 | 11 | Print the array every time a value is shifted in the array until the array is fully sorted. The goal of this challenge is to follow the correct order of insertion sort. 12 | 13 | Guideline: You can copy the value of V to a variable and consider its cell "empty". Since this leaves an extra cell empty on the right, you can shift everything over until V can be inserted. This will create a duplicate of each value, but when you reach the right spot, you can replace it with V. 14 | 15 | Input Format 16 | There will be two lines of input: 17 | 18 | s - the size of the array 19 | ar - the sorted array of integers 20 | Output Format 21 | On each line, output the entire array every time an item is shifted in it. 22 | 23 | Constraints 24 | 1≤s≤1000 25 | −10000≤V≤10000,V ∈ ar 26 | */ 27 | 28 | import java.io.*; 29 | import java.util.*; 30 | import java.text.*; 31 | import java.math.*; 32 | import java.util.regex.*; 33 | 34 | public class Solution { 35 | 36 | 37 | 38 | public static void insertIntoSorted(int[] ar) 39 | { 40 | int numToInsert = ar[ar.length-1]; 41 | int pos = ar.length-2; 42 | while(pos>=0){ 43 | if(ar[pos]>numToInsert){ 44 | ar[pos+1]=ar[pos]; 45 | pos--; 46 | printArray(ar); 47 | 48 | }else{ 49 | ar[pos+1]=numToInsert; 50 | printArray(ar); 51 | break; 52 | } 53 | } 54 | if(pos == -1){ 55 | ar[0]=numToInsert; 56 | printArray(ar); 57 | } 58 | 59 | } 60 | 61 | 62 | /* Tail starts here */ 63 | public static void main(String[] args) { 64 | Scanner in = new Scanner(System.in); 65 | int s = in.nextInt(); 66 | int[] ar = new int[s]; 67 | for(int i=0;i=0;i--){ 33 | if(ar[currentPos] hm = new HashMap(); 51 | sc.nextLine(); 52 | String[]numArray = sc.nextLine().split(" "); 53 | for (String num:numArray){ 54 | Double number = hm.get(num); 55 | if(number == null){ 56 | hm.put(num,new Double(1)); 57 | }else{ 58 | hm.put(num,number+1); 59 | } 60 | } 61 | 62 | double total = 0; 63 | for (Double value : hm.values()) { 64 | total=total+(value*(value-1)); 65 | } 66 | 67 | System.out.printf("%.0f\n",total); 68 | 69 | } 70 | } 71 | } -------------------------------------------------------------------------------- /Algorithms/Strings/AlternatingCharacters.java: -------------------------------------------------------------------------------- 1 | /* Alternating Characters 2 | Shashank likes strings in which consecutive characters are different. For example, he likes ABABA, while he doesn't like ABAA. Given a string containing characters A and B only, he wants to change it into a string he likes. To do this, he is allowed to delete the characters in the string. 3 | 4 | Your task is to find the minimum number of required deletions. 5 | 6 | Input Format 7 | 8 | The first line contains an integer T, i.e. the number of test cases. 9 | The next T lines contain a string each. 10 | 11 | Output Format 12 | 13 | For each test case, print the minimum number of deletions required. 14 | 15 | Constraints 16 | 17 | 1≤T≤10 18 | 1≤ length of string ≤10^5 19 | */ 20 | 21 | import java.io.*; 22 | import java.util.*; 23 | 24 | public class AlternatingCharacters { 25 | 26 | public static int consecutiveChars(String str) 27 | { 28 | StringBuilder mutableStr = new StringBuilder(str); 29 | int numDeletions = 0; 30 | int pos = 0; 31 | while(pos dict = new HashMap(); 43 | int numTestCases = Integer.parseInt(sc.nextLine()); 44 | for(int i = 0;ialphabet = new ArrayList(Arrays.asList("abcdefghijklmnopqrstuvwxyz".split(""))); 27 | alphabet.remove(0); 28 | Scanner sc = new Scanner(System.in); 29 | String sentence = sc.nextLine().toLowerCase(); 30 | 31 | for(int i=0;i a.length - 1 ? k % a.length : k; 26 | 27 | for(int a0 = 0; a0 < q; a0++){ 28 | int m = in.nextInt(); 29 | int pos = m - offset; 30 | if(pos < 0){ 31 | pos = a.length + pos; 32 | } 33 | System.out.println(a[pos]); 34 | } 35 | 36 | } 37 | } 38 | 39 | -------------------------------------------------------------------------------- /Algorithms/Warmup/DiagonalDifference.java: -------------------------------------------------------------------------------- 1 | /* Diagonal Difference 2 | You are given a square matrix of size N×N. Calculate the absolute difference of the sums across the two main diagonals. 3 | 4 | Input Format 5 | 6 | The first line contains a single integer N. The next N lines contain N integers describing the matrix. 7 | 8 | Constraints 9 | 1≤N≤100 10 | −100≤A[i]≤100 11 | Output Format 12 | 13 | Output a single integer equal to the absolute difference in the sums across the diagonals. 14 | 15 | Sample Input 16 | 17 | 3 18 | 11 2 4 19 | 4 5 6 20 | 10 8 -12 21 | Sample Output 22 | 23 | 15 24 | Explanation 25 | 26 | The first diagonal of the matrix is: 27 | 28 | 11 29 | 5 30 | -12 31 | Sum across the first diagonal = 11+5-12= 4 32 | 33 | The second diagonal of the matrix is: 34 | 35 | 4 36 | 5 37 | 10 38 | Sum across the second diagonal = 4+5+10 = 19 39 | Difference: |4-19| =15 40 | */ 41 | 42 | import java.io.*; 43 | import java.util.*; 44 | 45 | public class DiagonalDifference { 46 | 47 | public static void main(String[] args) { 48 | /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ 49 | Scanner sc = new Scanner(System.in); 50 | 51 | int length = Integer.parseInt(sc.nextLine()); 52 | int diagonalOne=0, diagonalTwo =0; 53 | for(int i=0;i0){ 49 | positiveCount++; 50 | }else{ 51 | zeroCount++; 52 | } 53 | } 54 | System.out.printf("%.6f\n%.6f\n%.6f",positiveCount/numCases,negativeCount/numCases,zeroCount/numCases); 55 | } 56 | } -------------------------------------------------------------------------------- /Algorithms/Warmup/SavethePrisoner.java: -------------------------------------------------------------------------------- 1 | /* Save the Prisoner! 2 | https://www.hackerrank.com/challenges/save-the-prisoner 3 | 4 | A jail has prisoners, and each prisoner has a unique id number, S , ranging from 1 to N . 5 | There are sweets that must be distributed to the prisoners. 6 | 7 | The jailer decides the fairest way to do this is by sitting the prisoners down in a circle (ordered by ascending ), 8 | and then, starting with some random , distribute one candy at a time to each sequentially numbered prisoner until all candies are distributed. For example, if the jailer picks prisoner , then his distribution order would be until all sweets are distributed. 9 | 10 | But wait—there's a catch—the very last sweet is poisoned! Can you find and print the ID number of the last prisoner 11 | to receive a sweet so he can be warned? 12 | 13 | Input Format 14 | 15 | The first line contains an integer, T , denoting the number of test cases. 16 | The T subsequent lines each contain 3 space-separated integers: 17 | N (the number of prisoners), M (the number of sweets), and S (the prisoner ID), respectively. 18 | 19 | 20 | Output Format 21 | 22 | For each test case, print the ID number of the prisoner who receives the poisoned sweet on a new line. 23 | 24 | Sample Input 25 | 26 | 1 27 | 5 2 1 28 | Sample Output 29 | 30 | 2 31 | */ 32 | 33 | import java.io.*; 34 | import java.util.*; 35 | 36 | public class SavethePrisoner { 37 | 38 | public static void main(String[] args) 39 | { 40 | Scanner sc = new Scanner(System.in); 41 | int numTestCases = sc.nextInt(); 42 | for(int i = 0; i < numTestCases; i++){ 43 | int numPrisoners = sc.nextInt(); 44 | int numCandies = sc.nextInt(); 45 | int startID = sc.nextInt(); 46 | 47 | if ((startID + numCandies) > numPrisoners) { 48 | int leftCandies = (startID + numCandies) - numPrisoners - 1; 49 | System.out.println(leftCandies <= 1 || (leftCandies % numPrisoners) == 0?numPrisoners : (leftCandies % numPrisoners)); 50 | } else { 51 | System.out.println("" + ((startID + numCandies) - 1) ); 52 | } 53 | } 54 | 55 | } 56 | } -------------------------------------------------------------------------------- /Algorithms/Warmup/SimpleArraySum.java: -------------------------------------------------------------------------------- 1 | /* Simple Array Sum 2 | 3 | You are given an array of integers of size N. Can you find the sum of the elements in the array? 4 | 5 | Input 6 | The first line of input consists of an integer N. The next line contains N space-separated integers 7 | representing the array elements. 8 | Sample: 9 | 10 | 6 11 | 1 2 3 4 10 11 12 | Output 13 | Output a single value equal to the sum of the elements in the array. 14 | For the sample above you would just print 31 since 1+2+3+4+10+11=31. 15 | 16 | */ 17 | 18 | import java.io.*; 19 | import java.util.*; 20 | import java.text.*; 21 | import java.math.*; 22 | import java.util.regex.*; 23 | 24 | public class SimpleArraySum { 25 | 26 | public static void main(String[] args) { 27 | 28 | Scanner sc = new Scanner(System.in); 29 | int number = sc.nextInt(); 30 | int sum=0; 31 | for(int i = 0;i 30 | int solveMeFirst(int a, int b) { 31 | return a+b; 32 | } 33 | 34 | int main (int argc, const char * argv[]) { 35 | NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 36 | int a,b,res; 37 | scanf("%d %d", &a, &b); 38 | res = solveMeFirst(a,b); 39 | printf("%d", res); 40 | [pool drain]; 41 | return 0; 42 | } -------------------------------------------------------------------------------- /Algorithms/Warmup/SolveMeSecond.c: -------------------------------------------------------------------------------- 1 | /*Solve Me Second 2 | 3 | You learnt about STDIN and STDOUT in Solve me first. 4 | 5 | This is the second challenge in the introduction series. The purpose of this challenge is to give you a working I/O template in your preferred language. It includes scanning two space-separated integers from STDIN in a loop over T lines, calling a function, returning a value, and printing it to STDOUT. 6 | 7 | A pseudo code looks like the following: 8 | 9 | read T 10 | loop from 1 to T 11 | read A and B 12 | compute the sum 13 | print value in a newline 14 | end loop 15 | The task is to scan two numbers from STDIN, and print the sum A+B on STDOUT. The code has already been provided for most of the popular languages. This is primarily for you to read and inspect how the IO is handled. 16 | 17 | Note: The code has been saved in a template, which you can submit if you want. Or, you may try rewriting it and building it up from scratch. 18 | 19 | Input Format 20 | (This section specifies the Input Format.) 21 | The first line contains T (number of test cases) followed by T lines 22 | Each line contains A and B, separated by a space. 23 | 24 | As you can see that we have provided in advance the number of lines, we discourage the use of scanning till EOF as not every language has an easy way to handle that. In fact, every HackerRank challenge is designed in such a way that multitests begin with a T line to indicate the number of lines. 25 | 26 | Output Format 27 | (This section specifies the Output Format.) 28 | An integer that denotes Sum (A+B) printed on new line for every testcase. 29 | 30 | Constraints 31 | (This section tells what input you can expect. You can freely assume that the input will remain within the boundaries specified.) 32 | 1≤T,A,B≤1000 33 | 34 | Sample Input 35 | 36 | 2 37 | 2 3 38 | 3 7 39 | Sample Output 40 | 41 | 5 42 | 10 43 | The above sample should be taken seriously. 2 in the first line describes how many lines will follow, and your test cases are 2, 3 and 3, 7 in two separate lines. Your output should be 5 and 10 printed on two separate lines. If you print extra lines or "The answer is: 5", any such extra characters in output will result in a Wrong Answer, as the judging is done using diff checker. 44 | */ 45 | 46 | #include 47 | #include 48 | #include 49 | #include 50 | 51 | 52 | int solveMeSecond(int a, int b) { 53 | return a+b; 54 | } 55 | int main() { 56 | int t,i; 57 | scanf("%d",&t); 58 | int num1,num2; 59 | int sum; 60 | for ( i = 0;i < t; i++ ) { 61 | scanf("%d %d",&num1,&num2); 62 | sum = solveMeSecond(num1,num2); 63 | printf("%d\n",sum); 64 | } 65 | return 0; 66 | } 67 | 68 | -------------------------------------------------------------------------------- /Algorithms/Warmup/StairCase.java: -------------------------------------------------------------------------------- 1 | /* Staircase 2 | Your teacher has given you the task to draw the structure of a staircase. Being an expert programmer, you decided to make a program for the same. You are given the height of the staircase. You need to print a staircase as shown in the example. 3 | 4 | Input Format 5 | 6 | You are given an integer N depicting the height of the staircase. 7 | 8 | Constraints 9 | 1≤N≤100 10 | Output Format 11 | 12 | Draw a staircase of height N in the format given below. 13 | 14 | For example: 15 | 16 | # 17 | ## 18 | ### 19 | #### 20 | ##### 21 | ###### 22 | Staircase of height 6, note that last line has 0 spaces before it. 23 | */ 24 | 25 | import java.io.*; 26 | import java.util.*; 27 | 28 | public class Solution { 29 | 30 | public static void main(String[] args) { 31 | 32 | Scanner sc = new Scanner(System.in); 33 | int num = Integer.parseInt(sc.nextLine()); 34 | for(int j=0;j 39 | 40 | 41 | int main(int argc, const char * argv[]){ 42 | NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 43 | NSInteger a0; 44 | NSInteger a1; 45 | NSInteger a2; 46 | scanf("%li %li %li",&a0,&a1,&a2); 47 | NSInteger b0; 48 | NSInteger b1; 49 | NSInteger b2; 50 | scanf("%li %li %li",&b0,&b1,&b2); 51 | NSInteger aliceTotal = 0; 52 | NSInteger bobTotal = 0; 53 | a0 > b0?aliceTotal++:a0 < b0?bobTotal++:0; 54 | a1 > b1?aliceTotal++:a1 < b1?bobTotal++:0; 55 | a2 > b2?aliceTotal++:a2 < b2?bobTotal++:0; 56 | printf("%li %li",aliceTotal, bobTotal); 57 | 58 | [pool drain]; 59 | return 0; 60 | } -------------------------------------------------------------------------------- /Contests/CodeWhiz.java 2016/ComparetheTriplets.java: -------------------------------------------------------------------------------- 1 | /* Compare the Triplets 2 | 3 | Alice and Bob each created one problem for HackerRank. A reviewer rates the two challenges, 4 | awarding points on a scale from to for three categories: problem clarity, originality, and difficulty. 5 | 6 | We define the rating for Alice's challenge to be the triplet , and the rating for 7 | Bob's challenge to be the triplet. 8 | 9 | Your task is to find their comparison scores by comparing with , with , and with. 10 | 11 | If , then Alice is awarded point. 12 | If , then Bob is awarded point. 13 | If , then neither person receives a point. 14 | Given and , can you compare the two challenges and print their respective comparison points? 15 | 16 | Input Format 17 | 18 | The first line contains space-separated integers, , , and , describing the respective values in triplet . 19 | The second line contains space-separated integers, , , and , describing the respective values in triplet . 20 | 21 | Constraints 22 | 23 | 24 | 25 | Output Format 26 | 27 | Print two space-separated integers denoting the respective comparison scores earned by Alice and Bob. 28 | 29 | Sample Input 30 | 31 | 5 6 7 32 | 3 6 10 33 | Sample Output 34 | 35 | 1 1 36 | */ 37 | 38 | import java.io.*; 39 | import java.util.*; 40 | import java.text.*; 41 | import java.math.*; 42 | import java.util.regex.*; 43 | 44 | 45 | public class ComparetheTriplets { 46 | 47 | public static void main(String[] args)throws IOException { 48 | Math ob = new Math(); 49 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 50 | int T=Integer.parseInt(br.readLine()); 51 | performOperation op; 52 | int ret =0; 53 | String ans=null; 54 | while(T-->0){ 55 | String s=br.readLine().trim(); 56 | StringTokenizer st=new StringTokenizer(s); 57 | int ch=Integer.parseInt(st.nextToken()); 58 | int num=Integer.parseInt(st.nextToken()); 59 | if(ch==1){ 60 | op = ob.checkEvenOdd(); 61 | ret = ob.checker(op,num); 62 | ans = (ret == 0)?"EVEN":"ODD"; 63 | } 64 | else if(ch==2){ 65 | op = ob.checkPrime(); 66 | ret = ob.checker(op,num); 67 | ans = (ret == 0)?"PRIME":"COMPOSITE"; 68 | } 69 | else if(ch==3){ 70 | op = ob.checkPalindrome(); 71 | ret = ob.checker(op,num); 72 | ans = (ret == 0)?"PALINDROME":"NOT PALINDROME"; 73 | 74 | } 75 | System.out.println(ans); 76 | } 77 | } 78 | } -------------------------------------------------------------------------------- /Contests/CodeWhiz.java 2016/CovariantReturnTypes.java: -------------------------------------------------------------------------------- 1 | /* Covariant Return Types 2 | 3 | Java allows for Covariant Return Types, which means you can vary your return type as long you are returning a 4 | subclass of your specified return type. 5 | 6 | Method Overriding allows a subclass to override the behavior of an existing superclass method and specify a 7 | return type that is some subclass of the original return type. 8 | 9 | Note: It is best practice to use the @Override annotation when overriding a superclass method. 10 | 11 | We will append a hidden class to test your code; the method in our test class takes the 12 | name of a state as input and prints the national flower of that state using the classes and 13 | methods you written by you. 14 | 15 | Resources 16 | Covariant Return Type 17 | Java Covariant Type 18 | 19 | Input Format 20 | 21 | Input is handled for you by the hidden test class. 22 | 23 | Output Format 24 | 25 | Output is handled for you by the hidden test class. 26 | 27 | Sample Input 28 | 29 | A single line containing the name of a State: 30 | 31 | AndhraPradesh 32 | Sample Output 33 | 34 | A single line containing the national flower of the State received as input: 35 | 36 | Lily 37 | */ 38 | 39 | import java.io.*; 40 | import java.util.*; 41 | import java.text.*; 42 | import java.math.*; 43 | import java.util.regex.*; 44 | 45 | class Flower 46 | { 47 | String whats_Your_Name() 48 | { 49 | return "I have many names and types"; 50 | } 51 | } 52 | 53 | class Jasmine extends Flower 54 | { 55 | @Override 56 | String whats_Your_Name() 57 | { 58 | return "Jasmine"; 59 | } 60 | } 61 | 62 | class Lily extends Flower 63 | { 64 | @Override 65 | String whats_Your_Name() 66 | { 67 | return "Lily"; 68 | } 69 | } 70 | 71 | class Lotus extends Flower 72 | { 73 | @Override 74 | String whats_Your_Name() 75 | { 76 | return "Lotus"; 77 | } 78 | } 79 | 80 | class State 81 | { 82 | Flower your_National_Flower() 83 | { 84 | return new Flower(); 85 | } 86 | } 87 | 88 | class WestBengal extends State 89 | { 90 | @Override 91 | Flower your_National_Flower() 92 | { 93 | return new Jasmine(); 94 | } 95 | } 96 | 97 | class Karnataka extends State 98 | { 99 | @Override 100 | Flower your_National_Flower() 101 | { 102 | return new Lotus(); 103 | } 104 | } 105 | 106 | class AndhraPradesh extends State 107 | { 108 | @Override 109 | Flower your_National_Flower() 110 | { 111 | return new Lily(); 112 | } 113 | } -------------------------------------------------------------------------------- /Contests/CodeWhiz.java 2016/JavaList.java: -------------------------------------------------------------------------------- 1 | /* Java List 2 | 3 | For this problem, we have types of queries you can perform on a List: 4 | 5 | Insert at index : 6 | 7 | Insert 8 | x y 9 | Delete the element at index : 10 | 11 | Delete 12 | x 13 | Given a list, , of integers, perform queries on the list. Once all queries are completed, 14 | print the modified list as a single line of space-separated integers. 15 | 16 | Input Format 17 | 18 | The first line contains an integer, (the initial number of elements in ). 19 | The second line contains space-separated integers describing . 20 | The third line contains an integer, (the number of queries). 21 | The subsequent lines describe the queries, and each query is described over two lines: 22 | 23 | If the first line of a query contains the String Insert, then the second line contains 24 | two space separated integers , and the value must be inserted into at index. 25 | If the first line of a query contains the String Delete, then the second line contains index, 26 | whose element must be deleted from . 27 | Constraints 28 | 29 | Each element in is a 32-bit integer. 30 | Output Format 31 | 32 | Print the updated list as a single line of space-separated integers. 33 | 34 | Sample Input 35 | 36 | 5 37 | 12 0 1 78 12 38 | 2 39 | Insert 40 | 5 23 41 | Delete 42 | 0 43 | Sample Output 44 | 45 | 0 1 78 12 23 46 | 47 | */ 48 | 49 | import java.io.*; 50 | import java.util.*; 51 | import java.text.*; 52 | import java.math.*; 53 | import java.util.regex.*; 54 | 55 | public class JavaList 56 | { 57 | 58 | public static void main(String[] args) { 59 | 60 | Scanner sc = new Scanner(System.in); 61 | int numElements = Integer.parseInt(sc.nextLine()); 62 | ArrayList numList = new ArrayList<>(); 63 | for(int i = 0;i < numElements;i++){ 64 | numList.add(sc.nextInt()); 65 | } 66 | int numQueries = sc.nextInt(); 67 | sc.nextLine(); 68 | for(int i = 0;i < numQueries;i++){ 69 | String queryType = sc.nextLine(); 70 | if(queryType.equals("Insert")){ 71 | String[] queryArray = sc.nextLine().split(" "); 72 | numList.add(Integer.parseInt(queryArray[0]),Integer.parseInt(queryArray[1])); 73 | }else{ 74 | int removeIndex = Integer.parseInt(sc.nextLine()); 75 | numList.remove(removeIndex); 76 | } 77 | } 78 | for(Integer num : numList){ 79 | System.out.print(num+" "); 80 | } 81 | } 82 | } -------------------------------------------------------------------------------- /Contests/CodeWhiz.java 2016/JavaPrimalityTest.java: -------------------------------------------------------------------------------- 1 | /* Java List 2 | 3 | Java's BitSet class implements a vector of bit values (i.e.: () or ()) that grows as needed, 4 | allowing us to easily manipulate bits while optimizing space (when compared to other collections). 5 | Any element having a bit value of is called a set bit. 6 | 7 | Given BitSets, and , of size where all bits in both BitSets are initialized to, 8 | perform a series of operations. After each operation, print the number of set bits 9 | in the respective BitSets as two space-separated integers on a new line. 10 | 11 | Input Format 12 | 13 | The first line contains space-separated integers, (the length of both BitSets and ) 14 | and (the number of operations to perform), respectively. 15 | The subsequent lines each contain an operation in one of the following forms: 16 | 17 | AND 18 | OR 19 | XOR 20 | FLIP 21 | SET 22 | In the list above, is the integer or , where denotes and denotes. 23 | is an integer denoting a bit's index in the BitSet corresponding to. 24 | 25 | For the binary operations , , and , operands are read from left to right and the BitSet resulting 26 | from the operation replaces the contents of the first operand. For example: 27 | 28 | AND 2 1 29 | is the left operand, and is the right operand. This operation should assign the result of to . 30 | 31 | Constraints 32 | 33 | Output Format 34 | 35 | After each operation, print the respective number of set bits in BitSet and BitSet 36 | as space-separated integers on a new line. 37 | 38 | Sample Input 39 | 40 | 5 4 41 | AND 1 2 42 | SET 1 4 43 | FLIP 2 2 44 | OR 2 1 45 | Sample Output 46 | 47 | 0 0 48 | 1 0 49 | 1 1 50 | 1 2 51 | 52 | */ 53 | 54 | import java.io.*; 55 | import java.util.*; 56 | import java.text.*; 57 | import java.math.*; 58 | import java.util.regex.*; 59 | 60 | public class JavaPrimalityTest 61 | { 62 | 63 | public static void main(String[] args) 64 | { 65 | Scanner sc = new Scanner(System.in); 66 | int bitSetSize = sc.nextInt(); 67 | int numOperations = sc.nextInt(); 68 | BitSet[] bitSetArray = new BitSet[2]; 69 | bitSetArray[0] = new BitSet(bitSetSize); 70 | bitSetArray[1] = new BitSet(bitSetSize); 71 | sc.nextLine(); 72 | for(int i = 0;i < numOperations; i++) 73 | { 74 | String[] opArray = sc.nextLine().split(" "); 75 | switch(opArray[0]){ 76 | case "AND": bitSetArray[Integer.parseInt(opArray[1])-1].and(bitSetArray[Integer.parseInt(opArray[2])-1]); 77 | break; 78 | case "OR": bitSetArray[Integer.parseInt(opArray[1])-1].or(bitSetArray[Integer.parseInt(opArray[2])-1]); 79 | break; 80 | case "XOR": bitSetArray[Integer.parseInt(opArray[1])-1].xor(bitSetArray[Integer.parseInt(opArray[2])-1]); 81 | break; 82 | case "FLIP": bitSetArray[Integer.parseInt(opArray[1])-1].flip(Integer.parseInt(opArray[2])); 83 | break; 84 | case "SET": bitSetArray[Integer.parseInt(opArray[1])-1].set(Integer.parseInt(opArray[2])); 85 | break; 86 | } 87 | System.out.println(bitSetArray[0].cardinality() + " " + bitSetArray[1].cardinality()); 88 | 89 | } 90 | } 91 | } -------------------------------------------------------------------------------- /Contests/CodeWhiz.java 2016/JavaSingleton.java: -------------------------------------------------------------------------------- 1 | /* Java Singleton 2 | 3 | "The singleton pattern is a design pattern that restricts the instantiation of a class to one object. 4 | This is useful when exactly one object is needed to coordinate actions across the system." 5 | - Wikipedia: Singleton Pattern 6 | 7 | Complete the Singleton class in your editor which contains the following components: 8 | 9 | A private Singleton non parameterized constructor. 10 | A public String instance variable named . 11 | Write a static method named getSingleInstance that returns the single instance of the Singleton class. 12 | Once submitted, our hidden Solution class will check your code by taking a String as input and 13 | then using your Singleton class to print a line. 14 | 15 | Input Format 16 | 17 | You will not be handling any input in this challenge. 18 | 19 | Output Format 20 | 21 | You will not be producing any output in this challenge. 22 | 23 | Sample Input 24 | 25 | hello world 26 | Sample Output 27 | 28 | Hello I am a singleton! Let me say hello world to you 29 | 30 | */ 31 | 32 | import java.io.*; 33 | import java.util.*; 34 | import java.text.*; 35 | import java.math.*; 36 | import java.util.regex.*; 37 | 38 | public class JavaSingleton 39 | { 40 | 41 | public String str; 42 | private static Singleton singleton = new Singleton(); 43 | 44 | private Singleton(){}; 45 | 46 | public static Singleton getSingleInstance() 47 | { 48 | return singleton; 49 | } 50 | } -------------------------------------------------------------------------------- /Contests/CodeWhiz.java 2016/MaximumandMinimum.java: -------------------------------------------------------------------------------- 1 | /* Maximum and Minimum 2 | 3 | The locked code in your editor passes array (of size ) and index to the print method, whose try 4 | block attempts to print element ; if is Out-of-Range, an Array Index Out Of Bounds Exception is thrown. 5 | 6 | Complete the code in your editor so that it prints the maximum and minimum elements in array 7 | regardless of whether or not an exception is thrown. 8 | 9 | Input Format 10 | 11 | The first line contains an integer, , the number of elements in . 12 | The second line contains space-separated integers describing . 13 | The third line contains an index, , to be accessed. 14 | 15 | Note: Input from stdin handled by the locked code in the editor. 16 | 17 | Constraints 18 | 19 | 20 | 21 | Output Format 22 | 23 | The try block will print the value accessed at ; if an Exception is thrown, it will be printed by 24 | the locked code in your editor. 25 | You must print the respective maximum and minimum values in array as a single pair of space-separated integers 26 | on a new line—regardless of whether an exception is thrown. 27 | 28 | Note: Observe that your max/min values may print on either the first or second line, depending on 29 | whether or not an Exception was thrown! 30 | 31 | Sample Input 0 32 | 33 | 12 34 | -12 0 1 -899 23 45 96 10 75 23 0 33 35 | 100 36 | Sample Output 0 37 | 38 | 96 -899 39 | java.lang.ArrayIndexOutOfBoundsException 40 | Sample Input 1 41 | 42 | 10 43 | 4 908 -05 445 -208 325 -2 -718 863 400 44 | 9 45 | Sample Output 1 46 | 47 | 400 48 | 908 -718 49 | 50 | */ 51 | 52 | import java.io.*; 53 | import java.util.*; 54 | import java.text.*; 55 | import java.math.*; 56 | import java.util.regex.*; 57 | 58 | public class MaximumandMinimum 59 | { 60 | 61 | public static void print(int A[],int i) 62 | { 63 | try{ 64 | System.out.println(A[i]); 65 | } 66 | catch(ArrayIndexOutOfBoundsException e){ 67 | int max = A[0]; 68 | int min = A[0]; 69 | for(int j = 0;j < A.length;j++){ 70 | if(max < A[j]) max = A[j]; 71 | if(min > A[j]) min = A[j]; 72 | } 73 | System.out.println(max+" "+min); 74 | throw e; 75 | } 76 | int max = A[0]; 77 | int min = A[0]; 78 | for(int j = 0;j < A.length;j++){ 79 | if(max < A[j]) max = A[j]; 80 | if(min > A[j]) min = A[j]; 81 | } 82 | System.out.println(max+" "+min); 83 | } 84 | 85 | public static void main(String[] args) { 86 | int N; 87 | Scanner st=new Scanner(System.in); 88 | N=st.nextInt(); 89 | int A[]=new int[N]; 90 | for(int i=0;i=0 otherwise −1×x. 16 | 17 | Input Format 18 | First Line of Input contains N and Q separated by space. 19 | Next Line contains N space separated integers. 20 | Next Q queries follows, each query contains two integers L and R separated by a space. 21 | 22 | Constraints 23 | 1≤N≤105 24 | 1≤Q≤105 25 | −9≤A[i]≤9 26 | 1≤L≤R≤N 27 | 28 | Output Format 29 | For each query output Even if the value returned by Find(L,R) is even otherwise Odd. 30 | */ 31 | 32 | 33 | import java.io.*; 34 | import java.util.*; 35 | 36 | public class SomeOfAbsolute { 37 | public static String isSumEvenOrOdd(int l,int r,int[]intArray) 38 | { 39 | int sum = 0; 40 | for(int i=l-1;i shoeList = new ArrayList<>(); 43 | Scanner sc = new Scanner(System.in); 44 | int numShoes = Integer.parseInt(sc.nextLine()); 45 | int numOfPairs = 0; 46 | for(int i = 0;i < numShoes;i++){ 47 | String shoe = sc.nextLine(); 48 | String shoeDesc = shoe.substring(0,shoe.length()-2); 49 | String shoeType = shoe.substring(shoe.length()-1,shoe.length()-0); 50 | System.out.println(shoeDesc + ":"+shoeType); 51 | if(shoeType.equals("L")){ 52 | int indexRightShoe = shoeList.indexOf(shoeDesc+" R"); 53 | if(indexRightShoe != -1) 54 | { 55 | numOfPairs++; 56 | shoeList.remove(indexRightShoe); 57 | }else{ 58 | shoeList.add(shoe); 59 | } 60 | }else if(shoeType.equals("R")){ 61 | int indexRightShoe = shoeList.indexOf(shoeDesc+" L"); 62 | if(indexRightShoe != -1) 63 | { 64 | numOfPairs++; 65 | shoeList.remove(indexRightShoe); 66 | }else{ 67 | shoeList.add(shoe); 68 | } 69 | } 70 | 71 | } 72 | } 73 | } 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /Java/Advanced/CanYouAccess.java: -------------------------------------------------------------------------------- 1 | /* Can You Access? 2 | 3 | You are given a class Solution and an inner class Inner.Private. The main method of class Solution 4 | takes an integer num as input. The powerof2 in class Inner.Private checks whether a number is a power of 2. 5 | You have to call the method powerof2 of the class Inner.Private from the main method of the class Solution. 6 | 7 | Constraints 8 | 1≤num≤230 9 | 10 | Sample Input 11 | 12 | 8 13 | 14 | Sample Output 15 | 16 | 8 is power of 2 17 | An instance of class: Solution.Inner.Private has been created 18 | */ 19 | 20 | o = new Inner().new Private(); 21 | System.out.println(""+num+" is "+((Inner.Private)o).powerof2(num)); -------------------------------------------------------------------------------- /Java/Advanced/JavaFactory.java: -------------------------------------------------------------------------------- 1 | /* Java Factory 2 | 3 | According to Wikipedia, a factory is simply an object that returns another object from some other method call, which is assumed to be "new". 4 | 5 | In this problem, you are given an interface Food. There are two classes Pizza and Cake which implement the Food interface, and they both contain a method getType(). 6 | 7 | The main function in the Main class creates an instance of the FoodFactory class. The FoodFactory class contains a method getFood(String) that returns a new instance of Pizza or Cake according to its parameter. 8 | 9 | You are given the partially completed code in the editor. Please complete the FoodFactory class. 10 | 11 | Sample Input 1 12 | 13 | cake 14 | Sample Output 1 15 | 16 | The factory returned class Cake 17 | Someone ordered a Dessert! 18 | Sample Input 2 19 | 20 | pizza 21 | Sample Output 2 22 | 23 | The factory returned class Pizza 24 | Someone ordered Fast Food! 25 | 26 | */ 27 | 28 | if(order.equals("cake")){ 29 | 30 | return new Cake(); 31 | }else{ 32 | return new Pizza(); 33 | } -------------------------------------------------------------------------------- /Java/Advanced/JavaReflection.java: -------------------------------------------------------------------------------- 1 | /* Java Reflection - Attributes 2 | 3 | JAVA reflection is a very powerful tool to inspect the attributes of a class in runtime. For example, 4 | we can retrieve the list of public fields of a class using getDeclaredMethods(). 5 | 6 | In this problem, you will be given a class Solution in the editor. You have to fill in the incompleted 7 | lines so that it prints all the methods of another class called Student in alphabetical order. 8 | We will append your code with the Student class before running it. The Student class looks like this: 9 | 10 | class Student{ 11 | private String name; 12 | private String id; 13 | private String email; 14 | 15 | public String getName() { 16 | return name; 17 | } 18 | public void setId(String id) { 19 | this.id = id; 20 | } 21 | public void setEmail(String email) { 22 | this.email = email; 23 | } 24 | public void anothermethod(){ } 25 | ...... 26 | ...... 27 | some more methods 28 | ...... 29 | } 30 | You have to print all the methods of the student class in alphabetical order like this: 31 | 32 | anothermethod 33 | getName 34 | setEmail 35 | setId 36 | ...... 37 | ...... 38 | some more methods 39 | ...... 40 | There is no sample input/output for this problem. If you press "Run Code", it will compile it, but it won't show any outputs. 41 | 42 | */ 43 | 44 | public class JavaReflection { 45 | 46 | public static void main(String[] args){ 47 | Class student = new Student().getClass(); 48 | Method[] methods = student.getDeclaredMethods(); 49 | 50 | ArrayList methodList = new ArrayList<>(); 51 | for(Method method:methods){ 52 | methodList.add(method.getName()); 53 | } 54 | Collections.sort(methodList); 55 | for(String name: methodList){ 56 | System.out.println(name); 57 | } 58 | } 59 | } -------------------------------------------------------------------------------- /Java/Advanced/JavaVarargs.java: -------------------------------------------------------------------------------- 1 | /* Java Varargs - Simple Addition 2 | 3 | You are given a class Solution and its main method in the editor. 4 | Your task is to create the class Add and the required methods so that the code prints the sum of the numbers 5 | passed to the function add. 6 | 7 | Note: Your add method in the Add class must print the sum as given in the Sample Output 8 | 9 | Input Format 10 | 11 | There are six lines of input, each containing an integer. 12 | 13 | Output Format 14 | 15 | There will be only four lines of output. Each line contains the sum of the integers passed as the parameters 16 | to add in the main method. 17 | 18 | Sample Input 19 | 20 | 1 21 | 2 22 | 3 23 | 4 24 | 5 25 | 6 26 | Sample Output 27 | 28 | 1+2=3 29 | 1+2+3=6 30 | 1+2+3+4+5=15 31 | 1+2+3+4+5+6=21 32 | 33 | */ 34 | 35 | class Add 36 | { 37 | static void add(int...numbers) 38 | { 39 | int sum = 0; 40 | for(int num:numbers) 41 | { 42 | if(sum !=0){ 43 | System.out.print("+"); 44 | } 45 | sum+=num; 46 | System.out.print(num); 47 | } 48 | System.out.println("="+sum); 49 | } 50 | } -------------------------------------------------------------------------------- /Java/Advanced/PrimeChecker.java: -------------------------------------------------------------------------------- 1 | /* Prime Checker 2 | 3 | You are given a class Solution and its main method in the editor. Your task is to create a 4 | class Prime which contains a single method checkPrime so that the code prints only prime numbers as the output. 5 | 6 | Please do not use method overloading! 7 | 8 | Note: You may get a compile time error in this problem due to the below statement: 9 | 10 | BufferedReader br=new BufferedReader(new InputStreamReader(in)); 11 | This was added intentionally, and you have to figure out a way to get rid of the error. 12 | 13 | Input Format 14 | 15 | There are only five lines of input, each containing one integer. 16 | 17 | Output Format 18 | 19 | There will be only four lines of output. Each line contains only prime numbers depending 20 | upon the parameters passed to checkPrime in the main method of the class Solution. In case there is 21 | no prime number, then a blank line should be printed. 22 | 23 | Sample Input 24 | 25 | 2 26 | 1 27 | 3 28 | 4 29 | 5 30 | 31 | Sample Output 32 | 33 | 2 34 | 2 35 | 2 3 36 | 2 3 5 37 | 38 | */ 39 | 40 | import static java.lang.System.in; 41 | class Prime 42 | { 43 | public boolean isPrime(int num) 44 | { 45 | if (num == 1) return false; 46 | for(int i = 2;i() { 65 | @Override 66 | public int compare(Object a1, Object a2) { 67 | BigDecimal bigDec1 = new BigDecimal((String)a1); 68 | BigDecimal bigDec2 = new BigDecimal((String)a2); 69 | return bigDec2.compareTo(bigDec1); 70 | } 71 | }); 72 | 73 | for(int i=0;ilargestSum){ 70 | largestSum=sum; 71 | } 72 | } 73 | } 74 | } 75 | System.out.println(largestSum); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /Java/Collections/JavaArrayList.java: -------------------------------------------------------------------------------- 1 | /* Java Arraylist 2 | 3 | Sometimes it's better to use dynamic size arrays. Java's Arraylist can provide you this feature. 4 | Try to solve this problem using Arraylist. 5 | 6 | You are given n lines. In each line there are zero or more integers. You need to answer a few queries 7 | where you need to tell the number located in yth position of xth line. 8 | 9 | Take your input from System.in. 10 | 11 | Input Format 12 | The first line has an integer n. In each of the next n lines there will be an integer d denoting number 13 | of integers on that line and then there will be d space-separated integers. In the next line there will 14 | be an integer q denoting number of queries. Each query will consist of two integers x and y. 15 | 16 | Constraints 17 | 18 | 1<=n<=20000 19 | 0<=d<=50000 20 | 1<=q<=1000 21 | 1<=x,y<=n 22 | 23 | Each number will fit in signed integer. 24 | Total number of integers in n lines will not cross 100000. 25 | 26 | Output Format 27 | In each line, output the number located in yth position of xth line. If there is no such position, just print "ERROR!" 28 | 29 | Sample Input 30 | 31 | 5 32 | 5 41 77 74 22 44 33 | 1 12 34 | 4 37 34 36 52 35 | 0 36 | 3 20 22 33 37 | 5 38 | 1 3 39 | 3 4 40 | 3 1 41 | 4 3 42 | 5 5 43 | 44 | Sample Output 45 | 46 | 74 47 | 52 48 | 37 49 | ERROR! 50 | ERROR! 51 | 52 | */ 53 | 54 | import java.io.*; 55 | import java.util.*; 56 | import java.text.*; 57 | import java.math.*; 58 | import java.util.regex.*; 59 | 60 | public class Solution { 61 | 62 | public static void main(String[] args) { 63 | 64 | Scanner sc = new Scanner(System.in); 65 | int numLines = Integer.parseInt(sc.nextLine()); 66 | ArrayList listArray = new ArrayList(); 67 | for(int i = 0;i intArrayList = new ArrayList(); 70 | for(int j=0;j desc = new Comparator() { 48 | 49 | @Override 50 | public int compare(Player o1, Player o2) { 51 | 52 | if(o1.score==o2.score){ 53 | return o2.name.compareTo(o1.name); 54 | } 55 | return o1.score>o2.score?-1:1; 56 | } 57 | }; 58 | 59 | } -------------------------------------------------------------------------------- /Java/Collections/JavaDeque.java: -------------------------------------------------------------------------------- 1 | /* Java Deque 2 | 3 | In computer science, a double-ended queue (dequeue, often abbreviated to deque, pronounced deck) is an 4 | abstract data type that generalizes a queue, for which elements can be added to or removed from either the 5 | front (head) or back (tail). 6 | 7 | Deque interfaces can be implemented using various types of collections such as LinkedList or ArrayDeque 8 | classes. For example, deque can be declared as: 9 | 10 | Deque deque = new LinkedList<>(); 11 | or 12 | Deque deque = new ArrayDeque<>(); 13 | You can find more details about Deque here. 14 | 15 | In this problem, you are given N integers. You need to find the maximum number of unique integers among 16 | all the possible contiguous subarrays of size M. 17 | 18 | Note: Time limit is 3 second for this problem. 19 | 20 | Input Format 21 | 22 | The first line of input contains two integers N and M: representing the total number of integers and 23 | the size of the subarray, respectively. The next line contains N space separated integers. 24 | 25 | Constraints 26 | 27 | 1≤N≤100000 28 | 1≤M≤100000 29 | M≤N 30 | The numbers in the array will range between [0,10000000]. 31 | 32 | Output Format 33 | 34 | Print the maximum number of unique integers among all possible contiguous subarrays of size M separated by a space. 35 | 36 | Sample Input 37 | 38 | 6 3 39 | 5 3 5 2 3 2 40 | 41 | Sample Output 42 | 43 | 3 44 | 45 | */ 46 | 47 | import java.util.*; 48 | public class test { 49 | public static void main(String[] args) { 50 | 51 | Scanner in = new Scanner(System.in); 52 | Deque deque = new ArrayDeque(); 53 | int n = in.nextInt(); 54 | int m = in.nextInt(); 55 | int maxUnique = 0; 56 | for (int i = 0; i < n; i++) { 57 | int num = in.nextInt(); 58 | if(i == 0){ 59 | deque.add(num); 60 | maxUnique++; 61 | }else{ 62 | if(deque.size() == m){ 63 | deque.removeFirst(); 64 | } 65 | if(!deque.contains(num) && maxUniqueclosingParan = Arrays.asList("}", ")", "]"); 54 | boolean isBallanced = true; 55 | ArrayList stack = new ArrayList(); 56 | if(paranString.length()>0){ 57 | for(int i = 0;i0) isBallanced = false; 78 | return isBallanced; 79 | } 80 | public static void main(String[] args) { 81 | Scanner sc = new Scanner(System.in); 82 | while(sc.hasNext()){ 83 | if(isBallanced(sc.nextLine())){ 84 | System.out.println("true"); 85 | }else{ 86 | System.out.println("false"); 87 | } 88 | } 89 | 90 | } 91 | } -------------------------------------------------------------------------------- /Java/Exception Handling/JavaExceptionHandling.java: -------------------------------------------------------------------------------- 1 | /* Java Exception Handling 2 | Create a class myCalculator which consists of a single method power(int,int). This method takes two integers, 3 | n and p, as parameters and finds np. If either n or p is negative, then the method must throw an exception 4 | which says "n and p should be non-negative". 5 | 6 | Please read the partially completed code in the editor and complete it. Your code mustn't be public. 7 | 8 | No need to worry about constraints, there won't be any overflow if your code is correct. 9 | 10 | */ 11 | 12 | class JavaExceptionHandling 13 | { 14 | public int power(int n, int p) throws Exception 15 | { 16 | if(n<0 || p<0){ 17 | throw new Exception("n and p should be non-negative"); 18 | } 19 | return (int) Math.pow(n,p); 20 | 21 | } 22 | 23 | } -------------------------------------------------------------------------------- /Java/Exception Handling/JavaExceptionHandlingTryCatch.java: -------------------------------------------------------------------------------- 1 | /* Java Exception Handling Try Catch 2 | Exception handling is the process of responding to the occurrence, during computation, of 3 | exceptions – anomalous or exceptional conditions requiring special processing – often changing 4 | the normal flow of program execution. (Wikipedia) 5 | Java has built-in mechanism to handle exceptions. Using the try statement we can test a block 6 | of code for errors. The catch block contains the code that says what to do if exception occurs. 7 | 8 | This problem will test your knowledge on try-catch block. 9 | 10 | You will be given two integers x and y as input, you have to compute x/y. If x and y are 11 | not 32 bit signed integers or if y is zero, exception will occur and you have to report it. 12 | Read sample Input/Output to know what to report in case of exceptions. 13 | 14 | Sample Input 1: 15 | 16 | 10 17 | 3 18 | 19 | Sample Output 1: 20 | 21 | 3 22 | 23 | Sample Input 2: 24 | 25 | 10 26 | Hello 27 | 28 | Sample Output 2: 29 | 30 | java.util.InputMismatchException 31 | 32 | Sample Input 3: 33 | 34 | 10 35 | 0 36 | 37 | Sample Output 3: 38 | 39 | java.lang.ArithmeticException: / by zero 40 | 41 | Sample Input 4: 42 | 43 | 23.323 44 | 0 45 | Sample Output 4: 46 | 47 | java.util.InputMismatchException 48 | */ 49 | import java.io.*; 50 | import java.util.*; 51 | import java.text.*; 52 | import java.math.*; 53 | import java.util.regex.*; 54 | 55 | public class JavaExceptionHanldingTryCatch { 56 | 57 | public static void main(String[] args) { 58 | /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ 59 | Scanner sc = new Scanner(System.in); 60 | try{ 61 | try{ 62 | int x = new Integer(sc.nextInt()); 63 | int y = new Integer(sc.nextInt()); 64 | System.out.println(""+(x/y)); 65 | }catch (InputMismatchException e){ 66 | System.out.println("java.util.InputMismatchException"); 67 | } 68 | 69 | }catch(Exception e){ 70 | System.out.println(e); 71 | } 72 | 73 | } 74 | } -------------------------------------------------------------------------------- /Java/Introduction/JavaDatatypes.java: -------------------------------------------------------------------------------- 1 | /* Java Datatypes 2 | 3 | Java has 8 Primitive Data Types; they are char, boolean, byte, short, int, long, float, and double. In this problem we are only concerned about integer datatypes used to hold integer values (byte, short, int, long). Let's take a closer look at them: 4 | 5 | byte data type is an 8-bit signed integer. 6 | short data type is an 16-bit signed integer. 7 | int data type is an 32-bit signed integer. 8 | long data type is an 64-bit signed integer. 9 | (Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html) 10 | 11 | Given an integer number, you have to determine which of these datatypes you can use to store that number. 12 | If there are multiple suitable datatypes, list them all in the order above. 13 | 14 | Input Format 15 | 16 | The first line will contain an integer T, which denotes the number of inputs that will follow. 17 | Each of the next T lines will contain an integer n. The number can be arbitrarily large or small! 18 | 19 | Output Format 20 | 21 | For each n, list all the datatypes it can be fitted into ordered by the size of the datatype. 22 | If it can't be fitted into any of these datatypes, print "n can't be fitted anywhere." See the sample output for the exact 23 | formatting. 24 | 25 | */ 26 | 27 | import java.io.*; 28 | import java.util.*; 29 | import java.text.*; 30 | import java.math.*; 31 | import java.util.regex.*; 32 | 33 | public class JavaDatatypes { 34 | 35 | static String whoCanFitTheNumber(String numString) 36 | { 37 | String answer = ""; 38 | try{ 39 | long num = Long.parseLong(numString); 40 | answer = numString + " can be fitted in:\n"; 41 | if((num<=Byte.MAX_VALUE) && (num>=Byte.MIN_VALUE)){ 42 | answer = answer.concat("* byte\n* short\n* int\n* long"); 43 | }else if((num <= Short.MAX_VALUE) && (num >= Short.MIN_VALUE)){ 44 | answer = answer.concat("* short\n* int\n* long"); 45 | }else if((num <= Integer.MAX_VALUE) && (num >= Integer.MIN_VALUE)){ 46 | answer = answer.concat("* int\n* long"); 47 | }else{ 48 | answer = answer.concat("* long"); 49 | } 50 | }catch (NumberFormatException e){ 51 | answer = numString+" can't be fitted anywhere."; 52 | } 53 | return answer; 54 | } 55 | public static void main(String[] args) { 56 | /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. 57 | */ 58 | Scanner scanner = new Scanner(System.in); 59 | int numTestCases = scanner.nextInt() ; 60 | scanner.nextLine(); 61 | for(int i=0; i42 26 | element[1]=>10 27 | element[2]=>"###" 28 | element[3]=>"Hello" 29 | element[4]=>"Java" 30 | You have to modify the func method by editing at most 2 lines so that the code only prints the elements 31 | after the special string "###". For the sample above the output will be: 32 | 33 | Hello 34 | Java 35 | Note: The stdin doesn't contain the string "###", it is added in the main method. 36 | */ 37 | 38 | import java.util.*; 39 | public class JavaIterator 40 | { 41 | static Iterator func(ArrayList mylist) 42 | { 43 | Iterator it=mylist.iterator(); 44 | while(it.hasNext()) 45 | { 46 | Object element = it.next(); 47 | if(element instanceof String) //Hints: use instanceof operator 48 | break; 49 | } 50 | return it; 51 | 52 | } 53 | 54 | public static void main(String []argh) 55 | { 56 | ArrayList mylist = new ArrayList(); 57 | Scanner sc=new Scanner(System.in); 58 | int n=sc.nextInt(); 59 | int m=sc.nextInt(); 60 | for(int i=0;i0){ 60 | String input = in.nextLine(); 61 | Matcher m = r.matcher(input); 62 | boolean findMatch = true; 63 | while(m.find( )){ 64 | input = input.replaceAll(pattern,"$1"); 65 | findMatch = false; 66 | } 67 | System.out.println(input); 68 | testCases--; 69 | } 70 | } 71 | } 72 | 73 | -------------------------------------------------------------------------------- /Java/Strings/JavaRegex3.java: -------------------------------------------------------------------------------- 1 | /* 2 | Java Regex 3 - Username Checker 3 | 4 | Regular expressions (regexp) help us match or search for patterns in strings. In this problem, you will be given a username. 5 | Your task is to check whether that username is valid. A valid username will have the following properties: 6 | 7 | The username can contain alphanumeric characters and/or underscores(_). 8 | The username must start with an alphabetic character. 9 | 8 ≤ |Username| ≤ 30. 10 | To simplify your task, we have provided a portion of the code in the editor. You just need to write down the regex pattern 11 | which will be used to validate the username input. 12 | 13 | Input Format 14 | 15 | The first line of input contains an integer N, representing the number of testcases. Each of the next N lines contains a 16 | string that represents a username. 17 | 18 | Constraints 19 | 20 | The username consists of any printable characters. 21 | 22 | 1≤N≤50 23 | Output Format 24 | 25 | For each username, output Valid if the username is valid; otherwise, output Invalid. 26 | 27 | Sample Input 28 | 29 | 4 30 | alpha_naheed 31 | xahidbuffon 32 | nagib@007 33 | 123Swakkhar 34 | 35 | Sample Output 36 | 37 | Valid 38 | Valid 39 | Invalid 40 | Invalid 41 | */ 42 | 43 | 44 | String pattern = "^[a-zA-Z][a-zA-Z0-9_]{7,29}$"; 45 | 46 | -------------------------------------------------------------------------------- /Java/Strings/JavaStringCompare.java: -------------------------------------------------------------------------------- 1 | /* Java String Compare 2 | 3 | Given a string, find out the lexicographically smallest and largest substring of length k. 4 | 5 | [Note: Lexicographic order is also known as alphabetic order dictionary order. So "ball" is smaller than "cat", "dog" is smaller 6 | than "dorm". Capital letter always comes before smaller letter, so "Happy" is smaller than "happy" and "Zoo" is smaller than "ball".] 7 | 8 | Input Format 9 | 10 | First line will consist a string containing english alphabets which has at most 1000 characters. 11 | 2nd line will consist an integer k. 12 | 13 | Output Format 14 | 15 | In the first line print the lexicographically minimum substring. In the second line print the lexicographically maximum substring. 16 | 17 | */ 18 | 19 | import java.io.*; 20 | import java.util.*; 21 | import java.text.*; 22 | import java.math.*; 23 | import java.util.regex.*; 24 | 25 | public class Solution { 26 | 27 | public static void main(String[] args) { 28 | Scanner sc = new Scanner(System.in); 29 | String inputString = sc.nextLine(); 30 | int length = sc.nextInt(); 31 | String smallest=""; 32 | String largest=""; 33 | for(int i = 0;i<=inputString.length()-length;i++){ 34 | String subString = inputString.substring(i,i+length); 35 | if(i == 0){ 36 | smallest = subString; 37 | } 38 | if(subString.compareTo(largest)>0){ 39 | largest = subString; 40 | }else if(subString.compareTo(smallest)<0) 41 | smallest = subString; 42 | } 43 | System.out.println(smallest); 44 | System.out.println(largest); 45 | 46 | } 47 | } -------------------------------------------------------------------------------- /Java/Strings/JavaStringReverse.java: -------------------------------------------------------------------------------- 1 | /* Java String Reverse 2 | 3 | Problem Statement 4 | 5 | A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward.(Wikipedia) 6 | Given a string A, print "Yes" if it is a palindrome, print "No" otherwise. The strings will consist lower case english letters only. 7 | The strings will have at most 50 characters. 8 | 9 | Some examples of palindromes are "madam", "anna", "reviver". 10 | 11 | Sample Input 12 | 13 | madam 14 | Sample Output 15 | 16 | Yes 17 | */ 18 | 19 | import java.io.*; 20 | import java.util.*; 21 | 22 | public class JavaStringReverse { 23 | 24 | public static boolean isPalindrome(String word) 25 | { 26 | boolean isPalindrome = true; 27 | 28 | for(int i = 0;i<(int)word.length()/2;i++) 29 | { 30 | if(word.charAt(i) != word.charAt(word.length()-1-i)){ 31 | isPalindrome = false; 32 | break; 33 | 34 | } 35 | } 36 | 37 | return isPalindrome; 38 | } 39 | public static void main(String[] args) { 40 | 41 | Scanner sc=new Scanner(System.in); 42 | String A=sc.next(); 43 | System.out.println(isPalindrome(A)?"Yes":"No"); 44 | 45 | } 46 | } -------------------------------------------------------------------------------- /Java/Strings/JavaStringToken.java: -------------------------------------------------------------------------------- 1 | /* Java String Token 2 | 3 | Given a string, find number of words in that string. For this problem a word is defined by a string of one or more 4 | english alphabets. 5 | 6 | There are multiple ways to tokenize a string in java, learn how to tokenize a string in java and demonstrate your 7 | skill by solving this problem! 8 | 9 | Input Format 10 | A string not more than 400000 characters long. The string can be defined by following regular expression: 11 | 12 | [A-Za-z !,?.\_'@]+ 13 | That means the string will only contain english alphabets, blank spaces and this characters: "!,?._'@". 14 | 15 | Output Format 16 | In the first line, print number of words n in the string. The words don't need to be unique. In the next n lines, 17 | print all the words you found in the order they appeared in the input. 18 | 19 | Sample Input 20 | 21 | He is a very very good boy, isn't he? 22 | Sample Output 23 | 24 | 10 25 | He 26 | is 27 | a 28 | very 29 | very 30 | good 31 | boy 32 | isn 33 | t 34 | he 35 | */ 36 | 37 | import java.io.*; 38 | import java.util.*; 39 | import java.text.*; 40 | import java.math.*; 41 | import java.util.regex.*; 42 | 43 | public class JavaStringToken { 44 | 45 | public static void main(String[] args) { 46 | Scanner sc = new Scanner(System.in); 47 | 48 | if (!sc.hasNext()){ 49 | System.out.println(0); 50 | }else { 51 | String input=sc.nextLine(); 52 | String[]a = input.trim().split("[ !,?._'@]+"); 53 | ArrayListlistOfStrings =new ArrayList(Arrays.asList(a)); 54 | System.out.println(listOfStrings.size()); 55 | 56 | for(String str:listOfStrings){ 57 | System.out.println(str); 58 | } 59 | } 60 | 61 | 62 | 63 | } 64 | } -------------------------------------------------------------------------------- /Java/Strings/JavaStrings.java: -------------------------------------------------------------------------------- 1 | /* Java Strings 2 | Today we will learn about java strings. Your task is simple, given a string, find out the lexicographically smallest and largest substring of length k. 3 | 4 | [Note: Lexicographic order is also known as alphabetic order dictionary order. So "ball" is smaller than "cat", "dog" is smaller than "dorm". Capital letter always comes before smaller letter, so "Happy" is smaller than "happy" and "Zoo" is smaller than "ball".] 5 | 6 | Input Format 7 | 8 | First line will consist a string containing english alphabets which has at most 1000 characters. 2nd line will consist an integer k. 9 | 10 | Output Format 11 | 12 | In the first line print the lexicographically minimum substring. In the second line print the lexicographically maximum substring. 13 | */ 14 | 15 | import java.io.*; 16 | import java.util.*; 17 | import java.text.*; 18 | import java.math.*; 19 | import java.util.regex.*; 20 | 21 | public class JavaStrings { 22 | 23 | public static void main(String[] args) { 24 | 25 | Scanner sc = new Scanner(System.in); 26 | String inputString = sc.nextLine(); 27 | int length = sc.nextInt(); 28 | String smallest=""; 29 | String largest=""; 30 | for(int i = 0;i<=inputString.length()-length;i++){ 31 | String subString = inputString.substring(i,i+length); 32 | if(i == 0){ 33 | smallest = subString; 34 | } 35 | if(subString.compareTo(largest)>0){ 36 | largest = subString; 37 | }else if(subString.compareTo(smallest)<0) 38 | smallest = subString; 39 | } 40 | System.out.println(smallest); 41 | System.out.println(largest); 42 | 43 | } 44 | } -------------------------------------------------------------------------------- /Java/Strings/PatternSyntaxChecker.java: -------------------------------------------------------------------------------- 1 | /* Patern Syntax Checker 2 | 3 | Using Regex, we can easily match or search for patterns in a text. Before searching for a pattern, 4 | we have to specify one using some well-defined syntax. 5 | 6 | In this problem, you are given a pattern. You have to check whether the syntax of the given pattern is valid. 7 | 8 | Note: In this problem, a regex is only valid if you can compile it using the Pattern.compile method. 9 | 10 | Input Format 11 | 12 | The first line of input contains an integer N, denoting the number of testcases. The next N lines contain a 13 | string of any printable characters representing the pattern of a regex. 14 | 15 | Output Format 16 | 17 | For each testcase, print "Valid" if the syntax of the given pattern is correct. Otherwise, print "Invalid". 18 | Do not print the quotes. 19 | 20 | Sample Input 21 | 22 | 3 23 | ([A-Z])(.+) 24 | [AZ[a-z](a-z) 25 | batcatpat(nat 26 | 27 | Sample Output 28 | 29 | Valid 30 | Invalid 31 | Invalid 32 | 33 | */ 34 | 35 | 36 | import java.util.Scanner; 37 | import java.util.regex.*; 38 | 39 | public class PatternSyntaxChecker 40 | { 41 | public static void main(String[] args){ 42 | Scanner in = new Scanner(System.in); 43 | int testCases = Integer.parseInt(in.nextLine()); 44 | while(testCases>0){ 45 | testCases--; 46 | String pattern = in.nextLine(); 47 | //Write your code 48 | try{ 49 | Pattern.compile(pattern); 50 | System.out.println("Valid"); 51 | }catch(PatternSyntaxException e){ 52 | System.out.println("Invalid"); 53 | } 54 | 55 | 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | My Solutions to Hackerrank.com Challenges --------------------------------------------------------------------------------