diff --git a/.gitignore b/.gitignore index 84c048a..b7d5a53 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,80 @@ /build/ + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +.settings/** + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +.idea/sonarlint diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..84da703 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..003b7f0 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.settings/.jsdtscope b/.settings/.jsdtscope deleted file mode 100644 index fd53605..0000000 --- a/.settings/.jsdtscope +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 0c68a61..0000000 --- a/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,7 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/.settings/org.eclipse.wst.common.component b/.settings/org.eclipse.wst.common.component deleted file mode 100644 index 76b9c7a..0000000 --- a/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/.settings/org.eclipse.wst.common.project.facet.core.xml b/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index f4ef8aa..0000000 --- a/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/.settings/org.eclipse.wst.jsdt.ui.superType.container b/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a..0000000 --- a/.settings/org.eclipse.wst.jsdt.ui.superType.container +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/.settings/org.eclipse.wst.jsdt.ui.superType.name b/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b..0000000 --- a/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/Codes/CommonDivisorHE.java b/Codes/CommonDivisorHE.java new file mode 100644 index 0000000..7a44509 --- /dev/null +++ b/Codes/CommonDivisorHE.java @@ -0,0 +1,31 @@ +import java.util.Scanner; + +public class CommonDivisorHE { + + public static void main(String[] args) { + // TODO Auto-generated method stub + Scanner in = new Scanner(System.in); + System.out.println("Enter the numbers"); + int a = in.nextInt(); + int b = in.nextInt(); + int count = 0; + if(a>b){ + //int count =0; + for(int i =1;i<=a;i++){ + if(a%i == 0 && b%i == 0){ + count++; + } + } + }else if(a= 2){ + return "NO"; + } + return "YES"; + + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + /* Scanner in = new Scanner(System.in); + System.out.println("Enter the length of array"); + int l = in.nextInt(); + int arr[] = new int[l]; + + System.out.println("Enter the elements of array"); + for(int i=0;i=0 && arr[j]>key){ - arr[j+1] = arr[j]; - j = j-1; - } - arr[j+1] = key; - } - } - void printarray(int arr[]){ - int n = arr.length; - for(int i=0;i= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } + + } + + void printarray(int arr[]) { + int n = arr.length; + for (int i = 0; i < n; i++) { + System.out.println(arr[i] + " "); + } + System.out.println(); + } + + public static void main(String[] args) { + Insertion_sort ob = new Insertion_sort(); + int arr[] = {12, 11, 13, 5, 6, 1, 8}; + ob.sort(arr); + ob.printarray(arr); + } } \ No newline at end of file diff --git a/Codes/LinkedList_Recursive.java b/Codes/LinkedList_Recursive.java index 0820bea..515a380 100644 --- a/Codes/LinkedList_Recursive.java +++ b/Codes/LinkedList_Recursive.java @@ -1,4 +1,5 @@ -// Recursive Java program to count number of nodes in +/* +// Recursive Java program to count number of nodes in // a linked list class Node @@ -40,4 +41,4 @@ public static void main(String[] args) System.out.println("Count of nodes is " + lList.getCount()); } -} \ No newline at end of file +}*/ diff --git a/Codes/MatrixOperations.java b/Codes/MatrixOperations.java new file mode 100644 index 0000000..0d41d7e --- /dev/null +++ b/Codes/MatrixOperations.java @@ -0,0 +1,59 @@ +import java.util.Scanner; + +public class MatrixOperations { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Scanner in = new Scanner(System.in); + + int board[][] = new int[256][256]; + for(int i=0;i<=255;i++){ + for(int j=0;j<=255;j++){ + board[i][j] = 0; + } + } + + + while(in.hasNext()){ + String line = in.nextLine(); + String elements[] = line.split("\\s"); + String command = elements[0]; + int target = Integer.parseInt(elements[1]); + int value = 0; + + + if(command.equalsIgnoreCase("setrow")){ + value = Integer.parseInt(elements[2]); + for(int i=0;i<256;i++){ + board[target][i] = value; + } + } + + if(command.equalsIgnoreCase("setcol")){ + value = Integer.parseInt(elements[2]); + for(int i=0;i<256;i++){ + board[i][target] = value; + } + } + + + if(command.equalsIgnoreCase("querycol")){ + int total = 0; + for(int i=0;i<256;i++){ + total += board[i][target]; + } + System.out.println(total); + } + + if(command.equalsIgnoreCase("queryrow")){ + int total = 0; + for(int i=0;i<256;i++){ + total += board[target][i]; + } + System.out.println(total); + } + } + } +} + diff --git a/Codes/PairRecoveryHE.java b/Codes/PairRecoveryHE.java new file mode 100644 index 0000000..133f4cb --- /dev/null +++ b/Codes/PairRecoveryHE.java @@ -0,0 +1,28 @@ +import java.util.Scanner; + +public class PairRecoveryHE { + + public static void calculate(int a3, int a4) + { + int a1,a2 = 0; + int temp = a4-a3; + a2 = temp; + int temp1 = a3-a2; + a1 = temp1; + + System.out.println(a1 +" "+a2); + + } + + + public static void main(String[] args) { + // TODO Auto-generated method stub + Scanner in = new Scanner(System.in); + int a3 = in.nextInt(); + int a4 = in.nextInt(); + + calculate(a3,a4); + + } + +} diff --git a/Codes/StringRev_Stack.java b/Codes/StringRev_Stack.java deleted file mode 100644 index 4c6ff7b..0000000 --- a/Codes/StringRev_Stack.java +++ /dev/null @@ -1,30 +0,0 @@ -// String reverse using stack. - -package stringpractice; - -import java.util.Scanner; -import java.util.Stack; - -public class StringRev_Stack { - - public static void main(String[] args) { - // TODO Auto-generated method stub - Stack st = new Stack(); - Scanner in = new Scanner(System.in); - System.out.println("Enter the string: "); - String s = in.nextLine(); - - for(char c : s.toCharArray()){ - st.push(c); - } - System.out.println("Stack is: "+st ); - - String output = ""; - while(!st.isEmpty()){ - char ch = st.pop(); - output = output + ch; - } - System.out.println(output); - } - -} diff --git a/Codes/loop_LinkedList.java b/Codes/loop_LinkedList.java index 70fd4f1..8b02df5 100644 --- a/Codes/loop_LinkedList.java +++ b/Codes/loop_LinkedList.java @@ -20,6 +20,7 @@ int detectAndRemoveLoop(Node node) { fast = fast.next.next; if (slow == fast) { + System.out.println(slow.data); removeLoop(slow, node); return 1; } diff --git a/Codes/testcommit.java b/Codes/testcommit.java index 2b07fc5..a50a6a2 100644 --- a/Codes/testcommit.java +++ b/Codes/testcommit.java @@ -3,6 +3,25 @@ public class testcommit { public static void main(String[] args) { // TODO Auto-generated method stub + String s = "hello i'm lOOking for a Java Developer Position."; + s.toLowerCase(); + char[] c = s.toCharArray(); + + + for(int i=0;i + + + + + + + + + + + + \ No newline at end of file diff --git a/README.md b/README.md index b1e4162..d3038d7 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,3 @@ -# Java-Practice +# Java-practice Contains Various programming questions asked in interviews and from various coding challanges sites. diff --git a/props.properties b/props.properties new file mode 100644 index 0000000..573589d --- /dev/null +++ b/props.properties @@ -0,0 +1,2 @@ +A=10 +b=20 \ No newline at end of file diff --git a/src/ChainInspection.java b/src/ChainInspection.java new file mode 100644 index 0000000..edd3d77 --- /dev/null +++ b/src/ChainInspection.java @@ -0,0 +1,32 @@ +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + +public class ChainInspection { + + public static void main(String[] args) { + String input = "4-2;BEGIN-3;3-4;2-END"; + String[] tempArr = input.split(";"); + for(int i=0;i map = new HashMap(); + for(String s: tempArr) { + String[] elements = s.split("-"); + map.put(elements[0], elements[1]); + /*for(int i=0;i s: map.entrySet()) { + if(s.getKey().equals(s.getValue())) + System.out.println("bad"); + else if(map.get("BEGIN") != null) { + System.out.println(map.get("BEGIN")); + } + } + } + +} \ No newline at end of file diff --git a/src/Consecutive1TF.java b/src/Consecutive1TF.java new file mode 100644 index 0000000..f5275d2 --- /dev/null +++ b/src/Consecutive1TF.java @@ -0,0 +1,30 @@ +import java.util.Scanner; + +public class Consecutive1TF { + + + public static boolean checkAppearance(String[] arr) { + boolean result = false; + + for(int i=0;i strings = new ArrayList<>(Arrays.asList(arr)); + strings.stream() + .collect(HashMap::new, (h, o) -> h.put(h.size(), o), (h, o) -> {}) + .forEach((i, o) -> { + System.out.println(String.format("%d => %s", i, o)); + }); + }*/ + + + public static void main(String[] args) { + + Integer[] a = {0, 1, 20, 3, 40, 5}; + + print(a); + } +} diff --git a/src/careercup/ReorderArray.java b/src/careercup/ReorderArray.java new file mode 100644 index 0000000..716c0c1 --- /dev/null +++ b/src/careercup/ReorderArray.java @@ -0,0 +1,40 @@ +//not done :( + +package careercup; + +public class ReorderArray { + + public static int reorder(int[] arr) { + + int oddI = 0; + int evenI = 0; + int count = 0; + + if (evenI < arr.length && (arr[evenI] % 2 == 0)) { + evenI = evenI + 2; + } + + if (oddI < arr.length && (arr[oddI] % 2 == 1)) { + oddI = oddI + 2; + } + + if (evenI < arr.length && oddI < arr.length) { + count++; + int temp = arr[evenI]; + arr[evenI] = arr[oddI]; + arr[oddI] = temp; + } + + for(int a : arr) { + System.out.println(a); + } + //System.out.println(count); + return 5; + + } + + + public static void main(String[] args) { + reorder(new int[]{2, 1, 3, 4}); + } +} diff --git a/src/careercup/Test1.java b/src/careercup/Test1.java new file mode 100644 index 0000000..404abb0 --- /dev/null +++ b/src/careercup/Test1.java @@ -0,0 +1,24 @@ +package careercup; + +public class Test1 { + + + public static String foo(String s) { + + char[] chars = s.toCharArray(); + int right = chars.length - 1; + for (int left = 0; left < right; left++) { + char swap = chars[left]; + chars[left] = chars[right]; + chars[right--] = swap; + } + + return new String(chars); + } + + public static void main(String[] args) { + System.out.println(foo("hello world")); + } + + +} diff --git a/src/codewars/DeleteAndEarnHackerRank.java b/src/codewars/DeleteAndEarnHackerRank.java new file mode 100644 index 0000000..00fa233 --- /dev/null +++ b/src/codewars/DeleteAndEarnHackerRank.java @@ -0,0 +1,54 @@ +package codewars; + +import java.util.Arrays; +import java.util.HashMap; + +public class DeleteAndEarnHackerRank { + + + public static int deleteAndEarn(int[] nums) { + if (nums == null || nums.length == 0) + return 0; + else if (nums.length == 1) + return nums[0]; + + // sum and hash + HashMap numMap = new HashMap<>(); + for (int num : nums) { + if (numMap.containsKey(num)) { + numMap.put(num, numMap.get(num) + num); + } else + numMap.put(num, num); + } + + // sorted num + Integer[] uniqueNums = new Integer[numMap.size()]; + uniqueNums = numMap.keySet().toArray(uniqueNums); + Arrays.sort(uniqueNums); + + + int prevSum = 0; + int prevLSum = 0; + for (int i = 0; i < uniqueNums.length; i++) { + int temp = 0; + if (i - 1 >= 0 && uniqueNums[i - 1] == uniqueNums[i] - 1) { + temp = Math.max(prevLSum + numMap.get(uniqueNums[i]), prevLSum); + } else { + temp = prevSum + numMap.get(uniqueNums[i]); + } + + prevLSum = prevSum; + prevSum = temp; + } + + return prevSum; + } + + public static void main(String[] args) { + //int[] arr = {3, 4, 2}; + int[] arr = {5, 6, 6, 4, 11}; + + System.out.println(deleteAndEarn(arr)); + } + +} \ No newline at end of file diff --git a/src/codewars/FindTheMissingLetter.java b/src/codewars/FindTheMissingLetter.java new file mode 100644 index 0000000..65caca3 --- /dev/null +++ b/src/codewars/FindTheMissingLetter.java @@ -0,0 +1,24 @@ +package codewars; + +public class FindTheMissingLetter { + + public static char findMissingLetter(char[] array) { + + char letter = 'a'; + + for(int i= 0; i< array.length;i++) { + if(array[i+1] - array[i] != 1) { + char b = array[i]; + int letterValue = b + 1; + letter = (char) letterValue; + break; + } + } + return letter; + } + + public static void main(String[] args) { + System.out.println(findMissingLetter(new char[] { 'a','b','c','d','f' })); + System.out.println(findMissingLetter(new char[] { 'O','Q','R','S' })); + } +} diff --git a/src/codewars/GetMiddleChar.java b/src/codewars/GetMiddleChar.java new file mode 100644 index 0000000..8a7bb9a --- /dev/null +++ b/src/codewars/GetMiddleChar.java @@ -0,0 +1,32 @@ +/** + * You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. + * If the word's length is even, return the middle 2 characters. + */ + + +package codewars; + +public class GetMiddleChar { + + public static String getMiddle(String word) { + + int a; + if (word.length() == 1 || word.length() == 2) { + return word; + } + + if (word.length() % 2 == 0) { + return word.substring((word.length() / 2) - 1, (word.length() / 2) + 1); + } else { + a = (int) Math.ceil(word.length() / 2); + return word.substring(a, a+1); + } + } + + public static void main(String[] args) { + System.out.println(getMiddle("testing")); + System.out.println(getMiddle("test")); + System.out.println(getMiddle("A")); + System.out.println(getMiddle("middle")); + } +} diff --git a/src/codewars/GiveMeADiamond.java b/src/codewars/GiveMeADiamond.java new file mode 100644 index 0000000..ee961db --- /dev/null +++ b/src/codewars/GiveMeADiamond.java @@ -0,0 +1,42 @@ +/** + * Jamie is a programmer, and James' girlfriend. She likes diamonds, and wants a diamond string from James. + * Since James doesn't know how to make this happen, he needs your help. + * + * Task + * You need to return a string that looks like a diamond shape when printed on the screen, using asterisk (*) characters. + * Trailing spaces should be removed, and every line must be terminated with a newline character (\n). + * + * Return null/nil/None/... if the input is an even number or negative, as it is not possible to print a diamond of even or negative size. + * + */ + + + +package codewars; + +public class GiveMeADiamond { + + public static String print(int n) { + if (n % 2 == 0 || n <= 0) return null; + StringBuffer sb = new StringBuffer(); + int mid = n / 2 + 1; + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= Math.abs(mid - i); j++) { + sb.append(" "); + } + if (i <= mid) { + for (int j = 1; j <= 2 * i - 1; j++) + sb.append("*"); + } else { + for (int j = 1; j <= 2 * (2 * mid - i) - 1; j++) + sb.append("*"); + } + sb.append("\n"); + } + return sb.toString(); + } + + public static void main(String[] args) { + System.out.println(print(5)); + } +} diff --git a/src/codewars/HelptheBookSeller.java b/src/codewars/HelptheBookSeller.java new file mode 100644 index 0000000..a7835ca --- /dev/null +++ b/src/codewars/HelptheBookSeller.java @@ -0,0 +1,57 @@ +/** + * A bookseller has lots of books classified in 26 categories labeled A, B, ... Z. Each book has a code c of 3, 4, 5 or more capitals letters. + * The 1st letter of a code is the capital letter of the book category. In the bookseller's stocklist each code c is followed by a space and by a positive integer n (int n >= 0) which indicates the quantity of books of this code in stock. + * + * For example an extract of one of the stocklists could be: + * + * L = {"ABART 20", "CDXEF 50", "BKWRK 25", "BTSQZ 89", "DRTYM 60"}. + * M = {"A", "B", "C", "W"} + * + * + * output: + * (A : 20) - (B : 114) - (C : 50) - (W : 0) + */ + +package codewars; + +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; + +public class HelptheBookSeller { + + public static String stockSummary(String[] lstOfArt, String[] lstOf1stLetter) { + Map result = new HashMap<>(); + + for (String s : lstOfArt) { + String[] splitRes = s.split(" "); + + String s1 = splitRes[0]; + + for (String x : lstOf1stLetter) { + if (x.equalsIgnoreCase(String.valueOf(s1.toCharArray()[0]))) { + + if (result.containsKey(String.valueOf(s1.toCharArray()[0]))) { + result.put(String.valueOf(s1.toCharArray()[0]), result.get(String.valueOf(s1.toCharArray()[0])) + Integer.valueOf(splitRes[1])); + } else { + result.put((String.valueOf(s1.toCharArray()[0])), Integer.valueOf(splitRes[1])); + } + } + } + } + String content = result.entrySet() + .stream() + .map(e -> "("+e.getKey() + " : " + e.getValue() + ")") + .collect(Collectors.joining("-")); + + // your code here + return content; + } + + + public static void main(String[] args) { + String[] art = new String[]{"ABAR 200", "CDXE 500", "BKWR 250", "BTSQ 890", "DRTY 600"}; + String[] cd = {"A", "B" ,"E"}; + System.out.println(stockSummary(art, cd)); + } +} diff --git a/src/codewars/HighestScoringWord.java b/src/codewars/HighestScoringWord.java new file mode 100644 index 0000000..cc7f501 --- /dev/null +++ b/src/codewars/HighestScoringWord.java @@ -0,0 +1,42 @@ +/** + * Given a string of words, you need to find the highest scoring word. + *

+ * Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc. + * You need to return the highest scoring word as a string. + *

+ * If two words score the same, return the word that appears earliest in the original string. + * All letters will be lowercase and all inputs will be valid. + */ + + +package codewars; + +public class HighestScoringWord { + + public static String high(String s) { + + String[] words = s.split(" "); + int highestScore = 0; + String finalWord = ""; + + for (String str : words) { + int score = 0; + for (char c : str.toCharArray()) { + score += c - 'a' + 1; + } + + if (score > highestScore) { + finalWord = str; + highestScore = score; + } + } + + return finalWord; + } + + public static void main(String[] args) { + System.out.println(high("man i need a taxi up to ubud txai")); + System.out.println(high("what time are we climbing up to the volcano")); + System.out.println(high("take me to semynak")); + } +} diff --git a/src/codewars/MoneyMoneyMoney.java b/src/codewars/MoneyMoneyMoney.java new file mode 100644 index 0000000..0056592 --- /dev/null +++ b/src/codewars/MoneyMoneyMoney.java @@ -0,0 +1,47 @@ +/** + * Mr. Scrooge has a sum of money 'P' that wants to invest, and he wants to know how many years 'Y' this sum has to be kept in the bank in order for this sum of money to amount to 'D'. + * + * The sum is kept for 'Y' years in the bank where interest 'I' is paid yearly, and the new sum is re-invested yearly after paying tax 'T' + * + * Note that the principal is not taxed but only the year's accrued interest + * + * Example: + * Let P be the Principal = 1000.00 + * Let I be the Interest Rate = 0.05 + * Let T be the Tax Rate = 0.18 + * Let D be the Desired Sum = 1100.00 + * + * + * After 1st Year --> + * P = 1041.00 + * After 2nd Year --> + * P = 1083.86 + * After 3rd Year --> + * P = 1128.30 + */ + + +package codewars; + +public class MoneyMoneyMoney { + + public static int calculateYears(double principal, double interest, double tax, double desired) { + + double interestYearly; + double taxRes; + int counter = 0; + + while (principal < desired) { + counter++; + interestYearly = principal * interest; + taxRes = interestYearly * tax; + principal = principal + (interestYearly - taxRes); + } + return counter; + } + + public static void main(String[] args) { + System.out.println(calculateYears(1000, 0.05, 0.18, 1100)); + System.out.println(calculateYears(1000,0.05,0.18,1000)); + } +} diff --git a/src/codewars/OddOccuranceArrayElement.java b/src/codewars/OddOccuranceArrayElement.java new file mode 100644 index 0000000..d2f6242 --- /dev/null +++ b/src/codewars/OddOccuranceArrayElement.java @@ -0,0 +1,44 @@ +/** + * return the input integer with odd occurrences + */ + +package codewars; + +import java.util.HashMap; +import java.util.Map; + +public class OddOccuranceArrayElement { + + public static int findIt(int[] a) { + int odd = 0; + + Map resMap = new HashMap<>(); + + for(int i= 0;i entry : resMap.entrySet()) { + if(entry.getValue() %2 == 1) { + odd = entry.getKey(); + } + } + + return odd; + } + + + + public static void main(String[] args) { + System.out.println(findIt(new int[]{20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5})); + System.out.println(findIt(new int[]{1,1,2,-2,5,2,4,4,-1,-2,5})); + System.out.println(findIt(new int[]{20,1,1,2,2,3,3,5,5,4,20,4,5})); + System.out.println(findIt(new int[]{10})); + System.out.println(findIt(new int[]{1,1,1,1,1,1,10,1,1,1,1})); + System.out.println(findIt(new int[]{5,4,3,2,1,5,4,3,2,10,10})); + } +} diff --git a/src/codewars/Scramblies.java b/src/codewars/Scramblies.java new file mode 100644 index 0000000..7e953b6 --- /dev/null +++ b/src/codewars/Scramblies.java @@ -0,0 +1,39 @@ +/** + * Complete the function scramble(str1, str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false. + * + * Notes: + * + * Only lower case letters will be used (a-z). No punctuation or digits will be included. + * Performance needs to be considered + */ + + +package codewars; + +public class Scramblies { + + public static boolean scramble(String str1, String str2) { + + for (int i = 0; i < str1.length(); i++) { + str2 = str2.replaceFirst("" + str1.charAt(i), ""); + if (str2.isEmpty()) { + return true; + } + } + return false; + } + + + public static void main(String[] args) { + System.out.println(scramble("rkqodlw", "world")); + System.out.println(scramble("cedewaraaossoqqyt", "codewars")); + System.out.println(scramble("katas", "steak")); + System.out.println(scramble("scriptjavx", "javascript")); + System.out.println(scramble("scriptingjava", "javascript")); + System.out.println(scramble("scriptsjava", "javascripts")); + System.out.println(scramble("javscripts", "javascript")); + System.out.println(scramble("aabbcamaomsccdd", "commas")); + System.out.println(scramble("commas", "commas")); + System.out.println(scramble("sammoc", "commas")); + } +} diff --git a/src/codewars/SumOfNumbers.java b/src/codewars/SumOfNumbers.java new file mode 100644 index 0000000..9bd9dfc --- /dev/null +++ b/src/codewars/SumOfNumbers.java @@ -0,0 +1,42 @@ +/** + * Given two integers a and b, which can be positive or negative, find the sum of all the numbers between including them too and return it. + * If the two numbers are equal return a or b. + * + * Note: a and b are not ordered! + */ + + + +package codewars; + +public class SumOfNumbers { + + public static int getSum(int a , int b) { + int result = 0; + + if(a == b ){ + return a; + } + + if(a > b) { + for(int i= b ; i<=a; i++) { + result = result+i; + } + }else { + for(int i=a;i<=b;i++){ + result = result+i; + } + } + return result; + } + + public static void main(String[] args) { + System.out.println(getSum(0,-1)); + System.out.println(getSum(0,1)); + System.out.println(getSum(1,2)); + System.out.println(getSum(0,1)); + System.out.println(getSum(1,1)); + System.out.println(getSum(-1,0)); + System.out.println(getSum(-1,2)); + } +} diff --git a/src/codewars/WhoLikesIt.java b/src/codewars/WhoLikesIt.java new file mode 100644 index 0000000..6ab2b18 --- /dev/null +++ b/src/codewars/WhoLikesIt.java @@ -0,0 +1,34 @@ +/** + * You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other items. + * We want to create the text that should be displayed next to such an item. + * + * Implement a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. + * It must return the display text as shown in the examples: + */ + + +package codewars; + +public class WhoLikesIt { + + public static String whoLikesIt(String... names) { + + switch (names.length) { + case 0: return "no one likes this"; + case 1: return names[0] + " likes this"; + case 2: return names[0] +" and "+ names[1] + " likes this"; + case 3: return names[0] +", " + names[1] + " and" + names[2] + " likes this"; + case 4: return names[0] +", "+ names[1] +" and " + (names.length -2)+ " likes this"; + default: + return "no one"; + } + } + + public static void main(String[] args) { + System.out.println(whoLikesIt()); + System.out.println(whoLikesIt("Peter")); + System.out.println(whoLikesIt("Jacob", "Alex")); + System.out.println(whoLikesIt("Max", "John", "Mark")); + System.out.println(whoLikesIt("Alex", "Jacob", "Mark", "Max")); + } +} diff --git a/src/codewars/YourOrderPlease.java b/src/codewars/YourOrderPlease.java new file mode 100644 index 0000000..3621061 --- /dev/null +++ b/src/codewars/YourOrderPlease.java @@ -0,0 +1,30 @@ +/** + * Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result. + *

+ * Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0). + *

+ * If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers. + */ + +package codewars; + +public class YourOrderPlease { + + public static String order(String words) { + + String[] word = words.split(" "); + StringBuilder sb = new StringBuilder(); + + for (int i = 1; i <= word.length; i++) { + + for (String str : word) { + if (str.contains(Integer.toString(i))) sb.append(str).append(" "); + } + } + return sb.toString().trim(); + } + + public static void main(String[] args) { + System.out.println(order("is2 Thi1s T4est 3a")); + } +} diff --git a/src/codewars/maxDifferenceHackerRank.java b/src/codewars/maxDifferenceHackerRank.java new file mode 100644 index 0000000..ba3214d --- /dev/null +++ b/src/codewars/maxDifferenceHackerRank.java @@ -0,0 +1,42 @@ +package codewars; + +import java.util.ArrayList; +import java.util.List; + +public class maxDifferenceHackerRank { + + public static int maxDiff(List arr) { + int difference = 0; + int result = 0; + List results = new ArrayList<>(); + + int size = arr.get(0); + + + if(arr.get(2) > arr.get(1)) { + difference = arr.get(2) - arr.get(1); + results.add(difference); + } + + for(int i=size;i>3;i--) { + if(arr.get(i-1) < arr.get(i)) { + difference = arr.get(i) - arr.get(i-1); + results.add(difference); + } + } + System.out.println(results); + + return result; + } + + + public static void main(String[] args) { + List di = new ArrayList<>(); + di.add(4); + di.add(1); + di.add(2); + di.add(6); + di.add(4); + maxDiff(di); + } +} diff --git a/src/hackerRank/AddTwoNumbers.java b/src/hackerRank/AddTwoNumbers.java new file mode 100644 index 0000000..79a47b1 --- /dev/null +++ b/src/hackerRank/AddTwoNumbers.java @@ -0,0 +1,52 @@ +package hackerRank; + +import java.util.LinkedList; +import java.util.List; +import java.util.Scanner; + + +class Node{ + int data; + Node next; + + public Node(int d) { + data = d; + next = null; + } +} + + +public class AddTwoNumbers { + static Node head; + public static void push(int new_data){ + Node newData = new Node(new_data); + newData.next = head; + head = newData; + } + + + public static void getCount(){ + Node temp = head; + while(temp != null){ + System.out.println(temp.data); + temp = temp.next; + } + } + + public static void main(String[] args) { + List first = new LinkedList<>(); + List second = new LinkedList<>(); + // TODO Auto-generated method stub + Scanner in = new Scanner(System.in); + + int len = in.nextInt(); + for(int i=0;i daysSteps = new HashMap<>(); + for(int i=0;i 0){ + int count = 0; + if(daysSteps.containsKey(count)){ + s = s - daysSteps.get(count); + count++; + } + else if(s>0){ + s = s-x; + count++; + } + else + { + System.out.println("No"); + } + + System.out.println(count); + } + + System.out.println(s); + + } + +} diff --git a/src/hackerRank/ContainerWithMostWaterLC.java b/src/hackerRank/ContainerWithMostWaterLC.java new file mode 100644 index 0000000..492b04d --- /dev/null +++ b/src/hackerRank/ContainerWithMostWaterLC.java @@ -0,0 +1,50 @@ +/* + * Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). + * n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). + * Find two lines, which together with x-axis forms a container, such that the container contains the most water. + + * + *Input: [1,8,6,2,5,4,8,3,7] +Output: 49 + */ + + + +package hackerRank; + +import java.util.Scanner; + +public class ContainerWithMostWaterLC { + + + public static int calculateArea(int arr[]){ + int area = 0; + int left = 0; + int right = arr.length -1; + + while(left < right){ + area = Math.max(area,(right - left) * Math.min(arr[left], arr[right])); + if(arr[left] < arr[right]) + left++; + else{ + right--; + } + } + + return area; + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + Scanner in = new Scanner(System.in); + int n = in.nextInt(); + + int arr[] = new int[n]; + for(int i=0;i0){ + long height = sc.nextLong(); + long width = sc.nextLong(); + long ia = height*width; + long total = 0; + total += (height/4)*(width/2); + if(width%2==0){ + if(height%4 ==0 || height%4==1){ + total += ((height/4 )-1)*((width-2)/2); + }else{ + total += ((height/4))*((width-2)/2); + } + }else{ + if(height%4 ==0 || height%4==1){ + total += ((height/4 )-1)*((width-1)/2); + }else{ + total += ((height/4))*((width-1)/2); + } + } + System.out.println(ia-(total*4)); + + } + } + + } \ No newline at end of file diff --git a/src/hackerRank/EasyQueriesHE.java b/src/hackerRank/EasyQueriesHE.java new file mode 100644 index 0000000..818d9d8 --- /dev/null +++ b/src/hackerRank/EasyQueriesHE.java @@ -0,0 +1,62 @@ +package hackerRank; + +/* + * You are given an empty list A and Q queries. Each query is one of the following: + * 1) 1 X Y: add element X to the list Y times + * 2) 2 N : find the Nth element in list A + * + * + * + *Input: + *4 + *1 5 5 + *1 3 6 + *2 7 -----> Output : 5 + *2 6 -----> Output : 3 + * + * */ + + + + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Scanner; + +public class EasyQueriesHE { + static Scanner in = new Scanner(System.in); + + public static void addEle(int ini,List ll){ + + if(ini == 1){ + int ele = in.nextInt(); + int noOfTimes = in.nextInt(); + + for(int i=0;i ll = new ArrayList<>(); + int queries = in.nextInt(); + + for(int i=0;i i % 3 == 0 ? (i % 5 == 0 ? "HelloWorld" : "Hello") : (i % 7 == 0 ? "World" : i)) + .forEach(System.out::println); + } + + + public static void main(String args[]) { + Scanner in = new Scanner(System.in); + int n = in.nextInt(); + fizzBuzz(n); + + } +} diff --git a/src/hackerRank/GatesHE.java b/src/hackerRank/GatesHE.java new file mode 100644 index 0000000..e1b5859 --- /dev/null +++ b/src/hackerRank/GatesHE.java @@ -0,0 +1,25 @@ +package hackerRank; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.text.DecimalFormat; + +public class GatesHE { + public static void main(String[] args) throws Exception{ + // TODO Auto-generated method stub + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + + int n=Integer.parseInt(br.readLine()); + while(n>0){ + n--; + int d=Integer.parseInt(br.readLine()); + double r=(double)1/d; + r=(double)1-r; + DecimalFormat numberFormat = new DecimalFormat("0.000000"); + //numberFormat.setRoundingMode(RoundingMode.FLOOR); + System.out.println(numberFormat.format(r)); + } +} + +} \ No newline at end of file diff --git a/src/hackerRank/JavaArrayListHR.java b/src/hackerRank/JavaArrayListHR.java new file mode 100644 index 0000000..8e0a777 --- /dev/null +++ b/src/hackerRank/JavaArrayListHR.java @@ -0,0 +1,65 @@ +/*Sometimes it's better to use dynamic size arrays. Java's Arraylist can provide you this feature. Try to solve this problem using Arraylist. +You are given n lines. In each line there are zero or more integers. You need to answer a few queries where you need to tell the number located in yth position of xth line. + + +5 //number of lines +5 41 77 74 22 44// line 1 {the first element of line represnets the number of elements in line} +1 12 // line 2 +4 37 34 36 52 // line 3 +0// line 4 +3 20 22 33 // line 5 +5 +1 3 +3 4 +3 1 +4 3 +5 5 + +OUTPUT: + 74 + 52 + 37 + ERROR! + ERROR! +*/ + +package hackerRank; + +import java.util.ArrayList; +import java.util.Scanner; + +public class JavaArrayListHR { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Scanner in = new Scanner(System.in); + int numLines = in.nextInt(); + + ArrayList> lists = new ArrayList<>(); + for(int row = 0;row< numLines;row++){ + int d = in.nextInt(); + ArrayList list = new ArrayList<>(); + for(int col = 0; col < d ; col++){ + list.add(in.nextInt()); + } + lists.add(list); + } + + int q = in.nextInt(); + for(int i=0;i list = lists.get(x-1); + if(y <= list.size()){ + System.out.println(list.get(y-1)); + } + else{ + System.out.println("ERROR!"); + } + } + in.close(); + } + +} diff --git a/src/hackerRank/JavaHashSet.java b/src/hackerRank/JavaHashSet.java new file mode 100644 index 0000000..482eaff --- /dev/null +++ b/src/hackerRank/JavaHashSet.java @@ -0,0 +1,47 @@ +/*Input +5 +john tom +john mary +john tom +mary anna +mary anna + + +output: +1 +2 +2 +3 +3 +*/ +package hackerRank; + +import java.util.HashSet; +import java.util.Scanner; + +public class JavaHashSet { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + HashSet pair = new HashSet<>(); + Scanner in = new Scanner(System.in); + int t = in.nextInt(); + String[] pair_left = new String[t]; + String[] pair_right = new String[t]; + + for(int i=0;i list = new ArrayList<>(); + for (int i = 0; i < N; i++) { + list.add(in.nextInt()); + } + + /* Perfrom queries on Linked List */ + int q = in.nextInt(); + for (int i = 0; i < q; i++) { + String action = in.next(); + if (action.equals("Insert")) { + int index = in.nextInt(); + int value = in.nextInt(); + list.add(index, value); + } else { // "Delete" + int index = in.nextInt(); + list.remove(index); + } + } + in.close(); + + /* Print our updated Linked List */ + System.out.print(list); + + } + } \ No newline at end of file diff --git a/src/hackerRank/JavaMap.java b/src/hackerRank/JavaMap.java new file mode 100644 index 0000000..96895cd --- /dev/null +++ b/src/hackerRank/JavaMap.java @@ -0,0 +1,36 @@ +package hackerRank; + +import java.util.HashMap; +import java.util.Map; +import java.util.Scanner; + +public class JavaMap { + + public static void main(String[] args) { + // TODO Auto-generated method stub + Scanner in = new Scanner(System.in); + Map phonebook = new HashMap<>(); + System.out.println("entries"); + int entries = in.nextInt(); + in.nextLine(); + for(int i=0;i{ + + @Override + public int compare(Student o1, Student o2) { + if(o1.getCgpa() == o2.getCgpa()){ + if(o1.getFname().equals(o2.getFname())) + return ((o1.getId() < o2.getId()) ? 1:-1); + else + return (o1.getFname().compareTo(o2.getFname())); + } + else + return ((o1.getCgpa() < o2.getCgpa()) ? 1:-1); + } + +} + + +public class JavaSortHR { + + public static void main(String[] args) { + // TODO Auto-generated method stub + Scanner in = new Scanner(System.in); + List stu = new ArrayList<>(); + int testCases = in.nextInt(); + + for(int i=0;i s = new Stack(); + boolean isBalanced = true; + for(char c : input.toCharArray()) { + switch (c) { + case '{': + case '(': + case '[': + s.push(c); + break; + case '}': + if (!s.empty() && s.peek() == '{') + s.pop(); + else + isBalanced = false; + break; + case ')': + if (!s.empty() && s.peek() == '(') + s.pop(); + else + isBalanced = false; + break; + case ']': + if (!s.empty() && s.peek() == '[') + s.pop(); + else + isBalanced = false; + break; + } + } + if (!s.empty() || !isBalanced){ + System.out.println("false"); + } else + System.out.println("true"); + } + + } + } \ No newline at end of file diff --git a/src/hackerRank/JewelsAndStonesLC.java b/src/hackerRank/JewelsAndStonesLC.java new file mode 100644 index 0000000..22b26cc --- /dev/null +++ b/src/hackerRank/JewelsAndStonesLC.java @@ -0,0 +1,54 @@ +/*Input: J = "aA", S = "aAAbbbb" +Output: 3 + + +Input: J = "z", S = "ZZ" +Output: 0 + +*/ + + +package hackerRank; + +import java.util.HashSet; +import java.util.Scanner; +import java.util.Set; + +public class JewelsAndStonesLC { + + private static int evaluate(String J, String S){ + int count = 0; + if(S == null || J == null){ + return 0; + } + Set res = new HashSet<>(); + + char[] s1 = S.toCharArray(); + char[] j1 = J.toCharArray(); + + for(char jewel : j1){ + res.add(jewel); + } + + for(char stones : s1){ + if(res.contains(stones)){ + count++; + } + } + + return count; + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + Scanner in = new Scanner(System.in); + + String J = in.next(); + String S = in.next(); + + System.out.println(evaluate(J,S)); + in.close(); + + } + +} diff --git a/src/hackerRank/LastAndSecondLastString.java b/src/hackerRank/LastAndSecondLastString.java new file mode 100644 index 0000000..dbe8658 --- /dev/null +++ b/src/hackerRank/LastAndSecondLastString.java @@ -0,0 +1,34 @@ +//Given the string print the last two characters reversed and with a space between them. +//ex : bat output: t a + + + +package hackerRank; + +import java.util.Scanner; + +public class LastAndSecondLastString { + + + + public static String lastLetters(String word) { + + String substring = word.length() > 2 ? word.substring(word.length() - 2) : word; + System.out.println(substring); + + char[] a = substring.toCharArray(); + substring = a[1] + " " +a[0]; + + return substring; + } + + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + String s = in.next(); + + lastLetters(s); + } + + +} diff --git a/src/hackerRank/LongestWord.java b/src/hackerRank/LongestWord.java new file mode 100644 index 0000000..4193244 --- /dev/null +++ b/src/hackerRank/LongestWord.java @@ -0,0 +1,22 @@ +package hackerRank; + +import java.util.Scanner; + +public class LongestWord { + + private static void evaluate(String str){ + str = str.replaceAll("[^a-zA-Z0-9]", ""); + System.out.println(str); + + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + Scanner in = new Scanner(System.in); + String str = in.next(); + + evaluate(str); + + } + +} diff --git a/src/hackerRank/MaxCircularSum.java b/src/hackerRank/MaxCircularSum.java new file mode 100644 index 0000000..db078a8 --- /dev/null +++ b/src/hackerRank/MaxCircularSum.java @@ -0,0 +1,44 @@ +package hackerRank; + +import java.util.Scanner; + +public class MaxCircularSum { +static int smallestSumSubarr(int arr[], int n) +{ + int min_ending_here = 0; + + + int min_so_far = 2147483647; + + for (int i = 0; i < n/2; i++) + { + + if (min_ending_here > 0) + min_ending_here = arr[i]; + + + else + min_ending_here += arr[i]; + + min_so_far = Math.min(min_so_far, + min_ending_here); + } + + return min_so_far; +} + +// Driver method +public static void main(String[] args) +{ + + Scanner in = new Scanner(System.in); + int n = in.nextInt(); + int arr[] = new int[n]; + + for(int i=0;i max1) + { + max2=max1; + max1=happy[j]; + } + else if(happy[j] < max1 && happy[j] > max2) + max2=happy[j]; + } + + System.out.println(max1+max2-sum); + } + + } +} \ No newline at end of file diff --git a/src/hackerRank/QuestionPaperOCT18HE.java b/src/hackerRank/QuestionPaperOCT18HE.java new file mode 100644 index 0000000..fb65472 --- /dev/null +++ b/src/hackerRank/QuestionPaperOCT18HE.java @@ -0,0 +1,39 @@ +package hackerRank; + +import java.util.HashSet; +import java.util.Scanner; +import java.util.Set; + +public class QuestionPaperOCT18HE { + + public static void calculate(int noOfQues,int corrMark,int wrongMarks){ + Set marks = new HashSet<>(); + int corrcTot = 0; + int wrongTotal = 0; + marks.add(0); + for(int i=0;i 75){ + return 0; + } + else{ + return (int)Math.abs((classesH*3-classesA*4)); + } + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + Scanner in = new Scanner(System.in); + int testcases = in.nextInt(); + + for(int i=0;i=1;i--){ + if(minSeatsForLowCost >= availSeats){ + expenditure = expenditure+hikedCost; + noOfTickets--; + availSeats--; + } + else{ + expenditure = expenditure+iniCost; + noOfTickets--; + availSeats--; + } + } + + System.out.println(expenditure); + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + Scanner in = new Scanner(System.in); + int iniCost = in.nextInt(); + int availSeats = in.nextInt(); + int minSeatsForLowCost = in.nextInt(); + int hikedCost = in.nextInt(); + int noOfTickets = in.nextInt(); + + calculate(iniCost,availSeats,minSeatsForLowCost,hikedCost,noOfTickets); + + } + +} diff --git a/src/hackerRank/UniqueEmailAddress.java b/src/hackerRank/UniqueEmailAddress.java new file mode 100644 index 0000000..593237a --- /dev/null +++ b/src/hackerRank/UniqueEmailAddress.java @@ -0,0 +1,54 @@ +package hackerRank; + + +/* + * Besides lowercase letters, these emails may contain '.'s or '+'s. + * Discard everything after the + sign and do not consider . + * "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address. + * + * Given a list of emails, we send one email to each address in the list. + * How many different addresses actually receive mails? + * + */ + + +import java.util.HashSet; +import java.util.Scanner; +import java.util.Set; + +public class UniqueEmailAddress { + + + public static int check(String[] emails){ + Set res = new HashSet<>(); + for (String email : emails) { + String localName = email.split("@")[0]; + String domainName = email.split("@")[1]; + + localName = localName.replace(".", ""); + int index = localName.indexOf('+'); + if (index != -1) { + localName = localName.substring(0, index); + } + + res.add(localName+"@"+domainName); + } + + return res.size(); + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + Scanner in = new Scanner(System.in); + int n = in.nextInt(); + String emails[] = new String[n]; + + for(int i=0;i "--...-." +"zen" -> "--...-." +"gig" -> "--...--." +"msg" -> "--...--." + +There are 2 different transformations, "--...-." and "--...--.". + + */ + + + + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Scanner; +import java.util.Set; + +public class UniqueMorseCodeWords { + + static String[] dictionary = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; + + + private static int uniqueMorseRepresentations(String[] words){ + Set morseValues = new HashSet<>(); + + for(String word : words){ + morseValues.add(morseCodeRep(word)); + } + + return morseValues.size(); + + } + + + public static String morseCodeRep(String word){ + StringBuilder representation = new StringBuilder(); + for(int i=0;i al = new ArrayList<>(); + for (String line = in.nextLine(); !line.isEmpty(); line = in.nextLine()) + { + al.add(line); + } + + String [] words = new String[al.size()]; + for(int i=0;i res = new HashMap<>(); + int result = 0; + int count = 0; + + for (int i = 0; i < n; i++) { + if (res.containsKey(ar[i])) { + res.put(ar[i], res.get(ar[i]) + 1); + } else { + res.put(ar[i], 1); + } + } + + + for (Map.Entry entry : res.entrySet()) { + int a = (int) entry.getValue(); + while (a > 0) { + if (a % 2 == 0) { + count++; + a = a - 2; + } else { + if (a >= 1) { + a = a - 1; + if ((a != 0) && (a % 2 == 0)) { + count++; + a = a - 2; + } + } + } + } + result = count; + } + return result; + } + + + public static void main(String[] args) { + //int[] ar = {1, 1, 3, 1, 2, 1, 3, 3, 3, 3}; + int[] ar = {10,20,20,10,10,30,50,10,20}; + System.out.println(sockMerchant(9, ar)); + } +} diff --git a/src/hackerRank/localMimArray.java b/src/hackerRank/localMimArray.java new file mode 100644 index 0000000..6569558 --- /dev/null +++ b/src/hackerRank/localMimArray.java @@ -0,0 +1,10 @@ +package hackerRank; + +public class localMimArray { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/src/hackerRank/longestSubString.java b/src/hackerRank/longestSubString.java new file mode 100644 index 0000000..1796d28 --- /dev/null +++ b/src/hackerRank/longestSubString.java @@ -0,0 +1,45 @@ +/*Input: "abcabcbb" +Output: 3 +Explanation: The answer is "abc", with the length of 3.*/ + + + + + +package hackerRank; + +import java.util.LinkedHashMap; +import java.util.Scanner; + +public class longestSubString { + + public static int lengthOfLongestSubstring(String s) { + int length = 0; + LinkedHashMap chaPos = new LinkedHashMap<>(); + for(int i=0;i length){ + length = chaPos.size(); + } + } + + return length; + } + + + public static void main(String[] args) { + // TODO Auto-generated method stub + Scanner in = new Scanner(System.in); + String s = in.next(); + System.out.println(lengthOfLongestSubstring(s)); + } + +} diff --git a/src/interviews/Test.java b/src/interviews/Test.java new file mode 100644 index 0000000..8004ef2 --- /dev/null +++ b/src/interviews/Test.java @@ -0,0 +1,4 @@ +package interviews; + +public class Test { +} diff --git a/src/leetcode/DefangingIPAddr.java b/src/leetcode/DefangingIPAddr.java new file mode 100644 index 0000000..5bccbed --- /dev/null +++ b/src/leetcode/DefangingIPAddr.java @@ -0,0 +1,13 @@ +package leetcode; + +public class DefangingIPAddr { + + public static String defangIPaddr(String address) { + return address.replace(".","[.]"); + } + + + public static void main(String[] args) { + System.out.println(defangIPaddr("1.1.1.1")); + } +} diff --git a/src/practice/MostOccurance.java b/src/practice/MostOccurance.java new file mode 100644 index 0000000..08869bb --- /dev/null +++ b/src/practice/MostOccurance.java @@ -0,0 +1,37 @@ +package practice; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.Scanner; + +public class MostOccurance { + + public static String printResult(String str) { + String result = ""; + + Map res = new HashMap<>(); + char[] arr = str.toCharArray(); + Arrays.sort(arr); + + for(int i= 0 ;i