diff --git a/10 Days of Statistics/Day 0 - Mean, Median, and Mode/Solution.java b/10 Days of Statistics/Day 0 - Mean, Median, and Mode/Solution.java index f8ea7ab..248f190 100644 --- a/10 Days of Statistics/Day 0 - Mean, Median, and Mode/Solution.java +++ b/10 Days of Statistics/Day 0 - Mean, Median, and Mode/Solution.java @@ -6,15 +6,12 @@ import java.util.Scanner; import java.util.Arrays; import java.util.HashMap; -/* Runtime: O(n log n) due to sorting */ +// Time Complexity: O(n log n) due to sorting public class Solution { - public static void main(String[] args) { - - /* Read input: Create and fill array */ + /* Save input */ Scanner scan = new Scanner(System.in); int size = scan.nextInt(); - int [] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = scan.nextInt(); @@ -39,26 +36,14 @@ public class Solution { median = array[size / 2]; } - /* Calculate Mode */ + /* Calculate Mode - if there's a tie, choose the smaller number */ HashMap map = new HashMap<>(); int maxOccurrences = 0; int mode = Integer.MAX_VALUE; - for (int num : array) { - /* Update occurrences for this number */ - int occurrences; - if (map.containsKey(num)) { - occurrences = map.get(num) + 1; - } else { - occurrences = 1; - } - map.put(num, occurrences); - - /* Update our mode. If there's a tie, choose the smaller number */ - if (occurrences > maxOccurrences) { - maxOccurrences = occurrences; - mode = num; - } else if (occurrences == maxOccurrences && num < mode) { // this does the tie-breaking + map.merge(num, 1, Integer::sum); + int occurrences = map.get(num); + if (occurrences > maxOccurrences || (occurrences == maxOccurrences && num < mode)) { maxOccurrences = occurrences; mode = num; } diff --git a/10 Days of Statistics/Day 0 - Weighted Mean/Solution.java b/10 Days of Statistics/Day 0 - Weighted Mean/Solution.java index da550c0..d468fc0 100644 --- a/10 Days of Statistics/Day 0 - Weighted Mean/Solution.java +++ b/10 Days of Statistics/Day 0 - Weighted Mean/Solution.java @@ -5,10 +5,8 @@ import java.util.Scanner; public class Solution { - public static void main(String[] args) { - - /* Read and save data */ + /* Save input */ Scanner scan = new Scanner(System.in); int size = scan.nextInt(); int [] elements = new int[size]; @@ -28,7 +26,6 @@ public class Solution { total += elements[i] * weights[i]; totalWeights += weights[i]; } - double weightedMean = (double) total / totalWeights; System.out.format("%.1f", weightedMean); } diff --git a/10 Days of Statistics/Day 1 - Interquartile Range/Solution.java b/10 Days of Statistics/Day 1 - Interquartile Range/Solution.java index 930dc1c..17b354c 100644 --- a/10 Days of Statistics/Day 1 - Interquartile Range/Solution.java +++ b/10 Days of Statistics/Day 1 - Interquartile Range/Solution.java @@ -6,9 +6,8 @@ import java.util.Scanner; import java.util.Arrays; public class Solution { - public static void main(String[] args) { - /* Read and save input */ + /* Save input */ Scanner scan = new Scanner(System.in); int size = scan.nextInt(); int [] element = new int[size]; @@ -16,7 +15,6 @@ public class Solution { for (int i = 0; i < size; i++) { element[i] = scan.nextInt(); } - int numElements = 0; for (int i = 0; i < size; i++) { frequency[i] = scan.nextInt(); @@ -35,14 +33,13 @@ public class Solution { } Arrays.sort(data); - /* Works with both even and odd length arrays */ + /* Calculate interquartile range */ double q1 = findMedian(data, 0, data.length / 2 - 1); double q3 = findMedian(data, (data.length + 1) / 2, data.length - 1); - System.out.println(q3 - q1); } - /* Treats elements from "start" to "end" as an array and calculates its median */ + /* Treats elements from "start" to "end" (inclusive) as an array and calculates its median */ private static double findMedian(int [] array, int start, int end) { if ((end - start) % 2 == 0) { // odd number of elements return (array[(end + start) / 2]); diff --git a/10 Days of Statistics/Day 1 - Quartiles/Solution.java b/10 Days of Statistics/Day 1 - Quartiles/Solution.java index 5dfc62a..27e555e 100644 --- a/10 Days of Statistics/Day 1 - Quartiles/Solution.java +++ b/10 Days of Statistics/Day 1 - Quartiles/Solution.java @@ -6,33 +6,19 @@ import java.util.Scanner; import java.util.Arrays; public class Solution { - public static void main(String[] args) { int [] array = getValues(); Arrays.sort(array); - /* Works with both even and odd length arrays */ int q1 = findMedian(array, 0, array.length / 2 - 1); int q2 = findMedian(array, 0, array.length - 1); int q3 = findMedian(array, (array.length + 1) / 2, array.length - 1); - /* Print output */ System.out.println(q1); System.out.println(q2); System.out.println(q3); } - /* Treats elements from "start" to "end" as an array and calculates its median */ - private static int findMedian(int [] array, int start, int end) { - if ((end - start) % 2 == 0) { // odd number of elements - return (array[(end + start) / 2]); - } else { // even number of elements - int value1 = array[(end + start) / 2]; - int value2 = array[(end + start) / 2 + 1]; - return Math.round((value1 + value2) / 2); - } - } - /* Creates array from input */ private static int [] getValues() { Scanner scan = new Scanner(System.in); @@ -44,4 +30,15 @@ public class Solution { scan.close(); return array; } + + /* Treats elements from "start" to "end" (inclusive) as an array and calculates its median */ + private static int findMedian(int [] array, int start, int end) { + if ((end - start) % 2 == 0) { // odd number of elements + return (array[(end + start) / 2]); + } else { // even number of elements + int value1 = array[(end + start) / 2]; + int value2 = array[(end + start) / 2 + 1]; + return Math.round((value1 + value2) / 2); + } + } } diff --git a/10 Days of Statistics/Day 1 - Standard Deviation/Solution.java b/10 Days of Statistics/Day 1 - Standard Deviation/Solution.java index 9e7d776..68ad06b 100644 --- a/10 Days of Statistics/Day 1 - Standard Deviation/Solution.java +++ b/10 Days of Statistics/Day 1 - Standard Deviation/Solution.java @@ -5,9 +5,8 @@ import java.util.Scanner; public class Solution { - public static void main(String[] args) { - /* Read and save input */ + /* Save input */ Scanner scan = new Scanner(System.in); int size = scan.nextInt(); int [] array = new int[size]; diff --git a/10 Days of Statistics/Day 4 - Binomial Distribution I/Solution.java b/10 Days of Statistics/Day 4 - Binomial Distribution I/Solution.java index 6f2104f..64317a3 100644 --- a/10 Days of Statistics/Day 4 - Binomial Distribution I/Solution.java +++ b/10 Days of Statistics/Day 4 - Binomial Distribution I/Solution.java @@ -3,12 +3,10 @@ // HackerRank: hackerrank.com/rshaghoulian public class Solution { - public static void main(String[] args) { - double ratio = 1.09; - - double p = ratio / (1 + ratio); - int n = 6; + double ratio = 1.09; // hardcoded value + double p = ratio / (1 + ratio); + int n = 6; /* Calculate result */ double result = 0; @@ -32,7 +30,7 @@ public class Solution { return factorial(n) / (factorial(x) * factorial(n - x)); } - private static Long factorial (int n) { + private static Long factorial(int n) { if (n < 0) { return null; } diff --git a/10 Days of Statistics/Day 4 - Binomial Distribution II/Solution.java b/10 Days of Statistics/Day 4 - Binomial Distribution II/Solution.java index b2089b1..1eb867e 100644 --- a/10 Days of Statistics/Day 4 - Binomial Distribution II/Solution.java +++ b/10 Days of Statistics/Day 4 - Binomial Distribution II/Solution.java @@ -3,7 +3,6 @@ // HackerRank: hackerrank.com/rshaghoulian public class Solution { - public static void main(String[] args) { /* Values given in problem statement */ double p = 0.12; @@ -35,7 +34,7 @@ public class Solution { return factorial(n) / (factorial(x) * factorial(n - x)); } - private static Long factorial (int n) { + private static Long factorial(int n) { if (n < 0) { return null; } diff --git a/10 Days of Statistics/Day 4 - Geometric Distribution I/Solution.java b/10 Days of Statistics/Day 4 - Geometric Distribution I/Solution.java index 48f6f35..8a1289e 100644 --- a/10 Days of Statistics/Day 4 - Geometric Distribution I/Solution.java +++ b/10 Days of Statistics/Day 4 - Geometric Distribution I/Solution.java @@ -5,9 +5,8 @@ import java.util.Scanner; public class Solution { - public static void main(String[] args) { - /* Read and save input */ + /* Save input */ Scanner scan = new Scanner(System.in); int numerator = scan.nextInt(); int denominator = scan.nextInt(); @@ -30,7 +29,7 @@ public class Solution { return factorial(n) / (factorial(x) * factorial(n - x)); } - private static Long factorial (int n) { + private static Long factorial (int n){ if (n < 0) { return null; } diff --git a/10 Days of Statistics/Day 4 - Geometric Distribution II/Solution.java b/10 Days of Statistics/Day 4 - Geometric Distribution II/Solution.java index dded2d4..4f27ca9 100644 --- a/10 Days of Statistics/Day 4 - Geometric Distribution II/Solution.java +++ b/10 Days of Statistics/Day 4 - Geometric Distribution II/Solution.java @@ -5,9 +5,8 @@ import java.util.Scanner; public class Solution { - public static void main(String[] args) { - /* Read and save input */ + /* Save input */ Scanner scan = new Scanner(System.in); int numerator = scan.nextInt(); int denominator = scan.nextInt(); @@ -34,7 +33,7 @@ public class Solution { return factorial(n) / (factorial(x) * factorial(n - x)); } - private static Long factorial (int n) { + private static Long factorial(int n) { if (n < 0) { return null; } diff --git a/10 Days of Statistics/Day 5 - Normal Distribution I/Solution.java b/10 Days of Statistics/Day 5 - Normal Distribution I/Solution.java index e560a84..fd2eda5 100644 --- a/10 Days of Statistics/Day 5 - Normal Distribution I/Solution.java +++ b/10 Days of Statistics/Day 5 - Normal Distribution I/Solution.java @@ -3,7 +3,6 @@ // HackerRank: hackerrank.com/rshaghoulian public class Solution { - public static void main(String[] args) { double mean = 20; double std = 2; diff --git a/10 Days of Statistics/Day 5 - Normal Distribution II/Solution.java b/10 Days of Statistics/Day 5 - Normal Distribution II/Solution.java index 545c64f..f4f82ff 100644 --- a/10 Days of Statistics/Day 5 - Normal Distribution II/Solution.java +++ b/10 Days of Statistics/Day 5 - Normal Distribution II/Solution.java @@ -3,7 +3,6 @@ // HackerRank: hackerrank.com/rshaghoulian public class Solution { - public static void main(String[] args) { double mean = 70; double std = 10; diff --git a/10 Days of Statistics/Day 5 - Poisson Distribution I/Solution.java b/10 Days of Statistics/Day 5 - Poisson Distribution I/Solution.java index 031341b..905cba7 100644 --- a/10 Days of Statistics/Day 5 - Poisson Distribution I/Solution.java +++ b/10 Days of Statistics/Day 5 - Poisson Distribution I/Solution.java @@ -5,9 +5,8 @@ import java.util.Scanner; public class Solution { - public static void main(String[] args) { - /* Read and save input */ + /* Save input */ Scanner scan = new Scanner(System.in); double lambda = scan.nextDouble(); int k = scan.nextInt(); @@ -20,7 +19,7 @@ public class Solution { return (Math.pow(lambda, k) * Math.pow(Math.E, -1 * lambda)) / factorial(k); } - private static Long factorial (int n) { + private static Long factorial(int n) { if (n < 0) { return null; } diff --git a/10 Days of Statistics/Day 5 - Poisson Distribution II/Solution.java b/10 Days of Statistics/Day 5 - Poisson Distribution II/Solution.java index 0f3693f..d883715 100644 --- a/10 Days of Statistics/Day 5 - Poisson Distribution II/Solution.java +++ b/10 Days of Statistics/Day 5 - Poisson Distribution II/Solution.java @@ -9,9 +9,8 @@ import java.util.Scanner; https://www.hackerrank.com/challenges/s10-poisson-distribution-2/forum/comments/176962 */ public class Solution { - public static void main(String[] args) { - /* Read and save input */ + /* Save input */ Scanner scan = new Scanner(System.in); double A = scan.nextDouble(); double B = scan.nextDouble(); diff --git a/10 Days of Statistics/Day 6 - The Central Limit Theorem I/Solution.java b/10 Days of Statistics/Day 6 - The Central Limit Theorem I/Solution.java index 13cf6a6..54cd24c 100644 --- a/10 Days of Statistics/Day 6 - The Central Limit Theorem I/Solution.java +++ b/10 Days of Statistics/Day 6 - The Central Limit Theorem I/Solution.java @@ -3,7 +3,6 @@ // HackerRank: hackerrank.com/rshaghoulian public class Solution { - public static void main(String[] args) { double mean = 205; double std = 15; diff --git a/10 Days of Statistics/Day 6 - The Central Limit Theorem II/Solution.java b/10 Days of Statistics/Day 6 - The Central Limit Theorem II/Solution.java index 522da68..a51a2ad 100644 --- a/10 Days of Statistics/Day 6 - The Central Limit Theorem II/Solution.java +++ b/10 Days of Statistics/Day 6 - The Central Limit Theorem II/Solution.java @@ -3,7 +3,6 @@ // HackerRank: hackerrank.com/rshaghoulian public class Solution { - public static void main(String[] args) { double ticketsLeft = 250; int n = 100; diff --git a/10 Days of Statistics/Day 7 - Pearson Correlation Coefficient I/Solution.java b/10 Days of Statistics/Day 7 - Pearson Correlation Coefficient I/Solution.java index 28a6a8b..08506d1 100644 --- a/10 Days of Statistics/Day 7 - Pearson Correlation Coefficient I/Solution.java +++ b/10 Days of Statistics/Day 7 - Pearson Correlation Coefficient I/Solution.java @@ -5,9 +5,8 @@ import java.util.Scanner; public class Solution { - public static void main(String[] args) { - /* Read and save input */ + /* Save input */ Scanner scan = new Scanner(System.in); int size = scan.nextInt(); double [] xs = new double[size]; @@ -18,10 +17,11 @@ public class Solution { for (int i = 0; i < size; i++) { ys[i] = scan.nextDouble(); } + scan.close(); System.out.println(pearson(xs, ys)); } - + /* Calculates Pearson coefficient */ private static Double pearson(double [] xs, double [] ys) { if (xs == null || ys == null || xs.length != ys.length) { @@ -62,3 +62,4 @@ public class Solution { return Math.sqrt(variance); } } + diff --git a/10 Days of Statistics/Day 7 - Spearman's Rank Correlation Coefficient/Solution.java b/10 Days of Statistics/Day 7 - Spearman's Rank Correlation Coefficient/Solution.java index 48f8cd2..a693882 100644 --- a/10 Days of Statistics/Day 7 - Spearman's Rank Correlation Coefficient/Solution.java +++ b/10 Days of Statistics/Day 7 - Spearman's Rank Correlation Coefficient/Solution.java @@ -6,14 +6,14 @@ import java.util.Scanner; import java.util.Arrays; import java.util.Comparator; -/* O(n log n) runtime. O(n) space - * - * The challenging part is creating the rank arrays. - */ -public class Solution { +// The challenging part is creating the rank arrays +// Time Complexity: O(n log n) +// Space Complexity: O(n) + +public class Solution { public static void main(String[] args) { - /* Read and save input */ + /* Save input */ Scanner scan = new Scanner(System.in); int size = scan.nextInt(); double [] X = new double[size]; @@ -24,6 +24,7 @@ public class Solution { for (int i = 0; i < size; i++) { Y[i] = scan.nextDouble(); } + scan.close(); System.out.format("%.3f", spearman(X, Y)); } @@ -49,7 +50,7 @@ public class Solution { return 1 - numerator / (n * ((n * n) - 1)); } - /* Returns a new array with ranks. Assumes unique array values. */ + /* Returns a new (parallel) array of ranks. Assumes unique array values */ public static int[] getRanks(double [] array) { int n = array.length; @@ -68,29 +69,23 @@ public class Solution { } return ranks; } - - /* A class to store 2 variables */ - public static class Pair { - public final int index; - public final double value; - - public Pair(int i, double v) { - index = i; - value = v; - } - } +} - /* This lets us sort Pairs based on their value field */ - public static class PairValueComparator implements Comparator { - @Override - public int compare(Pair p1, Pair p2) { - if (p1.value < p2.value) { - return -1; - } else if (p1.value > p2.value) { - return 1; - } else { - return 0; - } - } +/* A class to store 2 variables */ +class Pair { + public final int index; + public final double value; + + public Pair(int i, double v) { + index = i; + value = v; + } +} + +/* This lets us sort Pairs based on their value field */ +class PairValueComparator implements Comparator { + @Override + public int compare(Pair p1, Pair p2) { + return Double.compare(p1.value, p2.value); } } diff --git a/10 Days of Statistics/Day 8 - Least Square Regression Rate/Solution.java b/10 Days of Statistics/Day 8 - Least Square Regression Rate/Solution.java index cf5713d..7f7364c 100644 --- a/10 Days of Statistics/Day 8 - Least Square Regression Rate/Solution.java +++ b/10 Days of Statistics/Day 8 - Least Square Regression Rate/Solution.java @@ -5,7 +5,6 @@ import java.util.Scanner; public class Solution { - public static void main(String[] args) { /* Hardcoded data */ int [] x = {95, 85, 80, 70, 60}; diff --git a/10 Days of Statistics/Day 9 - Multiple Linear Regression/Solution.java b/10 Days of Statistics/Day 9 - Multiple Linear Regression/Solution.java index 21928b1..f3cd13e 100644 --- a/10 Days of Statistics/Day 9 - Multiple Linear Regression/Solution.java +++ b/10 Days of Statistics/Day 9 - Multiple Linear Regression/Solution.java @@ -38,6 +38,8 @@ public class Solution { } System.out.println(result); } + + scan.close(); } /* Multiplies 2 matrices in O(n^3) time */ diff --git a/30 Days of Code/Day 08 - Dictionaries and Maps/Solution.java b/30 Days of Code/Day 08 - Dictionaries and Maps/Solution.java index b4de7f7..5bed875 100644 --- a/30 Days of Code/Day 08 - Dictionaries and Maps/Solution.java +++ b/30 Days of Code/Day 08 - Dictionaries and Maps/Solution.java @@ -7,21 +7,21 @@ import java.util.HashMap; class Solution { public static void main(String [] args) { - /* Read input and save as entries in a HashMap */ + /* Save input as entries in a HashMap */ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); HashMap map = new HashMap<>(); - for(int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) { String name = scan.next(); int phone = scan.nextInt(); map.put(name, phone); } /* Read each query and check if its in our HashMap */ - while(scan.hasNext()) { - String s = scan.next(); - if (map.containsKey(s)) { - System.out.println(s + "=" + map.get(s)); + while (scan.hasNext()) { + String str = scan.next(); + if (map.containsKey(str)) { + System.out.println(str + "=" + map.get(str)); } else { System.out.println("Not found"); } diff --git a/30 Days of Code/Day 09 - Recursion/Solution.java b/30 Days of Code/Day 09 - Recursion/Solution.java index 09ac17e..2e87da1 100644 --- a/30 Days of Code/Day 09 - Recursion/Solution.java +++ b/30 Days of Code/Day 09 - Recursion/Solution.java @@ -5,12 +5,11 @@ import java.util.Scanner; public class Solution { - public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); - System.out.println(factorial(n)); scan.close(); + System.out.println(factorial(n)); } private static Long factorial (int n) { diff --git a/30 Days of Code/Day 11 - 2D Arrays/Solution.java b/30 Days of Code/Day 11 - 2D Arrays/Solution.java index 645294a..3a023f0 100644 --- a/30 Days of Code/Day 11 - 2D Arrays/Solution.java +++ b/30 Days of Code/Day 11 - 2D Arrays/Solution.java @@ -5,7 +5,6 @@ import java.util.Scanner; public class Solution { - public static void main(String [] args) { Scanner scan = new Scanner(System.in); int arr[][] = new int[6][6]; diff --git a/30 Days of Code/Day 13 - Abstract Classes/Solution.java b/30 Days of Code/Day 13 - Abstract Classes/Solution.java index 4a56dfc..6f999fe 100644 --- a/30 Days of Code/Day 13 - Abstract Classes/Solution.java +++ b/30 Days of Code/Day 13 - Abstract Classes/Solution.java @@ -7,8 +7,8 @@ import java.util.*; abstract class Book { String title; String author; - Book(String t,String a) { - title = t; + Book(String t, String a) { + title = t; author = a; } abstract void display(); @@ -23,19 +23,19 @@ class MyBook extends Book { } void display() { - System.out.println("Title: " + title); + System.out.println("Title: " + title); System.out.println("Author: " + author); - System.out.println("Price: " + price); + System.out.println("Price: " + price); } } public class Solution { public static void main(String [] args) { - Scanner sc = new Scanner(System.in); - String title = sc.nextLine(); - String author = sc.nextLine(); - int price = sc.nextInt(); - Book new_novel = new MyBook(title,author,price); + Scanner sc = new Scanner(System.in); + String title = sc.nextLine(); + String author = sc.nextLine(); + int price = sc.nextInt(); + Book new_novel = new MyBook(title, author, price); new_novel.display(); } } diff --git a/30 Days of Code/Day 18 - Queues and Stacks/Solution.java b/30 Days of Code/Day 18 - Queues and Stacks/Solution.java index e2d8c2b..7975675 100644 --- a/30 Days of Code/Day 18 - Queues and Stacks/Solution.java +++ b/30 Days of Code/Day 18 - Queues and Stacks/Solution.java @@ -5,24 +5,26 @@ import java.io.*; import java.util.*; +// ArrayDeque "is likely to be faster than Stack when used as a stack, and faster than LinkedList when used as a queue." - Java documentation + public class Solution { - Stack stack = new Stack<>(); - Queue queue = new LinkedList<>(); + ArrayDeque dequeAsStack = new ArrayDeque<>(); + ArrayDeque dequeAsQueue = new ArrayDeque<>(); void pushCharacter(char ch) { - stack.push(ch); + dequeAsStack.push(ch); } void enqueueCharacter(char ch) { - queue.add(ch); + dequeAsQueue.add(ch); } char popCharacter() { - return stack.pop(); + return dequeAsStack.pop(); } char dequeueCharacter() { - return queue.remove(); + return dequeAsQueue.remove(); } public static void main(String[] args) { @@ -51,7 +53,7 @@ public class Solution { } } - //Finally, print whether string s is palindrome or not. + // Finally, print whether string s is palindrome or not. System.out.println( "The word, " + input + ", is " + ( (!isPalindrome) ? "not a palindrome." : "a palindrome." ) ); } diff --git a/30 Days of Code/Day 20 - Sorting/Solution.java b/30 Days of Code/Day 20 - Sorting/Solution.java index 9284fb8..f94580e 100644 --- a/30 Days of Code/Day 20 - Sorting/Solution.java +++ b/30 Days of Code/Day 20 - Sorting/Solution.java @@ -7,8 +7,8 @@ import java.util.Scanner; public class Solution { private static int swaps = 0; - public static void main(String[] args) { - /* Read input */ + public static void main(String [] args) { + /* Save input */ Scanner scan = new Scanner(System.in); int size = scan.nextInt(); int [] array = new int[size]; @@ -17,26 +17,24 @@ public class Solution { } scan.close(); - /* Sort array */ bubbleSort(array); - /* Print output */ System.out.println("Array is sorted in " + swaps + " swaps."); System.out.println("First Element: " + array[0]); System.out.println("Last Element: " + array[array.length - 1]); } - private static void bubbleSort(int [] array) { - if (array == null) + private static void bubbleSort(int [] array) { + if (array == null) { return; - + } boolean swapped = true; int endOffset = 0; // optimizes code while (swapped) { swapped = false; for (int i = 1; i < array.length - endOffset; i++) { - if (array[i] < array[i-1]) { - swap(array, i, i-1); + if (array[i-1] > array[i]){ + swap(array, i-1, i); swapped = true; } } diff --git a/30 Days of Code/Day 22 - Binary Search Trees/Solution.java b/30 Days of Code/Day 22 - Binary Search Trees/Solution.java index ea7d7d8..15c2aa5 100644 --- a/30 Days of Code/Day 22 - Binary Search Trees/Solution.java +++ b/30 Days of Code/Day 22 - Binary Search Trees/Solution.java @@ -27,15 +27,13 @@ class Solution { public static Node insert(Node root, int data) { if (root == null) { return new Node(data); - } - else{ + } else { Node cur; if (data <= root.data) { - cur = insert(root.left,data); + cur = insert(root.left, data); root.left = cur; - } - else{ - cur = insert(root.right,data); + } else { + cur = insert(root.right, data); root.right = cur; } return root; @@ -46,7 +44,7 @@ class Solution { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); Node root = null; - while(T-- > 0){ + while (T-- > 0) { int data = sc.nextInt(); root = insert(root,data); } diff --git a/30 Days of Code/Day 23 - BST Level-Order Traversal/Solution.java b/30 Days of Code/Day 23 - BST Level-Order Traversal/Solution.java index cb55d50..5547a7f 100644 --- a/30 Days of Code/Day 23 - BST Level-Order Traversal/Solution.java +++ b/30 Days of Code/Day 23 - BST Level-Order Traversal/Solution.java @@ -6,7 +6,7 @@ import java.io.*; import java.util.*; class Node { - Node left,right; + Node left, right; int data; Node(int data) { this.data = data; @@ -16,18 +16,18 @@ class Node { class Solution { static void levelOrder(Node root){ - Queue queue = new LinkedList<>(); + ArrayDeque deque = new ArrayDeque<>(); // use deque as a queue if (root != null) { - queue.add(root); + deque.add(root); } - while ( ! queue.isEmpty()) { - Node n = queue.remove(); + while (!deque.isEmpty()) { + Node n = deque.remove(); System.out.print(n.data + " "); if (n.left != null) { - queue.add(n.left); + deque.add(n.left); } if (n.right != null) { - queue.add(n.right); + deque.add(n.right); } } } diff --git a/30 Days of Code/Day 25 - Running Time and Complexity/Solution.java b/30 Days of Code/Day 25 - Running Time and Complexity/Solution.java index c8477a0..ac2cb23 100644 --- a/30 Days of Code/Day 25 - Running Time and Complexity/Solution.java +++ b/30 Days of Code/Day 25 - Running Time and Complexity/Solution.java @@ -5,18 +5,17 @@ import java.util.Scanner; public class Solution { - public static void main(String[] args) { Scanner scan = new Scanner(System.in); - int p = scan.nextInt(); - for (int a0 = 0; a0 < p; a0++) { + int T = scan.nextInt(); + while (T-- > 0) { int n = scan.nextInt(); System.out.println(isPrime(n) ? "Prime" : "Not prime"); } scan.close(); } - public static boolean isPrime (int n) { + private static boolean isPrime(int n) { if (n < 2) { return false; } diff --git a/Algorithms/Bit Manipulation/Lonely Integer/Solution.java b/Algorithms/Bit Manipulation/Lonely Integer/Solution.java index bd5f9fc..485c057 100644 --- a/Algorithms/Bit Manipulation/Lonely Integer/Solution.java +++ b/Algorithms/Bit Manipulation/Lonely Integer/Solution.java @@ -4,18 +4,16 @@ import java.util.Scanner; -/* O(n) runtime. O(1) space. Uses XOR. Keep in mind: - 1) x ^ x = 0 - 2) x ^ 0 = x - 3) XOR is commutative and associative -*/ +// O(n) runtime. O(1) space. Uses XOR. Keep in mind: +// 1) x ^ x = 0 +// 2) x ^ 0 = x +// 3) XOR is commutative and associative public class Solution { - - public static void main(String[] args) { - /* Read input */ + public static void main(String [] args) { + /* Save input */ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); - int array[] = new int[n]; + int [] array = new int[n]; for(int i = 0; i < n; i++){ array[i] = scan.nextInt(); } diff --git a/Algorithms/Dynamic Programming/The Coin Change Problem/Solution.java b/Algorithms/Dynamic Programming/The Coin Change Problem/Solution.java index cb4ba96..7c4f3de 100644 --- a/Algorithms/Dynamic Programming/The Coin Change Problem/Solution.java +++ b/Algorithms/Dynamic Programming/The Coin Change Problem/Solution.java @@ -5,20 +5,18 @@ import java.util.Scanner; import java.util.HashMap; -/* Use a HashMap as a cache to speed up runtime - * - * Tricky: Must use "long" instead of "int" to avoid integer overflow -*/ +// Use a HashMap as a cache to speed up runtime +// Must use "long" instead of "int" to avoid integer overflow + public class Solution { - - public static void main(String[] args) { - /* Read and save input */ + public static void main(String [] args) { + /* Save input */ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int m = scan.nextInt(); - int coins[] = new int[m]; - for (int coins_i = 0; coins_i < m; coins_i++) { - coins[coins_i] = scan.nextInt(); + int [] coins = new int[m]; + for (int i = 0; i < m; i++) { + coins[i] = scan.nextInt(); } scan.close(); diff --git a/Algorithms/Graph Theory/Breadth First Search - Shortest Reach/Solution.java b/Algorithms/Graph Theory/Breadth First Search - Shortest Reach/Solution.java index ce8c7fc..324dc2f 100644 --- a/Algorithms/Graph Theory/Breadth First Search - Shortest Reach/Solution.java +++ b/Algorithms/Graph Theory/Breadth First Search - Shortest Reach/Solution.java @@ -4,16 +4,12 @@ import java.util.Scanner; import java.util.HashSet; -import java.util.Queue; -import java.util.LinkedList; +import java.util.ArrayDeque; -/* Creates a graph and uses breadth-first search (BFS) to find minimum spanning tree (MST) */ public class Solution { - private static final int EDGE_WEIGHT = 6; public static void main(String[] args) { - Scanner scan = new Scanner(System.in); int numQueries = scan.nextInt(); @@ -22,7 +18,7 @@ public class Solution { int numEdges = scan.nextInt(); /* Create Nodes */ - Node [] node = new Node[numNodes + 1]; // make array 1 bigger than number of Nodes so Node 1 is at index 1 + Node [] node = new Node[numNodes + 1]; // node "i" will be at index "i" node[0] = null; for (int i = 1; i <= numNodes; i++) { node[i] = new Node(i); @@ -37,7 +33,7 @@ public class Solution { /* Create MST */ int start = scan.nextInt(); - createMST(node[start]); + findDistances(node[start]); /* Print results */ for (int i = 1; i <= numNodes; i++) { @@ -50,23 +46,21 @@ public class Solution { scan.close(); } - /* Use BFS to create minimum spanning tree */ - private static void createMST(Node start) { - if (start == null) + /* Uses BFS to find minimum distance of each Node from "start". + Can use BFS instead of Dijkstra's Algorithm since edges are equally weighted. */ + private static void findDistances(Node start) { + if (start == null) { return; - - Queue queue = new LinkedList(); - + } + ArrayDeque deque = new ArrayDeque<>(); // use deque as a queue start.distance = 0; - queue.add(start); - - while ( ! queue.isEmpty()) { - Node curr = queue.remove(); - + deque.add(start); + while (!deque.isEmpty()) { + Node curr = deque.remove(); for (Node neighbor : curr.neighbors) { if (neighbor.distance == -1) { // meaning it's unvisited neighbor.distance = curr.distance + EDGE_WEIGHT; - queue.add(neighbor); + deque.add(neighbor); } } } @@ -74,8 +68,8 @@ public class Solution { /* Implementation of an UNDIRECTED graph */ public static class Node { - public final int id; - public int distance; // this can also tell us if Node has been visited + public final int id; // each Node will have a unique ID + public int distance; // Also tells us if Node has been visited (-1 means unvisited) public HashSet neighbors; public Node (int id) { @@ -88,5 +82,21 @@ public class Solution { neighbors.add(neighbor); neighbor.neighbors.add(this); } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } else if (other == null || !(other instanceof Node)) { + return false; + } + Node otherNode = (Node) other; + return this.id == otherNode.id; + } + + @Override + public int hashCode() { + return id; // simple and effective + } } } diff --git a/Algorithms/Greedy/Beautiful Pairs/Solution.java b/Algorithms/Greedy/Beautiful Pairs/Solution.java index d6c9e3b..7fdc3ba 100644 --- a/Algorithms/Greedy/Beautiful Pairs/Solution.java +++ b/Algorithms/Greedy/Beautiful Pairs/Solution.java @@ -4,9 +4,12 @@ import java.util.Scanner; -// For an element in A, if there's a matching element in B, this creates a "beautiful pair". Each element can only be used once to create a beautiful pair. +// For an element in A, if there's a matching element in B, this creates a "beautiful pair". +// Each element can only be used once to create a beautiful pair. -// Additionaly, We MUST change exactly 1 element in B. We attempt to change it to create 1 more beautiful pair. In the special case where we already have the max number of beautiful pairs, being forced to change it gives us 1 less beautiful pair. +// Additionaly, We MUST change exactly 1 element in B. We attempt to change it to create +// 1 more beautiful pair. In the special case where we already have the max number of +// beautiful pairs, being forced to change it gives us 1 less beautiful pair. // Time Complexity: O(n) // Space Complexity: O(1) @@ -15,7 +18,7 @@ public class Solution { private static final int MAX_NUM = 1000; // max value of any number in array - public static void main(String[] args) { + public static void main(String [] args) { Scanner scan = new Scanner(System.in); int N = scan.nextInt(); int [] bucketA = new int[MAX_NUM + 1]; diff --git a/Algorithms/Greedy/Luck Balance/Solution.java b/Algorithms/Greedy/Luck Balance/Solution.java index adf1583..d63993c 100644 --- a/Algorithms/Greedy/Luck Balance/Solution.java +++ b/Algorithms/Greedy/Luck Balance/Solution.java @@ -5,13 +5,14 @@ import java.util.Scanner; import java.util.ArrayList; -// Algorithm: Lose every non-important contest to save luck. For important contests, lose the K contests with the most luck, and win the rest. This greedy algorithm maximizes saved luck. +// Algorithm: Lose every non-important contest to save luck. For important contests, lose the +// K contests with the most luck, and win the rest. This greedy algorithm maximizes saved luck. // Time Complexity: O(n) average-case runtime using Quickselect // Space Complexity: O(n) public class Solution { - public static void main(String[] args) { + public static void main(String [] args) { Scanner scan = new Scanner(System.in); int N = scan.nextInt(); int K = scan.nextInt(); diff --git a/Algorithms/Greedy/Marc's Cakewalk/Solution.java b/Algorithms/Greedy/Marc's Cakewalk/Solution.java index 75a8e9c..a77a7eb 100644 --- a/Algorithms/Greedy/Marc's Cakewalk/Solution.java +++ b/Algorithms/Greedy/Marc's Cakewalk/Solution.java @@ -6,6 +6,7 @@ import java.util.Scanner; import java.util.Arrays; import java.util.Collections; +// Time Complexity: O(n log n) public class Solution { public static void main(String[] args) { Scanner scan = new Scanner(System.in); @@ -18,7 +19,7 @@ public class Solution { System.out.println(minimumMiles(calories)); } - /* Uses Greedy Algorithm */ + /* Eat the largest cupcakes first */ private static long minimumMiles(Integer [] calories) { Arrays.sort(calories, Collections.reverseOrder()); long multiplier = 1; diff --git a/Algorithms/Implementation/Append and Delete/Solution.java b/Algorithms/Implementation/Append and Delete/Solution.java index 888d97d..0767294 100644 --- a/Algorithms/Implementation/Append and Delete/Solution.java +++ b/Algorithms/Implementation/Append and Delete/Solution.java @@ -4,12 +4,17 @@ import java.util.Scanner; -// Case 1: See if we can completely erase String "s" and append String "t". If we need to waste operations to reach "k" operations, we can do so when String "s" has no characters. +// Case 1: See if we can completely erase String "s" and append String "t". If we need to waste +// operations to reach "k" operations, we can do so when String "s" has no characters. -// Case 2: See if we can convert String "s" to String "t" without completely erasing String "s". We keep erasing charcters from String "s" until it becomes a prefix of String "t". We then add the characters needed to turn String "s" into String "t". If we need to waste operations to reach "k" operations, we can only do so in groups of 2 by doing an append and a delete. +// Case 2: See if we can convert String "s" to String "t" without completely erasing String "s". +// We keep erasing charcters from String "s" until it becomes a prefix of String "t". We +// then add the characters needed to turn String "s" into String "t". If we need to waste +// operations to reach "k" operations, we can only do so in groups of 2 by doing an append +// and a delete. public class Solution { - public static void main(String[] args) { + public static void main(String [] args) { Scanner scan = new Scanner(System.in); String s = scan.next(); String t = scan.next(); diff --git a/Algorithms/Implementation/Apple and Orange/Solution.java b/Algorithms/Implementation/Apple and Orange/Solution.java index f897b7f..851967d 100644 --- a/Algorithms/Implementation/Apple and Orange/Solution.java +++ b/Algorithms/Implementation/Apple and Orange/Solution.java @@ -4,12 +4,11 @@ import java.util.Scanner; -// Runtime: O(m + n) +// Time Complexity: O(m + n) // Space Complexity: O(1) public class Solution { - - public static void main(String[] args) { - /* Read and save input */ + public static void main(String [] args) { + /* Save input */ Scanner scan = new Scanner(System.in); int s = scan.nextInt(); int t = scan.nextInt(); diff --git a/Algorithms/Implementation/Beautiful Days at the Movies/Solution.java b/Algorithms/Implementation/Beautiful Days at the Movies/Solution.java index cd31bc6..1c29d0d 100644 --- a/Algorithms/Implementation/Beautiful Days at the Movies/Solution.java +++ b/Algorithms/Implementation/Beautiful Days at the Movies/Solution.java @@ -5,12 +5,13 @@ import java.util.Scanner; public class Solution { - public static void main(String[] args) { + public static void main(String [] args) { Scanner scan = new Scanner(System.in); int i = scan.nextInt(); int j = scan.nextInt(); int k = scan.nextInt(); scan.close(); + int count = 0; for (int num = i; num <= j; num++) { if (Math.abs(num - reverse(num)) % k == 0) { diff --git a/Algorithms/Implementation/Between Two Sets/Solution.java b/Algorithms/Implementation/Between Two Sets/Solution.java index 667d81f..3bccf1b 100644 --- a/Algorithms/Implementation/Between Two Sets/Solution.java +++ b/Algorithms/Implementation/Between Two Sets/Solution.java @@ -6,9 +6,8 @@ import java.util.Scanner; import java.util.Arrays; public class Solution { - - public static void main(String[] args) { - /* Read and save input */ + public static void main(String [] args) { + /* Save input */ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int m = scan.nextInt(); diff --git a/Algorithms/Implementation/Circular Array Rotation/Solution.java b/Algorithms/Implementation/Circular Array Rotation/Solution.java index d157cee..5ca4c8e 100644 --- a/Algorithms/Implementation/Circular Array Rotation/Solution.java +++ b/Algorithms/Implementation/Circular Array Rotation/Solution.java @@ -5,29 +5,28 @@ import java.util.Scanner; import java.util.Arrays; -/* Runtime: O(n) - Space Complexity: O(1) by doing an "in place" rotation -*/ +// Time Complexity: O(n) +// Space Complexity: O(1) by doing an "in place" rotation public class Solution { public static void main(String[] args) { - /* Read input and create array */ + /* Save input */ Scanner scan = new Scanner(System.in); - int n = scan.nextInt(); - int k = scan.nextInt(); - int q = scan.nextInt(); - int [] array = new int[n]; - for (int i = 0; i < n; i++) { + int size = scan.nextInt(); + int k = scan.nextInt(); + int q = scan.nextInt(); + int [] array = new int[size]; + for (int i = 0; i < size; i++) { array[i] = scan.nextInt(); } /* Rotate array (in place) using 3 reverse operations */ - k = k % n; // to account for cases where k > n + k %= size; // to account for k > size reverse(array, 0, array.length - 1); reverse(array, 0, k - 1); reverse(array, k, array.length - 1); /* Print output */ - for (int i = 0; i < q; i++) { + while (q-- > 0) { int m = scan.nextInt(); System.out.println(array[m]); } @@ -46,8 +45,8 @@ public class Solution { swap(array, start + offset, end - offset); } } - - private static void swap (int [] array, int i, int j) { + + private static void swap(int [] array, int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; diff --git a/Algorithms/Implementation/Designer PDF Viewer/Solution.java b/Algorithms/Implementation/Designer PDF Viewer/Solution.java index dc94328..e9cc943 100644 --- a/Algorithms/Implementation/Designer PDF Viewer/Solution.java +++ b/Algorithms/Implementation/Designer PDF Viewer/Solution.java @@ -8,8 +8,8 @@ public class Solution { private static final int letters = 26; - public static void main(String[] args) { - /* Read and save input */ + public static void main(String [] args) { + /* Save input */ Scanner scan = new Scanner(System.in); int [] height = new int[letters]; for (int i = 0; i < letters; i++){ diff --git a/Algorithms/Implementation/Divisible Sum Pairs/Solution.java b/Algorithms/Implementation/Divisible Sum Pairs/Solution.java index 49210b6..b6c96d4 100644 --- a/Algorithms/Implementation/Divisible Sum Pairs/Solution.java +++ b/Algorithms/Implementation/Divisible Sum Pairs/Solution.java @@ -4,12 +4,14 @@ /* - Runtime: O(n + k) + Time Complexity: O(n + k) Space Complexity: O(k) -We keep track of the mod values in buckets for each number we read. We can do this by creating k buckets where bucket "i" counts each number "n" where n % k = i. +We keep track of the mod values in buckets for each number we read. We can do this +by creating k buckets where bucket "i" counts each number "n" where n % k = i. -Notice that each bucket has a corresponding "complement" bucket. That is, if we take the mod value of one bucket and add it to the mod value of another bucket, we get "k". +Notice that each bucket has a corresponding "complement" bucket. That is, if we take +the mod value of one bucket and add it to the mod value of another bucket, we get "k". Bucket Complement Bucket ------ ----------------- @@ -22,24 +24,25 @@ Bucket Complement Bucket k-2 2 k-1 1 -As we come across each number, we find its corresponding complement bucket. Each number in this complement bucket can be paired with our original number to create a sum divisible by *k* +As we come across each number, we find its corresponding complement bucket. Each number in +this complement bucket can be paired with our original number to create a sum divisible by *k* */ import java.util.Scanner; public class Solution { - public static void main(String[] args) { + public static void main(String [] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int k = scan.nextInt(); - int [] modBucket = new int[k]; + int [] bucket = new int[k]; int count = 0; for (int i = 0; i < n; i++) { int modValue = scan.nextInt() % k; - count += modBucket[(k - modValue) % k]; // adds # of elements in complement bucket - modBucket[modValue]++; // saves in bucket + count += bucket[(k - modValue) % k]; // adds # of elements in complement bucket + bucket[modValue]++; // saves in bucket } scan.close(); diff --git a/Algorithms/Implementation/Equalize the Array/Solution.java b/Algorithms/Implementation/Equalize the Array/Solution.java index 1187886..658c592 100644 --- a/Algorithms/Implementation/Equalize the Array/Solution.java +++ b/Algorithms/Implementation/Equalize the Array/Solution.java @@ -5,16 +5,16 @@ import java.util.Scanner; import java.util.Arrays; -// Runtime: O(n) -// Space Complexity: O(n) +// Time Complexity: O(a + n) +// Space Complexity: O(a) public class Solution { private static final int size = 100; - public static void main(String[] args) { + public static void main(String [] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); - int [] counts = new int[size + 1]; + int [] counts = new int[size + 1]; // could alternatively use a HashMap for (int i = 0; i < n; i++) { counts[scan.nextInt()]++; } diff --git a/Algorithms/Implementation/Grading Students/Solution.java b/Algorithms/Implementation/Grading Students/Solution.java index a465bfa..57e86de 100644 --- a/Algorithms/Implementation/Grading Students/Solution.java +++ b/Algorithms/Implementation/Grading Students/Solution.java @@ -5,14 +5,14 @@ import java.util.Scanner; public class Solution { - - public static void main(String[] args) { + public static void main(String [] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); while (n-- > 0) { int grade = scan.nextInt(); System.out.println(roundGrade(grade)); } + scan.close(); } private static int roundGrade(int grade) { diff --git a/Algorithms/Implementation/Jumping on the Clouds - Revisited/Solution.java b/Algorithms/Implementation/Jumping on the Clouds - Revisited/Solution.java index 99d206e..f9e205e 100644 --- a/Algorithms/Implementation/Jumping on the Clouds - Revisited/Solution.java +++ b/Algorithms/Implementation/Jumping on the Clouds - Revisited/Solution.java @@ -5,13 +5,13 @@ import java.util.Scanner; public class Solution { - public static void main(String[] args) { + public static void main(String [] args) { int E = 100; /* Save input */ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int k = scan.nextInt(); - int cloud[] = new int[n]; + int [] cloud = new int[n]; for (int i = 0; i < n; i++) { cloud[i] = scan.nextInt(); } diff --git a/Algorithms/Implementation/Kangaroo/Solution.java b/Algorithms/Implementation/Kangaroo/Solution.java index 07cb469..14ba967 100644 --- a/Algorithms/Implementation/Kangaroo/Solution.java +++ b/Algorithms/Implementation/Kangaroo/Solution.java @@ -4,24 +4,17 @@ import java.util.Scanner; -/* +// Case 1: v1 <= v2 +// In this case, kangaroo 1 can never catch up to kangaroo 2 -Case 1: +// Case2 : v1 > v2 +// x2 - x1 represents the distance between the 2 kangaroos +// v2 - v1 represents the difference in velocities between the 2 kangaroos. It also represents how much closer the kangaroos get in each step (until they either meet or 1 kangaroo jumps over the other) +// If the distance between the kangaroos (x2 - x1) is divisible by how much closer they get in each step (v2 - v1), then they will land at the same location at the same time. Otherwise, 1 kangaroo will jump over the other and they will never be at the same location at the same time. -v1 <= v2. In this case, kangaroo 1 can never catch up to kangaroo 2 - -Case2 : - -x2 - x1 represents the distance between the 2 kangaroos - -v2 - v1 represents the difference in velocities between the 2 kangaroos. It also represents how much closer the kangaroos get in each step (until they either meet or 1 kangaroo passes the other) - -If the distance between the kangaroos (x2 - x1) is divisible by how much closer they get in each step (v2 - v1), then they will land at the same location at the same time. Otherwise, 1 kangaroo will jump over the other and they will never be at the same location at the same time. - -*/ public class Solution { - public static void main(String[] args) { - /* Read and save input */ + public static void main(String [] args) { + /* Save input */ Scanner scan = new Scanner(System.in); int x1 = scan.nextInt(); int v1 = scan.nextInt(); diff --git a/Algorithms/Implementation/Manasa and Stones/Solution.java b/Algorithms/Implementation/Manasa and Stones/Solution.java index ed2c224..89a3a60 100644 --- a/Algorithms/Implementation/Manasa and Stones/Solution.java +++ b/Algorithms/Implementation/Manasa and Stones/Solution.java @@ -8,16 +8,24 @@ import java.util.Scanner; if (a == b), the last stone can have only 1 value, which is (n - 1) * a -if (a != b), we notice that 2 consecutive stones can have a difference of "a" or "b". In a path, there are n-1 differences representing pairs of adjacent stones. We are not interested in where in the path the difference between 2 stones is "a" or "b", since changing the order of where the differences occur still results in the same value for the last stone. What's important is the # of times the difference between 2 stones is "a" and the # of times it's "b". For a >= 0 and b >= 0, there are n-1 ways to choose "a" and "b" such that a + b == n-1, so there are n-1 possibilities for the last stone. +if (a != b), we notice that 2 consecutive stones can have a difference of "a" or "b". +In a path, there are n-1 differences representing pairs of adjacent stones. We are not +interested in where in the path the difference between 2 stones is "a" or "b", since +changing the order of where the differences occur still results in the same value for +the last stone. What's important is the # of times the difference between 2 stones is +"a" and the # of times it's "b". For a >= 0 and b >= 0, there are n-1 ways to choose +"a" and "b" such that a + b == n-1, so there are n-1 possibilities for the last stone. -To print the n-1 possible values for the last stone, we iterate through the n-1 combinations of "a" and b" and calculate the value of the last stone for each combination. +To print the n-1 possible values for the last stone, we iterate through the n-1 combinations +of "a" and b" and calculate the value of the last stone for each combination. + + Time complexity: O(n) +Space complexity: O(1) */ -// Time complexity: O(n) -// Space complexity: O(1) public class Solution { - public static void main(String[] args) { + public static void main(String [] args) { Scanner scan = new Scanner(System.in); int T = scan.nextInt(); while (T-- > 0) { @@ -27,7 +35,8 @@ public class Solution { if (a == b) { System.out.print((n - 1) * a); } else { - if (a > b) { // swap to make "a" the smaller value. + if (a > b) { + /* swap to make "a" the smaller value */ int temp = a; a = b; b = temp; diff --git a/Algorithms/Implementation/Repeated String/Solution.java b/Algorithms/Implementation/Repeated String/Solution.java index 73e0cfc..a1e03bf 100644 --- a/Algorithms/Implementation/Repeated String/Solution.java +++ b/Algorithms/Implementation/Repeated String/Solution.java @@ -19,15 +19,18 @@ public class Solution { wordAs++; } } + long completeWords = n / str.length(); - long remainingLetters = n % str.length(); - long totalAs = completeWords * wordAs; + long remainingLetters = n % str.length(); + long totalAs = completeWords * wordAs; + /* Count up the remaining 'a' characters */ for (int i = 0; i < remainingLetters; i++) { if (str.charAt(i) == 'a') { totalAs++; } } + System.out.println(totalAs); } } diff --git a/Algorithms/Implementation/Save the Prisoner!/Solution.java b/Algorithms/Implementation/Save the Prisoner!/Solution.java index e44bb6b..3fec182 100644 --- a/Algorithms/Implementation/Save the Prisoner!/Solution.java +++ b/Algorithms/Implementation/Save the Prisoner!/Solution.java @@ -4,8 +4,19 @@ import java.util.Scanner; +/* + +We start off at some random prisoner S and try to distribute M candies. We could just do +S + M to see which prisoner we end up at. However, we may have more candies than prisoners, +so we loop back around to the first prisoner by doing the % N where N is number of prisoners. + +Each +1 and -1 that you see in the equation is to fix the off-by-one problems that exist +since prisoners are counted from 1 to N while modular arithmetic is counted from 0. + +*/ + public class Solution { - public static void main(String[] args) { + public static void main(String [] args) { Scanner scan = new Scanner(System.in); int T = scan.nextInt(); while (T-- > 0) { diff --git a/Algorithms/Implementation/The Hurdle Race/Solution.java b/Algorithms/Implementation/The Hurdle Race/Solution.java index 6b3fe0d..b8f3e0d 100644 --- a/Algorithms/Implementation/The Hurdle Race/Solution.java +++ b/Algorithms/Implementation/The Hurdle Race/Solution.java @@ -6,8 +6,8 @@ import java.util.Scanner; import java.util.Arrays; public class Solution { - public static void main(String[] args) { - /* Read and save input */ + public static void main(String [] args) { + /* Save input */ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int k = scan.nextInt(); diff --git a/Algorithms/Implementation/Utopian Tree/Solution.java b/Algorithms/Implementation/Utopian Tree/Solution.java index 23d1648..87ff826 100644 --- a/Algorithms/Implementation/Utopian Tree/Solution.java +++ b/Algorithms/Implementation/Utopian Tree/Solution.java @@ -5,11 +5,11 @@ import java.util.Scanner; import java.util.Arrays; -// Runtime: O(N + T) +// Time Complexity: O(N + T) // Space Complexity: O(N + T) public class Solution { - public static void main(String[] args) { - /* Read and save input */ + public static void main(String [] args) { + /* Save input */ Scanner scan = new Scanner(System.in); int T = scan.nextInt(); int [] testcase = new int[T]; @@ -19,7 +19,7 @@ public class Solution { /* Calculate answers for all T testcases */ int maxCycles = Arrays.stream(testcase).max().getAsInt(); - int [] cache = new int[maxCycles + 1]; + int [] cache = new int[maxCycles + 1]; // cache is crucial to increase runtime cache[0] = 1; for (int i = 1; i <= maxCycles; i++) { if (i % 2 == 1) { diff --git a/Algorithms/Search/Connected Cells in a Grid/Solution.java b/Algorithms/Search/Connected Cells in a Grid/Solution.java index 98ec868..b5fd3e9 100644 --- a/Algorithms/Search/Connected Cells in a Grid/Solution.java +++ b/Algorithms/Search/Connected Cells in a Grid/Solution.java @@ -5,24 +5,23 @@ import java.util.Scanner; import java.util.ArrayList; -/* Tips: -1) Instead of using a "boolean[][] visited" array, we alter our original grid -2) Dont create a 2-D "Point" or "Cell" class. It's not necessary. -*/ +// Tips: +// - Instead of using a "boolean[][] visited" array, we alter our original grid +// - Dont create a 2-D "Point" or "Cell" class. It's not necessary. + public class Solution { - private static int rows; // here for convenience private static int cols; // here for convenience - public static void main(String[] args) { - /* Read and save grid */ + public static void main(String [] args) { + /* Save input grid */ Scanner scan = new Scanner(System.in); rows = scan.nextInt(); cols = scan.nextInt(); - int grid[][] = new int[rows][cols]; - for (int grid_i = 0; grid_i < rows; grid_i++) { - for (int grid_j = 0; grid_j < cols; grid_j++) { - grid[grid_i][grid_j] = scan.nextInt(); + int [][] grid = new int[rows][cols]; + for (int row = 0; row < rows; row++) { + for (int col = 0; col < cols; col++) { + grid[row][col] = scan.nextInt(); } } scan.close(); @@ -34,11 +33,11 @@ public class Solution { public static int largestRegion(int [][] grid) { int maxRegion = 0; - /* From each filled cell, find the largest region from that cell */ for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { + /* Find the largest region from the current cell */ if (grid[row][col] == 1) { - int size = findLargestRegion(grid, row, col); + int size = findLargestRegion(grid, row, col); maxRegion = Math.max(maxRegion, size); } } @@ -47,21 +46,18 @@ public class Solution { } private static int findLargestRegion(int [][] grid, int row, int col) { - /* Pro tip: put boundary checks at top of recursive call, - instead of before doing recursive call */ - if (row < 0 || row >= rows || col < 0 || col >= cols) { - return 0; - } else if (grid[row][col] == 0) { + /* Put boundary checks here (at top of recursive call), instead of before doing recursive call */ + if (row < 0 || row >= rows || col < 0 || col >= cols || grid == null || grid[row][col] == 0) { return 0; } grid[row][col] = 0; // we alter the original matrix here int size = 1; // 1 accounts for our size - /* Accounts recursively for neighbors sizes */ + /* Recursively search neighbors */ for (int r = row - 1; r <= row + 1; r++) { for (int c = col - 1; c <= col + 1; c++) { - if ( ! (r == 0 && c == 0)) { + if (!(r == row && c == col)) { size += findLargestRegion(grid, r, c); } } diff --git a/Algorithms/Search/Ice Cream Parlor/Solution.java b/Algorithms/Search/Ice Cream Parlor/Solution.java index 54a9cc4..2c9f293 100644 --- a/Algorithms/Search/Ice Cream Parlor/Solution.java +++ b/Algorithms/Search/Ice Cream Parlor/Solution.java @@ -8,14 +8,13 @@ import java.util.HashMap; // Time Complexity: O(n) // Space Complexity: O(n) public class Solution { - - public static void main(String[] args) { + public static void main(String [] args) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(); while (t-- > 0) { int m = scan.nextInt(); int n = scan.nextInt(); - int costs [] = new int[n]; + int [] costs = new int[n]; for (int i = 0; i < n; i++) { costs[i] = scan.nextInt(); } @@ -26,18 +25,17 @@ public class Solution { public static void buyIceCream(int [] costs, int money) { HashMap map = new HashMap<>(); // key = cost, value = ice cream ID - for (int i = 0; i < costs.length; i++) { int icecreamID = i + 1; int cost = costs[i]; - int otherCost = money - cost; /* Find 2 flavors to buy that sum to "money" */ + int otherCost = money - cost; if (map.containsKey(otherCost)) { System.out.println(map.get(otherCost) + " " + icecreamID); } - map.putIfAbsent(cost, icecreamID); // update HashMap + map.putIfAbsent(cost, icecreamID); } } } diff --git a/Algorithms/Sorting/The Full Counting Sort/Solution.java b/Algorithms/Sorting/The Full Counting Sort/Solution.java index aff6f28..2e36e84 100644 --- a/Algorithms/Sorting/The Full Counting Sort/Solution.java +++ b/Algorithms/Sorting/The Full Counting Sort/Solution.java @@ -13,30 +13,31 @@ import java.util.ArrayList; // - used StringBuffer to do 1 output to console instead of multiple outputs public class Solution { - public static void main(String[] args) throws IOException { + public static void main(String [] args) throws IOException { final int maxValue = 100; - HashMap> map = new HashMap<>(); + + /* Create HashMap with empty "buckets" to put Strings into */ + HashMap> map = new HashMap<>(maxValue); + for (int i = 0; i < maxValue; i++) { + map.put(i, new ArrayList()); + } /* Save input */ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); for (int i = 0; i < n; i++) { - String[] pair = br.readLine().split(" "); - int key = Integer.parseInt(pair[0]); - String value = (i < n/2) ? "-" : pair[1]; + String [] pair = br.readLine().split(" "); + int key = Integer.parseInt(pair[0]); + String value = (i < n/2) ? "-" : pair[1]; ArrayList list = map.get(key); - if (list == null) { - list = new ArrayList(); - map.put(key, list); - } list.add(value); } br.close(); /* Print output */ StringBuffer sb = new StringBuffer(); - for (int i = 0; i < map.size(); i++) { + for (int i = 0; i < maxValue; i++) { ArrayList values = map.get(i); for (String str : values) { sb.append(str + " "); diff --git a/Algorithms/Strings/CamelCase/Solution.java b/Algorithms/Strings/CamelCase/Solution.java index b955f3e..3b5cf80 100644 --- a/Algorithms/Strings/CamelCase/Solution.java +++ b/Algorithms/Strings/CamelCase/Solution.java @@ -5,8 +5,7 @@ import java.util.Scanner; public class Solution { - - public static void main(String[] args) { + public static void main(String [] args) { Scanner scan = new Scanner(System.in); String str = scan.next(); scan.close(); diff --git a/Algorithms/Strings/Making Anagrams/Solution.java b/Algorithms/Strings/Making Anagrams/Solution.java index 2172de7..df6fd9f 100644 --- a/Algorithms/Strings/Making Anagrams/Solution.java +++ b/Algorithms/Strings/Making Anagrams/Solution.java @@ -7,7 +7,17 @@ import java.util.Scanner; public class Solution { private static final int NUM_LETTERS = 26; // we assume lower-case letters only - public static int numberNeeded(String first, String second) { + public static void main(String[] args) { + /* Save input */ + Scanner scan = new Scanner(System.in); + String a = scan.next(); + String b = scan.next(); + scan.close(); + + System.out.println(numberNeeded(a, b)); + } + + private static int numberNeeded(String first, String second) { /* For each string, create an array of the count of each character */ int [] array1 = createFilledArray(first); int [] array2 = createFilledArray(second); @@ -29,14 +39,4 @@ public class Solution { } return array; } - - public static void main(String[] args) { - /* Read input */ - Scanner scan = new Scanner(System.in); - String a = scan.next(); - String b = scan.next(); - scan.close(); - - System.out.println(numberNeeded(a, b)); - } } diff --git a/Algorithms/Strings/Super Reduced String/Solution.java b/Algorithms/Strings/Super Reduced String/Solution.java index 44efdb7..ba67f35 100644 --- a/Algorithms/Strings/Super Reduced String/Solution.java +++ b/Algorithms/Strings/Super Reduced String/Solution.java @@ -5,12 +5,15 @@ import java.util.Scanner; import java.util.Stack; -// Runtime: O(n) +// Time Complexity: O(n) // Space Complexity: O(n) +// Can alternatively use an ArrayDeque instead of a Stack. Just make sure to iterate +// through it properly since iteration order is opposite that of a Stack. + public class Solution { - public static void main(String[] args) { - /* Read and save input */ + public static void main(String [] args) { + /* Save input */ Scanner scan = new Scanner(System.in); String str = scan.next(); scan.close(); diff --git a/Algorithms/Strings/Two Characters/Solution.java b/Algorithms/Strings/Two Characters/Solution.java index 39556a0..797af86 100644 --- a/Algorithms/Strings/Two Characters/Solution.java +++ b/Algorithms/Strings/Two Characters/Solution.java @@ -6,18 +6,26 @@ import java.util.Scanner; /* -There are approximately 26^2 possible combinations of alternating pairs of letters. Notice that this number remains constant and is not dependent on the length of our input String. This fact will help us achieve a linear O(n) runtime. + Time Complexity: O(n) with just 1 traversal of our String +Space Complexity: O(1) -We want to solve this problem with just 1 traversal of our String, so we solve all 26^2 subproblems simultaneously. We use two int[26][26] arrays to keep track of the 26^2 solutions. +There are approximately 26^2 possible combinations of alternating pairs of letters. +Notice that this number remains constant and is not dependent on the length of our +input String. This fact will help us achieve a linear O(n) runtime. + +We want to solve this problem with just 1 traversal of our String, so we solve all +26^2 subproblems simultaneously. We use two int[26][26] arrays to keep track of the +26^2 solutions. As we iterate through our String, we update our two int[26][26] arrays as follows: -- int[26][26] letter ---> This array is used to keep track of which of the alternating characters we saw last. To achieve this, for the current character "ch", we update the corresponding row (26 entries) and column (26 entries) with the (ASCII) value of "ch". -- int[26][26] count ----> if we find that no solution exists for a pair of characters (which happens when the characters don't alternate), we store -1 in this array. Otherwise, we store he current maximum length of "s" for the pair of characters. +- int[26][26] letter ---> This array is used to keep track of which of the alternating + characters we saw last. To achieve this, for the current character "ch", we update the + corresponding row (26 entries) and column (26 entries) with the (ASCII) value of "ch". +- int[26][26] count ----> if we find that no solution exists for a pair of characters + (which happens when the characters don't alternate), we store -1 in this array. + Otherwise, we store he current maximum length of "s" for the pair of characters. -Our final answer is the maximum value in "int[26][26] count". - -Time Complexity: O(n) with just 1 traversal of our String -Space Complexity: O(1) +Our final answer is the maximum value in our "int[26][26] count" array. */ @@ -25,7 +33,7 @@ public class Solution { public static final int NUM_LETTERS = 26; - public static void main(String[] args) { + public static void main(String [] args) { /* Save input */ Scanner scan = new Scanner(System.in); int length = scan.nextInt(); diff --git a/Algorithms/Warmup/A Very Big Sum/Solution.java b/Algorithms/Warmup/A Very Big Sum/Solution.java index ad4b82f..bc105ed 100644 --- a/Algorithms/Warmup/A Very Big Sum/Solution.java +++ b/Algorithms/Warmup/A Very Big Sum/Solution.java @@ -5,13 +5,14 @@ import java.util.Scanner; public class Solution { - public static void main(String[] args) { + public static void main(String [] args) { Scanner scan = new Scanner(System.in); int size = scan.nextInt(); long sum = 0; // use long to prevent integer overflow for (int i = 0; i < size; i++) { sum += scan.nextInt(); } + scan.close(); System.out.println(sum); } } diff --git a/Algorithms/Warmup/Compare the Triplets/Solution.java b/Algorithms/Warmup/Compare the Triplets/Solution.java index 221ff12..a69c396 100644 --- a/Algorithms/Warmup/Compare the Triplets/Solution.java +++ b/Algorithms/Warmup/Compare the Triplets/Solution.java @@ -5,10 +5,7 @@ import java.util.Scanner; public class Solution { - - private int points = 0; - - public static void main(String[] args) { + public static void main(String [] args) { Scanner scan = new Scanner(System.in); int a0 = scan.nextInt(); int a1 = scan.nextInt(); @@ -16,6 +13,7 @@ public class Solution { int b0 = scan.nextInt(); int b1 = scan.nextInt(); int b2 = scan.nextInt(); + scan.close(); int aPoints = (a0 > b0 ? 1 : 0) + (a1 > b1 ? 1 : 0) + (a2 > b2 ? 1 : 0); int bPoints = (a0 < b0 ? 1 : 0) + (a1 < b1 ? 1 : 0) + (a2 < b2 ? 1 : 0); diff --git a/Algorithms/Warmup/Simple Array Sum/Solution.java b/Algorithms/Warmup/Simple Array Sum/Solution.java index f3f5992..f19d951 100644 --- a/Algorithms/Warmup/Simple Array Sum/Solution.java +++ b/Algorithms/Warmup/Simple Array Sum/Solution.java @@ -12,6 +12,7 @@ public class Solution { for (int i = 0; i < size; i++) { sum += scan.nextInt(); } + scan.close(); System.out.println(sum); } } diff --git a/Algorithms/Warmup/Solve Me First/Solution.java b/Algorithms/Warmup/Solve Me First/Solution.java index 945c873..f1c320b 100644 --- a/Algorithms/Warmup/Solve Me First/Solution.java +++ b/Algorithms/Warmup/Solve Me First/Solution.java @@ -5,13 +5,8 @@ import java.util.Scanner; public class Solution { - - static int solveMeFirst(int a, int b) { - return a + b; - } - - public static void main(String[] args) { - /* Read input */ + public static void main(String [] args) { + /* Save input */ Scanner scan = new Scanner(System.in); int a = scan.nextInt(); int b = scan.nextInt(); @@ -23,4 +18,8 @@ public class Solution { /* Print output */ System.out.println(sum); } + + static int solveMeFirst(int a, int b) { + return a + b; + } } diff --git a/Algorithms/Warmup/Staircase/Solution.java b/Algorithms/Warmup/Staircase/Solution.java index 69114af..873a8e9 100644 --- a/Algorithms/Warmup/Staircase/Solution.java +++ b/Algorithms/Warmup/Staircase/Solution.java @@ -5,10 +5,11 @@ import java.util.Scanner; public class Solution { - public static void main(String[] args) { - /* Read and save input */ + public static void main(String [] args) { + /* Save input */ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); + scan.close(); /* Print staircase */ for (int spaces = n - 1; spaces >= 0; spaces--) { @@ -21,4 +22,4 @@ public class Solution { System.out.println(); } } -} +} \ No newline at end of file diff --git a/Cracking the Coding Interview/Algorithms/BFS - Shortest Reach in a Graph/Solution.java b/Cracking the Coding Interview/Algorithms/BFS - Shortest Reach in a Graph/Solution.java index ce8c7fc..324dc2f 100644 --- a/Cracking the Coding Interview/Algorithms/BFS - Shortest Reach in a Graph/Solution.java +++ b/Cracking the Coding Interview/Algorithms/BFS - Shortest Reach in a Graph/Solution.java @@ -4,16 +4,12 @@ import java.util.Scanner; import java.util.HashSet; -import java.util.Queue; -import java.util.LinkedList; +import java.util.ArrayDeque; -/* Creates a graph and uses breadth-first search (BFS) to find minimum spanning tree (MST) */ public class Solution { - private static final int EDGE_WEIGHT = 6; public static void main(String[] args) { - Scanner scan = new Scanner(System.in); int numQueries = scan.nextInt(); @@ -22,7 +18,7 @@ public class Solution { int numEdges = scan.nextInt(); /* Create Nodes */ - Node [] node = new Node[numNodes + 1]; // make array 1 bigger than number of Nodes so Node 1 is at index 1 + Node [] node = new Node[numNodes + 1]; // node "i" will be at index "i" node[0] = null; for (int i = 1; i <= numNodes; i++) { node[i] = new Node(i); @@ -37,7 +33,7 @@ public class Solution { /* Create MST */ int start = scan.nextInt(); - createMST(node[start]); + findDistances(node[start]); /* Print results */ for (int i = 1; i <= numNodes; i++) { @@ -50,23 +46,21 @@ public class Solution { scan.close(); } - /* Use BFS to create minimum spanning tree */ - private static void createMST(Node start) { - if (start == null) + /* Uses BFS to find minimum distance of each Node from "start". + Can use BFS instead of Dijkstra's Algorithm since edges are equally weighted. */ + private static void findDistances(Node start) { + if (start == null) { return; - - Queue queue = new LinkedList(); - + } + ArrayDeque deque = new ArrayDeque<>(); // use deque as a queue start.distance = 0; - queue.add(start); - - while ( ! queue.isEmpty()) { - Node curr = queue.remove(); - + deque.add(start); + while (!deque.isEmpty()) { + Node curr = deque.remove(); for (Node neighbor : curr.neighbors) { if (neighbor.distance == -1) { // meaning it's unvisited neighbor.distance = curr.distance + EDGE_WEIGHT; - queue.add(neighbor); + deque.add(neighbor); } } } @@ -74,8 +68,8 @@ public class Solution { /* Implementation of an UNDIRECTED graph */ public static class Node { - public final int id; - public int distance; // this can also tell us if Node has been visited + public final int id; // each Node will have a unique ID + public int distance; // Also tells us if Node has been visited (-1 means unvisited) public HashSet neighbors; public Node (int id) { @@ -88,5 +82,21 @@ public class Solution { neighbors.add(neighbor); neighbor.neighbors.add(this); } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } else if (other == null || !(other instanceof Node)) { + return false; + } + Node otherNode = (Node) other; + return this.id == otherNode.id; + } + + @Override + public int hashCode() { + return id; // simple and effective + } } } diff --git a/Cracking the Coding Interview/Algorithms/Binary Search - Ice Cream Parlor/Solution.java b/Cracking the Coding Interview/Algorithms/Binary Search - Ice Cream Parlor/Solution.java index 54a9cc4..2c9f293 100644 --- a/Cracking the Coding Interview/Algorithms/Binary Search - Ice Cream Parlor/Solution.java +++ b/Cracking the Coding Interview/Algorithms/Binary Search - Ice Cream Parlor/Solution.java @@ -8,14 +8,13 @@ import java.util.HashMap; // Time Complexity: O(n) // Space Complexity: O(n) public class Solution { - - public static void main(String[] args) { + public static void main(String [] args) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(); while (t-- > 0) { int m = scan.nextInt(); int n = scan.nextInt(); - int costs [] = new int[n]; + int [] costs = new int[n]; for (int i = 0; i < n; i++) { costs[i] = scan.nextInt(); } @@ -26,18 +25,17 @@ public class Solution { public static void buyIceCream(int [] costs, int money) { HashMap map = new HashMap<>(); // key = cost, value = ice cream ID - for (int i = 0; i < costs.length; i++) { int icecreamID = i + 1; int cost = costs[i]; - int otherCost = money - cost; /* Find 2 flavors to buy that sum to "money" */ + int otherCost = money - cost; if (map.containsKey(otherCost)) { System.out.println(map.get(otherCost) + " " + icecreamID); } - map.putIfAbsent(cost, icecreamID); // update HashMap + map.putIfAbsent(cost, icecreamID); } } } diff --git a/Cracking the Coding Interview/Algorithms/DFS - Connected Cell in a Grid/Solution.java b/Cracking the Coding Interview/Algorithms/DFS - Connected Cell in a Grid/Solution.java index 98ec868..b5fd3e9 100644 --- a/Cracking the Coding Interview/Algorithms/DFS - Connected Cell in a Grid/Solution.java +++ b/Cracking the Coding Interview/Algorithms/DFS - Connected Cell in a Grid/Solution.java @@ -5,24 +5,23 @@ import java.util.Scanner; import java.util.ArrayList; -/* Tips: -1) Instead of using a "boolean[][] visited" array, we alter our original grid -2) Dont create a 2-D "Point" or "Cell" class. It's not necessary. -*/ +// Tips: +// - Instead of using a "boolean[][] visited" array, we alter our original grid +// - Dont create a 2-D "Point" or "Cell" class. It's not necessary. + public class Solution { - private static int rows; // here for convenience private static int cols; // here for convenience - public static void main(String[] args) { - /* Read and save grid */ + public static void main(String [] args) { + /* Save input grid */ Scanner scan = new Scanner(System.in); rows = scan.nextInt(); cols = scan.nextInt(); - int grid[][] = new int[rows][cols]; - for (int grid_i = 0; grid_i < rows; grid_i++) { - for (int grid_j = 0; grid_j < cols; grid_j++) { - grid[grid_i][grid_j] = scan.nextInt(); + int [][] grid = new int[rows][cols]; + for (int row = 0; row < rows; row++) { + for (int col = 0; col < cols; col++) { + grid[row][col] = scan.nextInt(); } } scan.close(); @@ -34,11 +33,11 @@ public class Solution { public static int largestRegion(int [][] grid) { int maxRegion = 0; - /* From each filled cell, find the largest region from that cell */ for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { + /* Find the largest region from the current cell */ if (grid[row][col] == 1) { - int size = findLargestRegion(grid, row, col); + int size = findLargestRegion(grid, row, col); maxRegion = Math.max(maxRegion, size); } } @@ -47,21 +46,18 @@ public class Solution { } private static int findLargestRegion(int [][] grid, int row, int col) { - /* Pro tip: put boundary checks at top of recursive call, - instead of before doing recursive call */ - if (row < 0 || row >= rows || col < 0 || col >= cols) { - return 0; - } else if (grid[row][col] == 0) { + /* Put boundary checks here (at top of recursive call), instead of before doing recursive call */ + if (row < 0 || row >= rows || col < 0 || col >= cols || grid == null || grid[row][col] == 0) { return 0; } grid[row][col] = 0; // we alter the original matrix here int size = 1; // 1 accounts for our size - /* Accounts recursively for neighbors sizes */ + /* Recursively search neighbors */ for (int r = row - 1; r <= row + 1; r++) { for (int c = col - 1; c <= col + 1; c++) { - if ( ! (r == 0 && c == 0)) { + if (!(r == row && c == col)) { size += findLargestRegion(grid, r, c); } } diff --git a/Cracking the Coding Interview/Algorithms/Merge Sort - Counting Inversions/Solution.java b/Cracking the Coding Interview/Algorithms/Merge Sort - Counting Inversions/Solution.java index 50ced8f..7e7e74e 100644 --- a/Cracking the Coding Interview/Algorithms/Merge Sort - Counting Inversions/Solution.java +++ b/Cracking the Coding Interview/Algorithms/Merge Sort - Counting Inversions/Solution.java @@ -5,14 +5,27 @@ import java.util.Scanner; import java.util.Arrays; -/* We basically implement MergeSort and - 1) Add "swaps" counter and 1 line of code to count swaps when merging - 2) Use "long" instead of "int" to avoid integer overflow +// We basically implement MergeSort and +// 1) Add "swaps" counter and 1 line of code to count swaps when merging +// 2) Use "long" instead of "int" to avoid integer overflow - Runtime: O(n log n) - Space Complexity: O(n) -*/ +// Time Complexity: O(n log n) +// Space Complexity: O(n) public class Solution { + public static void main(String [] args) { + Scanner scan = new Scanner(System.in); + int testcases = scan.nextInt(); + while (testcases-- > 0) { + int n = scan.nextInt(); + int [] array = new int[n]; + for (int i = 0; i < n; i++) { + array[i] = scan.nextInt(); + } + MergeSort ms = new MergeSort(); + System.out.println(ms.mergeSort(arr)); + } + scan.close(); + } private static class MergeSort { /* Our array has up to n = 100,000 elements. That means there may be O(n^2) swaps. @@ -36,7 +49,6 @@ public class Solution { } private void merge(int [] array, int [] helper, int start, int mid, int end) { - /* Fill helper array with same elements as original array */ for (int i = start; i <= end; i++) { // notice "i" goes from "start" to "end", not "0" to "array.length" helper[i] = array[i]; @@ -64,20 +76,4 @@ public class Solution { } } } - - public static void main(String[] args) { - Scanner scan = new Scanner(System.in); - int t = scan.nextInt(); - for (int a0 = 0; a0 < t; a0++) { - int n = scan.nextInt(); - int arr[] = new int[n]; - for (int arr_i=0; arr_i < n; arr_i++) { - arr[arr_i] = scan.nextInt(); - } - - MergeSort ms = new MergeSort(); - System.out.println(ms.mergeSort(arr)); - } - scan.close(); - } } diff --git a/Cracking the Coding Interview/Algorithms/Sorting - Bubble Sort/Solution.java b/Cracking the Coding Interview/Algorithms/Sorting - Bubble Sort/Solution.java index 9284fb8..f94580e 100644 --- a/Cracking the Coding Interview/Algorithms/Sorting - Bubble Sort/Solution.java +++ b/Cracking the Coding Interview/Algorithms/Sorting - Bubble Sort/Solution.java @@ -7,8 +7,8 @@ import java.util.Scanner; public class Solution { private static int swaps = 0; - public static void main(String[] args) { - /* Read input */ + public static void main(String [] args) { + /* Save input */ Scanner scan = new Scanner(System.in); int size = scan.nextInt(); int [] array = new int[size]; @@ -17,26 +17,24 @@ public class Solution { } scan.close(); - /* Sort array */ bubbleSort(array); - /* Print output */ System.out.println("Array is sorted in " + swaps + " swaps."); System.out.println("First Element: " + array[0]); System.out.println("Last Element: " + array[array.length - 1]); } - private static void bubbleSort(int [] array) { - if (array == null) + private static void bubbleSort(int [] array) { + if (array == null) { return; - + } boolean swapped = true; int endOffset = 0; // optimizes code while (swapped) { swapped = false; for (int i = 1; i < array.length - endOffset; i++) { - if (array[i] < array[i-1]) { - swap(array, i, i-1); + if (array[i-1] > array[i]){ + swap(array, i-1, i); swapped = true; } } diff --git a/Cracking the Coding Interview/Algorithms/Sorting - Comparator/Solution.java b/Cracking the Coding Interview/Algorithms/Sorting - Comparator/Solution.java index 405aae2..97b8c06 100644 --- a/Cracking the Coding Interview/Algorithms/Sorting - Comparator/Solution.java +++ b/Cracking the Coding Interview/Algorithms/Sorting - Comparator/Solution.java @@ -10,7 +10,7 @@ class Checker implements Comparator { if (p1.score == p2.score) { return p1.name.compareTo(p2.name); } else { - return p2.score - p1.score; + return p2.score - p1.score; // descending order } } } @@ -26,7 +26,7 @@ class Player { } class Solution { - public static void main(String[] args) { + public static void main(String [] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); diff --git a/Cracking the Coding Interview/Data Structures/Arrays - Left Rotation/Solution.java b/Cracking the Coding Interview/Data Structures/Arrays - Left Rotation/Solution.java index 046ba6c..12cbbfa 100644 --- a/Cracking the Coding Interview/Data Structures/Arrays - Left Rotation/Solution.java +++ b/Cracking the Coding Interview/Data Structures/Arrays - Left Rotation/Solution.java @@ -4,12 +4,11 @@ import java.util.Scanner; -// Runtime: O(n) +// Time Complexity: O(n) // Space Complexity: O(1) by doing an "in place" rotation public class Solution { - - public static void main(String[] args) { - /* Read and save input */ + public static void main(String [] args) { + /* Save input */ Scanner scan = new Scanner(System.in); int size = scan.nextInt(); int numRotations = scan.nextInt(); diff --git a/Cracking the Coding Interview/Data Structures/Hash Tables - Ransom Note/Solution.java b/Cracking the Coding Interview/Data Structures/Hash Tables - Ransom Note/Solution.java index 6cb1ede..18fb487 100644 --- a/Cracking the Coding Interview/Data Structures/Hash Tables - Ransom Note/Solution.java +++ b/Cracking the Coding Interview/Data Structures/Hash Tables - Ransom Note/Solution.java @@ -6,9 +6,8 @@ import java.util.Scanner; import java.util.HashMap; public class Solution { - public static void main(String[] args) { - /* Read and save input */ + /* Save input */ Scanner scan = new Scanner(System.in); int m = scan.nextInt(); int n = scan.nextInt(); @@ -16,7 +15,7 @@ public class Solution { for (int i = 0; i < m; i++) { magazine[i] = scan.next(); } - String ransom[] = new String[n]; + String [] ransom = new String[n]; for (int i = 0; i < n; i++) { ransom[i] = scan.next(); } @@ -33,7 +32,6 @@ public class Solution { /* Determines if ransom letter can be made from magazine */ public static void canCreate(String [] magazine, String [] ransom) { HashMap usableWords = makeMap(magazine); - for (int i = 0; i < ransom.length; i++) { if (usableWords.containsKey(ransom[i]) && usableWords.get(ransom[i]) > 0) { usableWords.merge(ransom[i], -1, Integer::sum); // uses the word @@ -45,7 +43,7 @@ public class Solution { System.out.println("Yes"); } - /* Makes HashMap out of an array of Strings */ + /* Creates and returns a HashMap out of an array of Strings */ private static HashMap makeMap(String [] words) { HashMap map = new HashMap<>(); for (int i = 0; i < words.length; i++) { @@ -54,4 +52,3 @@ public class Solution { return map; } } - diff --git a/Cracking the Coding Interview/Data Structures/Heaps - Find the Running Median/Solution.java b/Cracking the Coding Interview/Data Structures/Heaps - Find the Running Median/Solution.java index 9499126..560a304 100644 --- a/Cracking the Coding Interview/Data Structures/Heaps - Find the Running Median/Solution.java +++ b/Cracking the Coding Interview/Data Structures/Heaps - Find the Running Median/Solution.java @@ -6,28 +6,24 @@ import java.util.Scanner; import java.util.PriorityQueue; import java.util.Collections; -/* - We want either - 1) maxHeap.size() == minHeap.size() - 2) maxHeap.size() - 1 = minHeap.size() - to always be true - */ -public class Solution { +// - We use 2 Heaps to keep track of median +// - We make sure that 1 of the following conditions is always true: +// 1) maxHeap.size() == minHeap.size() +// 2) maxHeap.size() - 1 = minHeap.size() - private static PriorityQueue minHeap = new PriorityQueue<>(); // keeps track of the LARGE numbers +public class Solution { private static PriorityQueue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); // keeps track of the SMALL numbers + private static PriorityQueue minHeap = new PriorityQueue<>(); // keeps track of the LARGE numbers - public static void main(String[] args) { - /* Read input */ + public static void main(String [] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); - int[] a = new int[n]; - for (int a_i=0; a_i < n; a_i++) { - a[a_i] = scan.nextInt(); + int [] array = new int[n]; + for (int i = 0; i < n; i++) { + array[i] = scan.nextInt(); } scan.close(); - - medianTracker(a); + medianTracker(array); } public static void medianTracker(int [] array) { @@ -37,37 +33,34 @@ public class Solution { } } - private static void addNumber(int num) { + private static void addNumber(int n) { if (maxHeap.isEmpty()) { - maxHeap.add(num); - } - else if (maxHeap.size() == minHeap.size()) { - if (num > maxHeap.peek()) { - minHeap.add(num); + maxHeap.add(n); + } else if (maxHeap.size() == minHeap.size()) { + if (n < minHeap.peek()) { + maxHeap.add(n); + } else { + minHeap.add(n); maxHeap.add(minHeap.remove()); } - else { - maxHeap.add(num); - } - } - else if (maxHeap.size() > minHeap.size()) { - if (num > maxHeap.peek()) { - minHeap.add(num); - } - else { - maxHeap.add(num); + } else if (maxHeap.size() > minHeap.size()) { + if (n > maxHeap.peek()) { + minHeap.add(n); + } else { + maxHeap.add(n); minHeap.add(maxHeap.remove()); } } - // Note: maxHeap will never be smaller size than minHeap + // maxHeap will never have fewer elements than minHeap } - private static double getMedian() { // problem statement said: will always have at least 1 element - if (maxHeap.size() > minHeap.size()) { - return maxHeap.peek(); - } - else { // same size + private static double getMedian() { + if (maxHeap.isEmpty()) { + return 0; + } else if (maxHeap.size() == minHeap.size()) { return (maxHeap.peek() + minHeap.peek()) / 2.0; + } else { // maxHeap must have more elements than minHeap + return maxHeap.peek(); } } } diff --git a/Cracking the Coding Interview/Data Structures/Linked Lists - Detect a Cycle/Solution.java b/Cracking the Coding Interview/Data Structures/Linked Lists - Detect a Cycle/Solution.java index 7c255de..27f94e9 100644 --- a/Cracking the Coding Interview/Data Structures/Linked Lists - Detect a Cycle/Solution.java +++ b/Cracking the Coding Interview/Data Structures/Linked Lists - Detect a Cycle/Solution.java @@ -12,12 +12,13 @@ A Node is defined as: } */ -/* If "slow" and "fast" collide, we must have a cycle */ +// If "slow" and "fast" collide, we must have a cycle boolean hasCycle(Node head) { - if (head == null) + if (head == null) { return false; + } - Node slow = head; // moves 1 Node at a time + Node slow = head; // moves 1 Node at a time Node fast = head; // moves 2 Nodes at a time while (fast != null && fast.next != null) { diff --git a/Cracking the Coding Interview/Data Structures/Stacks - Balanced Brackets/Solution.java b/Cracking the Coding Interview/Data Structures/Stacks - Balanced Brackets/Solution.java index 05e7785..8385cfc 100644 --- a/Cracking the Coding Interview/Data Structures/Stacks - Balanced Brackets/Solution.java +++ b/Cracking the Coding Interview/Data Structures/Stacks - Balanced Brackets/Solution.java @@ -3,11 +3,12 @@ // HackerRank: hackerrank.com/rshaghoulian import java.util.Scanner; -import java.util.Stack; import java.util.HashMap; +import java.util.ArrayDeque; + +// ArrayDeque is "likely to be faster than Stack when used as a stack" - Java documentation public class Solution { - public static void main(String[] args) { /* Create HashMap to match opening brackets with closing brackets */ HashMap map = new HashMap<>(); @@ -25,21 +26,19 @@ public class Solution { scan.close(); } - public static boolean isBalanced(String expression, HashMap map) { - /* Odd length strings are not balanced */ + private static boolean isBalanced(String expression, HashMap map) { if ((expression.length() % 2) != 0) { - return false; - } - - Stack stack = new Stack<>(); + return false; // odd length Strings are not balanced + } + ArrayDeque deque = new ArrayDeque<>(); // use deque as a stack for (int i = 0; i < expression.length(); i++) { Character ch = expression.charAt(i); if (map.containsKey(ch)) { - stack.push(ch); - } else if (stack.isEmpty() || ch != map.get(stack.pop())) { + deque.push(ch); + } else if (deque.isEmpty() || ch != map.get(deque.pop())) { return false; } } - return stack.isEmpty(); + return deque.isEmpty(); } } diff --git a/Cracking the Coding Interview/Data Structures/Strings - Making Anagrams/Solution.java b/Cracking the Coding Interview/Data Structures/Strings - Making Anagrams/Solution.java index 2172de7..df6fd9f 100644 --- a/Cracking the Coding Interview/Data Structures/Strings - Making Anagrams/Solution.java +++ b/Cracking the Coding Interview/Data Structures/Strings - Making Anagrams/Solution.java @@ -7,7 +7,17 @@ import java.util.Scanner; public class Solution { private static final int NUM_LETTERS = 26; // we assume lower-case letters only - public static int numberNeeded(String first, String second) { + public static void main(String[] args) { + /* Save input */ + Scanner scan = new Scanner(System.in); + String a = scan.next(); + String b = scan.next(); + scan.close(); + + System.out.println(numberNeeded(a, b)); + } + + private static int numberNeeded(String first, String second) { /* For each string, create an array of the count of each character */ int [] array1 = createFilledArray(first); int [] array2 = createFilledArray(second); @@ -29,14 +39,4 @@ public class Solution { } return array; } - - public static void main(String[] args) { - /* Read input */ - Scanner scan = new Scanner(System.in); - String a = scan.next(); - String b = scan.next(); - scan.close(); - - System.out.println(numberNeeded(a, b)); - } } diff --git a/Cracking the Coding Interview/Data Structures/Tries - Contacts/Solution.java b/Cracking the Coding Interview/Data Structures/Tries - Contacts/Solution.java index f4db7d3..dfd436c 100644 --- a/Cracking the Coding Interview/Data Structures/Tries - Contacts/Solution.java +++ b/Cracking the Coding Interview/Data Structures/Tries - Contacts/Solution.java @@ -6,60 +6,56 @@ import java.util.Scanner; import java.util.HashMap; public class Solution { - + private static TrieNode root = new TrieNode(); public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); - for(int a0 = 0; a0 < n; a0++) { - String op = scan.next(); - String contact = scan.next(); - if (op.equals("add")) { + for (int i = 0; i < n; i++) { + String operation = scan.next(); + String contact = scan.next(); + if (operation.equals("add")) { add(contact); - } else if (op.equals("find")) { + } else if (operation.equals("find")) { System.out.println(find(contact)); } } scan.close(); } - + private static void add(String str) { TrieNode curr = root; for (int i = 0; i < str.length(); i++) { Character ch = str.charAt(i); - - if ( ! curr.children.containsKey(ch)) { - curr.addChild(ch); - } + curr.addChildIfAbsent(ch); curr = curr.children.get(ch); - curr.size++; // each time we visit a node (while adding letters), we increment this. + curr.size++; } } - - private static int find(String str) { + + private static int find(String prefix) { TrieNode curr = root; /* Traverse down tree to end of our prefix */ - for (int i = 0; i < str.length(); i++) { - Character ch = str.charAt(i); - if ( ! curr.children.containsKey(ch)) { + for (int i = 0; i < prefix.length(); i++) { + Character ch = prefix.charAt(i); + if (!curr.children.containsKey(ch)) { return 0; } else { curr = curr.children.get(ch); } } - return curr.size; } /* This implementation is somewhat based off the tutorial video in this problem */ - public static class TrieNode { + public static class TrieNode { // must be a nested class since it's "static" public HashMap children = new HashMap<>(); public int size = 0; // this was the main trick to decrease runtime to pass tests. - public void addChild(Character ch) { - children.put(ch, new TrieNode()); + public void addChildIfAbsent(Character ch) { + children.putIfAbsent(ch, new TrieNode()); } } } diff --git a/Cracking the Coding Interview/Techniques, Concepts/Bit Manipulation - Lonely Integer/Solution.java b/Cracking the Coding Interview/Techniques, Concepts/Bit Manipulation - Lonely Integer/Solution.java index bd5f9fc..73fd2ea 100644 --- a/Cracking the Coding Interview/Techniques, Concepts/Bit Manipulation - Lonely Integer/Solution.java +++ b/Cracking the Coding Interview/Techniques, Concepts/Bit Manipulation - Lonely Integer/Solution.java @@ -4,18 +4,16 @@ import java.util.Scanner; -/* O(n) runtime. O(1) space. Uses XOR. Keep in mind: - 1) x ^ x = 0 - 2) x ^ 0 = x - 3) XOR is commutative and associative -*/ +// O(n) runtime. O(1) space. Uses XOR. Keep in mind: +// 1) x ^ x = 0 +// 2) x ^ 0 = x +// 3) XOR is commutative and associative public class Solution { - - public static void main(String[] args) { + public static void main(String [] args) { /* Read input */ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); - int array[] = new int[n]; + int [] array = new int[n]; for(int i = 0; i < n; i++){ array[i] = scan.nextInt(); } diff --git a/Cracking the Coding Interview/Techniques, Concepts/DP - Coin Change/Solution.java b/Cracking the Coding Interview/Techniques, Concepts/DP - Coin Change/Solution.java index cb4ba96..7c4f3de 100644 --- a/Cracking the Coding Interview/Techniques, Concepts/DP - Coin Change/Solution.java +++ b/Cracking the Coding Interview/Techniques, Concepts/DP - Coin Change/Solution.java @@ -5,20 +5,18 @@ import java.util.Scanner; import java.util.HashMap; -/* Use a HashMap as a cache to speed up runtime - * - * Tricky: Must use "long" instead of "int" to avoid integer overflow -*/ +// Use a HashMap as a cache to speed up runtime +// Must use "long" instead of "int" to avoid integer overflow + public class Solution { - - public static void main(String[] args) { - /* Read and save input */ + public static void main(String [] args) { + /* Save input */ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int m = scan.nextInt(); - int coins[] = new int[m]; - for (int coins_i = 0; coins_i < m; coins_i++) { - coins[coins_i] = scan.nextInt(); + int [] coins = new int[m]; + for (int i = 0; i < m; i++) { + coins[i] = scan.nextInt(); } scan.close(); diff --git a/Cracking the Coding Interview/Techniques, Concepts/Recursion - Davis' Staircase/Solution.java b/Cracking the Coding Interview/Techniques, Concepts/Recursion - Davis' Staircase/Solution.java index 00abe4f..b108484 100644 --- a/Cracking the Coding Interview/Techniques, Concepts/Recursion - Davis' Staircase/Solution.java +++ b/Cracking the Coding Interview/Techniques, Concepts/Recursion - Davis' Staircase/Solution.java @@ -5,24 +5,28 @@ import java.util.Scanner; import java.util.HashMap; -/* Recursive solution using dynamic programming */ -public class Solution { +// Recursive solution using dynamic programming + +// Time Complexity: O(n) +// Space Complexity: O(n) + +// Can alternatively be solved in O(1) space (per testcase) by using iteration instead of recursion +public class Solution { private static HashMap cache = new HashMap<>(); - public static void main(String[] args) { + public static void main(String [] args) { Scanner scan = new Scanner(System.in); - int s = scan.nextInt(); - + int testcases = scan.nextInt(); cache.put(0, 1); // base case - for (int a0 = 0; a0 < s; a0++) { + while (testcases-- > 0) { int n = scan.nextInt(); System.out.println(staircase(n)); } scan.close(); } - public static int staircase(int n) { + private static int staircase(int n) { if (n < 0) { return 0; } diff --git a/Cracking the Coding Interview/Techniques, Concepts/Recursion - Fibonacci Numbers/Solution.java b/Cracking the Coding Interview/Techniques, Concepts/Recursion - Fibonacci Numbers/Solution.java index 8e969fa..a5c4a0b 100644 --- a/Cracking the Coding Interview/Techniques, Concepts/Recursion - Fibonacci Numbers/Solution.java +++ b/Cracking the Coding Interview/Techniques, Concepts/Recursion - Fibonacci Numbers/Solution.java @@ -4,10 +4,17 @@ import java.util.Scanner; +// Time Complexity: O(n) +// Space Complexity: O(1) public class Solution { - // Runtime: O(n) - // Space Complexity: O(1) - public static int fibonacci(int n) { + public static void main(String [] args) { + Scanner scan = new Scanner(System.in); + int n = scan.nextInt(); + scan.close(); + System.out.println(fibonacci(n)); + } + + private static int fibonacci(int n) { int prev = 0; int curr = 1; for (int i = 2; i <= n; i++) { @@ -17,11 +24,4 @@ public class Solution { } return curr; } - - public static void main(String[] args) { - Scanner scan = new Scanner(System.in); - int n = scan.nextInt(); - scan.close(); - System.out.println(fibonacci(n)); - } } diff --git a/Cracking the Coding Interview/Techniques, Concepts/Time Complexity - Primality/Solution.java b/Cracking the Coding Interview/Techniques, Concepts/Time Complexity - Primality/Solution.java index b2db98d..41413f2 100644 --- a/Cracking the Coding Interview/Techniques, Concepts/Time Complexity - Primality/Solution.java +++ b/Cracking the Coding Interview/Techniques, Concepts/Time Complexity - Primality/Solution.java @@ -5,18 +5,17 @@ import java.util.Scanner; public class Solution { - - public static void main(String[] args) { + public static void main(String [] args) { Scanner scan = new Scanner(System.in); int p = scan.nextInt(); - for (int a0 = 0; a0 < p; a0++) { + while (p-- > 0) { int n = scan.nextInt(); System.out.println(isPrime(n) ? "Prime" : "Not prime"); } scan.close(); } - public static boolean isPrime (int n) { + public static boolean isPrime(int n) { if (n < 2) { return false; } diff --git a/Data Structures/Arrays/Algorithmic Crush/Solution.java b/Data Structures/Arrays/Algorithmic Crush/Solution.java index 2c737a0..b0b9b61 100644 --- a/Data Structures/Arrays/Algorithmic Crush/Solution.java +++ b/Data Structures/Arrays/Algorithmic Crush/Solution.java @@ -2,24 +2,34 @@ // Github: github.com/rshaghoulian // HackerRank: hackerrank.com/rshaghoulian +// Author: Rodney Shaghoulian +// Github: github.com/rshaghoulian +// HackerRank: hackerrank.com/rshaghoulian + import java.util.Scanner; -// Runtime: O(n + m) +// For each of the "m" operations, we do not want to take O(n) time to process it. That's because our runtime will end up being O(nm). To get a O(n+m) runtime, we have to process each operation in O(1) time. To do so, we keep track of just the endpoints, which are just 2 numbers, instead of the O(n) numbers in between the endpoints. This is the main idea to decrease our runtime. + +// For a value "k", we can mark its left endpoint "a" in the original array, along with its right endpoint "b" in the original array. To distinguish between "a" and "b" we can store "+k" for "a" and "-k" for "b". Now, we technically have stored all information that the "m" operations represent, into an array. Most importantly, we stored it in O(m) time. + +// The next step is to actually find the maximum value based off of our unique representation of the data. We traverse our array from left to right. Whenever we reach a left endpoint "a" (which we represented with a positive number), we just add that to our sum. Whenever we reach a right endpoint "b" (which we represented with a negative number), we subtract that from our sum (well, technically we add a negative value). By doing so, the value "sum" represents the value that array[i] would have if we had applied all "m" operations to it. The maximum value of "sum" that we get while traversing the array is the value we return. If this algorithm is still unclear to you, try walking through HackerRank's sample input (Testcase 0) with the code below. + +// Time Complexity: O(n + m) // Space Complexity: O(n) public class Solution { - public static void main(String[] args) { + public static void main(String [] args) { Scanner scan = new Scanner(System.in); int N = scan.nextInt(); int M = scan.nextInt(); - /* Save interval endpoint's "k" values in array */ + /* Save interval endpoints' "k" values in array */ long [] array = new long[N + 1]; - for (int m = 0; m < M; m++) { + while (M-- > 0) { int a = scan.nextInt(); int b = scan.nextInt(); int k = scan.nextInt(); array[a-1] += k; - array[b] -= k; + array[b] -= k; // see comment at end of code } scan.close(); @@ -35,10 +45,5 @@ public class Solution { } } -/* -For each of the "m" operations, we do not want to take O(n) time to process it. That's because our runtime will end up being O(nm). To get a O(n+m) runtime, we have to process each operation in O(1) time. To do so, we keep track of just the endpoints, which are just 2 numbers, instead of the O(n) numbers in between the endpoints. This is the main idea to decrease our runtime. +// Regarding the exact values of "a" and "b", it's a little tricky since "a" and "b" are 1-indexed but our array is 0-indexed. So we want to subtract 1 from both "a" and "b". However, for "b" we re-add 1 because we want to change values from "a" to "b" inclusive as stated in the problem, so we want the end of the interval to be 1 to the right of "b" which is why we re-add the 1. -For a value "k", we can mark its left endpoint "a" in the original array, along with its right endpoint "b" in the original array. To distinguish between "a" and "b" we can store "+k" for "a" and "-k" for "b". Now, we technically have stored all information that the "m" operations represent, into an array. Most importantly, we stored it in O(m) time. - -The next step is to actually find the maximum value based off of our unique representation of the data. We traverse our array from left to right. Whenever we reach a left endpoint "a" (which we represented with a positive number), we just add that to our sum. Whenever we reach a right endpoint "b" (which we represented with a negative number), we subtract that from our sum (well, technically we add a negative value). By doing so, the value "sum" represents the value that array[i] would have if we had applied all "m" operations to it. The maximum value of "sum" that we get while traversing the array is the value we return. If this algorithm is still unclear to you, try walking through HackerRank's Testcase 0 with the code above. -*/ diff --git a/Data Structures/Arrays/Arrays - DS/Solution.java b/Data Structures/Arrays/Arrays - DS/Solution.java index 117d9ec..097d44b 100644 --- a/Data Structures/Arrays/Arrays - DS/Solution.java +++ b/Data Structures/Arrays/Arrays - DS/Solution.java @@ -5,8 +5,8 @@ import java.util.Scanner; public class Solution { - public static void main(String[] args) { - /* Read and save input */ + public static void main(String [] args) { + /* Save input */ Scanner scan = new Scanner(System.in); int size = scan.nextInt(); int [] array = new int[size]; diff --git a/Data Structures/Arrays/Left Rotation/Solution.java b/Data Structures/Arrays/Left Rotation/Solution.java index 046ba6c..12cbbfa 100644 --- a/Data Structures/Arrays/Left Rotation/Solution.java +++ b/Data Structures/Arrays/Left Rotation/Solution.java @@ -4,12 +4,11 @@ import java.util.Scanner; -// Runtime: O(n) +// Time Complexity: O(n) // Space Complexity: O(1) by doing an "in place" rotation public class Solution { - - public static void main(String[] args) { - /* Read and save input */ + public static void main(String [] args) { + /* Save input */ Scanner scan = new Scanner(System.in); int size = scan.nextInt(); int numRotations = scan.nextInt(); diff --git a/Data Structures/Heap/Find the Running Median/Solution.java b/Data Structures/Heap/Find the Running Median/Solution.java index 9499126..560a304 100644 --- a/Data Structures/Heap/Find the Running Median/Solution.java +++ b/Data Structures/Heap/Find the Running Median/Solution.java @@ -6,28 +6,24 @@ import java.util.Scanner; import java.util.PriorityQueue; import java.util.Collections; -/* - We want either - 1) maxHeap.size() == minHeap.size() - 2) maxHeap.size() - 1 = minHeap.size() - to always be true - */ -public class Solution { +// - We use 2 Heaps to keep track of median +// - We make sure that 1 of the following conditions is always true: +// 1) maxHeap.size() == minHeap.size() +// 2) maxHeap.size() - 1 = minHeap.size() - private static PriorityQueue minHeap = new PriorityQueue<>(); // keeps track of the LARGE numbers +public class Solution { private static PriorityQueue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); // keeps track of the SMALL numbers + private static PriorityQueue minHeap = new PriorityQueue<>(); // keeps track of the LARGE numbers - public static void main(String[] args) { - /* Read input */ + public static void main(String [] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); - int[] a = new int[n]; - for (int a_i=0; a_i < n; a_i++) { - a[a_i] = scan.nextInt(); + int [] array = new int[n]; + for (int i = 0; i < n; i++) { + array[i] = scan.nextInt(); } scan.close(); - - medianTracker(a); + medianTracker(array); } public static void medianTracker(int [] array) { @@ -37,37 +33,34 @@ public class Solution { } } - private static void addNumber(int num) { + private static void addNumber(int n) { if (maxHeap.isEmpty()) { - maxHeap.add(num); - } - else if (maxHeap.size() == minHeap.size()) { - if (num > maxHeap.peek()) { - minHeap.add(num); + maxHeap.add(n); + } else if (maxHeap.size() == minHeap.size()) { + if (n < minHeap.peek()) { + maxHeap.add(n); + } else { + minHeap.add(n); maxHeap.add(minHeap.remove()); } - else { - maxHeap.add(num); - } - } - else if (maxHeap.size() > minHeap.size()) { - if (num > maxHeap.peek()) { - minHeap.add(num); - } - else { - maxHeap.add(num); + } else if (maxHeap.size() > minHeap.size()) { + if (n > maxHeap.peek()) { + minHeap.add(n); + } else { + maxHeap.add(n); minHeap.add(maxHeap.remove()); } } - // Note: maxHeap will never be smaller size than minHeap + // maxHeap will never have fewer elements than minHeap } - private static double getMedian() { // problem statement said: will always have at least 1 element - if (maxHeap.size() > minHeap.size()) { - return maxHeap.peek(); - } - else { // same size + private static double getMedian() { + if (maxHeap.isEmpty()) { + return 0; + } else if (maxHeap.size() == minHeap.size()) { return (maxHeap.peek() + minHeap.peek()) / 2.0; + } else { // maxHeap must have more elements than minHeap + return maxHeap.peek(); } } } diff --git a/Data Structures/Linked Lists/Delete a Node/Solution.java b/Data Structures/Linked Lists/Delete a Node/Solution.java index d9241dd..323f722 100644 --- a/Data Structures/Linked Lists/Delete a Node/Solution.java +++ b/Data Structures/Linked Lists/Delete a Node/Solution.java @@ -4,7 +4,7 @@ /* Delete Node at a given position in a linked list - head pointer input could be NULL as well for empty list + Node is defined as class Node { int data; @@ -18,11 +18,14 @@ Node Delete(Node head, int position) { } else if (position == 0) { return head.next; } else { + /* Get Node one element before desired position */ Node n = head; for (int i = 0; i < position - 1; i++) { n = n.next; } + /* Delete Node */ n.next = n.next.next; + return head; } } diff --git a/Data Structures/Linked Lists/Get Node Value/Solution.java b/Data Structures/Linked Lists/Get Node Value/Solution.java index d74ae71..985266b 100644 --- a/Data Structures/Linked Lists/Get Node Value/Solution.java +++ b/Data Structures/Linked Lists/Get Node Value/Solution.java @@ -12,7 +12,7 @@ } */ -// Runtime: O(n) +// Time Complexity: O(n) // Space Complexity: O(1) int GetNode(Node head, int k) { Node curr = head; @@ -25,7 +25,7 @@ int GetNode(Node head, int k) { /* Move both pointers */ while (runner.next != null) { - curr = curr.next; + curr = curr.next; runner = runner.next; } diff --git a/Data Structures/Linked Lists/Insert a Node at the Tail of a Linked List/Solution.java b/Data Structures/Linked Lists/Insert a Node at the Tail of a Linked List/Solution.java index 739136c..5b71a39 100644 --- a/Data Structures/Linked Lists/Insert a Node at the Tail of a Linked List/Solution.java +++ b/Data Structures/Linked Lists/Insert a Node at the Tail of a Linked List/Solution.java @@ -4,7 +4,7 @@ /* Insert Node at the end of a linked list - head pointer input could be NULL as well for empty list + Node is defined as class Node { int data; diff --git a/Data Structures/Linked Lists/Insert a node at a specific position in a linked list/Solution.java b/Data Structures/Linked Lists/Insert a node at a specific position in a linked list/Solution.java index c30ba60..c91e0e3 100644 --- a/Data Structures/Linked Lists/Insert a node at a specific position in a linked list/Solution.java +++ b/Data Structures/Linked Lists/Insert a node at a specific position in a linked list/Solution.java @@ -4,7 +4,7 @@ /* Insert Node at a given position in a linked list - head can be NULL + First element in the linked list is at position 0 Node is defined as class Node { @@ -22,14 +22,14 @@ Node InsertNth(Node head, int data, int position) { return newNode; } else { /* Get Node one element before desired position */ - Node curr = head; + Node n = head; for (int i = 0; i < position - 1; i++) { - curr = curr.next; + n = n.next; } /* Insert our new Node */ - newNode.next = curr.next; - curr.next = newNode; + newNode.next = n.next; + n.next = newNode; return head; } diff --git a/Data Structures/Linked Lists/Insert a node at the head of a linked list/Solution.java b/Data Structures/Linked Lists/Insert a node at the head of a linked list/Solution.java index 4b73f31..f411f7e 100644 --- a/Data Structures/Linked Lists/Insert a node at the head of a linked list/Solution.java +++ b/Data Structures/Linked Lists/Insert a node at the head of a linked list/Solution.java @@ -4,7 +4,7 @@ /* Insert Node at the beginning of a linked list - head pointer input could be NULL as well for empty list + Node is defined as class Node { int data; diff --git a/Data Structures/Linked Lists/Inserting a Node Into a Sorted Doubly Linked List/Solution.java b/Data Structures/Linked Lists/Inserting a Node Into a Sorted Doubly Linked List/Solution.java index 8439929..e5199df 100644 --- a/Data Structures/Linked Lists/Inserting a Node Into a Sorted Doubly Linked List/Solution.java +++ b/Data Structures/Linked Lists/Inserting a Node Into a Sorted Doubly Linked List/Solution.java @@ -11,7 +11,7 @@ } */ -// Runtime: O(n) +// Time Complexity: O(n) // Space Complexity: O(1) Node SortedInsert(Node head, int data) { /* Create Node to insert */ @@ -24,8 +24,8 @@ Node SortedInsert(Node head, int data) { newNode.next = head; head.prev = newNode; return newNode; - } else { - /* Walk list with 2 pointers */ + } else { + /* Walk list with 2 pointers (code is cleaner than using just 1 pointer) */ Node n1 = null; Node n2 = head; while (n2 != null && n2.data < data) { @@ -36,7 +36,7 @@ Node SortedInsert(Node head, int data) { if (n2 == null) { // insert at end of list n1.next = newNode; newNode.prev = n1; - } else { // insert in empty list + } else { // insert somewhere within the list n1.next = newNode; n2.prev = newNode; newNode.prev = n1; @@ -45,3 +45,4 @@ Node SortedInsert(Node head, int data) { return head; } } + diff --git a/Data Structures/Linked Lists/Merge two sorted linked lists/Solution.java b/Data Structures/Linked Lists/Merge two sorted linked lists/Solution.java index ab33b69..c4457ed 100644 --- a/Data Structures/Linked Lists/Merge two sorted linked lists/Solution.java +++ b/Data Structures/Linked Lists/Merge two sorted linked lists/Solution.java @@ -4,7 +4,7 @@ /* Merge two linked lists - head pointer input could be NULL as well for empty list + Node is defined as class Node { int data; @@ -12,7 +12,7 @@ } */ -// Runtime: O(n) +// Time Complexity: O(n) // Space Complexity: O(1) Node MergeLists(Node currA, Node currB) { if (currA == null) { diff --git a/Data Structures/Linked Lists/Print in Reverse/Solution.java b/Data Structures/Linked Lists/Print in Reverse/Solution.java index ce39884..32d088f 100644 --- a/Data Structures/Linked Lists/Print in Reverse/Solution.java +++ b/Data Structures/Linked Lists/Print in Reverse/Solution.java @@ -3,20 +3,16 @@ // HackerRank: hackerrank.com/rshaghoulian /* - Insert Node at the end of a linked list - head pointer input could be NULL as well for empty list Node is defined as class Node { int data; Node next; } */ - // This is a "method-only" submission. - // You only need to complete this method. -void ReversePrint(Node head) { - if (head != null) { - ReversePrint(head.next); - System.out.println(head.data); +void ReversePrint(Node n) { + if (n != null) { + ReversePrint(n.next); + System.out.println(n.data); } } diff --git a/Data Structures/Linked Lists/Print the Elements of a Linked List/Solution.java b/Data Structures/Linked Lists/Print the Elements of a Linked List/Solution.java index 99017e6..b603c4c 100644 --- a/Data Structures/Linked Lists/Print the Elements of a Linked List/Solution.java +++ b/Data Structures/Linked Lists/Print the Elements of a Linked List/Solution.java @@ -4,7 +4,7 @@ /* Print elements of a linked list on console - head pointer input could be NULL as well for empty list + Node is defined as class Node { int data; diff --git a/Data Structures/Stacks/Balanced Brackets/Solution.java b/Data Structures/Stacks/Balanced Brackets/Solution.java index 05e7785..8385cfc 100644 --- a/Data Structures/Stacks/Balanced Brackets/Solution.java +++ b/Data Structures/Stacks/Balanced Brackets/Solution.java @@ -3,11 +3,12 @@ // HackerRank: hackerrank.com/rshaghoulian import java.util.Scanner; -import java.util.Stack; import java.util.HashMap; +import java.util.ArrayDeque; + +// ArrayDeque is "likely to be faster than Stack when used as a stack" - Java documentation public class Solution { - public static void main(String[] args) { /* Create HashMap to match opening brackets with closing brackets */ HashMap map = new HashMap<>(); @@ -25,21 +26,19 @@ public class Solution { scan.close(); } - public static boolean isBalanced(String expression, HashMap map) { - /* Odd length strings are not balanced */ + private static boolean isBalanced(String expression, HashMap map) { if ((expression.length() % 2) != 0) { - return false; - } - - Stack stack = new Stack<>(); + return false; // odd length Strings are not balanced + } + ArrayDeque deque = new ArrayDeque<>(); // use deque as a stack for (int i = 0; i < expression.length(); i++) { Character ch = expression.charAt(i); if (map.containsKey(ch)) { - stack.push(ch); - } else if (stack.isEmpty() || ch != map.get(stack.pop())) { + deque.push(ch); + } else if (deque.isEmpty() || ch != map.get(deque.pop())) { return false; } } - return stack.isEmpty(); + return deque.isEmpty(); } } diff --git a/Data Structures/Trees/Binary Search Tree - Lowest Common Ancestor/Solution.java b/Data Structures/Trees/Binary Search Tree - Lowest Common Ancestor/Solution.java index 04c4e5d..1907148 100644 --- a/Data Structures/Trees/Binary Search Tree - Lowest Common Ancestor/Solution.java +++ b/Data Structures/Trees/Binary Search Tree - Lowest Common Ancestor/Solution.java @@ -10,18 +10,20 @@ } */ -// Assumes tree has unique values -// Runtime: O(log n) on a balanced tree +// Assumes tree has unique values. +// This problem is simpler since we're given a binary SEARCH tree. + +// Time Complexity: O(log n) on a balanced tree // Space Complexity: O(1) -static Node lca(Node root, int v1, int v2) { - while (root != null) { - if (root.data > v1 && root.data > v2) { - root = root.left; - } else if (root.data < v1 && root.data < v2) { - root = root.right; +static Node lca(Node n, int v1, int v2) { + while (n != null) { + if (n.data > v1 && n.data > v2) { + n = n.left; + } else if (n.data < v1 && n.data < v2) { + n = n.right; } else { break; } } - return root; + return n; } diff --git a/Data Structures/Trees/Is This a Binary Search Tree/Solution.java b/Data Structures/Trees/Is This a Binary Search Tree/Solution.java index e740f4d..44bded4 100644 --- a/Data Structures/Trees/Is This a Binary Search Tree/Solution.java +++ b/Data Structures/Trees/Is This a Binary Search Tree/Solution.java @@ -2,8 +2,7 @@ // Github: github.com/rshaghoulian // HackerRank: hackerrank.com/rshaghoulian -/* Hidden stub code will pass a root argument to the function below. - +/* The Node class is defined as follows: class Node { int data; @@ -13,14 +12,15 @@ The Node class is defined as follows: */ boolean checkBST(Node root) { - return checkBST(root, 0, 10000); // range of values in problem + return checkBST(root, 0, 10000); } boolean checkBST(Node node, int min, int max) { if (node == null) { return true; - } else if (node.data < min || node.data > max) { + } else if (node.data < min || node.data > max) { // we assume BST cannot have duplicate values return false; + } else { + return checkBST(node.left, min, node.data - 1) && checkBST(node.right, node.data + 1, max); } - return checkBST(node.left, min, node.data - 1) && checkBST(node.right, node.data + 1, max); } diff --git a/Data Structures/Trees/Square-Ten Tree/Solution.java b/Data Structures/Trees/Square-Ten Tree/Solution.java index 4235811..1a62731 100644 --- a/Data Structures/Trees/Square-Ten Tree/Solution.java +++ b/Data Structures/Trees/Square-Ten Tree/Solution.java @@ -5,12 +5,18 @@ import java.util.Scanner; import java.util.Arrays; +// I recommend skipping this problem. The problem statement is way too convoluted. +// However, here are some takeaway concepts from this problem: +// - Implementing a custom BigInt as a byte[] +// - Implementing log2(int n) +// - Realizing that our algorithm can process the giant numbers in portions + // - Runtime: O(n + m) where n = # of digits in L, m = # of digits in R (for interval [L,R]). // - Numbers can literally have millions of digits in this problem. An "int" or "long" is not big enough to store these numbers. Although Java's BigInteger is big enough, it turns out to be too slow for this problem. I wrote a custom "BigInt" class to speed up calculations. // - To achieve linear runtime, we need an algorithm that splits up these giant numbers into portions and processes them separately. A great way to do this is to split by level, as done below. // - This was a very difficult problem. You must have both linear runtime and efficient code to pass all testcases. public class Solution { - public static void main(String[] args) { + public static void main(String [] args) { /* Read and save input */ Scanner scan = new Scanner(System.in); String strL = new BigInt(scan.next()).subtract(BigInt.ONE).toString(); // subtract 1 since it's [L,R] inclusive @@ -53,7 +59,7 @@ public class Solution { } /* If not skipping this level, process it */ - if ( (!numL.equals(BigInt.ZERO) && !numL.equals(upperBound)) || startR == 0) { + if ((!numL.equals(BigInt.ZERO) && !numL.equals(upperBound)) || startR == 0) { BigInt count = upperBound.subtract(numL); carry = true; blockCount++; @@ -94,7 +100,7 @@ public class Solution { System.out.println(blockCount + "\n" + sb + sb2); } - static int log2 (int n) { // assumes positive number + static int log2(int n) { // assumes positive number return 31 - Integer.numberOfLeadingZeros(n); } @@ -140,7 +146,7 @@ class BigInt { public BigInt add(BigInt other) { byte [] digitsA = digits; byte [] digitsB = other.digits; - + /* Create new Array to hold answer */ int newLength = Math.max(digitsA.length, digitsB.length); if (!(digitsA[0] == 0 && digitsB[0] == 0)) { diff --git a/Data Structures/Trees/Swap Nodes [Algo]/Solution.java b/Data Structures/Trees/Swap Nodes [Algo]/Solution.java index a49dad2..1b3de05 100644 --- a/Data Structures/Trees/Swap Nodes [Algo]/Solution.java +++ b/Data Structures/Trees/Swap Nodes [Algo]/Solution.java @@ -4,8 +4,10 @@ import java.util.Scanner; +// Main trick: Repesent our tree as a 1-D array + public class Solution { - public static void main(String[] args) { + public static void main(String [] args) { /* Create tree */ Scanner scan = new Scanner(System.in); int N = scan.nextInt(); @@ -16,7 +18,7 @@ public class Solution { /* Perform swaps and print inorder traversals */ int T = scan.nextInt(); - for (int i = 1; i <= T; i++) { + while (T-- > 0) { int K = scan.nextInt(); swap(array, K, N); inorderTraverse(array, 1); @@ -31,16 +33,16 @@ public class Solution { } } - private static void swap(Pair [] array, int depth, int currIndex, int currDepth) { + private static void swap(Pair [] array, int depthToSwap, int currIndex, int currDepth) { if (currIndex < 1) { return; } Pair p = array[currIndex]; - if (currDepth == depth) { + if (currDepth == depthToSwap) { p.swapSubtrees(); } else { - swap(array, depth, p.left, currDepth + 1); - swap(array, depth, p.right, currDepth + 1); + swap(array, depthToSwap, p.left, currDepth + 1); + swap(array, depthToSwap, p.right, currDepth + 1); } } diff --git a/Data Structures/Trees/Tree - Height of a Binary Tree/Solution.java b/Data Structures/Trees/Tree - Height of a Binary Tree/Solution.java index af6b731..ec30b9c 100644 --- a/Data Structures/Trees/Tree - Height of a Binary Tree/Solution.java +++ b/Data Structures/Trees/Tree - Height of a Binary Tree/Solution.java @@ -8,7 +8,7 @@ import java.io.*; class Node { Node left; Node right; - int data; + int data; Node(int data) { this.data = data; @@ -18,13 +18,6 @@ class Node { } class Solution { - /* - class Node - int data; - Node left; - Node right; - */ - /* We define a 1-Node tree to have height of 0 */ static int height(Node root) { if (root == null) { @@ -37,8 +30,7 @@ class Solution { public static Node insert(Node root, int data) { if (root == null) { return new Node(data); - } - else { + } else { Node cur; if (data <= root.data) { cur = insert(root.left, data); @@ -50,7 +42,7 @@ class Solution { return root; } } - public static void main(String[] args) { + public static void main(String [] args) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(); Node root = null; diff --git a/Data Structures/Trees/Tree - Huffman Decoding/Solution.java b/Data Structures/Trees/Tree - Huffman Decoding/Solution.java index c255f15..b33e64e 100644 --- a/Data Structures/Trees/Tree - Huffman Decoding/Solution.java +++ b/Data Structures/Trees/Tree - Huffman Decoding/Solution.java @@ -13,7 +13,7 @@ void decode(String str, Node root) { Node n = root; for (int i = 0; i < str.length(); i++) { - n = str.charAt(i) == '0' ? n.left : n.right; + n = (str.charAt(i) == '0') ? n.left : n.right; if (n.left == null && n.right == null) { System.out.print(n.data); n = root; diff --git a/Data Structures/Trees/Tree - Inorder Traversal/Solution.java b/Data Structures/Trees/Tree - Inorder Traversal/Solution.java index ab7946f..0a92c98 100644 --- a/Data Structures/Trees/Tree - Inorder Traversal/Solution.java +++ b/Data Structures/Trees/Tree - Inorder Traversal/Solution.java @@ -2,7 +2,7 @@ // Github: github.com/rshaghoulian // HackerRank: hackerrank.com/rshaghoulian -/* you only have to complete the function given below. +/* Node is defined as class Node { @@ -13,10 +13,10 @@ class Node { */ -void inOrder(Node root) { - if (root != null) { - inOrder(root.left); - System.out.print(root.data + " "); - inOrder(root.right); +void inOrder(Node n) { + if (n != null) { + inOrder(n.left); + System.out.print(n.data + " "); + inOrder(n.right); } } diff --git a/Data Structures/Trees/Tree - Level Order Traversal/Solution.java b/Data Structures/Trees/Tree - Level Order Traversal/Solution.java index 8bd5882..d3b069a 100644 --- a/Data Structures/Trees/Tree - Level Order Traversal/Solution.java +++ b/Data Structures/Trees/Tree - Level Order Traversal/Solution.java @@ -11,18 +11,18 @@ */ void LevelOrder(Node root) { - Queue queue = new LinkedList<>(); + ArrayDeque deque = new ArrayDeque<>(); // use deque as a queue if (root != null) { - queue.add(root); + deque.add(root); } - while ( ! queue.isEmpty()) { - Node n = queue.remove(); + while (!deque.isEmpty()) { + Node n = deque.remove(); System.out.print(n.data + " "); if (n.left != null) { - queue.add(n.left); + deque.add(n.left); } if (n.right != null) { - queue.add(n.right); + deque.add(n.right); } } } diff --git a/Data Structures/Trees/Tree - Postorder Traversal/Solution.java b/Data Structures/Trees/Tree - Postorder Traversal/Solution.java index d106021..6979284 100644 --- a/Data Structures/Trees/Tree - Postorder Traversal/Solution.java +++ b/Data Structures/Trees/Tree - Postorder Traversal/Solution.java @@ -2,7 +2,7 @@ // Github: github.com/rshaghoulian // HackerRank: hackerrank.com/rshaghoulian -/* you only have to complete the function given below. +/* Node is defined as class Node { @@ -13,10 +13,10 @@ class Node { */ -void postOrder(Node root) { - if (root != null) { - postOrder(root.left); - postOrder(root.right); - System.out.print(root.data + " "); +void postOrder(Node n) { + if (n != null) { + postOrder(n.left); + postOrder(n.right); + System.out.print(n.data + " "); } } diff --git a/Data Structures/Trees/Tree - Preorder Traversal/Solution.java b/Data Structures/Trees/Tree - Preorder Traversal/Solution.java index 3bb1d21..8bdd3f3 100644 --- a/Data Structures/Trees/Tree - Preorder Traversal/Solution.java +++ b/Data Structures/Trees/Tree - Preorder Traversal/Solution.java @@ -2,7 +2,7 @@ // Github: github.com/rshaghoulian // HackerRank: hackerrank.com/rshaghoulian -/* you only have to complete the function given below. +/* Node is defined as class Node { @@ -13,10 +13,10 @@ class Node { */ -void preOrder(Node root) { - if (root != null) { - System.out.print(root.data + " "); - preOrder(root.left); - preOrder(root.right); +void preOrder(Node n) { + if (n != null) { + System.out.print(n.data + " "); + preOrder(n.left); + preOrder(n.right); } } diff --git a/Data Structures/Trie/Contacts/Solution.java b/Data Structures/Trie/Contacts/Solution.java index f4db7d3..dfd436c 100644 --- a/Data Structures/Trie/Contacts/Solution.java +++ b/Data Structures/Trie/Contacts/Solution.java @@ -6,60 +6,56 @@ import java.util.Scanner; import java.util.HashMap; public class Solution { - + private static TrieNode root = new TrieNode(); public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); - for(int a0 = 0; a0 < n; a0++) { - String op = scan.next(); - String contact = scan.next(); - if (op.equals("add")) { + for (int i = 0; i < n; i++) { + String operation = scan.next(); + String contact = scan.next(); + if (operation.equals("add")) { add(contact); - } else if (op.equals("find")) { + } else if (operation.equals("find")) { System.out.println(find(contact)); } } scan.close(); } - + private static void add(String str) { TrieNode curr = root; for (int i = 0; i < str.length(); i++) { Character ch = str.charAt(i); - - if ( ! curr.children.containsKey(ch)) { - curr.addChild(ch); - } + curr.addChildIfAbsent(ch); curr = curr.children.get(ch); - curr.size++; // each time we visit a node (while adding letters), we increment this. + curr.size++; } } - - private static int find(String str) { + + private static int find(String prefix) { TrieNode curr = root; /* Traverse down tree to end of our prefix */ - for (int i = 0; i < str.length(); i++) { - Character ch = str.charAt(i); - if ( ! curr.children.containsKey(ch)) { + for (int i = 0; i < prefix.length(); i++) { + Character ch = prefix.charAt(i); + if (!curr.children.containsKey(ch)) { return 0; } else { curr = curr.children.get(ch); } } - return curr.size; } /* This implementation is somewhat based off the tutorial video in this problem */ - public static class TrieNode { + public static class TrieNode { // must be a nested class since it's "static" public HashMap children = new HashMap<>(); public int size = 0; // this was the main trick to decrease runtime to pass tests. - public void addChild(Character ch) { - children.put(ch, new TrieNode()); + public void addChildIfAbsent(Character ch) { + children.putIfAbsent(ch, new TrieNode()); } } } diff --git a/Java/Advanced/Prime Checker/Solution.java b/Java/Advanced/Prime Checker/Solution.java index 2718798..48f712b 100644 --- a/Java/Advanced/Prime Checker/Solution.java +++ b/Java/Advanced/Prime Checker/Solution.java @@ -25,13 +25,14 @@ class Prime { if (n < 2) { return false; } - for (int i = 2; i <= (int) Math.sqrt(n); i++) { + int sqrt = (int) Math.sqrt(n); + for (int i = 2; i <= sqrt; i++) { if (n % i == 0) { return false; } } return true; - } + } } public class Solution { diff --git a/Java/BigNumber/Java BigDecimal/Solution.java b/Java/BigNumber/Java BigDecimal/Solution.java index 60d2f0f..a5a1f92 100644 --- a/Java/BigNumber/Java BigDecimal/Solution.java +++ b/Java/BigNumber/Java BigDecimal/Solution.java @@ -6,7 +6,7 @@ import java.math.BigDecimal; import java.util.*; class Solution { - public static void main(String []args){ + public static void main(String []args) { //Input Scanner sc = new Scanner(System.in); int n = sc.nextInt(); diff --git a/Java/Data Structures/Java 1D Array (Part 2)/Solution.java b/Java/Data Structures/Java 1D Array (Part 2)/Solution.java index 507cf27..e88780b 100644 --- a/Java/Data Structures/Java 1D Array (Part 2)/Solution.java +++ b/Java/Data Structures/Java 1D Array (Part 2)/Solution.java @@ -8,23 +8,21 @@ public class Solution { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int T = scan.nextInt(); - for (int testCase = 0; testCase < T; testCase++) { + while (T-- > 0) { int n = scan.nextInt(); int m = scan.nextInt(); - - /* Create array of values */ int [] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = scan.nextInt(); } - - System.out.println(solvable(array, m, 0) ? "YES" : "NO"); + System.out.println(isSolvable(array, m, 0) ? "YES" : "NO"); } + scan.close(); } /* Basically a depth-first search (DFS). Marks each array value as 1 when visiting (Side-effect: alters array) */ - private static boolean solvable(int [] array, int m, int i) { + private static boolean isSolvable(int [] array, int m, int i) { /* Base Cases */ if (i < 0 || array[i] == 1) { return false; @@ -35,8 +33,8 @@ public class Solution { array[i] = 1; // marks as visited /* Recursive Cases */ - return solvable(array, m, i - 1) || - solvable(array, m, i + 1) || - solvable(array, m, i + m); + return isSolvable(array, m, i - 1) || + isSolvable(array, m, i + 1) || + isSolvable(array, m, i + m); } } diff --git a/Java/Data Structures/Java 1D Array/Solution.java b/Java/Data Structures/Java 1D Array/Solution.java index 5026983..cea6bb9 100644 --- a/Java/Data Structures/Java 1D Array/Solution.java +++ b/Java/Data Structures/Java 1D Array/Solution.java @@ -8,12 +8,10 @@ public class Solution { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); - int [] a = new int[n]; for (int i = 0 ; i < n; i++) { a[i] = scan.nextInt(); } - scan.close(); // Prints each sequential element in array a diff --git a/Java/Data Structures/Java 2D Array/Solution.java b/Java/Data Structures/Java 2D Array/Solution.java index 645294a..3a023f0 100644 --- a/Java/Data Structures/Java 2D Array/Solution.java +++ b/Java/Data Structures/Java 2D Array/Solution.java @@ -5,7 +5,6 @@ import java.util.Scanner; public class Solution { - public static void main(String [] args) { Scanner scan = new Scanner(System.in); int arr[][] = new int[6][6]; diff --git a/Java/Data Structures/Java Comparator/Solution.java b/Java/Data Structures/Java Comparator/Solution.java index cf0052f..54ed89a 100644 --- a/Java/Data Structures/Java Comparator/Solution.java +++ b/Java/Data Structures/Java Comparator/Solution.java @@ -26,7 +26,7 @@ class Player { } class Solution { - public static void main(String[] args) { + public static void main(String [] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); diff --git a/Java/Data Structures/Java Dequeue/Solution.java b/Java/Data Structures/Java Dequeue/Solution.java index 1780281..86d94e6 100644 --- a/Java/Data Structures/Java Dequeue/Solution.java +++ b/Java/Data Structures/Java Dequeue/Solution.java @@ -16,8 +16,8 @@ public class test { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); - int m = scan.nextInt(); - int max = map.size(); + int m = scan.nextInt(); + int max = 0; for (int i = 0; i < n; i++) { /* Remove old value (if necessary) */ diff --git a/Java/Data Structures/Java Generics/Solution.java b/Java/Data Structures/Java Generics/Solution.java index 9f19372..4759d9d 100644 --- a/Java/Data Structures/Java Generics/Solution.java +++ b/Java/Data Structures/Java Generics/Solution.java @@ -14,21 +14,19 @@ class Printer { } public class Solution { - public static void main( String args[] ) { - Printer myPrinter = new Printer(); - Integer[] intArray = { 1, 2, 3 }; + public static void main(String args[]) { + Printer myPrinter = new Printer(); + Integer[] intArray = { 1, 2, 3 }; String[] stringArray = {"Hello", "World"}; myPrinter.printArray(intArray); myPrinter.printArray(stringArray); int count = 0; - for (Method method : Printer.class.getDeclaredMethods()) { String name = method.getName(); if (name.equals("printArray")) { count++; } } - if (count > 1) { System.out.println("Method overloading is not allowed!"); } diff --git a/Java/Data Structures/Java Hashset/Solution.java b/Java/Data Structures/Java Hashset/Solution.java index 47ea6b8..1773a38 100644 --- a/Java/Data Structures/Java Hashset/Solution.java +++ b/Java/Data Structures/Java Hashset/Solution.java @@ -11,12 +11,12 @@ import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner s = new Scanner(System.in); - int t = s.nextInt(); - String [] pair_left = new String[t]; + int t = s.nextInt(); + String [] pair_left = new String[t]; String [] pair_right = new String[t]; for (int i = 0; i < t; i++) { - pair_left[i] = s.next(); + pair_left[i] = s.next(); pair_right[i] = s.next(); } s.close(); diff --git a/Java/Data Structures/Java List/Solution.java b/Java/Data Structures/Java List/Solution.java index 5cb505b..a334477 100644 --- a/Java/Data Structures/Java List/Solution.java +++ b/Java/Data Structures/Java List/Solution.java @@ -16,7 +16,7 @@ public class Solution { list.add(value); } - /* Perfrom queries on Linked List */ + /* Perform queries on Linked List */ int Q = scan.nextInt(); for (int i = 0; i < Q; i++) { String action = scan.next(); diff --git a/Java/Data Structures/Java Priority Queue/Solution.java b/Java/Data Structures/Java Priority Queue/Solution.java index 5c5b7ba..7f19528 100644 --- a/Java/Data Structures/Java Priority Queue/Solution.java +++ b/Java/Data Structures/Java Priority Queue/Solution.java @@ -6,13 +6,13 @@ import java.util.Scanner; import java.util.PriorityQueue; import java.util.Comparator; -class Student{ +class Student { private String fname; private double cgpa; private int token; public Student(String fname, double cgpa, int token) { this.fname = fname; - this.cgpa = cgpa; + this.cgpa = cgpa; this.token = token; } public int getToken() { @@ -55,7 +55,7 @@ public class Solution { if (pq.isEmpty()) { System.out.println("EMPTY"); } else { - while ( ! pq.isEmpty()) { + while (!pq.isEmpty()) { Student s = pq.remove(); System.out.println(s.getFname()); } diff --git a/Java/Data Structures/Java Sort/Solution.java b/Java/Data Structures/Java Sort/Solution.java index dbc28f6..ba239cf 100644 --- a/Java/Data Structures/Java Sort/Solution.java +++ b/Java/Data Structures/Java Sort/Solution.java @@ -8,15 +8,15 @@ import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; -class Student{ - private int id; +class Student { + private int id; private String fname; private double cgpa; public Student(int id, String fname, double cgpa) { super(); - this.id = id; + this.id = id; this.fname = fname; - this.cgpa = cgpa; + this.cgpa = cgpa; } public int getId() { return id; @@ -30,8 +30,8 @@ class Student{ } public class Solution { - public static void main(String[] args){ - Scanner scan = new Scanner(System.in); + public static void main(String[] args) { + Scanner scan = new Scanner(System.in); int testCases = Integer.parseInt(scan.nextLine()); List studentList = new ArrayList(); @@ -39,14 +39,12 @@ public class Solution { int id = scan.nextInt(); String fname = scan.next(); double cgpa = scan.nextDouble(); - - Student st = new Student(id, fname, cgpa); + Student st = new Student(id, fname, cgpa); studentList.add(st); } scan.close(); Collections.sort(studentList, new StudentComparator()); - for (Student st: studentList) { System.out.println(st.getFname()); } diff --git a/Java/Data Structures/Java Stack/Solution.java b/Java/Data Structures/Java Stack/Solution.java index 9da5d26..d2a0f87 100644 --- a/Java/Data Structures/Java Stack/Solution.java +++ b/Java/Data Structures/Java Stack/Solution.java @@ -3,11 +3,12 @@ // HackerRank: hackerrank.com/rshaghoulian import java.util.Scanner; -import java.util.Stack; import java.util.HashMap; +import java.util.ArrayDeque; + +// ArrayDeque is "likely to be faster than Stack when used as a stack" - Java documentation class Solution { - public static void main(String[] args) { /* Create HashMap to match opening brackets with closing brackets */ HashMap map = new HashMap<>(); @@ -24,21 +25,19 @@ class Solution { scan.close(); } - public static boolean isBalanced(String expression, HashMap map) { - /* Odd length strings are not balanced */ + private static boolean isBalanced(String expression, HashMap map) { if ((expression.length() % 2) != 0) { - return false; - } - - Stack stack = new Stack<>(); + return false; // odd length Strings are not balanced + } + ArrayDeque deque = new ArrayDeque<>(); // use deque as a stack for (int i = 0; i < expression.length(); i++) { Character ch = expression.charAt(i); if (map.containsKey(ch)) { - stack.push(ch); - } else if (stack.isEmpty() || ch != map.get(stack.pop())) { + deque.push(ch); + } else if (deque.isEmpty() || ch != map.get(deque.pop())) { return false; } } - return stack.isEmpty(); + return deque.isEmpty(); } } diff --git a/Java/Data Structures/Java Subarray/Solution.java b/Java/Data Structures/Java Subarray/Solution.java index 9cf5d30..2ef487f 100644 --- a/Java/Data Structures/Java Subarray/Solution.java +++ b/Java/Data Structures/Java Subarray/Solution.java @@ -4,12 +4,15 @@ import java.util.Scanner; -public class Solution { +// Our subarray must be contiguous, so we have O(n^2) contiguous subarrays +// Time Complexity: O(n^2) +// Space Complexity: O(1) +public class Solution { public static void main(String[] args) { - /* Read and save input */ + /* Save input */ Scanner scan = new Scanner(System.in); - int size = scan.nextInt(); + int size = scan.nextInt(); int [] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = scan.nextInt(); @@ -19,7 +22,6 @@ public class Solution { System.out.println(negativeSubarrays(array)); } - /* O(n^2) runtime */ private static int negativeSubarrays(int [] array) { int count = 0; int sum = 0; diff --git a/Java/Introduction/Java Currency Formatter/Solution.java b/Java/Introduction/Java Currency Formatter/Solution.java index 4394163..08e7173 100644 --- a/Java/Introduction/Java Currency Formatter/Solution.java +++ b/Java/Introduction/Java Currency Formatter/Solution.java @@ -7,15 +7,13 @@ import java.text.NumberFormat; import java.util.Locale; public class Solution { - public static void main(String[] args) { - /* Read input */ - Scanner scanner = new Scanner(System.in); + /* Save input */ + Scanner scan = new Scanner(System.in); double payment = scanner.nextDouble(); - scanner.close(); + scan.close(); - /* Create custom Locale for India. - I used the "IANA Language Subtag Registry" to find India's country code */ + /* Create custom Locale for India - I used the "IANA Language Subtag Registry" to find India's country code */ Locale indiaLocale = new Locale("en", "IN"); /* Create NumberFormats using Locales */ diff --git a/Java/Introduction/Java Datatypes/Solution.java b/Java/Introduction/Java Datatypes/Solution.java index d21fed8..e0a6f00 100644 --- a/Java/Introduction/Java Datatypes/Solution.java +++ b/Java/Introduction/Java Datatypes/Solution.java @@ -4,12 +4,10 @@ import java.util.Scanner; -class Solution{ - public static void main(String []args) { - +class Solution { + public static void main(String[] args) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(); - for (int i = 0; i < t; i++) { try { long x = scan.nextLong(); @@ -26,8 +24,8 @@ class Solution{ if (x >= Long.MIN_VALUE && x <= Long.MAX_VALUE) { System.out.println("* long"); } - } catch(Exception e) { - System.out.println(scan.next() +" can't be fitted anywhere."); + } catch (Exception e) { + System.out.println(scan.next() + " can't be fitted anywhere."); } } scan.close(); diff --git a/Java/Introduction/Java End-of-file/Solution.java b/Java/Introduction/Java End-of-file/Solution.java index dabeeda..fa9b30f 100644 --- a/Java/Introduction/Java End-of-file/Solution.java +++ b/Java/Introduction/Java End-of-file/Solution.java @@ -5,7 +5,6 @@ import java.util.Scanner; public class Solution { - public static void main(String[] args) { Scanner scan = new Scanner(System.in); int i = 1; diff --git a/Java/Introduction/Java Loops II/Solution.java b/Java/Introduction/Java Loops II/Solution.java index a3590b7..e650f5e 100644 --- a/Java/Introduction/Java Loops II/Solution.java +++ b/Java/Introduction/Java Loops II/Solution.java @@ -5,14 +5,13 @@ import java.util.Scanner; class Solution{ - public static void main(String []args) { + public static void main(String[] args) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(); for (int i = 0; i < t; i++) { int a = scan.nextInt(); int b = scan.nextInt(); int n = scan.nextInt(); - for (int j = 0; j < n; j++) { a += b * (int) Math.pow(2, j); System.out.print(a + " "); diff --git a/Java/Introduction/Java Output Formatting/Solution.java b/Java/Introduction/Java Output Formatting/Solution.java index d5e4882..6f13fb9 100644 --- a/Java/Introduction/Java Output Formatting/Solution.java +++ b/Java/Introduction/Java Output Formatting/Solution.java @@ -5,16 +5,15 @@ import java.util.Scanner; public class Solution { - public static void main(String[] args) { - Scanner scan = new Scanner(System.in); - System.out.println("================================"); - for (int i = 0; i < 3; i++) { - String s1 = scan.next(); - int x = scan.nextInt(); - System.out.format("%-15s%03d%n", s1, x); - } - System.out.println("================================"); - scan.close(); + Scanner scan = new Scanner(System.in); + System.out.println("================================"); + for (int i = 0; i < 3; i++) { + String s1 = scan.next(); + int x = scan.nextInt(); + System.out.format("%-15s%03d%n", s1, x); + } + scan.close(); + System.out.println("================================"); } } diff --git a/Java/Object Oriented Programming/Calculating Volume/Solution.java b/Java/Object Oriented Programming/Calculating Volume/Solution.java index b6557d1..fc8429d 100644 --- a/Java/Object Oriented Programming/Calculating Volume/Solution.java +++ b/Java/Object Oriented Programming/Calculating Volume/Solution.java @@ -16,10 +16,10 @@ import java.security.Permission; class Calculate { static Scanner scan = new Scanner(System.in); - static Output output = new Output(); + static Calculate output = new Calculate(); public static Calculate do_calc() { - return new Calculate(); + return output; } public int get_int_val() throws IOException, NumberFormatException { @@ -54,13 +54,64 @@ class Calculate { return Math.PI * (r * r) * h; } - static void display (double value) { - System.out.println(value); - } -} - -class Output { void display(double value) { System.out.format("%.3f%n", value); } } + +public class Solution { + public static void main(String[] args) { + DoNotTerminate.forbidExit(); + try { + Calculate cal = new Calculate(); + int T = cal.get_int_val(); + while (T--> 0) { + double volume = 0.0; + int ch = cal.get_int_val(); + if (ch == 1) { + int a = cal.get_int_val(); + volume = Calculate.do_calc().get_volume(a); + } else if (ch == 2) { + int l = cal.get_int_val(); + int b = cal.get_int_val(); + int h = cal.get_int_val(); + volume = Calculate.do_calc().get_volume(l, b, h); + } else if (ch == 3) { + double r = cal.get_double_val(); + volume = Calculate.do_calc().get_volume(r); + } else if (ch == 4) { + double r = cal.get_double_val(); + double h = cal.get_double_val(); + volume = Calculate.do_calc().get_volume(r, h); + } + cal.output.display(volume); + } + } catch (NumberFormatException e) { + System.out.print(e); + } catch (IOException e) { + e.printStackTrace(); + } catch (DoNotTerminate.ExitTrappedException e) { + System.out.println("Unsuccessful Termination!!"); + } + } // end of main +} //end of Solution + +/** +*This class prevents the user form using System.exit(0) +* from terminating the program abnormally. +* +*/ +class DoNotTerminate { + public static class ExitTrappedException extends SecurityException {} + public static void forbidExit() { + final SecurityManager securityManager = new SecurityManager() { + @Override + public void checkPermission(Permission permission) { + if (permission.getName().contains("exitVM")) { + throw new ExitTrappedException(); + } + } + }; + System.setSecurityManager(securityManager); + } +} //end of Do_Not_Terminate diff --git a/Java/Object Oriented Programming/Java Abstract Class/Solution.java b/Java/Object Oriented Programming/Java Abstract Class/Solution.java index 62abf93..8bdfd55 100644 --- a/Java/Object Oriented Programming/Java Abstract Class/Solution.java +++ b/Java/Object Oriented Programming/Java Abstract Class/Solution.java @@ -21,12 +21,12 @@ class MyBook extends Book { public class Main { public static void main(String []args) { - //Book new_novel=new Book(); This line prHMain.java:25: error: Book is abstract; cannot be instantiated + // Book new_novel=new Book(); This line prHMain.java:25: error: Book is abstract; cannot be instantiated Scanner sc = new Scanner(System.in); String title = sc.nextLine(); MyBook new_novel = new MyBook(); new_novel.setTitle(title); - System.out.println("The title is: "+ new_novel.getTitle()); + System.out.println("The title is: " + new_novel.getTitle()); sc.close(); } } diff --git a/Java/Object Oriented Programming/Java Inheritance II/Solution.java b/Java/Object Oriented Programming/Java Inheritance II/Solution.java index 67e4903..92355c9 100644 --- a/Java/Object Oriented Programming/Java Inheritance II/Solution.java +++ b/Java/Object Oriented Programming/Java Inheritance II/Solution.java @@ -16,7 +16,7 @@ class Arithmetic { class Adder extends Arithmetic {} -public class Solution{ +public class Solution { public static void main(String []args) { // Create a new Adder object Adder a = new Adder(); @@ -26,5 +26,5 @@ public class Solution{ // Print the result of 3 calls to Adder's `add(int,int)` method as 3 space-separated integers: System.out.print(a.add(10,32) + " " + a.add(10,3) + " " + a.add(10,10) + "\n"); - } + } } diff --git a/Java/Object Oriented Programming/Java Interface/Solution.java b/Java/Object Oriented Programming/Java Interface/Solution.java index c5dd330..c821673 100644 --- a/Java/Object Oriented Programming/Java Interface/Solution.java +++ b/Java/Object Oriented Programming/Java Interface/Solution.java @@ -9,10 +9,10 @@ interface AdvancedArithmetic { } class MyCalculator implements AdvancedArithmetic { - // Runtime: O(n^(1/2)) + // Time Complexity: O(n^(1/2)) // Space Complexity: O(1) public int divisor_sum(int n) { - int sum = 0; + int sum = 0; int sqrt = (int) Math.sqrt(n); for (int i = 1; i <= sqrt; i++) { if (n % i == 0) { // if "i" is a divisor @@ -28,7 +28,7 @@ class MyCalculator implements AdvancedArithmetic { } class Solution { - public static void main(String []args) { + public static void main(String[] args) { MyCalculator my_calculator = new MyCalculator(); System.out.print("I implemented: "); ImplementedInterfaceNames(my_calculator); diff --git a/Java/Strings/Java Anagrams/Solution.java b/Java/Strings/Java Anagrams/Solution.java index ae2ed74..4c89042 100644 --- a/Java/Strings/Java Anagrams/Solution.java +++ b/Java/Strings/Java Anagrams/Solution.java @@ -6,15 +6,14 @@ import java.io.*; import java.util.*; public class Solution { - /* Runtime: O(n) using a HashMap */ + // Time Complexity: O(n) using a HashMap + // Space Complexity: O(n) static boolean isAnagram(String a, String b) { if (a == null || b == null || a.length() != b.length()) { return false; } - a = a.toLowerCase(); b = b.toLowerCase(); - HashMap map = new HashMap<>(); /* Fill HashMap with 1st String */ diff --git a/Java/Strings/Java Regex 3 - Username Checker/Solution.java b/Java/Strings/Java Regex 3 - Username Checker/Solution.java index e7fca8f..bb04698 100644 --- a/Java/Strings/Java Regex 3 - Username Checker/Solution.java +++ b/Java/Strings/Java Regex 3 - Username Checker/Solution.java @@ -9,7 +9,7 @@ import java.math.*; import java.util.regex.*; public class Solution { - public static void main(String[] args){ + public static void main(String[] args) { Scanner in = new Scanner(System.in); int testCases = Integer.parseInt(in.nextLine()); while (testCases > 0) { diff --git a/Java/Strings/Java String Compare/Solution.java b/Java/Strings/Java String Compare/Solution.java index b8d7aa1..12e0800 100644 --- a/Java/Strings/Java String Compare/Solution.java +++ b/Java/Strings/Java String Compare/Solution.java @@ -5,9 +5,8 @@ import java.util.Scanner; public class Solution { - public static void main(String[] args) { - /* Read input */ + /* Save input */ Scanner scan = new Scanner(System.in); String s = scan.nextLine(); int k = scan.nextInt(); diff --git a/Java/Strings/Java String Reverse/Solution.java b/Java/Strings/Java String Reverse/Solution.java index f89d854..73e8f46 100644 --- a/Java/Strings/Java String Reverse/Solution.java +++ b/Java/Strings/Java String Reverse/Solution.java @@ -6,7 +6,6 @@ import java.util.Scanner; /* If a String is equivalent to itself when reversed, it's a palindrome */ public class Solution { - public static void main(String[] args) { /* Read input */ Scanner scan = new Scanner(System.in); diff --git a/Java/Strings/Java Strings Introduction/Solution.java b/Java/Strings/Java Strings Introduction/Solution.java index 9623d0c..3e1be5e 100644 --- a/Java/Strings/Java Strings Introduction/Solution.java +++ b/Java/Strings/Java Strings Introduction/Solution.java @@ -5,9 +5,8 @@ import java.util.Scanner; public class Solution { - public static void main(String[] args) { - /* Read input */ + /* Save input */ Scanner scan = new Scanner(System.in); String A = scan.next(); String B = scan.next(); diff --git a/Java/Strings/Pattern Syntax Checker/Solution.java b/Java/Strings/Pattern Syntax Checker/Solution.java index 0e5202b..34b0e1f 100644 --- a/Java/Strings/Pattern Syntax Checker/Solution.java +++ b/Java/Strings/Pattern Syntax Checker/Solution.java @@ -6,14 +6,12 @@ import java.util.Scanner; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; -/* If a PatternSyntaxException is not thrown by Pattern.compile, - then the regular expression is valid. -*/ +// If a PatternSyntaxException is not thrown by Pattern.compile, the regular expresion is valid public class Solution { - public static void main(String[] args){ + public static void main(String[] args) { Scanner scan = new Scanner(System.in); int testCases = Integer.parseInt(scan.nextLine()); - while (testCases-- > 0){ + while (testCases-- > 0) { String pattern = scan.nextLine(); try { Pattern.compile(pattern); diff --git a/Java/Strings/Tag Content Extractor/Solution.java b/Java/Strings/Tag Content Extractor/Solution.java index 28fae50..8586b95 100644 --- a/Java/Strings/Tag Content Extractor/Solution.java +++ b/Java/Strings/Tag Content Extractor/Solution.java @@ -7,25 +7,23 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; /* Solution assumes we can't have the symbol "<" as text between tags */ -public class Solution{ - public static void main(String[] args){ - Scanner scan = new Scanner(System.in); +public class Solution { + public static void main(String[] args) { + Scanner scan = new Scanner(System.in); int testCases = Integer.parseInt(scan.nextLine()); - while (testCases-- > 0) { String line = scan.nextLine(); - boolean matchFound = false; Pattern r = Pattern.compile("<(.+)>([^<]+)"); Matcher m = r.matcher(line); - while (m.find()) { System.out.println(m.group(2)); matchFound = true; } - if ( ! matchFound) { + if (!matchFound) { System.out.println("None"); } } + scan.close(); } }