├── SQL ├── Basic Select │ ├── Select All.sql │ ├── Select By ID.sql │ ├── Employee Names.sql │ ├── Weather Observation Station 1.sql │ ├── Japanese Cities' Attributes.sql │ ├── Japanese Cities' Names.sql │ ├── Weather Observation Station 3.sql │ ├── Weather Observation Station 10.sql │ ├── Weather Observation Station 9.sql │ ├── Higher Than 75 Marks.sql │ ├── Revising the Select Query I.sql │ ├── Employee Salaries.sql │ ├── Revising the Select Query II.sql │ ├── Weather Observation Station 11.sql │ ├── Weather Observation Station 4.sql │ ├── Weather Observation Station 8.sql │ ├── Weather Observation Station 12.sql │ ├── Weather Observation Station 5.sql │ ├── Weather Observation Station 7.sql │ └── Weather Observation Station 6.sql ├── Aggregation │ ├── Average Population.sql │ ├── Japan Population.sql │ ├── Population Density Difference.sql │ ├── Revising Aggregations - Averages.sql │ ├── Revising Aggregations - The Count Function.sql │ ├── The Blunder.sql │ ├── Revising Aggregations - The Sum Function.sql │ ├── Weather Observation Station 2.sql │ ├── Weather Observation Station 14.sql │ ├── Weather Observation Station 16.sql │ ├── Weather Observation Station 17.sql │ ├── Weather Observation Station 15.sql │ ├── Top Earners.sql │ ├── Weather Observation Station 13.sql │ ├── Weather Observation Station 18.sql │ └── Weather Observation Station 19.sql └── Basic Join │ ├── African Cities.sql │ ├── Asian Population.sql │ ├── Average Population of Each Continent.sql │ └── The Report.sql ├── Data Structures ├── Multiple Choice │ ├── Data Structures MCQ 3 │ │ └── Solution.txt │ ├── Data Structures MCQ 1 │ │ └── Solution.txt │ └── Data Structures MCQ 2 │ │ └── Solution.txt ├── Trees │ ├── Tree - Inorder Traversal │ │ └── Solution.java │ ├── Tree - Preorder Traversal │ │ └── Solution.java │ ├── Tree - Postorder Traversal │ │ └── Solution.java │ ├── Tree - Huffman Decoding │ │ └── Solution.java │ ├── Is This a Binary Search Tree │ │ └── Solution.java │ ├── Tree - Level Order Traversal │ │ └── Solution.java │ ├── Binary Search Tree - Lowest Common Ancestor │ │ └── Solution.java │ └── Binary Search Tree - Insertion │ │ └── Solution.java ├── Linked Lists │ ├── Insert a node at the head of a linked list │ │ └── Solution.java │ ├── Print the Elements of a Linked List │ │ └── Solution.java │ ├── Print in Reverse │ │ └── Solution.java │ ├── Delete duplicate-value nodes from a sorted linked list │ │ └── Solution.java │ ├── Insert a Node at the Tail of a Linked List │ │ └── Solution.java │ ├── Compare two linked lists │ │ └── Solution.java │ ├── Delete a Node │ │ └── Solution.java │ ├── Reverse a linked list │ │ └── Solution.java │ ├── Cycle Detection │ │ └── Solution.java │ ├── Get Node Value │ │ └── Solution.java │ ├── Insert a node at a specific position in a linked list │ │ └── Solution.java │ ├── Reverse a doubly linked list │ │ └── Solution.java │ ├── Find Merge Point of Two Lists │ │ └── Solution.java │ └── Merge two sorted linked lists │ │ └── Solution.java ├── Arrays │ ├── Arrays - DS │ │ └── Solution.java │ ├── Sparse Arrays │ │ └── Solution.java │ ├── Dynamic Array │ │ └── Solution.java │ └── 2D Array - DS │ │ └── Solution.java └── Stacks │ └── Maximum Element │ └── Solution.java ├── Java ├── Introduction │ ├── Java Int to String │ │ └── Solution.java │ ├── Welcome to Java! │ │ └── Solution.java │ ├── Java End-of-file │ │ └── Solution.java │ ├── Java Loops I │ │ └── Solution.java │ ├── Java Stdin and Stdout I │ │ └── Solution.java │ ├── Java Output Formatting │ │ └── Solution.java │ ├── Java Loops II │ │ └── Solution.java │ ├── Java Stdin and Stdout II │ │ └── Solution.java │ ├── Java If-Else │ │ └── Solution.java │ ├── Java Static Initializer Block │ │ └── Solution.java │ ├── Java Datatypes │ │ └── Solution.java │ └── Java Currency Formatter │ │ └── Solution.java ├── Strings │ ├── Java Substring │ │ └── Solution.java │ ├── Java String Reverse │ │ └── Solution.java │ ├── Java Regex │ │ └── Solution.java │ ├── Java Regex 3 - Username Checker │ │ └── Solution.java │ ├── Pattern Syntax Checker │ │ └── Solution.java │ ├── Tag Content Extractor │ │ └── Solution.java │ ├── Java Strings Introduction │ │ └── Solution.java │ ├── Java String Compare │ │ └── Solution.java │ ├── Java String Tokens │ │ └── Solution.java │ └── Java Anagrams │ │ └── Solution.java ├── Advanced │ ├── Java Singleton Pattern │ │ └── Solution.java │ ├── Java Reflection - Attributes │ │ └── Solution.java │ ├── Java MD5 │ │ └── Solution.java │ ├── Java SHA-256 │ │ └── Solution.java │ └── Covariant Return Types │ │ └── Solution.java ├── BigNumber │ ├── Java BigInteger │ │ └── Solution.java │ ├── Java Primality Test │ │ └── Solution.java │ └── Java BigDecimal │ │ └── Solution.java ├── Data Structures │ ├── Java 1D Array │ │ └── Solution.java │ ├── Java 1D Array (Part 2) │ │ └── Solution.java │ ├── Java Hashset │ │ └── Solution.java │ ├── Java Generics │ │ └── Solution.java │ ├── Java Subarray │ │ └── Solution.java │ ├── Java 2D Array │ │ └── Solution.java │ ├── Java Comparator │ │ └── Solution.java │ ├── Java ArrayList │ │ └── Solution.java │ ├── Java List │ │ └── Solution.java │ └── Java Map │ │ └── Solution.java ├── Exception Handling │ ├── Java Exception Handling (Try-catch) │ │ └── Solution.java │ └── Java Exception Handling │ │ └── Solution.java └── Object Oriented Programming │ ├── Java Inheritance I │ └── Solution.java │ ├── Java Method Overriding 2 (Super Keyword) │ └── Solution.java │ ├── Java Abstract Class │ └── Solution.java │ ├── Java Inheritance II │ └── Solution.java │ ├── Java Method Overriding │ └── Solution.java │ ├── Java Iterator │ └── Solution.java │ └── Java Instanceof keyword │ └── Solution.java ├── contributing.md ├── 10 Days of Statistics ├── Day 2 - More Dice │ └── Solution.txt ├── Day 3 - Drawing Marbles │ └── Solution.txt ├── Day 2 - Basic Probability │ └── Solution.txt ├── Day 3 - Cards of the Same Suit │ └── Solution.txt ├── Day 6 - The Central Limit Theorem III │ └── Solution.java ├── Day 2 - Compound Event Probability │ └── Solution.txt ├── Day 5 - Poisson Distribution I │ └── Solution.java ├── Day 8 - Pearson Correlation Coefficient II │ └── Solution.txt ├── Day 5 - Poisson Distribution II │ └── Solution.java ├── Day 0 - Weighted Mean │ └── Solution.java ├── Day 1 - Standard Deviation │ └── Solution.java ├── Day 4 - Geometric Distribution I │ └── Solution.java ├── Day 4 - Binomial Distribution I │ └── Solution.java ├── Day 4 - Geometric Distribution II │ └── Solution.java └── Day 4 - Binomial Distribution II │ └── Solution.java ├── .gitattributes ├── Cracking the Coding Interview ├── Techniques, Concepts │ ├── Bit Manipulation - Lonely Integer │ │ └── Solution.java │ ├── Recursion - Fibonacci Numbers │ │ └── Solution.java │ ├── DP - Coin Change │ │ └── Solution.java │ ├── Recursion - Davis' Staircase │ │ └── Solution.java │ └── Time Complexity - Primality │ │ └── Solution.java ├── Data Structures │ ├── Trees - Is This a Binary Search Tree │ │ └── Solution.java │ ├── Hash Tables - Ransom Note │ │ └── Solution.java │ ├── Linked Lists - Detect a Cycle │ │ └── Solution.java │ ├── Stacks - Balanced Brackets │ │ └── Solution.java │ └── Strings - Making Anagrams │ │ └── Solution.java └── Algorithms │ ├── Sorting - Comparator │ └── Solution.java │ └── Binary Search - Ice Cream Parlor │ └── Solution.java ├── 30 Days of Code ├── Day 05 - Loops │ └── Solution.java ├── Day 16 - Exceptions - String to Integer │ └── Solution.java ├── Day 09 - Recursion │ └── Solution.java ├── Day 07 - Arrays │ └── Solution.java ├── Day 27 - Testing │ └── Solution.java ├── Day 10 - Binary Numbers │ └── Solution.java ├── Day 03 - Intro to Conditional Statements │ └── Solution.java ├── Day 00 - Hello, World │ └── Solution.java ├── Day 02 - Operators │ └── Solution.java ├── Day 06 - Let's Review │ └── Solution.java ├── Day 17 - More Exceptions │ └── Solution.java ├── Day 08 - Dictionaries and Maps │ └── Solution.java ├── Day 13 - Abstract Classes │ └── Solution.java ├── Day 25 - Running Time and Complexity │ └── Solution.java ├── Day 14 - Scope │ └── Solution.java ├── Day 11 - 2D Arrays │ └── Solution.java ├── Day 15 - Linked List │ └── Solution.java ├── Day 04 - Class vs. Instance │ └── Solution.java ├── Day 26 - Nested Logic │ └── Solution.java ├── Day 21 - Generics │ └── Solution.java ├── Day 19 - Interfaces │ └── Solution.java └── Day 01 - Data Types │ └── Solution.java ├── General Programming ├── Basic Programming │ ├── Find Digits │ │ └── Solution.java │ ├── Simple Array Sum │ │ └── Solution.java │ ├── A Very Big Sum │ │ └── Solution.java │ ├── Viral Advertising │ │ └── Solution.java │ ├── Solve Me First │ │ └── Solution.java │ ├── Sherlock and Squares │ │ └── Solution.java │ ├── Extra Long Factorials │ │ └── Solution.java │ ├── Staircase │ │ └── Solution.java │ ├── Angry Professor │ │ └── Solution.java │ ├── Mini-Max Sum │ │ └── Solution.java │ ├── Grading Students │ │ └── Solution.java │ ├── The Hurdle Race │ │ └── Solution.java │ ├── Compare the Triplets │ │ └── Solution.java │ ├── Taum and B'day │ │ └── Solution.java │ ├── Equalize the Array │ │ └── Solution.java │ ├── Cut the sticks │ │ └── Solution.java │ ├── Jumping on the Clouds │ │ └── Solution.java │ ├── Beautiful Days at the Movies │ │ └── Solution.java │ ├── Repeated String │ │ └── Solution.java │ ├── Sock Merchant │ │ └── Solution.java │ ├── Time Conversion │ │ └── Solution.java │ ├── Jumping on the Clouds - Revisited │ │ └── Solution.java │ ├── Cats and a Mouse │ │ └── Solution.java │ ├── Designer PDF Viewer │ │ └── Solution.java │ ├── Plus Minus │ │ └── Solution.java │ ├── Drawing Book │ │ └── Solution.java │ ├── Diagonal Difference │ │ └── Solution.java │ ├── Bon Appetit │ │ └── Solution.java │ ├── Save the Prisoner! │ │ └── Solution.java │ ├── Minimum Distances │ │ └── Solution.java │ ├── Sequence Equation │ │ └── Solution.java │ ├── Breaking the Records │ │ └── Solution.java │ ├── Utopian Tree │ │ └── Solution.java │ ├── Migratory Birds │ │ └── Solution.java │ ├── Counting Valleys │ │ └── Solution.java │ ├── Picking Numbers │ │ └── Solution.java │ ├── Birthday Cake Candles │ │ └── Solution.java │ ├── Divisible Sum Pairs │ │ └── Solution.java │ ├── Library Fine │ │ └── Solution.java │ ├── Apple and Orange │ │ └── Solution.java │ ├── Kangaroo │ │ └── Solution.java │ └── Fair Rations │ │ └── Solution.java ├── RegEx │ └── HackerRank in a String! │ │ └── Solution.java └── Object-oriented Programming │ ├── Abstract Classes │ └── Solution.java │ └── Class vs. Instance │ └── Solution.java ├── Algorithms ├── Sorting │ ├── Intro to Tutorial Challenges │ │ └── Solution.java │ ├── Counting Sort 1 │ │ └── Solution.java │ ├── Counting Sort 2 │ │ └── Solution.java │ ├── Counting Sort 3 │ │ └── Solution.java │ ├── Insertion Sort - Part 1 │ │ └── Solution.java │ ├── Running Time of Algorithms │ │ └── Solution.java │ ├── Minimum Absolute Difference in an Array │ │ └── Solution.java │ ├── Correctness and the Loop Invariant │ │ └── Solution.java │ └── Insertion Sort - Part 2 │ │ └── Solution.java ├── Strings │ ├── CamelCase │ │ └── Solution.java │ ├── Mars Exploration │ │ └── Solution.java │ ├── Gemstones │ │ └── Solution.java │ ├── Caesar Cipher │ │ └── Solution.java │ ├── Beautiful Binary String │ │ └── Solution.java │ ├── String Construction │ │ └── Solution.java │ ├── Alternating Characters │ │ └── Solution.java │ ├── The Love-Letter Mystery │ │ └── Solution.java │ ├── Super Reduced String │ │ └── Solution.java │ └── Weighted Uniform Strings │ │ └── Solution.java ├── Bit Manipulation │ ├── Lonely Integer │ │ └── Solution.java │ ├── Bit Manipulation - Lonely Integer │ │ └── Solution.java │ ├── Maximizing XOR │ │ └── Solution.java │ └── Sum vs XOR │ │ └── Solution.java ├── Greedy │ ├── Maximum Perimeter Triangle │ │ └── Solution.java │ └── Grid Challenge │ │ └── Solution.java └── Search │ └── Ice Cream Parlor │ └── Solution.java ├── Implementation └── Brute Force │ ├── Pangrams │ └── Solution.java │ ├── Modified Kaprekar Numbers │ └── Solution.java │ └── Making Anagrams │ └── Solution.java ├── .gitignore └── license /SQL/Basic Select/Select All.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT * FROM CITY; 4 | -------------------------------------------------------------------------------- /SQL/Basic Select/Select By ID.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT * FROM CITY 4 | WHERE ID = 1661; 5 | -------------------------------------------------------------------------------- /SQL/Basic Select/Employee Names.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT name FROM Employee 4 | ORDER BY name; 5 | -------------------------------------------------------------------------------- /SQL/Aggregation/Average Population.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT FLOOR(AVG(POPULATION)) 4 | FROM CITY; 5 | -------------------------------------------------------------------------------- /SQL/Basic Select/Weather Observation Station 1.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT CITY, STATE FROM STATION; 4 | -------------------------------------------------------------------------------- /SQL/Aggregation/Japan Population.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT SUM(POPULATION) FROM CITY 4 | WHERE COUNTRYCODE = 'JPN'; 5 | -------------------------------------------------------------------------------- /SQL/Basic Select/Japanese Cities' Attributes.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT * FROM CITY 4 | WHERE COUNTRYCODE = 'JPN'; 5 | -------------------------------------------------------------------------------- /SQL/Basic Select/Japanese Cities' Names.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT NAME FROM CITY 4 | WHERE COUNTRYCODE = 'JPN'; 5 | -------------------------------------------------------------------------------- /SQL/Aggregation/Population Density Difference.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT MAX(POPULATION) - MIN(POPULATION) 4 | FROM CITY; 5 | -------------------------------------------------------------------------------- /SQL/Basic Select/Weather Observation Station 3.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT DISTINCT CITY FROM STATION 4 | WHERE ID % 2 = 0; 5 | -------------------------------------------------------------------------------- /SQL/Aggregation/Revising Aggregations - Averages.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT AVG(POPULATION) FROM CITY 4 | WHERE DISTRICT = 'California'; 5 | -------------------------------------------------------------------------------- /SQL/Aggregation/Revising Aggregations - The Count Function.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT COUNT(*) FROM CITY 4 | WHERE POPULATION > 100000; 5 | -------------------------------------------------------------------------------- /SQL/Aggregation/The Blunder.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT 4 | CEIL(AVG(Salary) - AVG(REPLACE(SALARY, '0', ''))) 5 | FROM EMPLOYEES; 6 | -------------------------------------------------------------------------------- /SQL/Basic Select/Weather Observation Station 10.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT DISTINCT CITY FROM STATION 4 | WHERE CITY REGEXP '[^aeiou]$'; 5 | -------------------------------------------------------------------------------- /SQL/Basic Select/Weather Observation Station 9.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT DISTINCT CITY FROM STATION 4 | WHERE CITY REGEXP '^[^aeiou]'; 5 | -------------------------------------------------------------------------------- /SQL/Basic Select/Higher Than 75 Marks.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT Name FROM STUDENTS 4 | WHERE Marks > 75 5 | ORDER BY RIGHT(Name, 3), ID; 6 | -------------------------------------------------------------------------------- /SQL/Basic Select/Revising the Select Query I.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT * FROM CITY 4 | WHERE COUNTRYCODE = 'USA' AND POPULATION > 100000; 5 | -------------------------------------------------------------------------------- /SQL/Aggregation/Revising Aggregations - The Sum Function.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT SUM(POPULATION) FROM CITY 4 | WHERE DISTRICT = 'California'; 5 | -------------------------------------------------------------------------------- /SQL/Basic Select/Employee Salaries.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT name FROM Employee 4 | WHERE salary > 2000 AND months < 10 5 | ORDER BY employee_id; 6 | -------------------------------------------------------------------------------- /SQL/Basic Select/Revising the Select Query II.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT NAME FROM CITY 4 | WHERE COUNTRYCODE = 'USA' AND POPULATION > 120000; 5 | -------------------------------------------------------------------------------- /SQL/Basic Select/Weather Observation Station 11.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT DISTINCT CITY FROM STATION 4 | WHERE CITY REGEXP '^[^aeiou]|[^aeiou]$'; 5 | -------------------------------------------------------------------------------- /SQL/Basic Select/Weather Observation Station 4.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT 4 | COUNT(CITY) - COUNT(DISTINCT CITY) 5 | FROM 6 | STATION; 7 | -------------------------------------------------------------------------------- /SQL/Basic Select/Weather Observation Station 8.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT DISTINCT CITY FROM STATION 4 | WHERE CITY REGEXP '^[aeiou].*[aeiou]$'; 5 | -------------------------------------------------------------------------------- /SQL/Basic Select/Weather Observation Station 12.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT DISTINCT CITY FROM STATION 4 | WHERE CITY REGEXP '^[^aeiou].*[^aeiou]$'; 5 | -------------------------------------------------------------------------------- /SQL/Aggregation/Weather Observation Station 2.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT 4 | ROUND(SUM(LAT_N), 2), 5 | ROUND(SUM(LONG_W), 2) 6 | FROM 7 | STATION; 8 | -------------------------------------------------------------------------------- /SQL/Aggregation/Weather Observation Station 14.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT 4 | TRUNCATE(MAX(LAT_N), 4) 5 | FROM 6 | STATION 7 | WHERE 8 | LAT_N < 137.2345; 9 | -------------------------------------------------------------------------------- /SQL/Aggregation/Weather Observation Station 16.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT 4 | ROUND(MIN(LAT_N), 4) 5 | FROM 6 | STATION 7 | WHERE 8 | LAT_N > 38.7780; 9 | -------------------------------------------------------------------------------- /SQL/Aggregation/Weather Observation Station 17.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT ROUND(LONG_W, 4) 4 | FROM STATION 5 | WHERE LAT_N > 38.7780 6 | ORDER BY LAT_N 7 | LIMIT 1; 8 | -------------------------------------------------------------------------------- /SQL/Basic Join/African Cities.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT CITY.NAME 4 | FROM CITY, COUNTRY 5 | WHERE CITY.COUNTRYCODE = COUNTRY.CODE AND COUNTRY.CONTINENT = 'Africa'; 6 | -------------------------------------------------------------------------------- /SQL/Aggregation/Weather Observation Station 15.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT ROUND(LONG_W, 4) 4 | FROM STATION 5 | WHERE LAT_N < 137.2345 6 | ORDER BY LAT_N DESC 7 | LIMIT 1; 8 | -------------------------------------------------------------------------------- /SQL/Aggregation/Top Earners.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT salary * months AS earnings, COUNT(*) 4 | FROM Employee 5 | GROUP BY earnings 6 | ORDER BY earnings DESC 7 | LIMIT 1; 8 | -------------------------------------------------------------------------------- /SQL/Basic Join/Asian Population.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT SUM(CITY.POPULATION) 4 | FROM CITY, COUNTRY 5 | WHERE CITY.COUNTRYCODE = COUNTRY.CODE AND COUNTRY.CONTINENT = 'Asia'; 6 | -------------------------------------------------------------------------------- /SQL/Aggregation/Weather Observation Station 13.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT 4 | TRUNCATE(SUM(LAT_N), 4) 5 | FROM 6 | STATION 7 | WHERE 8 | LAT_N BETWEEN 38.7880 AND 137.2345; 9 | -------------------------------------------------------------------------------- /SQL/Aggregation/Weather Observation Station 18.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT 4 | ROUND(ABS(MAX(LAT_N) - MIN(LAT_N)) 5 | + ABS(MAX(LONG_W) - MIN(LONG_W)), 4) 6 | FROM 7 | STATION; 8 | -------------------------------------------------------------------------------- /SQL/Basic Join/Average Population of Each Continent.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT COUNTRY.CONTINENT, FLOOR(AVG(CITY.POPULATION)) 4 | FROM CITY INNER JOIN COUNTRY 5 | ON CITY.COUNTRYCODE = COUNTRY.CODE 6 | GROUP BY COUNTRY.CONTINENT; 7 | -------------------------------------------------------------------------------- /SQL/Basic Join/The Report.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT IF (S.Marks < 70, 'NULL', S.Name), G.Grade, S.Marks 4 | FROM Students AS S, Grades AS G 5 | WHERE S.Marks BETWEEN G.Min_Mark AND G.Max_Mark 6 | ORDER BY G.GRADE DESC, S.NAME; 7 | -------------------------------------------------------------------------------- /SQL/Aggregation/Weather Observation Station 19.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT 4 | ROUND(SQRT( 5 | POWER(MAX(LAT_N) - MIN(LAT_N), 2) 6 | + POWER(MAX(LONG_W) - MIN(LONG_W), 2) 7 | ), 4) 8 | FROM 9 | STATION; 10 | -------------------------------------------------------------------------------- /Data Structures/Multiple Choice/Data Structures MCQ 3/Solution.txt: -------------------------------------------------------------------------------- 1 | github.com/RodneyShag 2 | 3 | 4 | 5 | Answer: Stack 6 | 7 | - A Queue is FIFO = First In First Out 8 | - A Stack is LIFO = Last In First Out 9 | - An array or vector aren't exactly applicable here. -------------------------------------------------------------------------------- /Java/Introduction/Java Int to String/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* Here are 3 ways to convert an int to a String. Use any of the 3 methods. */ 4 | // String s = String.valueOf(n); 5 | // String s = Integer.toString(n); 6 | String s = "" + n; 7 | -------------------------------------------------------------------------------- /Java/Introduction/Welcome to Java!/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | public class Solution { 4 | public static void main(String[] args) { 5 | System.out.println("Hello, World."); 6 | System.out.println("Hello, Java."); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /SQL/Basic Select/Weather Observation Station 5.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT CITY, LENGTH(CITY) FROM STATION 4 | ORDER BY LENGTH(CITY), CITY 5 | LIMIT 1; 6 | 7 | SELECT CITY, LENGTH(CITY) FROM STATION 8 | ORDER BY LENGTH(CITY) DESC, CITY 9 | LIMIT 1; 10 | -------------------------------------------------------------------------------- /contributing.md: -------------------------------------------------------------------------------- 1 | ### Pull Requests / Contributions 2 | 3 | Sorry, this repo is currently not accepting contributions or pull requests. 4 | 5 | ### Adding a solution 6 | 7 | If you want to add a solution, feel free to fork the repo and add the solution in your new forked repo. 8 | -------------------------------------------------------------------------------- /10 Days of Statistics/Day 2 - More Dice/Solution.txt: -------------------------------------------------------------------------------- 1 | github.com/RodneyShag 2 | 3 | 4 | Answer: 1/9 5 | 6 | There are 6 possibilities on each die. On 2 dice, there are 6 * 6 = 36 possibilities 7 | 8 | There are 4 cases that match the desired criteria: (1,5) (5,1) (2,4) (4,2) 9 | 10 | This gives us a probability of 4/36 = 1/9 11 | -------------------------------------------------------------------------------- /10 Days of Statistics/Day 3 - Drawing Marbles/Solution.txt: -------------------------------------------------------------------------------- 1 | github.com/RodneyShag 2 | 3 | 4 | Answer: 2/3 5 | 6 | After drawing the first marble, we are left with 2 red marbles and 4 blue marbles. 7 | Now we calculate the probability of drawing a blue marble as : 8 | 9 | = (# of blue marbles) / (total # of marbles) 10 | = 4 / (2 + 4) 11 | = 2 / 3 12 | -------------------------------------------------------------------------------- /10 Days of Statistics/Day 2 - Basic Probability/Solution.txt: -------------------------------------------------------------------------------- 1 | github.com/RodneyShag 2 | 3 | 4 | Answer: 5/6 5 | 6 | There are 6 possibilities on each die. On 2 dice, there are 6 * 6 = 36 possibilities 7 | 8 | There are 6 cases where sum >= 10: (4,6), (5,5), (5,6), (6,4), (6,5), (6,6) 9 | 10 | This gives us probability(sum >= 10) = 6/36 = 1/6 11 | 12 | That means probability(sum <= 9) = 1 - 1/6 = 5/6 13 | -------------------------------------------------------------------------------- /Data Structures/Trees/Tree - Inorder Traversal/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* 4 | Node is defined as 5 | 6 | class Node { 7 | int data; 8 | Node left; 9 | Node right; 10 | } 11 | 12 | */ 13 | 14 | void inOrder(Node n) { 15 | if (n != null) { 16 | inOrder(n.left); 17 | System.out.print(n.data + " "); 18 | inOrder(n.right); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Data Structures/Trees/Tree - Preorder Traversal/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* 4 | Node is defined as 5 | 6 | class Node { 7 | int data; 8 | Node left; 9 | Node right; 10 | } 11 | 12 | */ 13 | 14 | void preOrder(Node n) { 15 | if (n != null) { 16 | System.out.print(n.data + " "); 17 | preOrder(n.left); 18 | preOrder(n.right); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Data Structures/Trees/Tree - Postorder Traversal/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* 4 | Node is defined as 5 | 6 | class Node { 7 | int data; 8 | Node left; 9 | Node right; 10 | } 11 | 12 | */ 13 | 14 | void postOrder(Node n) { 15 | if (n != null) { 16 | postOrder(n.left); 17 | postOrder(n.right); 18 | System.out.print(n.data + " "); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Data Structures/Linked Lists/Insert a node at the head of a linked list/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* 4 | Insert Node at the beginning of a linked list 5 | 6 | Node is defined as 7 | class Node { 8 | int data; 9 | Node next; 10 | } 11 | */ 12 | 13 | Node Insert(Node head, int x) { 14 | Node n = new Node(); 15 | n.data = x; 16 | n.next = head; 17 | return n; 18 | } 19 | -------------------------------------------------------------------------------- /SQL/Basic Select/Weather Observation Station 7.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT DISTINCT CITY FROM STATION 4 | WHERE CITY REGEXP '[aeiou]$'; 5 | 6 | -- Pattern | What the pattern matches 7 | --------------------------------------- 8 | -- $ | End of string 9 | -- [...] | Any character listed between the square brackets 10 | 11 | -- Useful Reference: https://www.tutorialspoint.com/mysql/mysql-regexps.htm 12 | -------------------------------------------------------------------------------- /Data Structures/Linked Lists/Print the Elements of a Linked List/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* 4 | Print elements of a linked list on console 5 | 6 | Node is defined as 7 | class Node { 8 | int data; 9 | Node next; 10 | } 11 | */ 12 | 13 | void Print(Node head) { 14 | Node n = head; 15 | while (n != null) { 16 | System.out.println(n.data); 17 | n = n.next; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /SQL/Basic Select/Weather Observation Station 6.sql: -------------------------------------------------------------------------------- 1 | -- github.com/RodneyShag 2 | 3 | SELECT DISTINCT CITY FROM STATION 4 | WHERE CITY REGEXP '^[aeiou]'; 5 | 6 | -- Pattern | What the pattern matches 7 | --------------------------------------- 8 | -- ^ | Beginning of string 9 | -- [...] | Any character listed between the square brackets 10 | 11 | -- Useful Reference: https://www.tutorialspoint.com/mysql/mysql-regexps.htm 12 | -------------------------------------------------------------------------------- /10 Days of Statistics/Day 3 - Cards of the Same Suit/Solution.txt: -------------------------------------------------------------------------------- 1 | github.com/RodneyShag 2 | 3 | 4 | Answer: 12/51 5 | 6 | There are 13 of each suit in a deck. 7 | 8 | We can view this as 2 separate events. First we draw 1 card and see what suit it is. 9 | Whatever suit it is, there are 12 of the same matching suit remaining in the 51-card deck. 10 | Therefore, when we draw the 2nd card, there is a 12/51 chance that it is the same suit. 11 | -------------------------------------------------------------------------------- /Java/Introduction/Java End-of-file/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int i = 1; 9 | while (scan.hasNextLine()) { 10 | System.out.println(i + " " + scan.nextLine()); 11 | i++; 12 | } 13 | scan.close(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/Techniques, Concepts/Bit Manipulation - Lonely Integer/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | // O(n) runtime. O(1) space. Uses XOR. Keep in mind: 4 | // 1) x ^ x = 0 5 | // 2) x ^ 0 = x 6 | // 3) XOR is commutative and associative 7 | 8 | int findLonely(List array) { 9 | int val = 0; 10 | for (int num : array) { 11 | val = val ^ num; // ^ is XOR operator 12 | } 13 | return val; 14 | } 15 | -------------------------------------------------------------------------------- /Data Structures/Multiple Choice/Data Structures MCQ 1/Solution.txt: -------------------------------------------------------------------------------- 1 | github.com/RodneyShag 2 | 3 | 4 | Answer: n-1 5 | 6 | A tree with 1 node has 0 edges. For each node we connect to the tree, we must connect it using 1 additional edge. 7 | 8 | # of nodes # of edges 9 | ---------- ---------- 10 | 1 0 11 | 2 1 12 | 3 2 13 | 4 3 14 | 5 4 15 | 6 5 16 | n n-1 17 | -------------------------------------------------------------------------------- /Java/Introduction/Java Loops I/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int multiplier = scan.nextInt(); 9 | scan.close(); 10 | for (int i = 1; i <= 10; i++) { 11 | System.out.format("%d x %d = %d%n", multiplier, i , i * multiplier); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Java/Strings/Java Substring/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | String str = scan.next(); 9 | int start = scan.nextInt(); 10 | int end = scan.nextInt(); 11 | scan.close(); 12 | 13 | System.out.println(str.substring(start, end)); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /30 Days of Code/Day 05 - Loops/Solution.java: -------------------------------------------------------------------------------- 1 | 2 | // github.com/RodneyShag 3 | 4 | import java.util.Scanner; 5 | 6 | public class Solution { 7 | public static void main(String[] args) { 8 | Scanner scan = new Scanner(System.in); 9 | int multiplier = scan.nextInt(); 10 | scan.close(); 11 | for (int i = 1; i <= 10; i++) { 12 | System.out.format("%d x %d = %d%n", multiplier, i , i * multiplier); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Java/Advanced/Java Singleton Pattern/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.lang.reflect.Constructor; 5 | 6 | class Singleton { 7 | private Singleton() {} 8 | public String str; 9 | private static Singleton instance = null; 10 | public static Singleton getSingleInstance() { 11 | if (instance == null) { 12 | instance = new Singleton(); 13 | } 14 | return instance; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Find Digits/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | static int findDigits(int num) { 4 | int count = 0; 5 | int n = num; 6 | while (n > 0) { 7 | int digit = n % 10; 8 | if (digit != 0 && num % digit == 0) { 9 | count++; 10 | } 11 | n /= 10; 12 | } 13 | return count; 14 | } 15 | 16 | // Discuss on HackerRank: https://www.hackerrank.com/challenges/find-digits/forum/comments/265470 17 | -------------------------------------------------------------------------------- /Java/BigNumber/Java BigInteger/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.math.BigInteger; 5 | 6 | public class Solution { 7 | public static void main(String[] args) { 8 | Scanner scan = new Scanner(System.in); 9 | BigInteger a = new BigInteger(scan.next()); 10 | BigInteger b = new BigInteger(scan.next()); 11 | System.out.println(a.add(b)); 12 | System.out.println(a.multiply(b)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Simple Array Sum/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int size = scan.nextInt(); 9 | int sum = 0; 10 | for (int i = 0; i < size; i++) { 11 | sum += scan.nextInt(); 12 | } 13 | scan.close(); 14 | System.out.println(sum); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/A Very Big Sum/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int size = scan.nextInt(); 9 | long sum = 0; // use long to prevent integer overflow 10 | for (int i = 0; i < size; i++) { 11 | sum += scan.nextInt(); 12 | } 13 | scan.close(); 14 | System.out.println(sum); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Algorithms/Sorting/Intro to Tutorial Challenges/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int V = scan.nextInt(); 9 | int n = scan.nextInt(); 10 | for (int i = 0; i < n; i++) { 11 | if (scan.nextInt() == V) { 12 | System.out.println(i); 13 | break; 14 | } 15 | } 16 | scan.close(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Data Structures/Linked Lists/Print in Reverse/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* 4 | * For your reference: 5 | * 6 | * SinglyLinkedListNode { 7 | * int data; 8 | * SinglyLinkedListNode next; 9 | * } 10 | * 11 | */ 12 | 13 | void reversePrint(SinglyLinkedListNode n) { 14 | if (n != null) { 15 | reversePrint(n.next); 16 | System.out.println(n.data); 17 | } 18 | } 19 | 20 | // Discuss on HackerRank: https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list-in-reverse/forum/comments/255098 21 | -------------------------------------------------------------------------------- /30 Days of Code/Day 16 - Exceptions - String to Integer/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | String str = scan.next(); 9 | scan.close(); 10 | try { 11 | int num = Integer.parseInt(str); 12 | System.out.println(num); 13 | } catch (NumberFormatException e) { 14 | System.out.println("Bad String"); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Data Structures/Linked Lists/Delete duplicate-value nodes from a sorted linked list/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* 4 | Node is defined as 5 | class Node { 6 | int data; 7 | Node next; 8 | } 9 | */ 10 | 11 | Node RemoveDuplicates(Node head) { 12 | if (head == null) { 13 | return null; 14 | } 15 | Node n = head; 16 | while (n.next != null) { 17 | if (n.data == n.next.data) { 18 | n.next = n.next.next; 19 | } else { 20 | n = n.next; 21 | } 22 | } 23 | return head; 24 | } 25 | -------------------------------------------------------------------------------- /Data Structures/Multiple Choice/Data Structures MCQ 2/Solution.txt: -------------------------------------------------------------------------------- 1 | github.com/RodneyShag 2 | 3 | 4 | 5 | Answer: Segment Tree 6 | 7 | By "updates" they mean inserting/deleting an element in the data structure. 8 | By "queries" they mean searching for a specific element. 9 | 10 | Notice that a segment tree (assuming it's balanced) will have height = log n. 11 | Whether we do an insert, delete, or query, we start from the root and decide 12 | to go left or right at each node/level in the tree. We have to make (log n) 13 | of these decisions since that is the height of the segment tree. -------------------------------------------------------------------------------- /General Programming/Basic Programming/Viral Advertising/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int n = scan.nextInt(); 9 | scan.close(); 10 | 11 | int people = 2; 12 | int count = 2; 13 | for (int i = 2; i <= n; i++) { 14 | people = (people * 3) / 2; 15 | count += people; 16 | } 17 | System.out.println(count); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Java/Introduction/Java Stdin and Stdout I/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | /* Read and save input */ 8 | Scanner scan = new Scanner(System.in); 9 | int a = scan.nextInt(); 10 | int b = scan.nextInt(); 11 | int c = scan.nextInt(); 12 | scan.close(); 13 | 14 | /* Print data */ 15 | System.out.println(a); 16 | System.out.println(b); 17 | System.out.println(c); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Data Structures/Trees/Tree - Huffman Decoding/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* 4 | class Node { 5 | public int frequency; // the frequency of this tree 6 | public char data; 7 | public Node left, right; 8 | } 9 | */ 10 | 11 | void decode(String str, Node root) { 12 | Node n = root; 13 | for (int i = 0; i < str.length(); i++) { 14 | n = (str.charAt(i) == '0') ? n.left : n.right; 15 | if (n.left == null && n.right == null) { 16 | System.out.print(n.data); 17 | n = root; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Java/Data Structures/Java 1D Array/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.*; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int n = scan.nextInt(); 9 | int [] a = new int[n]; 10 | for (int i = 0 ; i < n; i++) { 11 | a[i] = scan.nextInt(); 12 | } 13 | scan.close(); 14 | 15 | // Prints each sequential element in array a 16 | for (int i = 0; i < a.length; i++) { 17 | System.out.println(a[i]); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Java/Introduction/Java Output Formatting/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | System.out.println("================================"); 9 | for (int i = 0; i < 3; i++) { 10 | String s1 = scan.next(); 11 | int x = scan.nextInt(); 12 | System.out.format("%-15s%03d%n", s1, x); 13 | } 14 | scan.close(); 15 | System.out.println("================================"); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /30 Days of Code/Day 09 - Recursion/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int n = scan.nextInt(); 9 | scan.close(); 10 | System.out.println(factorial(n)); 11 | } 12 | 13 | private static Long factorial (int n) { 14 | if (n < 0) { 15 | return null; 16 | } 17 | long result = 1; 18 | while (n > 0) { 19 | result *= n--; 20 | } 21 | return result; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Java/Strings/Java String Reverse/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | /* If a String is equivalent to itself when reversed, it's a palindrome */ 6 | public class Solution { 7 | public static void main(String[] args) { 8 | /* Read input */ 9 | Scanner scan = new Scanner(System.in); 10 | String str = scan.nextLine(); 11 | scan.close(); 12 | 13 | /* Reverse string and compare to original */ 14 | String reversed = new StringBuilder(str).reverse().toString(); 15 | System.out.println(str.equals(reversed) ? "Yes" : "No"); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Solve Me First/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | /* Save input */ 8 | Scanner scan = new Scanner(System.in); 9 | int a = scan.nextInt(); 10 | int b = scan.nextInt(); 11 | scan.close(); 12 | 13 | /* Calculate sum */ 14 | int sum = solveMeFirst(a, b); 15 | 16 | /* Print output */ 17 | System.out.println(sum); 18 | } 19 | 20 | static int solveMeFirst(int a, int b) { 21 | return a + b; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Data Structures/Linked Lists/Insert a Node at the Tail of a Linked List/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* 4 | Insert Node at the end of a linked list 5 | 6 | Node is defined as 7 | class Node { 8 | int data; 9 | Node next; 10 | } 11 | */ 12 | 13 | Node Insert(Node head, int data) { 14 | Node n = new Node(); 15 | n.data = data; 16 | n.next = null; 17 | 18 | if (head == null) { 19 | return n; 20 | } else { 21 | Node curr = head; 22 | while (curr.next != null) { 23 | curr = curr.next; 24 | } 25 | curr.next = n; 26 | return head; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms/Sorting/Counting Sort 1/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | final int maxValue = 100; 8 | Scanner scan = new Scanner(System.in); 9 | int n = scan.nextInt(); 10 | int[] array = new int[maxValue]; 11 | 12 | for (int i = 0; i < n; i++) { 13 | int num = scan.nextInt(); 14 | array[num]++; 15 | } 16 | scan.close(); 17 | 18 | for (int i = 0; i < n; i++) { 19 | System.out.print(array[i] + " "); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Data Structures/Arrays/Arrays - DS/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | /* Save input */ 8 | Scanner scan = new Scanner(System.in); 9 | int size = scan.nextInt(); 10 | int [] array = new int[size]; 11 | for (int i = 0; i < size; i++) { 12 | array[i] = scan.nextInt(); 13 | } 14 | scan.close(); 15 | 16 | /* Print elements in reverse order */ 17 | for (int i = size - 1; i >= 0; i--) { 18 | System.out.print(array[i] + " "); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /30 Days of Code/Day 07 - Arrays/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | /* Read and save input */ 8 | Scanner scan = new Scanner(System.in); 9 | int size = scan.nextInt(); 10 | int [] array = new int[size]; 11 | for (int i = 0; i < size; i++) { 12 | array[i] = scan.nextInt(); 13 | } 14 | scan.close(); 15 | 16 | /* Print elements in reverse order */ 17 | for (int i = size - 1; i >= 0; i--) { 18 | System.out.print(array[i] + " "); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /30 Days of Code/Day 27 - Testing/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | public class Solution { 4 | public static void main(String[] args) { 5 | System.out.println(5); 6 | 7 | System.out.println("4 3"); 8 | System.out.println("-1 0 1 2"); 9 | 10 | System.out.println("3 1"); 11 | System.out.println("-1 0 1"); 12 | 13 | System.out.println("5 4"); 14 | System.out.println("-1 0 1 2 3"); 15 | 16 | System.out.println("6 1"); 17 | System.out.println("-1 0 1 2 3 4"); 18 | 19 | System.out.println("7 6"); 20 | System.out.println("-1 0 1 2 3 4 5"); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Algorithms/Strings/CamelCase/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | String str = scan.next(); 9 | scan.close(); 10 | System.out.println(numWords(str)); 11 | } 12 | 13 | private static int numWords(String str) { 14 | int count = 1; 15 | for (int i = 0; i < str.length(); i++) { 16 | char ch = str.charAt(i); 17 | if (ch >= 'A' && ch <= 'Z') { 18 | count++; 19 | } 20 | } 21 | return count; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Sherlock and Squares/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | /* Count # of integers (inclusive) between the square roots of A and B */ 6 | public class Solution { 7 | public static void main(String[] args) { 8 | Scanner scan = new Scanner(System.in); 9 | int T = scan.nextInt(); 10 | while (T-- > 0) { 11 | int A = scan.nextInt(); 12 | int B = scan.nextInt(); 13 | int numSquares = (int) (Math.floor(Math.sqrt(B)) - Math.ceil(Math.sqrt(A)) + 1); 14 | System.out.println(numSquares); 15 | } 16 | scan.close(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Java/Introduction/Java Loops II/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | class Solution{ 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int t = scan.nextInt(); 9 | for (int i = 0; i < t; i++) { 10 | int a = scan.nextInt(); 11 | int b = scan.nextInt(); 12 | int n = scan.nextInt(); 13 | for (int j = 0; j < n; j++) { 14 | a += b * (int) Math.pow(2, j); 15 | System.out.print(a + " "); 16 | } 17 | System.out.println(); 18 | } 19 | scan.close(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Extra Long Factorials/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.math.BigInteger; 5 | 6 | public class Solution { 7 | public static void main(String[] args) { 8 | Scanner scan = new Scanner(System.in); 9 | int n = scan.nextInt(); 10 | scan.close(); 11 | System.out.println(factorial(n)); 12 | } 13 | 14 | private static BigInteger factorial(int n) { 15 | BigInteger result = BigInteger.ONE; 16 | while (n > 1) { 17 | result = result.multiply(BigInteger.valueOf(n)); 18 | n--; 19 | } 20 | return result; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Java/Introduction/Java Stdin and Stdout II/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | /* Read input */ 8 | Scanner scan = new Scanner(System.in); 9 | int i = scan.nextInt(); 10 | double d = scan.nextDouble(); 11 | scan.nextLine(); // gets rid of the pesky newline 12 | String s = scan.nextLine(); 13 | scan.close(); 14 | 15 | /* Print output */ 16 | System.out.println("String: " + s); 17 | System.out.println("Double: " + d); 18 | System.out.println("Int: " + i); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /10 Days of Statistics/Day 6 - The Central Limit Theorem III/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | public class Solution { 4 | public static void main(String[] args) { 5 | /* Provided variables */ 6 | double mean = 500; 7 | double std = 80; 8 | int n = 100; 9 | double zScore = 1.96; // equivalent to 95% confidence interval 10 | 11 | /* Formula (found online) for confidence interval +/- */ 12 | double marginOfError = zScore * std / Math.sqrt(n); 13 | 14 | /* Print output */ 15 | System.out.format("%.2f%n", mean - marginOfError); 16 | System.out.format("%.2f%n", mean + marginOfError); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Java/Exception Handling/Java Exception Handling (Try-catch)/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.InputMismatchException; 5 | 6 | public class Solution { 7 | public static void main(String[] args) { 8 | Scanner scan = new Scanner(System.in); 9 | try { 10 | int x = scan.nextInt(); 11 | int y = scan.nextInt(); 12 | System.out.println(x/y); 13 | } catch (InputMismatchException e) { 14 | System.out.println(e.getClass().getName()); 15 | } catch (ArithmeticException e) { 16 | System.out.println(e.getClass().getName() + ": / by zero"); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Algorithms/Strings/Mars Exploration/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | String str = scan.next(); 9 | scan.close(); 10 | System.out.println(alteredLetters(str)); 11 | } 12 | 13 | private static int alteredLetters(String message) { 14 | String sos = "SOS"; 15 | int count = 0; 16 | for (int i = 0; i < message.length(); i++) { 17 | if (message.charAt(i) != sos.charAt(i % 3)) { 18 | count++; 19 | } 20 | } 21 | return count; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /10 Days of Statistics/Day 2 - Compound Event Probability/Solution.txt: -------------------------------------------------------------------------------- 1 | github.com/RodneyShag 2 | 3 | 4 | Answer: 17/42 5 | 6 | Urn X has a 4/7 probability of giving a red ball 7 | Urn Y has a 5/9 probability of giving a red ball 8 | Urn Z has a 1/2 probability of giving a red ball 9 | 10 | Urn X has a 3/7 probability of giving a black ball 11 | Urn Y has a 4/9 probability of giving a black ball 12 | Urn Z has a 1/2 probability of giving a black ball 13 | 14 | P(2 red, 1 black) = P(Red Red Black) + P(Red Black Red) + P(Black Red Red) 15 | = (4/7)(5/9)(1/2) + (4/7)(4/9)(1/2) + (3/7)(5/9)(1/2) 16 | = 20/126 + 16/126 + 15/126 17 | = 51/126 18 | = 17/42 19 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/Data Structures/Trees - Is This a Binary Search Tree/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* 4 | 5 | The Node class is defined as follows: 6 | class Node { 7 | int data; 8 | Node left; 9 | Node right; 10 | } 11 | */ 12 | 13 | boolean checkBST(Node root) { 14 | return checkBST(root, 0, 10000); // range of values in problem 15 | } 16 | 17 | boolean checkBST(Node node, int min, int max) { 18 | if (node == null) { 19 | return true; 20 | } else if (node.data < min || node.data > max) { 21 | return false; 22 | } 23 | return checkBST(node.left, min, node.data - 1) && checkBST(node.right, node.data + 1, max); 24 | } 25 | -------------------------------------------------------------------------------- /Data Structures/Trees/Is This a Binary Search Tree/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* 4 | The Node class is defined as follows: 5 | class Node { 6 | int data; 7 | Node left; 8 | Node right; 9 | } 10 | */ 11 | 12 | boolean checkBST(Node root) { 13 | return checkBST(root, 0, 10000); 14 | } 15 | 16 | boolean checkBST(Node node, int min, int max) { 17 | if (node == null) { 18 | return true; 19 | } else if (node.data < min || node.data > max) { // we assume BST cannot have duplicate values 20 | return false; 21 | } else { 22 | return checkBST(node.left, min, node.data - 1) && checkBST(node.right, node.data + 1, max); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Data Structures/Linked Lists/Compare two linked lists/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* 4 | Compare two linked lists A and B 5 | Return 1 if they are identical and 0 if they are not. 6 | Node is defined as 7 | class Node { 8 | int data; 9 | Node next; 10 | } 11 | */ 12 | 13 | // Runtime: O(n) 14 | // Space Complexity: O(1) 15 | int CompareLists(Node n1, Node n2) { 16 | if (n1 == null && n2 == null) { 17 | return 1; 18 | } 19 | while (n1 != null && n2 != null) { 20 | if (n1.data != n2.data) { 21 | return 0; 22 | } 23 | n1 = n1.next; 24 | n2 = n2.next; 25 | } 26 | return (n1 == null && n2 == null) ? 1 : 0; 27 | } 28 | -------------------------------------------------------------------------------- /Implementation/Brute Force/Pangrams/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.HashSet; 5 | 6 | public class Solution { 7 | public static void main(String[] args) { 8 | Scanner scan = new Scanner(System.in); 9 | String str = scan.nextLine().toLowerCase(); 10 | scan.close(); 11 | 12 | HashSet set = new HashSet(); 13 | for (int i = 0; i < str.length(); i++) { 14 | char ch = str.charAt(i); 15 | if (Character.isLetter(ch)) { 16 | set.add(ch); 17 | } 18 | } 19 | 20 | System.out.println(set.size() == 26 ? "pangram" : "not pangram"); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Java/Advanced/Java Reflection - Attributes/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | public class Solution { 4 | public static void main(String[] args) { 5 | Class student = Student.class; // uses class literal, not a function. 6 | Method[] methods = student.getDeclaredMethods(); 7 | 8 | /* Get names from Methods */ 9 | ArrayList methodNames = new ArrayList(); 10 | for (Method method : methods) { 11 | methodNames.add(method.getName()); 12 | } 13 | 14 | /* Sort and print names */ 15 | Collections.sort(methodNames); 16 | for (String name: methodNames) { 17 | System.out.println(name); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Algorithms/Strings/Gemstones/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | static int gemstones(String[] array) { 4 | final int NUM_ELEMENTS = 26; 5 | BitSet bitset = new BitSet(NUM_ELEMENTS); 6 | bitset.set(0, NUM_ELEMENTS); 7 | 8 | /* Create a BitSet for each rock. "AND" it with our original BitSet */ 9 | for (String rock : array) { 10 | BitSet currBitSet = new BitSet(NUM_ELEMENTS); 11 | for (int i = 0; i < rock.length(); i++) { 12 | currBitSet.set(rock.charAt(i) - 'a'); 13 | } 14 | bitset.and(currBitSet); 15 | } 16 | 17 | return bitset.cardinality(); 18 | } 19 | 20 | // Discuss on HackerRank: https://www.hackerrank.com/challenges/gem-stones/forum/comments/284428 21 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Staircase/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | /* Save input */ 8 | Scanner scan = new Scanner(System.in); 9 | int n = scan.nextInt(); 10 | scan.close(); 11 | 12 | /* Print staircase */ 13 | for (int spaces = n - 1; spaces >= 0; spaces--) { 14 | for (int i = 0; i < spaces; i++) { 15 | System.out.print(" "); 16 | } 17 | for (int i = spaces; i < n; i++) { 18 | System.out.print("#"); 19 | } 20 | System.out.println(); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /Java/Object Oriented Programming/Java Inheritance I/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | import java.text.*; 6 | import java.math.*; 7 | import java.util.regex.*; 8 | 9 | class Animal { 10 | void walk() { 11 | System.out.println("I am walking"); 12 | } 13 | } 14 | 15 | class Bird extends Animal { 16 | void fly() { 17 | System.out.println("I am flying"); 18 | } 19 | void sing() { 20 | System.out.println("I am singing"); 21 | } 22 | } 23 | 24 | public class Solution { 25 | public static void main(String args[]) { 26 | Bird bird = new Bird(); 27 | bird.walk(); 28 | bird.fly(); 29 | bird.sing(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Algorithms/Sorting/Counting Sort 2/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | static int[] countingSort(int[] givenArray) { 4 | /* Save into buckets */ 5 | final int maxValue = 100; 6 | int[] bucket = new int[maxValue]; 7 | for (int value : givenArray) { 8 | bucket[value]++; 9 | } 10 | 11 | /* Create sorted array */ 12 | int[] sortedArray = new int[givenArray.length]; 13 | int position = 0; 14 | for (int i = 0; i < bucket.length; i++) { 15 | for (int j = 0 ; j < bucket[i]; j++) { 16 | sortedArray[position++] = i; 17 | } 18 | } 19 | return sortedArray; 20 | } 21 | 22 | // Discuss on HackerRank: https://www.hackerrank.com/challenges/countingsort2/forum/comments/272970 23 | -------------------------------------------------------------------------------- /Data Structures/Linked Lists/Delete a Node/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* 4 | Delete Node at a given position in a linked list 5 | 6 | Node is defined as 7 | class Node { 8 | int data; 9 | Node next; 10 | } 11 | */ 12 | 13 | Node Delete(Node head, int position) { 14 | if (head == null) { 15 | return null; 16 | } else if (position == 0) { 17 | return head.next; 18 | } else { 19 | /* Get Node one element before desired position */ 20 | Node n = head; 21 | for (int i = 0; i < position - 1; i++) { 22 | n = n.next; 23 | } 24 | /* Delete Node */ 25 | n.next = n.next.next; 26 | 27 | return head; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Angry Professor/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int T = scan.nextInt(); 9 | while (T-- > 0) { 10 | int onTimeStudents = 0; 11 | int N = scan.nextInt(); 12 | int K = scan.nextInt(); 13 | for (int i = 0; i < N; i++) { 14 | if (scan.nextInt() <= 0) { 15 | onTimeStudents++; 16 | } 17 | } 18 | System.out.println(onTimeStudents < K ? "YES" : "NO"); 19 | } 20 | scan.close(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Mini-Max Sum/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | // Runtime: O(n) 6 | // Space Complexity: O(1) 7 | public class Solution { 8 | public static void main(String[] args) { 9 | Scanner scan = new Scanner(System.in); 10 | long sum = 0; 11 | long min = Integer.MAX_VALUE; 12 | long max = Integer.MIN_VALUE; 13 | for (int i = 0; i < 5; i++) { 14 | long num = scan.nextLong(); 15 | sum += num; 16 | min = Math.min(min, num); 17 | max = Math.max(max, num); 18 | } 19 | scan.close(); 20 | System.out.print((sum - max) + " " + (sum - min)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Algorithms/Strings/Caesar Cipher/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | static String caesarCipher(String str, int k) { 4 | StringBuilder sb = new StringBuilder(); 5 | for (int i = 0; i < str.length(); i++) { 6 | char ch = str.charAt(i); 7 | sb.append(encrypt(ch, k)); 8 | } 9 | return sb.toString(); 10 | } 11 | 12 | /* Encrypts a character using Caesar Cipher */ 13 | private static char encrypt(char ch, int K) { 14 | if (!Character.isLetter(ch)) { 15 | return ch; 16 | } 17 | char base = Character.isLowerCase(ch) ? 'a' : 'A'; 18 | return (char) ((ch - base + K) % 26 + base); 19 | } 20 | 21 | // Discuss on HackerRank: https://www.hackerrank.com/challenges/caesar-cipher-1/forum/comments/269393 22 | -------------------------------------------------------------------------------- /Data Structures/Trees/Tree - Level Order Traversal/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* 4 | class Node { 5 | int data; 6 | Node left; 7 | Node right; 8 | } 9 | */ 10 | 11 | // Time Complexity: O(n) 12 | // Space Complexity: O(n) 13 | 14 | void LevelOrder(Node root) { 15 | ArrayDeque deque = new ArrayDeque(); // use deque as a queue 16 | if (root != null) { 17 | deque.add(root); 18 | } 19 | while (!deque.isEmpty()) { 20 | Node n = deque.remove(); 21 | System.out.print(n.data + " "); 22 | if (n.left != null) { 23 | deque.add(n.left); 24 | } 25 | if (n.right != null) { 26 | deque.add(n.right); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Java/Introduction/Java If-Else/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | /* Read input */ 8 | Scanner scan = new Scanner(System.in); 9 | int n = scan.nextInt(); 10 | scan.close(); 11 | 12 | /* Determine answer */ 13 | String ans = ""; 14 | if (n % 2 == 1) { 15 | ans = "Weird"; 16 | } else { 17 | if (n >= 6 && n <= 20) { 18 | ans = "Weird"; 19 | } else { 20 | ans = "Not Weird"; 21 | } 22 | } 23 | 24 | /* Print output */ 25 | System.out.println(ans); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/Techniques, Concepts/Recursion - Fibonacci Numbers/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | // Time Complexity: O(n) 6 | // Space Complexity: O(1) 7 | public class Solution { 8 | public static void main(String[] args) { 9 | Scanner scan = new Scanner(System.in); 10 | int n = scan.nextInt(); 11 | scan.close(); 12 | System.out.println(fibonacci(n)); 13 | } 14 | 15 | private static int fibonacci(int n) { 16 | int prev = 0; 17 | int curr = 1; 18 | for (int i = 2; i <= n; i++) { 19 | int next = prev + curr; 20 | prev = curr; 21 | curr = next; 22 | } 23 | return curr; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Grading Students/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int n = scan.nextInt(); 9 | while (n-- > 0) { 10 | int grade = scan.nextInt(); 11 | System.out.println(roundGrade(grade)); 12 | } 13 | scan.close(); 14 | } 15 | 16 | private static int roundGrade(int grade) { 17 | if (grade >= 38) { 18 | int gradeMod5 = grade % 5; 19 | if (gradeMod5 > 2) { 20 | grade += 5 - gradeMod5; 21 | } 22 | } 23 | return grade; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/The Hurdle Race/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.Arrays; 5 | 6 | public class Solution { 7 | public static void main(String[] args) { 8 | /* Save input */ 9 | Scanner scan = new Scanner(System.in); 10 | int n = scan.nextInt(); 11 | int k = scan.nextInt(); 12 | int [] height = new int[n]; 13 | for (int i = 0; i < n; i++) { 14 | height[i] = scan.nextInt(); 15 | } 16 | scan.close(); 17 | 18 | /* Calculate # of magic beverages needed */ 19 | int maxHeight = Arrays.stream(height).max().getAsInt(); 20 | System.out.println(Math.max(maxHeight - k, 0)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Data Structures/Trees/Binary Search Tree - Lowest Common Ancestor/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* Node is defined as : 4 | class Node { 5 | int data; 6 | Node left; 7 | Node right; 8 | } 9 | */ 10 | 11 | // Assumes tree has unique values. 12 | // This problem is simpler since we're given a binary SEARCH tree. 13 | 14 | // Time Complexity: O(log n) on a balanced tree 15 | // Space Complexity: O(1) 16 | static Node lca(Node n, int v1, int v2) { 17 | while (n != null) { 18 | if (n.data > v1 && n.data > v2) { 19 | n = n.left; 20 | } else if (n.data < v1 && n.data < v2) { 21 | n = n.right; 22 | } else { 23 | break; 24 | } 25 | } 26 | return n; 27 | } 28 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Compare the Triplets/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int a0 = scan.nextInt(); 9 | int a1 = scan.nextInt(); 10 | int a2 = scan.nextInt(); 11 | int b0 = scan.nextInt(); 12 | int b1 = scan.nextInt(); 13 | int b2 = scan.nextInt(); 14 | scan.close(); 15 | 16 | int aPoints = (a0 > b0 ? 1 : 0) + (a1 > b1 ? 1 : 0) + (a2 > b2 ? 1 : 0); 17 | int bPoints = (a0 < b0 ? 1 : 0) + (a1 < b1 ? 1 : 0) + (a2 < b2 ? 1 : 0); 18 | 19 | System.out.println(aPoints + " " + bPoints); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /30 Days of Code/Day 10 - Binary Numbers/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int n = scan.nextInt(); 9 | scan.close(); 10 | System.out.println(consecutiveOnes(n)); 11 | } 12 | 13 | public static int consecutiveOnes(int n) { 14 | int count = 0; 15 | int max = 0; 16 | while (n > 0) { 17 | if (n % 2 == 1) { 18 | count++; 19 | max = Math.max(max, count); 20 | } else { 21 | count = 0; 22 | } 23 | n = n >> 1; 24 | } 25 | return max; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Java/Strings/Java Regex/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.regex.Matcher; 4 | import java.util.regex.Pattern; 5 | import java.util.Scanner; 6 | 7 | class Solution { 8 | public static void main(String []args) { 9 | Scanner in = new Scanner(System.in); 10 | while(in.hasNext()) { 11 | String IP = in.next(); 12 | System.out.println(IP.matches(new MyRegex().pattern)); 13 | } 14 | } 15 | } 16 | 17 | /* 18 | [01]?\\d{1,2} matches numbers 0-199. 19 | 2[0-4]\\d matches numbers 200-249 20 | 25[0-5] matches numbers 250-255 21 | */ 22 | class MyRegex { 23 | String num = "([01]?\\d{1,2}|2[0-4]\\d|25[0-5])"; 24 | String pattern = num + "." + num + "." + num + "." + num; 25 | } 26 | -------------------------------------------------------------------------------- /30 Days of Code/Day 03 - Intro to Conditional Statements/Solution.java: -------------------------------------------------------------------------------- 1 | 2 | // github.com/RodneyShag 3 | 4 | import java.util.Scanner; 5 | 6 | public class Solution { 7 | public static void main(String[] args) { 8 | /* Read input */ 9 | Scanner scan = new Scanner(System.in); 10 | int n = scan.nextInt(); 11 | scan.close(); 12 | 13 | /* Determine answer */ 14 | String ans = ""; 15 | if (n % 2 == 1) { 16 | ans = "Weird"; 17 | } else { 18 | if (n >= 6 && n <= 20) { 19 | ans = "Weird"; 20 | } else { 21 | ans = "Not Weird"; 22 | } 23 | } 24 | 25 | /* Print output */ 26 | System.out.println(ans); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Taum and B'day/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int T = scan.nextInt(); 9 | while (T-- > 0) { 10 | long B = scan.nextLong(); 11 | long W = scan.nextLong(); 12 | long X = scan.nextLong(); 13 | long Y = scan.nextLong(); 14 | long Z = scan.nextLong(); 15 | long priceB = Math.min(X, Y + Z); // conversion price 16 | long priceW = Math.min(Y, X + Z); // conversion price 17 | System.out.println(B * priceB + W * priceW); 18 | } 19 | scan.close(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Java/Object Oriented Programming/Java Method Overriding 2 (Super Keyword)/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.*; 4 | import java.io.*; 5 | 6 | class BiCycle { 7 | String define_me() { 8 | return "a vehicle with pedals."; 9 | } 10 | } 11 | 12 | class MotorCycle extends BiCycle { 13 | String define_me() { 14 | return "a cycle with an engine."; 15 | } 16 | 17 | MotorCycle() { 18 | System.out.println("Hello I am a motorcycle, I am " + define_me()); 19 | String temp = super.define_me(); 20 | System.out.println("My ancestor is a cycle who is " + temp); 21 | } 22 | } 23 | 24 | class Solution { 25 | public static void main(String[] args) { 26 | MotorCycle M = new MotorCycle(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Equalize the Array/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.Arrays; 5 | 6 | // Time Complexity: O(a + n) 7 | // Space Complexity: O(a) 8 | public class Solution { 9 | 10 | private static final int size = 100; 11 | 12 | public static void main(String[] args) { 13 | Scanner scan = new Scanner(System.in); 14 | int n = scan.nextInt(); 15 | int [] counts = new int[size + 1]; // could alternatively use a HashMap 16 | for (int i = 0; i < n; i++) { 17 | counts[scan.nextInt()]++; 18 | } 19 | scan.close(); 20 | int maxRepetitions = Arrays.stream(counts).max().getAsInt(); 21 | System.out.println(n - maxRepetitions); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Algorithms/Strings/Beautiful Binary String/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | // Idea: - For each 010, we can flip it to 011, and count that as one "step". 6 | // - An easy way to count the number of steps is to change each 010 to 01 instead, 7 | // and to compare the length of the resulting string with the original string 8 | 9 | public class Solution { 10 | static int minSteps(String B) { 11 | return B.length() - B.replace("010","01").length(); 12 | } 13 | 14 | public static void main(String[] args) { 15 | Scanner scan = new Scanner(System.in); 16 | scan.nextInt(); // we don't need "n" 17 | String B = scan.next(); 18 | scan.close(); 19 | 20 | System.out.println(minSteps(B)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Data Structures/Linked Lists/Reverse a linked list/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | // Iterative Solution using 3 pointers 4 | // Time Complexity: O(n) 5 | // Space Complexity: O(1) 6 | 7 | /* 8 | * For your reference: 9 | * 10 | * SinglyLinkedListNode { 11 | * int data; 12 | * SinglyLinkedListNode next; 13 | * } 14 | * 15 | */ 16 | 17 | static SinglyLinkedListNode reverse(SinglyLinkedListNode head) { 18 | if (head == null || head.next == null) { 19 | return head; 20 | } 21 | SinglyLinkedListNode prev = null; 22 | SinglyLinkedListNode curr = head; 23 | SinglyLinkedListNode next = null; 24 | while (curr != null) { 25 | next = curr.next; 26 | curr.next = prev; // changes arrow direction 27 | prev = curr; 28 | curr = next; 29 | } 30 | return prev; 31 | } 32 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Cut the sticks/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.Arrays; 5 | 6 | public class Solution { 7 | public static void main(String[] args) { 8 | /* Save Input */ 9 | Scanner scan = new Scanner(System.in); 10 | int numSticks = scan.nextInt(); 11 | int [] array = new int[numSticks]; 12 | for (int i = 0; i < numSticks; i++) { 13 | array[i] = scan.nextInt(); 14 | } 15 | scan.close(); 16 | 17 | Arrays.sort(array); 18 | 19 | System.out.println(array.length); 20 | for (int i = 1; i < array.length; i++) { 21 | if (array[i] != array[i-1]) { 22 | System.out.println(array.length - i); 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Java/Advanced/Java MD5/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.security.MessageDigest; 5 | import java.security.NoSuchAlgorithmException; 6 | 7 | public class Solution { 8 | public static void main(String[] args) throws NoSuchAlgorithmException { 9 | /* Read and save the input String */ 10 | Scanner scan = new Scanner(System.in); 11 | String str = scan.next(); 12 | scan.close(); 13 | 14 | /* Encode the String using MD5 */ 15 | MessageDigest md = MessageDigest.getInstance("MD5"); 16 | md.update(str.getBytes()); 17 | byte[] digest = md.digest(); 18 | 19 | /* Print the encoded value in hexadecimal */ 20 | for (byte b : digest) { 21 | System.out.format("%02x", b); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Data Structures/Linked Lists/Cycle Detection/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* 4 | Detect a cycle in a linked list. Note that the head pointer may be 'null' if the list is empty. 5 | 6 | A Node is defined as: 7 | class Node { 8 | int data; 9 | Node next; 10 | } 11 | */ 12 | 13 | /* If "slow" and "fast" collide, we must have a cycle */ 14 | boolean hasCycle(Node head) { 15 | if (head == null) 16 | return false; 17 | 18 | Node slow = head; // moves 1 Node at a time 19 | Node fast = head; // moves 2 Nodes at a time 20 | 21 | while (fast != null && fast.next != null) { 22 | slow = slow.next; 23 | fast = fast.next.next; 24 | if (slow == fast) { 25 | return true; // since "slow" and "fast" collided 26 | } 27 | } 28 | return false; 29 | } 30 | -------------------------------------------------------------------------------- /Java/Advanced/Java SHA-256/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.security.MessageDigest; 5 | import java.security.NoSuchAlgorithmException; 6 | 7 | public class Solution { 8 | public static void main(String[] args) throws NoSuchAlgorithmException { 9 | /* Read and save the input String */ 10 | Scanner scan = new Scanner(System.in); 11 | String str = scan.next(); 12 | scan.close(); 13 | 14 | /* Encode the String using SHA-256 */ 15 | MessageDigest md = MessageDigest.getInstance("SHA-256"); 16 | md.update(str.getBytes()); 17 | byte[] digest = md.digest(); 18 | 19 | /* Print the encoded value in hexadecimal */ 20 | for (byte b : digest) { 21 | System.out.format("%02x", b); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Java/Data Structures/Java 1D Array (Part 2)/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | public static boolean canWin(int leap, int[] game) { 4 | if (game == null) { 5 | return false; 6 | } 7 | return isSolvable(leap, game, 0); 8 | } 9 | 10 | private static boolean isSolvable(int leap, int[] game, int i) { 11 | // Base Cases 12 | if (i >= game.length) { 13 | return true; 14 | } else if (i < 0 || game[i] == 1) { 15 | return false; 16 | } 17 | 18 | game[i] = 1; // marks as visited 19 | 20 | // Recursive Cases (Tries +m first to try to finish game quickly) 21 | return isSolvable(leap, game, i + leap) 22 | || isSolvable(leap, game, i + 1) 23 | || isSolvable(leap, game, i - 1); 24 | } 25 | 26 | // Discuss on HackerRank: https://www.hackerrank.com/challenges/java-1d-array/forum/comments/253767 27 | -------------------------------------------------------------------------------- /Java/Strings/Java Regex 3 - Username Checker/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | import java.text.*; 6 | import java.math.*; 7 | import java.util.regex.*; 8 | 9 | public class Solution { 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | int testCases = Integer.parseInt(in.nextLine()); 13 | while (testCases > 0) { 14 | String username = in.nextLine(); 15 | String pattern = "^[a-zA-Z]\\w{7,29}$"; 16 | 17 | Pattern r = Pattern.compile(pattern); 18 | Matcher m = r.matcher(username); 19 | 20 | if (m.find()) { 21 | System.out.println("Valid"); 22 | } else { 23 | System.out.println("Invalid"); 24 | } 25 | testCases--; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Windows image file caches 2 | Thumbs.db 3 | ehthumbs.db 4 | 5 | # Folder config file 6 | Desktop.ini 7 | 8 | # Recycle Bin used on file shares 9 | $RECYCLE.BIN/ 10 | 11 | # Windows Installer files 12 | *.cab 13 | *.msi 14 | *.msm 15 | *.msp 16 | 17 | # Windows shortcuts 18 | *.lnk 19 | 20 | # ========================= 21 | # Operating System Files 22 | # ========================= 23 | 24 | # OSX 25 | # ========================= 26 | 27 | .DS_Store 28 | .AppleDouble 29 | .LSOverride 30 | 31 | # Thumbnails 32 | ._* 33 | 34 | # Files that might appear in the root of a volume 35 | .DocumentRevisions-V100 36 | .fseventsd 37 | .Spotlight-V100 38 | .TemporaryItems 39 | .Trashes 40 | .VolumeIcon.icns 41 | 42 | # Directories potentially created on remote AFP share 43 | .AppleDB 44 | .AppleDesktop 45 | Network Trash Folder 46 | Temporary Items 47 | .apdisk 48 | -------------------------------------------------------------------------------- /Algorithms/Sorting/Counting Sort 3/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | final int maxValue = 100; 8 | Scanner scan = new Scanner(System.in); 9 | int n = scan.nextInt(); 10 | int[] array = new int[maxValue]; 11 | 12 | /* Save into buckets */ 13 | for (int i = 0; i < n; i++) { 14 | int num = scan.nextInt(); 15 | scan.next(); // don't need the String 16 | array[num]++; 17 | } 18 | scan.close(); 19 | 20 | /* Print "L" for each bucket */ 21 | int count = 0; 22 | for (int i = 0; i < array.length; i++) { 23 | count += array[i]; 24 | System.out.print(count + " "); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms/Strings/String Construction/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | // Idea: 6 | // - Once a letter is in "p", we no longer have to copy it from "s" to "p". We can 7 | // use Rule #2 to append it to "p" at no charge 8 | // - To get our final answer, we count the number of distinct characters in "s" 9 | 10 | public class Solution { 11 | static long stringConstruction(String s) { 12 | return s.chars().distinct().count(); 13 | } 14 | 15 | public static void main(String[] args) { 16 | Scanner scan = new Scanner(System.in); 17 | int q = scan.nextInt(); 18 | while (q-- > 0) { 19 | String s = scan.next(); 20 | long result = stringConstruction(s); 21 | System.out.println(result); 22 | } 23 | scan.close(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /30 Days of Code/Day 00 - Hello, World/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | public class Solution { 4 | public static void main(String[] args) { 5 | // Create a Scanner object to read input from stdin. 6 | Scanner scan = new Scanner(System.in); 7 | 8 | // Read a full line of input from stdin and save it to our variable, inputString. 9 | String inputString = scan.nextLine(); 10 | 11 | // Close the scanner object, because we've finished reading 12 | // all of the input from stdin needed for this challenge. 13 | scan.close(); 14 | 15 | // Print a string literal saying "Hello, World." to stdout. 16 | System.out.println("Hello, World."); 17 | 18 | // Prints the contents of inputString to stdout. 19 | System.out.println(inputString); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Jumping on the Clouds/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | /* Save input */ 8 | Scanner scan = new Scanner(System.in); 9 | int n = scan.nextInt(); 10 | int [] cloud = new int[n]; 11 | for (int i = 0; i < n; i++) { 12 | cloud[i] = scan.nextInt(); 13 | } 14 | scan.close(); 15 | 16 | /* Jump on clouds */ 17 | int jumps = 0; 18 | int i = 0; 19 | while (i < n - 1) { 20 | if (i + 2 < n && cloud[i + 2] == 0) { 21 | i += 2; 22 | } else { 23 | i++; 24 | } 25 | jumps++; 26 | } 27 | System.out.println(jumps); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Algorithms/Strings/Alternating Characters/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | // Each time we have 2 consecutive characters that are the same, we can delete 1 of them 6 | 7 | public class Solution { 8 | public static void main(String[] args) { 9 | Scanner scan = new Scanner(System.in); 10 | int T = scan.nextInt(); 11 | while (T-- > 0) { 12 | String str = scan.next(); 13 | System.out.println(minimumDeletions(str)); 14 | } 15 | scan.close(); 16 | } 17 | 18 | private static int minimumDeletions(String str) { 19 | int deletions = 0; 20 | for (int i = 1; i < str.length(); i++) { 21 | if (str.charAt(i) == str.charAt(i-1)) { 22 | deletions++; 23 | } 24 | } 25 | return deletions; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Java/Data Structures/Java Hashset/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | import java.text.*; 6 | import java.math.*; 7 | import java.util.regex.*; 8 | 9 | public class Solution { 10 | public static void main(String[] args) { 11 | Scanner s = new Scanner(System.in); 12 | int t = s.nextInt(); 13 | String [] pair_left = new String[t]; 14 | String [] pair_right = new String[t]; 15 | 16 | for (int i = 0; i < t; i++) { 17 | pair_left[i] = s.next(); 18 | pair_right[i] = s.next(); 19 | } 20 | s.close(); 21 | 22 | HashSet set = new HashSet(t); 23 | for (int i = 0; i < t; i++) { 24 | set.add(pair_left[i] + " " + pair_right[i]); 25 | System.out.println(set.size()); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Beautiful Days at the Movies/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int i = scan.nextInt(); 9 | int j = scan.nextInt(); 10 | int k = scan.nextInt(); 11 | scan.close(); 12 | 13 | int count = 0; 14 | for (int num = i; num <= j; num++) { 15 | if (Math.abs(num - reverse(num)) % k == 0) { 16 | count++; 17 | } 18 | } 19 | System.out.println(count); 20 | } 21 | 22 | private static int reverse(int num) { 23 | StringBuilder sb = new StringBuilder(); 24 | sb.append(num); 25 | sb.reverse(); 26 | return Integer.parseInt(sb.toString()); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Repeated String/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | static long repeatedString(String str, long n) { 4 | /* Found out # of times 'a' appears in our String */ 5 | int wordAs = 0; 6 | for (int i = 0; i < str.length(); i++) { 7 | if (str.charAt(i) == 'a') { 8 | wordAs++; 9 | } 10 | } 11 | 12 | long completeWords = n / str.length(); 13 | long remainingLetters = n % str.length(); 14 | long totalAs = completeWords * wordAs; 15 | 16 | /* Count up the remaining 'a' characters */ 17 | for (int i = 0; i < remainingLetters; i++) { 18 | if (str.charAt(i) == 'a') { 19 | totalAs++; 20 | } 21 | } 22 | 23 | return totalAs; 24 | } 25 | 26 | // Discuss on HackerRank: https://www.hackerrank.com/challenges/repeated-string/forum/comments/266320 27 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Sock Merchant/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.HashSet; 5 | 6 | public class Solution { 7 | public static void main(String[] args) { 8 | /* Read some input */ 9 | Scanner scan = new Scanner(System.in); 10 | int n = scan .nextInt(); 11 | 12 | /* Count pairs */ 13 | HashSet set = new HashSet(); 14 | int pairs = 0; 15 | for (int i = 0; i < n; i++) { 16 | int cost = scan.nextInt(); 17 | if (set.contains(cost)) { 18 | set.remove(cost); 19 | pairs++; 20 | } else { 21 | set.add(cost); 22 | } 23 | } 24 | 25 | /* Print output */ 26 | scan.close(); 27 | System.out.println(pairs); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Time Conversion/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | String str = scan.nextLine(); 9 | scan.close(); 10 | 11 | int hours = Integer.parseInt(str.substring(0,2)); 12 | int minutes = Integer.parseInt(str.substring(3,5)); 13 | int seconds = Integer.parseInt(str.substring(6,8)); 14 | 15 | /* Convert to 24-hour format */ 16 | if (str.substring(8, 10).equals("PM") && hours != 12) { 17 | hours += 12; 18 | } else if (str.substring(8, 10).equals("AM") && hours == 12) { 19 | hours = 0; 20 | } 21 | 22 | System.out.format("%02d:%02d:%02d", hours, minutes, seconds); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /30 Days of Code/Day 02 - Operators/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Arithmetic { 6 | public static void main(String[] args) { 7 | /* Read input */ 8 | Scanner scan = new Scanner(System.in); 9 | double mealCost = scan.nextDouble(); // original meal price 10 | int tipPercent = scan.nextInt(); // tip percentage 11 | int taxPercent = scan.nextInt(); // tax percentage 12 | scan.close(); 13 | 14 | /* Calculate total cost */ 15 | int totalCost = (int) Math.round(mealCost + 16 | mealCost * tipPercent / 100.0 + 17 | mealCost * taxPercent / 100.0); 18 | 19 | /* Print output */ 20 | System.out.println("The total meal cost is " + totalCost + " dollars."); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Jumping on the Clouds - Revisited/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | int E = 100; 8 | /* Save input */ 9 | Scanner scan = new Scanner(System.in); 10 | int n = scan.nextInt(); 11 | int k = scan.nextInt(); 12 | int [] cloud = new int[n]; 13 | for (int i = 0; i < n; i++) { 14 | cloud[i] = scan.nextInt(); 15 | } 16 | scan.close(); 17 | 18 | /* Jump on clouds */ 19 | int position = 0; 20 | do { 21 | position = (position + k) % n; 22 | if (cloud[position] == 1) { 23 | E -= 2; 24 | } 25 | E--; 26 | } while (position != 0); 27 | System.out.println(E); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Data Structures/Linked Lists/Get Node Value/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* 4 | Get Nth element from the end in a linked list of integers 5 | Number of elements in the list will always be greater than N. 6 | Node is defined as 7 | class Node { 8 | int data; 9 | Node next; 10 | } 11 | */ 12 | 13 | // Time Complexity: O(n) 14 | // Space Complexity: O(1) 15 | int getNode(SinglyLinkedListNode head, int positionFromTail) { 16 | SinglyLinkedListNode curr = head; 17 | SinglyLinkedListNode runner = head; 18 | 19 | /* Move runner into the list by k elements */ 20 | for (int i = 0; i < positionFromTail; i++) { 21 | runner = runner.next; 22 | } 23 | 24 | /* Move both pointers */ 25 | while (runner.next != null) { 26 | curr = curr.next; 27 | runner = runner.next; 28 | } 29 | 30 | return curr.data; 31 | } 32 | -------------------------------------------------------------------------------- /Java/Object Oriented Programming/Java Abstract Class/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.*; 4 | 5 | abstract class Book { 6 | String title; 7 | abstract void setTitle(String s); 8 | String getTitle() { 9 | return title; 10 | } 11 | } 12 | 13 | class MyBook extends Book { 14 | @Override 15 | void setTitle(String s) { 16 | title = s; 17 | } 18 | } 19 | 20 | public class Main { 21 | public static void main(String []args) { 22 | // Book new_novel=new Book(); This line prHMain.java:25: error: Book is abstract; cannot be instantiated 23 | Scanner sc = new Scanner(System.in); 24 | String title = sc.nextLine(); 25 | MyBook new_novel = new MyBook(); 26 | new_novel.setTitle(title); 27 | System.out.println("The title is: " + new_novel.getTitle()); 28 | sc.close(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Java/BigNumber/Java Primality Test/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.math.BigInteger; 5 | 6 | /* 7 | 8 | I use isProbablePrime() with certainty = 10 to achieve 99.9% accuracy. 9 | However, even certainty = 1 (which achieves 50% accuracy) is enough to 10 | pass the HackerRank test cases. 11 | 12 | isProbablePrime() is always 100% certain if it tells you if a number 13 | is "not prime". If it says "prime", it's only 99.9% certain. It may be 14 | the case that it just hasn't found a prime number number that divides 15 | the BigInteger yet. 16 | 17 | */ 18 | public class Solution { 19 | public static void main(String[] args) { 20 | Scanner scan = new Scanner(System.in); 21 | BigInteger n = scan.nextBigInteger(); 22 | scan.close(); 23 | System.out.println(n.isProbablePrime(10) ? "prime" : "not prime"); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /10 Days of Statistics/Day 5 - Poisson Distribution I/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | /* Save input */ 8 | Scanner scan = new Scanner(System.in); 9 | double lambda = scan.nextDouble(); 10 | int k = scan.nextInt(); 11 | scan.close(); 12 | 13 | System.out.println(poisson(k, lambda)); 14 | } 15 | 16 | private static double poisson(int k, double lambda) { 17 | return (Math.pow(lambda, k) * Math.pow(Math.E, -1 * lambda)) / factorial(k); 18 | } 19 | 20 | private static Long factorial(int n) { 21 | if (n < 0) { 22 | return null; 23 | } 24 | long result = 1; 25 | while (n > 0) { 26 | result *= n--; 27 | } 28 | return result; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Java/Strings/Pattern Syntax Checker/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.regex.Pattern; 5 | import java.util.regex.PatternSyntaxException; 6 | 7 | // If a PatternSyntaxException is not thrown by Pattern.compile, the regular expresion is valid 8 | public class Solution { 9 | public static void main(String[] args) { 10 | Scanner scan = new Scanner(System.in); 11 | int testCases = scan.nextInt(); 12 | scan.nextLine(); // gets rid of the pesky newline. 13 | while (testCases-- > 0) { 14 | String pattern = scan.nextLine(); 15 | try { 16 | Pattern.compile(pattern); 17 | System.out.println("Valid"); 18 | } catch (PatternSyntaxException exception) { 19 | System.out.println("Invalid"); 20 | } 21 | } 22 | scan.close(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Java/Object Oriented Programming/Java Inheritance II/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | import java.text.*; 6 | import java.math.*; 7 | import java.util.regex.*; 8 | 9 | class Arithmetic { 10 | int add (int a, int b) { 11 | return a + b; 12 | } 13 | } 14 | 15 | class Adder extends Arithmetic {} 16 | 17 | public class Solution { 18 | public static void main(String []args) { 19 | // Create a new Adder object 20 | Adder a = new Adder(); 21 | 22 | // Print the name of the superclass on a new line 23 | System.out.println("My superclass is: " + a.getClass().getSuperclass().getName()); 24 | 25 | // Print the result of 3 calls to Adder's `add(int,int)` method as 3 space-separated integers: 26 | System.out.print(a.add(10,32) + " " + a.add(10,3) + " " + a.add(10,10) + "\n"); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Cats and a Mouse/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int q = scan.nextInt(); 9 | while (q-- > 0) { 10 | int x = scan.nextInt(); 11 | int y = scan.nextInt(); 12 | int z = scan.nextInt(); 13 | System.out.println(solve(x, y, z)); 14 | } 15 | scan.close(); 16 | } 17 | 18 | private static String solve(int x, int y, int z) { 19 | int A_to_C = Math.abs(z - x); 20 | int B_to_C = Math.abs(z - y); 21 | if (A_to_C < B_to_C) { 22 | return "Cat A"; 23 | } else if (A_to_C > B_to_C) { 24 | return "Cat B"; 25 | } else { 26 | return "Mouse C"; 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Designer PDF Viewer/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | 7 | private static final int letters = 26; 8 | 9 | public static void main(String[] args) { 10 | /* Save input */ 11 | Scanner scan = new Scanner(System.in); 12 | int [] height = new int[letters]; 13 | for (int i = 0; i < letters; i++){ 14 | height[i] = scan.nextInt(); 15 | } 16 | String str = scan.next(); 17 | scan.close(); 18 | 19 | /* Calculate and print area */ 20 | int maxHeight = 0; 21 | for (int i = 0; i < str.length(); i++) { 22 | int index = str.charAt(i) - 'a'; 23 | maxHeight = Math.max(maxHeight, height[index]); 24 | } 25 | int area = maxHeight * str.length(); 26 | System.out.println(area); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Data Structures/Arrays/Sparse Arrays/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.HashMap; 5 | 6 | public class Solution { 7 | public static void main(String[] args) { 8 | Scanner scan = new Scanner(System.in); 9 | int N = scan.nextInt(); 10 | scan.nextLine(); // gets rid of pesky newline 11 | 12 | /* Create and fill HashMap */ 13 | HashMap map = new HashMap(); 14 | for (int i = 0; i < N; i++) { 15 | String str = scan.nextLine(); 16 | map.merge(str, 1, Integer::sum); 17 | } 18 | 19 | /* Query HashMap */ 20 | int Q = scan.nextInt(); 21 | scan.nextLine(); // gets rid of pesky newline 22 | for (int i = 0; i < Q; i++) { 23 | String str = scan.nextLine(); 24 | System.out.println(map.getOrDefault(str, 0)); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /10 Days of Statistics/Day 8 - Pearson Correlation Coefficient II/Solution.txt: -------------------------------------------------------------------------------- 1 | github.com/RodneyShag 2 | 3 | 4 | Answer: -3/4 5 | 6 | 7 | *** Step 1: Rewrite the 2 lines in proper form *** 8 | 9 | Rewrite the 2 lines as: 10 | 11 | y = -2 + (-3/4) * x 12 | x = -7/4 + (-3/4) * y 13 | 14 | so b1 = -3/4 and b2 = -3/4 15 | 16 | 17 | *** Step 2: Apply Pearson's Coefficient formula *** 18 | 19 | Let p = pearson coefficient 20 | Let x_std = standard deviation of x 21 | Let y_std = standard deviation of y 22 | 23 | p = b1 (x_std / y_std) 24 | p = b2 (y_std / x_std) 25 | 26 | Multiplying these 2 equations together we get 27 | p^2 = b1 * b2 28 | p^2 = (-3/4) * (-3/4) 29 | p^2 = 9/16 30 | p = 3/4 or -3/4 (depending on correlation of x and y) 31 | 32 | 33 | *** Step 3: Find out if p is postive or negative *** 34 | 35 | Notice that both of the original line equations have negative slopes, 36 | so x and y are negatively correlated by definition. So, p = -3/4 37 | -------------------------------------------------------------------------------- /Data Structures/Linked Lists/Insert a node at a specific position in a linked list/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* 4 | Insert Node at a given position in a linked list 5 | 6 | First element in the linked list is at position 0 7 | Node is defined as 8 | class Node { 9 | int data; 10 | Node next; 11 | } 12 | */ 13 | 14 | Node InsertNth(Node head, int data, int position) { 15 | Node newNode = new Node(); 16 | newNode.data = data; 17 | 18 | if (position == 0) { 19 | newNode.next = head; 20 | return newNode; 21 | } else { 22 | /* Get Node one element before desired position */ 23 | Node n = head; 24 | for (int i = 0; i < position - 1; i++) { 25 | n = n.next; 26 | } 27 | 28 | /* Insert our new Node */ 29 | newNode.next = n.next; 30 | n.next = newNode; 31 | 32 | return head; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /General Programming/RegEx/HackerRank in a String!/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int q = scan.nextInt(); 9 | while (q-- > 0) { 10 | String str = scan.next(); 11 | System.out.println(subsequenceExists(str) ? "YES" : "NO"); 12 | } 13 | scan.close(); 14 | } 15 | 16 | private static boolean subsequenceExists(String str) { 17 | String hackerrank = "hackerrank"; 18 | int index = 0; 19 | for (int i = 0; i < str.length(); i++) { 20 | if (str.charAt(i) == hackerrank.charAt(index)) { 21 | index++; 22 | } 23 | if (index == hackerrank.length()) { 24 | return true; 25 | } 26 | } 27 | return false; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Java/Introduction/Java Static Initializer Block/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | import java.text.*; 6 | import java.math.*; 7 | import java.util.regex.*; 8 | 9 | public class Solution { 10 | private static int B; 11 | private static int H; 12 | private static boolean flag; 13 | 14 | static { 15 | Scanner scan = new Scanner(System.in); 16 | B = scan.nextInt(); 17 | H = scan.nextInt(); 18 | scan.close(); 19 | if (B <= 0 || H <= 0) { 20 | System.out.println("java.lang.Exception: Breadth and height must be positive"); 21 | flag = false; 22 | } else { 23 | flag = true; 24 | } 25 | } 26 | 27 | public static void main(String[] args) { 28 | if (flag) { 29 | int area = B * H; 30 | System.out.print(area); 31 | } 32 | } // end of main 33 | } // end of class 34 | -------------------------------------------------------------------------------- /Data Structures/Linked Lists/Reverse a doubly linked list/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* 4 | * For your reference: 5 | * 6 | * DoublyLinkedListNode { 7 | * int data; 8 | * DoublyLinkedListNode next; 9 | * DoublyLinkedListNode prev; 10 | * } 11 | * 12 | */ 13 | 14 | // Time Complexity: O(n) 15 | // Space Complexity: O(1) 16 | DoublyLinkedListNode reverse(DoublyLinkedListNode head) { 17 | if (head == null || head.next == null) { 18 | return head; 19 | } 20 | DoublyLinkedListNode prev = null; 21 | DoublyLinkedListNode curr = head; 22 | DoublyLinkedListNode next = null; 23 | while (curr != null) { 24 | next = curr.next; 25 | curr.next = prev; 26 | curr.prev = next; 27 | prev = curr; 28 | curr = next; 29 | } 30 | return prev; 31 | } 32 | 33 | // Discuss on HackerRank: https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list/forum/comments/255770 34 | -------------------------------------------------------------------------------- /Algorithms/Strings/The Love-Letter Mystery/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | // We compare ASCII values for pairs of characters. The 1st pair we consider is the 2 6 | // characters at opposite ends of the String. We then move inwards until we consider 7 | // all palindromic pairs. 8 | 9 | public class Solution { 10 | public static void main(String[] args) { 11 | Scanner scan = new Scanner(System.in); 12 | int T = scan.nextInt(); 13 | while (T-- > 0) { 14 | String str = scan.next(); 15 | System.out.println(minimumOperations(str)); 16 | } 17 | scan.close(); 18 | } 19 | 20 | private static int minimumOperations(String str) { 21 | int count = 0; 22 | for (int i = 0; i < str.length() / 2; i++) { 23 | count += Math.abs(str.charAt(i) - str.charAt(str.length() - 1 - i)); 24 | } 25 | return count; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /10 Days of Statistics/Day 5 - Poisson Distribution II/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | /* Useful Formulas: 6 | https://www.hackerrank.com/challenges/s10-poisson-distribution-2/forum/comments/175398 7 | https://www.hackerrank.com/challenges/s10-poisson-distribution-2/forum/comments/176962 8 | */ 9 | public class Solution { 10 | public static void main(String[] args) { 11 | /* Save input */ 12 | Scanner scan = new Scanner(System.in); 13 | double A = scan.nextDouble(); 14 | double B = scan.nextDouble(); 15 | scan.close(); 16 | 17 | /* E[x^2] = lambda + lambda^2. Plug this into each formula */ 18 | double dailyCostA = 160 + 40 * (A + (A * A)); 19 | double dailyCostB = 128 + 40 * (B + (B * B)); 20 | 21 | /* Print output */ 22 | System.out.format("%.3f%n", dailyCostA); 23 | System.out.format("%.3f%n", dailyCostB); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms/Bit Manipulation/Lonely Integer/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | // O(n) runtime. O(1) space. Uses XOR. Keep in mind: 6 | // 1) x ^ x = 0 7 | // 2) x ^ 0 = x 8 | // 3) XOR is commutative and associative 9 | public class Solution { 10 | public static void main(String[] args) { 11 | /* Save input */ 12 | Scanner scan = new Scanner(System.in); 13 | int n = scan.nextInt(); 14 | int [] array = new int[n]; 15 | for(int i = 0; i < n; i++){ 16 | array[i] = scan.nextInt(); 17 | } 18 | scan.close(); 19 | 20 | System.out.println(lonelyInteger(array)); 21 | } 22 | 23 | /* XORs all numbers in array together */ 24 | public static int lonelyInteger(int [] array) { 25 | int val = 0; 26 | for (int num : array) { 27 | val = val ^ num; // ^ is XOR operator 28 | } 29 | return val; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Plus Minus/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | // Runtime: O(n) 6 | // Space Complexity: O(1) 7 | public class Solution { 8 | public static void main(String[] args) { 9 | Scanner scan = new Scanner(System.in); 10 | int size = scan.nextInt(); 11 | 12 | double positives = 0; 13 | double negatives = 0; 14 | double zeroes = 0; 15 | for (int i = 0; i < size; i++) { 16 | int value = scan.nextInt(); 17 | if (value > 0) { 18 | positives++; 19 | } else if (value < 0) { 20 | negatives++; 21 | } else { 22 | zeroes++; 23 | } 24 | } 25 | scan.close(); 26 | 27 | System.out.println(positives / size); 28 | System.out.println(negatives / size); 29 | System.out.println(zeroes / size); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Java/Strings/Tag Content Extractor/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.regex.Matcher; 5 | import java.util.regex.Pattern; 6 | 7 | /* Solution assumes we can't have the symbol "<" as text between tags */ 8 | public class Solution { 9 | public static void main(String[] args) { 10 | Scanner scan = new Scanner(System.in); 11 | int testCases = Integer.parseInt(scan.nextLine()); 12 | while (testCases-- > 0) { 13 | String line = scan.nextLine(); 14 | boolean matchFound = false; 15 | Pattern r = Pattern.compile("<(.+)>([^<]+)"); 16 | Matcher m = r.matcher(line); 17 | while (m.find()) { 18 | System.out.println(m.group(2)); 19 | matchFound = true; 20 | } 21 | if (!matchFound) { 22 | System.out.println("None"); 23 | } 24 | } 25 | scan.close(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Java/Object Oriented Programming/Java Method Overriding/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.*; 4 | 5 | class Sports { 6 | String getName() { 7 | return "Generic Sports"; 8 | } 9 | 10 | void getNumberOfTeamMembers() { 11 | System.out.println("Each team has n players in " + getName()); 12 | } 13 | } 14 | 15 | class Soccer extends Sports { 16 | @Override 17 | String getName() { 18 | return "Soccer Class"; 19 | } 20 | 21 | @Override 22 | void getNumberOfTeamMembers() { 23 | System.out.println("Each team has 11 players in " + getName()); 24 | } 25 | } 26 | 27 | public class Solution { 28 | public static void main(String[] args) { 29 | Sports c1 = new Sports(); 30 | Soccer c2 = new Soccer(); 31 | System.out.println(c1.getName()); 32 | c1.getNumberOfTeamMembers(); 33 | System.out.println(c2.getName()); 34 | c2.getNumberOfTeamMembers(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Algorithms/Bit Manipulation/Bit Manipulation - Lonely Integer/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | // O(n) runtime. O(1) space. Uses XOR. Keep in mind: 6 | // 1) x ^ x = 0 7 | // 2) x ^ 0 = x 8 | // 3) XOR is commutative and associative 9 | public class Solution { 10 | public static void main(String[] args) { 11 | /* Read input */ 12 | Scanner scan = new Scanner(System.in); 13 | int n = scan.nextInt(); 14 | int [] array = new int[n]; 15 | for(int i = 0; i < n; i++){ 16 | array[i] = scan.nextInt(); 17 | } 18 | scan.close(); 19 | 20 | System.out.println(lonelyInteger(array)); 21 | } 22 | 23 | /* XORs all numbers in array together */ 24 | public static int lonelyInteger(int [] array) { 25 | int val = 0; 26 | for (int num : array) { 27 | val = val ^ num; // ^ is XOR operator 28 | } 29 | return val; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/Data Structures/Hash Tables - Ransom Note/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* Determines if ransom letter can be made from magazine */ 4 | public static void checkMagazine(String[] magazine, String[] ransom) { 5 | HashMap usableWords = makeMap(magazine); 6 | for (int i = 0; i < ransom.length; i++) { 7 | if (usableWords.containsKey(ransom[i]) && usableWords.get(ransom[i]) > 0) { 8 | usableWords.merge(ransom[i], -1, Integer::sum); // uses the word 9 | } else { 10 | System.out.println("No"); 11 | return; 12 | } 13 | } 14 | System.out.println("Yes"); 15 | } 16 | 17 | /* Creates and returns a HashMap out of an array of Strings */ 18 | private static HashMap makeMap(String[] words) { 19 | HashMap map = new HashMap(); 20 | for (int i = 0; i < words.length; i++) { 21 | map.merge(words[i], 1, Integer::sum); 22 | } 23 | return map; 24 | } 25 | -------------------------------------------------------------------------------- /Java/Strings/Java Strings Introduction/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | /* Save input */ 8 | Scanner scan = new Scanner(System.in); 9 | String A = scan.next(); 10 | String B = scan.next(); 11 | scan.close(); 12 | 13 | /* Sum lengths */ 14 | System.out.println(A.length() + B.length()); 15 | 16 | /* Compare lexicographical ordering */ 17 | System.out.println(A.compareTo(B) > 0 ? "Yes" : "No"); 18 | 19 | /* Print the Strings in desired format */ 20 | System.out.println(capFirstLetter(A) + " " + capFirstLetter(B)); 21 | } 22 | 23 | private static String capFirstLetter(String str) { 24 | if (str == null || str.length() == 0) { 25 | return ""; 26 | } else { 27 | return str.substring(0,1).toUpperCase() + str.substring(1); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /30 Days of Code/Day 06 - Let's Review/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int T = scan.nextInt(); 9 | for (int i = 0; i < T; i++) { 10 | String str = scan.next(); 11 | printEvensOdds(str); 12 | } 13 | scan.close(); 14 | } 15 | 16 | /* For efficient appending, use a StringBuffer instead of a String */ 17 | public static void printEvensOdds(String str) { 18 | StringBuffer evens = new StringBuffer(); 19 | StringBuffer odds = new StringBuffer(); 20 | for (int i = 0; i < str.length(); i++) { 21 | char ch = str.charAt(i); 22 | if (i % 2 == 0) { 23 | evens.append(ch); 24 | } else { 25 | odds.append(ch); 26 | } 27 | } 28 | System.out.println(evens + " " + odds); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /30 Days of Code/Day 17 - More Exceptions/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.*; 4 | import java.io.*; 5 | 6 | class Calculator { 7 | int power(int n, int p) throws Exception { 8 | if (n < 0 || p < 0) { 9 | throw new Exception("n and p should be non-negative"); 10 | } else { 11 | return (int) Math.pow(n, p); 12 | } 13 | } 14 | } 15 | 16 | class Solution { 17 | public static void main(String[] args) { 18 | Scanner in = new Scanner(System.in); 19 | int t = in.nextInt(); 20 | while (t-- > 0) { 21 | int n = in.nextInt(); 22 | int p = in.nextInt(); 23 | Calculator myCalculator = new Calculator(); 24 | try { 25 | int ans = myCalculator.power(n, p); 26 | System.out.println(ans); 27 | } catch (Exception e) { 28 | System.out.println(e.getMessage()); 29 | } 30 | } 31 | in.close(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Drawing Book/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | // Explanation: 6 | // - The last page is n/2 page turns away. 7 | // - It takes p/2 pages to get to the p-th page (from the front) 8 | // - It takes n/2 - p/2 pages to get to the p-th page (from the back) 9 | // - The minimum of p/2 and (n/2 - p/2) is the minimum number of pages Brie must turn 10 | 11 | // Time complexity: O(1) 12 | // Space complexity: O(1) 13 | public class Solution { 14 | static int solve (int n, int p) { 15 | int pagesFromFront = p/2; 16 | int pagesFromBack = n/2 - p/2; 17 | return Math.min(pagesFromFront, pagesFromBack); 18 | } 19 | 20 | public static void main(String[] args) { 21 | Scanner scan = new Scanner(System.in); 22 | int n = scan.nextInt(); 23 | int p = scan.nextInt(); 24 | scan.close(); 25 | 26 | int result = solve(n, p); 27 | System.out.println(result); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /30 Days of Code/Day 08 - Dictionaries and Maps/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.HashMap; 5 | 6 | class Solution { 7 | public static void main(String[] args) { 8 | /* Save input as entries in a HashMap */ 9 | Scanner scan = new Scanner(System.in); 10 | int n = scan.nextInt(); 11 | HashMap map = new HashMap(); 12 | for (int i = 0; i < n; i++) { 13 | String name = scan.next(); 14 | int phone = scan.nextInt(); 15 | map.put(name, phone); 16 | } 17 | 18 | /* Read each query and check if its in our HashMap */ 19 | while (scan.hasNext()) { 20 | String str = scan.next(); 21 | if (map.containsKey(str)) { 22 | System.out.println(str + "=" + map.get(str)); 23 | } else { 24 | System.out.println("Not found"); 25 | } 26 | } 27 | 28 | scan.close(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Diagonal Difference/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | /* O(N^2) runtime. O(1) space */ 6 | public class Solution { 7 | public static void main(String[] args) { 8 | Scanner scan = new Scanner(System.in); 9 | int N = scan.nextInt(); 10 | 11 | int primaryDiagonal = 0; 12 | int secondaryDiagonal = 0; 13 | 14 | for (int row = 0; row < N; row++) { 15 | for (int col = 0; col < N; col++) { 16 | int value = scan.nextInt(); 17 | if (row == col) { 18 | primaryDiagonal += value; 19 | } 20 | if (row + col == N - 1) { 21 | secondaryDiagonal += value; 22 | } 23 | } 24 | } 25 | scan.close(); 26 | 27 | int absoluteDifference = Math.abs(primaryDiagonal - secondaryDiagonal); 28 | System.out.println(absoluteDifference); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Java/Strings/Java String Compare/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | /* Save input */ 8 | Scanner scan = new Scanner(System.in); 9 | String s = scan.nextLine(); 10 | int k = scan.nextInt(); 11 | scan.close(); 12 | 13 | /* Create smallest and largest strings and initialize them */ 14 | String smallest = s.substring(0, k); 15 | String largest = s.substring(0, k); 16 | 17 | for (int i = 0; i <= s.length() - k; i++) { 18 | String curr = s.substring(i, i + k); 19 | if (smallest.compareTo(curr) > 0){ 20 | smallest = curr; 21 | } 22 | if (largest.compareTo(curr) < 0) { 23 | largest = curr; 24 | } 25 | } 26 | 27 | /* Print results */ 28 | System.out.println(smallest); 29 | System.out.println(largest); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /10 Days of Statistics/Day 0 - Weighted Mean/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | /* Save input */ 8 | Scanner scan = new Scanner(System.in); 9 | int size = scan.nextInt(); 10 | int [] elements = new int[size]; 11 | int [] weights = new int[size]; 12 | for (int i = 0; i < size; i++) { 13 | elements[i] = scan.nextInt(); 14 | } 15 | for (int i = 0; i < size; i++) { 16 | weights[i] = scan.nextInt(); 17 | } 18 | scan.close(); 19 | 20 | /* Calculate weighted mean */ 21 | int total = 0; 22 | int totalWeights = 0; 23 | for (int i = 0; i < size; i++) { 24 | total += elements[i] * weights[i]; 25 | totalWeights += weights[i]; 26 | } 27 | double weightedMean = (double) total / totalWeights; 28 | System.out.format("%.1f", weightedMean); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Java/Data Structures/Java Generics/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.io.IOException; 4 | import java.lang.reflect.Method; 5 | 6 | class Printer { 7 | public void printArray(T[] array) { 8 | for (T item : array) { 9 | System.out.println(item); 10 | } 11 | } 12 | } 13 | 14 | public class Solution { 15 | public static void main(String args[]) { 16 | Printer myPrinter = new Printer(); 17 | Integer[] intArray = { 1, 2, 3 }; 18 | String[] stringArray = {"Hello", "World"}; 19 | myPrinter.printArray(intArray); 20 | myPrinter.printArray(stringArray); 21 | int count = 0; 22 | for (Method method : Printer.class.getDeclaredMethods()) { 23 | String name = method.getName(); 24 | if (name.equals("printArray")) { 25 | count++; 26 | } 27 | } 28 | if (count > 1) { 29 | System.out.println("Method overloading is not allowed!"); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Data Structures/Linked Lists/Find Merge Point of Two Lists/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* 4 | Node is defined as 5 | class Node { 6 | int data; 7 | Node next; 8 | } 9 | */ 10 | 11 | // Create a pointer that iterates through a list. When it's at the end 12 | // of the list, have it jump to the beginning of the other list. Create 13 | // 2 of these pointers, pointing to 2 different list heads. The pointers 14 | // will collide at the merge point after 1 or 2 passes. 15 | 16 | // Time Complexity: O(n + m) 17 | // Space Complexity: O(1) 18 | 19 | int FindMergeNode(Node headA, Node headB) { 20 | Node currA = headA; 21 | Node currB = headB; 22 | 23 | while (currA != currB) { 24 | if (currA.next == null) { 25 | currA = headB; 26 | } else { 27 | currA = currA.next; 28 | } 29 | 30 | if (currB.next == null) { 31 | currB = headA; 32 | } else { 33 | currB = currB.next; 34 | } 35 | } 36 | return currA.data; 37 | } -------------------------------------------------------------------------------- /General Programming/Basic Programming/Bon Appetit/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | // Although imprecise, this problem is intended to be solved using an "int" instead of a "double" to store dollar amounts. 6 | public class Solution { 7 | public static void main(String[] args) { 8 | /* Read input and calcute chargedBill and actualBill */ 9 | Scanner scan = new Scanner(System.in); 10 | int n = scan.nextInt(); 11 | int k = scan.nextInt(); 12 | int actualBill = 0; 13 | for (int i = 0; i < n; i++) { 14 | int price = scan.nextInt(); 15 | if (i != k) { 16 | actualBill += price; 17 | } 18 | } 19 | actualBill *= 0.5; 20 | int chargedBill = scan.nextInt(); 21 | 22 | /* Print output */ 23 | if (chargedBill == actualBill) { 24 | System.out.println("Bon Appetit"); 25 | } else { 26 | System.out.println(chargedBill - actualBill); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Java/Exception Handling/Java Exception Handling/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.*; 4 | import java.util.Scanner; 5 | 6 | class MyCalculator { 7 | long power(int n, int p) throws Exception { 8 | if (n < 0 || p < 0) { 9 | throw new Exception("n or p should not be negative."); 10 | } else if (n == 0 && p == 0) { 11 | throw new Exception("n and p should not be zero."); 12 | } else { 13 | return (long) Math.pow(n, p); 14 | } 15 | } 16 | } 17 | 18 | class Solution { 19 | public static void main(String[] args) { 20 | Scanner in = new Scanner(System.in); 21 | while (in .hasNextInt()) { 22 | int n = in .nextInt(); 23 | int p = in .nextInt(); 24 | MyCalculator my_calculator = new MyCalculator(); 25 | try { 26 | System.out.println(my_calculator.power(n, p)); 27 | } catch (Exception e) { 28 | System.out.println(e); 29 | } 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Algorithms/Sorting/Insertion Sort - Part 1/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int s = scan.nextInt(); 9 | int[] array = new int[s]; 10 | for (int i = 0; i < s; i++) { 11 | array[i] = scan.nextInt(); 12 | } 13 | scan.close(); 14 | insertIntoSorted(array); 15 | } 16 | 17 | public static void insertIntoSorted(int[] array) { 18 | int i = array.length - 1; 19 | int value = array[i]; 20 | while (i >= 1 && array[i-1] > value) { 21 | array[i] = array[i-1]; 22 | i--; 23 | printArray(array); 24 | } 25 | array[i] = value; 26 | printArray(array); 27 | } 28 | 29 | private static void printArray(int[] array) { 30 | for (int num: array) { 31 | System.out.print(num + " "); 32 | } 33 | System.out.println(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Java/Object Oriented Programming/Java Iterator/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.*; 4 | public class Main{ 5 | 6 | static Iterator func(ArrayList mylist){ 7 | Iterator it=mylist.iterator(); 8 | while(it.hasNext()){ 9 | Object element = it.next(); 10 | if (element.equals("###")) 11 | break; 12 | } 13 | return it; 14 | 15 | } 16 | @SuppressWarnings({ "unchecked" }) 17 | public static void main(String []args){ 18 | ArrayList mylist = new ArrayList(); 19 | Scanner sc = new Scanner(System.in); 20 | int n = sc.nextInt(); 21 | int m = sc.nextInt(); 22 | for(int i = 0;i= 1 && array[j-1] > value) { // find where to insert "value" 23 | array[j] = array[j-1]; // shift elements (1 by 1) to make room for inserting 24 | j--; 25 | shifts++; 26 | } 27 | array[j] = value; 28 | } 29 | System.out.println(shifts); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /30 Days of Code/Day 13 - Abstract Classes/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.*; 4 | 5 | abstract class Book { 6 | String title; 7 | String author; 8 | Book(String t, String a) { 9 | title = t; 10 | author = a; 11 | } 12 | abstract void display(); 13 | } 14 | 15 | class MyBook extends Book { 16 | int price; 17 | 18 | MyBook(String title, String author, int price) { 19 | super(title, author); 20 | this.price = price; 21 | } 22 | 23 | void display() { 24 | System.out.println("Title: " + title); 25 | System.out.println("Author: " + author); 26 | System.out.println("Price: " + price); 27 | } 28 | } 29 | 30 | public class Solution { 31 | public static void main(String[] args) { 32 | Scanner sc = new Scanner(System.in); 33 | String title = sc.nextLine(); 34 | String author = sc.nextLine(); 35 | int price = sc.nextInt(); 36 | Book new_novel = new MyBook(title, author, price); 37 | new_novel.display(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/Data Structures/Linked Lists - Detect a Cycle/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | // Algorithm 4 | // 5 | // 1. Create a pointer that moves 1 step at a time: 'slow' 6 | // 2. Create a pointer that moves 2 steps at a time: 'fast' 7 | // 3. If the Linked List has a cycle, 'slow' and 'fast' will collide. 8 | 9 | /* 10 | 11 | A Node is defined as: 12 | class Node { 13 | int data; 14 | Node next; 15 | } 16 | */ 17 | 18 | // If "slow" and "fast" collide, we must have a cycle 19 | boolean hasCycle(Node head) { 20 | if (head == null) { 21 | return false; 22 | } 23 | 24 | Node slow = head; // moves 1 Node at a time 25 | Node fast = head; // moves 2 Nodes at a time 26 | 27 | while (fast != null && fast.next != null) { 28 | slow = slow.next; 29 | fast = fast.next.next; 30 | if (slow == fast) { 31 | return true; // since "slow" and "fast" collided 32 | } 33 | } 34 | return false; 35 | } 36 | 37 | // Time Complexity: O(n) 38 | // Space Complexity: O(1) 39 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Save the Prisoner!/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | /* 6 | 7 | We start off at some random prisoner S and try to distribute M candies. We could just do 8 | S + M to see which prisoner we end up at. However, we may have more candies than prisoners, 9 | so we loop back around to the first prisoner by doing the % N where N is number of prisoners. 10 | 11 | Each +1 and -1 that you see in the equation is to fix the off-by-one problems that exist 12 | since prisoners are counted from 1 to N while modular arithmetic is counted from 0. 13 | 14 | */ 15 | 16 | public class Solution { 17 | public static void main(String[] args) { 18 | Scanner scan = new Scanner(System.in); 19 | int T = scan.nextInt(); 20 | while (T-- > 0) { 21 | int N = scan.nextInt(); 22 | int M = scan.nextInt(); 23 | int S = scan.nextInt(); 24 | int last = ((S - 1) + (M - 1)) % N + 1; 25 | System.out.println(last); 26 | } 27 | scan.close(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /General Programming/Object-oriented Programming/Abstract Classes/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.*; 4 | 5 | abstract class Book { 6 | String title; 7 | String author; 8 | Book(String t, String a) { 9 | title = t; 10 | author = a; 11 | } 12 | abstract void display(); 13 | } 14 | 15 | class MyBook extends Book { 16 | int price; 17 | 18 | MyBook(String title, String author, int price) { 19 | super(title, author); 20 | this.price = price; 21 | } 22 | 23 | void display() { 24 | System.out.println("Title: " + title); 25 | System.out.println("Author: " + author); 26 | System.out.println("Price: " + price); 27 | } 28 | } 29 | 30 | public class Solution { 31 | public static void main(String[] args) { 32 | Scanner sc = new Scanner(System.in); 33 | String title = sc.nextLine(); 34 | String author = sc.nextLine(); 35 | int price = sc.nextInt(); 36 | Book new_novel = new MyBook(title, author, price); 37 | new_novel.display(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Algorithms/Greedy/Maximum Perimeter Triangle/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.Arrays; 5 | import java.util.Collections; 6 | 7 | // Time complexity: O(n log n) 8 | public class Solution { 9 | public static void main(String[] args) { 10 | Scanner scan = new Scanner(System.in); 11 | int N = scan.nextInt(); 12 | Integer [] stick = new Integer[N]; 13 | for (int i = 0; i < N; i++) { 14 | stick[i] = scan.nextInt(); 15 | } 16 | scan.close(); 17 | findTriangle(stick); 18 | } 19 | 20 | /* Greedy Approach: Try to use the biggest sticks first */ 21 | private static void findTriangle(Integer [] stick) { 22 | Arrays.sort(stick, Collections.reverseOrder()); 23 | for (int i = 0; i < stick.length - 2; i++) { 24 | if (stick[i] < stick[i+1] + stick[i+2]) { 25 | System.out.println(stick[i+2] + " " + stick[i+1] + " " + stick[i]); 26 | return; 27 | } 28 | } 29 | System.out.println(-1); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Algorithms/Bit Manipulation/Maximizing XOR/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | // To maximize A xor B, we want A and B to differ as much as possible at every bit index. 4 | // We first find the most significant bit that we can force to differ by looking at L and R. 5 | // For all of the lesser significant bits in A and B, we can always ensure that they differ 6 | // and still have L <= A <= B <= R. Our final answer will be the number represented by all 7 | // 1s starting from the most significant bit that differs between A and B 8 | 9 | // Example: 10 | // L = 10111 11 | // R = 11100 12 | // _X___ <-- that's most significant differing bit 13 | // 01111 <-- here's our final answer 14 | // 15 | // Notice that we never directly calculate the values of A and B 16 | 17 | static int maximizingXor(int L, int R) { 18 | int xored = L ^ R; 19 | int significantBit = 31 - Integer.numberOfLeadingZeros(xored); 20 | int result = (1 << (significantBit + 1)) - 1; 21 | return result; 22 | } 23 | 24 | // Discuss on HackerRank: https://www.hackerrank.com/challenges/maximizing-xor/forum/comments/284317 25 | -------------------------------------------------------------------------------- /Java/Data Structures/Java Subarray/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | // A subarray must be contiguous. There are O(n^2) contiguous subarrays. 6 | 7 | // Time Complexity: O(n^2) 8 | // Space Complexity: O(1) 9 | public class Solution { 10 | public static void main(String[] args) { 11 | Scanner scan = new Scanner(System.in); 12 | int size = scan.nextInt(); 13 | int[] array = new int[size]; 14 | for (int i = 0; i < size; i++) { 15 | array[i] = scan.nextInt(); 16 | } 17 | scan.close(); 18 | 19 | System.out.println(negativeSubarrays(array)); 20 | } 21 | 22 | private static int negativeSubarrays(int[] array) { 23 | int count = 0; 24 | for (int i = 0; i < array.length; i++) { 25 | int sum = 0; 26 | for (int j = i; j < array.length; j++) { 27 | sum += array[j]; 28 | if (sum < 0) { 29 | count++; 30 | } 31 | } 32 | } 33 | return count; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms/Sorting/Minimum Absolute Difference in an Array/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.Arrays; 5 | 6 | // Algorithm: Sort the array and compare adjacent pairs 7 | 8 | // Greedy algorithm? No 9 | 10 | // A greedy algorithm makes "the locally optimal choice at each 11 | // stage with the hope of finding a global optimum" - Wikipedia 12 | 13 | public class Solution { 14 | public static void main(String[] args) { 15 | Scanner scan = new Scanner(System.in); 16 | int n = scan.nextInt(); 17 | int [] array = new int[n]; 18 | for (int i = 0; i < n; i++) { 19 | array[i] = scan.nextInt(); 20 | } 21 | scan.close(); 22 | System.out.println(minAbsoluteDifference(array)); 23 | } 24 | 25 | private static int minAbsoluteDifference(int [] array) { 26 | Arrays.sort(array); 27 | int min = Integer.MAX_VALUE; 28 | for (int i = 1; i < array.length; i++) { 29 | min = Math.min(min, Math.abs(array[i] - array[i-1])); 30 | } 31 | return min; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /10 Days of Statistics/Day 1 - Standard Deviation/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | /* Save input */ 8 | Scanner scan = new Scanner(System.in); 9 | int size = scan.nextInt(); 10 | int [] array = new int[size]; 11 | for (int i = 0; i < size; i++) { 12 | array[i] = scan.nextInt(); 13 | } 14 | scan.close(); 15 | 16 | System.out.format("%.1f", standardDeviation(array)); 17 | } 18 | 19 | public static double getMean(int [] array) { 20 | int sum = 0; 21 | for (int x : array) { 22 | sum += x; 23 | } 24 | return (double) sum / array.length; 25 | } 26 | 27 | public static double standardDeviation(int [] array) { 28 | double mean = getMean(array); 29 | double sum = 0; 30 | for (int x : array) { 31 | sum += Math.pow(x - mean, 2); 32 | } 33 | double variance = sum / array.length; 34 | return Math.sqrt(variance); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Rodney Shaghoulian 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /30 Days of Code/Day 25 - Running Time and Complexity/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int T = scan.nextInt(); 9 | while (T-- > 0) { 10 | int n = scan.nextInt(); 11 | System.out.println(isPrime(n) ? "Prime" : "Not prime"); 12 | } 13 | scan.close(); 14 | } 15 | 16 | private static boolean isPrime(int n) { 17 | if (n < 2) { 18 | return false; 19 | } else if (n == 2) { // account for even numbers now, so that we can do i+=2 in loop below 20 | return true; 21 | } else if (n % 2 == 0) { // account for even numbers now, so that we can do i+=2 in loop below 22 | return false; 23 | } 24 | int sqrt = (int) Math.sqrt(n); 25 | for (int i = 3; i <= sqrt; i += 2) { // skips even numbers for faster results 26 | if (n % i == 0) { 27 | return false; 28 | } 29 | } 30 | return true; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Minimum Distances/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.HashMap; 5 | 6 | // Main trick: Use a HashMap that maps from "value" to "index" 7 | // to keep track of the largest index for each value that we've 8 | // seen so far as we loop through array 9 | 10 | // Time Complexity: O(n) 11 | // Space Complexity: O(n) 12 | 13 | // Complete the minimumDistances function below. 14 | static int minimumDistances(int[] array) { 15 | HashMap map = new HashMap(); 16 | int minDistance = Integer.MAX_VALUE; 17 | for (int i = 0; i < array.length; i++) { 18 | if (map.containsKey(array[i])) { 19 | int prevIndex = map.get(array[i]); 20 | int currDistance = i - prevIndex; 21 | minDistance = Math.min(minDistance, currDistance); 22 | } 23 | map.put(array[i], i); 24 | } 25 | return minDistance == Integer.MAX_VALUE ? -1 : minDistance; 26 | } 27 | 28 | // Discuss on HackerRank: https://www.hackerrank.com/challenges/minimum-distances/forum/comments/360084 29 | -------------------------------------------------------------------------------- /Data Structures/Linked Lists/Merge two sorted linked lists/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* 4 | class SinglyLinkedListNode { 5 | int data; 6 | SinglyLinkedListNode next; 7 | } 8 | */ 9 | 10 | // Time Complexity: O(n + m) 11 | // Space Complexity: O(1) 12 | 13 | static SinglyLinkedListNode mergeLists(SinglyLinkedListNode currA, SinglyLinkedListNode currB) { 14 | if (currA == null) { 15 | return currB; 16 | } else if (currB == null) { 17 | return currA; 18 | } 19 | 20 | SinglyLinkedListNode result = new SinglyLinkedListNode(0); // dummy/placeholder ListNode 21 | SinglyLinkedListNode n = result; 22 | while (currA != null && currB != null) { 23 | if (currA.data < currB.data) { 24 | n.next = currA; 25 | currA = currA.next; 26 | } else { 27 | n.next = currB; 28 | currB = currB.next; 29 | } 30 | n = n.next; 31 | } 32 | 33 | /* Attach the remaining elements */ 34 | if (currA == null) { 35 | n.next = currB; 36 | } else { 37 | n.next = currA; 38 | } 39 | 40 | return result.next; 41 | } 42 | -------------------------------------------------------------------------------- /Java/Advanced/Covariant Return Types/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | class Flower { 4 | String whatsYourName() { 5 | return "I have many names and types."; 6 | } 7 | } 8 | 9 | class Jasmine extends Flower { 10 | @Override 11 | String whatsYourName() { 12 | return "Jasmine"; 13 | } 14 | } 15 | 16 | class Lily extends Flower { 17 | @Override 18 | String whatsYourName() { 19 | return "Lily"; 20 | } 21 | } 22 | 23 | class Lotus extends Flower { 24 | @Override 25 | String whatsYourName() { 26 | return "Lotus"; 27 | } 28 | } 29 | 30 | class Region { 31 | Flower yourNationalFlower() { 32 | return new Flower(); 33 | } 34 | } 35 | 36 | class WestBengal extends Region { 37 | @Override 38 | Jasmine yourNationalFlower() { 39 | return new Jasmine(); 40 | } 41 | } 42 | 43 | class Karnataka extends Region { 44 | @Override 45 | Lotus yourNationalFlower() { 46 | return new Lotus(); 47 | } 48 | } 49 | 50 | class AndhraPradesh extends Region { 51 | @Override 52 | Lily yourNationalFlower() { 53 | return new Lily(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Data Structures/Arrays/Dynamic Array/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.ArrayList; 5 | 6 | public class Solution { 7 | public static void main(String[] args) { 8 | Scanner scan = new Scanner(System.in); 9 | int N = scan.nextInt(); 10 | int Q = scan.nextInt(); 11 | int lastAns = 0; 12 | 13 | /* Create 2-D ArrayList */ 14 | ArrayList> lists = new ArrayList(); 15 | for (int i = 0; i < N; i++) { 16 | lists.add(new ArrayList()); 17 | } 18 | 19 | /* Perform Q Queries */ 20 | for (int i = 0; i < Q; i++) { 21 | int q = scan.nextInt(); 22 | int x = scan.nextInt(); 23 | int y = scan.nextInt(); 24 | ArrayList seq = lists.get((x ^ lastAns) % N); 25 | if (q == 1) { 26 | seq.add(y); 27 | } else if (q == 2) { 28 | lastAns = seq.get(y % seq.size()); 29 | System.out.println(lastAns); 30 | } 31 | } 32 | 33 | scan.close(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Sequence Equation/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | // - Our input provides us "n" values of x and p(x) 6 | // - p(x) is a 1-to-1 function, so it has an inverse. 7 | // - We create the function representing the inverse of p(x), and represent it as an array: int [] p_inverse 8 | // - We need find a y where p(p(y)) = x. This equation can be rewritten as y = p_inverse(p_inverse(x)), which is the version of the equation we use to calculate and print "y". 9 | 10 | public class Solution { 11 | public static void main(String[] args) { 12 | /* Create function: p_inverse */ 13 | Scanner scan = new Scanner(System.in); 14 | int n = scan.nextInt(); 15 | int [] p_inverse = new int[n + 1]; 16 | for (int x = 1; x <= n; x++) { 17 | int px = scan.nextInt(); 18 | p_inverse[px] = x; 19 | } 20 | scan.close(); 21 | 22 | /* Calculate and print each y */ 23 | for (int x = 1; x <= n; x++) { 24 | int y = p_inverse[p_inverse[x]]; 25 | System.out.println(y); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Data Structures/Trees/Binary Search Tree - Insertion/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* Node is defined as : 4 | class Node { 5 | int data; 6 | Node left; 7 | Node right; 8 | } 9 | */ 10 | 11 | // Runtime: O(log n) on a balanced tree. 12 | // Space Complexity: O(1) 13 | static Node Insert(Node root, int value) { 14 | /* Create new Node */ 15 | Node newNode = new Node(); 16 | newNode.data = value; 17 | 18 | /* Special case: empty tree */ 19 | if (root == null) { 20 | return newNode; 21 | } 22 | 23 | /* Iteratively walk tree and insert new Node */ 24 | Node curr = root; 25 | while (true) { 26 | if (value <= curr.data) { 27 | if (curr.left == null) { 28 | curr.left = newNode; 29 | return root; 30 | } else { 31 | curr = curr.left; 32 | } 33 | } else { 34 | if (curr.right == null) { 35 | curr.right = newNode; 36 | return root; 37 | } else { 38 | curr = curr.right; 39 | } 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Breaking the Records/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | // Time complexity: O(n) 6 | public class Solution { 7 | public static void main(String[] args) { 8 | /* Save input */ 9 | Scanner scan = new Scanner(System.in); 10 | int n = scan.nextInt(); 11 | int[] scores = new int[n]; 12 | for (int i = 0; i < n; i++) { 13 | scores[i] = scan.nextInt(); 14 | } 15 | scan.close(); 16 | 17 | /* Calculate answer */ 18 | printRecords(scores); 19 | } 20 | 21 | static void printRecords(int[] scores){ 22 | int min = scores[0]; 23 | int max = scores[0]; 24 | int higherScore = 0; 25 | int lowerScore = 0; 26 | for (int score: scores) { 27 | if (score > max) { 28 | max = score; 29 | higherScore++; 30 | } 31 | if (score < min) { 32 | min = score; 33 | lowerScore++; 34 | } 35 | } 36 | System.out.print(higherScore + " " + lowerScore); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Java/Strings/Java String Tokens/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | /* Read input */ 8 | Scanner scan = new Scanner(System.in); 9 | String s = scan.nextLine(); 10 | scan.close(); 11 | 12 | s = removeLeadingNonLetters(s); 13 | 14 | /* Check special cases */ 15 | if (s.length() == 0) { 16 | System.out.println(0); 17 | return; 18 | } 19 | 20 | /* Split on all non-alphabetic characters */ 21 | String[] words = s.split("[^a-zA-Z]+"); 22 | 23 | /* Print output */ 24 | System.out.println(words.length); 25 | for (String word : words) { 26 | System.out.println(word); 27 | } 28 | } 29 | 30 | private static String removeLeadingNonLetters(String str) { 31 | int i; 32 | for (i = 0; i < str.length(); i++) { 33 | if (Character.isLetter(str.charAt(i))) { 34 | break; 35 | } 36 | } 37 | return str.substring(i); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Algorithms/Sorting/Correctness and the Loop Invariant/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int s = scan.nextInt(); 9 | int[] array = new int[s]; 10 | for (int i = 0; i < s; i++) { 11 | array[i] = scan.nextInt(); 12 | } 13 | scan.close(); 14 | insertionSort(array); 15 | } 16 | 17 | /* Task: Find bug in HackerRank's insertionSort function below */ 18 | public static void insertionSort(int[] A) { 19 | for (int i = 1; i < A.length; i++) { 20 | int value = A[i]; 21 | int j = i - 1; 22 | while (j >= 0 && A[j] > value) { // fixed bug on this line 23 | A[j + 1] = A[j]; 24 | j = j - 1; 25 | } 26 | A[j + 1] = value; 27 | } 28 | printArray(A); 29 | } 30 | 31 | private static void printArray(int[] array) { 32 | for (int num: array) { 33 | System.out.print(num + " "); 34 | } 35 | System.out.println(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Utopian Tree/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.Arrays; 5 | 6 | // Time Complexity: O(N + T) 7 | // Space Complexity: O(N + T) 8 | public class Solution { 9 | public static void main(String[] args) { 10 | /* Save input */ 11 | Scanner scan = new Scanner(System.in); 12 | int T = scan.nextInt(); 13 | int [] testcase = new int[T]; 14 | for (int i = 0; i < T; i++) { 15 | testcase[i] = scan.nextInt(); 16 | } 17 | 18 | /* Calculate answers for all T testcases */ 19 | int maxCycles = Arrays.stream(testcase).max().getAsInt(); 20 | int [] cache = new int[maxCycles + 1]; // cache is crucial to increase runtime 21 | cache[0] = 1; 22 | for (int i = 1; i <= maxCycles; i++) { 23 | if (i % 2 == 1) { 24 | cache[i] = cache[i-1] * 2; 25 | } else { 26 | cache[i] = cache[i-1] + 1; 27 | } 28 | } 29 | 30 | /* Print answers */ 31 | for (int i = 0; i < T; i++) { 32 | System.out.println(cache[testcase[i]]); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /30 Days of Code/Day 14 - Scope/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | import java.text.*; 6 | import java.math.*; 7 | import java.util.regex.*; 8 | 9 | class Difference { 10 | private int[] elements; 11 | public int maximumDifference; 12 | 13 | Difference (int [] elements) { 14 | this.elements = elements; 15 | } 16 | 17 | // Runtime: O(n) 18 | // Space Complexity: O(1) 19 | void computeDifference() { 20 | int max = Arrays.stream(elements).max().getAsInt(); 21 | int min = Arrays.stream(elements).min().getAsInt(); 22 | maximumDifference = max - min ; 23 | } 24 | } // End of Difference class 25 | 26 | public class Solution { 27 | public static void main(String[] args) { 28 | Scanner sc = new Scanner(System.in); 29 | int n = sc.nextInt(); 30 | int[] a = new int[n]; 31 | for (int i = 0; i < n; i++) { 32 | a[i] = sc.nextInt(); 33 | } 34 | sc.close(); 35 | 36 | Difference difference = new Difference(a); 37 | 38 | difference.computeDifference(); 39 | 40 | System.out.print(difference.maximumDifference); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Algorithms/Sorting/Insertion Sort - Part 2/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int s = scan.nextInt(); 9 | int[] array = new int[s]; 10 | for (int i = 0; i < s; i++) { 11 | array[i] = scan.nextInt(); 12 | } 13 | scan.close(); 14 | insertionSortPart2(array); 15 | } 16 | 17 | public static void insertionSortPart2(int[] array) { 18 | for (int i = 1; i < array.length; i++) { 19 | int j = i; 20 | int value = array[i]; 21 | while (j >= 1 && array[j-1] > value) { // find where to insert "value" 22 | array[j] = array[j-1]; // shift the elements (1 by 1) to make room for inserting 23 | j--; 24 | } 25 | array[j] = value; 26 | printArray(array); 27 | } 28 | } 29 | 30 | private static void printArray(int[] array) { 31 | for (int num: array) { 32 | System.out.print(num + " "); 33 | } 34 | System.out.println(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Java/Introduction/Java Datatypes/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int t = scan.nextInt(); 9 | for (int i = 0; i < t; i++) { 10 | try { 11 | long x = scan.nextLong(); 12 | System.out.println(x + " can be fitted in:"); 13 | if (x >= Byte.MIN_VALUE && x <= Byte.MAX_VALUE) { 14 | System.out.println("* byte"); 15 | } 16 | if (x >= Short.MIN_VALUE && x <= Short.MAX_VALUE) { 17 | System.out.println("* short"); 18 | } 19 | if (x >= Integer.MIN_VALUE && x <= Integer.MAX_VALUE) { 20 | System.out.println("* int"); 21 | } 22 | if (x >= Long.MIN_VALUE && x <= Long.MAX_VALUE) { 23 | System.out.println("* long"); 24 | } 25 | } catch (Exception e) { 26 | System.out.println(scan.next() + " can't be fitted anywhere."); 27 | } 28 | } 29 | scan.close(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/Techniques, Concepts/DP - Coin Change/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | // Use a HashMap as a cache to speed up runtime 4 | // Must use "long" instead of "int" to avoid integer overflow 5 | 6 | static long ways(int n, int[] coins) { 7 | if (n < 0) { 8 | return 0; 9 | } 10 | return numWays(n, coins, 0, new HashMap()); 11 | } 12 | 13 | private static long numWays(int n, int [] coins, int coinNumber, HashMap cache) { 14 | /* Check our cache */ 15 | String key = n + "," + coinNumber; 16 | if (cache.containsKey(key)) { 17 | return cache.get(key); 18 | } 19 | /* Base case */ 20 | if (coinNumber == coins.length - 1) { 21 | if (n % coins[coinNumber] == 0) { 22 | cache.put(key, 1L); 23 | return 1; 24 | } else { 25 | cache.put(key, 0L); 26 | return 0; 27 | } 28 | } 29 | /* Recursive case */ 30 | long ways = 0; 31 | for (int i = 0; i <= n; i += coins[coinNumber]) { 32 | ways += numWays(n - i, coins, coinNumber + 1, cache); 33 | } 34 | /* Cache and return solution */ 35 | cache.put(key, ways); 36 | return ways; 37 | } 38 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Migratory Birds/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | // Time Complexity: O(n) 6 | public class Solution { 7 | 8 | static final int NUM_TYPES = 5; 9 | 10 | static int migratoryBirds(int[] birds) { 11 | /* Get counts of each type */ 12 | int[] count = new int[NUM_TYPES + 1]; 13 | for (int num : birds) { 14 | count[num]++; 15 | } 16 | 17 | /* Find max */ 18 | int maxIndex = 1; 19 | for (int i = 0; i < count.length; i++) { 20 | if (count[i] > count[maxIndex]) { 21 | maxIndex = i; 22 | } 23 | } 24 | return maxIndex; 25 | } 26 | 27 | public static void main(String[] args) { 28 | /* Save input */ 29 | Scanner scan = new Scanner(System.in); 30 | int n = scan.nextInt(); 31 | int[] birds = new int[n]; 32 | for (int i = 0; i < n; i++){ 33 | birds[i] = scan.nextInt(); 34 | } 35 | scan.close(); 36 | 37 | /* Calculate result */ 38 | int result = migratoryBirds(birds); 39 | System.out.println(result); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /30 Days of Code/Day 11 - 2D Arrays/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int arr[][] = new int[6][6]; 9 | for (int row = 0; row < 6; row++) { 10 | for (int col = 0; col < 6; col++) { 11 | arr[row][col] = scan.nextInt(); 12 | } 13 | } 14 | scan.close(); 15 | 16 | System.out.println(maxHourglass(arr)); 17 | } 18 | 19 | public static int maxHourglass(int [][] arr) { 20 | int max = Integer.MIN_VALUE; 21 | for (int row = 0; row < 4; row++) { 22 | for (int col = 0; col < 4; col++) { 23 | int sum = findSum(arr, row, col); 24 | max = Math.max(max, sum); 25 | } 26 | } 27 | return max; 28 | } 29 | 30 | private static int findSum(int [][] arr, int r, int c) { 31 | int sum = arr[r+0][c+0] + arr[r+0][c+1] + arr[r+0][c+2] 32 | + arr[r+1][c+1] + 33 | arr[r+2][c+0] + arr[r+2][c+1] + arr[r+2][c+2]; 34 | return sum; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Java/Data Structures/Java 2D Array/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | Scanner scan = new Scanner(System.in); 8 | int arr[][] = new int[6][6]; 9 | for (int row = 0; row < 6; row++) { 10 | for (int col = 0; col < 6; col++) { 11 | arr[row][col] = scan.nextInt(); 12 | } 13 | } 14 | scan.close(); 15 | 16 | System.out.println(maxHourglass(arr)); 17 | } 18 | 19 | public static int maxHourglass(int [][] arr) { 20 | int max = Integer.MIN_VALUE; 21 | for (int row = 0; row < 4; row++) { 22 | for (int col = 0; col < 4; col++) { 23 | int sum = findSum(arr, row, col); 24 | max = Math.max(max, sum); 25 | } 26 | } 27 | return max; 28 | } 29 | 30 | private static int findSum(int [][] arr, int r, int c) { 31 | int sum = arr[r+0][c+0] + arr[r+0][c+1] + arr[r+0][c+2] 32 | + arr[r+1][c+1] + 33 | arr[r+2][c+0] + arr[r+2][c+1] + arr[r+2][c+2]; 34 | return sum; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Data Structures/Arrays/2D Array - DS/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | 7 | public static void main(String[] args) { 8 | Scanner scan = new Scanner(System.in); 9 | int arr[][] = new int[6][6]; 10 | for (int row = 0; row < 6; row++) { 11 | for (int col = 0; col < 6; col++) { 12 | arr[row][col] = scan.nextInt(); 13 | } 14 | } 15 | scan.close(); 16 | 17 | System.out.println(maxHourglass(arr)); 18 | } 19 | 20 | public static int maxHourglass(int [][] arr) { 21 | int max = Integer.MIN_VALUE; 22 | for (int row = 0; row < 4; row++) { 23 | for (int col = 0; col < 4; col++) { 24 | int sum = findSum(arr, row, col); 25 | max = Math.max(max, sum); 26 | } 27 | } 28 | return max; 29 | } 30 | 31 | private static int findSum(int [][] arr, int r, int c) { 32 | int sum = arr[r+0][c+0] + arr[r+0][c+1] + arr[r+0][c+2] 33 | + arr[r+1][c+1] + 34 | arr[r+2][c+0] + arr[r+2][c+1] + arr[r+2][c+2]; 35 | return sum; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /10 Days of Statistics/Day 4 - Geometric Distribution I/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | /* Save input */ 8 | Scanner scan = new Scanner(System.in); 9 | int numerator = scan.nextInt(); 10 | int denominator = scan.nextInt(); 11 | int n = scan.nextInt(); 12 | scan.close(); 13 | 14 | /* Geometric Series */ 15 | double p = (double) numerator / denominator; 16 | System.out.format("%.3f", geometric(n, p)); 17 | } 18 | 19 | private static double geometric (int n, double p) { 20 | return Math.pow(1 - p, n - 1) * p; 21 | } 22 | 23 | private static Long combinations(int n, int x) { 24 | if (n < 0 || x < 0 || x > n) { 25 | return null; 26 | } 27 | return factorial(n) / (factorial(x) * factorial(n - x)); 28 | } 29 | 30 | private static Long factorial (int n){ 31 | if (n < 0) { 32 | return null; 33 | } 34 | long result = 1; 35 | while (n > 0) { 36 | result *= n--; 37 | } 38 | return result; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/Data Structures/Stacks - Balanced Brackets/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | // ArrayDeque is "likely to be faster than Stack when used as a stack" - Java documentation 4 | 5 | // Time Complexity: O(n) 6 | // Space Complexity: O(n) 7 | 8 | /* Create HashMap to match opening brackets with closing brackets */ 9 | static String isBalanced(String expression) { 10 | HashMap map = new HashMap(); 11 | map.put('(', ')'); 12 | map.put('[', ']'); 13 | map.put('{', '}'); 14 | return isBalanced(expression, map) ? "YES" : "NO"; 15 | } 16 | 17 | private static boolean isBalanced(String expression, HashMap map) { 18 | if ((expression.length() % 2) != 0) { 19 | return false; // odd length Strings are not balanced 20 | } 21 | ArrayDeque deque = new ArrayDeque(); // use deque as a stack 22 | for (int i = 0; i < expression.length(); i++) { 23 | Character ch = expression.charAt(i); 24 | if (map.containsKey(ch)) { 25 | deque.push(ch); 26 | } else if (deque.isEmpty() || ch != map.get(deque.pop())) { 27 | return false; 28 | } 29 | } 30 | return deque.isEmpty(); 31 | } 32 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/Techniques, Concepts/Recursion - Davis' Staircase/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.HashMap; 5 | 6 | // Recursive solution using dynamic programming 7 | 8 | // Time Complexity: O(n) 9 | // Space Complexity: O(n) 10 | 11 | // Can alternatively be solved in O(1) space (per testcase) by using iteration instead of recursion 12 | 13 | public class Solution { 14 | private static HashMap cache = new HashMap(); 15 | 16 | public static void main(String[] args) { 17 | Scanner scan = new Scanner(System.in); 18 | int testcases = scan.nextInt(); 19 | cache.put(0, 1); // base case 20 | while (testcases-- > 0) { 21 | int n = scan.nextInt(); 22 | System.out.println(staircase(n)); 23 | } 24 | scan.close(); 25 | } 26 | 27 | private static int staircase(int n) { 28 | if (n < 0) { 29 | return 0; 30 | } 31 | if (cache.containsKey(n)) { 32 | return cache.get(n); 33 | } 34 | int ways = staircase(n - 1) + staircase(n - 2) + staircase(n - 3); 35 | cache.put(n, ways); 36 | return ways; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/Techniques, Concepts/Time Complexity - Primality/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | // Time Complexity: O(n^(1/2)) for each 6 | // Space Complexity: O(1) 7 | public class Solution { 8 | public static void main(String[] args) { 9 | Scanner scan = new Scanner(System.in); 10 | int p = scan.nextInt(); 11 | while (p-- > 0) { 12 | int n = scan.nextInt(); 13 | System.out.println(isPrime(n) ? "Prime" : "Not prime"); 14 | } 15 | scan.close(); 16 | } 17 | 18 | public static boolean isPrime(int n) { 19 | if (n < 2) { 20 | return false; 21 | } else if (n == 2) { // account for even numbers now, so that we can do i+=2 in loop below 22 | return true; 23 | } else if (n % 2 == 0) { // account for even numbers now, so that we can do i+=2 in loop below 24 | return false; 25 | } 26 | int sqrt = (int) Math.sqrt(n); 27 | for (int i = 3; i <= sqrt; i += 2) { // skips even numbers for faster results 28 | if (n % i == 0) { 29 | return false; 30 | } 31 | } 32 | return true; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Algorithms/Strings/Super Reduced String/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.Stack; 5 | 6 | // Time Complexity: O(n) 7 | // Space Complexity: O(n) 8 | 9 | // Can alternatively use an ArrayDeque instead of a Stack. Just make sure to iterate 10 | // through it properly since iteration order is opposite that of a Stack. 11 | 12 | String superReducedString(String str) { 13 | /* Iterate through String, creating final result in a Stack */ 14 | Stack stack = new Stack(); 15 | for (int i = 0; i < str.length(); i++) { 16 | Character ch = str.charAt(i); 17 | if (!stack.isEmpty() && ch == stack.peek()) { 18 | stack.pop(); // since String has 2 adjacent equal characters 19 | } else { 20 | stack.push(ch); 21 | } 22 | } 23 | 24 | /* Return final result */ 25 | if (stack.isEmpty()) { 26 | return "Empty String"; 27 | } else { 28 | StringBuffer sb = new StringBuffer(); 29 | for (char ch : stack) { 30 | sb.append(ch); 31 | } 32 | return sb.toString(); 33 | } 34 | } 35 | 36 | // Discuss on HackerRank: https://www.hackerrank.com/challenges/reduced-string/forum/comments/263979 37 | -------------------------------------------------------------------------------- /Java/Object Oriented Programming/Java Instanceof keyword/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.*; 4 | 5 | 6 | class Student{} 7 | class Rockstar{ } 8 | class Hacker{} 9 | 10 | 11 | public class InstanceOFTutorial{ 12 | 13 | static String count(ArrayList mylist){ 14 | int a = 0,b = 0,c = 0; 15 | for(int i = 0; i < mylist.size(); i++){ 16 | Object element=mylist.get(i); 17 | if(element instanceof Student) 18 | a++; 19 | if(element instanceof Rockstar) 20 | b++; 21 | if(element instanceof Hacker) 22 | c++; 23 | } 24 | String ret = Integer.toString(a)+" "+ Integer.toString(b)+" "+ Integer.toString(c); 25 | return ret; 26 | } 27 | 28 | public static void main(String []args){ 29 | ArrayList mylist = new ArrayList(); 30 | Scanner sc = new Scanner(System.in); 31 | int t = sc.nextInt(); 32 | for(int i=0; i 0) { 43 | int ele = sc.nextInt(); 44 | head = insert(head,ele); 45 | } 46 | display(head); 47 | sc.close(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Java/Data Structures/Java Comparator/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.*; 4 | 5 | class Checker implements Comparator { 6 | @Override 7 | public int compare(Player p1, Player p2) { 8 | if (p1.score == p2.score) { 9 | return p1.name.compareTo(p2.name); 10 | } else { 11 | return p2.score - p1.score; // descending order 12 | } 13 | } 14 | } 15 | 16 | class Player { 17 | String name; 18 | int score; 19 | 20 | Player(String name, int score) { 21 | this.name = name; 22 | this.score = score; 23 | } 24 | } 25 | 26 | class Solution { 27 | public static void main(String[] args) { 28 | Scanner scan = new Scanner(System.in); 29 | int n = scan.nextInt(); 30 | 31 | Player[] player = new Player[n]; 32 | Checker checker = new Checker(); 33 | 34 | for (int i = 0; i < n; i++) { 35 | player[i] = new Player(scan.next(), scan.nextInt()); 36 | } 37 | scan.close(); 38 | 39 | Arrays.sort(player, checker); 40 | for (int i = 0; i < player.length; i++) { 41 | System.out.printf("%s %s\n", player[i].name, player[i].score); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Java/Data Structures/Java ArrayList/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.ArrayList; 5 | 6 | public class Solution { 7 | public static void main(String[] args) { 8 | Scanner scan = new Scanner(System.in); 9 | int n = scan.nextInt(); 10 | 11 | /* Save numbers in 2-D ArrayList */ 12 | ArrayList> lists = new ArrayList(); 13 | for (int row = 0; row < n; row++) { 14 | int d = scan.nextInt(); 15 | ArrayList list = new ArrayList(); 16 | for (int col = 0; col < d; col++) { 17 | list.add(scan.nextInt()); 18 | } 19 | lists.add(list); 20 | } 21 | 22 | /* Answer the queries */ 23 | int q = scan.nextInt(); 24 | for (int i = 0; i < q; i++) { 25 | int x = scan.nextInt(); 26 | int y = scan.nextInt(); 27 | ArrayList list = lists.get(x-1); 28 | if (y <= list.size()) { 29 | System.out.println(list.get(y-1)); 30 | } else { 31 | System.out.println("ERROR!"); 32 | } 33 | } 34 | 35 | scan.close(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Java/Data Structures/Java List/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.LinkedList; 5 | 6 | public class Solution { 7 | public static void main(String[] args) { 8 | /* Create and fill Linked List of Integers */ 9 | Scanner scan = new Scanner(System.in); 10 | int N = scan.nextInt(); 11 | LinkedList list = new LinkedList(); 12 | for (int i = 0; i < N; i++) { 13 | int value = scan.nextInt(); 14 | list.add(value); 15 | } 16 | 17 | /* Perform queries on Linked List */ 18 | int Q = scan.nextInt(); 19 | for (int i = 0; i < Q; i++) { 20 | String action = scan.next(); 21 | if (action.equals("Insert")) { 22 | int index = scan.nextInt(); 23 | int value = scan.nextInt(); 24 | list.add(index, value); 25 | } else { // "Delete" 26 | int index = scan.nextInt(); 27 | list.remove(index); 28 | } 29 | } 30 | scan.close(); 31 | 32 | /* Print our updated Linked List */ 33 | for (Integer num : list) { 34 | System.out.print(num + " "); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/Algorithms/Sorting - Comparator/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.*; 4 | 5 | class Checker implements Comparator { 6 | @Override 7 | public int compare(Player p1, Player p2) { 8 | if (p1.score == p2.score) { 9 | return p1.name.compareTo(p2.name); 10 | } else { 11 | return p2.score - p1.score; // descending order 12 | } 13 | } 14 | } 15 | 16 | class Player { 17 | String name; 18 | int score; 19 | 20 | Player(String name, int score) { 21 | this.name = name; 22 | this.score = score; 23 | } 24 | } 25 | 26 | class Solution { 27 | public static void main(String[] args) { 28 | Scanner scan = new Scanner(System.in); 29 | int n = scan.nextInt(); 30 | 31 | Player[] player = new Player[n]; 32 | Checker checker = new Checker(); 33 | 34 | for (int i = 0; i < n; i++) { 35 | player[i] = new Player(scan.next(), scan.nextInt()); 36 | } 37 | scan.close(); 38 | 39 | Arrays.sort(player, checker); 40 | for (int i = 0; i < player.length; i++) { 41 | System.out.printf("%s %s\n", player[i].name, player[i].score); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Java/Data Structures/Java Map/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.io.BufferedReader; 4 | import java.io.InputStreamReader; 5 | import java.io.IOException; 6 | import java.util.HashMap; 7 | 8 | /* BufferedReader is used instead of Scanner since it's faster and 9 | won't time out on HackerRank test cases when using Java8 */ 10 | class Solution { 11 | public static void main(String[] args) throws IOException { 12 | /* Save input as entries in a HashMap */ 13 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 14 | int n = Integer.parseInt(br.readLine()); 15 | HashMap map = new HashMap(); 16 | while (n-- > 0) { 17 | String name = br.readLine(); 18 | int phone = Integer.parseInt(br.readLine()); 19 | map.put(name, phone); 20 | } 21 | 22 | /* Read each query and check if its in our HashMap */ 23 | String s; 24 | while((s = br.readLine()) != null) { 25 | if (map.containsKey(s)) { 26 | System.out.println(s + "=" + map.get(s)); 27 | } else { 28 | System.out.println("Not found"); 29 | } 30 | } 31 | 32 | br.close(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Java/Introduction/Java Currency Formatter/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.text.NumberFormat; 5 | import java.util.Locale; 6 | 7 | public class Solution { 8 | public static void main(String[] args) { 9 | /* Save input */ 10 | Scanner scan = new Scanner(System.in); 11 | double payment = scan.nextDouble(); 12 | scan.close(); 13 | 14 | /* Create custom Locale for India - I used the "IANA Language Subtag Registry" to find India's country code */ 15 | Locale indiaLocale = new Locale("en", "IN"); 16 | 17 | /* Create NumberFormats using Locales */ 18 | NumberFormat us = NumberFormat.getCurrencyInstance(Locale.US); 19 | NumberFormat india = NumberFormat.getCurrencyInstance(indiaLocale); 20 | NumberFormat china = NumberFormat.getCurrencyInstance(Locale.CHINA); 21 | NumberFormat france = NumberFormat.getCurrencyInstance(Locale.FRANCE); 22 | 23 | /* Print output */ 24 | System.out.println("US: " + us.format(payment)); 25 | System.out.println("India: " + india.format(payment)); 26 | System.out.println("China: " + china.format(payment)); 27 | System.out.println("France: " + france.format(payment)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /10 Days of Statistics/Day 4 - Binomial Distribution I/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | public class Solution { 4 | public static void main(String[] args) { 5 | double ratio = 1.09; // hardcoded value 6 | double p = ratio / (1 + ratio); 7 | int n = 6; 8 | 9 | /* Calculate result */ 10 | double result = 0; 11 | for (int x = 3; x <= n; x++) { 12 | result += binomial(n, x, p); 13 | } 14 | System.out.format("%.3f", result); 15 | } 16 | 17 | private static Double binomial(int n, int x, double p) { 18 | if (p < 0 || p > 1 || n < 0 || x < 0 || x > n) { 19 | return null; 20 | } 21 | return combinations(n, x) * Math.pow(p, x) * Math.pow(1 - p, n - x); 22 | } 23 | 24 | private static Long combinations(int n, int x) { 25 | if (n < 0 || x < 0 || x > n) { 26 | return null; 27 | } 28 | return factorial(n) / (factorial(x) * factorial(n - x)); 29 | } 30 | 31 | private static Long factorial(int n) { 32 | if (n < 0) { 33 | return null; 34 | } 35 | long result = 1; 36 | while (n > 0) { 37 | result *= n--; 38 | } 39 | return result; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Counting Valleys/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | // Idea: Keep track of your "level", which is how far above or below sea level you are. 6 | // If you ever take a step up to sea level, you just completed walking through a valley. 7 | 8 | // Time Complexity: O(n) 9 | public class Solution { 10 | public static void main(String[] args) { 11 | /* Save input */ 12 | Scanner scan = new Scanner(System.in); 13 | scan.nextLine(); // gets rid of 1st line 14 | String str = scan.nextLine(); // String is of size "n" 15 | scan.close(); 16 | 17 | System.out.println(countValleys(str)); 18 | } 19 | 20 | private static int countValleys(String str) { 21 | int level = 0; 22 | int numValleys = 0; 23 | for (int i = 0; i < str.length(); i++) { 24 | char ch = str.charAt(i); 25 | if (ch == 'U') { 26 | level++; 27 | if (level == 0) { 28 | numValleys++; // since we just stepped up to sea level 29 | } 30 | } else if (ch == 'D') { 31 | level--; 32 | } 33 | } 34 | return numValleys; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/Data Structures/Strings - Making Anagrams/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | private static final int NUM_LETTERS = 26; // we assume lower-case letters only 7 | 8 | private static int createFilledArray(String first, String second) { 9 | /* For each string, create an array of the count of each character */ 10 | int [] array1 = createFilledArray(first); 11 | int [] array2 = createFilledArray(second); 12 | 13 | /* Count number of deletions we need to make the Strings anagrams of each other */ 14 | int deletions = 0; 15 | for (int i = 0; i < NUM_LETTERS; i++) { 16 | deletions += Math.abs(array1[i] - array2[i]); 17 | } 18 | return deletions; 19 | } 20 | 21 | /* Creates an array with the count of each character */ 22 | private static int [] createFilledArray(String str) { 23 | int [] array = new int[NUM_LETTERS]; 24 | for (int i = 0; i < str.length(); i++) { 25 | char ch = str.charAt(i); 26 | array[ch - 'a']++; 27 | } 28 | return array; 29 | } 30 | } 31 | 32 | // Discuss on HackerRank: https://www.hackerrank.com/challenges/ctci-making-anagrams/forum/comments/246741 33 | -------------------------------------------------------------------------------- /30 Days of Code/Day 04 - Class vs. Instance/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | 6 | public class Person { 7 | private int age; 8 | 9 | public Person(int initialAge) { 10 | age = initialAge; 11 | if (age < 0) { 12 | System.out.println("Age is not valid, setting age to 0."); 13 | age = 0; 14 | } 15 | } 16 | 17 | public void amIOld() { 18 | if (age < 13) { 19 | System.out.println("You are young."); 20 | } else if (age >= 13 && age < 18) { 21 | System.out.println("You are a teenager."); 22 | } else { 23 | System.out.println("You are old."); 24 | } 25 | } 26 | 27 | public void yearPasses() { 28 | age++; 29 | } 30 | 31 | public static void main(String[] args) { 32 | Scanner sc = new Scanner(System.in); 33 | int T = sc.nextInt(); 34 | for (int i = 0; i < T; i++) { 35 | int age = sc.nextInt(); 36 | Person p = new Person(age); 37 | p.amIOld(); 38 | for (int j = 0; j < 3; j++) { 39 | p.yearPasses(); 40 | } 41 | p.amIOld(); 42 | System.out.println(); 43 | } 44 | sc.close(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Picking Numbers/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | // Algorithm: 4 | // 1 - Notice there is a special restriction on the range of values in the array: values are between 0 and 100. 5 | // 2 - Since the order of elements in our array does not matter, we can just keep the counts of each number. 6 | // 3 - Create a new 100-element "counts" array to store the counts of each number. 7 | // 4 - In our "counts" array, the adjacent pair with the largest sum is our final solution. 8 | // 5 - This is because the original numbers represented by the 2 adjacent slots in counts[] can be used to create a 9 | // maximal solution 10 | 11 | // Time complexity: O(n) 12 | 13 | public static int pickingNumbers(List array) { 14 | final int MAX_VALUE = 100; 15 | 16 | /* Save counts of each number */ 17 | int[] counts = new int[MAX_VALUE]; 18 | for (int num : array) { 19 | counts[num]++; 20 | } 21 | 22 | /* Find adjacent pair with largest sum */ 23 | int max = 2; 24 | for (int i = 1; i < 100; i++) { 25 | int adjacentSum = counts[i] + counts[i-1]; 26 | max = Math.max(max, adjacentSum); 27 | } 28 | return max; 29 | } 30 | 31 | // Discuss on HackerRank: https://www.hackerrank.com/challenges/picking-numbers/forum/comments/362225 32 | -------------------------------------------------------------------------------- /Algorithms/Strings/Weighted Uniform Strings/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.HashSet; 5 | 6 | // Traverse the string just 1 time. Save the weights of every possible uniform substring in a HashSet. 7 | 8 | // Time complexity: O(n) 9 | // Space complexity: O(n) 10 | 11 | public class Solution { 12 | public static void main(String[] args) { 13 | Scanner scan = new Scanner(System.in); 14 | String str = scan.next(); 15 | int n = scan.nextInt(); 16 | HashSet weights = getWeights(str); 17 | while (n-- > 0) { 18 | int x = scan.nextInt(); 19 | System.out.println(weights.contains(x) ? "Yes" : "No"); 20 | } 21 | scan.close(); 22 | } 23 | 24 | private static HashSet getWeights(String str) { 25 | HashSet weights = new HashSet(); 26 | int weight = 0; 27 | char prev = ' '; // so it doesn't match 1st character 28 | for (int i = 0; i < str.length(); i++) { 29 | char curr = str.charAt(i); 30 | if (curr != prev) { 31 | weight = 0; 32 | } 33 | weight += curr - 'a' + 1; 34 | weights.add(weight); 35 | prev = curr; 36 | } 37 | return weights; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /30 Days of Code/Day 26 - Nested Logic/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.time.LocalDate; 5 | 6 | public class Solution { 7 | public static void main(String[] args) { 8 | /* Read and save input as LocalDates */ 9 | Scanner scan = new Scanner(System.in); 10 | LocalDate returnDate = readDate(scan); 11 | LocalDate expectDate = readDate(scan); 12 | scan.close(); 13 | 14 | /* Calculate fine */ 15 | int fine; 16 | if (returnDate.isEqual(expectDate) || returnDate.isBefore(expectDate)) { 17 | fine = 0; 18 | } else if (returnDate.getMonth() == expectDate.getMonth() && returnDate.getYear() == expectDate.getYear()) { 19 | fine = 15 * (returnDate.getDayOfMonth() - expectDate.getDayOfMonth()); 20 | } else if (returnDate.getYear() == expectDate.getYear()) { 21 | fine = 500 * (returnDate.getMonthValue() - expectDate.getMonthValue()); 22 | } else { 23 | fine = 10000; 24 | } 25 | System.out.println(fine); 26 | } 27 | 28 | private static LocalDate readDate(Scanner scan) { 29 | int day = scan.nextInt(); 30 | int month = scan.nextInt(); 31 | int year = scan.nextInt(); 32 | return LocalDate.of(year, month, day); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /General Programming/Object-oriented Programming/Class vs. Instance/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | 6 | public class Person { 7 | private int age; 8 | 9 | public Person(int initialAge) { 10 | age = initialAge; 11 | if (age < 0) { 12 | System.out.println("Age is not valid, setting age to 0."); 13 | age = 0; 14 | } 15 | } 16 | 17 | public void amIOld() { 18 | if (age < 13) { 19 | System.out.println("You are young."); 20 | } else if (age >= 13 && age < 18) { 21 | System.out.println("You are a teenager."); 22 | } else { 23 | System.out.println("You are old."); 24 | } 25 | } 26 | 27 | public void yearPasses() { 28 | age++; 29 | } 30 | 31 | public static void main(String[] args) { 32 | Scanner sc = new Scanner(System.in); 33 | int T = sc.nextInt(); 34 | for (int i = 0; i < T; i++) { 35 | int age = sc.nextInt(); 36 | Person p = new Person(age); 37 | p.amIOld(); 38 | for (int j = 0; j < 3; j++) { 39 | p.yearPasses(); 40 | } 41 | p.amIOld(); 42 | System.out.println(); 43 | } 44 | sc.close(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Java/BigNumber/Java BigDecimal/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.math.BigDecimal; 4 | import java.util.*; 5 | 6 | class Solution { 7 | public static void main(String []args) { 8 | //Input 9 | Scanner sc = new Scanner(System.in); 10 | int n = sc.nextInt(); 11 | String [] s = new String[n+2]; 12 | for (int i = 0; i < n; i++) { 13 | s[i] = sc.next(); 14 | } 15 | sc.close(); 16 | 17 | // We want to sort in descending order while preserving the contents 18 | // of each String. A comparator can achieve this for us. We convert 19 | // to BigDecimal inside our comparator so that the change is not 20 | // permanent and our String's form for each number is preserved. 21 | Comparator customComparator = new Comparator() { 22 | @Override 23 | public int compare(String s1, String s2) { 24 | BigDecimal a = new BigDecimal(s1); 25 | BigDecimal b = new BigDecimal(s2); 26 | return b.compareTo(a); // descending order 27 | } 28 | }; 29 | 30 | Arrays.sort(s, 0, n, customComparator); 31 | 32 | //Output 33 | for (int i = 0; i < n; i++) { 34 | System.out.println(s[i]); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Birthday Cake Candles/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.Arrays; 5 | 6 | // Time Complexity: O(n) 7 | // Space Complexity: O(n) to save the input. 8 | // You can reduce the space complexity to O(1) by omitting the array and 9 | // working with the input directly, but it will make the code less modular 10 | 11 | public class Solution { 12 | static int cakeCandles(int[] candles) { 13 | int tallest = 0; 14 | int count = 0; 15 | for (int candle : candles) { 16 | if (candle > tallest) { 17 | tallest = candle; 18 | count = 1; 19 | } else if (tallest == candle) { 20 | count++; 21 | } 22 | } 23 | return count; 24 | } 25 | 26 | public static void main(String[] args) { 27 | /* Save input */ 28 | Scanner scan = new Scanner(System.in); 29 | int n = scan.nextInt(); 30 | int[] candles = new int[n]; 31 | for (int i = 0; i < n; i++) { 32 | candles[i] = scan.nextInt(); 33 | } 34 | scan.close(); 35 | 36 | /* Get num candles blown out */ 37 | int result = cakeCandles(candles); 38 | System.out.println(result); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /10 Days of Statistics/Day 4 - Geometric Distribution II/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | public static void main(String[] args) { 7 | /* Save input */ 8 | Scanner scan = new Scanner(System.in); 9 | int numerator = scan.nextInt(); 10 | int denominator = scan.nextInt(); 11 | int n = scan.nextInt(); 12 | scan.close(); 13 | 14 | /* Geometric Series */ 15 | double p = (double) numerator / denominator; 16 | double result = 0; 17 | for (int i = 1; i <= 5; i++) { 18 | result += geometric(i, p); 19 | } 20 | System.out.format("%.3f", result); 21 | } 22 | 23 | private static double geometric (int n, double p) { 24 | return Math.pow(1 - p, n - 1) * p; 25 | } 26 | 27 | private static Long combinations(int n, int x) { 28 | if (n < 0 || x < 0 || x > n) { 29 | return null; 30 | } 31 | return factorial(n) / (factorial(x) * factorial(n - x)); 32 | } 33 | 34 | private static Long factorial(int n) { 35 | if (n < 0) { 36 | return null; 37 | } 38 | long result = 1; 39 | while (n > 0) { 40 | result *= n--; 41 | } 42 | return result; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Divisible Sum Pairs/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | /* 4 | 5 | Time Complexity: O(n + k) 6 | Space Complexity: O(k) 7 | 8 | We keep track of the mod values in buckets for each number we read. We can do this 9 | by creating k buckets where bucket "i" counts each number "n" where n % k = i. 10 | 11 | Notice that each bucket has a corresponding "complement" bucket. That is, if we take 12 | the mod value of one bucket and add it to the mod value of another bucket, we get "k". 13 | 14 | Bucket Complement Bucket 15 | ------ ----------------- 16 | 0 0 17 | 1 k-1 18 | 2 k-2 19 | 3 k-3 20 | ... 21 | k-3 3 22 | k-2 2 23 | k-1 1 24 | 25 | As we come across each number, we find its corresponding complement bucket. Each number in 26 | this complement bucket can be paired with our original number to create a sum divisible by *k* 27 | 28 | */ 29 | 30 | static int divisibleSumPairs(int n, int k, int[] ar) { 31 | int [] bucket = new int[k]; 32 | int count = 0; 33 | for (int value : ar) { 34 | int modValue = value % k; 35 | count += bucket[(k - modValue) % k]; // adds # of elements in complement bucket. 36 | bucket[modValue]++; // saves in bucket. 37 | } 38 | return count; 39 | } 40 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Library Fine/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.time.LocalDate; 5 | 6 | public class Solution { 7 | public static void main(String[] args) { 8 | /* Read and save input as LocalDates */ 9 | Scanner scan = new Scanner(System.in); 10 | LocalDate returnDate = readDate(scan); 11 | LocalDate expectDate = readDate(scan); 12 | scan.close(); 13 | 14 | /* Calculate fine */ 15 | int fine; 16 | if (returnDate.isEqual(expectDate) || returnDate.isBefore(expectDate)) { 17 | fine = 0; 18 | } else if (returnDate.getMonth() == expectDate.getMonth() && returnDate.getYear() == expectDate.getYear()) { 19 | fine = 15 * (returnDate.getDayOfMonth() - expectDate.getDayOfMonth()); 20 | } else if (returnDate.getYear() == expectDate.getYear()) { 21 | fine = 500 * (returnDate.getMonthValue() - expectDate.getMonthValue()); 22 | } else { 23 | fine = 10000; 24 | } 25 | System.out.println(fine); 26 | } 27 | 28 | private static LocalDate readDate(Scanner scan) { 29 | int day = scan.nextInt(); 30 | int month = scan.nextInt(); 31 | int year = scan.nextInt(); 32 | return LocalDate.of(year, month, day); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Algorithms/Bit Manipulation/Sum vs XOR/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | // XOR represents binary addition without the "carry" for each digit. We want to see 6 | // how many values of x that will give us n+x = n^x, which is when XOR is the same as 7 | // ADDITION. This happens when there are no "carries". To make sure there are no 8 | // carries, for each digit in "n" that is a 1, we must have the corresponding digit in 9 | // "x" be a 0. For each digit in "n" that is a 0, we can have the corresponding digit 10 | // in "x" be either 0 or 1. Now we calculate the number of possibilities for "x" by 11 | // counting the number of 0s in "n" (up to the most significant 1 in n), and doing 12 | // 2^(number of 0s) (where ^ is exponentiation in this case) to count all combinations. 13 | 14 | static long sumXor(long n) { 15 | /* Calculate number of "x" values that will satisfy n+x = n^x */ 16 | int zeroes = numZeroes(n); 17 | return 1L << zeroes; // same as (long) Math.pow(2, zeroes); 18 | } 19 | 20 | private static int numZeroes(long n) { 21 | int count = 0; 22 | while (n > 0) { 23 | if ((n & 1) == 0) { 24 | count++; 25 | } 26 | n >>= 1; // divides by 2 27 | } 28 | return count; 29 | } 30 | 31 | // Discuss on HackerRank: https://www.hackerrank.com/challenges/sum-vs-xor/forum/comments/284300 32 | -------------------------------------------------------------------------------- /Implementation/Brute Force/Modified Kaprekar Numbers/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | // Brute-force solution 6 | public class Solution { 7 | public static void main(String[] args) { 8 | Scanner scan = new Scanner(System.in); 9 | int p = scan.nextInt(); 10 | int q = scan.nextInt(); 11 | scan.close(); 12 | 13 | boolean foundKaprekar = false; 14 | for (int num = p; num <= q; num++) { 15 | if (isKaprekar(num)) { 16 | foundKaprekar = true; 17 | } 18 | } 19 | if (!foundKaprekar) { 20 | System.out.println("INVALID RANGE"); 21 | } 22 | } 23 | 24 | private static boolean isKaprekar(int num) { 25 | long squared = (long) num * num; // multiplying 2 ints without typecast could cause overflow 26 | String str = String.valueOf(squared); 27 | String left = str.substring(0, str.length() / 2); 28 | String right = str.substring(str.length() / 2); 29 | int numL = (left.isEmpty()) ? 0 : Integer.parseInt(left); 30 | int numR = (right.isEmpty()) ? 0 : Integer.parseInt(right); 31 | if (numL + numR == num) { 32 | System.out.print(num + " "); 33 | return true; 34 | } else { 35 | return false; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Algorithms/Search/Ice Cream Parlor/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.HashMap; 5 | 6 | // Time Complexity: O(n) 7 | // Space Complexity: O(n) 8 | public class Solution { 9 | public static void main(String[] args) { 10 | Scanner scan = new Scanner(System.in); 11 | int t = scan.nextInt(); 12 | while (t-- > 0) { 13 | int m = scan.nextInt(); 14 | int n = scan.nextInt(); 15 | int [] costs = new int[n]; 16 | for (int i = 0; i < n; i++) { 17 | costs[i] = scan.nextInt(); 18 | } 19 | buyIceCream(costs, m); 20 | } 21 | scan.close(); 22 | } 23 | 24 | public static void buyIceCream(int [] costs, int money) { 25 | HashMap map = new HashMap(); // key = cost, value = ice cream ID 26 | for (int i = 0; i < costs.length; i++) { 27 | int icecreamID = i + 1; 28 | int cost = costs[i]; 29 | 30 | /* Find 2 flavors to buy that sum to "money" */ 31 | int otherCost = money - cost; 32 | if (map.containsKey(otherCost)) { 33 | System.out.println(map.get(otherCost) + " " + icecreamID); 34 | } 35 | 36 | map.putIfAbsent(cost, icecreamID); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Apple and Orange/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | // Time Complexity: O(m + n) 6 | // Space Complexity: O(1) 7 | public class Solution { 8 | public static void main(String[] args) { 9 | /* Save input */ 10 | Scanner scan = new Scanner(System.in); 11 | int s = scan.nextInt(); 12 | int t = scan.nextInt(); 13 | int a = scan.nextInt(); 14 | int b = scan.nextInt(); 15 | int m = scan.nextInt(); 16 | int n = scan.nextInt(); 17 | 18 | /* Calculate # of apples that fall on house */ 19 | int applesOnHouse = 0; 20 | for (int i = 0; i < m; i++) { 21 | int applePosition = a + scan.nextInt(); 22 | if (applePosition >= s && applePosition <= t) { 23 | applesOnHouse++; 24 | } 25 | } 26 | System.out.println(applesOnHouse); 27 | 28 | /* Calculate # of oranges that fall on house */ 29 | int orangesOnHouse = 0; 30 | for (int i = 0; i < n; i++) { 31 | int orangePosition = b + scan.nextInt(); 32 | if (orangePosition >= s && orangePosition <= t) { 33 | orangesOnHouse++; 34 | } 35 | } 36 | System.out.println(orangesOnHouse); 37 | 38 | scan.close(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /30 Days of Code/Day 21 - Generics/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.*; 4 | 5 | class Printer { 6 | /** 7 | * Method Name: printArray 8 | * Print each element of the generic array on a new line. Do not return anything. 9 | * @param A generic array 10 | **/ 11 | public void printArray(T[] array) { 12 | for (T item : array) { 13 | System.out.println(item); 14 | } 15 | } 16 | } 17 | 18 | public class Generics { 19 | public static void main(String args[]){ 20 | Scanner scanner = new Scanner(System.in); 21 | int n = scanner.nextInt(); 22 | Integer[] intArray = new Integer[n]; 23 | for (int i = 0; i < n; i++) { 24 | intArray[i] = scanner.nextInt(); 25 | } 26 | 27 | n = scanner.nextInt(); 28 | String[] stringArray = new String[n]; 29 | for (int i = 0; i < n; i++) { 30 | stringArray[i] = scanner.next(); 31 | } 32 | 33 | Printer intPrinter = new Printer(); 34 | Printer stringPrinter = new Printer(); 35 | intPrinter.printArray( intArray ); 36 | stringPrinter.printArray( stringArray ); 37 | if (Printer.class.getDeclaredMethods().length > 1) { 38 | System.out.println("The Printer class should only have 1 method named printArray."); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Cracking the Coding Interview/Algorithms/Binary Search - Ice Cream Parlor/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.HashMap; 5 | 6 | // Time Complexity: O(n) 7 | // Space Complexity: O(n) 8 | public class Solution { 9 | public static void main(String[] args) { 10 | Scanner scan = new Scanner(System.in); 11 | int t = scan.nextInt(); 12 | while (t-- > 0) { 13 | int m = scan.nextInt(); 14 | int n = scan.nextInt(); 15 | int [] costs = new int[n]; 16 | for (int i = 0; i < n; i++) { 17 | costs[i] = scan.nextInt(); 18 | } 19 | buyIceCream(costs, m); 20 | } 21 | scan.close(); 22 | } 23 | 24 | public static void buyIceCream(int [] costs, int money) { 25 | HashMap map = new HashMap(); // key = cost, value = ice cream ID 26 | for (int i = 0; i < costs.length; i++) { 27 | int icecreamID = i + 1; 28 | int cost = costs[i]; 29 | 30 | /* Find 2 flavors to buy that sum to "money" */ 31 | int otherCost = money - cost; 32 | if (map.containsKey(otherCost)) { 33 | System.out.println(map.get(otherCost) + " " + icecreamID); 34 | } 35 | 36 | map.putIfAbsent(cost, icecreamID); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Kangaroo/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | // Case 1: v1 <= v2 6 | // In this case, kangaroo 1 can never catch up to kangaroo 2 7 | 8 | // Case2 : v1 > v2 9 | // x2 - x1 represents the distance between the 2 kangaroos 10 | // 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) 11 | // 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. 12 | 13 | public class Solution { 14 | public static void main(String[] args) { 15 | /* Save input */ 16 | Scanner scan = new Scanner(System.in); 17 | int x1 = scan.nextInt(); 18 | int v1 = scan.nextInt(); 19 | int x2 = scan.nextInt(); 20 | int v2 = scan.nextInt(); 21 | scan.close(); 22 | 23 | /* See if kangaroos meet each other */ 24 | if (v1 <= v2) { 25 | System.out.println("NO"); 26 | } else { 27 | boolean kangaroosMeet = (x2 - x1) % (v2 - v1) == 0; 28 | System.out.println(kangaroosMeet ? "YES" : "NO"); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /30 Days of Code/Day 19 - Interfaces/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | 6 | interface AdvancedArithmetic { 7 | int divisorSum(int n); 8 | } 9 | 10 | class Calculator implements AdvancedArithmetic { 11 | // Runtime: O(n^(1/2)) 12 | // Space Complexity: O(1) 13 | public int divisorSum(int n) { 14 | int sum = 0; 15 | int sqrt = (int) Math.sqrt(n); 16 | 17 | // Small optimization: if n is odd, we can't have even numbers as divisors 18 | int stepSize = (n % 2 == 1) ? 2 : 1; 19 | 20 | for (int i = 1; i <= sqrt; i += stepSize) { 21 | if (n % i == 0) { // if "i" is a divisor 22 | sum += i + n/i; // add both divisors 23 | } 24 | } 25 | 26 | // If sqrt is a divisor, we should only count it once 27 | if (sqrt * sqrt == n) { 28 | sum -= sqrt; 29 | } 30 | return sum; 31 | } 32 | } 33 | 34 | class Solution { 35 | public static void main(String[] args) { 36 | Scanner scan = new Scanner(System.in); 37 | int n = scan.nextInt(); 38 | scan.close(); 39 | 40 | AdvancedArithmetic myCalculator = new Calculator(); 41 | int sum = myCalculator.divisorSum(n); 42 | System.out.println("I implemented: " + myCalculator.getClass().getInterfaces()[0].getName() ); 43 | System.out.println(sum); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Data Structures/Stacks/Maximum Element/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.Stack; 5 | 6 | // All 3 queries (1:push, 2:delete, 3:print max) are all O(1) runtime 7 | public class Solution { 8 | public static void main(String[] args) { 9 | Stack stack = new Stack(); 10 | Stack maxStack = new Stack(); // keeps track of maximums 11 | 12 | Scanner scan = new Scanner(System.in); 13 | int N = scan.nextInt(); 14 | 15 | for (int i = 0; i < N; i++) { 16 | int query = scan.nextInt(); 17 | switch (query) { 18 | case 1: 19 | int x = scan.nextInt(); 20 | stack.push(x); 21 | if (maxStack.isEmpty() || x >= maxStack.peek()) { 22 | maxStack.push(x); 23 | } 24 | break; 25 | case 2: 26 | int poppedValue = stack.pop(); 27 | if (poppedValue == maxStack.peek()) { 28 | maxStack.pop(); 29 | } 30 | break; 31 | case 3: 32 | System.out.println(maxStack.peek()); 33 | break; 34 | default: 35 | break; 36 | } 37 | } 38 | scan.close(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /10 Days of Statistics/Day 4 - Binomial Distribution II/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | public class Solution { 4 | public static void main(String[] args) { 5 | /* Values given in problem statement */ 6 | double p = 0.12; 7 | int n = 10; 8 | 9 | /* "No more than 2 rejects" */ 10 | double result = 0; 11 | for (int x = 0; x <= 2; x++) { 12 | result += binomial(n, x, p); 13 | } 14 | System.out.format("%.3f%n", result); 15 | 16 | /* "At least 2 rejects" */ 17 | result = 1 - binomial(n, 0, p) - binomial(n, 1, p); 18 | System.out.format("%.3f%n", result); 19 | } 20 | 21 | private static Double binomial(int n, int x, double p) { 22 | if (p < 0 || p > 1 || n < 0 || x < 0 || x > n) { 23 | return null; 24 | } 25 | return combinations(n, x) * Math.pow(p, x) * Math.pow(1 - p, n - x); 26 | } 27 | 28 | private static Long combinations(int n, int x) { 29 | if (n < 0 || x < 0 || x > n) { 30 | return null; 31 | } 32 | return factorial(n) / (factorial(x) * factorial(n - x)); 33 | } 34 | 35 | private static Long factorial(int n) { 36 | if (n < 0) { 37 | return null; 38 | } 39 | long result = 1; 40 | while (n > 0) { 41 | result *= n--; 42 | } 43 | return result; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /30 Days of Code/Day 01 - Data Types/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | import java.text.*; 6 | import java.math.*; 7 | import java.util.regex.*; 8 | 9 | public class Solution { 10 | public static void main(String[] args) { 11 | int i = 4; 12 | double d = 4.0; 13 | String s = "HackerRank "; 14 | 15 | Scanner scan = new Scanner(System.in); 16 | 17 | /* Declare second integer, double, and String variables. */ 18 | int myInt; 19 | double myDouble; 20 | String myString; 21 | 22 | /* Read and save an integer, double, and String to your variables.*/ 23 | // Note: If you have trouble reading the entire String, please go back and review the Tutorial closely. 24 | myInt = scan.nextInt(); 25 | myDouble = scan.nextDouble(); 26 | scan.nextLine(); // gets rid of newline at end of line 2 of input 27 | myString = scan.nextLine(); 28 | 29 | /* Print the sum of both integer variables on a new line. */ 30 | System.out.println(i + myInt); 31 | 32 | /* Print the sum of the double variables on a new line. */ 33 | System.out.println(d + myDouble); 34 | 35 | /* Concatenate and print the String variables on a new line; 36 | the 's' variable above should be printed first. */ 37 | System.out.println(s + myString); 38 | 39 | scan.close(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Java/Strings/Java Anagrams/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | 6 | public class Solution { 7 | // Time Complexity: O(n) using a HashMap 8 | // Space Complexity: O(n) 9 | static boolean isAnagram(String a, String b) { 10 | if (a == null || b == null || a.length() != b.length()) { 11 | return false; 12 | } 13 | a = a.toLowerCase(); 14 | b = b.toLowerCase(); 15 | HashMap map = new HashMap(); 16 | 17 | /* Fill HashMap with 1st String */ 18 | for (int i = 0; i < a.length(); i++) { 19 | char ch = a.charAt(i); 20 | map.merge(ch, 1, Integer::sum); 21 | } 22 | 23 | /* Compare 2nd String to 1st String's HashMap */ 24 | for (int i = 0; i < b.length(); i++) { 25 | char ch = b.charAt(i); 26 | if (map.containsKey(ch) && map.get(ch) > 0) { 27 | map.put(ch, map.get(ch) - 1); 28 | } else { 29 | return false; 30 | } 31 | } 32 | return true; 33 | } 34 | 35 | public static void main(String[] args) { 36 | Scanner scan = new Scanner(System.in); 37 | String a = scan.next(); 38 | String b = scan.next(); 39 | scan.close(); 40 | boolean ret = isAnagram(a, b); 41 | System.out.println( (ret) ? "Anagrams" : "Not Anagrams" ); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /General Programming/Basic Programming/Fair Rations/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | // Idea: Loop through the array. For every person with an odd number of bread, we distribute 1 bread to current 6 | // person, and 1 bread to next person. If last person has odd number of bread, there is no solution. 7 | // Otherwise, everyone has even number of bread, and we print how much bread was distributed. 8 | 9 | // Time Complexity: O(n) 10 | public class Solution { 11 | public static void main(String[] args) { 12 | Scanner scan = new Scanner(System.in); 13 | int N = scan.nextInt(); 14 | int array[] = new int[N]; 15 | for (int i = 0; i < N; i++) { 16 | array[i] = scan.nextInt(); 17 | } 18 | scan.close(); 19 | giveBread(array); 20 | } 21 | 22 | static void giveBread(int[] array) { 23 | int breadGiven = 0; 24 | for (int i = 0; i < array.length - 1; i++) { 25 | if (array[i] % 2 == 1) { 26 | array[i]++; // give bread to current person 27 | array[i+1]++; // give bread to next person 28 | breadGiven+= 2; 29 | } 30 | } 31 | if (array[array.length - 1] % 2 == 1) { 32 | System.out.println("NO"); // Array has odd parity. No solution exists 33 | } else { 34 | System.out.println(breadGiven); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Implementation/Brute Force/Making Anagrams/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | 5 | public class Solution { 6 | private static final int NUM_LETTERS = 26; // we assume lower-case letters only 7 | 8 | public static void main(String[] args) { 9 | /* Save input */ 10 | Scanner scan = new Scanner(System.in); 11 | String a = scan.next(); 12 | String b = scan.next(); 13 | scan.close(); 14 | 15 | System.out.println(numberNeeded(a, b)); 16 | } 17 | 18 | private static int numberNeeded(String first, String second) { 19 | /* For each string, create an array of the count of each character */ 20 | int [] array1 = createFilledArray(first); 21 | int [] array2 = createFilledArray(second); 22 | 23 | /* Count number of deletions we need to make the Strings anagrams of each other */ 24 | int deletions = 0; 25 | for (int i = 0; i < NUM_LETTERS; i++) { 26 | deletions += Math.abs(array1[i] - array2[i]); 27 | } 28 | return deletions; 29 | } 30 | 31 | /* Creates an array with the count of each character */ 32 | private static int [] createFilledArray(String str) { 33 | int [] array = new int[NUM_LETTERS]; 34 | for (int i = 0; i < str.length(); i++) { 35 | char ch = str.charAt(i); 36 | array[ch - 'a']++; 37 | } 38 | return array; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Algorithms/Greedy/Grid Challenge/Solution.java: -------------------------------------------------------------------------------- 1 | // github.com/RodneyShag 2 | 3 | import java.util.Scanner; 4 | import java.util.Arrays; 5 | 6 | public class Solution { 7 | public static void main(String[] args) { 8 | Scanner scan = new Scanner(System.in); 9 | int T = scan.nextInt(); 10 | while (T-- > 0) { 11 | int N = scan.nextInt(); 12 | char [][] grid = new char[N][N]; 13 | for (int i = 0; i < N; i++) { 14 | String str = scan.next(); 15 | for (int j = 0; j < str.length(); j++) { 16 | grid[i][j] = str.charAt(j); 17 | } 18 | } 19 | System.out.println(canConvert(grid) ? "YES" : "NO"); 20 | } 21 | scan.close(); 22 | } 23 | 24 | /* Uses Greedy Approach */ 25 | private static boolean canConvert(char [][] grid) { 26 | /* Sort each row */ 27 | int rows = grid.length; 28 | int cols = grid[0].length; 29 | for (int row = 0; row < rows; row++) { 30 | Arrays.sort(grid[row]); 31 | } 32 | 33 | /* Check columns for lexicographic ordering */ 34 | for (int row = 1; row < rows; row++) { 35 | for (int col = 0; col < cols; col++) { 36 | if (grid[row][col] < grid[row-1][col]) { 37 | return false; 38 | } 39 | } 40 | } 41 | return true; 42 | } 43 | } 44 | 45 | --------------------------------------------------------------------------------