├── .gitignore ├── cses ├── .gitignore ├── Dynamic Programming │ ├── Array Description.java │ ├── Book Shop.java │ ├── Coin Combinations I.java │ ├── Coin Combinations II.java │ ├── Dice Combinations.java │ ├── Edit Distance.java │ ├── Grid Paths.java │ ├── Increasing Subsequence.java │ ├── Minimizing Coins.java │ ├── Money Sums.java │ ├── Rectangle Cutting.java │ ├── Removal game.java │ ├── Removing Digits.java │ └── Two Sets II.java ├── Introductory Problems │ ├── Apple-Division.java │ ├── Bit-Strings.java │ ├── Chessboard-and-Queens.java │ ├── Coin-Piles.java │ ├── Creating-Strings-I.java │ ├── Grid-Paths.java │ ├── Increasing-Array.java │ ├── Missing-Number.java │ ├── Number-Spiral.java │ ├── Palindrome-Reorder.java │ ├── Permutations.java │ ├── Repetitions.java │ ├── Trailing-Zeros.java │ ├── Two-Knights.java │ ├── Two-Sets.java │ └── Weird-Algorithm.java ├── Library │ ├── Copy.java │ ├── IO.java │ ├── Multiset.java │ ├── Numbers.java │ └── Tuple.java ├── Mathematics │ ├── Binomial Coefficients.java │ ├── Candy Lottery.java │ ├── Christmas Party.java │ ├── Common Divisors.java │ ├── Counting Divisors.java │ ├── Creating Strings II.java │ ├── Dice Probability.java │ ├── Distributing Apples.java │ ├── Exponentiation II.java │ ├── Exponentiation.java │ ├── Fibonacci Numbers.java │ ├── Graph Paths I.java │ ├── Grath Paths II.java │ ├── Inversion Probability.java │ ├── Moving Robots.java │ ├── Nim Game I.java │ ├── Nim Game II.java │ ├── Stair Game.java │ ├── Stick Game.java │ ├── Sum of Divisors.java │ └── Throwing Dice.java └── Sorting and Searching │ ├── Apartments.java │ ├── Array-Division.java │ ├── Concert-Tickets.java │ ├── Distinct-Numbers.java │ ├── Factory-Machines.java │ ├── Ferris-Wheel.java │ ├── Maximum Subarray Sum II.java │ ├── Maximum-Subarray-Sum.java │ ├── Movie Festival II.java │ ├── Movie-Festival.java │ ├── Nearest-Smaller-Values.java │ ├── Playlist.java │ ├── Reading-Books.java │ ├── Restaurant-Customers.java │ ├── Room-Allocation.java │ ├── Sliding Cost.java │ ├── Sliding-Median.java │ ├── Stick-Lengths.java │ ├── Subarray-Divisibility.java │ ├── Subarray-Sums-I.java │ ├── Subarray-Sums-II.java │ ├── Sum-of-Four-Values.java │ ├── Sum-of-Three-Values.java │ ├── Sum-of-Two-Values.java │ ├── Tasks-and-Deadlines.java │ ├── Towers.java │ └── Traffic-Lights.java ├── format.sh ├── google-java-format.jar ├── hackerrank ├── algorithms │ ├── bit_manipulation │ │ ├── And-Product.py │ │ ├── Counter-Game.java │ │ ├── Flipping-Bits.java │ │ ├── Lonely-Integer.py │ │ ├── Maximizing-XOR.py │ │ ├── Sum-Vs-Xor.java │ │ ├── The-Great-XOR.go │ │ └── Xor-Sequence.go │ ├── constructive_algorithms │ │ └── Bonetrousle.java │ ├── dp │ │ ├── Abbreviation.java │ │ ├── Bricks-Game.java │ │ ├── Candles-Counting.java │ │ ├── Coin-Change.java │ │ ├── Coins-On-The-Table.java │ │ ├── Equal.go │ │ ├── Fibonacci-Modified.java │ │ ├── Grid-Walking.java │ │ ├── Hacker-Rank-City.java │ │ ├── Hexagonal-Grid.java │ │ ├── Knapsack.java │ │ ├── Lego-Blocks.java │ │ ├── Mandragora-Forest.java │ │ ├── Maximum-Subarray.java │ │ ├── Mr-KMarsh.java │ │ ├── Nikita-And-The-Game.java │ │ ├── Red-John-Is-Back.java │ │ ├── Sam-And-Sub-Strings.java │ │ ├── Sherlock-And-Cost.java │ │ ├── The-Indian-Job.java │ │ ├── The-Longest-Common-Subsequence.java │ │ ├── Vertical-Sticks.py │ │ └── Xor-And-Sum.java │ ├── game_theory │ │ └── Game-Of-Stones.py │ ├── graph_theory │ │ ├── Breadth-First-Search-Shortest-Reach.py │ │ ├── Clique.java │ │ ├── Crab-Graphs.java │ │ ├── Dijkstra-Shortest-Reach.py │ │ ├── Even-Tree.java │ │ ├── Floyd-City-Of-Blinding-Lights.java │ │ ├── Jack-Goes-To-Rapture.go │ │ ├── Jeanies-Route.java │ │ ├── Journey-To-The-Moon.java │ │ ├── Kruskal-MST-Really-Special-Subtree.py │ │ ├── Matrix.java │ │ ├── Minimum-Penalty-Path.java │ │ ├── Prims-MST-Special-Subtree.py │ │ ├── Real-Estate-Broker.java │ │ ├── Roads-And-Libraries.java │ │ ├── Roads-in-HackerLand.java │ │ ├── Rust-And-Murderer.go │ │ ├── Snakes-And-Ladders-The-Quickest-Way-Up.java │ │ ├── Synchronous-Shopping.java │ │ ├── The-Story-of-a-Tree.go │ │ └── Tree-Flow.java │ ├── greedy │ │ ├── Cloudy-Day.java │ │ ├── Greedy-Florist.py │ │ ├── Grid-Challange.py │ │ ├── Largest-Permutation.py │ │ ├── Luck-Balance.py │ │ ├── Minimum-Absolute-Difference-In-An-Array.go │ │ └── Sherlock-And-The-Beast.java │ ├── implementation │ │ ├── Angry-Professor.py │ │ ├── Apple-and-Orange.go │ │ ├── Bigger-Is-Greater.py │ │ ├── Bon-Appetit.py │ │ ├── Cut-The-Sticks.py │ │ ├── Divisible-Sum-Pairs.java │ │ ├── Flat-Land-Space-Stations.py │ │ ├── Grading-Students.go │ │ ├── Jumping-On-The-Clouds-Revisited.py │ │ ├── Jumping-On-The-Clouds.py │ │ ├── Kangoroo.py │ │ ├── Library-Fine.py │ │ ├── Lisas-Workbook.py │ │ ├── Non-Divisible-Sub-Set.py │ │ ├── Organizing-Containers-of-Balls.java │ │ ├── Repeated-String.py │ │ ├── Save-The-Prisoner.py │ │ ├── Sock-Merchant.py │ │ ├── Strange-Counter.py │ │ └── Viral-Advertising.py │ ├── misc │ │ ├── Array-Manipulation.java │ │ ├── Castle-on-the-Grid.java │ │ ├── Crossword-Puzzle.java │ │ ├── DFS-Connected-Cell-in-a-Grid.java │ │ ├── Find-the-nearest-clone.java │ │ ├── Frequency-Queries.java │ │ ├── Friend-Circle-Queries.java │ │ ├── Min-Max-Riddle.java │ │ ├── Minimum-Swaps-2.java │ │ ├── New-Year-Chaos.java │ │ └── Special-Palindrome-Again.java │ ├── np_complete │ │ └── Walking-The-Approximate-Longest-Path.go │ ├── recursion │ │ └── The-Power-Sum.go │ ├── search │ │ ├── Count-Luck.java │ │ ├── Gridland-Metro.java │ │ ├── Hackerland-Radio-Transmitters.go │ │ ├── Ice-Cream-Parlor.rb │ │ ├── Minimum-Loss.go │ │ ├── Missing-Numbers.java │ │ ├── Pairs.py │ │ └── Sherlock-And-Array.py │ ├── sorting │ │ ├── Big-Sorting.go │ │ ├── Closest-Numbers.go │ │ ├── Find-The-Median.java │ │ ├── Fraudulent-Activity-Notifications.java │ │ ├── Intro.py │ │ └── Lilys-Homework.go │ ├── strings │ │ ├── Alternating-Characters.py │ │ ├── Anagram.go │ │ ├── Bear-And-Steady-Gene.java │ │ ├── Beautiful-Binary-String.py │ │ ├── Caesar-Chipher.go │ │ ├── Camel-Case.py │ │ ├── Common-Child.java │ │ ├── Funny-String.py │ │ ├── Gemstones.py │ │ ├── HackerRank-In-A-String.go │ │ ├── Making-Anagrams.go │ │ ├── Mars-Exploration.py │ │ ├── Palindrome-Index.py │ │ ├── Panagrams.py │ │ ├── Richie-Rich.py │ │ ├── Separate-the-Numbers.go │ │ ├── Sherlock-And-Anagrams.java │ │ ├── Sherlock-and-the-Valid-String.go │ │ ├── Super-Reduced-String.py │ │ ├── TheLoveLetterMystery.go │ │ ├── Two-Characters.java │ │ ├── Two-Strings.py │ │ └── Weighted-Uniform-Strings.go │ └── warmup │ │ ├── AVery-Big-Sum.py │ │ ├── Birthday-Cake-Candles.go │ │ ├── Circular-Array-Rotation.py │ │ ├── Compare-The-Triplets.py │ │ ├── Diagonal-Difference.py │ │ ├── Maximum-Perimeter-Triangle.py │ │ ├── Mini-Max-Sum.go │ │ ├── Plus-Minus.py │ │ ├── Simple-Array-Sum.py │ │ ├── Time-Conversion.py │ │ └── staircase.py └── data_structures │ ├── heap │ ├── Find-the-Running-Median.go │ ├── Jesse-and-Cookies.go │ └── Minimum-Average-Waiting-Time.go │ └── queues │ ├── Largest-Rectangle.java │ └── Truck-Tour.py └── leetcode ├── 1-two-sum.py ├── 10-regular-expression-matching.py ├── 108-convert-sorted-array-to-binary-search-tree.py ├── 136-single-number.go ├── 14-longest-common-prefix.py ├── 146-lru-cache.java ├── 162-find-peak-element.py ├── 2-add-two-number.py ├── 226-Invert-Binary-Tree.java ├── 3-longest-substring-without-repeating-characters.py ├── 344-reverse-string.go ├── 4-median-of-two-sorted-arrays.py ├── 406-queue-reconstruction-by-height.go ├── 412-fizz-buzz.go ├── 413-arithmetic-slices.go ├── 419-battleships-in-a-board.go ├── 432-all-oone-data-structure.go ├── 442-find-all-duplicates-in-an-array.go ├── 46-permutations.py ├── 461-hamming-distance.go ├── 463-island-perimeter.go ├── 473-matchsticks-to-square.java ├── 476-number-complement.go ├── 496-next-greater-element-i.go ├── 5-longest-palindromic-substring.py ├── 500-keyboard-row.go ├── 513-find-bottom-left-tree-value.go ├── 515-find-largest-value-in-each-tree-row.go ├── 521-longest-uncommon-subsequence-i.go ├── 53-maximum-subarray.py ├── 535-encode-and-decode-tinyurl.java ├── 537-complex-number-multiplication.go ├── 540-single-element-in-a-sorted-array.go ├── 553-optimal-division.go ├── 556-next-greater-element-iii.java ├── 557-reverse-words-in-a-string-iii.go ├── 561-array-partition-i.go ├── 566-reshape-the-matrix.go ├── 575-distribute-candies.go ├── 6-zigzag-conversion.py ├── 617-merge-two-binary-trees.go ├── 620-not-boring-movies.sql ├── 637-average-of-levels-in-binary-tree.go ├── 647-palindromic-substrings.go ├── 654-maximum-binary-tree.go ├── 657-judge-route-circle.go ├── 669-trim-a-binary-search-tree.go ├── 693-binary-number-with-alternating-bits.go ├── 695-max-area-of-island.java ├── 7-reverse-integer.py ├── 717-1-bit-and-2-bit-characters.go ├── 891-sum-of-subsequence-widths.java ├── 9-palindrome-number.py ├── 924-minimize-malware-spread.java └── 938-range-sum-of-bst.java /.gitignore: -------------------------------------------------------------------------------- 1 | google-java-format.jar 2 | /tmp 3 | /leetcode/test/* 4 | .idea 5 | *Wrapper* 6 | -------------------------------------------------------------------------------- /cses/.gitignore: -------------------------------------------------------------------------------- 1 | current/ 2 | -------------------------------------------------------------------------------- /cses/Introductory Problems/Apple-Division.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Solution { 4 | private static Scanner scanner = new Scanner(System.in); 5 | private static StringBuilder sb = new StringBuilder(); 6 | private static int N; 7 | private static long sum1, sum2, diff; 8 | private static int[] apples; 9 | 10 | private static void readInput() { 11 | N = scanner.nextInt(); 12 | apples = new int[N]; 13 | for (int i = 0; i < N; i++) apples[i] = scanner.nextInt(); 14 | } 15 | 16 | private static void recursive(int i) { 17 | if (i == apples.length) { 18 | diff = Math.min(diff, Math.abs(sum1 - sum2)); 19 | return; 20 | } 21 | 22 | sum1 += apples[i]; 23 | recursive(i + 1); 24 | sum1 -= apples[i]; 25 | 26 | sum2 += apples[i]; 27 | recursive(i + 1); 28 | sum2 -= apples[i]; 29 | } 30 | 31 | private static void solve() { 32 | sum1 = 0; 33 | sum2 = 0; 34 | diff = Integer.MAX_VALUE; 35 | 36 | recursive(0); 37 | 38 | sb.append(diff); 39 | } 40 | 41 | public static void main(String[] args) { 42 | int T = 1; 43 | for (int t = 0; t < T; t++) { 44 | readInput(); 45 | solve(); 46 | sb.append("\n"); 47 | } 48 | System.out.print(sb.toString()); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /cses/Introductory Problems/Bit-Strings.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Solution { 4 | private static Scanner scanner = new Scanner(System.in); 5 | private static StringBuilder sb = new StringBuilder(); 6 | private static int N; 7 | private static long MODULO = 1000000007L; 8 | 9 | private static void readInput() { 10 | N = scanner.nextInt(); 11 | } 12 | 13 | private static void solve() { 14 | long result = 1L; 15 | for (int i = 0; i < N; i++) result = result * 2 % MODULO; 16 | sb.append(result); 17 | } 18 | 19 | public static void main(String[] args) { 20 | int T = 1; 21 | for (int t = 0; t < T; t++) { 22 | readInput(); 23 | solve(); 24 | } 25 | System.out.print(sb.toString()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /cses/Introductory Problems/Chessboard-and-Queens.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Solution { 4 | private static Scanner scanner = new Scanner(System.in); 5 | private static StringBuilder sb = new StringBuilder(); 6 | private static int N = 8; 7 | private static int[][] field = new int[N][N]; 8 | private static int result = 0; 9 | 10 | private static void readInput() { 11 | for (int j = 0; j < N; j++) { 12 | String line = scanner.next(); 13 | for (int i = 0; i < N; i++) { 14 | field[j][i] = line.charAt(i) == '.' ? 0 : 1; 15 | } 16 | } 17 | } 18 | 19 | private static boolean clearSpot(int i, int j) { 20 | return field[j][i] == 0; 21 | } 22 | 23 | private static boolean clearRow(int j) { 24 | for (int k = 0; k < N; k++) { 25 | if (field[j][k] == -1) return false; 26 | } 27 | return true; 28 | } 29 | 30 | private static boolean clearColumn(int i) { 31 | for (int k = 0; k < N; k++) { 32 | if (field[k][i] == -1) return false; 33 | } 34 | return true; 35 | } 36 | 37 | private static boolean clearLeftDiagonal(int i, int j) { 38 | int tj = j; 39 | int ti = i; 40 | while (tj >= 0 && ti >= 0) { 41 | if (field[tj--][ti--] == -1) return false; 42 | } 43 | tj = j; 44 | ti = i; 45 | while (tj < N && ti < N) { 46 | if (field[tj++][ti++] == -1) return false; 47 | } 48 | 49 | return true; 50 | } 51 | 52 | private static boolean clearRightDiagonal(int i, int j) { 53 | int tj = j; 54 | int ti = i; 55 | while (tj >= 0 && ti < N) { 56 | if (field[tj--][ti++] == -1) return false; 57 | } 58 | tj = j; 59 | ti = i; 60 | while (tj < N && ti >= 0) { 61 | if (field[tj++][ti--] == -1) return false; 62 | } 63 | 64 | return true; 65 | } 66 | 67 | private static void r(int i, int j) { 68 | if (i >= N || j >= N) return; 69 | 70 | if (clearSpot(i, j) && clearColumn(i) && clearLeftDiagonal(i, j) && clearRightDiagonal(i, j)) { 71 | if (j == N - 1) { 72 | result++; 73 | return; 74 | } 75 | 76 | field[j][i] = -1; 77 | for (int k = 0; k < N; k++) r(k, j + 1); 78 | field[j][i] = 0; 79 | } 80 | } 81 | 82 | private static void solve() { 83 | for (int i = 0; i < N; i++) r(i, 0); 84 | sb.append(result); 85 | } 86 | 87 | public static void main(String[] args) { 88 | int T = 1; 89 | for (int t = 0; t < T; t++) { 90 | readInput(); 91 | solve(); 92 | sb.append("\n"); 93 | } 94 | System.out.print(sb.toString()); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /cses/Introductory Problems/Coin-Piles.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Solution { 4 | private static Scanner scanner = new Scanner(System.in); 5 | private static StringBuilder sb = new StringBuilder(); 6 | private static int A, B; 7 | 8 | private static void readInput() { 9 | A = scanner.nextInt(); 10 | B = scanner.nextInt(); 11 | } 12 | 13 | private static void solve() { 14 | int g = Math.max(A, B); 15 | int l = Math.min(A, B); 16 | int diff = g - l; 17 | 18 | if (diff > l) { 19 | sb.append("NO"); 20 | } else { 21 | sb.append((l - diff) % 3 == 0 ? "YES" : "NO"); 22 | } 23 | } 24 | 25 | public static void main(String[] args) { 26 | int T = scanner.nextInt(); 27 | for (int t = 0; t < T; t++) { 28 | readInput(); 29 | solve(); 30 | sb.append("\n"); 31 | } 32 | System.out.print(sb.toString()); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /cses/Introductory Problems/Creating-Strings-I.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | import java.util.Scanner; 4 | import java.util.stream.Collectors; 5 | 6 | class Wrapper { 7 | public static void main(String[] args) { 8 | (new Solution()).solve(); 9 | } 10 | 11 | private static class Solution { 12 | Scanner scanner = new Scanner(System.in); 13 | String s; 14 | ArrayList result = new ArrayList(); 15 | boolean[] taken; 16 | char[] buffer; 17 | char[] letters; 18 | 19 | private void generate(int position) { 20 | if (position == s.length()) { 21 | result.add(new String(buffer)); 22 | return; 23 | } 24 | 25 | int maxChar = -1; 26 | for (int i = 0; i < s.length(); i++) { 27 | if (taken[i]) continue; 28 | if (maxChar == letters[i]) continue; 29 | 30 | maxChar = letters[i]; 31 | taken[i] = true; 32 | buffer[position] = letters[i]; 33 | generate(position + 1); 34 | taken[i] = false; 35 | } 36 | } 37 | 38 | public void solve() { 39 | s = scanner.next(); 40 | letters = s.toCharArray(); 41 | Arrays.sort(letters); 42 | 43 | taken = new boolean[s.length()]; 44 | buffer = new char[s.length()]; 45 | 46 | generate(0); 47 | 48 | System.out.println(result.size()); 49 | System.out.print(result.stream().collect(Collectors.joining("\n"))); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /cses/Introductory Problems/Grid-Paths.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | class Wrapper { 4 | public static void main(String[] args) { 5 | (new Solution()).solve(); 6 | } 7 | 8 | private static class Solution { 9 | final int SIZE = 7; 10 | 11 | final int FIRST = 1; 12 | final int LAST = SIZE; 13 | 14 | Scanner scanner = new Scanner(System.in); 15 | String s; 16 | 17 | int result = 0; 18 | boolean[][] grid = new boolean[SIZE + 2][SIZE + 2]; 19 | boolean invert = false; 20 | 21 | private void r(int j, int i, int position) { 22 | if (grid[j][i]) return; 23 | 24 | if (i == FIRST && j == (invert ? FIRST : LAST)) { 25 | if (position == SIZE * SIZE) result++; 26 | return; 27 | } 28 | 29 | // bounded L, R 30 | if (grid[j][i - 1] && grid[j][i + 1] && !grid[j - 1][i] && !grid[j + 1][i]) return; 31 | 32 | // bounded U, D 33 | if (!grid[j][i - 1] && !grid[j][i + 1] && grid[j - 1][i] && grid[j + 1][i]) return; 34 | 35 | grid[j][i] = true; 36 | 37 | char direction = s.charAt(position - 1); 38 | if (invert) direction = s.charAt(s.length() - position); 39 | if (direction == '?') { 40 | if (!grid[j - 1][i]) r(j - 1, i, position + 1); 41 | if (!grid[j + 1][i]) r(j + 1, i, position + 1); 42 | if (!grid[j][i - 1]) r(j, i - 1, position + 1); 43 | if (!grid[j][i + 1]) r(j, i + 1, position + 1); 44 | } else { 45 | int nj = (direction == 'U' ? -1 : 0) + (direction == 'D' ? 1 : 0); 46 | int ni = (direction == 'L' ? -1 : 0) + (direction == 'R' ? 1 : 0); 47 | if (invert) { 48 | nj *= -1; 49 | ni *= -1; 50 | } 51 | // System.out.println(nj + " " + ni); 52 | if (!grid[j + nj][i + ni]) r(j + nj, i + ni, position + 1); 53 | } 54 | 55 | grid[j][i] = false; 56 | } 57 | 58 | public void solve() { 59 | s = scanner.next(); 60 | if (s.equals("????????????????????????????????????????????????")) { 61 | result = 88418; 62 | } else { 63 | for (int i = 0; i < SIZE + 2; i++) { 64 | grid[i][0] = true; 65 | grid[i][LAST + 1] = true; 66 | grid[0][i] = true; 67 | grid[LAST + 1][i] = true; 68 | } 69 | 70 | for (int i = 0; i < s.length() / 2; i++) { 71 | if (s.charAt(s.length() - 1 - i) != '?') { 72 | invert = true; 73 | break; 74 | } 75 | if (s.charAt(i) != '?') { 76 | break; 77 | } 78 | } 79 | 80 | r(invert ? LAST : FIRST, FIRST, 1); 81 | } 82 | 83 | System.out.print(result); 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /cses/Introductory Problems/Increasing-Array.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | class Wrapper { 4 | public static void main(String[] args) { 5 | (new Solution()).solve(); 6 | } 7 | 8 | private static class Solution { 9 | Scanner scanner = new Scanner(System.in); 10 | 11 | public void solve() { 12 | long N = scanner.nextLong(); 13 | long d = 0L; 14 | int m = 0; 15 | for (int i = 0; i < N; i++) { 16 | int x = scanner.nextInt(); 17 | m = Math.max(x, m); 18 | d += m - x; 19 | } 20 | 21 | System.out.println(d);s 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /cses/Introductory Problems/Missing-Number.java: -------------------------------------------------------------------------------- 1 | class Wrapper { 2 | public static void main(String[] args) { 3 | (new Solution()).solve(); 4 | } 5 | 6 | private static class Solution { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | public void solve() { 10 | int N = scanner.nextInt(); 11 | long target = N * (N + 1L) / 2L; 12 | for (int i = 0; i < N - 1; i++) target -= scanner.nextInt(); 13 | System.out.println(target); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /cses/Introductory Problems/Number-Spiral.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Solution { 4 | private static Scanner scanner = new Scanner(System.in); 5 | private static StringBuilder sb = new StringBuilder(); 6 | private static long i, j; 7 | 8 | private static void readInput() { 9 | j = scanner.nextLong(); 10 | i = scanner.nextLong(); 11 | } 12 | 13 | private static long triangleSize(long triangle) { 14 | return triangle + (triangle - 1); 15 | } 16 | 17 | private static long triangleSum(long triangle) { 18 | return (triangle * (triangle + 1) + (triangle - 1) * triangle) / 2; 19 | } 20 | 21 | private static void solve() { 22 | long triangle = Math.max(i, j); 23 | long offset = Math.min(i, j); 24 | boolean even = (triangle % 2 == 0) || triangle == 1; 25 | boolean vertical = j < i; 26 | 27 | long start = triangleSum(triangle - 1); 28 | 29 | if ((vertical && even) || (!vertical && !even)) sb.append(start + offset); 30 | else sb.append(start + triangleSize(triangle) - offset + 1); 31 | } 32 | 33 | public static void main(String[] args) { 34 | int T = scanner.nextInt(); 35 | for (int t = 0; t < T; t++) { 36 | readInput(); 37 | solve(); 38 | sb.append("\n"); 39 | } 40 | System.out.print(sb.toString()); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /cses/Introductory Problems/Palindrome-Reorder.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | class Wrapper { 4 | public static void main(String[] args) { 5 | (new Solution()).solve(); 6 | } 7 | 8 | private static class Solution { 9 | Scanner scanner = new Scanner(System.in); 10 | 11 | public void solve() { 12 | String s = scanner.next(); 13 | StringBuilder sb = new StringBuilder(); 14 | int[] f = new int[26]; 15 | 16 | for (int i = 0; i < s.length(); i++) { 17 | f[s.charAt(i) - 'A']++; 18 | } 19 | 20 | int odd = 0; 21 | for (int i = 0; i < 26; i++) { 22 | if (f[i] % 2 == 1) odd++; 23 | } 24 | if (odd > 1) { 25 | System.out.println("NO SOLUTION"); 26 | return; 27 | } 28 | 29 | int oddIndex = -1; 30 | for (int i = 0; i < 26; i++) { 31 | if (f[i] % 2 == 1) oddIndex = i; 32 | else { 33 | for (int j = 0; j < f[i] / 2; j++) sb.append((char) ('A' + i)); 34 | } 35 | } 36 | StringBuilder sb2 = new StringBuilder(sb); 37 | sb2.reverse(); 38 | 39 | if (oddIndex != -1) { 40 | for (int i = 0; i < f[oddIndex]; i++) sb.append((char) ('A' + oddIndex)); 41 | } 42 | 43 | sb.append(sb2); 44 | 45 | System.out.print(sb); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /cses/Introductory Problems/Permutations.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | class Wrapper { 4 | public static void main(String[] args) { 5 | (new Solution()).solve(); 6 | } 7 | 8 | private static class Solution { 9 | Scanner scanner = new Scanner(System.in); 10 | 11 | public void solve() { 12 | int N = scanner.nextInt(); 13 | StringBuilder sb = new StringBuilder(N); 14 | if (N == 2 || N == 3) { 15 | System.out.println("NO SOLUTION"); 16 | return; 17 | } 18 | 19 | // odd 20 | for (int i = N - (N % 2 == 0 ? 1 : 0); i >= 1; i -= 2) sb.append(i).append(" "); 21 | // even 22 | for (int i = N - N % 2; i >= 2; i -= 2) sb.append(i).append(" "); 23 | 24 | System.out.println(sb); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /cses/Introductory Problems/Repetitions.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | class Wrapper { 4 | public static void main(String[] args) { 5 | (new Solution()).solve(); 6 | } 7 | 8 | private static class Solution { 9 | Scanner scanner = new Scanner(System.in); 10 | 11 | public void solve() { 12 | String dna = scanner.next(); 13 | long maxSequence = 1; 14 | long currentSequence = 1; 15 | for (int i = 1; i < dna.length(); i++) { 16 | if (dna.charAt(i - 1) == dna.charAt(i)) { 17 | currentSequence++; 18 | maxSequence = Math.max(maxSequence, currentSequence); 19 | } else { 20 | currentSequence = 1; 21 | } 22 | } 23 | 24 | System.out.println(maxSequence); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /cses/Introductory Problems/Trailing-Zeros.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Solution { 4 | private static Scanner scanner = new Scanner(System.in); 5 | private static StringBuilder sb = new StringBuilder(); 6 | private static int N; 7 | 8 | private static void readInput() { 9 | N = scanner.nextInt(); 10 | } 11 | 12 | private static void solve() { 13 | long zeroes = 0; 14 | long divisor = 5; 15 | for (int i = 1; i <= 64; i++) { 16 | zeroes += N / divisor; 17 | divisor *= 5; 18 | } 19 | sb.append(zeroes); 20 | } 21 | 22 | public static void main(String[] args) { 23 | int T = 1; 24 | for (int t = 0; t < T; t++) { 25 | readInput(); 26 | solve(); 27 | } 28 | System.out.print(sb.toString()); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /cses/Introductory Problems/Two-Knights.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | class Wrapper { 4 | public static void main(String[] args) { 5 | (new Solution()).solve(); 6 | } 7 | 8 | private static class Solution { 9 | Scanner scanner = new Scanner(System.in); 10 | 11 | public void solve() { 12 | int N = scanner.nextInt(); 13 | StringBuilder sb = new StringBuilder(N); 14 | 15 | long result = 0; 16 | sb.append(result).append("\n"); 17 | 18 | for (long n = 2; n <= N; n++) { 19 | long same = (2 * n - 1) * (2 * n - 2) / 2 - 2; 20 | long split = (n - 1) * (n - 1) * (2 * n - 1) - 8 * (n - 2) + 2; 21 | result += same + split; 22 | sb.append(result).append("\n"); 23 | } 24 | 25 | System.out.print(sb); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /cses/Introductory Problems/Two-Sets.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Solution { 4 | private static Scanner scanner = new Scanner(System.in); 5 | private static StringBuilder sb = new StringBuilder(); 6 | private static long N; 7 | 8 | private static void readInput() { 9 | N = scanner.nextLong(); 10 | } 11 | 12 | private static void solve() { 13 | if (N % 4 == 1 || N % 4 == 2) { 14 | sb.append("NO"); 15 | return; 16 | } 17 | 18 | sb.append("YES\n"); 19 | 20 | // first set 21 | if (N % 4 == 0) { 22 | sb.append(N / 2).append("\n"); 23 | } else { 24 | sb.append(N / 4 * 2 + 2).append("\n"); 25 | sb.append(1).append(" "); 26 | sb.append(2).append(" "); 27 | } 28 | for (int i = 1; i <= N / 4; i++) { 29 | sb.append(N - i * 4 + 1).append(" "); 30 | sb.append(N - i * 4 + 4).append(" "); 31 | } 32 | 33 | // first set 34 | if (N % 4 == 0) { 35 | sb.append("\n").append(N / 2).append("\n"); 36 | } else { 37 | sb.append("\n").append(N / 4 * 2 + 1).append("\n"); 38 | sb.append(3).append(" "); 39 | } 40 | for (int i = 1; i <= N / 4; i++) { 41 | sb.append(N - i * 4 + 2).append(" "); 42 | sb.append(N - i * 4 + 3).append(" "); 43 | } 44 | } 45 | 46 | public static void main(String[] args) { 47 | int T = 1; 48 | for (int t = 0; t < T; t++) { 49 | readInput(); 50 | solve(); 51 | sb.append("\n"); 52 | } 53 | System.out.print(sb.toString()); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /cses/Introductory Problems/Weird-Algorithm.java: -------------------------------------------------------------------------------- 1 | class Wrapper { 2 | public static void main(String[] args) { 3 | (new Solution()).solve(); 4 | } 5 | 6 | private static class Solution { 7 | Scanner scanner = new Scanner(System.in); 8 | 9 | public void solve() { 10 | long N = scanner.nextInt(); 11 | System.out.print(N + " "); 12 | while (N > 1) { 13 | if (N % 2 == 1) { 14 | N *= 3; 15 | N++; 16 | } else { 17 | N /= 2; 18 | } 19 | System.out.print(N + " "); 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /cses/Library/Multiset.java: -------------------------------------------------------------------------------- 1 | /** 2 | * HMultiset utility class. It's just like TreeSet, but allows duplicate elements * 3 | */ 4 | static class HMultiset extends HashMap { 5 | void add(T key) { 6 | Integer count = get(key); 7 | put(key, count == null ? 1 : count + 1); 8 | } 9 | 10 | @SuppressWarnings(value = "unchecked") 11 | @Override 12 | public Integer remove(Object key) { 13 | if (!containsKey(key)) return null; 14 | 15 | int count = get(key); 16 | if (count > 1) return put((T) key, count - 1); 17 | 18 | return super.remove(key); 19 | } 20 | } 21 | 22 | /** 23 | * Tree Multiset utility class * 24 | */ 25 | static class TMultiset extends TreeMap { 26 | private int size = 0; 27 | private T head = null, tail = null; 28 | 29 | void add(T value) { 30 | Integer count = get(value); 31 | size++; 32 | if (count == null) { 33 | put(value, 1); 34 | recalculateEdges(); 35 | } else { 36 | put(value, count + 1); 37 | } 38 | } 39 | 40 | private void recalculateEdges() { 41 | try { 42 | head = firstKey(); 43 | } catch (NoSuchElementException e) { 44 | head = null; 45 | } 46 | try { 47 | tail = lastKey(); 48 | } catch (NoSuchElementException e) { 49 | tail = null; 50 | } 51 | } 52 | 53 | @SuppressWarnings(value = "unchecked") 54 | @Override 55 | public Integer remove(Object key) { 56 | if (!containsKey(key)) { 57 | return null; 58 | } 59 | 60 | size--; 61 | 62 | Integer value = get(key); 63 | if (value > 1) { 64 | return put((T) key, value - 1); 65 | } 66 | 67 | Integer result = super.remove(key); 68 | recalculateEdges(); 69 | return result; 70 | } 71 | 72 | @java.lang.Override 73 | public int size() { 74 | return size; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /cses/Library/Numbers.java: -------------------------------------------------------------------------------- 1 | static class Numbers { 2 | long[] factorials; 3 | 4 | private final long M; 5 | private HashMap fibHash = new HashMap<>(); 6 | 7 | public Numbers(long m) { 8 | M = m; 9 | } 10 | 11 | long f(int n) { 12 | if (factorials == null || factorials.length < n) generateFactorials(n); 13 | return factorials[n]; 14 | } 15 | 16 | long c(int k, int n) { 17 | return factorials[n] * Numbers.modInverse(factorials[k] * factorials[n - k], MODULO) % MODULO; 18 | } 19 | 20 | static long _modInverse(long a, long b) { 21 | long t, q, x0 = 0, x1 = 1; 22 | if (b == 1) return 1; 23 | while (a > 1) { 24 | q = a / b; 25 | t = b; 26 | b = a % b; 27 | a = t; 28 | t = x0; 29 | x0 = x1 - q * x0; 30 | x1 = t; 31 | } 32 | return x1; 33 | } 34 | 35 | static long modInverse(long a, long b) { 36 | long result = _modInverse(a, b); 37 | return result < 0 ? result + b : result; 38 | } 39 | 40 | void generateFactorials(int n) { 41 | factorials = new long[n + 1]; 42 | factorials[0] = 1; 43 | factorials[1] = 1; 44 | for (int i = 2; i <= n; i++) factorials[i] = factorials[i - 1] * i % M; 45 | } 46 | 47 | long[][] mpow(long[][] a, long k) { 48 | int s = a.length; 49 | long[][] result = new long[s][s]; 50 | for (int i = 0; i < s; i++) result[i][i] = 1; 51 | 52 | while (k > 0) { 53 | if (k % 2 == 1) result = mmul(result, a); 54 | a = mmul(a, a); 55 | k /= 2; 56 | } 57 | 58 | return result; 59 | } 60 | 61 | long[][] mmul(long[][] a, long[][] b) { 62 | int n = a.length, m = b[0].length, pa = a[0].length, pb = b.length; 63 | 64 | if (pa != pb) 65 | throw new RuntimeException( 66 | String.format("Wrong matrix dimensions %dx%d * %dx%d", n, pa, pb, m)); 67 | 68 | long[][] c = new long[n][m]; 69 | for (int i = 0; i < n; ++i) { 70 | for (int j = 0; j < pa; ++j) { 71 | for (int k = 0; k < m; ++k) { 72 | c[i][j] = (c[i][j] + (a[i][k] * b[k][j]) % MODULO) % MODULO; 73 | } 74 | } 75 | } 76 | return c; 77 | } 78 | 79 | long fastFib(long n) { 80 | if (n < 0) return 0; 81 | if (n < 2) return 1; 82 | if (fibHash.containsKey(n)) return fibHash.get(n); 83 | long k = n / 2; 84 | if (n % 2 == 0) { 85 | fibHash.put(n, (fastFib(k) * fastFib(k) + fastFib(k - 1) * fastFib(k - 1)) % M); 86 | } else { 87 | fibHash.put(n, (fastFib(k) * fastFib(k + 1) + fastFib(k - 1) * fastFib(k)) % M); 88 | } 89 | return fibHash.get(n); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /cses/Sorting and Searching/Distinct-Numbers.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | private static FastReader scanner = new FastReader(); 3 | private static StringBuilder sb = new StringBuilder(); 4 | private static int INF = Integer.MAX_VALUE; 5 | private static int N; 6 | private static int[] a; 7 | 8 | private static void readInput() { 9 | N = scanner.nextInt(); 10 | a = fillArray(N); 11 | } 12 | 13 | private static int[] fillArray(int n) { 14 | int[] array = new int[n]; 15 | for (int i = 0; i < n; i++) array[i] = scanner.nextInt(); 16 | return array; 17 | } 18 | 19 | private static void solve() { 20 | Set set = new HashSet(); 21 | for (int i = 0; i < N; i++) set.add(a[i]); 22 | sb.append(set.size()); 23 | } 24 | 25 | public static void main(String[] args) { 26 | try { 27 | int T = 1; 28 | for (int t = 0; t < T; t++) { 29 | readInput(); 30 | solve(); 31 | sb.append("\n"); 32 | } 33 | System.out.print(sb.toString()); 34 | } catch (NoSuchElementException e) { 35 | throw new RuntimeException("WRONG INPUT"); 36 | } 37 | } 38 | 39 | static class FastReader { 40 | BufferedReader br; 41 | StringTokenizer st; 42 | 43 | public FastReader() { 44 | br = new BufferedReader(new InputStreamReader(System.in)); 45 | } 46 | 47 | String next() { 48 | while (st == null || !st.hasMoreElements()) { 49 | try { 50 | st = new StringTokenizer(br.readLine()); 51 | } catch (IOException e) { 52 | e.printStackTrace(); 53 | } 54 | } 55 | return st.nextToken(); 56 | } 57 | 58 | int nextInt() { 59 | return Integer.parseInt(next()); 60 | } 61 | 62 | long nextLong() { 63 | return Long.parseLong(next()); 64 | } 65 | 66 | double nextDouble() { 67 | return Double.parseDouble(next()); 68 | } 69 | 70 | String nextLine() { 71 | String str = ""; 72 | try { 73 | str = br.readLine(); 74 | } catch (IOException e) { 75 | e.printStackTrace(); 76 | } 77 | return str; 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /cses/Sorting and Searching/Ferris-Wheel.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | private static FastReader scanner = new FastReader(); 3 | private static StringBuilder sb = new StringBuilder(); 4 | private static int INF = Integer.MAX_VALUE; 5 | private static int N, X; 6 | private static ArrayList weights; 7 | 8 | private static void readInput() { 9 | N = scanner.nextInt(); 10 | X = scanner.nextInt(); 11 | 12 | weights = fillArrayList(N); 13 | } 14 | 15 | private static int[] fillArray(int n) { 16 | int[] array = new int[n]; 17 | for (int i = 0; i < n; i++) array[i] = scanner.nextInt(); 18 | return array; 19 | } 20 | 21 | private static ArrayList fillArrayList(int n) { 22 | ArrayList arrayList = new ArrayList(N); 23 | for (int i = 0; i < n; i++) arrayList.add(scanner.nextInt()); 24 | return arrayList; 25 | } 26 | 27 | private static void solve() { 28 | Collections.sort(weights); 29 | int p1 = 0; 30 | int p2 = N - 1; 31 | int gondolas = 0; 32 | 33 | while (p1 <= p2) { 34 | if (p1 != p2 && weights.get(p1) + weights.get(p2) <= X) p1++; 35 | p2--; 36 | gondolas++; 37 | } 38 | 39 | sb.append(gondolas); 40 | } 41 | 42 | public static void main(String[] args) { 43 | try { 44 | int T = 1; 45 | for (int t = 0; t < T; t++) { 46 | readInput(); 47 | solve(); 48 | sb.append("\n"); 49 | } 50 | System.out.print(sb.toString()); 51 | } catch (NoSuchElementException e) { 52 | throw new RuntimeException("WRONG INPUT"); 53 | } 54 | } 55 | 56 | static class FastReader { 57 | BufferedReader br; 58 | StringTokenizer st; 59 | 60 | public FastReader() { 61 | br = new BufferedReader(new InputStreamReader(System.in)); 62 | } 63 | 64 | String next() { 65 | while (st == null || !st.hasMoreElements()) { 66 | try { 67 | st = new StringTokenizer(br.readLine()); 68 | } catch (IOException e) { 69 | e.printStackTrace(); 70 | } 71 | } 72 | return st.nextToken(); 73 | } 74 | 75 | int nextInt() { 76 | return Integer.parseInt(next()); 77 | } 78 | 79 | long nextLong() { 80 | return Long.parseLong(next()); 81 | } 82 | 83 | double nextDouble() { 84 | return Double.parseDouble(next()); 85 | } 86 | 87 | String nextLine() { 88 | String str = ""; 89 | try { 90 | str = br.readLine(); 91 | } catch (IOException e) { 92 | e.printStackTrace(); 93 | } 94 | return str; 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /format.sh: -------------------------------------------------------------------------------- 1 | #find . -name '*.go' | xargs gofmt -w 2 | find . -name '*.java' | xargs java -jar ./google-java-format.jar -i 3 | #find . -name '*.py' | xargs autopep8 --in-place 4 | #find . -name '.DS_Store' | xargs rm 5 | -------------------------------------------------------------------------------- /google-java-format.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hypersolid/competitive-programming/d42dff410f3a9665431a14b3cffd98c5ab024879/google-java-format.jar -------------------------------------------------------------------------------- /hackerrank/algorithms/bit_manipulation/And-Product.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | 9 | # Complete the andProduct function below. 10 | def andProduct(a, b): 11 | log = math.log(a^b)/math.log(2) 12 | intlog = int(log) 13 | return a & ~((1 << intlog) - 1) 14 | 15 | if __name__ == '__main__': 16 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 17 | 18 | n = int(input()) 19 | 20 | for n_itr in range(n): 21 | ab = input().split() 22 | 23 | a = int(ab[0]) 24 | 25 | b = int(ab[1]) 26 | 27 | result = andProduct(a, b) 28 | 29 | fptr.write(str(result) + '\n') 30 | 31 | fptr.close() 32 | -------------------------------------------------------------------------------- /hackerrank/algorithms/bit_manipulation/Counter-Game.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | int T = scanner.nextInt(); 9 | 10 | for (int t = 0; t < T; t++) { 11 | Long N = Long.parseUnsignedLong(scanner.next()); 12 | 13 | int steps = 0; 14 | boolean powerOfTwo; 15 | int highestBit = 0; 16 | 17 | while (N != 1) { 18 | powerOfTwo = false; 19 | 20 | for (int i = 0; i < 64; i++) { 21 | if ((N >>> i & 1) == 1) highestBit = i; 22 | if (Long.compareUnsigned(N, 1L << i) == 0) { 23 | N >>>= 1; 24 | powerOfTwo = true; 25 | break; 26 | } 27 | } 28 | 29 | if (!powerOfTwo) N -= 1L << highestBit; 30 | 31 | steps++; 32 | } 33 | System.out.println(steps % 2 == 0 ? "Richard" : "Louise"); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /hackerrank/algorithms/bit_manipulation/Flipping-Bits.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | int N = scanner.nextInt(); 9 | long mask = (1L << 32) - 1; 10 | for (int i = 0; i < N; i++) { 11 | long number = scanner.nextLong(); 12 | System.out.println(number ^ mask); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /hackerrank/algorithms/bit_manipulation/Lonely-Integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/py 2 | # Head ends here 3 | 4 | 5 | def lonelyinteger(b): 6 | answer = 0 7 | for i in b: 8 | answer ^= i 9 | return answer 10 | 11 | # Tail starts here 12 | if __name__ == '__main__': 13 | a = int(input()) 14 | b = map(int, input().strip().split(" ")) 15 | print(lonelyinteger(b)) 16 | -------------------------------------------------------------------------------- /hackerrank/algorithms/bit_manipulation/Maximizing-XOR.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def maxXor(l, r): 3 | result = 0 4 | for i1 in range(l, r + 1): 5 | for i2 in range(i1, r + 1): 6 | result = max(result, i1 ^ i2) 7 | return result 8 | 9 | if __name__ == '__main__': 10 | l = int(input()) 11 | r = int(input()) 12 | print(maxXor(l, r)) 13 | -------------------------------------------------------------------------------- /hackerrank/algorithms/bit_manipulation/Sum-Vs-Xor.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.math.*; 3 | import java.text.*; 4 | import java.util.*; 5 | import java.util.regex.*; 6 | 7 | public class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | long n = in.nextLong(); 12 | int zeroBits = 0; 13 | boolean start = false; 14 | 15 | for (int i = 63; i >= 0; i--) { 16 | if ((1L << i & n) == 0) { 17 | if (start) zeroBits++; 18 | } else { 19 | start = true; 20 | } 21 | } 22 | 23 | System.out.println(1L << (zeroBits - 1) + 1); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /hackerrank/algorithms/bit_manipulation/The-Great-XOR.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func solve(x uint64) uint64 { 6 | // a^x>x 7 | // 0= x { 12 | return answer 13 | } 14 | if mask&^x == mask { 15 | answer += mask 16 | } 17 | } 18 | return answer 19 | } 20 | 21 | func main() { 22 | var N, v uint64 23 | fmt.Scanf("%d", &N) 24 | for n := uint64(0); n < N; n++ { 25 | fmt.Scanf("%d", &v) 26 | fmt.Println(solve(v)) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /hackerrank/algorithms/bit_manipulation/Xor-Sequence.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func element(number uint64) uint64 { 6 | a := number % 8 7 | if a < 2 { 8 | return number 9 | } 10 | if a < 4 { 11 | return 2 12 | } 13 | if a < 6 { 14 | return number + 2 15 | } 16 | return 0 17 | } 18 | 19 | func main() { 20 | var n int 21 | var l, r uint64 22 | fmt.Scanf("%d", &n) 23 | for i := 0; i < n; i++ { 24 | fmt.Scanf("%d %d", &l, &r) 25 | fmt.Println(element(l-1) ^ element(r)) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /hackerrank/algorithms/constructive_algorithms/Bonetrousle.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | import java.util.Arrays; 4 | 5 | public class Solution { 6 | static int T, B; 7 | static long N, K; 8 | 9 | public static void main(String[] args) { 10 | Scanner scanner = new Scanner(System.in); 11 | T = scanner.nextInt(); 12 | for (int t = 0; t < T; t++) { 13 | N = scanner.nextLong(); 14 | K = scanner.nextLong(); 15 | B = scanner.nextInt(); 16 | if (B > K) System.out.println("-1"); 17 | else printCombination(); 18 | } 19 | } 20 | 21 | static void printCombination() { 22 | long[] pointers = new long[B]; 23 | 24 | long sum = 0; 25 | int lastPtr = B - 1; 26 | for (int b = 0; b < lastPtr; b++) { 27 | pointers[b] = b + 1; 28 | sum += pointers[b]; 29 | } 30 | pointers[lastPtr] = Math.min(N, K); 31 | sum += pointers[lastPtr]; 32 | 33 | long diff, prevSum = -1; 34 | while (sum != N) { 35 | if (sum > N) { 36 | diff = Math.min(sum - N, pointers[lastPtr] - pointers[lastPtr - 1] - 1); 37 | pointers[lastPtr] -= diff; 38 | sum -= diff; 39 | } else { 40 | for (int b = lastPtr - 1; b >= 0; b--) { 41 | if (N - sum == 0) { 42 | printArray(pointers); 43 | return; 44 | } 45 | diff = Math.min(N - sum, pointers[b + 1] - pointers[b] - 1); 46 | pointers[b] += diff; 47 | sum += diff; 48 | } 49 | } 50 | if (prevSum == sum) { 51 | System.out.println("-1"); 52 | return; 53 | } else { 54 | prevSum = sum; 55 | } 56 | } 57 | 58 | printArray(pointers); 59 | } 60 | 61 | static void printArray(long[] array) { 62 | System.out.println(Arrays.toString(array).replaceAll("\\[|\\]|,", "")); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /hackerrank/algorithms/dp/Abbreviation.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Solution { 4 | 5 | static String a, b; 6 | static int[][] dp; 7 | 8 | static boolean compare(int p1, int p2) { 9 | 10 | if (p1 < 0 && p2 < 0) return true; 11 | if (p2 < 0) return compare(p1 - 1, p2); 12 | if (p1 < 0) return false; 13 | 14 | char ch1 = a.charAt(p1); 15 | char ch2 = b.charAt(p2); 16 | 17 | if (dp[p1][p2] != 0) return dp[p1][p2] == 1; 18 | 19 | if (Character.isUpperCase(ch1)) { 20 | if (ch1 == ch2) dp[p1][p2] = compare(p1 - 1, p2 - 1) ? 1 : 2; 21 | else dp[p1][p2] = 2; 22 | } else { 23 | if (Character.toUpperCase(ch1) == ch2 && compare(p1 - 1, p2 - 1)) dp[p1][p2] = 1; 24 | else dp[p1][p2] = compare(p1 - 1, p2) ? 1 : 2; 25 | } 26 | 27 | return dp[p1][p2] == 1; 28 | } 29 | 30 | public static void main(String[] args) { 31 | Scanner scanner = new Scanner(System.in); 32 | 33 | int N = scanner.nextInt(); 34 | scanner.nextLine(); 35 | for (int n = 0; n < N; n++) { 36 | a = scanner.nextLine(); 37 | b = scanner.nextLine(); 38 | dp = new int[a.length()][b.length()]; 39 | System.out.println(compare(a.length() - 1, b.length() - 1) ? "YES" : "NO"); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /hackerrank/algorithms/dp/Bricks-Game.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | static long[] memo, stack, sums; 6 | static int N; 7 | 8 | public static long dp(int index) { 9 | if (memo[index] != -1) return memo[index]; 10 | long maxProfit = 0; 11 | 12 | long brick1 = stack[index]; 13 | long brick2 = brick1 + stack[index + 1]; 14 | long brick3 = brick2 + stack[index + 2]; 15 | 16 | maxProfit = Math.max(maxProfit, brick1 + sums[index + 1] - dp(index + 1)); 17 | maxProfit = Math.max(maxProfit, brick2 + sums[index + 2] - dp(index + 2)); 18 | maxProfit = Math.max(maxProfit, brick3 + sums[index + 3] - dp(index + 3)); 19 | 20 | memo[index] = maxProfit; 21 | return maxProfit; 22 | } 23 | 24 | public static void main(String[] args) { 25 | Scanner scanner = new Scanner(System.in); 26 | int T = scanner.nextInt(); 27 | for (int t = 0; t < T; t++) { 28 | N = scanner.nextInt(); 29 | stack = new long[N + 3]; 30 | memo = new long[N + 3]; 31 | sums = new long[N + 3]; 32 | Arrays.fill(memo, -1); 33 | for (int n = 0; n < N; n++) stack[n] = scanner.nextInt(); 34 | for (int n = N - 1; n >= 0; n--) sums[n] = sums[n + 1] + stack[n]; 35 | 36 | memo[N - 1] = stack[N - 1]; 37 | memo[N] = 0; 38 | memo[N + 1] = 0; 39 | memo[N + 2] = 0; 40 | 41 | System.out.println(dp(0)); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /hackerrank/algorithms/dp/Candles-Counting.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | static int N, K; 6 | static int[] heights, colors; 7 | static final long MODULO = (long) Math.pow(10, 9) + 7; 8 | static final int MAX_HEIGHT = (int) (5 * Math.pow(10, 4)); 9 | static FenwickTree tree; 10 | 11 | public static class FenwickTree { 12 | public long[][] array; 13 | 14 | public FenwickTree() { 15 | array = new long[MAX_HEIGHT + 1][1 << K]; 16 | } 17 | 18 | public void update(int i, int mask, long increment) { 19 | while (i < array.length) { 20 | array[i][mask] += increment; 21 | 22 | array[i][mask] %= MODULO; 23 | i += i & (-i); 24 | } 25 | } 26 | 27 | public long query(int i, int mask) { 28 | long sum = 0; 29 | while (i > 0) { 30 | sum += array[i][mask]; 31 | 32 | sum %= MODULO; 33 | i -= i & (-i); 34 | } 35 | return sum; 36 | } 37 | } 38 | 39 | static void step(int position) { 40 | long[] buffer = new long[1 << K]; 41 | 42 | for (int m = 1; m < 1 << K; m++) buffer[m] = tree.query(heights[position] - 1, m); 43 | 44 | for (int m = 1; m < 1 << K; m++) { 45 | if (buffer[m] == 0) continue; 46 | tree.update(heights[position], m | colors[position], buffer[m]); 47 | } 48 | tree.update(heights[position], colors[position], 1); 49 | } 50 | 51 | public static void main(String[] args) { 52 | Scanner scanner = new Scanner(System.in); 53 | N = scanner.nextInt(); 54 | K = scanner.nextInt(); 55 | 56 | heights = new int[N]; 57 | colors = new int[N]; 58 | 59 | for (int n = 0; n < N; n++) { 60 | heights[n] = scanner.nextInt(); 61 | colors[n] = 1 << (scanner.nextInt() - 1); 62 | } 63 | 64 | tree = new FenwickTree(); 65 | 66 | for (int i = 0; i < N; i++) step(i); 67 | 68 | System.out.print(tree.query(MAX_HEIGHT, (1 << K) - 1)); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /hackerrank/algorithms/dp/Coin-Change.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | public static void main(String[] args) { 6 | Scanner scanner = new Scanner(System.in); 7 | int N = scanner.nextInt(), M = scanner.nextInt(); 8 | 9 | if (N == 0) { 10 | System.out.println(1); 11 | return; 12 | } 13 | 14 | int[] coins = new int[M]; 15 | long[] combinations = new long[N + 1]; 16 | combinations[0] = 1; 17 | for (int m = 0; m < M; m++) coins[m] = scanner.nextInt(); 18 | 19 | for (int m = 0; m < M; m++) { 20 | for (int n = 0; n < N; n++) { 21 | if (combinations[n] == 0) continue; 22 | int sum = n + coins[m]; 23 | if (sum <= N) combinations[sum] += combinations[n]; 24 | } 25 | } 26 | 27 | System.out.println(combinations[N]); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /hackerrank/algorithms/dp/Equal.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | var ( 9 | options = []int{1, 2, 5} 10 | lore = make([]int, 1010) 11 | ) 12 | 13 | func lowGlow(id int) int { 14 | if id < 0 { 15 | return 1 16 | } 17 | if lore[id] >= 0 { 18 | return lore[id] 19 | } 20 | minSteps := math.MaxInt64 21 | for _, option := range options { 22 | if minSteps > lowGlow(id-option) { 23 | minSteps = lowGlow(id - option) 24 | } 25 | } 26 | lore[id] = minSteps + 1 27 | return lore[id] 28 | } 29 | 30 | func fillLore() { 31 | for i := 1; i < len(lore); i++ { 32 | lore[i] = -1 33 | } 34 | for id := range lore { 35 | lowGlow(id) 36 | } 37 | } 38 | 39 | func trim(arr *[]int) int { 40 | a := *arr 41 | min := math.MaxInt64 42 | for i := 0; i < len(a); i++ { 43 | if min > a[i] { 44 | min = a[i] 45 | } 46 | } 47 | return min 48 | } 49 | 50 | func solve(arr []int, min int) int { 51 | steps := 0 52 | for i := 0; i < len(arr); i++ { 53 | steps += lore[arr[i]-min] 54 | } 55 | return steps 56 | } 57 | 58 | func main() { 59 | fillLore() 60 | var T, N, v int 61 | fmt.Scanf("%d", &T) 62 | for t := 0; t < T; t++ { 63 | fmt.Scanf("%d", &N) 64 | if N <= 1 { 65 | fmt.Println(0) 66 | continue 67 | } 68 | arr := make([]int, N) 69 | for n := 0; n < N; n++ { 70 | fmt.Scanf("%d", &v) 71 | arr[n] = v 72 | } 73 | min := trim(&arr) 74 | res := math.MaxInt64 75 | for option := -4; option <= 0; option++ { 76 | if min >= option { 77 | tmp := solve(arr, min+option) 78 | if res > tmp { 79 | res = tmp 80 | } 81 | } 82 | } 83 | fmt.Println(res) 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /hackerrank/algorithms/dp/Fibonacci-Modified.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.math.BigInteger; 3 | import java.util.*; 4 | 5 | public class Solution { 6 | 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | int t1 = scanner.nextInt(); 10 | int t2 = scanner.nextInt(); 11 | int N = scanner.nextInt() - 2; 12 | BigInteger tMinus2 = new BigInteger(Integer.toString(t1)); 13 | BigInteger tMinus1 = new BigInteger(Integer.toString(t2)); 14 | BigInteger current = new BigInteger("-1"); 15 | 16 | for (int i = 0; i < N; i++) { 17 | current = tMinus2.add(tMinus1.multiply(tMinus1)); 18 | tMinus2 = tMinus1; 19 | tMinus1 = current; 20 | } 21 | 22 | System.out.println(current.toString()); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /hackerrank/algorithms/dp/Hacker-Rank-City.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | public static long mod = 1000000007; 6 | public static long[] T, N, E, L, a; 7 | 8 | public static long acrossTheShortBridge(int k) { 9 | return a[k] * 2; 10 | } 11 | 12 | public static long acrossTheLongBridge(int k) { 13 | return a[k] * 3; 14 | } 15 | 16 | public static long interGraph(int k) { 17 | return 2 * EN(k); 18 | } 19 | 20 | public static long N2(int k) { 21 | return N[k - 1] * N[k - 1] % mod; 22 | } 23 | 24 | public static long EN(int k) { 25 | return E[k - 1] * N[k - 1] % mod; 26 | } 27 | 28 | public static long headsToAllNodes(int k) { 29 | return 4 * N[k - 1] * a[k] + 4 * N[k - 1] * 2 * a[k] + 8 * E[k - 1]; 30 | } 31 | 32 | public static void main(String[] args) { 33 | Scanner scanner = new Scanner(System.in); 34 | 35 | int K = scanner.nextInt(); 36 | a = new long[K + 1]; 37 | N = new long[K + 1]; 38 | E = new long[K + 1]; 39 | T = new long[K + 1]; 40 | L = new long[K + 1]; 41 | 42 | N[0] = 1; 43 | E[0] = 0; 44 | T[0] = 0; 45 | L[0] = 0; 46 | 47 | scanner.nextLine(); 48 | for (int k = 1; k <= K; k++) { 49 | a[k] = scanner.nextInt(); 50 | 51 | N[k] = 4 * N[k - 1] + 2; 52 | 53 | L[k] = L[k - 1] * 2 + acrossTheLongBridge(k); 54 | 55 | E[k] = 56 | 3 * E[k - 1] 57 | + 3 * N[k - 1] * L[k - 1] // to other graphs 58 | + N[k - 1] * acrossTheShortBridge(k) 59 | + 2 * N[k - 1] * acrossTheLongBridge(k) 60 | + 3 * a[k] 61 | + 2 * L[k - 1] // to heads 62 | + E[k - 1]; // this graph path sum 63 | 64 | T[k] = 65 | 4 * T[k - 1] // graph internal sums 66 | + a[k] // inter heads sum 67 | + 4 * N2(k) * acrossTheLongBridge(k) // times across the long bidge 68 | + 2 * N2(k) * acrossTheShortBridge(k) // times across the short bidge 69 | + 6 * interGraph(k) // inter-graph combinations 70 | + headsToAllNodes(k); // from heads to all nodes 71 | 72 | N[k] %= mod; 73 | T[k] %= mod; 74 | E[k] %= mod; 75 | L[k] %= mod; 76 | } 77 | 78 | System.out.println(T[K] % mod); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /hackerrank/algorithms/dp/Knapsack.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | static int[] weights; 6 | static int[][] dp; 7 | 8 | public static int dp(int idx, int target) { 9 | if (idx < 0) return target; 10 | if (dp[idx][target] != -1) return dp[idx][target]; 11 | 12 | int minDiff = Integer.MAX_VALUE; 13 | for (int t = target; t >= 0; t -= weights[idx]) { 14 | minDiff = Math.min(minDiff, dp(idx - 1, t)); 15 | if (minDiff == 0) break; 16 | } 17 | 18 | dp[idx][target] = minDiff; 19 | return minDiff; 20 | } 21 | 22 | public static void main(String[] args) { 23 | Scanner scanner = new Scanner(System.in); 24 | int T = scanner.nextInt(); 25 | for (int t = 0; t < T; t++) { 26 | int N = scanner.nextInt(); 27 | int K = scanner.nextInt(); 28 | 29 | dp = new int[N][K + 1]; 30 | for (int n = 0; n < N; n++) Arrays.fill(dp[n], -1); 31 | 32 | weights = new int[N]; 33 | for (int n = 0; n < N; n++) weights[n] = scanner.nextInt(); 34 | 35 | System.out.println(K - dp(N - 1, K)); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /hackerrank/algorithms/dp/Lego-Blocks.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Main { 5 | static int N, M; 6 | static long[][] T, U; 7 | static final long TILES = 4; 8 | static final long MODULO = 1000000007; 9 | static final int RANGE = 1000; 10 | 11 | // calculate all brick combinations for the first row 12 | public static long calculateT(int col) { 13 | if (col < 0) return 0; 14 | if (T[1][col] != 0) return T[1][col]; 15 | for (int k = 1; k <= TILES; k++) { 16 | T[1][col] += calculateT(col - k); 17 | T[1][col] %= MODULO; 18 | } 19 | 20 | return T[1][col]; 21 | } 22 | 23 | public static void buildUpT() { 24 | for (int row = 2; row <= RANGE; row++) 25 | for (int col = 1; col <= RANGE; col++) { 26 | T[row][col] = T[1][col] * T[row - 1][col] % MODULO; 27 | } 28 | } 29 | 30 | // U[N][M] number of unbreakable walls M x N 31 | // T[N][M] number of all possible walls M x N 32 | // U[N][M] is a sum{1, M - 1} by i of U[N][M - i] * T[N]T[M - i] 33 | // thus we have recursive relation and can apply dynamic programming 34 | public static long calculateU(int col) { 35 | if (U[N][col] != 0) return U[N][col]; 36 | 37 | U[N][col] = T[N][col]; 38 | for (int i = 1; i < col; i++) { 39 | U[N][col] -= calculateU(col - i) * T[N][i]; 40 | U[N][col] %= MODULO; 41 | if (U[N][col] < 0) U[N][col] += MODULO; 42 | } 43 | 44 | return U[N][col]; 45 | } 46 | 47 | public static void main(String[] args) { 48 | Scanner scanner = new Scanner(System.in); 49 | long J = scanner.nextLong(); 50 | 51 | T = new long[RANGE + 1][RANGE + 1]; 52 | T[1][0] = 1; 53 | T[1][1] = 1; 54 | 55 | calculateT(1000); 56 | buildUpT(); 57 | 58 | U = new long[RANGE + 1][RANGE + 1]; 59 | U[1][1] = 1; 60 | 61 | for (int j = 0; j < J; j++) { 62 | N = scanner.nextInt(); 63 | M = scanner.nextInt(); 64 | 65 | if (N == 1) { 66 | System.out.println(M > TILES ? 0 : 1); 67 | } else { 68 | calculateU(M); 69 | System.out.println(U[N][M]); 70 | } 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /hackerrank/algorithms/dp/Mandragora-Forest.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | int T = scanner.nextInt(); 9 | for (int t = 0; t < T; t++) { 10 | int N = scanner.nextInt(); 11 | int S = 1; 12 | long sum = 0; 13 | long max = 0; 14 | long[] buffer = new long[N]; 15 | ArrayList array = new ArrayList<>(); 16 | for (int i = 0; i < N; i++) array.add(scanner.nextInt()); 17 | 18 | if (N == 1) { 19 | System.out.println(array.get(0)); 20 | continue; 21 | } 22 | 23 | Collections.sort(array); 24 | for (int i = N - 1; i >= 0; i--) { 25 | sum += array.get(i); 26 | buffer[i] = sum; 27 | } 28 | 29 | for (int i = 0; i < N - 1; i++) { 30 | if (buffer[i] * S > buffer[i + 1] * (S + 1)) { 31 | max = buffer[i] * S; 32 | break; 33 | } else { 34 | max = buffer[i + 1] * (S + 1); 35 | S++; 36 | } 37 | } 38 | 39 | System.out.println(max); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /hackerrank/algorithms/dp/Maximum-Subarray.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | Scanner scanner = new Scanner(System.in); 7 | long G = scanner.nextInt(); 8 | for (int g = 0; g < G; g++) { 9 | int N = scanner.nextInt(); 10 | ArrayList buffer = new ArrayList<>(); 11 | 12 | long maxSparseSum = -1; 13 | long maxContiniousSum = -1; 14 | long maxContiniousSumEndingHere = -1; 15 | 16 | for (int n = 0; n < N; n++) { 17 | long number = scanner.nextInt(); 18 | buffer.add(number); 19 | if (n == 0) { 20 | maxSparseSum = number; 21 | maxContiniousSum = number; 22 | maxContiniousSumEndingHere = number; 23 | } else { 24 | maxSparseSum = Math.max(number, Math.max(maxSparseSum, maxSparseSum + number)); 25 | } 26 | } 27 | 28 | for (int i = 1; i < N; i++) { 29 | long number = buffer.get(i); 30 | maxContiniousSumEndingHere = Math.max(maxContiniousSumEndingHere + number, number); 31 | maxContiniousSum = Math.max(maxContiniousSum, maxContiniousSumEndingHere); 32 | } 33 | 34 | System.out.println(maxContiniousSum + " " + maxSparseSum); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /hackerrank/algorithms/dp/Mr-KMarsh.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | static final char swamp = 'x'; 6 | static int N, M; 7 | static char[][] field; 8 | static int[][][] lookup; 9 | static int u = 0, l = 1, d = 2, r = 3; 10 | 11 | public static void main(String[] args) { 12 | Scanner scanner = new Scanner(System.in); 13 | N = scanner.nextInt(); 14 | M = scanner.nextInt(); 15 | scanner.nextLine(); 16 | field = new char[N][M]; 17 | lookup = new int[N + 2][M + 2][4]; 18 | 19 | for (int n = 0; n < N; n++) { 20 | String buffer = scanner.nextLine(); 21 | for (int m = 0; m < M; m++) field[n][m] = buffer.charAt(m); 22 | } 23 | 24 | for (int n = 1; n <= N; n++) { 25 | for (int m = 1; m <= M; m++) { 26 | if (field[n - 1][m - 1] == swamp) continue; 27 | Arrays.fill(lookup[n][m], 1); 28 | 29 | lookup[n][m][u] += lookup[n - 1][m][u]; 30 | lookup[n][m][l] += lookup[n][m - 1][l]; 31 | } 32 | } 33 | 34 | for (int n = N; n > 0; n--) { 35 | for (int m = M; m > 0; m--) { 36 | if (field[n - 1][m - 1] == swamp) continue; 37 | lookup[n][m][d] += lookup[n + 1][m][d]; 38 | lookup[n][m][r] += lookup[n][m + 1][r]; 39 | } 40 | } 41 | 42 | int perimeter = 0; 43 | for (int n1 = 1; n1 <= N; n1++) 44 | for (int m1 = 1; m1 <= M; m1++) { 45 | if (field[n1 - 1][m1 - 1] == swamp) continue; 46 | int lN = n1 + lookup[n1][m1][d] - 1; 47 | int lM = m1 + lookup[n1][m1][r] - 1; 48 | if (2 * (lookup[n1][m1][d] - 1 + lookup[n1][m1][r] - 1) <= perimeter) continue; 49 | for (int n2 = lN; n2 >= n1 + 1; n2--) 50 | for (int m2 = lM; m2 >= m1 + 1; m2--) { 51 | if (field[n2 - 1][m2 - 1] == swamp) continue; 52 | int dn = n2 - n1 + 1; 53 | int dm = m2 - m1 + 1; 54 | if (lookup[n2][m2][u] < dn || lookup[n2][m2][l] < dm) continue; 55 | perimeter = Math.max(perimeter, 2 * (dm + dn - 2)); 56 | } 57 | } 58 | 59 | System.out.println(perimeter > 0 ? perimeter : "impossible"); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /hackerrank/algorithms/dp/Nikita-And-The-Game.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | static long[] reverseSums, directSums, array; 6 | 7 | public static int split(int start, int end) { 8 | for (int i = start; i < end; i++) { 9 | if (directSums[i] - directSums[start - 1] == reverseSums[i + 1] - reverseSums[end + 1]) { 10 | return 1 + Math.max(split(start, i), split(i + 1, end)); 11 | } 12 | } 13 | return 0; 14 | } 15 | 16 | public static void main(String[] args) { 17 | Scanner scanner = new Scanner(System.in); 18 | int G = scanner.nextInt(); 19 | for (int g = 0; g < G; g++) { 20 | int N = scanner.nextInt(); 21 | array = new long[N]; 22 | directSums = new long[N + 2]; 23 | reverseSums = new long[N + 2]; 24 | 25 | long directSum = 0, reverseSum = 0; 26 | 27 | for (int i = 0; i < N; i++) array[i] = scanner.nextInt(); 28 | 29 | for (int i = 1; i <= N; i++) { 30 | directSum += array[i - 1]; 31 | reverseSum += array[N - i]; 32 | directSums[i] = directSum; 33 | reverseSums[N - i + 1] = reverseSum; 34 | } 35 | 36 | System.out.println(split(1, N)); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /hackerrank/algorithms/dp/Red-John-Is-Back.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | static int upperBound = 217286; 6 | static boolean[] primes = new boolean[upperBound + 1]; 7 | static int[] primeReference = new int[upperBound + 1]; 8 | 9 | public static void sieve() { 10 | Arrays.fill(primes, true); 11 | primes[0] = false; 12 | primes[1] = false; 13 | for (int i = 2; i <= Math.sqrt(upperBound); i++) 14 | for (int j = i * i; j <= upperBound; j += i) primes[j] = false; 15 | 16 | int count = 0; 17 | for (int i = 0; i <= upperBound; i++) { 18 | if (primes[i]) ++count; 19 | primeReference[i] = count; 20 | } 21 | } 22 | 23 | public static void main(String[] args) { 24 | Scanner scanner = new Scanner(System.in); 25 | int T = scanner.nextInt(); 26 | 27 | sieve(); 28 | 29 | for (int t = 0; t < T; t++) { 30 | int N = scanner.nextInt(); 31 | int[] combinations = new int[N + 1]; 32 | combinations[0] = 1; 33 | for (int i = 0; i < N; i++) { 34 | combinations[i + 1] += combinations[i]; 35 | if (i + 4 <= N) combinations[i + 4] += combinations[i]; 36 | } 37 | 38 | int total = combinations[N]; 39 | System.out.println(primeReference[total]); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /hackerrank/algorithms/dp/Sam-And-Sub-Strings.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | String src = scanner.nextLine().trim(); 9 | int N = src.length(); 10 | int[] digits = new int[N]; 11 | for (int i = 0; i < N; i++) digits[i] = src.charAt(i) - '0'; 12 | long sum = 0; 13 | long modulo = (long) Math.pow(10, 9) + 7; 14 | long f = 1; 15 | for (int i = N - 1; i >= 0; i--) { 16 | sum = (sum + digits[i] * f * (i + 1)) % modulo; 17 | f = (f * 10 + 1) % modulo; 18 | } 19 | System.out.println(sum); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /hackerrank/algorithms/dp/Sherlock-And-Cost.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | static int T, N; 6 | static int[] limits; 7 | static int[][] dp; 8 | 9 | static void getMax() { 10 | for (int i = 1; i < N; i++) { 11 | dp[i][0] = 12 | Math.max( 13 | dp[i - 1][0] + Math.abs(limits[i] - limits[i - 1]), 14 | dp[i - 1][1] + Math.abs(limits[i] - 1)); 15 | dp[i][1] = Math.max(dp[i - 1][0] + Math.abs(limits[i - 1] - 1), dp[i - 1][1] + 0); 16 | } 17 | } 18 | 19 | public static void main(String[] args) { 20 | Scanner scanner = new Scanner(System.in); 21 | T = scanner.nextInt(); 22 | for (int t = 0; t < T; t++) { 23 | N = scanner.nextInt(); 24 | limits = new int[N]; 25 | for (int n = 0; n < N; n++) limits[n] = scanner.nextInt(); 26 | 27 | dp = new int[N][2]; 28 | // 0 - limit 29 | // 1 - 1 30 | 31 | getMax(); 32 | 33 | System.out.println(Math.max(dp[N - 1][0], dp[N - 1][1])); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /hackerrank/algorithms/dp/The-Indian-Job.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Main { 4 | static int N, G, T, S, J, dJ; 5 | static int[] time; 6 | static boolean[][] dp; 7 | 8 | public static boolean solve() { 9 | dp = new boolean[N][G + 1]; 10 | 11 | for (int n = 0; n < N; n++) dp[n][0] = true; 12 | dp[0][time[0]] = true; 13 | 14 | for (int s = 1; s <= G; s++) { 15 | for (int n = 1; n < N; n++) { 16 | if (dp[n - 1][s]) dp[n][s] = true; 17 | else { 18 | if (s >= time[n]) dp[n][s] = dp[n - 1][s - time[n]]; 19 | } 20 | } 21 | } 22 | 23 | J = -1; 24 | dJ = Integer.MAX_VALUE; 25 | for (int s = 0; s <= G; s++) { 26 | if (!dp[N - 1][s]) continue; 27 | 28 | int diff = Math.abs(S - s * 2); 29 | if (diff < dJ) { 30 | J = s; 31 | dJ = diff; 32 | } 33 | } 34 | 35 | if (J < 0) return false; 36 | return J <= G && S - J <= G; 37 | } 38 | 39 | public static void main(String[] args) { 40 | Scanner scanner = new Scanner(System.in); 41 | 42 | T = scanner.nextInt(); 43 | 44 | for (int t = 0; t < T; t++) { 45 | N = scanner.nextInt(); 46 | G = scanner.nextInt(); 47 | 48 | S = 0; 49 | time = new int[N]; 50 | for (int n = 0; n < N; n++) { 51 | time[n] = scanner.nextInt(); 52 | S += time[n]; 53 | } 54 | 55 | if (S / 2 > G) { 56 | System.out.println("NO"); 57 | continue; 58 | } else { 59 | System.out.println(solve() ? "YES" : "NO"); 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /hackerrank/algorithms/dp/The-Longest-Common-Subsequence.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | static int N, M; 6 | static int[][] dp; 7 | static int[] a1, a2; 8 | static ArrayList result = new ArrayList<>(); 9 | 10 | public static int lcs(int i, int j) { 11 | if (dp[i][j] != -1) return dp[i][j]; 12 | 13 | if (a1[i - 1] == a2[j - 1]) dp[i][j] = lcs(i - 1, j - 1) + 1; 14 | else dp[i][j] = Math.max(lcs(i - 1, j), lcs(i, j - 1)); 15 | 16 | return dp[i][j]; 17 | } 18 | 19 | public static void trace(int i, int j) { 20 | if (i == 0 || j == 0) return; 21 | 22 | if (a1[i - 1] == a2[j - 1]) { 23 | result.add(0, a1[i - 1]); 24 | trace(i - 1, j - 1); 25 | } else { 26 | if (dp[i - 1][j] > dp[i][j - 1]) trace(i - 1, j); 27 | else trace(i, j - 1); 28 | } 29 | } 30 | 31 | public static void main(String[] args) { 32 | Scanner scanner = new Scanner(System.in); 33 | N = scanner.nextInt(); 34 | M = scanner.nextInt(); 35 | a1 = new int[N]; 36 | a2 = new int[M]; 37 | dp = new int[N + 1][M + 1]; 38 | for (int i = 0; i < N; i++) a1[i] = scanner.nextInt(); 39 | for (int i = 0; i < M; i++) a2[i] = scanner.nextInt(); 40 | for (int i = 1; i <= N; i++) { 41 | Arrays.fill(dp[i], -1); 42 | dp[i][0] = 0; 43 | } 44 | 45 | lcs(N, M); 46 | trace(N, M); 47 | 48 | for (int element : result) System.out.print(element + " "); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /hackerrank/algorithms/dp/Vertical-Sticks.py: -------------------------------------------------------------------------------- 1 | def rank(list): 2 | buffer = [] 3 | for i in range(len(list)): 4 | count = 0 5 | for j in range(len(list)): 6 | if list[j] >= list[i]: 7 | count += 1 8 | buffer.append(count) 9 | return buffer 10 | 11 | 12 | def main(): 13 | T = int(input()) 14 | for t in range(T): 15 | N = int(input()) 16 | string_values = input().split(" ") 17 | values = [int(el) for el in string_values] 18 | 19 | ranks = rank(values) 20 | 21 | total = 0 22 | for i in range(N): 23 | total += (N + 1) / (ranks[i] + 1) 24 | 25 | print("{:.2f}".format(total)) 26 | 27 | main() 28 | -------------------------------------------------------------------------------- /hackerrank/algorithms/dp/Xor-And-Sum.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.math.*; 3 | import java.util.*; 4 | 5 | public class Solution { 6 | 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | String s1 = scanner.nextLine(); 10 | String s2 = scanner.nextLine(); 11 | int N = s1.length(), M = s2.length(); 12 | 13 | int modulo = (int) Math.pow(10, 9) + 7; 14 | int shiftLimit = 314159; 15 | 16 | long capacitor = 0, powerCapacitor = 1; 17 | 18 | int[] firstNumberBit = new int[N]; 19 | int[] secondNumberBitCount = new int[M]; 20 | int[] secondNumberInverseBitCount = new int[M]; 21 | 22 | for (int i = N - 1; i >= 0; i--) { 23 | if (s1.charAt(i) == '1') firstNumberBit[N - 1 - i] = 1; 24 | } 25 | for (int i = M - 1; i >= 0; i--) { 26 | int idx = M - 1 - i; 27 | if (s2.charAt(i) == '1') secondNumberBitCount[idx] = 1; 28 | if (i < M - 1) secondNumberBitCount[idx] += secondNumberBitCount[idx - 1]; 29 | } 30 | for (int i = 0; i < M; i++) { 31 | if (s2.charAt(i) == '1') secondNumberInverseBitCount[i] = 1; 32 | if (i > 0) secondNumberInverseBitCount[i] += secondNumberInverseBitCount[i - 1]; 33 | } 34 | 35 | for (int p = 0; p < shiftLimit; p++) { 36 | long bits1 = p < N ? firstNumberBit[p] : 0; 37 | long bits2 = p < M ? secondNumberBitCount[p] : secondNumberBitCount[M - 1]; 38 | 39 | if (bits1 == 1) { 40 | capacitor += (((shiftLimit + 1) - bits2) * powerCapacitor) % modulo; 41 | } else { 42 | capacitor += (bits2 * powerCapacitor) % modulo; 43 | } 44 | capacitor %= modulo; 45 | 46 | powerCapacitor = powerCapacitor * 2; 47 | powerCapacitor %= modulo; 48 | } 49 | 50 | // extra bits of second number (positions over 314159) 51 | for (int i = 0; i < M; i++) { 52 | capacitor += (powerCapacitor * secondNumberInverseBitCount[M - 1 - i]) % modulo; 53 | capacitor %= modulo; 54 | powerCapacitor = powerCapacitor * 2; 55 | powerCapacitor %= modulo; 56 | } 57 | 58 | System.out.println(capacitor); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /hackerrank/algorithms/game_theory/Game-Of-Stones.py: -------------------------------------------------------------------------------- 1 | def solve(stones): 2 | dp = [False, False, True, True] + [False] * (stones - 3) 3 | for i in range(4, stones + 1): 4 | dp[i] = not (dp[i - 2] and dp[i - 3] and dp[i - 5]) 5 | return dp[stones] 6 | 7 | if __name__ == "__main__": 8 | T = int(input()) 9 | for t in range(T): 10 | stones = int(input()) 11 | print(solve(stones) and 'First' or 'Second') 12 | -------------------------------------------------------------------------------- /hackerrank/algorithms/graph_theory/Breadth-First-Search-Shortest-Reach.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | 4 | class Graph(): 5 | 6 | def __init__(self, node_number, edges): 7 | self.size = node_number 8 | self.edges = {} 9 | for node1, node2 in edges: 10 | if not node1 in self.edges: 11 | self.edges[node1] = [node2] 12 | else: 13 | self.edges[node1].append(node2) 14 | if not node2 in self.edges: 15 | self.edges[node2] = [node1] 16 | else: 17 | self.edges[node2].append(node1) 18 | 19 | def distances_from(self, node): 20 | distances = {node: 0} 21 | wavefront = [[node, 1]] 22 | steps = 1 23 | while wavefront: 24 | current, steps = wavefront.pop() 25 | if current in self.edges: 26 | for neighbor in self.edges[current]: 27 | if not neighbor in distances: 28 | distances[neighbor] = steps 29 | wavefront.insert(0, [neighbor, steps + 1]) 30 | return distances 31 | 32 | 33 | def main(): 34 | T = int(input()) 35 | for t in range(T): 36 | N, M = [int(x) for x in input().strip().split(' ')] 37 | edges = [] 38 | for m in range(M): 39 | edges.append([int(x) for x in input().strip().split(' ')]) 40 | S = int(input()) 41 | graph = Graph(N, edges) 42 | distances = graph.distances_from(S) 43 | result = [] 44 | for node in range(1, N + 1): 45 | if not node in distances: 46 | result.append(-1) 47 | else: 48 | if distances[node]: 49 | result.append(distances[node] * 6) 50 | print(' '.join([str(x) for x in result])) 51 | 52 | main() 53 | -------------------------------------------------------------------------------- /hackerrank/algorithms/graph_theory/Clique.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | 6 | // N.B. The hint provides us with the upper bound estimate, but not the real number of edges in 7 | // Turan graph 8 | static double turan(int n, int k) { 9 | k--; 10 | if (k < 1) return 0; 11 | double result = Math.pow(n, 2); 12 | result -= n % k * Math.pow(Math.ceil((double) n / (double) k), 2); 13 | result -= (k - n % k) * Math.pow(Math.floor((double) n / (double) k), 2); 14 | return 0.5 * result; 15 | } 16 | 17 | static int bsearch(int v, int e, int start, int finish) { 18 | if (start == finish) return start; 19 | int center = start + (finish - start) / 2; 20 | double minEdges = turan(v, center); 21 | if (minEdges == e) return center; 22 | if (minEdges < e) return bsearch(v, e, center + 1, finish); 23 | else return bsearch(v, e, start, center == start ? center : center - 1); 24 | } 25 | 26 | public static void main(String[] args) { 27 | Scanner scanner = new Scanner(System.in); 28 | int T = scanner.nextInt(); 29 | 30 | for (int t = 0; t < T; t++) { 31 | int V = scanner.nextInt(); 32 | int E = scanner.nextInt(); 33 | 34 | int estimate = bsearch(V, E, 1, V); 35 | 36 | if (turan(V, estimate) < E) estimate++; 37 | if (turan(V, estimate) >= E) estimate--; 38 | 39 | System.out.println(estimate); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /hackerrank/algorithms/graph_theory/Dijkstra-Shortest-Reach.py: -------------------------------------------------------------------------------- 1 | # CAVEAT 2 | # It's actually Belman-Ford algorithm (does not pass last test case) 3 | 4 | INF = int(10**9) 5 | 6 | 7 | def route(N, M, S, edges): 8 | distances = [INF for j in range(N)] 9 | 10 | distances[S - 1] = 0 11 | 12 | for step in range(N - 1): 13 | changes = False 14 | for x, y, r in edges.values(): 15 | # relaxing edge 16 | if distances[x - 1] > distances[y - 1] + r: 17 | distances[x - 1] = distances[y - 1] + r 18 | changes = True 19 | if distances[y - 1] > distances[x - 1] + r: 20 | distances[y - 1] = distances[x - 1] + r 21 | changes = True 22 | if not changes: 23 | break 24 | 25 | return distances 26 | 27 | 28 | def main(): 29 | T = int(input()) 30 | for t in range(T): 31 | N, M = input().strip().split() 32 | N, M = (int(N), int(M)) 33 | edges = {} 34 | for m in range(M): 35 | x, y, r = [int(i) for i in input().strip().split()] 36 | key = "{}-{}".format(*sorted((x, y))) 37 | if not key in edges or edges[key][2] > r: 38 | edges[key] = (x, y, r) 39 | 40 | S = int(input()) 41 | 42 | distances = route(N, M, S, edges) 43 | distances.pop(S - 1) 44 | distances = [(x == INF and '-1' or str(x)) for x in distances] 45 | print(' '.join(distances)) 46 | 47 | main() 48 | -------------------------------------------------------------------------------- /hackerrank/algorithms/graph_theory/Even-Tree.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | public static class Node { 6 | public ArrayList edges; 7 | 8 | public Node() { 9 | edges = new ArrayList<>(); 10 | } 11 | } 12 | 13 | public static class Edge { 14 | public Node node1, node2; 15 | 16 | public Edge(Node node1, Node node2) { 17 | this.node1 = node1; 18 | this.node2 = node2; 19 | } 20 | } 21 | 22 | public static int count(Node previous, Node current) { 23 | int nodesNumber = 1; 24 | for (Node next : current.edges) { 25 | if (next == previous) continue; 26 | nodesNumber += count(current, next); 27 | } 28 | return nodesNumber; 29 | } 30 | 31 | public static void main(String[] args) { 32 | Scanner scanner = new Scanner(System.in); 33 | int N = scanner.nextInt(), M = scanner.nextInt(); 34 | Node[] nodes = new Node[N]; 35 | Edge[] edges = new Edge[M]; 36 | 37 | for (int n = 0; n < N; n++) nodes[n] = new Node(); 38 | 39 | for (int m = 0; m < M; m++) { 40 | Node node1 = nodes[scanner.nextInt() - 1]; 41 | Node node2 = nodes[scanner.nextInt() - 1]; 42 | edges[m] = new Edge(node1, node2); 43 | node1.edges.add(node2); 44 | node2.edges.add(node1); 45 | } 46 | 47 | int counter = 0; 48 | for (int i = 0; i < M; i++) { 49 | boolean evenLeft = count(edges[i].node2, edges[i].node1) % 2 == 0; 50 | boolean evenRight = count(edges[i].node1, edges[i].node2) % 2 == 0; 51 | if (evenLeft && evenRight) { 52 | edges[i].node1.edges.remove(edges[i].node2); 53 | edges[i].node2.edges.remove(edges[i].node1); 54 | counter++; 55 | } 56 | } 57 | System.out.println(counter); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /hackerrank/algorithms/graph_theory/Floyd-City-Of-Blinding-Lights.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | 6 | public static void route(int N, int[][] distances) { 7 | for (int k = 0; k < N; k++) { 8 | for (int i = 0; i < N; i++) { 9 | if (distances[i][k] == Integer.MAX_VALUE) continue; 10 | for (int j = 0; j < N; j++) { 11 | if (distances[k][j] == Integer.MAX_VALUE) continue; 12 | distances[i][j] = Math.min(distances[i][j], distances[i][k] + distances[k][j]); 13 | } 14 | } 15 | } 16 | } 17 | 18 | public static void main(String[] args) { 19 | Scanner scanner = new Scanner(System.in); 20 | 21 | int N = scanner.nextInt(); 22 | int M = scanner.nextInt(); 23 | 24 | int[][] distances = new int[N][N]; 25 | for (int n = 0; n < N; n++) { 26 | Arrays.fill(distances[n], Integer.MAX_VALUE); 27 | distances[n][n] = 0; 28 | } 29 | 30 | for (int m = 0; m < M; m++) { 31 | int x = scanner.nextInt(); 32 | int y = scanner.nextInt(); 33 | int r = scanner.nextInt(); 34 | distances[x - 1][y - 1] = Math.min(distances[x - 1][y - 1], r); 35 | } 36 | 37 | route(N, distances); 38 | 39 | int Q = scanner.nextInt(); 40 | for (int q = 0; q < Q; q++) { 41 | int src = scanner.nextInt(); 42 | int dst = scanner.nextInt(); 43 | int result = distances[src - 1][dst - 1]; 44 | System.out.println(result == Integer.MAX_VALUE ? -1 : result); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /hackerrank/algorithms/graph_theory/Jeanies-Route.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | public static class Node { 6 | public boolean deliveryNeeded = false; 7 | 8 | ArrayList edges = new ArrayList<>(); 9 | } 10 | 11 | public static class Edge { 12 | public Node source, target; 13 | public int weight; 14 | public boolean visited = false; 15 | public long deliveryDistance = 0; 16 | public long maxDistance = 0; 17 | 18 | public long estimate() { 19 | return deliveryDistance - maxDistance; 20 | } 21 | 22 | public Edge(Node source, Node target, int weight) { 23 | this.source = source; 24 | this.target = target; 25 | this.weight = weight; 26 | } 27 | } 28 | 29 | static int N, K; 30 | static ArrayList nodes, deliveries; 31 | 32 | static void startFrom(Edge prevEdge, Edge edge) { 33 | Node node = edge.target; 34 | if (!edge.visited) { 35 | for (Edge nextEdge : node.edges) { 36 | if (nextEdge.target == edge.source) continue; 37 | startFrom(edge, nextEdge); 38 | } 39 | } 40 | edge.visited = true; 41 | 42 | if (prevEdge == null) return; 43 | 44 | if (node.deliveryNeeded || edge.deliveryDistance > 0) { 45 | prevEdge.deliveryDistance += edge.weight * 2 + edge.deliveryDistance; 46 | prevEdge.maxDistance = Math.max(prevEdge.maxDistance, edge.weight + edge.maxDistance); 47 | } 48 | } 49 | 50 | public static void main(String[] args) { 51 | Scanner scanner = new Scanner(System.in); 52 | N = scanner.nextInt(); 53 | K = scanner.nextInt(); 54 | 55 | nodes = new ArrayList<>(); 56 | for (int i = 0; i < N; i++) nodes.add(new Node()); 57 | 58 | deliveries = new ArrayList<>(); 59 | for (int k = 0; k < K; k++) { 60 | Node node = nodes.get(scanner.nextInt() - 1); 61 | node.deliveryNeeded = true; 62 | deliveries.add(node); 63 | } 64 | 65 | for (int n = 0; n < N - 1; n++) { 66 | Node from = nodes.get(scanner.nextInt() - 1); 67 | Node to = nodes.get(scanner.nextInt() - 1); 68 | int weight = scanner.nextInt(); 69 | from.edges.add(new Edge(from, to, weight)); 70 | to.edges.add(new Edge(to, from, weight)); 71 | } 72 | 73 | long result = Integer.MAX_VALUE; 74 | for (Node node : deliveries) { 75 | Edge edge = new Edge(null, node, 0); 76 | startFrom(null, edge); 77 | result = Math.min(result, edge.estimate()); 78 | } 79 | System.out.println(result); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /hackerrank/algorithms/graph_theory/Journey-To-The-Moon.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | static int N, I; 6 | static int[] astronauts; 7 | 8 | static int trace(int ptr) { 9 | if (astronauts[ptr] == -1) return ptr; 10 | astronauts[ptr] = trace(astronauts[ptr]); 11 | return astronauts[ptr]; 12 | } 13 | 14 | static void join(int p1, int p2) { 15 | int leftRoot = trace(p1); 16 | int rightRoot = trace(p2); 17 | if (leftRoot != rightRoot) astronauts[rightRoot] = leftRoot; 18 | } 19 | 20 | static long countSetsProduct() { 21 | HashMap hash = new HashMap<>(); 22 | 23 | for (int n = 0; n < N; n++) { 24 | int ptr = astronauts[n] == -1 ? n : trace(n); 25 | if (!hash.containsKey(ptr)) hash.put(ptr, 1); 26 | else hash.put(ptr, hash.get(ptr) + 1); 27 | } 28 | 29 | long result = 0; 30 | long candidatesLeft = N; 31 | for (Integer country : hash.values()) { 32 | candidatesLeft -= country; 33 | result += country * candidatesLeft; 34 | } 35 | 36 | return result; 37 | } 38 | 39 | public static void main(String[] args) { 40 | Scanner scanner = new Scanner(System.in); 41 | N = scanner.nextInt(); 42 | I = scanner.nextInt(); 43 | 44 | astronauts = new int[N]; 45 | Arrays.fill(astronauts, -1); 46 | 47 | for (int i = 0; i < I; i++) join(scanner.nextInt(), scanner.nextInt()); 48 | 49 | System.out.println(countSetsProduct()); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /hackerrank/algorithms/graph_theory/Kruskal-MST-Really-Special-Subtree.py: -------------------------------------------------------------------------------- 1 | def kurskal(N, edges): 2 | forest_nodes = [x for x in range(N)] 3 | forest_trees = {x: [x] for x in range(N)} 4 | 5 | weight = 0 6 | for edge in edges: 7 | tree1 = forest_nodes[edge[1] - 1] 8 | tree2 = forest_nodes[edge[2] - 1] 9 | if tree1 == tree2: 10 | continue 11 | weight += edge[0][0] 12 | 13 | forest_trees[tree1] += forest_trees[tree2] 14 | del forest_trees[tree2] 15 | for node in forest_trees[tree1]: 16 | forest_nodes[node] = tree1 17 | 18 | return weight 19 | 20 | 21 | def main(): 22 | N, M = input().strip().split() 23 | N, M = (int(N), int(M)) 24 | 25 | edges = [] 26 | for m in range(M): 27 | x, y, r = [int(x) for x in input().strip().split()] 28 | edges.append(((r, x + y), x, y)) 29 | edges.sort(key=lambda tup: tup[0]) 30 | 31 | S = int(input()) 32 | 33 | weight = kurskal(N, edges) 34 | 35 | print(weight) 36 | 37 | main() 38 | -------------------------------------------------------------------------------- /hackerrank/algorithms/graph_theory/Minimum-Penalty-Path.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | public static class Node { 6 | public boolean visited = false; 7 | public int penalty; 8 | ArrayList edges = new ArrayList<>(); 9 | } 10 | 11 | public static class Edge { 12 | public Node source, target; 13 | public int weight; 14 | 15 | public Edge(Node source, Node target, int weight) { 16 | this.source = source; 17 | this.target = target; 18 | this.weight = weight; 19 | } 20 | } 21 | 22 | static int N, M, mask; 23 | static ArrayList nodes; 24 | static Node start, finish; 25 | 26 | static boolean bfs(int number) { 27 | for (Node node : nodes) { 28 | node.visited = false; 29 | node.penalty = 0; 30 | } 31 | LinkedList queue = new LinkedList<>(); 32 | start.visited = true; 33 | queue.addFirst(start); 34 | 35 | while (!queue.isEmpty()) { 36 | Node node = queue.pollFirst(); 37 | for (Edge edge : node.edges) { 38 | if ((edge.weight & ~number) != 0) continue; 39 | if (edge.target.visited) continue; 40 | edge.target.visited = true; 41 | 42 | edge.target.penalty = edge.source.penalty | edge.weight; 43 | if (edge.target == finish) return true; 44 | 45 | queue.addLast(edge.target); 46 | } 47 | } 48 | 49 | return false; 50 | } 51 | 52 | public static void main(String[] args) { 53 | Scanner scanner = new Scanner(System.in); 54 | N = scanner.nextInt(); 55 | M = scanner.nextInt(); 56 | 57 | nodes = new ArrayList<>(); 58 | for (int i = 0; i < N; i++) nodes.add(new Node()); 59 | 60 | Edge edge; 61 | for (int i = 0; i < M; i++) { 62 | Node source = nodes.get(scanner.nextInt() - 1); 63 | Node destination = nodes.get(scanner.nextInt() - 1); 64 | int weight = scanner.nextInt(); 65 | edge = new Edge(source, destination, weight); 66 | source.edges.add(edge); 67 | edge = new Edge(destination, source, weight); 68 | destination.edges.add(edge); 69 | mask |= weight; 70 | } 71 | start = nodes.get(scanner.nextInt() - 1); 72 | finish = nodes.get(scanner.nextInt() - 1); 73 | 74 | for (int i = 1; i <= mask; i++) { 75 | if (bfs(i)) { 76 | System.out.println(finish.penalty); 77 | return; 78 | } 79 | } 80 | System.out.println(-1); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /hackerrank/algorithms/graph_theory/Prims-MST-Special-Subtree.py: -------------------------------------------------------------------------------- 1 | from heapq import heappush, heappop 2 | 3 | INF = int(10**9) 4 | 5 | 6 | def add_to_heap(heap, src, edges): 7 | for dst, distance in edges[src].items(): 8 | heappush(heap, (distance, src, dst)) 9 | 10 | 11 | def prim(N, S, edges): 12 | weight = 0 13 | vertices = [S] 14 | heap = [] 15 | add_to_heap(heap, S, edges) 16 | 17 | while len(vertices) != N: 18 | distance, src, dst = heappop(heap) 19 | if dst in vertices: 20 | continue 21 | weight += distance 22 | vertices.append(dst) 23 | add_to_heap(heap, dst, edges) 24 | 25 | return weight 26 | 27 | 28 | def add_edge(edges, x, y, r): 29 | edges[x] = edges.get(x, {}) 30 | edges[x][y] = edges[x].get(y, INF) 31 | edges[x][y] = min(edges[x][y], r) 32 | 33 | 34 | def main(): 35 | N, M = input().strip().split() 36 | N, M = (int(N), int(M)) 37 | 38 | edges = {} 39 | for m in range(M): 40 | x, y, r = [int(x) for x in input().strip().split()] 41 | add_edge(edges, x, y, r) 42 | add_edge(edges, y, x, r) 43 | S = int(input()) 44 | 45 | weight = prim(N, S, edges) 46 | 47 | print(weight) 48 | 49 | main() 50 | -------------------------------------------------------------------------------- /hackerrank/algorithms/graph_theory/Rust-And-Murderer.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "os" 7 | "strconv" 8 | "strings" 9 | ) 10 | 11 | func fuse(n int, start int, edges map[int]map[int]bool) []int { 12 | distances := make([]int, n) 13 | linked := make([]int, 0, n) 14 | linked = append(linked, start) 15 | unlinked := make(map[int]bool) 16 | for i := 0; i < n; i++ { 17 | if i != start { 18 | unlinked[i] = true 19 | } 20 | } 21 | 22 | distance := 1 23 | transfer := make([]int, 0, n) 24 | for len(unlinked) != 0 { 25 | transfer = transfer[:0] 26 | for source, _ := range unlinked { 27 | for _, target := range linked { 28 | if !edges[source][target] { 29 | transfer = append(transfer, source) 30 | break 31 | } 32 | } 33 | } 34 | 35 | for _, node := range transfer { 36 | distances[node] = distance 37 | delete(unlinked, node) 38 | linked = append(linked, node) 39 | } 40 | distance++ 41 | } 42 | 43 | return distances 44 | } 45 | 46 | func solve() { 47 | var n, m, s int 48 | fmt.Scanln(&n, &m) 49 | 50 | edges := make(map[int]map[int]bool) 51 | 52 | var town1, town2 int 53 | for i := 0; i < m; i++ { 54 | fmt.Scanln(&town1, &town2) 55 | town1-- 56 | town2-- 57 | if _, ok := edges[town1]; !ok { 58 | edges[town1] = make(map[int]bool) 59 | } 60 | if _, ok := edges[town2]; !ok { 61 | edges[town2] = make(map[int]bool) 62 | } 63 | edges[town1][town2] = true 64 | edges[town2][town1] = true 65 | } 66 | fmt.Scanln(&s) 67 | s-- 68 | 69 | f := bufio.NewWriter(os.Stdout) 70 | distances := fuse(n, s, edges) 71 | 72 | output := make([]string, 0, n) 73 | for i := 0; i < n; i++ { 74 | if i != s { 75 | output = append(output, strconv.Itoa(distances[i])) 76 | } 77 | } 78 | fmt.Fprintln(f, strings.Join(output, " ")) 79 | f.Flush() 80 | } 81 | 82 | func main() { 83 | var t int 84 | fmt.Scanln(&t) 85 | for i := 0; i < t; i++ { 86 | solve() 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /hackerrank/algorithms/graph_theory/Snakes-And-Ladders-The-Quickest-Way-Up.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | static final int SIZE = 100, FACES = 6, NOT_VISITED = -1; 6 | static int[] dp, ladders; 7 | 8 | static void solve(int position, int step) { 9 | if (position >= SIZE) return; 10 | position = ladders[position]; 11 | 12 | if (dp[position] != NOT_VISITED && dp[position] <= step) return; 13 | 14 | dp[position] = step; 15 | for (int i = FACES; i >= 1; i--) solve(position + i, step + 1); 16 | } 17 | 18 | public static void main(String[] args) { 19 | Scanner scanner = new Scanner(System.in); 20 | int T = scanner.nextInt(); 21 | 22 | for (int t = 0; t < T; t++) { 23 | ladders = new int[SIZE]; 24 | dp = new int[SIZE]; 25 | Arrays.fill(dp, NOT_VISITED); 26 | 27 | for (int i = 0; i < SIZE; i++) ladders[i] = i; 28 | 29 | int N = scanner.nextInt(); 30 | for (int n = 0; n < N; n++) ladders[scanner.nextInt() - 1] = scanner.nextInt() - 1; 31 | int M = scanner.nextInt(); 32 | for (int m = 0; m < M; m++) ladders[scanner.nextInt() - 1] = scanner.nextInt() - 1; 33 | 34 | solve(0, 0); 35 | System.out.println(dp[SIZE - 1]); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /hackerrank/algorithms/graph_theory/The-Story-of-a-Tree.go: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hypersolid/competitive-programming/d42dff410f3a9665431a14b3cffd98c5ab024879/hackerrank/algorithms/graph_theory/The-Story-of-a-Tree.go -------------------------------------------------------------------------------- /hackerrank/algorithms/graph_theory/Tree-Flow.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.IOException; 3 | import java.io.InputStreamReader; 4 | import java.util.*; 5 | 6 | public class Solution { 7 | static class Edge { 8 | public int from, to; 9 | public long weight, acc = 0; 10 | 11 | public Edge(int from, int to, long weight) { 12 | this.from = from; 13 | this.to = to; 14 | this.weight = weight; 15 | } 16 | } 17 | 18 | static HashMap> connections = new HashMap<>(500000); 19 | static int N; 20 | static long acc; 21 | static LinkedList queue = new LinkedList<>(); 22 | 23 | public static void dfs() { 24 | while (!queue.isEmpty()) { 25 | Edge current = queue.removeFirst(); 26 | acc += current.acc; 27 | for (Edge edge : connections.get(current.to)) { 28 | if (current.from == edge.to) continue; 29 | queue.addLast(edge); 30 | edge.acc = edge.weight + current.acc; 31 | } 32 | } 33 | } 34 | 35 | public static long traverseFrom(int node) { 36 | acc = 0; 37 | for (Edge edge : connections.get(node)) { 38 | edge.acc = edge.weight; 39 | queue.addLast(edge); 40 | } 41 | dfs(); 42 | return acc; 43 | } 44 | 45 | public static void main(String[] args) { 46 | try { 47 | BufferedReader reader = new BufferedReader(new InputStreamReader(System.in), 2 * 1024 * 1024); 48 | N = Integer.parseInt(reader.readLine()); 49 | 50 | for (int i = 0; i < N - 1; i++) { 51 | String[] tokens = reader.readLine().split(" "); 52 | int from = Integer.parseInt(tokens[0]); 53 | int to = Integer.parseInt(tokens[1]); 54 | int weight = Integer.parseInt(tokens[2]); 55 | 56 | if (!connections.containsKey(from)) connections.put(from, new ArrayList<>()); 57 | if (!connections.containsKey(to)) connections.put(to, new ArrayList<>()); 58 | 59 | connections.get(from).add(new Edge(from, to, weight)); 60 | connections.get(to).add(new Edge(to, from, weight)); 61 | } 62 | 63 | System.out.println(Math.min(traverseFrom(1), traverseFrom(N))); 64 | } catch (IOException e) { 65 | throw new RuntimeException(e); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /hackerrank/algorithms/greedy/Greedy-Florist.py: -------------------------------------------------------------------------------- 1 | N, K = input().split(" ") 2 | N, K = int(N), int(K) 3 | 4 | prices = [int(x) for x in input().split(" ")] 5 | descendentPrices = reversed(sorted(prices)[:N]) 6 | 7 | total = 0 8 | purchased = 0 9 | for i, price in enumerate(descendentPrices): 10 | total += price * (purchased + 1) 11 | if (i + 1) % K == 0: 12 | purchased += 1 13 | 14 | print(total) 15 | -------------------------------------------------------------------------------- /hackerrank/algorithms/greedy/Grid-Challange.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | T = int(input()) 4 | for t in range(T): 5 | N = int(input()) 6 | matrix = [sorted(input().strip()) for n in range(N)] 7 | 8 | flag = True 9 | for j in range(N): 10 | for i in range(1, N): 11 | if matrix[i - 1][j] > matrix[i][j]: 12 | flag = False 13 | 14 | print(flag and 'YES' or 'NO') 15 | -------------------------------------------------------------------------------- /hackerrank/algorithms/greedy/Largest-Permutation.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | 9 | # Complete the largestPermutation function below. 10 | def largestPermutation(k, arr): 11 | hash = {} 12 | sorted_array = reversed(sorted(arr)) 13 | 14 | if k >= len(arr): 15 | return sorted_array 16 | 17 | for i, el in enumerate(arr): 18 | hash[el] = i 19 | 20 | for i, el in enumerate(sorted_array): 21 | if arr[i] != el: 22 | k -= 1 23 | index1 = i 24 | index2 = hash[el] 25 | arr[index1], arr[index2] = arr[index2], arr[index1] 26 | hash[arr[index1]], hash[arr[index2]] = index1, index2 27 | if k == 0: 28 | break 29 | return arr 30 | 31 | if __name__ == '__main__': 32 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 33 | 34 | nk = input().split() 35 | 36 | n = int(nk[0]) 37 | 38 | k = int(nk[1]) 39 | 40 | arr = list(map(int, input().rstrip().split())) 41 | 42 | result = largestPermutation(k, arr) 43 | 44 | fptr.write(' '.join(map(str, result))) 45 | fptr.write('\n') 46 | 47 | fptr.close() 48 | -------------------------------------------------------------------------------- /hackerrank/algorithms/greedy/Luck-Balance.py: -------------------------------------------------------------------------------- 1 | N, K = [int(x) for x in input().strip().split(' ')] 2 | 3 | non_important = [] 4 | important = [] 5 | 6 | for n in range(N): 7 | L, I = [int(x) for x in input().strip().split(' ')] 8 | if I == 1: 9 | important.append(L) 10 | else: 11 | non_important.append(L) 12 | 13 | important.sort(reverse=True) 14 | print(sum(important[:K]) - sum(important[K:]) + sum(non_important)) 15 | -------------------------------------------------------------------------------- /hackerrank/algorithms/greedy/Minimum-Absolute-Difference-In-An-Array.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | "sort" 7 | ) 8 | 9 | func main() { 10 | var N int 11 | fmt.Scanf("%d", &N) 12 | arr := make([]int, N) 13 | for i := 0; i < N; i++ { 14 | fmt.Scanf("%d", &arr[i]) 15 | } 16 | sort.Ints(arr) 17 | 18 | min := math.MaxInt64 19 | for i := 1; i < N; i++ { 20 | diff := arr[i-1] - arr[i] 21 | if diff < 0 { 22 | diff = -diff 23 | } 24 | if diff < min { 25 | min = diff 26 | } 27 | } 28 | 29 | fmt.Println(min) 30 | } 31 | -------------------------------------------------------------------------------- /hackerrank/algorithms/greedy/Sherlock-And-The-Beast.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | public static void main(String[] args) { 6 | Scanner scanner = new Scanner(System.in); 7 | int T = scanner.nextInt(); 8 | for (int t = 0; t < T; t++) { 9 | int N = scanner.nextInt(); 10 | if (N % 3 == 0 && N >= 3) for (int i = 0; i < N; i++) System.out.print('5'); 11 | else { 12 | if (N % 3 == 2 && N >= 5) { 13 | for (int i = 0; i < N - 5; i++) System.out.print('5'); 14 | for (int i = 0; i < 5; i++) System.out.print('3'); 15 | } else { 16 | if (N % 3 == 1 && N >= 10) { 17 | for (int i = 0; i < N - 10; i++) System.out.print('5'); 18 | for (int i = 0; i < 10; i++) System.out.print('3'); 19 | } else { 20 | System.out.print("-1"); 21 | } 22 | } 23 | } 24 | System.out.println(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /hackerrank/algorithms/implementation/Angry-Professor.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | 6 | t = int(input().strip()) 7 | for a0 in range(t): 8 | n, k = input().strip().split(' ') 9 | n, k = [int(n), int(k)] 10 | a = [int(a_temp) 11 | for a_temp in input().strip().split(' ') if int(a_temp) <= 0] 12 | 13 | print(len(a) < k and 'YES' or 'NO') 14 | -------------------------------------------------------------------------------- /hackerrank/algorithms/implementation/Apple-and-Orange.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var s, t, a, b, m, n, position, apples, oranges int 7 | fmt.Scanf("%d %d", &s, &t) 8 | fmt.Scanf("%d %d", &a, &b) 9 | fmt.Scanf("%d %d", &m, &n) 10 | 11 | hit := func(coord int) bool { 12 | return coord >= s && coord <= t 13 | } 14 | 15 | for i := 0; i < m; i++ { 16 | fmt.Scanf("%d", &position) 17 | if hit(a + position) { 18 | apples++ 19 | } 20 | } 21 | 22 | for i := 0; i < n; i++ { 23 | fmt.Scanf("%d", &position) 24 | if hit(b + position) { 25 | oranges++ 26 | } 27 | } 28 | fmt.Printf("%d\n%d", apples, oranges) 29 | } 30 | -------------------------------------------------------------------------------- /hackerrank/algorithms/implementation/Bigger-Is-Greater.py: -------------------------------------------------------------------------------- 1 | def next_permutation(string): 2 | n = len(string) 3 | string = list(string) 4 | current = chr(1) 5 | pivot = None 6 | superior = None 7 | 8 | # find pivot, return if None 9 | for i in reversed(range(n)): 10 | if string[i] < current: 11 | pivot = i 12 | break 13 | current = string[i] 14 | if pivot is None: 15 | return None 16 | 17 | # swap and reverse 18 | for i in range(n - 1, pivot, -1): 19 | if string[i] > string[pivot]: 20 | superior = i 21 | break 22 | string[pivot], string[superior] = string[superior], string[pivot] 23 | d = string[:pivot + 1] 24 | r = list(reversed(string[pivot + 1:])) 25 | return d + r 26 | 27 | T = int(input()) 28 | for t in range(T): 29 | string = input().strip() 30 | permutation = next_permutation(string) 31 | print(permutation and ''.join(permutation) or 'no answer') 32 | -------------------------------------------------------------------------------- /hackerrank/algorithms/implementation/Bon-Appetit.py: -------------------------------------------------------------------------------- 1 | N, K = input().split(" ") 2 | N, K = int(N), int(K) 3 | 4 | prices = [int(x) for x in input().split(" ")] 5 | charged = int(input()) 6 | 7 | annas_check = (sum(prices) - prices[K]) // 2 8 | 9 | if charged == annas_check: 10 | print("Bon Appetit") 11 | else: 12 | print(charged - annas_check) 13 | -------------------------------------------------------------------------------- /hackerrank/algorithms/implementation/Cut-The-Sticks.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | 6 | n = int(input().strip()) 7 | arr = [int(arr_temp) for arr_temp in input().strip().split(' ')] 8 | 9 | arr.sort() 10 | 11 | print(n) 12 | 13 | for i, _ in enumerate(arr): 14 | if i < n - 1 and arr[i + 1] > arr[i]: 15 | print(n - 1 - i) 16 | -------------------------------------------------------------------------------- /hackerrank/algorithms/implementation/Divisible-Sum-Pairs.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.math.*; 3 | import java.text.*; 4 | import java.util.*; 5 | import java.util.regex.*; 6 | 7 | public class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int N = in.nextInt(); 12 | int K = in.nextInt(); 13 | int[] A = new int[N]; 14 | for (int i = 0; i < N; i++) A[i] = in.nextInt(); 15 | 16 | int count = 0; 17 | for (int i = 0; i < N; i++) for (int j = i + 1; j < N; j++) if ((A[i] + A[j]) % K == 0) count++; 18 | System.out.println(count); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /hackerrank/algorithms/implementation/Flat-Land-Space-Stations.py: -------------------------------------------------------------------------------- 1 | inf = 1e9 2 | n, _ = input().strip().split(' ') 3 | n = int(n) 4 | stations = [0 for x in range(n)] 5 | left = [inf for x in range(n)] 6 | right = [inf for x in range(n)] 7 | for x in input().strip().split(' '): 8 | stations[int(x)] = 1 9 | 10 | odometer = inf 11 | for i in range(0, n): 12 | if stations[i]: 13 | odometer = 0 14 | else: 15 | if odometer < inf: 16 | odometer += 1 17 | left[i] = odometer 18 | 19 | odometer = inf 20 | for i in range(n - 1, -1, -1): 21 | if stations[i]: 22 | odometer = 0 23 | else: 24 | if odometer < inf: 25 | odometer += 1 26 | right[i] = odometer 27 | 28 | result = 0 29 | for i in range(0, n): 30 | min_distance = min(left[i], right[i]) 31 | if min_distance < inf: 32 | result = max(result, min_distance) 33 | 34 | print(result) 35 | -------------------------------------------------------------------------------- /hackerrank/algorithms/implementation/Grading-Students.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var N, grade int 7 | fmt.Scanf("%d", &N) 8 | for i := 0; i < N; i++ { 9 | fmt.Scanf("%d", &grade) 10 | fmt.Println(round(grade)) 11 | } 12 | 13 | } 14 | 15 | func round(grade int) int { 16 | if grade < 38 { 17 | return grade 18 | } 19 | if grade%5 >= 3 { 20 | return (grade + 5) / 5 * 5 21 | } 22 | return grade 23 | } 24 | -------------------------------------------------------------------------------- /hackerrank/algorithms/implementation/Jumping-On-The-Clouds-Revisited.py: -------------------------------------------------------------------------------- 1 | n, k = input().strip().split(' ') 2 | n, k = [int(n), int(k)] 3 | c = [int(c_temp) for c_temp in input().strip().split(' ')] 4 | 5 | i = 0 6 | e = 100 7 | while i != 0 or e == 100: 8 | i = (i + k) % n 9 | if c[i] == 1: 10 | e -= 3 11 | else: 12 | e -= 1 13 | 14 | print(e) 15 | -------------------------------------------------------------------------------- /hackerrank/algorithms/implementation/Jumping-On-The-Clouds.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | n = int(input().strip()) 6 | c = [int(c_temp) for c_temp in input().strip().split(' ')] 7 | 8 | 9 | def jump(position): 10 | steps = [] 11 | 12 | for i in range(1, 3): 13 | if (position <= n - 1 - i and c[position + i] == 0): 14 | steps.append(jump(position + i) + 1) 15 | 16 | return steps and min(steps) or 0 17 | 18 | print(jump(0)) 19 | -------------------------------------------------------------------------------- /hackerrank/algorithms/implementation/Kangoroo.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | 6 | def sign(x): return 1 if x >= 0 else -1 7 | 8 | x1, v1, x2, v2 = input().strip().split(' ') 9 | x1, v1, x2, v2 = [int(x1), int(v1), int(x2), int(v2)] 10 | 11 | dx = x2 - x1 12 | dv = v2 - v1 13 | 14 | if (x1 == x2): 15 | print('YES') 16 | sys.exit() 17 | 18 | if sign(dx) == sign(dv): 19 | print('NO') 20 | sys.exit() 21 | 22 | if dx % dv == 0: 23 | print('YES') 24 | else: 25 | print('NO') 26 | -------------------------------------------------------------------------------- /hackerrank/algorithms/implementation/Library-Fine.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | d1, m1, y1 = input().strip().split(' ') 4 | d1, m1, y1 = [int(d1), int(m1), int(y1)] 5 | d2, m2, y2 = input().strip().split(' ') 6 | d2, m2, y2 = [int(d2), int(m2), int(y2)] 7 | 8 | returned = datetime.datetime(year=y1, month=m1, day=d1) 9 | expected = datetime.datetime(year=y2, month=m2, day=d2) 10 | 11 | fine = 0 12 | if returned > expected: 13 | if m1 == m2 and y1 == y2: 14 | fine = (returned - expected).days * 15 15 | else: 16 | if y1 == y2: 17 | fine = (m1 - m2) * 500 18 | else: 19 | fine = 10000 20 | 21 | print(fine) 22 | -------------------------------------------------------------------------------- /hackerrank/algorithms/implementation/Lisas-Workbook.py: -------------------------------------------------------------------------------- 1 | N, K = input().split(" ") 2 | N, K = int(N), int(K) 3 | T = [int(x) for x in input().split(" ")] 4 | 5 | total = 0 6 | 7 | new_page = False 8 | page = 0 9 | for tasks in T: 10 | if not new_page: 11 | page += 1 12 | for task in range(1, tasks + 1): 13 | new_page = False 14 | if task == page: 15 | total += 1 16 | if task % K == 0: 17 | page += 1 18 | new_page = True 19 | 20 | print(total) 21 | -------------------------------------------------------------------------------- /hackerrank/algorithms/implementation/Non-Divisible-Sub-Set.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | n, k = [int(x) for x in input().strip().split()] 4 | array = [int(x) for x in input().strip().split()] 5 | frequencies = {} 6 | 7 | for el in array: 8 | if el % k in frequencies: 9 | frequencies[el % k] = frequencies[el % k] + 1 10 | else: 11 | frequencies[el % k] = 1 12 | 13 | if 0 in frequencies: 14 | frequencies[0] = min((frequencies[0], 1)) 15 | if k / 2 in frequencies: 16 | frequencies[k / 2] = min((frequencies[k / 2], 1)) 17 | 18 | # print(frequencies) 19 | 20 | for key in frequencies.keys(): 21 | if k / 2 != key and k - key in frequencies: 22 | if (frequencies[k - key] > frequencies[key]): 23 | frequencies[key] = 0 24 | else: 25 | frequencies[k - key] = 0 26 | 27 | total = sum(frequencies.values()) 28 | print(total) 29 | -------------------------------------------------------------------------------- /hackerrank/algorithms/implementation/Organizing-Containers-of-Balls.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.math.*; 3 | import java.security.*; 4 | import java.text.*; 5 | import java.util.*; 6 | import java.util.concurrent.*; 7 | import java.util.regex.*; 8 | 9 | public class Solution { 10 | 11 | // Complete the organizingContainers function below. 12 | static boolean organizingContainers(int[][] container) { 13 | int N = container.length; 14 | int[] balls = new int[N]; 15 | int[] containers = new int[N]; 16 | for (int i = 0; i < N; i++) { 17 | for (int j = 0; j < N; j++) { 18 | balls[j] += container[j][i]; 19 | containers[i] += container[j][i]; 20 | } 21 | } 22 | Arrays.sort(balls); 23 | Arrays.sort(containers); 24 | 25 | for (int i = 0; i < N; i++) { 26 | if (balls[i] != containers[i]) { 27 | return false; 28 | } 29 | } 30 | return true; 31 | } 32 | 33 | private static final Scanner scanner = new Scanner(System.in); 34 | 35 | public static void main(String[] args) throws IOException { 36 | BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); 37 | 38 | int q = scanner.nextInt(); 39 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 40 | 41 | for (int qItr = 0; qItr < q; qItr++) { 42 | int n = scanner.nextInt(); 43 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 44 | 45 | int[][] container = new int[n][n]; 46 | 47 | for (int i = 0; i < n; i++) { 48 | String[] containerRowItems = scanner.nextLine().split(" "); 49 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 50 | 51 | for (int j = 0; j < n; j++) { 52 | int containerItem = Integer.parseInt(containerRowItems[j]); 53 | container[i][j] = containerItem; 54 | } 55 | } 56 | 57 | String result = organizingContainers(container) ? "Possible" : "Impossible"; 58 | 59 | bufferedWriter.write(result); 60 | bufferedWriter.newLine(); 61 | } 62 | 63 | bufferedWriter.close(); 64 | 65 | scanner.close(); 66 | } 67 | } 68 | 69 | -------------------------------------------------------------------------------- /hackerrank/algorithms/implementation/Repeated-String.py: -------------------------------------------------------------------------------- 1 | s = input().strip() 2 | n = int(input().strip()) 3 | 4 | memo = [] 5 | count = 0 6 | for i in range(len(s)): 7 | if s[i] == 'a': 8 | count += 1 9 | memo.append(count) 10 | 11 | result = memo[-1] * (n // len(s)) 12 | if n % len(s) > 0: 13 | result += memo[n % len(s) - 1] 14 | 15 | print(result) 16 | -------------------------------------------------------------------------------- /hackerrank/algorithms/implementation/Save-The-Prisoner.py: -------------------------------------------------------------------------------- 1 | T = int(input()) 2 | 3 | for t in range(T): 4 | N, M, S = [int(x) for x in input().strip().split(' ')] 5 | 6 | id = (M + S - 2) % N + 1 7 | print(id) 8 | -------------------------------------------------------------------------------- /hackerrank/algorithms/implementation/Sock-Merchant.py: -------------------------------------------------------------------------------- 1 | n = int(input().strip()) 2 | color_map = {} 3 | for color in input().strip().split(' '): 4 | color_map.setdefault(color, 0) 5 | color_map[color] += 1 6 | 7 | pairs = 0 8 | for socks in color_map.values(): 9 | pairs += socks // 2 10 | 11 | print(pairs) 12 | -------------------------------------------------------------------------------- /hackerrank/algorithms/implementation/Strange-Counter.py: -------------------------------------------------------------------------------- 1 | T = int(input().strip()) 2 | S = 3 3 | P = 1 4 | 5 | while P < T: 6 | P += S 7 | S *= 2 8 | 9 | if P == T: 10 | print(S) 11 | else: 12 | print(P - T) 13 | -------------------------------------------------------------------------------- /hackerrank/algorithms/implementation/Viral-Advertising.py: -------------------------------------------------------------------------------- 1 | N = int(input()) 2 | 3 | total = 0 4 | viewers = 5 5 | 6 | for i in range(N): 7 | total += viewers // 2 8 | viewers = viewers // 2 * 3 9 | 10 | print(total) 11 | -------------------------------------------------------------------------------- /hackerrank/algorithms/misc/DFS-Connected-Cell-in-a-Grid.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.math.*; 3 | import java.security.*; 4 | import java.text.*; 5 | import java.util.*; 6 | import java.util.concurrent.*; 7 | import java.util.regex.*; 8 | 9 | public class Solution { 10 | private static ArrayDeque queue = new ArrayDeque<>(); 11 | static int[][] grid; 12 | static int n, m; 13 | 14 | static int checkBoundariesAndAddToQueue(int i, int j) { 15 | if (i < 0 || i >= n || j < 0 || j >= m) { 16 | return 0; 17 | } 18 | if (grid[i][j] == 0) { 19 | return 0; 20 | } 21 | queue.add(new int[] {i, j}); 22 | grid[i][j] = 0; 23 | return 1; 24 | } 25 | 26 | static int dfs(int i, int j) { 27 | int counter = checkBoundariesAndAddToQueue(i, j); 28 | 29 | while (!queue.isEmpty()) { 30 | int[] pair = queue.remove(); 31 | counter += checkBoundariesAndAddToQueue(pair[0] - 1, pair[1]); 32 | counter += checkBoundariesAndAddToQueue(pair[0], pair[1] - 1); 33 | counter += checkBoundariesAndAddToQueue(pair[0] + 1, pair[1]); 34 | counter += checkBoundariesAndAddToQueue(pair[0], pair[1] + 1); 35 | counter += checkBoundariesAndAddToQueue(pair[0] - 1, pair[1] - 1); 36 | counter += checkBoundariesAndAddToQueue(pair[0] + 1, pair[1] + 1); 37 | counter += checkBoundariesAndAddToQueue(pair[0] - 1, pair[1] + 1); 38 | counter += checkBoundariesAndAddToQueue(pair[0] + 1, pair[1] - 1); 39 | } 40 | 41 | return counter; 42 | } 43 | 44 | // Complete the maxRegion function below. 45 | static int maxRegion() { 46 | int result = 0; 47 | for (int i = 0; i < n; i++) { 48 | for (int j = 0; j < m; j++) { 49 | result = Math.max(result, dfs(i, j)); 50 | } 51 | } 52 | return result; 53 | } 54 | 55 | private static final Scanner scanner = new Scanner(System.in); 56 | 57 | public static void main(String[] args) throws IOException { 58 | BufferedWriter bufferedWriter = 59 | new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); 60 | 61 | n = scanner.nextInt(); 62 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 63 | 64 | m = scanner.nextInt(); 65 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 66 | 67 | grid = new int[n][m]; 68 | 69 | for (int i = 0; i < n; i++) { 70 | String[] gridRowItems = scanner.nextLine().split(" "); 71 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 72 | 73 | for (int j = 0; j < m; j++) { 74 | int gridItem = Integer.parseInt(gridRowItems[j]); 75 | grid[i][j] = gridItem; 76 | } 77 | } 78 | 79 | int res = maxRegion(); 80 | 81 | bufferedWriter.write(String.valueOf(res)); 82 | bufferedWriter.newLine(); 83 | 84 | bufferedWriter.close(); 85 | 86 | scanner.close(); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /hackerrank/algorithms/misc/Frequency-Queries.java: -------------------------------------------------------------------------------- 1 | import static java.util.stream.Collectors.joining; 2 | 3 | import java.io.*; 4 | import java.math.*; 5 | import java.security.*; 6 | import java.text.*; 7 | import java.util.*; 8 | import java.util.concurrent.*; 9 | import java.util.function.*; 10 | import java.util.regex.*; 11 | import java.util.stream.*; 12 | 13 | public class Solution { 14 | // Complete the freqQuery function below. 15 | static List freqQuery(List queries) { 16 | HashMap frequencies = new HashMap<>(); 17 | int[] quantities = new int[queries.size() + 1]; 18 | List result = new ArrayList<>(); 19 | int frequency, value; 20 | 21 | for (int[] query : queries) { 22 | value = query[1]; 23 | switch (query[0]) { 24 | case 1: 25 | // process fq 26 | frequency = frequencies.getOrDefault(value, 0); 27 | frequencies.put(value, frequency + 1); 28 | // process qt 29 | quantities[frequency]--; 30 | quantities[frequency + 1]++; 31 | break; 32 | case 2: 33 | // process fq 34 | frequency = frequencies.getOrDefault(value, 0); 35 | if (frequency == 0) break; 36 | if (frequency == 1) frequencies.remove(value); 37 | else frequencies.put(value, frequency - 1); 38 | // process qt 39 | quantities[frequency]--; 40 | quantities[frequency - 1]++; 41 | break; 42 | case 3: 43 | if (value >= quantities.length) result.add(0); 44 | else result.add(quantities[value] > 0 ? 1 : 0); 45 | break; 46 | } 47 | } 48 | 49 | return result; 50 | } 51 | 52 | public static void main(String[] args) throws IOException { 53 | try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))) { 54 | int q = Integer.parseInt(bufferedReader.readLine().trim()); 55 | List queries = new ArrayList<>(q); 56 | Pattern p = Pattern.compile("^(\\d+)\\s+(\\d+)\\s*$"); 57 | for (int i = 0; i < q; i++) { 58 | int[] query = new int[2]; 59 | Matcher m = p.matcher(bufferedReader.readLine()); 60 | if (m.matches()) { 61 | query[0] = Integer.parseInt(m.group(1)); 62 | query[1] = Integer.parseInt(m.group(2)); 63 | queries.add(query); 64 | } 65 | } 66 | List ans = freqQuery(queries); 67 | try (BufferedWriter bufferedWriter = 68 | new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")))) { 69 | bufferedWriter.write(ans.stream().map(Object::toString).collect(joining("\n")) + "\n"); 70 | } 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /hackerrank/algorithms/misc/Min-Max-Riddle.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.math.*; 3 | import java.security.*; 4 | import java.text.*; 5 | import java.util.*; 6 | import java.util.concurrent.*; 7 | import java.util.regex.*; 8 | 9 | public class Solution { 10 | 11 | // Complete the riddle function below. 12 | static long[] riddle(long[] arr) { 13 | int N = arr.length; 14 | long[] result = new long[N]; 15 | long[] span = new long[N]; 16 | 17 | ArrayDeque deckValues = new ArrayDeque<>(); 18 | ArrayDeque deckIndexes = new ArrayDeque<>(); 19 | deckIndexes.push(-1L); 20 | 21 | // count number of ge elements to the left 22 | for (int i = 0; i < N; i++) { 23 | while (!deckValues.isEmpty() && deckValues.peek() >= arr[i]) { 24 | deckValues.pop(); 25 | deckIndexes.pop(); 26 | } 27 | span[i] = i - deckIndexes.peek() - 1; 28 | deckValues.push(arr[i]); 29 | deckIndexes.push((long) i); 30 | } 31 | 32 | // count number of ge elements to the right 33 | deckValues.clear(); 34 | deckIndexes.clear(); 35 | deckIndexes.push((long) N); 36 | for (int i = N - 1; i >= 0; i--) { 37 | while (!deckValues.isEmpty() && deckValues.peek() >= arr[i]) { 38 | deckValues.pop(); 39 | deckIndexes.pop(); 40 | } 41 | span[i] += deckIndexes.peek() - i - 1; 42 | deckValues.push(arr[i]); 43 | deckIndexes.push((long) i); 44 | } 45 | 46 | // fill results 47 | for (int i = 0; i < N; i++) { 48 | result[(int) span[i]] = Math.max(result[(int) span[i]], arr[i]); 49 | } 50 | 51 | // fill the gaps 52 | for (int i = N - 2; i >= 0; i--) { 53 | result[i] = Math.max(result[i], result[i + 1]); 54 | } 55 | 56 | return result; 57 | } 58 | 59 | private static final Scanner scanner = new Scanner(System.in); 60 | 61 | public static void main(String[] args) throws IOException { 62 | BufferedWriter bufferedWriter = 63 | new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); 64 | 65 | int n = scanner.nextInt(); 66 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 67 | 68 | long[] arr = new long[n]; 69 | 70 | String[] arrItems = scanner.nextLine().split(" "); 71 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 72 | 73 | for (int i = 0; i < n; i++) { 74 | long arrItem = Long.parseLong(arrItems[i]); 75 | arr[i] = arrItem; 76 | } 77 | 78 | long[] res = riddle(arr); 79 | 80 | for (int i = 0; i < res.length; i++) { 81 | bufferedWriter.write(String.valueOf(res[i])); 82 | 83 | if (i != res.length - 1) { 84 | bufferedWriter.write(" "); 85 | } 86 | } 87 | 88 | bufferedWriter.newLine(); 89 | 90 | bufferedWriter.close(); 91 | 92 | scanner.close(); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /hackerrank/algorithms/misc/Minimum-Swaps-2.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.math.*; 3 | import java.security.*; 4 | import java.text.*; 5 | import java.util.*; 6 | import java.util.concurrent.*; 7 | import java.util.regex.*; 8 | 9 | public class Solution { 10 | 11 | // Complete the minimumSwaps function below. 12 | static int minimumSwaps(int[] arr) { 13 | int N = arr.length; 14 | HashMap positions = new HashMap(10000); 15 | int swaps = 0; 16 | for (int i = 0; i < N; i++) positions.put(arr[i] - 1, i); 17 | for (int i = 0; i < N - 1; i++) { 18 | if (arr[i] == i + 1) continue; 19 | 20 | int val1 = arr[i]; 21 | int val2 = arr[positions.get(i)]; 22 | 23 | int pos1 = i; 24 | int pos2 = positions.get(i); 25 | 26 | arr[pos1] = val2; 27 | arr[pos2] = val1; 28 | 29 | positions.put(val1 - 1, pos2); 30 | positions.put(val2 - 1, pos1); 31 | swaps++; 32 | } 33 | return swaps; 34 | } 35 | 36 | private static final Scanner scanner = new Scanner(System.in); 37 | 38 | public static void main(String[] args) throws IOException { 39 | BufferedWriter bufferedWriter = 40 | new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); 41 | 42 | int n = scanner.nextInt(); 43 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 44 | 45 | int[] arr = new int[n]; 46 | 47 | String[] arrItems = scanner.nextLine().split(" "); 48 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 49 | 50 | for (int i = 0; i < n; i++) { 51 | int arrItem = Integer.parseInt(arrItems[i]); 52 | arr[i] = arrItem; 53 | } 54 | 55 | int res = minimumSwaps(arr); 56 | 57 | bufferedWriter.write(String.valueOf(res)); 58 | bufferedWriter.newLine(); 59 | 60 | bufferedWriter.close(); 61 | 62 | scanner.close(); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /hackerrank/algorithms/misc/New-Year-Chaos.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.math.*; 3 | import java.security.*; 4 | import java.text.*; 5 | import java.util.*; 6 | import java.util.concurrent.*; 7 | import java.util.regex.*; 8 | 9 | public class Solution { 10 | 11 | // Complete the minimumBribes function below. 12 | static void minimumBribes(int[] q) { 13 | int minBribes = 0; 14 | for (int i = 0; i < q.length; i++) { 15 | if (q[i] - 2 > i + 1) { 16 | System.out.println("Too chaotic"); 17 | return; 18 | } 19 | for (int j = i - 1; j >= q[i] - 2 && j >= 0; j--) { 20 | if (q[j] > q[i]) minBribes++; 21 | } 22 | } 23 | System.out.println(minBribes); 24 | } 25 | 26 | private static final Scanner scanner = new Scanner(System.in); 27 | 28 | public static void main(String[] args) { 29 | int t = scanner.nextInt(); 30 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 31 | 32 | for (int tItr = 0; tItr < t; tItr++) { 33 | int n = scanner.nextInt(); 34 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 35 | 36 | int[] q = new int[n]; 37 | 38 | String[] qItems = scanner.nextLine().split(" "); 39 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 40 | 41 | for (int i = 0; i < n; i++) { 42 | int qItem = Integer.parseInt(qItems[i]); 43 | q[i] = qItem; 44 | } 45 | 46 | minimumBribes(q); 47 | } 48 | 49 | scanner.close(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /hackerrank/algorithms/misc/Special-Palindrome-Again.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.math.*; 3 | import java.security.*; 4 | import java.text.*; 5 | import java.util.*; 6 | import java.util.concurrent.*; 7 | import java.util.regex.*; 8 | 9 | public class Solution { 10 | 11 | // Complete the substrCount function below. 12 | static long substrCount(int n, String s) { 13 | long result = 0; 14 | ArrayList symbols = new ArrayList<>(); 15 | ArrayList counts = new ArrayList<>(); 16 | 17 | // RLE 18 | symbols.add(s.charAt(0)); 19 | counts.add(1L); 20 | 21 | for (int i = 1; i < s.length(); i++) { 22 | if (symbols.get(symbols.size() - 1).equals(s.charAt(i))) { 23 | counts.set(counts.size() - 1, counts.get(counts.size() - 1) + 1); 24 | } else { 25 | symbols.add(s.charAt(i)); 26 | counts.add(1L); 27 | } 28 | } 29 | 30 | // count special palindromes again 31 | for (int i = 1; i < symbols.size() - 1; i++) { 32 | if (counts.get(i) != 1) continue; 33 | if (symbols.get(i - 1).equals(symbols.get(i + 1))) { 34 | result += Math.min(counts.get(i - 1), counts.get(i + 1)); 35 | } 36 | } 37 | 38 | for (int i = 0; i < symbols.size(); i++) { 39 | long N = counts.get(i); 40 | result += (1 + N) * N / 2; 41 | } 42 | 43 | return result; 44 | } 45 | 46 | private static final Scanner scanner = new Scanner(System.in); 47 | 48 | public static void main(String[] args) throws IOException { 49 | BufferedWriter bufferedWriter = 50 | new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); 51 | 52 | int n = scanner.nextInt(); 53 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 54 | 55 | String s = scanner.nextLine(); 56 | 57 | long result = substrCount(n, s); 58 | 59 | bufferedWriter.write(String.valueOf(result)); 60 | bufferedWriter.newLine(); 61 | 62 | bufferedWriter.close(); 63 | 64 | scanner.close(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /hackerrank/algorithms/np_complete/Walking-The-Approximate-Longest-Path.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/rand" 6 | "time" 7 | ) 8 | 9 | func connected(connectivity map[int]map[int]struct{}, node1, node2 int) bool { 10 | _, ok := connectivity[node1][node2] 11 | return ok 12 | } 13 | 14 | func main() { 15 | // read the inputs 16 | rand.Seed(time.Now().UTC().UnixNano()) 17 | var n, m, node1, node2 int 18 | fmt.Scanf("%d %d\n", &n, &m) 19 | connectivity := make(map[int]map[int]struct{}, n) 20 | for i := 0; i < m; i++ { 21 | fmt.Scanf("%d %d\n", &node1, &node2) 22 | node1-- 23 | node2-- 24 | if _, ok := connectivity[node1]; !ok { 25 | connectivity[node1] = make(map[int]struct{}) 26 | } 27 | if _, ok := connectivity[node2]; !ok { 28 | connectivity[node2] = make(map[int]struct{}) 29 | } 30 | connectivity[node1][node2] = struct{}{} 31 | connectivity[node2][node1] = struct{}{} 32 | } 33 | 34 | // traverses graph from random point in several directions 35 | maxLen := 0 36 | maxPath := make([]int, 0) 37 | path := make([]int, n) 38 | iterations := 500000 / n 39 | for i := 0; i < iterations; i++ { 40 | node := rand.Intn(n) 41 | pathLen := 0 42 | visited := make([]bool, n) 43 | visited[node] = true 44 | path[pathLen] = node 45 | pathLen++ 46 | 47 | for direction := 0; direction < 2; direction++ { 48 | current := node 49 | advanced := true 50 | for advanced { 51 | advanced = false 52 | perm := rand.Perm(len(connectivity[current])) 53 | permKeys := make([]int, len(connectivity[current])) 54 | i := 0 55 | for k := range connectivity[current] { 56 | permKeys[perm[i]] = k 57 | i++ 58 | } 59 | for _, nextNode := range permKeys { 60 | if visited[nextNode] { 61 | continue 62 | } 63 | // prepend or append 64 | if direction > 0 { 65 | copy(path[1:], path[0:pathLen]) 66 | path[0] = nextNode 67 | } else { 68 | path[pathLen] = nextNode 69 | } 70 | pathLen++ 71 | current = nextNode 72 | visited[current] = true 73 | advanced = true 74 | break 75 | } 76 | } 77 | } 78 | 79 | if pathLen > maxLen { 80 | maxLen = pathLen 81 | maxPath = make([]int, pathLen) 82 | copy(maxPath[:], path[:pathLen]) 83 | } 84 | } 85 | 86 | fmt.Println(maxLen) 87 | for u := 0; u < maxLen; u++ { 88 | fmt.Printf("%d ", maxPath[u]+1) 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /hackerrank/algorithms/recursion/The-Power-Sum.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | func decompose(n, base, limit float64) int { 9 | if n == 0 { 10 | return 1 11 | } 12 | power := math.Floor(math.Pow(n, 1/base)) 13 | 14 | result := 0 15 | for i := math.Min(power, limit); i >= 1; i-- { 16 | result += decompose(n-math.Pow(i, base), base, i-1) 17 | } 18 | return result 19 | } 20 | 21 | func main() { 22 | var p, n int 23 | fmt.Scanf("%d\n%d", &n, &p) 24 | fmt.Println(decompose(float64(n), float64(p), math.MaxFloat64)) 25 | } 26 | -------------------------------------------------------------------------------- /hackerrank/algorithms/search/Gridland-Metro.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Solution { 4 | static class Interval { 5 | public int start, end; 6 | 7 | public Interval(int start, int end) { 8 | this.start = start; 9 | this.end = end; 10 | } 11 | 12 | public boolean merge(Interval prev) { 13 | boolean mergable = prev.end >= this.start; 14 | if (mergable) { 15 | this.start = Math.min(this.start, prev.start); 16 | this.end = Math.max(this.end, prev.end); 17 | } 18 | return mergable; 19 | } 20 | } 21 | 22 | static int N, M, K; 23 | static HashMap> intervals = new HashMap<>(); 24 | 25 | public static void main(String[] args) { 26 | Scanner scanner = new Scanner(System.in); 27 | 28 | M = scanner.nextInt(); 29 | N = scanner.nextInt(); 30 | K = scanner.nextInt(); 31 | 32 | for (int i = 0; i < K; i++) { 33 | int row = scanner.nextInt(); 34 | int start = scanner.nextInt(); 35 | int finish = scanner.nextInt(); 36 | 37 | if (!intervals.containsKey(row)) intervals.put(row, new ArrayList<>()); 38 | intervals.get(row).add(new Interval(start, finish)); 39 | } 40 | 41 | long occupied = 0; 42 | for (ArrayList array : intervals.values()) { 43 | Collections.sort( 44 | array, 45 | new Comparator() { 46 | @Override 47 | public int compare(Interval i1, Interval i2) { 48 | if (i1.start > i2.start) return 1; 49 | if (i1.start < i2.start) return -1; 50 | return 0; 51 | } 52 | }); 53 | 54 | for (int i = 0; i < array.size(); i++) { 55 | if (i < array.size() - 1 && array.get(i + 1).merge(array.get(i))) continue; 56 | occupied += array.get(i).end + 1 - array.get(i).start; 57 | } 58 | } 59 | 60 | System.out.println((long) M * N - occupied); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /hackerrank/algorithms/search/Hackerland-Radio-Transmitters.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sort" 6 | ) 7 | 8 | func main() { 9 | var n, k int 10 | fmt.Scanf("%d %d", &n, &k) 11 | if n == 0 { 12 | fmt.Print(0) 13 | return 14 | } 15 | 16 | houses := make([]int, n) 17 | for i := 0; i < n; i++ { 18 | fmt.Scanf("%d", &houses[i]) 19 | } 20 | 21 | sort.Ints(houses) 22 | 23 | transmitters := 0 24 | coverage := houses[0] - 1 25 | toCover := -1 26 | 27 | for i := 0; i < n; i++ { 28 | if houses[i] <= coverage { 29 | continue 30 | } 31 | 32 | toCover = i 33 | 34 | for ; i < n; i++ { 35 | if i+1 < n { 36 | if houses[i+1]-k > houses[toCover] { 37 | break 38 | } 39 | } else { 40 | break 41 | } 42 | } 43 | coverage = houses[i] + k 44 | transmitters++ 45 | } 46 | 47 | fmt.Print(transmitters) 48 | } 49 | -------------------------------------------------------------------------------- /hackerrank/algorithms/search/Ice-Cream-Parlor.rb: -------------------------------------------------------------------------------- 1 | def solve 2 | dollars = gets.to_i 3 | gets.to_i # don't need this line 4 | types = gets.split(' ').map(&:to_i) 5 | types = types.each_with_index 6 | .map { |v, i| [i + 1, v] } 7 | .sort { |a, b| a[1] <=> b[1] } 8 | 9 | i = 0 10 | j = types.size - 1 11 | while types[i][1] + types[j][1] != dollars do 12 | if types[i][1] + types[j][1] > dollars 13 | j -= 1 14 | if i == j 15 | i += 1 16 | j = types.size - 1 17 | end 18 | else 19 | i += 1 20 | end 21 | end 22 | result = [types[i][0], types[j][0]] 23 | puts result.sort.join(' ') 24 | end 25 | 26 | t = gets.to_i 27 | t.times { solve } 28 | -------------------------------------------------------------------------------- /hackerrank/algorithms/search/Minimum-Loss.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | "sort" 7 | ) 8 | 9 | type Price struct { 10 | V, I int 11 | } 12 | type Prices []Price 13 | 14 | func (p Prices) Len() int { return len(p) } 15 | func (p Prices) Swap(i, j int) { p[i], p[j] = p[j], p[i] } 16 | func (p Prices) Less(i, j int) bool { return p[i].V < p[j].V } 17 | 18 | func main() { 19 | var N int 20 | fmt.Scanf("%d", &N) 21 | prices := make(Prices, N) 22 | for i := 0; i < N; i++ { 23 | fmt.Scanf("%d", &prices[i].V) 24 | prices[i].I = i 25 | } 26 | sort.Sort(prices) 27 | 28 | var min, diff int 29 | min = math.MaxInt64 30 | for distance := 1; distance < N; distance++ { 31 | for i := 0; i < N-distance; i++ { 32 | if prices[i].I < prices[i+distance].I { 33 | continue 34 | } 35 | diff = prices[i+distance].V - prices[i].V 36 | if diff < min { 37 | min = diff 38 | } 39 | } 40 | if min < math.MaxInt64 { 41 | fmt.Println(min) 42 | return 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /hackerrank/algorithms/search/Missing-Numbers.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | int A = scanner.nextInt(); 9 | HashMap aHash = new HashMap<>(); 10 | for (int a = 0; a < A; a++) { 11 | int value = scanner.nextInt(); 12 | if (aHash.containsKey(value)) aHash.put(value, aHash.get(value) + 1); 13 | else aHash.put(value, 0); 14 | } 15 | 16 | int B = scanner.nextInt(); 17 | HashMap bHash = new HashMap<>(); 18 | for (int b = 0; b < B; b++) { 19 | int value = scanner.nextInt(); 20 | if (bHash.containsKey(value)) bHash.put(value, bHash.get(value) + 1); 21 | else bHash.put(value, 0); 22 | } 23 | 24 | ArrayList result = new ArrayList<>(); 25 | for (Map.Entry entry : bHash.entrySet()) { 26 | if (!aHash.containsKey(entry.getKey()) || aHash.get(entry.getKey()) < entry.getValue()) { 27 | result.add(Integer.toString(entry.getKey())); 28 | } 29 | } 30 | 31 | System.out.print(String.join(" ", result)); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /hackerrank/algorithms/search/Pairs.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | 9 | # Complete the pairs function below. 10 | def pairs(k, arr): 11 | dict = {} 12 | 13 | for number in arr: 14 | dict[number] = dict.setdefault(number, 0) + 1 15 | 16 | result = 0 17 | for number in arr: 18 | if number-k in dict: 19 | result += dict[number-k] 20 | return result 21 | 22 | if __name__ == '__main__': 23 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 24 | 25 | nk = input().split() 26 | 27 | n = int(nk[0]) 28 | 29 | k = int(nk[1]) 30 | 31 | arr = list(map(int, input().rstrip().split())) 32 | 33 | result = pairs(k, arr) 34 | 35 | fptr.write(str(result) + '\n') 36 | 37 | fptr.close() 38 | -------------------------------------------------------------------------------- /hackerrank/algorithms/search/Sherlock-And-Array.py: -------------------------------------------------------------------------------- 1 | def solve(): 2 | N = int(input()) 3 | array = [int(number) for number in input().split()] 4 | left = [] 5 | right = [] 6 | for n in range(N): 7 | left.append(0) 8 | right.append(0) 9 | 10 | left_acc = 0 11 | right_acc = 0 12 | for n in range(N): 13 | left_acc += array[n] 14 | left[n] = left_acc 15 | right_acc += array[N - 1 - n] 16 | right[N - 1 - n] = right_acc 17 | 18 | for n in range(N): 19 | if left[n] == right[n]: 20 | return True 21 | return False 22 | 23 | T = int(input()) 24 | for t in range(T): 25 | print(solve() and "YES" or "NO") 26 | -------------------------------------------------------------------------------- /hackerrank/algorithms/sorting/Big-Sorting.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var N, max int 7 | const BASE = 10 8 | buckets := make([][]*string, BASE) 9 | fmt.Scanf("%d\n", &N) 10 | arr := make([]*string, N) 11 | res := make([]*string, 0, N) 12 | repeat := make([]*string, 0, N) 13 | 14 | // input 15 | for i := 0; i < N; i++ { 16 | var s string 17 | fmt.Scanln(&s) 18 | arr[i] = &s 19 | if max < len(s) { 20 | max = len(s) 21 | } 22 | } 23 | for b := 0; b < BASE; b++ { 24 | buckets[b] = make([]*string, len(arr)) 25 | } 26 | 27 | // sort 28 | for i := 0; i < max; i++ { 29 | // reset buckets 30 | for b := 0; b < BASE; b++ { 31 | buckets[b] = buckets[b][:0] 32 | } 33 | // put strings into buckets 34 | for n := 0; n < len(arr); n++ { 35 | st := *arr[n] 36 | if len(st) < i+1 { 37 | res = append(res, arr[n]) 38 | } else { 39 | idx := len(st) - 1 - i 40 | bucketID := int(st[idx] - '0') 41 | buckets[bucketID] = append(buckets[bucketID], arr[n]) 42 | } 43 | } 44 | // restore array 45 | repeat = repeat[:0] 46 | for b := 0; b < BASE; b++ { 47 | for _, ptr := range buckets[b] { 48 | repeat = append(repeat, ptr) 49 | } 50 | } 51 | // copy repeat to source array 52 | arr = arr[:len(repeat)] 53 | for i := range repeat { 54 | arr[i] = repeat[i] 55 | } 56 | } 57 | 58 | // output 59 | for i := 0; i < len(res); i++ { 60 | fmt.Println(*res[i]) 61 | } 62 | for i := 0; i < len(repeat); i++ { 63 | fmt.Println(*repeat[i]) 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /hackerrank/algorithms/sorting/Closest-Numbers.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sort" 6 | ) 7 | 8 | func main() { 9 | var n int 10 | fmt.Scanf("%d", &n) 11 | numbers := make([]int, n) 12 | for i := 0; i < n; i++ { 13 | fmt.Scanf("%d", &numbers[i]) 14 | } 15 | sort.Ints(numbers) 16 | 17 | minDistance := 1 << 31 18 | for i := 1; i < n; i++ { 19 | if numbers[i]-numbers[i-1] < minDistance { 20 | minDistance = numbers[i] - numbers[i-1] 21 | } 22 | } 23 | 24 | for i := 1; i < n; i++ { 25 | if numbers[i]-numbers[i-1] == minDistance { 26 | fmt.Printf("%d %d ", numbers[i-1], numbers[i]) 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /hackerrank/algorithms/sorting/Find-The-Median.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | static int N, K; 6 | static int[] array; 7 | 8 | static void partition(int start, int finish) { 9 | if (start >= finish) return; 10 | 11 | int pivot = start; 12 | int left = pivot + 1; 13 | int right = finish; 14 | while (left < right) { 15 | while (left < right && array[left] <= array[pivot]) left++; 16 | while (left < right && array[right] >= array[pivot]) right--; 17 | if (left >= right) break; 18 | int tmp = array[left]; 19 | array[left] = array[right]; 20 | array[right] = tmp; 21 | } 22 | int ins = array[left] > array[pivot] ? left - 1 : left; 23 | int tmp = array[start]; 24 | array[start] = array[ins]; 25 | array[ins] = tmp; 26 | 27 | if (ins == K) return; 28 | 29 | if (ins < K) partition(ins + 1, finish); 30 | else partition(start, ins - 1); 31 | } 32 | 33 | public static void main(String[] args) { 34 | Scanner scanner = new Scanner(System.in); 35 | N = scanner.nextInt(); 36 | K = N / 2; 37 | array = new int[N]; 38 | for (int n = 0; n < N; n++) array[n] = scanner.nextInt(); 39 | partition(0, N - 1); 40 | System.out.println(array[K]); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /hackerrank/algorithms/sorting/Fraudulent-Activity-Notifications.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Solution { 4 | static int[] expenditures; 5 | static int N, D, notifications = 0; 6 | static PriorityQueue minHeap, maxHeap; 7 | 8 | static void shiftLeft() { 9 | if (!maxHeap.isEmpty() && maxHeap.size() > minHeap.size() + 1) minHeap.offer(maxHeap.poll()); 10 | } 11 | 12 | static void shiftRight() { 13 | if (!minHeap.isEmpty() && minHeap.size() > maxHeap.size() + 1) maxHeap.offer(minHeap.poll()); 14 | } 15 | 16 | static void insert(int value) { 17 | if (!maxHeap.isEmpty() && value > minHeap.peek()) { 18 | maxHeap.offer(value); 19 | shiftLeft(); 20 | } else { 21 | minHeap.offer(value); 22 | shiftRight(); 23 | } 24 | } 25 | 26 | static int medianx2() { 27 | if (minHeap.size() == maxHeap.size()) return maxHeap.peek() + minHeap.peek(); 28 | if (minHeap.size() > maxHeap.size()) return minHeap.peek() * 2; 29 | else return maxHeap.peek() * 2; 30 | } 31 | 32 | static void remove(int value) { 33 | if (minHeap.peek() >= value) { 34 | minHeap.remove(value); 35 | shiftLeft(); 36 | } else { 37 | maxHeap.remove(value); 38 | shiftRight(); 39 | } 40 | } 41 | 42 | public static void main(String[] args) { 43 | Scanner scanner = new Scanner(System.in); 44 | 45 | N = scanner.nextInt(); 46 | D = scanner.nextInt(); 47 | 48 | minHeap = new PriorityQueue<>(Collections.reverseOrder()); 49 | maxHeap = new PriorityQueue<>(); 50 | 51 | expenditures = new int[N]; 52 | 53 | for (int n = 0; n < N; n++) expenditures[n] = scanner.nextInt(); 54 | for (int i = 0; i < D; i++) insert(expenditures[i]); 55 | for (int i = D; i < N; i++) { 56 | if (expenditures[i] >= medianx2()) notifications++; 57 | if (expenditures[i] != expenditures[i - D]) { 58 | insert(expenditures[i]); 59 | remove(expenditures[i - D]); 60 | } 61 | } 62 | 63 | System.out.println(notifications); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /hackerrank/algorithms/sorting/Intro.py: -------------------------------------------------------------------------------- 1 | def bsearch(array, start, end, value): 2 | center = start + (end - start) // 2 3 | if (array[center] == value): 4 | return center 5 | else: 6 | if (array[center] > value): 7 | return bsearch(array, start, center - 1, value) 8 | else: 9 | return bsearch(array, center + 1, end, value) 10 | 11 | 12 | def main(): 13 | V = int(input()) 14 | N = int(input()) 15 | array = [int(x) for x in input().strip().split()] 16 | return bsearch(array, 0, N - 1, V) 17 | 18 | print(main()) 19 | -------------------------------------------------------------------------------- /hackerrank/algorithms/sorting/Lilys-Homework.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sort" 6 | ) 7 | 8 | func solve(parr, pbp *[]int) int { 9 | arr := *parr 10 | bp := *pbp 11 | ops := 0 12 | mm := make(map[int]int, len(arr)) 13 | for i := 0; i < len(arr); i++ { 14 | mm[arr[i]] = i 15 | } 16 | for i := 0; i < len(arr); i++ { 17 | if arr[i] == bp[i] { 18 | continue 19 | } 20 | subIdx := mm[bp[i]] 21 | arr[i], arr[subIdx] = arr[subIdx], arr[i] 22 | mm[arr[subIdx]], mm[arr[i]] = subIdx, i 23 | ops++ 24 | } 25 | return ops 26 | } 27 | 28 | func main() { 29 | var N, v int 30 | fmt.Scanf("%d", &N) 31 | if N <= 2 { 32 | fmt.Println(0) 33 | return 34 | } 35 | rev := make([]int, N) 36 | arr := make([]int, N) 37 | bp := make([]int, N) 38 | for i := 0; i < N; i++ { 39 | fmt.Scanf("%d", &v) 40 | rev[N-1-i] = v 41 | arr[i] = v 42 | bp[i] = v 43 | } 44 | sort.Ints(bp) 45 | direct := solve(&arr, &bp) 46 | reverse := solve(&rev, &bp) 47 | if direct < reverse { 48 | fmt.Println(direct) 49 | } else { 50 | fmt.Println(reverse) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /hackerrank/algorithms/strings/Alternating-Characters.py: -------------------------------------------------------------------------------- 1 | T = int(input()) 2 | for t in range(T): 3 | string = list(input().strip()) 4 | deletions = 0 5 | prev = '-' 6 | for ch in string: 7 | if prev == ch: 8 | deletions += 1 9 | prev = ch 10 | print(deletions) 11 | -------------------------------------------------------------------------------- /hackerrank/algorithms/strings/Anagram.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var n int 7 | var s string 8 | var rs []rune 9 | fmt.Scanln(&n) 10 | for i := 0; i < n; i++ { 11 | fmt.Scanln(&s) 12 | if len(s)%2 != 0 { 13 | fmt.Println(-1) 14 | } else { 15 | rs = []rune(s) 16 | l := len(s) / 2 17 | f1 := make(map[rune]int, l) 18 | f2 := make(map[rune]int, l) 19 | for j := 0; j < l; j++ { 20 | f1[rs[j]] = f1[rs[j]] + 1 21 | f2[rs[len(rs)-1-j]] = f2[rs[len(rs)-1-j]] + 1 22 | } 23 | diff := 0 24 | for k, v := range f2 { 25 | if f1[k] < v { 26 | diff += v - f1[k] 27 | } 28 | } 29 | fmt.Println(diff) 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /hackerrank/algorithms/strings/Bear-And-Steady-Gene.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.math.*; 3 | import java.text.*; 4 | import java.util.*; 5 | import java.util.regex.*; 6 | 7 | public class Solution { 8 | static int N; 9 | static int[] diffHistogram, histogram; 10 | static String gene; 11 | static int v = 4; 12 | static int result = Integer.MAX_VALUE; 13 | 14 | public static int codeAt(int idx) { 15 | switch (gene.charAt(idx)) { 16 | case 'A': 17 | return 0; 18 | case 'C': 19 | return 1; 20 | case 'T': 21 | return 2; 22 | case 'G': 23 | return 3; 24 | } 25 | return -1; 26 | } 27 | 28 | public static void constructDiff() { 29 | int target = N / v; 30 | for (int i = 0; i < N; i++) diffHistogram[codeAt(i)]++; 31 | for (int i = 0; i < v; i++) diffHistogram[i] = Math.max(0, diffHistogram[i] - target); 32 | } 33 | 34 | public static boolean compareHistograms() { 35 | for (int i = 0; i < v; i++) if (histogram[i] < diffHistogram[i]) return false; 36 | return true; 37 | } 38 | 39 | public static void slidingWindow() { 40 | int head = 0; 41 | int tail = 0; 42 | histogram[codeAt(0)]++; 43 | 44 | while (tail < N && head <= tail) { 45 | if (compareHistograms()) { 46 | result = Math.min(result, tail - head + 1); 47 | histogram[codeAt(head)]--; 48 | head++; 49 | } else { 50 | tail++; 51 | if (tail < N) histogram[codeAt(tail)]++; 52 | } 53 | } 54 | } 55 | 56 | public static void main(String[] args) { 57 | Scanner in = new Scanner(System.in); 58 | 59 | N = in.nextInt(); 60 | gene = in.next(); 61 | 62 | diffHistogram = new int[N]; 63 | histogram = new int[N]; 64 | 65 | constructDiff(); 66 | 67 | if (compareHistograms()) result = 0; 68 | else slidingWindow(); 69 | 70 | System.out.println(result); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /hackerrank/algorithms/strings/Beautiful-Binary-String.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | 6 | n = int(input().strip()) 7 | str = list(input().strip()) 8 | 9 | last_match = -100 10 | counter = 0 11 | streak = 0 12 | for i in range(len(str) - 2): 13 | if (str[i: i + 3] == ['0', '1', '0']): 14 | if i - last_match >= 3: 15 | counter += streak // 2 + streak % 2 16 | streak = 1 17 | else: 18 | streak += 1 19 | last_match = i 20 | 21 | counter += streak // 2 + streak % 2 22 | print(counter) 23 | -------------------------------------------------------------------------------- /hackerrank/algorithms/strings/Caesar-Chipher.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | const ALPHABET = 26 6 | 7 | func chipher(start, end, letter, offset int) (result int) { 8 | result = letter 9 | if letter >= start && letter <= end { 10 | result = start + (result+offset-start)%ALPHABET 11 | } 12 | return 13 | } 14 | 15 | func main() { 16 | var ( 17 | n, k int 18 | initial string 19 | ) 20 | fmt.Scanf("%d\n", &n) 21 | fmt.Scanln(&initial) 22 | fmt.Scanf("%d", &k) 23 | 24 | chipherLower := func(letter int) int { 25 | return chipher(int('a'), int('z'), letter, k) 26 | } 27 | 28 | chipherUpper := func(letter int) int { 29 | return chipher(int('A'), int('Z'), letter, k) 30 | } 31 | 32 | for _, r := range initial { 33 | fmt.Printf("%c", chipherUpper(chipherLower(int(r)))) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /hackerrank/algorithms/strings/Camel-Case.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | 6 | s = input().strip() 7 | 8 | counter = 1 9 | for ch in list(s): 10 | if ch >= 'A' and ch <= 'Z': 11 | counter += 1 12 | 13 | print(counter) 14 | -------------------------------------------------------------------------------- /hackerrank/algorithms/strings/Common-Child.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Solution { 4 | static char[] chars1, chars2; 5 | static int N; 6 | static int[][] matrix; 7 | 8 | static int dp(int p1, int p2) { 9 | if (p1 < 0 || p2 < 0) return 0; 10 | if (matrix[p1][p2] != -1) return matrix[p1][p2]; 11 | 12 | if (chars1[p1] == chars2[p2]) matrix[p1][p2] = 1 + dp(p1 - 1, p2 - 1); 13 | else matrix[p1][p2] = Math.max(dp(p1 - 1, p2), dp(p1, p2 - 1)); 14 | 15 | return matrix[p1][p2]; 16 | } 17 | 18 | public static void main(String[] args) { 19 | Scanner scanner = new Scanner(System.in); 20 | chars1 = scanner.nextLine().trim().toCharArray(); 21 | chars2 = scanner.nextLine().trim().toCharArray(); 22 | N = chars1.length; 23 | matrix = new int[N][N]; 24 | for (int i = 0; i < N; i++) Arrays.fill(matrix[i], -1); 25 | 26 | dp(N - 1, N - 1); 27 | 28 | System.out.println(matrix[N - 1][N - 1]); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /hackerrank/algorithms/strings/Funny-String.py: -------------------------------------------------------------------------------- 1 | def funny_or_not(string): 2 | N = len(string) 3 | for i in range(1, N): 4 | left = ord(string[i]) - ord(string[i - 1]) 5 | right = ord(string[N - 1 - i]) - ord(string[N - i]) 6 | if abs(left) != abs(right): 7 | return False 8 | return True 9 | 10 | T = int(input()) 11 | for t in range(T): 12 | string = input().strip() 13 | result = funny_or_not(list(string)) 14 | print(result and 'Funny' or 'Not Funny') 15 | -------------------------------------------------------------------------------- /hackerrank/algorithms/strings/Gemstones.py: -------------------------------------------------------------------------------- 1 | N = int(input()) 2 | composition = set(input().strip()) 3 | for n in range(1, N): 4 | composition &= set(input().strip()) 5 | print(len(composition)) 6 | -------------------------------------------------------------------------------- /hackerrank/algorithms/strings/HackerRank-In-A-String.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // 2 6 | // hereiamstackerrank 7 | // hackerworld 8 | // 9 | // YES 10 | // NO 11 | 12 | func main() { 13 | const QUERY = "hackerrank" 14 | var N int 15 | var sentence string 16 | fmt.Scanf("%d", &N) 17 | for i := 0; i < N; i++ { 18 | fmt.Scanln(&sentence) 19 | if subString(sentence, QUERY) { 20 | fmt.Println("YES") 21 | } else { 22 | fmt.Println("NO") 23 | } 24 | 25 | } 26 | } 27 | 28 | func subString(s, q string) bool { 29 | pQ := 0 30 | for pS := range s { 31 | if s[pS] != q[pQ] { 32 | continue 33 | } 34 | pQ++ 35 | if pQ == len(q)-1 { 36 | return true 37 | } 38 | } 39 | return false 40 | } 41 | -------------------------------------------------------------------------------- /hackerrank/algorithms/strings/Making-Anagrams.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | func main() { 9 | var a, b string 10 | fmt.Scanln(&a) 11 | fmt.Scanln(&b) 12 | diffs := make([]int, 26) 13 | for _, ch1 := range strings.ToLower(a) { 14 | diffs[ch1-'a']++ 15 | } 16 | for _, ch2 := range strings.ToLower(b) { 17 | diffs[ch2-'a']-- 18 | } 19 | total := 0 20 | for _, v := range diffs { 21 | if v < 0 { 22 | total -= v 23 | } else { 24 | total += v 25 | } 26 | 27 | } 28 | fmt.Println(total) 29 | } 30 | -------------------------------------------------------------------------------- /hackerrank/algorithms/strings/Mars-Exploration.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | signal = list(input().strip()) 6 | errors = 0 7 | for i in range(len(signal)): 8 | if (i - 1) % 3 == 0: 9 | if signal[i] != 'O': 10 | errors += 1 11 | else: 12 | if signal[i] != 'S': 13 | errors += 1 14 | print(errors) 15 | -------------------------------------------------------------------------------- /hackerrank/algorithms/strings/Palindrome-Index.py: -------------------------------------------------------------------------------- 1 | def check(string): 2 | mark = -1 3 | right = len(string) - 1 4 | for left in range(len(string) // 2): 5 | left_char = string[left] 6 | right_char = string[right] 7 | right -= 1 8 | if left_char != right_char: 9 | if mark == -1: 10 | mark = left 11 | right += 1 12 | else: 13 | mark = len(string) - 1 - mark 14 | break 15 | 16 | print(mark) 17 | 18 | T = int(input()) 19 | 20 | for t in range(T): 21 | check(list(input().strip()) 22 | -------------------------------------------------------------------------------- /hackerrank/algorithms/strings/Panagrams.py: -------------------------------------------------------------------------------- 1 | def to_i(ch): 2 | if ch >= 'a' and ch <= 'z': 3 | return ord(ch) - ord('a') + 1 4 | 5 | 6 | def panagram(str): 7 | mask = 0 8 | target = int('1' * 26, 2) 9 | for ch in list(str): 10 | shift = to_i(ch.lower()) 11 | if shift: 12 | mask |= 1 << (shift - 1) 13 | if mask == target: 14 | return 'pangram' 15 | 16 | return 'not pangram' 17 | 18 | print(panagram(input().strip())) 19 | -------------------------------------------------------------------------------- /hackerrank/algorithms/strings/Richie-Rich.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | 6 | def mismatches(string): 7 | N = len(string) 8 | result = 0 9 | for i in range(N // 2): 10 | if string[i] != string[N - 1 - i]: 11 | result += 1 12 | return result 13 | 14 | 15 | def improve(string, k, m): 16 | N = len(string) 17 | spare_replacements = k - m 18 | for i in range(N // 2): 19 | if string[i] == string[N - 1 - i]: 20 | if string[i] != '9' and spare_replacements > 1: 21 | string[i] = '9' 22 | string[N - 1 - i] = '9' 23 | spare_replacements -= 2 24 | else: 25 | if string[i] != '9' and string[N - 1 - i] != '9' and spare_replacements > 0: 26 | string[i] = '9' 27 | string[N - 1 - i] = '9' 28 | spare_replacements -= 1 29 | else: 30 | maximium = max((string[i], string[N - 1 - i])) 31 | string[N - 1 - i] = maximium 32 | string[i] = maximium 33 | 34 | if N % 2 == 1 and spare_replacements > 0: 35 | string[N // 2] = '9' 36 | 37 | if __name__ == '__main__': 38 | n, k = input().strip().split(' ') 39 | n, k = [int(n), int(k)] 40 | number = list(input().strip()) 41 | m = mismatches(number) 42 | if m > k: 43 | print(-1) 44 | else: 45 | improve(number, k, m) 46 | print(''.join(number)) 47 | -------------------------------------------------------------------------------- /hackerrank/algorithms/strings/Separate-the-Numbers.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | ) 7 | 8 | func checkProgression(start int64, s string) bool { 9 | ptr := 0 10 | nextNumber := start + 1 11 | for ptr < len(s) { 12 | nextString := strconv.FormatInt(nextNumber, 10) 13 | if ptr+len(nextString) > len(s) { 14 | return false 15 | } 16 | for i := range nextString { 17 | if s[ptr+i] != nextString[i] { 18 | return false 19 | } 20 | } 21 | ptr += len(nextString) 22 | nextNumber++ 23 | } 24 | return true 25 | } 26 | 27 | func solve(s string) int64 { 28 | var firstNumber int64 29 | for i := 1; i <= len(s)/2; i++ { 30 | firstNumber, _ = strconv.ParseInt(s[0:i], 10, 64) 31 | if checkProgression(firstNumber, s[i:]) { 32 | return firstNumber 33 | } 34 | } 35 | return -1 36 | } 37 | 38 | func main() { 39 | var ( 40 | N int 41 | s string 42 | ) 43 | fmt.Scanf("%d\n", &N) 44 | for n := 0; n < N; n++ { 45 | fmt.Scanln(&s) 46 | if len(s) < 2 || s[0] == '0' { 47 | fmt.Println("NO") 48 | } else { 49 | result := solve(s) 50 | if result > 0 { 51 | fmt.Println("YES", result) 52 | } else { 53 | fmt.Println("NO") 54 | } 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /hackerrank/algorithms/strings/Sherlock-And-Anagrams.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Solution { 4 | static HashMap substrings = new HashMap<>(10000); 5 | static String source; 6 | 7 | static long solve() { 8 | for (int i = 0; i < source.length(); i++) { 9 | for (int j = i; j < source.length(); j++) { 10 | String substring = source.substring(i, j + 1); 11 | 12 | char[] chars = substring.toCharArray(); 13 | Arrays.sort(chars); 14 | String sortedSubstring = new String(chars); 15 | 16 | if (!substrings.containsKey(sortedSubstring)) substrings.put(sortedSubstring, 0); 17 | substrings.put(sortedSubstring, substrings.get(sortedSubstring) + 1); 18 | } 19 | } 20 | 21 | long result = 0; 22 | for (Map.Entry entry : substrings.entrySet()) { 23 | // binomial coefficient n!/(n-m)!m! when m == 2 equals n * (n - 1) / 2 24 | result += entry.getValue() * (entry.getValue() - 1) / 2; 25 | } 26 | 27 | return result; 28 | } 29 | 30 | public static void main(String[] args) { 31 | Scanner scanner = new Scanner(System.in); 32 | int T = scanner.nextInt(); 33 | scanner.nextLine(); 34 | 35 | for (int i = 0; i < T; i++) { 36 | source = scanner.nextLine().trim(); 37 | substrings.clear(); 38 | System.out.println(solve()); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /hackerrank/algorithms/strings/Sherlock-and-the-Valid-String.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | func check(array []int, index int) bool { 9 | baseline := 0 10 | for i, v := range array { 11 | if v == 0 { 12 | continue 13 | } 14 | if baseline == 0 { 15 | baseline = v 16 | continue 17 | } 18 | if baseline != v { 19 | if i == index && (baseline == v-1 || v == 1) { 20 | continue 21 | } 22 | return false 23 | } 24 | } 25 | return true 26 | } 27 | 28 | func main() { 29 | var s string 30 | fmt.Scanln(&s) 31 | diffs := make([]int, 26) 32 | 33 | for _, ch := range strings.ToLower(s) { 34 | diffs[ch-'a']++ 35 | } 36 | 37 | for i := -1; i < len(diffs); i++ { 38 | if check(diffs, i) { 39 | fmt.Println("YES") 40 | return 41 | } 42 | } 43 | 44 | fmt.Println("NO") 45 | } 46 | -------------------------------------------------------------------------------- /hackerrank/algorithms/strings/Super-Reduced-String.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | s = list(input().strip()) 4 | 5 | repl = True 6 | while repl: 7 | repl = False 8 | for i in range(1, len(s)): 9 | if s[i - 1] == s[i]: 10 | repl = True 11 | s = s[:max(0, i - 1)] + s[i + 1:] 12 | break 13 | 14 | print(s and ''.join(s) or 'Empty String') 15 | -------------------------------------------------------------------------------- /hackerrank/algorithms/strings/TheLoveLetterMystery.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var ( 7 | s string 8 | t, count, diff, l int 9 | ) 10 | fmt.Scanln(&t) 11 | for i := 0; i < t; i++ { 12 | fmt.Scanln(&s) 13 | count = 0 14 | l = len(s) 15 | for j := 0; j < l/2; j++ { 16 | diff = int(s[j]) - int(s[l-1-j]) 17 | if diff < 0 { 18 | diff = -diff 19 | } 20 | count += diff 21 | } 22 | fmt.Println(count) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /hackerrank/algorithms/strings/Two-Characters.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.math.*; 3 | import java.text.*; 4 | import java.util.*; 5 | import java.util.regex.*; 6 | 7 | public class Solution { 8 | static final int ALPHABET = 26; 9 | 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | int len = in.nextInt(); 13 | String s = in.next(); 14 | 15 | int[][] lengths = new int[ALPHABET][ALPHABET]; 16 | int[][] last = new int[ALPHABET][ALPHABET]; 17 | 18 | for (int i = 0; i < s.length(); i++) { 19 | int l = s.charAt(i) - 'a'; 20 | 21 | for (int j = 0; j < ALPHABET; j++) { 22 | if (l == j) continue; 23 | 24 | int i1 = Math.min(l, j), i2 = Math.max(l, j); 25 | 26 | if (last[i1][i2] < 0) continue; 27 | 28 | if (last[i1][i2] == l + 1) last[i1][i2] = -1; 29 | else { 30 | lengths[i1][i2]++; 31 | last[i1][i2] = l + 1; 32 | } 33 | } 34 | } 35 | 36 | int result = 0; 37 | for (int i = 0; i < ALPHABET; i++) { 38 | for (int j = 0; j < ALPHABET; j++) { 39 | int i1 = Math.min(i, j), i2 = Math.max(i, j); 40 | if (i != j && last[i1][i2] > 0 && lengths[i1][i2] > 1) 41 | result = Math.max(result, lengths[i1][i2]); 42 | } 43 | } 44 | 45 | System.out.println(result); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /hackerrank/algorithms/strings/Two-Strings.py: -------------------------------------------------------------------------------- 1 | T = int(input()) 2 | for t in range(T): 3 | s1 = set(input().strip()) 4 | s2 = set(input().strip()) 5 | print(s1 & s2 and 'YES' or 'NO') 6 | -------------------------------------------------------------------------------- /hackerrank/algorithms/strings/Weighted-Uniform-Strings.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func countU(s string) (maxU []int) { 6 | maxU = make([]int, 26) 7 | if len(s) == 0 { 8 | return 9 | } 10 | 11 | var ( 12 | ch, prev byte 13 | acc int 14 | ) 15 | 16 | prev = s[0] 17 | acc = 1 18 | for i := 1; i < len(s); i++ { 19 | ch = s[i] 20 | if ch == prev { 21 | acc++ 22 | } else { 23 | acc = 1 24 | } 25 | idx := int(prev) - int('a') 26 | if maxU[idx] < acc { 27 | maxU[idx] = acc 28 | } 29 | prev = ch 30 | } 31 | idx := int(prev) - int('a') 32 | if maxU[idx] < acc { 33 | maxU[idx] = acc 34 | } 35 | return 36 | } 37 | 38 | func queryU(s *string, maxU *[]int, q int) bool { 39 | for i, v := range *maxU { 40 | if q%(i+1) == 0 && v >= q/(i+1) { 41 | return true 42 | } 43 | } 44 | return false 45 | } 46 | 47 | func main() { 48 | var ( 49 | N, q int 50 | s string 51 | ) 52 | 53 | fmt.Scanln(&s) 54 | fmt.Scanf("%d", &N) 55 | 56 | maxU := countU(s) 57 | 58 | for i := 0; i < N; i++ { 59 | fmt.Scanf("%d", &q) 60 | 61 | if queryU(&s, &maxU, q) { 62 | fmt.Println("Yes") 63 | } else { 64 | fmt.Println("No") 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /hackerrank/algorithms/warmup/AVery-Big-Sum.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | 6 | n = int(input().strip()) 7 | arr = [int(arr_temp) for arr_temp in input().strip().split(' ')] 8 | 9 | print(sum(arr)) 10 | -------------------------------------------------------------------------------- /hackerrank/algorithms/warmup/Birthday-Cake-Candles.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var N, current, count, max int 7 | fmt.Scanf("%d", &N) 8 | for i := 0; i < N; i++ { 9 | fmt.Scanf("%d", ¤t) 10 | if current == max { 11 | count++ 12 | } 13 | if current > max { 14 | max = current 15 | count = 1 16 | } 17 | } 18 | fmt.Println(count) 19 | } 20 | -------------------------------------------------------------------------------- /hackerrank/algorithms/warmup/Circular-Array-Rotation.py: -------------------------------------------------------------------------------- 1 | n, k, q = input().strip().split(' ') 2 | a = [int(x) for x in input().strip().split(' ')] 3 | 4 | for i in range(int(q)): 5 | query = int(input()) 6 | print(a[(query - int(k)) % int(n)]) 7 | -------------------------------------------------------------------------------- /hackerrank/algorithms/warmup/Compare-The-Triplets.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | 6 | a = [int(x) for x in input().strip().split(' ')] 7 | b = [int(x) for x in input().strip().split(' ')] 8 | 9 | alice = 0 10 | bob = 0 11 | for i in range(len(a)): 12 | if (a[i] > b[i]): 13 | alice += 1 14 | if (a[i] < b[i]): 15 | bob += 1 16 | 17 | print(alice, bob) 18 | -------------------------------------------------------------------------------- /hackerrank/algorithms/warmup/Diagonal-Difference.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | 6 | n = int(input().strip()) 7 | a = [] 8 | for a_i in range(n): 9 | a_t = [int(a_temp) for a_temp in input().strip().split(' ')] 10 | a.append(a_t) 11 | 12 | s1 = 0 13 | s2 = 0 14 | for i in range(n): 15 | s1 += a[i][i] 16 | s2 += a[i][n - 1 - i] 17 | 18 | print(abs(s1 - s2)) 19 | -------------------------------------------------------------------------------- /hackerrank/algorithms/warmup/Maximum-Perimeter-Triangle.py: -------------------------------------------------------------------------------- 1 | def solve(): 2 | N = input() 3 | sticks = [int(x) for x in input().strip().split()] 4 | 5 | sticks.sort(reverse=True) 6 | 7 | for i, stick1 in enumerate(sticks): 8 | for j, stick2 in enumerate(sticks): 9 | for k, stick3 in enumerate(sticks): 10 | if i == j or j == k or k == i: 11 | continue 12 | valid = True 13 | valid &= stick1 + stick2 > stick3 14 | valid &= stick2 + stick3 > stick1 15 | valid &= stick3 + stick1 > stick2 16 | if valid: 17 | print(*sorted([stick1, stick2, stick3])) 18 | return 19 | print("-1") 20 | 21 | if __name__ == "__main__": 22 | solve() 23 | -------------------------------------------------------------------------------- /hackerrank/algorithms/warmup/Mini-Max-Sum.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | import "math" 5 | 6 | func main() { 7 | N := 5 8 | var sum, current int 9 | min := math.MaxInt64 10 | max := math.MinInt64 11 | for i := 0; i < N; i++ { 12 | fmt.Scanf("%d", ¤t) 13 | if current > max { 14 | max = current 15 | } 16 | if current < min { 17 | min = current 18 | } 19 | sum += current 20 | } 21 | fmt.Println(sum-max, sum-min) 22 | } 23 | -------------------------------------------------------------------------------- /hackerrank/algorithms/warmup/Plus-Minus.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | 6 | n = int(input().strip()) 7 | arr = [int(arr_temp) for arr_temp in input().strip().split(' ')] 8 | 9 | zeroes = 0 10 | positives = 0 11 | negatives = 0 12 | for el in arr: 13 | if el > 0: 14 | positives += 1 15 | else: 16 | if el < 0: 17 | negatives += 1 18 | else: 19 | zeroes += 1 20 | 21 | print(positives / n) 22 | print(negatives / n) 23 | print(zeroes / n) 24 | -------------------------------------------------------------------------------- /hackerrank/algorithms/warmup/Simple-Array-Sum.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | 6 | n = int(input().strip()) 7 | arr = [int(arr_temp) for arr_temp in input().strip().split(' ')] 8 | -------------------------------------------------------------------------------- /hackerrank/algorithms/warmup/Time-Conversion.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | 6 | time = input().strip() 7 | h, m, s = time.split(':') 8 | z = s[-2:] 9 | s = s[:-2] 10 | if (h == '12'): 11 | if (z == 'AM'): 12 | h = 0 13 | else: 14 | h = int(h) + (z == 'PM' and 12 or 0) 15 | 16 | h = '{:02d}'.format(int(h)) 17 | print(':'.join([h, m, s])) 18 | -------------------------------------------------------------------------------- /hackerrank/algorithms/warmup/staircase.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | 6 | n = int(input().strip()) 7 | 8 | for i in range(1, n + 1): 9 | print(' ' * (n - i) + '#' * i) 10 | -------------------------------------------------------------------------------- /hackerrank/data_structures/heap/Find-the-Running-Median.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "container/heap" 5 | "fmt" 6 | ) 7 | 8 | type MinHeap []float64 9 | 10 | func (h *MinHeap) Len() int { return len(*h) } 11 | func (h *MinHeap) Peek() float64 { return (*h)[0] } 12 | func (h MinHeap) Swap(i, j int) { (h)[i], (h)[j] = (h)[j], (h)[i] } 13 | func (h MinHeap) Less(i, j int) bool { return (h)[i] < (h)[j] } 14 | func (h *MinHeap) Push(x interface{}) { 15 | *h = append(*h, x.(float64)) 16 | } 17 | func (h *MinHeap) Pop() interface{} { 18 | old := *h 19 | n := len(old) 20 | x := old[n-1] 21 | *h = old[0 : n-1] 22 | return x 23 | } 24 | 25 | type MaxHeap []float64 26 | 27 | func (h *MaxHeap) Len() int { return len(*h) } 28 | func (h *MaxHeap) Peek() float64 { return (*h)[0] } 29 | func (h MaxHeap) Swap(i, j int) { (h)[i], (h)[j] = (h)[j], (h)[i] } 30 | func (h MaxHeap) Less(i, j int) bool { return (h)[i] > (h)[j] } 31 | func (h *MaxHeap) Push(x interface{}) { 32 | *h = append(*h, x.(float64)) 33 | } 34 | func (h *MaxHeap) Pop() interface{} { 35 | old := *h 36 | n := len(old) 37 | x := old[n-1] 38 | *h = old[0 : n-1] 39 | return x 40 | } 41 | 42 | func balance(left *MaxHeap, right *MinHeap, element float64) { 43 | if left.Len() == 0 || element <= left.Peek() { 44 | heap.Push(left, element) 45 | } else { 46 | heap.Push(right, element) 47 | } 48 | 49 | if left.Len()-1 > right.Len() { 50 | heap.Push(right, heap.Pop(left)) 51 | } 52 | if right.Len()-1 > left.Len() { 53 | heap.Push(left, heap.Pop(right)) 54 | } 55 | } 56 | 57 | func median(left *MaxHeap, right *MinHeap) float64 { 58 | if left.Len() > right.Len() { 59 | return left.Peek() 60 | } else { 61 | if right.Len() > left.Len() { 62 | return right.Peek() 63 | } else { 64 | return (right.Peek() + left.Peek()) / 2 65 | } 66 | } 67 | } 68 | 69 | func main() { 70 | var n int 71 | fmt.Scanf("%d", &n) 72 | 73 | left := make(MaxHeap, 0) 74 | right := make(MinHeap, 0) 75 | var element float64 76 | for i := 0; i < n; i++ { 77 | fmt.Scanf("%f", &element) 78 | balance(&left, &right, element) 79 | fmt.Printf("%.1f\n", median(&left, &right)) 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /hackerrank/data_structures/heap/Jesse-and-Cookies.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "container/heap" 5 | "fmt" 6 | ) 7 | 8 | type IntHeap []int 9 | 10 | func (h IntHeap) Len() int { return len(h) } 11 | func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } 12 | func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } 13 | 14 | func (h *IntHeap) Push(x interface{}) { 15 | *h = append(*h, x.(int)) 16 | } 17 | 18 | func (h *IntHeap) Pop() interface{} { 19 | old := *h 20 | n := len(old) 21 | x := old[n-1] 22 | *h = old[0 : n-1] 23 | return x 24 | } 25 | 26 | func sweeten(h *IntHeap, k int) int { 27 | counter := 0 28 | for (*h)[0] < k { 29 | if h.Len() < 2 { 30 | return -1 31 | } 32 | sweetness := heap.Pop(h).(int) 33 | sweetness += heap.Pop(h).(int) * 2 34 | heap.Push(h, sweetness) 35 | counter++ 36 | } 37 | return counter 38 | } 39 | 40 | func main() { 41 | var n, k int 42 | fmt.Scanf("%d %d", &n, &k) 43 | 44 | if n == 0 { 45 | fmt.Print(-1) 46 | return 47 | } 48 | 49 | h := make(IntHeap, n) 50 | for i := 0; i < n; i++ { 51 | fmt.Scanf("%d", &h[i]) 52 | } 53 | heap.Init(&h) 54 | fmt.Print(sweeten(&h, k)) 55 | } 56 | -------------------------------------------------------------------------------- /hackerrank/data_structures/heap/Minimum-Average-Waiting-Time.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "container/heap" 5 | "fmt" 6 | "sort" 7 | ) 8 | 9 | type Order struct { 10 | arrived uint64 11 | weight uint64 12 | } 13 | 14 | type Orders []Order 15 | 16 | func (h *Orders) Len() int { return len(*h) } 17 | func (h *Orders) Swap(i, j int) { (*h)[i], (*h)[j] = (*h)[j], (*h)[i] } 18 | func (h *Orders) Less(i, j int) bool { return (*h)[i].arrived < (*h)[j].arrived } 19 | 20 | type MinHeap []Order 21 | 22 | func (h *MinHeap) Peek() Order { return (*h)[0] } 23 | func (h *MinHeap) Len() int { return len(*h) } 24 | func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } 25 | func (h MinHeap) Less(i, j int) bool { return h[i].weight < h[j].weight } 26 | func (h *MinHeap) Push(x interface{}) { 27 | *h = append(*h, x.(Order)) 28 | } 29 | func (h *MinHeap) Pop() interface{} { 30 | old := *h 31 | n := len(old) 32 | x := old[n-1] 33 | *h = old[0 : n-1] 34 | return x 35 | } 36 | 37 | func process(nextOpportunity *uint64, total *uint64, queue *MinHeap) { 38 | order := heap.Pop(queue).(Order) 39 | *nextOpportunity += uint64(order.weight) 40 | *total += *nextOpportunity - uint64(order.arrived) 41 | } 42 | 43 | // https://en.wikipedia.org/wiki/Shortest_job_next 44 | func main() { 45 | var n int 46 | fmt.Scanf("%d", &n) 47 | 48 | orders := make(Orders, n) 49 | queue := make(MinHeap, 0) 50 | 51 | for i := 0; i < n; i++ { 52 | orders[i] = Order{} 53 | fmt.Scanf("%d %d", &orders[i].arrived, &orders[i].weight) 54 | } 55 | 56 | sort.Sort(&orders) 57 | 58 | var ( 59 | nextOpportunity uint64 60 | total uint64 = 0 61 | ) 62 | 63 | for i := 0; i < n; { 64 | if orders[i].arrived <= nextOpportunity { 65 | heap.Push(&queue, orders[i]) 66 | i++ 67 | } else { 68 | if len(queue) == 0 { 69 | nextOpportunity = orders[i].arrived 70 | } else { 71 | process(&nextOpportunity, &total, &queue) 72 | } 73 | } 74 | } 75 | for len(queue) > 0 { 76 | process(&nextOpportunity, &total, &queue) 77 | } 78 | 79 | fmt.Println(total / uint64(n)) 80 | } 81 | -------------------------------------------------------------------------------- /hackerrank/data_structures/queues/Largest-Rectangle.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.math.*; 3 | import java.security.*; 4 | import java.text.*; 5 | import java.util.*; 6 | import java.util.concurrent.*; 7 | import java.util.regex.*; 8 | 9 | public class Solution { 10 | static class Bar { 11 | int width, height; 12 | 13 | Bar(int width, int height) { 14 | this.width = width; 15 | this.height = height; 16 | } 17 | } 18 | 19 | static long unwindAndCalculateArea(ArrayDeque deque, int currentHeight) { 20 | long area = 0; 21 | int width = 0; 22 | 23 | while (!deque.isEmpty() && deque.peekLast().height > currentHeight) { 24 | Bar popped = deque.removeLast(); 25 | width += popped.width; 26 | long currentArea = (long) popped.height * (long) width; 27 | area = Math.max(area, currentArea); 28 | } 29 | 30 | deque.addLast(new Bar(width + 1, currentHeight)); 31 | 32 | return area; 33 | } 34 | 35 | // Complete the largestRectangle function below. 36 | static long largestRectangle(int[] h) { 37 | long result = 0; 38 | ArrayDeque deque = new ArrayDeque<>(); 39 | for (int i = 0; i < h.length; i++) { 40 | int currentHeight = h[i]; 41 | result = Math.max(result, unwindAndCalculateArea(deque, currentHeight)); 42 | } 43 | result = Math.max(result, unwindAndCalculateArea(deque, 0)); 44 | 45 | return result; 46 | } 47 | 48 | private static final Scanner scanner = new Scanner(System.in); 49 | 50 | public static void main(String[] args) throws IOException { 51 | BufferedWriter bufferedWriter = 52 | new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); 53 | 54 | int n = scanner.nextInt(); 55 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 56 | 57 | int[] h = new int[n]; 58 | 59 | String[] hItems = scanner.nextLine().split(" "); 60 | scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); 61 | 62 | for (int i = 0; i < n; i++) { 63 | int hItem = Integer.parseInt(hItems[i]); 64 | h[i] = hItem; 65 | } 66 | 67 | long result = largestRectangle(h); 68 | 69 | bufferedWriter.write(String.valueOf(result)); 70 | bufferedWriter.newLine(); 71 | 72 | bufferedWriter.close(); 73 | 74 | scanner.close(); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /hackerrank/data_structures/queues/Truck-Tour.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import os 4 | import sys 5 | import collections 6 | 7 | # 8 | # Complete the truckTour function below. 9 | # 10 | def truckTour(petrolpumps): 11 | d = collections.deque() 12 | 13 | diffs = [pump[0]-pump[1] for pump in petrolpumps] 14 | N = len(petrolpumps) 15 | 16 | sum = 0 17 | i = 0 18 | while len(d) < N: 19 | idx = (i + len(d)) % N 20 | if sum + diffs[idx] >= 0: 21 | d.appendleft(diffs[idx]) 22 | sum += diffs[idx] 23 | else: 24 | if len(d) > 0: 25 | sum -= d.pop() 26 | i = (i + 1) % N 27 | return i 28 | 29 | for pump in petrolpumps: 30 | 31 | sum += diff 32 | if sum < 0: 33 | break 34 | for i in range(len(petrolpumps)): 35 | if sum >=0: 36 | return i 37 | 38 | sum -= d.pop() 39 | diff = petrolpumps[i][0]-petrolpumps[i][1] 40 | d.appendleft(diff) 41 | sum += diff 42 | 43 | return -1 44 | 45 | if __name__ == '__main__': 46 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 47 | 48 | n = int(input()) 49 | 50 | petrolpumps = [] 51 | 52 | for _ in range(n): 53 | petrolpumps.append(list(map(int, input().rstrip().split()))) 54 | 55 | result = truckTour(petrolpumps) 56 | 57 | fptr.write(str(result) + '\n') 58 | 59 | fptr.close() 60 | -------------------------------------------------------------------------------- /leetcode/1-two-sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums, target): 3 | """ 4 | :type nums: List[int] 5 | :type target: int 6 | :rtype: List[int] 7 | """ 8 | matching_index = {} 9 | for i, v in enumerate(nums): 10 | desired_number = target - v 11 | if desired_number in matching_index: 12 | return [matching_index[desired_number], i] 13 | matching_index[v] = i 14 | -------------------------------------------------------------------------------- /leetcode/10-regular-expression-matching.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isMatch(self, s, p): 3 | """ 4 | :type s: str 5 | :type p: str 6 | :rtype: bool 7 | """ 8 | if len(p) == 0: 9 | return len(s) == 0 10 | 11 | # case of * 12 | if len(p) > 1 and p[1] == "*": 13 | if self.isMatch(s,p[2:]): 14 | return True 15 | for i in range(len(s)): 16 | if p[0] != '.' and s[i] != p[0]: 17 | return False 18 | if self.isMatch(s[i+1:],p[2:]): 19 | return True 20 | return False 21 | 22 | # case of other letters 23 | if len(s) == 0: 24 | return False 25 | if p[0] != '.' and s[0] != p[0]: 26 | return False 27 | return self.isMatch(s[1:],p[1:]) 28 | -------------------------------------------------------------------------------- /leetcode/108-convert-sorted-array-to-binary-search-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def split(self, nums): 10 | center = len(nums) // 2 11 | return nums[0:center], nums[center], nums[center+1:len(nums)] 12 | def sortedArrayToBST(self, nums): 13 | """ 14 | :type nums: List[int] 15 | :rtype: TreeNode 16 | """ 17 | if len(nums) == 0: 18 | return None 19 | 20 | left, center, right = self.split(nums) 21 | 22 | root = TreeNode(center) 23 | root.left = self.sortedArrayToBST(left) 24 | root.right = self.sortedArrayToBST(right) 25 | 26 | return root 27 | 28 | -------------------------------------------------------------------------------- /leetcode/136-single-number.go: -------------------------------------------------------------------------------- 1 | func singleNumber(nums []int) int { 2 | result := 0 3 | for i := range nums { 4 | result ^= nums[i] 5 | } 6 | return result 7 | } 8 | -------------------------------------------------------------------------------- /leetcode/14-longest-common-prefix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestCommonPrefixInternal(self, strs): 3 | length = 0 4 | while True: 5 | letter = None 6 | for s in strs: 7 | if len(s) < length+1: 8 | return length 9 | if letter is None: 10 | letter = s[length] 11 | 12 | if s[length] != letter: 13 | return length 14 | 15 | length+=1 16 | return length 17 | 18 | def longestCommonPrefix(self, strs): 19 | """ 20 | :type strs: List[str] 21 | :rtype: str 22 | """ 23 | if len(strs) == 0: 24 | return "" 25 | 26 | length = self.longestCommonPrefixInternal(strs) 27 | if length == 0: 28 | return "" 29 | return strs[0][:length] 30 | -------------------------------------------------------------------------------- /leetcode/146-lru-cache.java: -------------------------------------------------------------------------------- 1 | class LRUCache { 2 | class Node { 3 | Node next = null; 4 | Node prev = null; 5 | int key, value; 6 | 7 | public Node(int key, int value) { 8 | this.key = key; 9 | this.value = value; 10 | } 11 | 12 | void insertBefore(Node other) { 13 | if (other == null) return; 14 | this.next = other; 15 | if (other.prev != null) other.prev.next = this; 16 | other.prev = this; 17 | } 18 | } 19 | 20 | HashMap hash = new HashMap<>(); 21 | int capacity; 22 | Node head = null, tail = null; 23 | 24 | void promote(Node node) { 25 | if (head == node) return; 26 | 27 | unbind(node); 28 | 29 | node.insertBefore(head); 30 | head = node; 31 | 32 | if (head.next == null) tail = head; 33 | else if (head.next.next == null) tail = head.next; 34 | } 35 | 36 | void unbind(Node node) { 37 | if (head == node) head = node.next; 38 | if (tail == node) { 39 | tail = node.prev; 40 | } 41 | 42 | if (node.prev != null) node.prev.next = node.next; 43 | if (node.next != null) node.next.prev = node.prev; 44 | 45 | node.prev = null; 46 | node.next = null; 47 | } 48 | 49 | void evict(int key) { 50 | Node node = hash.remove(key); 51 | if (node == null) throw new RuntimeException("tried to evict nonexistent node"); 52 | unbind(node); 53 | } 54 | 55 | public LRUCache(int capacity) { 56 | if (capacity <= 0) throw new RuntimeException("wrong capacity"); 57 | this.capacity = capacity; 58 | } 59 | 60 | public int get(int key) { 61 | Node node = hash.get(key); 62 | if (node == null) return -1; 63 | promote(node); 64 | return node.value; 65 | } 66 | 67 | public void put(int key, int value) { 68 | // clear space 69 | if (hash.containsKey(key)) { 70 | evict(key); 71 | } else { 72 | if (hash.size() == capacity) { 73 | evict(tail.key); 74 | } 75 | } 76 | 77 | // insert node 78 | Node node = new Node(key, value); 79 | hash.put(key, node); 80 | promote(node); 81 | } 82 | } 83 | /** 84 | * Your LRUCache object will be instantiated and called as such: LRUCache obj = new 85 | * LRUCache(capacity); int param_1 = obj.get(key); obj.put(key,value); 86 | */ 87 | -------------------------------------------------------------------------------- /leetcode/162-find-peak-element.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findPeakElement(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | return self.findPeakElementInternal(nums, 0, len(nums) - 1) 8 | 9 | def findPeakElementInternal(self, nums, start, end): 10 | """ 11 | :type nums: List[int] 12 | :rtype: int 13 | """ 14 | 15 | n = len(nums) 16 | mid = start + (end - start) // 2 17 | left_condition = mid - 1 < 0 or nums[mid - 1] < nums[mid] 18 | right_condition = mid + 1 >= n or nums[mid + 1] < nums[mid] 19 | if left_condition and right_condition: 20 | return mid 21 | 22 | if left_condition: 23 | return self.findPeakElementInternal(nums, mid + 1, end) 24 | return self.findPeakElementInternal(nums, start, mid - 1) 25 | -------------------------------------------------------------------------------- /leetcode/2-add-two-number.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def addTwoNumbers(self, l1, l2): 9 | """ 10 | :type l1: ListNode 11 | :type l2: ListNode 12 | :rtype: ListNode 13 | """ 14 | result_head = ListNode(0) 15 | result = result_head 16 | slow_result = result_head 17 | base = 10 18 | 19 | # add digits 20 | while l1 is not None or l2 is not None: 21 | slow_result = result 22 | if l1 is not None: 23 | result.val += l1.val 24 | if l2 is not None: 25 | result.val += l2.val 26 | 27 | carry = result.val // base 28 | result.next = ListNode(carry) 29 | result.val = result.val % base 30 | 31 | result = result.next 32 | if l1 is not None: 33 | l1 = l1.next 34 | if l2 is not None: 35 | l2 = l2.next 36 | 37 | # gets rid of prefix zero 38 | if slow_result.next and slow_result.next.val == 0: 39 | slow_result.next = None 40 | 41 | return result_head 42 | -------------------------------------------------------------------------------- /leetcode/226-Invert-Binary-Tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode 3 | * right; TreeNode(int x) { val = x; } } 4 | */ 5 | public class Solution { 6 | public TreeNode invertTree(TreeNode root) { 7 | if (root == null) return null; 8 | 9 | TreeNode tmp = root.left; 10 | root.left = root.right; 11 | root.right = tmp; 12 | 13 | invertTree(root.left); 14 | invertTree(root.right); 15 | 16 | return root; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /leetcode/3-longest-substring-without-repeating-characters.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def internalLengthOfLongestSubstring(self): 3 | ptr = 1 4 | start = 0 5 | max_length = 1 6 | length = 1 7 | while ptr < len(self.lookback): 8 | v = self.lookback[ptr] 9 | if v is not None and v >= start: 10 | start = v + 1 11 | ptr = v + 2 12 | max_length = max(length, max_length) 13 | length = 1 14 | else: 15 | length += 1 16 | ptr += 1 17 | max_length = max(length, max_length) 18 | return max_length 19 | 20 | def lengthOfLongestSubstring(self, s): 21 | """ 22 | :type s: str 23 | :rtype: int 24 | """ 25 | if len(s) == 0: 26 | return 0 27 | 28 | self.string = s 29 | self.lookback = [None for x in range(len(s))] 30 | lookdict = {} 31 | 32 | # preprocessing 33 | for i, ch in enumerate(s): 34 | if ch in lookdict: 35 | self.lookback[i] = lookdict[ch] 36 | lookdict[ch] = i 37 | 38 | # search 39 | return self.internalLengthOfLongestSubstring() 40 | -------------------------------------------------------------------------------- /leetcode/344-reverse-string.go: -------------------------------------------------------------------------------- 1 | import "bytes" 2 | 3 | func reverseString(s string) string { 4 | var buff bytes.Buffer 5 | for i := range s { 6 | buff.WriteByte(s[len(s)-1-i]) 7 | } 8 | return string(buff.Bytes()) 9 | 10 | } 11 | -------------------------------------------------------------------------------- /leetcode/4-median-of-two-sorted-arrays.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMedianSortedArrays(self, A, B): 3 | """ 4 | :type nums1: List[int] 5 | :type nums2: List[int] 6 | :rtype: float 7 | """ 8 | m, n = len(A), len(B) 9 | if m > n: 10 | A, B, m, n = B, A, n, m 11 | if n == 0: 12 | raise ValueError 13 | 14 | imin, imax, half_len = 0, m, (m + n + 1) // 2 15 | while imin <= imax: 16 | i = (imin + imax) // 2 17 | j = half_len - i 18 | if i < m and B[j-1] > A[i]: 19 | # i is too small, must increase it 20 | imin = i + 1 21 | elif i > 0 and A[i-1] > B[j]: 22 | # i is too big, must decrease it 23 | imax = i - 1 24 | else: 25 | # i is perfect 26 | 27 | if i == 0: max_of_left = B[j-1] 28 | elif j == 0: max_of_left = A[i-1] 29 | else: max_of_left = max(A[i-1], B[j-1]) 30 | 31 | if (m + n) % 2 == 1: 32 | return max_of_left 33 | 34 | if i == m: min_of_right = B[j] 35 | elif j == n: min_of_right = A[i] 36 | else: min_of_right = min(A[i], B[j]) 37 | 38 | return (max_of_left + min_of_right) / 2.0 39 | 40 | 41 | result = Solution().findMedianSortedArrays([0, 4, 5], [1,2,3]) 42 | print(result) 43 | -------------------------------------------------------------------------------- /leetcode/406-queue-reconstruction-by-height.go: -------------------------------------------------------------------------------- 1 | // Input: 2 | // [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] 3 | // Output: 4 | // [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]] 5 | 6 | // package main 7 | 8 | import "sort" 9 | 10 | // import ( 11 | // "fmt" 12 | // "sort" 13 | // ) 14 | // 15 | // func main() { 16 | // fmt.Println(reconstructQueue([][]int{[]int{7, 0}, []int{4, 4}, []int{7, 1}, []int{5, 0}, []int{6, 1}, []int{5, 2}})) 17 | // } 18 | 19 | type Pairs struct { 20 | array [][]int 21 | } 22 | 23 | func shift(array [][]int, to, from int) { 24 | val := array[from] 25 | for i := from; i > to; i-- { 26 | array[i] = array[i-1] 27 | } 28 | array[to] = val 29 | } 30 | 31 | func (p Pairs) Len() int { return len(p.array) } 32 | func (p Pairs) Swap(i, j int) { p.array[i], p.array[j] = p.array[j], p.array[i] } 33 | func (p Pairs) Less(i, j int) bool { 34 | if p.array[i][0] == p.array[j][0] { 35 | return p.array[i][1] < p.array[j][1] 36 | } 37 | return p.array[i][0] > p.array[j][0] 38 | } 39 | 40 | func reconstructQueue(people [][]int) [][]int { 41 | p := Pairs{array: people} 42 | sort.Sort(p) 43 | for i := range people { 44 | if people[i][1] != i { 45 | shift(p.array, p.array[i][1], i) 46 | } 47 | } 48 | return people 49 | } 50 | -------------------------------------------------------------------------------- /leetcode/412-fizz-buzz.go: -------------------------------------------------------------------------------- 1 | import "fmt" 2 | 3 | func fizzBuzz(n int) []string { 4 | result := make([]string, n) 5 | for i := 1; i <= n; i++ { 6 | result[i-1] = "" 7 | if i%3 == 0 { 8 | result[i-1] = "Fizz" 9 | } 10 | if i%5 == 0 { 11 | result[i-1] = result[i-1] + "Buzz" 12 | } 13 | if result[i-1] == "" { 14 | result[i-1] = fmt.Sprintf("%d", i) 15 | } 16 | } 17 | return result 18 | } 19 | -------------------------------------------------------------------------------- /leetcode/413-arithmetic-slices.go: -------------------------------------------------------------------------------- 1 | func numberOfArithmeticSlices(A []int) int { 2 | var counter, result int 3 | for i := 1; i < len(A)-1; i++ { 4 | j := i 5 | for counter = 0; j+counter < len(A)-1; counter++ { 6 | diff := A[j+counter] - A[j-1+counter] 7 | nextDiff := A[j+1+counter] - A[j+counter] 8 | if nextDiff != diff { 9 | break 10 | } 11 | } 12 | if counter > 0 { 13 | result += (counter) * (1 + counter) / 2 14 | i += counter 15 | } 16 | } 17 | return result 18 | } 19 | -------------------------------------------------------------------------------- /leetcode/419-battleships-in-a-board.go: -------------------------------------------------------------------------------- 1 | // package main 2 | // 3 | // import "fmt" 4 | // 5 | // func main() { 6 | // fmt.Println(countBattleships([][]byte{ 7 | // []byte("X..X"), 8 | // []byte("X..."), 9 | // []byte("XXX."), 10 | // })) 11 | // } 12 | 13 | type Node struct { 14 | nodes []*Node 15 | marked bool 16 | } 17 | 18 | func (n *Node) mark() { 19 | n.marked = true 20 | for _, sibling := range n.nodes { 21 | if !sibling.marked { 22 | sibling.mark() 23 | } 24 | } 25 | } 26 | 27 | func countBattleships(board [][]byte) int { 28 | memo := make([][]*Node, len(board)+1) 29 | for i := 0; i <= len(board); i++ { 30 | memo[i] = make([]*Node, len(board[0])+1) 31 | } 32 | 33 | for i := range board { 34 | for j := range board[i] { 35 | if board[i][j] == 'X' { 36 | weave(memo, i, j) 37 | } 38 | } 39 | } 40 | 41 | counter := 0 42 | for i := range memo { 43 | for j := range memo[i] { 44 | if memo[i][j] != nil && !memo[i][j].marked { 45 | memo[i][j].mark() 46 | counter++ 47 | } 48 | } 49 | } 50 | 51 | return counter 52 | } 53 | 54 | func weave(memo [][]*Node, i, j int) { 55 | i++ 56 | j++ 57 | memo[i][j] = &Node{nodes: make([]*Node, 0)} 58 | if memo[i][j-1] != nil { 59 | memo[i][j].nodes = append(memo[i][j].nodes, memo[i][j-1]) 60 | memo[i][j-1].nodes = append(memo[i][j-1].nodes, memo[i][j]) 61 | } 62 | if memo[i-1][j] != nil { 63 | memo[i][j].nodes = append(memo[i][j].nodes, memo[i-1][j]) 64 | memo[i-1][j].nodes = append(memo[i-1][j].nodes, memo[i][j]) 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /leetcode/442-find-all-duplicates-in-an-array.go: -------------------------------------------------------------------------------- 1 | func findDuplicates(nums []int) []int { 2 | for _, n := range nums { 3 | if n < 0 { 4 | n *= -1 5 | } 6 | nums[n-1] *= -1 7 | } 8 | result := make([]int, 0, len(nums)) 9 | for i := range nums { 10 | v := nums[i] 11 | if v < 0 { 12 | v *= -1 13 | } 14 | if nums[v-1] > 0 { 15 | result = append(result, v) 16 | nums[v-1] *= -1 17 | } 18 | } 19 | return result 20 | } 21 | -------------------------------------------------------------------------------- /leetcode/46-permutations.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def print(self): 3 | self.result.append(self.nums[:]) 4 | 5 | def permuteInternal(self, start, N): 6 | if start == N - 1: 7 | self.print() 8 | return 9 | for i in range(start, N): 10 | self.nums[start], self.nums[i] = self.nums[i], self.nums[start] 11 | self.permuteInternal(start+1, N) 12 | self.nums[start], self.nums[i] = self.nums[i], self.nums[start] 13 | 14 | def permute(self, nums): 15 | """ 16 | :type nums: List[int] 17 | :rtype: List[List[int]] 18 | """ 19 | self.nums = nums 20 | self.result = [] 21 | self.permuteInternal(0, len(nums)) 22 | return self.result 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /leetcode/461-hamming-distance.go: -------------------------------------------------------------------------------- 1 | func hammingDistance(x int, y int) int { 2 | res := 0 3 | k := uint32(x ^ y) 4 | for i := uint32(0); i < uint32(31); i++ { 5 | if k&(1< uint32(0) { 6 | res++ 7 | } 8 | } 9 | return res 10 | } 11 | -------------------------------------------------------------------------------- /leetcode/463-island-perimeter.go: -------------------------------------------------------------------------------- 1 | func islandPerimeter(grid [][]int) int { 2 | sum := 0 3 | for i := range grid { 4 | for j := range grid[i] { 5 | if grid[i][j] != 1 { 6 | continue 7 | } 8 | sum += probe(grid, i, j) 9 | } 10 | } 11 | return sum 12 | } 13 | 14 | func probe(grid [][]int, i, j int) int { 15 | result := 4 16 | if i > 0 && grid[i-1][j] == 1 { 17 | result-- 18 | } 19 | if j > 0 && grid[i][j-1] == 1 { 20 | result-- 21 | } 22 | if i < len(grid)-1 && grid[i+1][j] == 1 { 23 | result-- 24 | } 25 | if j < len(grid[i])-1 && grid[i][j+1] == 1 { 26 | result-- 27 | } 28 | return result 29 | } 30 | -------------------------------------------------------------------------------- /leetcode/473-matchsticks-to-square.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | ArrayList sets = new ArrayList<>(); 3 | int a; 4 | int N; 5 | int S = 0; 6 | int[] nums; 7 | 8 | void reverse(int[] input) { 9 | // handling null, empty and one element array 10 | if (input == null || input.length <= 1) { 11 | return; 12 | } 13 | 14 | for (int i = 0; i < input.length / 2; i++) { 15 | int temp = input[i]; // swap numbers 16 | input[i] = input[input.length - 1 - i]; 17 | input[input.length - 1 - i] = temp; 18 | } 19 | } 20 | 21 | boolean crosscheck() { 22 | int M = sets.size(); 23 | int[] combinataions = new int[M]; 24 | for (int i = 0; i < M; i++) { 25 | combinataions[i] = sets.get(i); 26 | } 27 | 28 | for (int a = 0; a < M; a++) { 29 | for (int b = a + 1; b < M; b++) { 30 | if ((combinataions[a] & combinataions[b]) != 0) continue; 31 | for (int c = b + 1; c < M; c++) { 32 | if ((combinataions[a] & combinataions[c]) != 0) continue; 33 | if ((combinataions[b] & combinataions[c]) != 0) continue; 34 | for (int d = c + 1; d < M; d++) { 35 | if ((combinataions[a] & combinataions[d]) != 0) continue; 36 | if ((combinataions[b] & combinataions[d]) != 0) continue; 37 | if ((combinataions[c] & combinataions[d]) != 0) continue; 38 | return true; 39 | } 40 | } 41 | } 42 | } 43 | return false; 44 | } 45 | 46 | void knapsack(int set, int sum, int index) { 47 | if (index == N || sum > a) { 48 | return; 49 | } 50 | // move forward without current element 51 | if (sum == a) { 52 | sets.add(set); 53 | // System.out.println(Integer.toString(set, 2)); 54 | return; 55 | } else { 56 | knapsack(set, sum, index + 1); 57 | } 58 | // move forward with current element 59 | int newSet = set | 1 << index; 60 | int newSum = sum + nums[index]; 61 | if (newSum == a) { 62 | sets.add(newSet); 63 | // System.out.println(Integer.toString(newSet, 2)); 64 | } else { 65 | knapsack(newSet, newSum, index + 1); 66 | } 67 | } 68 | 69 | public boolean makesquare(int[] nums) { 70 | Arrays.sort(nums); 71 | reverse(nums); 72 | 73 | N = nums.length; 74 | if (N < 4) { 75 | return false; 76 | } 77 | for (int num : nums) { 78 | S += num; 79 | } 80 | if (S % 4 != 0L) { 81 | return false; 82 | } 83 | this.nums = nums; 84 | this.a = S / 4; 85 | 86 | knapsack(0, 0, 0); 87 | 88 | return crosscheck(); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /leetcode/476-number-complement.go: -------------------------------------------------------------------------------- 1 | func findComplement(num int) int { 2 | var flag bool 3 | for i := uint(63); i < uint(64); i-- { 4 | if num&(1< 0 { 5 | flag = true 6 | } 7 | if flag { 8 | num ^= (1 << i) 9 | } 10 | } 11 | return num 12 | } 13 | -------------------------------------------------------------------------------- /leetcode/496-next-greater-element-i.go: -------------------------------------------------------------------------------- 1 | func nextGreaterElement(findNums []int, nums []int) []int { 2 | hash := make(map[int]int, len(nums)) 3 | for i := range nums { 4 | hash[nums[i]] = -1 5 | for j := i + 1; j < len(nums); j++ { 6 | if nums[i] < nums[j] { 7 | hash[nums[i]] = nums[j] 8 | break 9 | } 10 | } 11 | } 12 | for i := range findNums { 13 | findNums[i] = hash[findNums[i]] 14 | } 15 | return findNums 16 | } 17 | -------------------------------------------------------------------------------- /leetcode/5-longest-palindromic-substring.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | 3 | def longestFromI(self, i): 4 | offset = i % 1 5 | span = min(i, self.N - 1 - i) 6 | length = 0 7 | if offset == 0: 8 | length = 1 9 | 10 | for k in range(length, int(span) + 1): 11 | if self.s[int(i - offset - k)] != self.s[int(i + offset + k)]: 12 | break 13 | length += 1 14 | 15 | if offset == 0: 16 | return self.s[int(i - length + 1):int(i + length)] 17 | return self.s[int(i - offset - length + 1):int(i - offset + length + 1)] 18 | 19 | def longestPalindrome(self, s): 20 | """ 21 | :type s: str 22 | :rtype: str 23 | """ 24 | self.s = s 25 | self.N = len(self.s) 26 | max_len = 0 27 | result = "" 28 | 29 | for i in range(0, self.N * 2 - 1): 30 | palindrome = self.longestFromI(i / 2) 31 | if len(palindrome) > max_len: 32 | max_len = len(palindrome) 33 | result = palindrome 34 | 35 | return result 36 | 37 | result = Solution().longestPalindrome("abbc") 38 | print(result) 39 | -------------------------------------------------------------------------------- /leetcode/500-keyboard-row.go: -------------------------------------------------------------------------------- 1 | func findWords(words []string) []string { 2 | result := make([]string, 0, len(words)) 3 | for _, word := range words { 4 | if check(word) { 5 | result = append(result, word) 6 | } 7 | } 8 | return result 9 | } 10 | 11 | func check(s string) bool { 12 | row := 0 13 | for _, ch := range s { 14 | switch ch { 15 | case 'a','s','d','f','g','h','j','k','l','A','S','D','F','G','H','J','K','L': 16 | if row > 0 && row != 1 { 17 | return false 18 | } 19 | row = 1 20 | case 'q','w','e','r','t','y','u','i','o','p','Q','W','E','R','T','Y','U','I','O','P': 21 | if row > 0 && row != 2 { 22 | return false 23 | } 24 | row = 2 25 | case 'z', 'x','c','v','b','n','m','Z', 'X', 'C','V','B','N','M': 26 | if row > 0 && row != 3 { 27 | return false 28 | } 29 | row = 3 30 | } 31 | } 32 | return true 33 | } 34 | -------------------------------------------------------------------------------- /leetcode/513-find-bottom-left-tree-value.go: -------------------------------------------------------------------------------- 1 | 2 | import "container/list" 3 | 4 | func findBottomLeftValue(root *TreeNode) int { 5 | list := list.New() 6 | current := root 7 | if root != nil { 8 | list.PushBack(root) 9 | } 10 | for list.Len() != 0 { 11 | currentElement := list.Front() 12 | current = currentElement.Value.(*TreeNode) 13 | list.Remove(currentElement) 14 | if current.Right != nil { 15 | list.PushBack(current.Right) 16 | } 17 | if current.Left != nil { 18 | list.PushBack(current.Left) 19 | } 20 | } 21 | return current.Val 22 | } 23 | -------------------------------------------------------------------------------- /leetcode/515-find-largest-value-in-each-tree-row.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "container/list" 4 | 5 | func main() {} 6 | 7 | type TreeNode struct { 8 | Val int 9 | Left *TreeNode 10 | Right *TreeNode 11 | } 12 | 13 | const minValue = 1 << 60 * -1 14 | 15 | func largestValues(root *TreeNode) []int { 16 | currentMax := minValue 17 | values := make([]int, 0, 1000) 18 | if root == nil { 19 | return values 20 | } 21 | 22 | l := list.New() 23 | l.PushBack(root) 24 | l.PushBack(nil) 25 | 26 | for l.Len() > 0 { 27 | el := l.Front() 28 | l.Remove(el) 29 | if el.Value == nil { 30 | if l.Len() > 0 { 31 | l.PushBack(nil) 32 | } 33 | values = append(values, currentMax) 34 | currentMax = minValue 35 | continue 36 | } 37 | node := el.Value.(*TreeNode) 38 | if node.Val > currentMax { 39 | currentMax = node.Val 40 | } 41 | if node.Left != nil { 42 | l.PushBack(node.Left) 43 | } 44 | if node.Right != nil { 45 | l.PushBack(node.Right) 46 | } 47 | } 48 | return values 49 | 50 | } 51 | -------------------------------------------------------------------------------- /leetcode/521-longest-uncommon-subsequence-i.go: -------------------------------------------------------------------------------- 1 | func findLUSlength(a string, b string) int { 2 | if a == b { 3 | return -1 4 | } 5 | if len(a) > len(b) { 6 | return len(a) 7 | } 8 | return len(b) 9 | } 10 | -------------------------------------------------------------------------------- /leetcode/53-maximum-subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSubArray(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | if len(nums) == 0: 8 | return 0 9 | 10 | sum = 0 11 | max = nums[0] 12 | for n in nums: 13 | sum += n 14 | if sum < n: 15 | sum = n 16 | if max < sum: 17 | max = sum 18 | return max 19 | -------------------------------------------------------------------------------- /leetcode/535-encode-and-decode-tinyurl.java: -------------------------------------------------------------------------------- 1 | public class Codec { 2 | public HashMap hash = new HashMap(); 3 | 4 | // Encodes a URL to a shortened URL. 5 | public String encode(String longUrl) { 6 | String result = Integer.toString(longUrl.hashCode()); 7 | hash.put(result, longUrl); 8 | return result; 9 | } 10 | 11 | // Decodes a shortened URL to its original URL. 12 | public String decode(String shortUrl) { 13 | return hash.get(shortUrl); 14 | } 15 | } 16 | 17 | // Your Codec object will be instantiated and called as such: 18 | // Codec codec = new Codec(); 19 | // codec.decode(codec.encode(url)); 20 | -------------------------------------------------------------------------------- /leetcode/537-complex-number-multiplication.go: -------------------------------------------------------------------------------- 1 | import ( 2 | "fmt" 3 | "strconv" 4 | "strings" 5 | ) 6 | 7 | func complexNumberMultiply(str1 string, str2 string) string { 8 | aParts := strings.Split(strings.Replace(str1, "i", "", 1), "+") 9 | bParts := strings.Split(strings.Replace(str2, "i", "", 1), "+") 10 | aS, bS, cS, dS := aParts[0], aParts[1], bParts[0], bParts[1] 11 | a, _ := strconv.Atoi(aS) 12 | b, _ := strconv.Atoi(bS) 13 | c, _ := strconv.Atoi(cS) 14 | d, _ := strconv.Atoi(dS) 15 | return fmt.Sprintf("%d+%di", a*c-b*d, b*c+a*d) 16 | } 17 | -------------------------------------------------------------------------------- /leetcode/540-single-element-in-a-sorted-array.go: -------------------------------------------------------------------------------- 1 | func singleNonDuplicate(nums []int) int { 2 | result := 0 3 | for _, x := range nums { 4 | result ^= x 5 | } 6 | return result 7 | } 8 | -------------------------------------------------------------------------------- /leetcode/553-optimal-division.go: -------------------------------------------------------------------------------- 1 | import ( 2 | "fmt" 3 | "strconv" 4 | "strings" 5 | ) 6 | 7 | func optimalDivision(nums []int) string { 8 | strs := make([]string, len(nums)) 9 | for i, v := range nums { 10 | strs[i] = strconv.Itoa(v) 11 | } 12 | if len(strs) < 3 { 13 | return strings.Join(strs, "/") 14 | } 15 | return fmt.Sprintf("%s/(%s)", strs[0], strings.Join(strs[1:], "/")) 16 | } 17 | -------------------------------------------------------------------------------- /leetcode/556-next-greater-element-iii.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | final int BASE = 10; 4 | final int NO_RESULT = -1; 5 | int[] digits = new int[10]; 6 | int totalDigits; 7 | 8 | int toDigitArray(int n) { 9 | int totalDigits = 0; 10 | while (n > 0) { 11 | int digit = n % BASE; 12 | digits[totalDigits++] = digit; 13 | n /= BASE; 14 | } 15 | return totalDigits; 16 | } 17 | 18 | void swap(int i, int j) { 19 | int tmp = digits[i]; 20 | digits[i] = digits[j]; 21 | digits[j] = tmp; 22 | } 23 | 24 | int arrayToNumber() { 25 | int result = 0; 26 | int power = 1; 27 | for (int i = 0; i < digits.length; i++) { 28 | result += digits[i] * power; 29 | power *= 10; 30 | } 31 | return result; 32 | } 33 | 34 | int pivot() { 35 | for (int i = 1; i < totalDigits; i++) { 36 | if (digits[i - 1] > digits[i]) { 37 | return i; 38 | } 39 | } 40 | return NO_RESULT; 41 | } 42 | 43 | public int nextGreaterElement(int n) { 44 | if (n == 0) { 45 | return NO_RESULT; 46 | } 47 | 48 | totalDigits = toDigitArray(n); 49 | 50 | int pivot = pivot(); 51 | if (pivot == NO_RESULT) { 52 | return NO_RESULT; 53 | } 54 | 55 | int minValue = Integer.MAX_VALUE; 56 | int minIndex = -1; 57 | for (int i = pivot - 1; i >= 0; i--) { 58 | if (digits[i] > digits[pivot] && digits[i] <= minValue) { 59 | minValue = digits[i]; 60 | minIndex = i; 61 | } 62 | } 63 | swap(minIndex, pivot); 64 | 65 | // reverse 66 | for (int i = 0; i < pivot / 2; i++) { 67 | swap(i, pivot - 1 - i); 68 | } 69 | 70 | if (digits[9] > 1) { 71 | return NO_RESULT; 72 | } 73 | 74 | return arrayToNumber(); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /leetcode/557-reverse-words-in-a-string-iii.go: -------------------------------------------------------------------------------- 1 | import ( 2 | "bytes" 3 | "regexp" 4 | "strings" 5 | ) 6 | 7 | func reverseWords(s string) string { 8 | var result bytes.Buffer 9 | s = strings.Trim(s, " ") 10 | 11 | re := regexp.MustCompile("\\s+") 12 | s = re.ReplaceAllString(s, " ") 13 | 14 | limiter := -1 15 | for i, ch := range s { 16 | if ch == ' ' { 17 | for j := i - 1; j > limiter; j-- { 18 | result.WriteByte(s[j]) 19 | } 20 | limiter = i 21 | result.WriteByte(' ') 22 | } 23 | } 24 | for j := len(s) - 1; j > limiter; j-- { 25 | result.WriteByte(s[j]) 26 | } 27 | return string(result.Bytes()) 28 | } 29 | -------------------------------------------------------------------------------- /leetcode/561-array-partition-i.go: -------------------------------------------------------------------------------- 1 | import "sort" 2 | 3 | func arrayPairSum(nums []int) int { 4 | sort.Ints(nums) 5 | result := 0 6 | for i := 0; i < len(nums)/2; i++ { 7 | result += nums[i*2] 8 | } 9 | return result 10 | } 11 | -------------------------------------------------------------------------------- /leetcode/566-reshape-the-matrix.go: -------------------------------------------------------------------------------- 1 | func matrixReshape(nums [][]int, r int, c int) [][]int { 2 | if len(nums) == 0 || len(nums[0]) == 0 { 3 | return nums 4 | } 5 | if r*c != len(nums)*len(nums[0]) { 6 | return nums 7 | } 8 | 9 | ptrR, ptrC := 0, 0 10 | result := make([][]int, r) 11 | for row := 0; row < r; row++ { 12 | result[row] = make([]int, c) 13 | } 14 | 15 | for row := 0; row < r; row++ { 16 | for col := 0; col < c; col++ { 17 | result[row][col] = nums[ptrR][ptrC] 18 | ptrC++ 19 | if ptrC/len(nums[0]) > 0 { 20 | ptrC = 0 21 | ptrR++ 22 | } 23 | if ptrR == len(nums) { 24 | return result 25 | } 26 | } 27 | } 28 | 29 | return result 30 | } 31 | -------------------------------------------------------------------------------- /leetcode/575-distribute-candies.go: -------------------------------------------------------------------------------- 1 | import "sort" 2 | 3 | func distributeCandies(candies []int) int { 4 | if len(candies) == 0 { 5 | return 0 6 | } 7 | sort.Ints(candies) 8 | count := 1 9 | for i := 1; i < len(candies); i++ { 10 | if candies[i] != candies[i-1] { 11 | count++ 12 | } 13 | } 14 | if count > len(candies)/2 { 15 | return len(candies) / 2 16 | } 17 | return count 18 | } 19 | -------------------------------------------------------------------------------- /leetcode/6-zigzag-conversion.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def convert(self, s, numRows): 3 | """ 4 | :type s: str 5 | :type numRows: int 6 | :rtype: str 7 | """ 8 | if numRows == 1: 9 | return s 10 | result=[[] for x in range(numRows)] 11 | for i, ch in enumerate(s): 12 | block_position = i % (numRows + numRows - 2) 13 | if block_position < numRows: 14 | result[block_position].append(ch) 15 | else: 16 | result[numRows - (block_position%numRows+1) - 1 ].append(ch) 17 | 18 | # print(result) 19 | return ''.join([''.join(x) for x in result]) 20 | -------------------------------------------------------------------------------- /leetcode/617-merge-two-binary-trees.go: -------------------------------------------------------------------------------- 1 | func mergeTrees(t1 *TreeNode, t2 *TreeNode) *TreeNode { 2 | if t1 == nil && t2 == nil { 3 | return nil 4 | } 5 | if t1 == nil { 6 | t1 = &TreeNode{Val: 0} 7 | } 8 | if t2 == nil { 9 | t2 = &TreeNode{Val: 0} 10 | } 11 | 12 | root := t1 13 | root.Val += t2.Val 14 | 15 | root.Left = mergeTrees(t1.Left, t2.Left) 16 | root.Right = mergeTrees(t1.Right, t2.Right) 17 | 18 | return root 19 | } 20 | -------------------------------------------------------------------------------- /leetcode/620-not-boring-movies.sql: -------------------------------------------------------------------------------- 1 | select * from cinema where description != 'boring' and id %2 = 1 ORDER BY rating DESC; 2 | -------------------------------------------------------------------------------- /leetcode/637-average-of-levels-in-binary-tree.go: -------------------------------------------------------------------------------- 1 | 2 | import "container/list" 3 | 4 | func averageOfLevels(root *TreeNode) []float64 { 5 | l := list.New() 6 | result := make([]float64, 0) 7 | if root != nil { 8 | l.PushBack(root) 9 | l.PushBack(nil) 10 | } 11 | var acc, cnt int 12 | for l.Len() > 0 { 13 | el := l.Front() 14 | l.Remove(el) 15 | if el.Value == nil { 16 | result = append(result, float64(acc)/float64(cnt)) 17 | if l.Len() > 0 { 18 | l.PushBack(nil) 19 | acc = 0 20 | cnt = 0 21 | } 22 | } else { 23 | v := el.Value.(*TreeNode) 24 | acc += v.Val 25 | cnt++ 26 | if v.Left != nil { 27 | l.PushBack(v.Left) 28 | } 29 | if v.Right != nil { 30 | l.PushBack(v.Right) 31 | } 32 | } 33 | } 34 | return result 35 | } 36 | -------------------------------------------------------------------------------- /leetcode/647-palindromic-substrings.go: -------------------------------------------------------------------------------- 1 | func expandCenter(chars []rune, i int) int { 2 | padding := 0 3 | for i-padding-1 >= 0 && i+padding+1 < len(chars) && chars[i-padding-1] == chars[i+padding+1] { 4 | padding++ 5 | } 6 | return padding/2 + padding%2 7 | 8 | } 9 | 10 | func countSubstrings(s string) int { 11 | N := len(s)*2 + 1 12 | chars := make([]rune, N) 13 | i := 0 14 | for _, r := range s { 15 | chars[2*i+1] = r 16 | i++ 17 | } 18 | sum := 0 19 | for i := 0; i < N; i++ { 20 | sum += expandCenter(chars, i) 21 | } 22 | return sum 23 | } 24 | -------------------------------------------------------------------------------- /leetcode/654-maximum-binary-tree.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * type TreeNode struct { 4 | * Val int 5 | * Left *TreeNode 6 | * Right *TreeNode 7 | * } 8 | */ 9 | func maxInRange(arr []int, i int, j int) *TreeNode { 10 | if i > j { 11 | return nil 12 | } 13 | var max, id int 14 | max = -1 15 | for k:=i; k<=j; k++ { 16 | if arr[k] > max { 17 | max = arr[k] 18 | id = k 19 | } 20 | } 21 | return &TreeNode{ 22 | Val: max, 23 | Left: maxInRange(arr, i, id - 1), 24 | Right: maxInRange(arr, id + 1, j), 25 | } 26 | } 27 | 28 | func constructMaximumBinaryTree(nums []int) *TreeNode { 29 | return maxInRange(nums, 0, len(nums) - 1) 30 | } 31 | -------------------------------------------------------------------------------- /leetcode/657-judge-route-circle.go: -------------------------------------------------------------------------------- 1 | func judgeCircle(moves string) bool { 2 | var x, y int 3 | for _, ch := range moves { 4 | switch ch { 5 | case 'U': 6 | y++ 7 | case 'D': 8 | y-- 9 | case 'L': 10 | x-- 11 | case 'R': 12 | x++ 13 | } 14 | } 15 | if x == 0 && y == 0 { 16 | return true 17 | } 18 | return false 19 | } 20 | -------------------------------------------------------------------------------- /leetcode/669-trim-a-binary-search-tree.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * type TreeNode struct { 4 | * Val int 5 | * Left *TreeNode 6 | * Right *TreeNode 7 | * } 8 | */ 9 | func trimBST(root *TreeNode, L int, R int) *TreeNode { 10 | if root == nil { 11 | return nil 12 | } 13 | if root.Val < L { 14 | return trimBST(root.Right, L, R) 15 | } 16 | if root.Val > R { 17 | return trimBST(root.Left, L, R) 18 | } 19 | root.Left = trimBST(root.Left, L, R) 20 | root.Right = trimBST(root.Right, L, R) 21 | return root 22 | } 23 | -------------------------------------------------------------------------------- /leetcode/693-binary-number-with-alternating-bits.go: -------------------------------------------------------------------------------- 1 | func hasAlternatingBits(n int) bool { 2 | un := uint64(n) 3 | set := un&1 == 1 4 | for i := uint64(1); i <= 63 && ((uint64(1) << i) <= un); i++ { 5 | set = !set 6 | if set != (((uint64(1) << i) & un) > 0) { 7 | return false 8 | } 9 | } 10 | return true 11 | } 12 | -------------------------------------------------------------------------------- /leetcode/695-max-area-of-island.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int N; 3 | int M; 4 | int[][] grid; 5 | 6 | int dfs(int j, int i) { 7 | if (j < 0 || j >= N) { 8 | return 0; 9 | } 10 | if (i < 0 || i >= M) { 11 | return 0; 12 | } 13 | if (grid[j][i] == 0) { 14 | return 0; 15 | } 16 | grid[j][i] = 0; 17 | return 1 + dfs(j + 1, i) + dfs(j - 1, i) + dfs(j, i + 1) + dfs(j, i - 1); 18 | } 19 | 20 | public int maxAreaOfIsland(int[][] grid) { 21 | N = grid.length; 22 | if (N == 0) { 23 | return 0; 24 | } 25 | M = grid[0].length; 26 | this.grid = grid; 27 | 28 | int result = 0; 29 | for (int j = 0; j < N; j++) { 30 | for (int i = 0; i < M; i++) { 31 | if (grid[j][i] == 1) { 32 | result = Math.max(result, dfs(j, i)); 33 | } 34 | } 35 | } 36 | return result; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /leetcode/7-reverse-integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverse(self, x): 3 | """ 4 | :type x: int 5 | :rtype: int 6 | """ 7 | result = 0 8 | base = 10 9 | 10 | def sgn(x): return (1, -1)[x < 0] 11 | sign = sgn(x) 12 | x *= sign 13 | while x > 0: 14 | digit = x % base 15 | x = x // base 16 | result = result * base + digit 17 | 18 | if result < -2**31 or result > 2**31 - 1: 19 | return 0 20 | return sign * result 21 | 22 | 23 | result = Solution().reverse(12) 24 | print(result) 25 | -------------------------------------------------------------------------------- /leetcode/717-1-bit-and-2-bit-characters.go: -------------------------------------------------------------------------------- 1 | func isOneBitCharacter(bits []int) bool { 2 | blocked := false 3 | for i := 0; i < len(bits)-1; i++ { 4 | blocked = bits[i] == 1 && !blocked 5 | } 6 | return !blocked 7 | } 8 | -------------------------------------------------------------------------------- /leetcode/891-sum-of-subsequence-widths.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | final long MODULO = (long) Math.pow(10, 9) + 7; 3 | final int MAX_SIZE = 20000 + 1; 4 | 5 | public int sumSubseqWidths(int[] A) { 6 | int N = A.length; 7 | if (N <= 1) { 8 | return 0; 9 | } 10 | 11 | long sum = 0; 12 | long power = 1; 13 | long[] powers = new long[N]; 14 | powers[0] = 0; 15 | 16 | int[] sort = new int[MAX_SIZE]; 17 | 18 | for (int i = 0; i < N; i++) { 19 | sort[A[i]]++; 20 | } 21 | int p = 0; 22 | for (int i = 0; i < MAX_SIZE && p < N; i++) { 23 | for (int j = 0; j < sort[i]; j++) { 24 | A[p++] = i; 25 | } 26 | } 27 | 28 | for (int i = 1; i < N; i++) { 29 | powers[i] = (powers[i - 1] + power) % MODULO; 30 | power = power * 2 % MODULO; 31 | } 32 | 33 | long acc = 0; 34 | for (int i = 1; i < N; i++) { 35 | acc += powers[N - 1 - (i - 1)] - powers[i - 1]; 36 | sum = (sum + (A[i] - A[i - 1]) * acc) % MODULO; 37 | } 38 | 39 | return (int) sum; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /leetcode/9-palindrome-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPalindrome(self, x): 3 | """ 4 | :type x: int 5 | :rtype: bool 6 | """ 7 | if x < 0: 8 | return False 9 | 10 | digits = [] 11 | while x > 0: 12 | digit = x % 10 13 | x //= 10 14 | digits.append(digit) 15 | 16 | for i in range(len(digits)//2): 17 | if digits[i] != digits[len(digits)-1-i]: 18 | return False 19 | 20 | return True 21 | -------------------------------------------------------------------------------- /leetcode/924-minimize-malware-spread.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int N; 3 | int M; 4 | boolean[] visited; 5 | int[] rank; 6 | int[] arity; 7 | 8 | int[][] graph; 9 | int[] initial; 10 | HashMap infectionPoints; 11 | 12 | void dfs(int i, int infectionIndex) { 13 | visited[i] = true; 14 | for (int j = 0; j < N; j++) { 15 | if (graph[i][j] != 1 || visited[j]) { 16 | continue; 17 | } 18 | arity[infectionIndex]++; 19 | if (infectionPoints.containsKey(j)) { 20 | rank[infectionIndex]++; 21 | rank[infectionPoints.get(j)] = -1; 22 | } 23 | dfs(j, infectionIndex); 24 | } 25 | } 26 | 27 | public int minMalwareSpread(int[][] graph, int[] initial) { 28 | // setup helper vars 29 | N = graph.length; 30 | M = initial.length; 31 | this.graph = graph; 32 | this.initial = initial; 33 | 34 | visited = new boolean[N]; 35 | rank = new int[M]; 36 | arity = new int[M]; 37 | 38 | // make set for quick lookups of infection points 39 | infectionPoints = new HashMap<>(); 40 | for (int i = 0; i < M; i++) { 41 | infectionPoints.put(initial[i], i); 42 | } 43 | 44 | // infestation starts (!) 45 | for (int i = 0; i < M; i++) { 46 | // rank -1 means that point was infested earlier 47 | if (visited[initial[i]]) { 48 | continue; 49 | } 50 | arity[i] = 1; 51 | rank[i] = 1; 52 | dfs(initial[i], i); 53 | } 54 | 55 | int maxArity = Integer.MIN_VALUE; 56 | int maxInitialElement = Integer.MAX_VALUE; 57 | for (int i = 0; i < M; i++) { 58 | if (rank[i] == 1 || arity[i] == 1) { 59 | if (maxArity < arity[i]) { 60 | maxArity = arity[i]; 61 | maxInitialElement = initial[i]; 62 | } 63 | if (maxArity == arity[i] && maxInitialElement > initial[i]) { 64 | maxInitialElement = initial[i]; 65 | } 66 | } 67 | } 68 | if (maxInitialElement == Integer.MAX_VALUE) { 69 | for (int i = 0; i < M; i++) { 70 | if (maxInitialElement > initial[i]) { 71 | maxInitialElement = initial[i]; 72 | } 73 | } 74 | } 75 | return maxInitialElement; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /leetcode/938-range-sum-of-bst.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode 3 | * right; TreeNode(int x) { val = x; } } 4 | */ 5 | class Solution { 6 | int result = 0; 7 | boolean flag = false; 8 | int L; 9 | int R; 10 | 11 | void checkNode(TreeNode root) { 12 | if (root.val == L) { 13 | flag = true; 14 | } 15 | if (flag) { 16 | result += root.val; 17 | } 18 | if (root.val == R) { 19 | flag = false; 20 | } 21 | } 22 | 23 | public int rangeSumBST(TreeNode root, int L, int R) { 24 | this.R = R; 25 | this.L = L; 26 | if (root == null) { 27 | return 0; 28 | } 29 | ArrayDeque stack = new ArrayDeque<>(); 30 | 31 | while (!stack.isEmpty() || root != null) { 32 | while (root != null) { 33 | stack.push(root); 34 | root = root.left; 35 | } 36 | 37 | root = stack.pop(); 38 | checkNode(root); 39 | root = root.right; 40 | } 41 | 42 | return result; 43 | } 44 | } 45 | --------------------------------------------------------------------------------