├── .gitignore ├── Hackerrank ├── README.md └── Algorithms │ ├── Implementation │ └── src │ │ ├── SockMerchant.java │ │ ├── MiniMaxSum.java │ │ ├── DesignerPDFViewer.java │ │ ├── BonAppetit.java │ │ └── Kangaroo.java │ └── Sorting │ └── src │ ├── ClosestNumbers.java │ └── FindTheMedian.java ├── codeforces ├── README.md ├── round238_div2 │ └── ProblemB.java ├── round322_div2 │ ├── ProblemA.java │ └── ProblemB.java ├── round327_div2 │ └── ProblemA.java ├── round320_div2 │ └── ProblemA.java ├── round321_div2 │ └── ProblemA.java └── round334_div2 │ └── ProblemB.java ├── leetcode ├── README.md ├── VersionControl.java ├── Relation.java ├── PowerOfTwo.java ├── customer_placing_the_largest_number_of_orders.sql ├── tree_node.sql ├── NumberOf1Bits.java ├── ExcelSheetColumnTitle.java ├── PowerOfThree.java ├── HammingDistance.java ├── RemoveElement.java ├── ValidPalindrome.java ├── ClimbingStairs.java ├── BestTimeToBuyAndSellStockII.java ├── ContainsDuplicate.java ├── RotateArray.java ├── DeleteNodeInALinkedList.java ├── MinimumMovesToEqualArrayElementsII.java ├── FindTheDuplicateNumber.java ├── MaximumDepthOfBinaryTree.java ├── MinCostClimbingStairs.java ├── PaintFence.java ├── HouseRobber.java ├── KthLargestElementInAnArray.java ├── FindAnagramMappings.java ├── ContainsDuplicateII.java ├── JewelsAndStones.java ├── MaxConsecutiveOnes.java ├── UniquePaths.java ├── NthDigit.java ├── ValidPerfectSquare.java ├── FindTheDifference.java ├── MinimumSizeSubarraySum.java ├── Subsets.java ├── SumOfSquareNumbers3.java ├── CountPrimes.java ├── PathSum.java ├── ValidWordSquare.java ├── BestTimeToBuyAndSellStock.java ├── NimGame.java ├── Sqrt.java ├── ValidAnagram.java ├── PalindromePermutation.java ├── ProductOfArrayExceptSelf.java ├── TwoSum.java ├── ValidateBinarySearchTree.java ├── PaintHouse.java ├── IncreasingTripletSubsequence.java ├── ValidPalindromeII.java ├── LargestNumberAtLeastTwiceOfOthers.java ├── PowXN.java ├── RemoveDuplicatesFromSortedArray.java ├── FindTheCelebrity.java ├── PlusOne.java ├── SumOfSquareNumbers.java ├── Flatten2DVector.java ├── SameTree.java ├── SingleNumber.java ├── FindSmallestLetterGreaterThanTarget.java ├── GenerateParentheses.java ├── GlobalAndLocalInversions.java ├── LicenseKeyFormatting.java ├── MergeTwoBinaryTrees.java ├── MergeTwoSortedLists.java ├── DiameterOfBinaryTree.java ├── FirstBadVersion.java ├── SymmetricTree.java ├── MaximumAverageSubarrayI.java ├── LowestCommonAncestorOfBinarySearchTree.java ├── LongestAbsoluteFilePath.java ├── IntersectionOfTwoArrays.java ├── LongestPalindrome.java ├── ShortestUnsortedContinuousSubarray.java ├── CountAndSay.java ├── UglyNumberII.java ├── FindAllNumbersDisappearedInAnArray.java ├── TwoSumII.java ├── MinimumPathSum.java ├── PascalsTriangle.java ├── MaximumSubarray.java ├── FindAllNumbersDisappearedInAnArrayII.java ├── LongestContinuousIncreasingSubsequence.java ├── ReverseLinkedList.java ├── LinkedListCycle.java ├── SparseMatrixMultiplication.java ├── PascalsTriangleII.java ├── FirstUniqueCharacterInAString.java ├── FlipGame.java ├── BinaryTreePreorderTraversalRecursive.java ├── ReverseInteger.java ├── JudgeRouteCircle.java ├── MaxSubArray.java ├── NumArray.java ├── ShortestWordDistance.java ├── WordBreak.java ├── FirstMissingPositive.java ├── HIndexII.java ├── Heaters.java ├── ReadNCharactersGivenRead4.java ├── RemoveDuplicateLetters.java ├── WiggleSort.java ├── MissingNumber.java ├── StrobogrammaticNumber.java ├── NestedListWeightSum.java ├── SumOfSquareNumbers2.java ├── LargestPlusSign.java ├── MonotoneIncreasingDigits.java ├── PerfectSquares.java ├── MinimumDistanceBetweenBSTNodes.java ├── MinimizeMaxDistanceToGasStation.java ├── ShortestPalindrome.java ├── CountingBits.java ├── InvertBinaryTree.java ├── MoveZeroes.java ├── FindPeakElement.java ├── FindMinimumInRotatedSortedArray.java ├── LoggerRateLimiter.java ├── IsomorphicStrings.java ├── LongestCommonPrefix.java ├── PaintHouseII.java ├── MinimumAbsoluteDifferenceInBST.java ├── AddStrings.java ├── KthSmallestElementInBST.java ├── OddEvenLinkedList.java ├── CanPlaceFlowers.java ├── FlattenBinaryTreeToLinkedList.java ├── BinaryTreePaths.java ├── BinaryTreeRightSideView.java ├── AddDigits.java ├── GroupAnagrams.java ├── FindLargestValueInEachTreeRow.java ├── IntersectionOfTwoArraysII.java ├── SortColors.java ├── ConvertSortedArrayToBinarySearchTree.java ├── MinimumTimeDifference.java ├── NumberOfCornerRectangles.java ├── ValidParentheses.java ├── BinaryTreePreorderTraversalIterative.java ├── IslandPerimeter.java ├── SecondMinimumNodeInABinaryTree.java ├── BestMeetingPoint.java ├── GuessNumberHigherOrLower.java ├── PrimeNumberOfSetBitsInBinaryRepresentation.java ├── StudentAttendanceRecordII.java ├── CheapestFlightsWithinKStops.java ├── PopulatingNextRightPointersInEachNode.java ├── ClosestBinarySearchTreeValue.java ├── EditDistance.java ├── NumberOfBoomerangs.java ├── RelativeRanks.java ├── FlipGameII.java └── ReverseVowelsOfAString.java ├── algorithms ├── dynamic_programming │ ├── README.md │ ├── CoinChangeProblem.java │ ├── test │ │ ├── ScoresProblemTest.java │ │ ├── MaximumSubarrayTest.java │ │ └── MinimumEditDistanceTest.java │ ├── MaximumSubarray.java │ ├── Fibo.java │ ├── MinimumEditDistance.java │ └── ScoresProblem.java ├── README.md ├── bit_manipulation │ ├── NumberOfOnes.java │ └── Insertion.java ├── sorting │ ├── InsertionSort.java │ ├── SelectionSort.java │ ├── ShellSort.java │ └── QuickSort.java ├── arrays │ ├── RotateMatrix.java │ ├── RandomShuffle.java │ ├── test │ │ └── RotateMatrixTest.java │ └── LookAndSaySequence.java ├── strings │ ├── test │ │ ├── CheckPermutationTest.java │ │ ├── URLifyTest.java │ │ └── IsUniqueTest.java │ └── URLify.java ├── linked_lists │ ├── Palindrome.java │ ├── KthElementFromTheEnd.java │ ├── RemoveMiddleInLinkedList.java │ ├── RemoveDuplicates.java │ └── Intersection.java ├── combinatorics │ └── Permutation.java ├── sets │ └── SetTest.java ├── threads │ └── Deadlock.java └── heaps │ ├── SortIncreasingDecreasingArray.java │ └── test │ └── MergeSortedArraysTest.java ├── TopCoder ├── README.md ├── srm648div2 │ ├── src │ │ └── KitayutaMart2.java │ └── test │ │ └── KitayutaMart2Test.java ├── srm644div2 │ ├── src │ │ ├── OkonomiyakiShop.java │ │ └── LostCharacter.java │ └── test │ │ └── OkonomiyakiShopTest.java ├── srm649div2 │ └── src │ │ ├── DecipherabilityEasy.java │ │ └── CartInSupermarketEasy.java ├── srm642div2 │ ├── src │ │ └── ForgetfulAddition.java │ └── test │ │ └── ForgetfulAdditionTest.java ├── srm467div2 │ ├── src │ │ └── ShorterSuperSum.java │ └── test │ │ └── ShorterSuperSumTest.java ├── srm646div2 │ ├── src │ │ └── TheConsecutiveIntegersDivTwo.java │ └── test │ │ └── TheConsecutiveIntegersDivTwoTest.java ├── srm652div2 │ ├── src │ │ ├── ThePermutationGameDiv2.java │ │ └── ValueOfString.java │ └── test │ │ └── ThePermutationGameDiv2Test.java ├── srm661div2 │ └── src │ │ └── BridgeBuildingDiv2.java ├── srm660div2 │ ├── src │ │ ├── PrivateD2party.java │ │ └── Cyclemin.java │ └── test │ │ └── PrivateD2partyTest.java ├── srm651div2 │ └── src │ │ └── FoxAndSouvenirTheNext.java ├── srm653div2 │ ├── src │ │ └── CountryGroup.java │ └── test │ │ └── CountryGroupTest.java ├── srm650div2 │ ├── src │ │ └── TaroJiroDividing.java │ └── test │ │ └── TaroJiroDividingTest.java └── srm643div2 │ └── src │ └── TheKingsArmyDiv2.java ├── ProjectEuler ├── src │ ├── python │ │ ├── 016 Power digit sum.py │ │ ├── 001 multiplies of 3 and 5.py │ │ ├── 006 Sum square difference.py │ │ ├── 020 Factorial digit sum.py │ │ ├── 003 Largest prime factor.py │ │ ├── 005 Smallest multiple.py │ │ ├── 009 Special Pythagorean triplet.py │ │ ├── 002 even fibo.py │ │ ├── 011 Largest product in a grid.py │ │ ├── 018 Counting Sundays.py │ │ ├── 022 names scores.py │ │ ├── 033 Digit cancelling fractions.py │ │ ├── 021 Amicable numbers.py │ │ ├── 015 Lattice paths.py │ │ ├── 004 Largest palindrome product.py │ │ ├── 032 Pandigital products.py │ │ ├── 023 Non-abundant sums.py │ │ ├── 031 Coin sums.py │ │ ├── 034 Digit factorials.py │ │ ├── 012 Highly divisible triangular number.py │ │ ├── 014 Longest Collatz sequence.py │ │ ├── 007 10001st prime.py │ │ └── 010 Summation of primes.py │ └── java │ │ ├── 003 Largest prime factor │ │ └── src │ │ │ └── Solution.java │ │ └── 001 Euler │ │ └── src │ │ └── Solution.java └── README.md └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.xml 2 | *.iml 3 | *.class 4 | out 5 | 6 | */resource/ 7 | *.idea/ 8 | *.DS_Store 9 | -------------------------------------------------------------------------------- /Hackerrank/README.md: -------------------------------------------------------------------------------- 1 | # Hackerrank 2 | 3 | My solutions for Hackerrank problems. 4 | 5 | Feel free to grab if you find something useful or interesting. 6 | -------------------------------------------------------------------------------- /codeforces/README.md: -------------------------------------------------------------------------------- 1 | # CodeForces 2 | 3 | My solutions for CodeForces.com problems. 4 | 5 | Feel free to grab if you find something (hopefully) useful or interesting. 6 | -------------------------------------------------------------------------------- /leetcode/README.md: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | 3 | My solutions for [LeetCode](https://leetcode.com) problems. 4 | 5 | Feel free to grab if you find something useful or interesting. 6 | -------------------------------------------------------------------------------- /leetcode/VersionControl.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | public class VersionControl { 4 | public boolean isBadVersion(int version) { 5 | return true; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /algorithms/dynamic_programming/README.md: -------------------------------------------------------------------------------- 1 | # Dynamic Programming problems solutions in Java 2 | 3 | Here you can find my implementations for some of the popular Dynamic Programming problems. 4 | -------------------------------------------------------------------------------- /algorithms/README.md: -------------------------------------------------------------------------------- 1 | # Algorithms and Data structures 2 | 3 | Here you can find implementations of different kind of algorithms and Data structures. 4 | 5 | - [Linked Lists](./LinkedList/src) 6 | -------------------------------------------------------------------------------- /TopCoder/README.md: -------------------------------------------------------------------------------- 1 | # TopCoder 2 | 3 | My solutions for TopCoder SRM problems. 4 | 5 | Most of the solutions include JUnit tests. 6 | 7 | Feel free to grab if you find something useful or interesting. 8 | 9 | -------------------------------------------------------------------------------- /leetcode/Relation.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // dumb class for "FindTheCelebrity" problem 4 | 5 | public class Relation { 6 | boolean knows(int a, int b) { 7 | return true; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /ProjectEuler/src/python/016 Power digit sum.py: -------------------------------------------------------------------------------- 1 | def solve(x): 2 | res = 0 3 | num = 1 << x 4 | while num > 0: 5 | res += num % 10 6 | num //= 10 7 | return res 8 | 9 | 10 | n = 1000 11 | print(int(solve(n))) 12 | -------------------------------------------------------------------------------- /leetcode/PowerOfTwo.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/power-of-two/ 4 | // 231. Power of Two 5 | 6 | class PowerOfTwo { 7 | public boolean isPowerOfTwo(int n) { 8 | return n > 0 && (n & (n - 1)) == 0; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /ProjectEuler/src/python/001 multiplies of 3 and 5.py: -------------------------------------------------------------------------------- 1 | def solve(): 2 | s = set() 3 | sum = 0 4 | for i in range(1000): 5 | if i % 3 == 0 or i % 5 == 0: 6 | sum += i 7 | return sum 8 | 9 | if __name__ == "__main__": 10 | res = solve() 11 | print(res) 12 | -------------------------------------------------------------------------------- /ProjectEuler/src/python/006 Sum square difference.py: -------------------------------------------------------------------------------- 1 | def sum_1_n(n): 2 | return n*(1+n)//2 3 | 4 | def solve(): 5 | s1 = sum_1_n(100) 6 | s2 = 0 7 | for i in range(101): 8 | s2 += i*i 9 | return s1*s1 - s2 10 | 11 | 12 | if __name__ == "__main__": 13 | print(solve()) 14 | -------------------------------------------------------------------------------- /ProjectEuler/src/python/020 Factorial digit sum.py: -------------------------------------------------------------------------------- 1 | def factor(n): 2 | p = 1 3 | i = 1 4 | while i <= n: 5 | p *= i 6 | i += 1 7 | return p 8 | 9 | x = 100 10 | res = str(factor(x)) 11 | sum_factor = 0 12 | for digit in res: 13 | sum_factor += int(digit) 14 | 15 | print(sum_factor) 16 | -------------------------------------------------------------------------------- /leetcode/customer_placing_the_largest_number_of_orders.sql: -------------------------------------------------------------------------------- 1 | -- https://leetcode.com/problems/customer-placing-the-largest-number-of-orders/description/ 2 | -- 586. Customer Placing the Largest Number of Orders 3 | 4 | select `customer_number` from `orders` group by `customer_number` order by count(`customer_number`) desc limit 1 5 | -------------------------------------------------------------------------------- /algorithms/bit_manipulation/NumberOfOnes.java: -------------------------------------------------------------------------------- 1 | package algorithms.bit_manipulation; 2 | 3 | public class NumberOfOnes { 4 | public static int numberOfOnes(int x) { 5 | int res = 0; 6 | while (x != 0) { 7 | x = x & (x - 1); 8 | res++; 9 | } 10 | return res; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /ProjectEuler/src/python/003 Largest prime factor.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | def get_max_prime(x): 5 | i = 2 6 | while i < math.sqrt(x): 7 | while x % i == 0 and x != i: 8 | x //= i 9 | i += 1 10 | 11 | return x 12 | 13 | if __name__ == "__main__": 14 | res = get_max_prime(600851475143) 15 | print(res) 16 | -------------------------------------------------------------------------------- /TopCoder/srm648div2/src/KitayutaMart2.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.math.*; 3 | import static java.lang.Math.*; 4 | 5 | public class KitayutaMart2 { 6 | 7 | public int numBought(int K, int T) { 8 | int x = T / K + 1; 9 | int total = 0; 10 | while (x > 1) { 11 | total++; 12 | x /= 2; 13 | } 14 | return total; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /ProjectEuler/src/python/005 Smallest multiple.py: -------------------------------------------------------------------------------- 1 | from functools import reduce 2 | 3 | 4 | def gcd(a, b): 5 | while b: 6 | a, b = b, a % b 7 | return a 8 | 9 | def lcm(a, b): 10 | return a * b // gcd(a, b) 11 | 12 | def solve(): 13 | return reduce(lcm, range(1, 21)) 14 | 15 | 16 | if __name__ == "__main__": 17 | print(solve()) 18 | -------------------------------------------------------------------------------- /ProjectEuler/src/python/009 Special Pythagorean triplet.py: -------------------------------------------------------------------------------- 1 | def solve(): 2 | for i in range(1, 1000): 3 | for j in range(1, 1000): 4 | for k in range(1, 1000): 5 | if i*i + j*j == k*k and i+j+k == 1000: 6 | print(i*j*k) 7 | return 8 | 9 | if __name__ == "__main__": 10 | solve() 11 | -------------------------------------------------------------------------------- /leetcode/tree_node.sql: -------------------------------------------------------------------------------- 1 | -- https://leetcode.com/problems/tree-node/description/ 2 | -- 608. Tree Node 3 | 4 | select id as `Id`, 5 | case 6 | when `id` = (select `id` from `tree` where `p_id` is null) then 'Root' 7 | when `id` in (select `p_id` from `tree`) then 'Inner' 8 | else 'Leaf' 9 | end as `Type` 10 | from `tree` order by `id` asc; 11 | -------------------------------------------------------------------------------- /ProjectEuler/src/python/002 even fibo.py: -------------------------------------------------------------------------------- 1 | def solve(): 2 | max_fibo = 4000000 3 | a = 1 4 | b = 1 5 | c = a 6 | total = 0 7 | while c <= max_fibo: 8 | c = a + b 9 | if c % 2 == 0: 10 | total += c 11 | a = b 12 | b = c 13 | 14 | return total 15 | 16 | if __name__ == "__main__": 17 | res = solve() 18 | print(res) 19 | -------------------------------------------------------------------------------- /TopCoder/srm644div2/src/OkonomiyakiShop.java: -------------------------------------------------------------------------------- 1 | public class OkonomiyakiShop { 2 | public int count(int[] osize, int K) { 3 | int n = osize.length; 4 | int res = 0; 5 | for (int i = 0; i < n - 1; i++) 6 | for (int j = i + 1; j < n; j++) 7 | if (Math.abs(osize[i] - osize[j]) <= K) 8 | res++; 9 | return res; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /leetcode/NumberOf1Bits.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/number-of-1-bits/description/ 4 | // 191. Number of 1 Bits 5 | 6 | public class NumberOf1Bits { 7 | public int hammingWeight(int n) { 8 | int res = 0; 9 | 10 | while (n != 0) { 11 | res++; 12 | n = n & (n - 1); 13 | } 14 | 15 | return res; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /ProjectEuler/src/python/011 Largest product in a grid.py: -------------------------------------------------------------------------------- 1 | from sys import stdin 2 | 3 | def solve(): 4 | pass 5 | 6 | if __name__ == "__main__": 7 | a = [] 8 | line = stdin.readline() 9 | n, m = int(line.split(" ")[0]), int(line.split(" ")[1]) 10 | 11 | for i in range(n): 12 | line = stdin.readline().split(" ") 13 | a.append(list(map(int, line))) 14 | 15 | print(a) 16 | -------------------------------------------------------------------------------- /algorithms/dynamic_programming/CoinChangeProblem.java: -------------------------------------------------------------------------------- 1 | package algorithms.dynamic_programming; 2 | 3 | public class CoinChangeProblem { 4 | public int numberOfChanges(int n, int[] c) { 5 | int[] d = new int[n + 1]; 6 | d[0] = 1; 7 | 8 | for (int i = 0; i < c.length; i++) 9 | for (int j = c[i]; j <= n; j++) 10 | d[j] += d[j - c[i]]; 11 | 12 | return d[n]; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /algorithms/sorting/InsertionSort.java: -------------------------------------------------------------------------------- 1 | package algorithms.sorting; 2 | 3 | public class InsertionSort { 4 | public static void sort(int[] arr) { 5 | int n = arr.length; 6 | for (int i = 1; i < n; i++) { 7 | for (int j = i; j > 0 && arr[j] < arr[j - 1]; j--) { 8 | int t = arr[j]; 9 | arr[j] = arr[j - 1]; 10 | arr[j - 1] = t; 11 | } 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /ProjectEuler/README.md: -------------------------------------------------------------------------------- 1 | # Project Euler 2 | 3 | https://projecteuler.net/ 4 | 5 | Project Euler has a lot of problems that are mostly related to mathematics. And it has different approach of challenges and the way you submit the solution. Actually, you don't have to submit the source code, but the answer to one of the big test cases (for example, "What is the answer is N = 1000000", etc.) 6 | 7 | Solutions in: 8 | - [Python](./src/python) 9 | - [Java](./src/java) 10 | -------------------------------------------------------------------------------- /TopCoder/srm649div2/src/DecipherabilityEasy.java: -------------------------------------------------------------------------------- 1 | public class DecipherabilityEasy { 2 | 3 | public String check(String s, String t) { 4 | if (s.length() != t.length() + 1) 5 | return "Impossible"; 6 | 7 | StringBuilder sb; 8 | for (int i = 0; i < s.length(); i++) { 9 | sb = new StringBuilder(s); 10 | String sub = sb.deleteCharAt(i).toString(); 11 | if (sub.equals(t)) 12 | return "Possible"; 13 | } 14 | return "Impossible"; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /leetcode/ExcelSheetColumnTitle.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/excel-sheet-column-title 4 | // 168. Excel Sheet Column Title 5 | 6 | class ExcelSheetColumnTitle { 7 | public String convertToTitle(int n) { 8 | String res = ""; 9 | 10 | while (n > 0) { 11 | n--; 12 | res = (char)('A' + n % 26) + res; 13 | n /= 26; 14 | } 15 | 16 | return res; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /ProjectEuler/src/python/018 Counting Sundays.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | from datetime import timedelta 3 | 4 | count = 0 5 | cur_date = date(1901, 1, 1) 6 | end = date(2000, 12, 31) 7 | 8 | while cur_date <= end: 9 | if cur_date.weekday() == 6: # if it's Sunday 10 | count += 1 11 | month_ahead = cur_date + timedelta(days=32) # go 32 days ahead from current month's 1st day 12 | cur_date = month_ahead.replace(day=1) # set day as 1st 13 | 14 | print(count) 15 | -------------------------------------------------------------------------------- /algorithms/arrays/RotateMatrix.java: -------------------------------------------------------------------------------- 1 | package algorithms.arrays; 2 | 3 | /* 4 | Rotate a square matrix on 90 degrees 5 | */ 6 | 7 | public class RotateMatrix { 8 | public static int[][] rotate(int[][] matrix) { 9 | int n = matrix.length; 10 | int[][] res = new int[n][n]; 11 | 12 | for (int i = 0; i < n; i++) 13 | for (int j = 0; j < n; j++) 14 | res[j][n - i - 1] = matrix[i][j]; 15 | 16 | return res; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /leetcode/PowerOfThree.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/power-of-three/description/ 4 | // 326. Power of Three 5 | 6 | class PowerOfThree { 7 | public boolean isPowerOfThree(int n) { 8 | if (n == 0) 9 | return false; 10 | 11 | if (n == 1) 12 | return true; 13 | 14 | if (n % 3 > 0) 15 | return false; 16 | 17 | return isPowerOfThree(n / 3); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /leetcode/HammingDistance.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/hamming-distance 4 | // 461. Hamming Distance 5 | 6 | public class HammingDistance { 7 | public int hammingDistance(int x, int y) { 8 | int res = 0; 9 | 10 | while (x != 0 || y != 0) { 11 | if (((x & 1) ^ (y & 1)) == 1) 12 | res++; 13 | 14 | x >>= 1; 15 | y >>= 1; 16 | } 17 | 18 | return res; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode/RemoveElement.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/remove-element 4 | // 27. Remove Element 5 | 6 | class RemoveElement { 7 | public int removeElement(int[] nums, int val) { 8 | int ind = 0; 9 | 10 | for (int i = 0; i < nums.length; i++) { 11 | if (nums[i] != val) { 12 | nums[ind] = nums[i]; 13 | ind++; 14 | } 15 | } 16 | 17 | return ind; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /leetcode/ValidPalindrome.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/valid-palindrome/description/ 4 | // 125. Valid Palindrome 5 | 6 | class ValidPalindrome { 7 | public boolean isPalindrome(String s) { 8 | if (s.length() == 0) 9 | return true; 10 | 11 | s = s.replaceAll("\\W", "").toUpperCase(); 12 | String reversed = new StringBuilder(s).reverse().toString(); 13 | 14 | return s.equals(reversed); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /ProjectEuler/src/python/022 names scores.py: -------------------------------------------------------------------------------- 1 | filename = "names.txt" 2 | 3 | with open(filename) as f: 4 | content = f.readlines() # get all names 5 | 6 | names = [] 7 | for name in content[0].split(","): 8 | names.append(name[1:-1]) # remove quotes 9 | 10 | names = sorted(names) # sort names 11 | 12 | total = 0 13 | for i, name in enumerate(names): 14 | cur_val = 0 15 | for x in name: 16 | cur_val += ord(x) - ord('A') + 1 17 | total += cur_val * (i+1) 18 | 19 | print(total) 20 | -------------------------------------------------------------------------------- /TopCoder/srm642div2/src/ForgetfulAddition.java: -------------------------------------------------------------------------------- 1 | public class ForgetfulAddition { 2 | 3 | public int minNumber(String expression) { 4 | int min = Integer.MAX_VALUE; 5 | for (int i = 1; i <= expression.length() - 1; i++) { 6 | int val1 = Integer.parseInt(expression.substring(0, i)); 7 | int val2 = Integer.parseInt(expression.substring(i)); 8 | if (min > val1 + val2) 9 | min = val1 + val2; 10 | } 11 | return min; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Algorithms and Data structures 2 | 3 | This repository is aimed to collect implementations of some of the popular algorithms and data structures. 4 | 5 | - [Algorithms and Data Structures](./algorithms) 6 | - [LeetCode](./leetcode) 7 | - [TopCoder](./TopCoder) 8 | - [CodeForces](./codeforces) 9 | - [Hackerrank](./Hackerrank) 10 | - [Project Euler](./ProjectEuler) 11 | 12 | 13 | If you find something useful or interesting please feel free to grab, or give me feedback via email: gmegido@gmail.com 14 | -------------------------------------------------------------------------------- /leetcode/ClimbingStairs.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/climbing-stairs/description/ 4 | // 70. Climbing Stairs 5 | 6 | class ClimbingStairs { 7 | public int climbStairs(int n) { 8 | if (n == 0) 9 | return 1; 10 | 11 | int[] dp = new int[n + 1]; 12 | dp[0] = 1; 13 | dp[1] = 1; 14 | 15 | for (int i = 2; i <= n; i++) 16 | dp[i] = dp[i - 1] + dp[i - 2]; 17 | 18 | return dp[n]; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode/BestTimeToBuyAndSellStockII.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii 4 | // 122. Best Time to Buy and Sell Stock II 5 | 6 | class BestTimeToBuyAndSellStockII { 7 | 8 | public int maxProfit(int[] prices) { 9 | int profit = 0; 10 | 11 | for (int i = 1; i < prices.length; i++) 12 | if (prices[i] > prices[i - 1]) 13 | profit += prices[i] - prices[i - 1]; 14 | 15 | return profit; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /leetcode/ContainsDuplicate.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/contains-duplicate/ 4 | // 217. Contains Duplicate 5 | 6 | import java.util.*; 7 | 8 | public class ContainsDuplicate { 9 | public boolean containsDuplicate(int[] nums) { 10 | Set set = new HashSet(); 11 | 12 | for (int x : nums) { 13 | if (set.contains(x)) 14 | return true; 15 | set.add(x); 16 | } 17 | 18 | return false; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /ProjectEuler/src/python/033 Digit cancelling fractions.py: -------------------------------------------------------------------------------- 1 | from fractions import gcd 2 | 3 | """ 4 | 5 | 10*n + i n 6 | -------- = - 7 | 10*i + d d 8 | 9 | """ 10 | 11 | numerator = 1 12 | denominator = 1 13 | 14 | for i in range(1, 10): 15 | for n in range(1, 9): 16 | for d in range(n + 1, 10): 17 | if d * (10 * n + i) == n * (10 * i + d): 18 | numerator *= n 19 | denominator *= d 20 | 21 | common = gcd(numerator, denominator) 22 | print(denominator/common) 23 | -------------------------------------------------------------------------------- /TopCoder/srm467div2/src/ShorterSuperSum.java: -------------------------------------------------------------------------------- 1 | public class ShorterSuperSum { 2 | public int calculate(int k, int n) { 3 | int[][] s = new int[k + 1][n + 1]; 4 | 5 | for (int i = 0; i <= n; i++) 6 | s[0][i] = i; 7 | 8 | for (int kk = 1; kk <= k; kk++) { 9 | for (int nn = 1; nn <= n; nn++) { 10 | for (int i = 1; i <= nn; i++) 11 | s[kk][nn] += s[kk - 1][i]; 12 | } 13 | } 14 | 15 | return s[k][n]; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /codeforces/round238_div2/ProblemB.java: -------------------------------------------------------------------------------- 1 | package codeforces.round238_div2; 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | 6 | public class ProblemB { 7 | public void solve() { 8 | Scanner in = new Scanner(System.in); 9 | PrintWriter out = new PrintWriter(System.out); 10 | long n = in.nextInt() - 2; 11 | out.print(n * n); 12 | out.close(); 13 | } 14 | 15 | public static void main(String[] args) { 16 | new codeforces.round305_div2.ProblemB().solve(); 17 | } 18 | } -------------------------------------------------------------------------------- /TopCoder/srm646div2/src/TheConsecutiveIntegersDivTwo.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class TheConsecutiveIntegersDivTwo { 4 | 5 | public int find(int[] numbers, int k) { 6 | if (k == 1) 7 | return 0; 8 | int minDiff = 20000001; 9 | Arrays.sort(numbers); 10 | for (int i = 0; i < numbers.length - 1; i++) { 11 | if (minDiff > numbers[i+1] - numbers[i] - 1) 12 | minDiff = numbers[i+1] - numbers[i] - 1; 13 | } 14 | return minDiff; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /algorithms/dynamic_programming/test/ScoresProblemTest.java: -------------------------------------------------------------------------------- 1 | import algorithms.dynamic_programming.ScoresProblem; 2 | import org.junit.Test; 3 | 4 | import static org.junit.Assert.assertEquals; 5 | 6 | public class ScoresProblemTest { 7 | 8 | @Test 9 | public void mainTest() { 10 | int test = 12; 11 | int[] scores = new int[]{2, 3, 7}; 12 | assertEquals(18, ScoresProblem.countNumberOfScoreCombinations(test, scores)); 13 | assertEquals(4, ScoresProblem.numberOfNonRepeatedCombinations(test, scores)); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /leetcode/RotateArray.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/rotate-array/description/ 4 | // 189. Rotate Array 5 | 6 | class RotateArray { 7 | public void rotate(int[] nums, int k) { 8 | int n = nums.length; 9 | k %= n; 10 | int[] d = new int[2 * n]; 11 | for (int i = 0; i < n; i++) { 12 | d[i] = nums[i]; 13 | d[i + n] = nums[i]; 14 | } 15 | 16 | for (int i = 0; i < n; i++) { 17 | nums[i] = d[n - k + i]; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /algorithms/dynamic_programming/MaximumSubarray.java: -------------------------------------------------------------------------------- 1 | package algorithms.dynamic_programming; 2 | 3 | import java.util.*; 4 | 5 | public class MaximumSubarray { 6 | public static int getMaxSubArray(List list) { 7 | int minSum = 0, sum = 0, maxSum = 0; 8 | for (int x : list) { 9 | sum += x; 10 | 11 | if (minSum > sum) 12 | minSum = sum; 13 | 14 | if (maxSum < sum - minSum) 15 | maxSum = sum - minSum; 16 | } 17 | 18 | return maxSum; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode/DeleteNodeInALinkedList.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/delete-node-in-a-linked-list/description/ 4 | // 237. Delete Node in a Linked List 5 | 6 | public class DeleteNodeInALinkedList { 7 | public void deleteNode(ListNode node) { 8 | if (node == null) 9 | return; 10 | node.val = node.next.val; 11 | node.next = node.next.next; 12 | } 13 | 14 | public class ListNode { 15 | int val; 16 | ListNode next; 17 | ListNode(int x) { val = x; } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /leetcode/MinimumMovesToEqualArrayElementsII.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/description/ 4 | // 462. Minimum Moves to Equal Array Elements II 5 | 6 | import java.util.Arrays; 7 | 8 | class MinimumMovesToEqualArrayElementsII { 9 | public int minMoves2(int[] nums) { 10 | Arrays.sort(nums); 11 | int res = 0; 12 | int i = 0, j = nums.length - 1; 13 | while (i < j) 14 | res += nums[j--] - nums[i++]; 15 | 16 | return res; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /codeforces/round322_div2/ProblemA.java: -------------------------------------------------------------------------------- 1 | package codeforces.round322_div2; 2 | 3 | import java.io.PrintWriter; 4 | import java.util.*; 5 | 6 | public class ProblemA { 7 | 8 | public static void main(String[] args) { 9 | Scanner in = new Scanner(System.in); 10 | PrintWriter out = new PrintWriter(System.out); 11 | 12 | int red = in.nextInt(); 13 | int blue = in.nextInt(); 14 | 15 | out.print(Math.min(red, blue) + " "); 16 | out.print((Math.max(red, blue) - Math.min(red, blue)) / 2); 17 | 18 | out.close(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode/FindTheDuplicateNumber.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/find-the-duplicate-number/description/ 4 | // 287. Find the Duplicate Number 5 | 6 | import java.util.Arrays; 7 | 8 | public class FindTheDuplicateNumber { 9 | public int findDuplicate(int[] nums) { 10 | int res = 0; 11 | Arrays.sort(nums); 12 | for (int i = 0; i < nums.length - 1; i++) 13 | if (nums[i] == nums[i + 1]) { 14 | res = nums[i]; 15 | break; 16 | } 17 | 18 | return res; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode/MaximumDepthOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/maximum-depth-of-binary-tree/description/ 4 | // 104. Maximum Depth of Binary Tree 5 | 6 | 7 | class MaximumDepthOfBinaryTree { 8 | class TreeNode { 9 | int val; 10 | TreeNode left; 11 | TreeNode right; 12 | TreeNode(int x) { val = x; } 13 | } 14 | 15 | public int maxDepth(TreeNode root) { 16 | if (root == null) 17 | return 0; 18 | return Math.max(maxDepth(root.left) + 1, maxDepth(root.right) + 1); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /ProjectEuler/src/python/021 Amicable numbers.py: -------------------------------------------------------------------------------- 1 | def sum_of_divisors(x): 2 | if x == 1: 3 | return 1 4 | 5 | total = 1 6 | for i in range(2, int(x**0.5)+1): 7 | if x % i == 0: 8 | total += i 9 | if x // i != i: 10 | total += x // i 11 | return total 12 | 13 | res = {} 14 | n = 10000 15 | for num in range(2, n+1): 16 | res[num] = sum_of_divisors(num) 17 | 18 | total_sum = 0 19 | for key, value in res.items(): 20 | if value in res and key == res[value] and key != value: 21 | total_sum += key 22 | 23 | print(total_sum) 24 | -------------------------------------------------------------------------------- /leetcode/MinCostClimbingStairs.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/min-cost-climbing-stairs/description/ 4 | // 746. Min Cost Climbing Stairs 5 | 6 | public class MinCostClimbingStairs { 7 | public int minCostClimbingStairs(int[] cost) { 8 | int n = cost.length; 9 | int[] dp = new int[n + 1]; 10 | dp[0] = cost[0]; 11 | dp[1] = cost[1]; 12 | 13 | for (int i = 2; i < n; i++) { 14 | dp[i] = Math.min(dp[i - 1], dp[i - 2]) + cost[i]; 15 | } 16 | 17 | return Math.min(dp[n - 1], dp[n - 2]); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /leetcode/PaintFence.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/paint-fence/ 4 | // 276. Paint Fence 5 | 6 | public class PaintFence { 7 | public int numWays(int n, int k) { 8 | if (n == 0) 9 | return 0; 10 | 11 | if (n == 1) 12 | return k; 13 | 14 | int same = k; 15 | int diff = k * (k - 1); 16 | 17 | for (int i = 2; i < n; i++) { 18 | int temp = diff; 19 | diff = (same + diff) * (k - 1); 20 | same = temp; 21 | } 22 | 23 | return same + diff; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /TopCoder/srm652div2/src/ThePermutationGameDiv2.java: -------------------------------------------------------------------------------- 1 | public class ThePermutationGameDiv2 { 2 | 3 | public long gcd(long a, long b) { 4 | long r = a % b; 5 | while (r != 0) { 6 | a = b; 7 | b = r; 8 | r = a % b; 9 | } 10 | return b; 11 | } 12 | 13 | public long lcm(long a, long b) { 14 | return a * b / gcd(a, b); 15 | } 16 | 17 | public long findMin(int N) { 18 | long result = 1l; 19 | for (int i = 1; i <= N; i++) 20 | result = lcm(result, (long)i); 21 | return result; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /TopCoder/srm661div2/src/BridgeBuildingDiv2.java: -------------------------------------------------------------------------------- 1 | public class BridgeBuildingDiv2 { 2 | public int minDiameter(int[] a, int[] b, int k) { 3 | int n = a.length; 4 | int[][] d = new int[2 * n][2 * n]; 5 | 6 | for (int mask = 0; mask < (1 << k); mask++) { 7 | if (Integer.bitCount(mask) == k) { 8 | for (int i = 0; i < n; i++) 9 | if (mask & (1 << i) ) { 10 | d[i][i + n] = 0; 11 | d[i + n][i] = 0; 12 | } 13 | } 14 | } 15 | return 0; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /leetcode/HouseRobber.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/house-robber/ 4 | // 198. HouseRobber 5 | 6 | class HouseRobber { 7 | public int rob(int[] nums) { 8 | int n = nums.length; 9 | 10 | int prevRobbed = 0; 11 | int prevNotRobbed = 0; 12 | 13 | for (int i = 0; i < n; i++) { 14 | int temp = prevNotRobbed; 15 | prevNotRobbed = Math.max(prevNotRobbed, prevRobbed); 16 | prevRobbed = temp + nums[i]; 17 | } 18 | 19 | return Math.max(prevRobbed, prevNotRobbed); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /leetcode/KthLargestElementInAnArray.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/kth-largest-element-in-an-array/description/ 4 | // 215. Kth Largest Element in an Array 5 | 6 | import java.util.*; 7 | 8 | class KthLargestElementInAnArray { 9 | public int findKthLargest(int[] nums, int k) { 10 | PriorityQueue pq = new PriorityQueue<>(k + 1); 11 | 12 | for (int i = 0; i < nums.length; i++) { 13 | pq.add(nums[i]); 14 | 15 | if (i >= k) 16 | pq.poll(); 17 | } 18 | 19 | return pq.peek(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /leetcode/FindAnagramMappings.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/find-anagram-mappings/description/ 4 | // 760. Find Anagram Mappings 5 | 6 | import java.util.*; 7 | 8 | public class FindAnagramMappings { 9 | public int[] anagramMappings(int[] A, int[] B) { 10 | Map map = new HashMap(); 11 | int[] res = new int[A.length]; 12 | 13 | for (int i = 0; i < B.length; i++) 14 | map.put(B[i], i); 15 | 16 | for (int i = 0; i < A.length; i++) 17 | res[i] = map.get(A[i]); 18 | 19 | return res; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /algorithms/sorting/SelectionSort.java: -------------------------------------------------------------------------------- 1 | package algorithms.sorting; 2 | 3 | public class SelectionSort { 4 | private static void swap(int[] arr, int i, int j) { 5 | int temp = arr[i]; 6 | arr[i] = arr[j]; 7 | arr[j] = temp; 8 | } 9 | 10 | public static void sort(int[] arr) { 11 | int n = arr.length; 12 | for (int i = 0; i < n; i++) { 13 | int minIndex = i; 14 | for (int j = i + 1; j < n; j++) 15 | if (arr[j] < arr[minIndex]) 16 | minIndex = j; 17 | swap(arr, minIndex, i); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode/ContainsDuplicateII.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/contains-duplicate-ii/description/ 4 | // 219. Contains Duplicate II 5 | 6 | import java.util.*; 7 | 8 | public class ContainsDuplicateII { 9 | public boolean containsNearbyDuplicate(int[] nums, int k) { 10 | Map map = new HashMap(); 11 | 12 | for (int i = 0; i < nums.length; i++) { 13 | if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) 14 | return true; 15 | map.put(nums[i], i); 16 | } 17 | 18 | return false; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /ProjectEuler/src/python/015 Lattice paths.py: -------------------------------------------------------------------------------- 1 | def solve(n, m): 2 | d = [] 3 | for i in range(0, n): 4 | col = [] 5 | for j in range(0, m): 6 | col.append(0) 7 | d.append(col) 8 | 9 | d[0][0] = 1 10 | for i in range(1, n): 11 | d[i][0] = 1 12 | 13 | for j in range(1, m): 14 | d[0][j] = 1 15 | 16 | for i in range(1, n): 17 | for j in range(1, m): 18 | d[i][j] = d[i-1][j] + d[i][j-1] 19 | 20 | return d[n-1][m-1] 21 | 22 | if __name__ == "__main__": 23 | n = 20 24 | m = 20 25 | res = solve(n+1, m+1) 26 | print(res) 27 | -------------------------------------------------------------------------------- /leetcode/JewelsAndStones.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/jewels-and-stones/description/ 4 | // 771. Jewels and Stones 5 | 6 | import java.util.*; 7 | 8 | public class JewelsAndStones { 9 | public int numJewelsInStones(String J, String S) { 10 | Set jewels = new HashSet(); 11 | int res = 0; 12 | 13 | for (int i = 0; i < J.length(); i++) 14 | jewels.add(J.charAt(i)); 15 | 16 | for (int i = 0; i < S.length(); i++) 17 | if (jewels.contains(S.charAt(i))) 18 | res++; 19 | 20 | return res; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /leetcode/MaxConsecutiveOnes.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/max-consecutive-ones/description/ 4 | // 485. Max Consecutive Ones 5 | 6 | public class MaxConsecutiveOnes { 7 | public int findMaxConsecutiveOnes(int[] nums) { 8 | int count = 0, max = 0; 9 | for (int num : nums) { 10 | if (num == 0) { 11 | max = Math.max(max, count); 12 | count = 0; 13 | continue; 14 | } 15 | 16 | count++; 17 | } 18 | 19 | max = Math.max(max, count); 20 | 21 | return max; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /leetcode/UniquePaths.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/unique-paths/description/ 4 | // 62. Unique Paths 5 | 6 | public class UniquePaths { 7 | public int uniquePaths(int m, int n) { 8 | long[][] d = new long[m][n]; 9 | d[0][0] = 1; 10 | for (int i = 1; i < m; i++) 11 | d[i][0] = 1; 12 | 13 | for (int i = 1; i < n; i++) 14 | d[0][i] = 1; 15 | 16 | for (int i = 1; i < m; i++) 17 | for (int j = 1; j < n; j++) 18 | d[i][j] = d[i - 1][j] + d[i][j - 1]; 19 | 20 | return (int)d[m - 1][n - 1]; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /ProjectEuler/src/python/004 Largest palindrome product.py: -------------------------------------------------------------------------------- 1 | def is_palindrome(x): 2 | n = x 3 | rev = 0 4 | while x > 0: 5 | dig = x % 10 6 | rev = rev * 10 + dig 7 | x //= 10 8 | return n == rev 9 | 10 | def get_largest_palindrome_product(): 11 | pal = 0 12 | for i in range(100, 1000): 13 | for j in range(100, 1000): 14 | if i != j: 15 | cur = i * j 16 | if is_palindrome(cur) and pal < cur: 17 | pal = cur 18 | return pal 19 | 20 | if __name__ == "__main__": 21 | res = get_largest_palindrome_product() 22 | print(res) 23 | -------------------------------------------------------------------------------- /leetcode/NthDigit.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/nth-digit/description/ 4 | // 400. Nth Digit 5 | 6 | public class NthDigit { 7 | public int findNthDigit(int n) { 8 | int len = 1; 9 | long count = 9; 10 | int start = 1; 11 | 12 | while (n > len * count) { 13 | n -= len * count; 14 | 15 | len++; 16 | count *= 10; 17 | start *= 10; 18 | } 19 | 20 | start += (n - 1) / len; 21 | 22 | String s = String.valueOf(start); 23 | return Character.getNumericValue(s.charAt((n - 1) % len)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /codeforces/round327_div2/ProblemA.java: -------------------------------------------------------------------------------- 1 | package codeforces.round327_div2; 2 | 3 | import java.io.PrintWriter; 4 | import java.util.*; 5 | 6 | public class ProblemA { 7 | 8 | public static void main(String[] args) { 9 | Scanner in = new Scanner(System.in); 10 | PrintWriter out = new PrintWriter(System.out); 11 | int l = in.nextInt(); 12 | 13 | int p = in.nextInt(); 14 | int q = in.nextInt(); 15 | 16 | double time; 17 | q += p; 18 | time = 1.0 * l / q; 19 | 20 | double res = time * p; 21 | out.print(String.format("%.4f", res)); 22 | out.close(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /leetcode/ValidPerfectSquare.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/valid-perfect-square/description/ 4 | // 367. Valid Perfect Square 5 | 6 | class ValidPerfectSquare { 7 | public boolean isPerfectSquare(int num) { 8 | int l = 1; 9 | int r = num; 10 | 11 | while (l < r) { 12 | int m = l + (r - l) / 2; 13 | 14 | if (m * m == num) 15 | return true; 16 | else if (num / m < m) 17 | r = m; 18 | else 19 | l = m + 1; 20 | } 21 | 22 | return l * l == num; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /leetcode/FindTheDifference.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/find-the-difference/description/ 4 | // 389. Find the Difference 5 | 6 | public class FindTheDifference { 7 | public char findTheDifference(String s, String t) { 8 | int[] count = new int[128]; 9 | char res = 'a'; // dummy init 10 | 11 | for (char c : s.toCharArray()) 12 | count[c]++; 13 | 14 | for (char c : t.toCharArray()) { 15 | count[c]--; 16 | if (count[c] < 0) { 17 | res = c; 18 | break; 19 | } 20 | } 21 | 22 | return res; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /leetcode/MinimumSizeSubarraySum.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/minimum-size-subarray-sum/description/ 4 | // 209. Minimum Size Subarray Sum 5 | 6 | public class MinimumSizeSubarraySum { 7 | public int minSubArrayLen(int s, int[] nums) { 8 | int res = Integer.MAX_VALUE; 9 | 10 | int i = 0, j = 0, sum = 0; 11 | while (j < nums.length) { 12 | sum += nums[j++]; 13 | 14 | while (sum >= s) { 15 | res = Math.min(res, j - i); 16 | sum -= nums[i++]; 17 | } 18 | } 19 | 20 | return res == Integer.MAX_VALUE ? 0 : res; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /leetcode/Subsets.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/subsets/description/ 4 | // 78. Subsets 5 | 6 | import java.util.*; 7 | 8 | class Subsets { 9 | List> res; 10 | 11 | public List> subsets(int[] nums) { 12 | res = new ArrayList(); 13 | for (int i = 0; i < (1 << nums.length); i++) { 14 | List subset = new ArrayList(); 15 | for (int j = 0; j < nums.length; j++) 16 | if ((i & (1 << j)) > 0) 17 | subset.add(nums[j]); 18 | 19 | res.add(subset); 20 | } 21 | 22 | return res; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /TopCoder/srm652div2/src/ValueOfString.java: -------------------------------------------------------------------------------- 1 | public class ValueOfString { 2 | 3 | public int charValue(char c) { 4 | return c - 'a' + 1; 5 | } 6 | 7 | public int findValue(String s) { 8 | int total = 0; 9 | for (int i = 0; i < s.length(); i++) { 10 | char c = s.charAt(i); 11 | int curAppearances = 0; 12 | for (int j = 0; j < s.length(); j++) 13 | if (s.charAt(j) <= c) 14 | curAppearances++; 15 | 16 | int curCharValue = charValue(c); 17 | total += curAppearances * curCharValue; 18 | 19 | } 20 | return total; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /algorithms/strings/test/CheckPermutationTest.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | import static algorithms.strings.CheckPermutation.*; 4 | import static org.junit.Assert.assertEquals; 5 | 6 | 7 | public class CheckPermutationTest { 8 | @Test 9 | public void mainTest() { 10 | assertEquals(true, check( "alibek", "kebila")); 11 | assertEquals(false, check( "alibek", "bekalk")); 12 | assertEquals(false, check( "abcde", "edcbaedcba")); 13 | 14 | assertEquals(true, check1( "alibek", "kebila")); 15 | assertEquals(false, check1( "alibek", "bekalk")); 16 | assertEquals(false, check1( "abcde", "edcbaedcba")); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /leetcode/SumOfSquareNumbers3.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/sum-of-square-numbers/description/ 4 | // 633. Sum of Square Numbers 5 | 6 | class SumOfSquareNumbers3 { 7 | public boolean judgeSquareSum(int c) { 8 | int left = 0; 9 | int right = (int)Math.sqrt(c); 10 | while (left <= right) { 11 | int cur = left * left + right * right; 12 | 13 | if (cur > c) 14 | right--; 15 | else if (cur < c) 16 | left++; 17 | else 18 | return true; 19 | } 20 | 21 | return false; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /ProjectEuler/src/python/032 Pandigital products.py: -------------------------------------------------------------------------------- 1 | def is_pandigital(num_str, pan=9): 2 | s = '' 3 | for c in range(1, pan+1): 4 | s += str(c) 5 | 6 | sorted_str = ''.join(sorted(num_str)) # sort given string 7 | return s == sorted_str # and compare to all numbers along from 1 to 9 8 | 9 | products = set() 10 | 11 | for i in range(2, 60): # multiplicand 12 | start = 1234 if i < 10 else 123 # multiplier 13 | for j in range(start, 10000//i): 14 | if is_pandigital(str(i) + str(j) + str(i*j)): 15 | products.add(i*j) # store products in set because we may have multiple ways to get pandigital 16 | 17 | print(sum(products)) 18 | -------------------------------------------------------------------------------- /leetcode/CountPrimes.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/count-primes/ 4 | // 204. Count Primes 5 | 6 | class CountPrimes { 7 | public int countPrimes(int n) { 8 | int count = 0; 9 | 10 | int[] p = new int[n + 1]; 11 | int cur = 2; 12 | while (cur < n) { 13 | int i = cur; 14 | if (p[i] == 0) { 15 | count++; 16 | while (i < n) { 17 | p[i] = 1; 18 | i+= cur; 19 | } 20 | } 21 | 22 | cur++; 23 | } 24 | 25 | return count; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /leetcode/PathSum.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/path-sum/description/ 4 | // 112. Path Sum 5 | 6 | public class PathSum { 7 | public boolean hasPathSum(TreeNode root, int sum) { 8 | if (root == null) 9 | return false; 10 | 11 | if (root.left == null && root.right == null && sum - root.val == 0) 12 | return true; 13 | 14 | return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); 15 | } 16 | 17 | public class TreeNode { 18 | int val; 19 | TreeNode left; 20 | TreeNode right; 21 | TreeNode(int x) { val = x; } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /leetcode/ValidWordSquare.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/valid-word-square/description/ 4 | // 422. Valid Word Square 5 | 6 | import java.util.List; 7 | 8 | public class ValidWordSquare { 9 | public boolean validWordSquare(List words) { 10 | for (int i = 0; i < words.size(); i++) { 11 | String row = words.get(i); 12 | for (int j = 0; j < row.length(); j++) { 13 | 14 | if (j >= words.size() || i >= words.get(j).length() || words.get(j).charAt(i) != row.charAt(j)) 15 | return false; 16 | } 17 | } 18 | 19 | return true; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /leetcode/BestTimeToBuyAndSellStock.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/best-time-to-buy-and-sell-stock 4 | // 121. Best Time to Buy and Sell Stock 5 | 6 | class BestTimeToBuyAndSellStock { 7 | public int maxProfit(int[] prices) { 8 | int res = 0; 9 | int min = Integer.MAX_VALUE; 10 | 11 | for (int x : prices) { 12 | if (min > x) { 13 | min = x; 14 | continue; 15 | } 16 | 17 | int diff = x - min; 18 | 19 | if (res < diff) { 20 | res = diff; 21 | } 22 | } 23 | 24 | return res; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /leetcode/NimGame.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/nim-game 4 | // 292. Nim Game 5 | 6 | import java.io.PrintWriter; 7 | import java.util.*; 8 | 9 | public class NimGame { 10 | 11 | public boolean canWinNim(int n) { 12 | return n % 4 > 0; 13 | } 14 | 15 | public void solve() { 16 | Scanner in = new Scanner(System.in); 17 | PrintWriter out = new PrintWriter(System.out); 18 | int n = in.nextInt(); 19 | boolean res = canWinNim(n); 20 | out.print(res); 21 | out.close(); 22 | } 23 | 24 | public static void main(String[] args) { 25 | new NimGame().solve(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /algorithms/sorting/ShellSort.java: -------------------------------------------------------------------------------- 1 | package algorithms.sorting; 2 | 3 | public class ShellSort { 4 | private static void swap(int[] arr, int i, int j) { 5 | int temp = arr[i]; 6 | arr[i] = arr[j]; 7 | arr[j] = temp; 8 | } 9 | 10 | public static void sort(int[] arr) { 11 | int n = arr.length; 12 | int h = 1; 13 | 14 | while (h < n / 3) 15 | h = 3 * h + 1; 16 | 17 | while (h >= 1) { 18 | for (int i = h; i < n; i++) 19 | for (int j = i; j >= h && arr[j] < arr[j - h]; j -= h) 20 | swap(arr, j, j - h); 21 | 22 | h /= 3; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /leetcode/Sqrt.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/sqrtx 4 | // 69. Sqrt(x) 5 | 6 | class Sqrt { 7 | public int mySqrt(int x) { 8 | if (x < 2) 9 | return x; 10 | 11 | long l = 1; 12 | long r = x; 13 | while (l < r) { 14 | long m = l + (r - l) / 2; 15 | 16 | if (m * m > (long)(x)) 17 | r = m; 18 | else if (m * m < (long)(x)) 19 | l = m + 1; 20 | else 21 | return (int)(m); 22 | } 23 | if (l * l > x) 24 | l--; 25 | 26 | return (int)(l); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode/ValidAnagram.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/valid-anagram/description/ 4 | // 242. Valid Anagram 5 | 6 | import java.util.Arrays; 7 | 8 | class ValidAnagram { 9 | public boolean isAnagram(String s, String t) { 10 | if (s.length() != t.length()) 11 | return false; 12 | 13 | char[] c1 = s.toCharArray(); 14 | char[] c2 = t.toCharArray(); 15 | 16 | Arrays.sort(c1); 17 | Arrays.sort(c2); 18 | 19 | for (int i = 0; i < c1.length; i++) 20 | if (c1[i] != c2[i]) 21 | return false; 22 | 23 | return true; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /ProjectEuler/src/python/023 Non-abundant sums.py: -------------------------------------------------------------------------------- 1 | def div_sum(x): 2 | total = 0 3 | for i in range(2, int(x**0.5+1)): 4 | if x % i == 0: 5 | total += i 6 | if x // i != i: 7 | total += x // i 8 | return total 9 | 10 | 11 | abundants = [] 12 | sums = set() 13 | 14 | for n in range(1, 28124): 15 | cur_sum = div_sum(n) 16 | if cur_sum > n: 17 | abundants.append(n) 18 | for j in range(0, len(abundants)): 19 | sums.add(n + abundants[j]) 20 | 21 | total_sum = 0 22 | for num in range(1, 28124): 23 | if num not in sums: 24 | print(num) 25 | total_sum += num 26 | 27 | print(total_sum) 28 | -------------------------------------------------------------------------------- /ProjectEuler/src/python/031 Coin sums.py: -------------------------------------------------------------------------------- 1 | coins = [1, 2, 5, 10, 20, 50, 100, 200] 2 | target = 200 3 | d = {} # d[x][y] - number of ways to get x coins using coins with index up to y from "coins" array 4 | 5 | for i in range(0, target + 1): 6 | d[i, 0] = 1 7 | 8 | for y in range(0, target + 1): 9 | for x in range(1, len(coins)): 10 | d[y, x] = 0 11 | 12 | if y >= coins[x]: 13 | d[y, x] += d[y, x - 1] # same as previous number, +1 gives same amount of ways 14 | d[y, x] += d[y - coins[x], x] # plus number of ways without current coin 15 | else: 16 | d[y, x] = d[y, x - 1] # using current coin will overlap total 17 | 18 | print(d[200, 7]) 19 | -------------------------------------------------------------------------------- /leetcode/PalindromePermutation.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/palindrome-permutation/description/ 4 | // 266. Palindrome Permutation 5 | 6 | public class PalindromePermutation { 7 | public boolean canPermutePalindrome(String s) { 8 | // palindrome is when all characters appears twice 9 | // and at most one character appears once 10 | int[] ch = new int[128]; 11 | int count = 0; 12 | for (int i = 0; i < s.length(); i++) { 13 | int num = s.charAt(i); 14 | ch[num]++; 15 | if (ch[num] % 2 == 0) count--; 16 | else count++; 17 | } 18 | 19 | return count <= 1; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /ProjectEuler/src/java/003 Largest prime factor/src/Solution.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Solution { 5 | public static void main(String[] args) { 6 | Scanner in = new Scanner(System.in); 7 | PrintWriter out = new PrintWriter(System.out); 8 | int t = in.nextInt(); 9 | while (t > 0) { 10 | long n = in.nextLong(); 11 | long i = 2; 12 | 13 | while (i < (long)Math.sqrt(n) + 1) { 14 | while (n % i == 0 && i != n) 15 | n /= i; 16 | i++; 17 | } 18 | out.println(n); 19 | t--; 20 | } 21 | out.close(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /leetcode/ProductOfArrayExceptSelf.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/product-of-array-except-self/description/ 4 | // 238. Product of Array Except Self 5 | 6 | class ProductOfArrayExceptSelf { 7 | public int[] productExceptSelf(int[] nums) { 8 | int n = nums.length; 9 | int[] res = new int[n]; 10 | res[0] = 1; 11 | 12 | for (int i = 1; i < n; i++) { 13 | res[i] = res[i - 1] * nums[i - 1]; 14 | } 15 | 16 | int right = 1; 17 | for (int i = n - 1; i >= 0; i--) { 18 | res[i] *= right; 19 | right *= nums[i]; 20 | } 21 | 22 | return res; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /leetcode/TwoSum.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/two-sum/description/ 4 | // 1. Two Sum 5 | 6 | import java.util.HashMap; 7 | import java.util.Map; 8 | 9 | public class TwoSum { 10 | public int[] twoSum(int[] nums, int target) { 11 | int[] res = new int[2]; 12 | 13 | Map map = new HashMap(); 14 | for (int i = 0; i < nums.length; i++) { 15 | int x = nums[i]; 16 | if (map.containsKey(x)) { 17 | res[0] = i; 18 | res[1] = map.get(x); 19 | break; 20 | } 21 | 22 | map.put(target - x, i); 23 | } 24 | 25 | return res; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /leetcode/ValidateBinarySearchTree.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/validate-binary-search-tree/ 4 | // 98. Validate Binary Search Tree 5 | 6 | class Solution { 7 | public boolean isValidBST(TreeNode root) { 8 | return rec(root, Long.MIN_VALUE, Long.MAX_VALUE); 9 | } 10 | 11 | public boolean rec(TreeNode node, long min, long max) { 12 | return node == null || 13 | node.val < max && node.val > min && rec(node.left, node.val, min) && rec(node.right, max, node.val); 14 | } 15 | 16 | public class TreeNode { 17 | int val; 18 | TreeNode left; 19 | TreeNode right; 20 | TreeNode(int x) { val = x; } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Hackerrank/Algorithms/Implementation/src/SockMerchant.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | public class SockMerchant { 5 | public static void main(String[] args) { 6 | Scanner in = new Scanner(System.in); 7 | PrintWriter out = new PrintWriter(System.out); 8 | int res = 0; 9 | int n = in.nextInt(); 10 | Set set = new HashSet<>(); 11 | for (int i = 0; i < n; i++) { 12 | int x = in.nextInt(); 13 | if (set.contains(x)) { 14 | set.remove(x); 15 | res++; 16 | } else 17 | set.add(x); 18 | } 19 | 20 | out.print(res); 21 | out.close(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /leetcode/PaintHouse.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/paint-house/description/ 4 | // 256. Paint House 5 | 6 | class PaintHouse { 7 | public int minCost(int[][] costs) { 8 | int n = costs.length; 9 | 10 | if (n == 0) 11 | return 0; 12 | 13 | for (int i = 1; i < costs.length; i++) { 14 | costs[i][0] += Math.min(costs[i - 1][1], costs[i - 1][2]); 15 | costs[i][1] += Math.min(costs[i - 1][0], costs[i - 1][2]); 16 | costs[i][2] += Math.min(costs[i - 1][0], costs[i - 1][1]); 17 | } 18 | 19 | return Math.min(costs[n - 1][0], Math.min(costs[n - 1][1], costs[n - 1][2])); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /algorithms/strings/test/URLifyTest.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | import static algorithms.strings.URLify.*; 4 | import static org.junit.Assert.assertEquals; 5 | 6 | public class URLifyTest { 7 | @Test 8 | public void mainTest() { 9 | char[] c1 = "Mr John Smith ".toCharArray(); 10 | assertEquals("Mr%20John%20Smith", convert(c1, 13)); 11 | assertEquals("Mr%20John%20Smith", convert1(c1, 13)); 12 | 13 | char[] c2 = "Mr John Smith And Scuba Divers GoGoGo! ".toCharArray(); 14 | assertEquals("Mr%20John%20Smith%20And%20Scuba%20Divers%20GoGoGo!", convert(c2, 38)); 15 | assertEquals("Mr%20John%20Smith%20And%20Scuba%20Divers%20GoGoGo!", convert1(c2, 38)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /leetcode/IncreasingTripletSubsequence.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/increasing-triplet-subsequence/ 4 | // 334. Increasing Triplet Subsequence 5 | 6 | public class IncreasingTripletSubsequence { 7 | public boolean increasingTriplet(int[] nums) { 8 | if (nums.length < 3) 9 | return false; 10 | 11 | int min0 = Integer.MAX_VALUE; 12 | int min1 = Integer.MAX_VALUE; 13 | 14 | for (int num : nums) { 15 | if (min0 >= num) { 16 | min0 = num; 17 | } else if (min1 >= num) 18 | min1 = num; 19 | else 20 | return true; 21 | } 22 | 23 | return false; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /leetcode/ValidPalindromeII.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/valid-palindrome-ii/ 4 | // 680. Valid Palindrome II 5 | 6 | public class ValidPalindromeII { 7 | public boolean validPalindrome(String s) { 8 | return rec(s.toCharArray(), 0, s.length() - 1, 1); 9 | } 10 | 11 | private boolean rec(char[] c, int left, int right, int max) { 12 | if (max < 0) 13 | return false; 14 | 15 | while (left < right) { 16 | if (c[left] != c[right]) 17 | return rec(c, left, right - 1, max - 1) || rec(c, left + 1, right, max - 1); 18 | 19 | right--; 20 | left++; 21 | } 22 | 23 | return true; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /TopCoder/srm660div2/src/PrivateD2party.java: -------------------------------------------------------------------------------- 1 | public class PrivateD2party { 2 | 3 | int[] f; 4 | int[] map; 5 | 6 | public int dfs(int v) { 7 | f[v] = 1; 8 | int x = map[v]; 9 | int currentResult = (x == v || f[x] == 2 ? 1 : 0); 10 | 11 | if (f[x] == 0) 12 | currentResult += dfs(x) + 1; 13 | 14 | f[v] = 2; 15 | 16 | return currentResult; 17 | } 18 | 19 | public int getsz(int[] a){ 20 | map = a; 21 | int n = a.length; 22 | f = new int[n + 1]; 23 | 24 | int result = 0; 25 | for (int i = 0; i < n; i++) 26 | if (f[i] == 0) 27 | result += dfs(i); 28 | 29 | return result; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Hackerrank/Algorithms/Implementation/src/MiniMaxSum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | public class MiniMaxSum { 5 | public static void main(String[] args) { 6 | Scanner in = new Scanner(System.in); 7 | PrintWriter out = new PrintWriter(System.out); 8 | int n = 5; 9 | long sum = 0; 10 | 11 | long max = Integer.MIN_VALUE; 12 | long min = Integer.MAX_VALUE; 13 | 14 | for (int i = 0; i < n; i++) { 15 | long cur = in.nextInt(); 16 | max = Math.max(max, cur); 17 | min = Math.min(min, cur); 18 | sum += cur; 19 | } 20 | 21 | out.print((sum - max) + " " + (sum - min)); 22 | out.close(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /algorithms/linked_lists/Palindrome.java: -------------------------------------------------------------------------------- 1 | package algorithms.linked_lists; 2 | 3 | public class Palindrome { 4 | public static boolean isPalindrome(Node head) { 5 | if (head == null) 6 | return true; // depends on problem description, I assumed nothing is a palindrome 7 | 8 | if (head.next == null) // one node itself is a palindrome linked list 9 | return true; 10 | 11 | Node reversedList = Node.reversedClone(head); 12 | while (reversedList != null) { 13 | if (reversedList.data != head.data) 14 | return false; 15 | reversedList = reversedList.next; 16 | head = head.next; 17 | } 18 | 19 | return true; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /leetcode/LargestNumberAtLeastTwiceOfOthers.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/largest-number-at-least-twice-of-others/description/ 4 | // 747. Largest Number At Least Twice of Others 5 | 6 | public class LargestNumberAtLeastTwiceOfOthers { 7 | public int dominantIndex(int[] nums) { 8 | int max = nums[0], prevMax = -1, indMax = 0; 9 | 10 | for (int i = 1; i < nums.length; i++) { 11 | if (nums[i] > max) { 12 | prevMax = max; 13 | max = nums[i]; 14 | indMax = i; 15 | } else if (nums[i] > prevMax) 16 | prevMax = nums[i]; 17 | } 18 | 19 | return max >= 2 * prevMax ? indMax : -1; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /leetcode/PowXN.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/powx-n/description/ 4 | // 50. Pow(x, n) 5 | 6 | class PowXN { 7 | public double myPow(double x, int n) { 8 | if (n < 0) { 9 | double res = pow(x, -1 * (n + 1)) * x; 10 | res = 1.0 / res; 11 | return res; 12 | } else { 13 | return pow(x, n); 14 | } 15 | } 16 | 17 | private double pow(double x, int n) { 18 | if (n == 0) 19 | return 1.0; 20 | 21 | if (n == 1) 22 | return x; 23 | 24 | if (n % 2 == 1) 25 | return myPow(x, n - 1) * x; 26 | 27 | double cur = myPow(x, n / 2); 28 | 29 | return cur * cur; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /algorithms/linked_lists/KthElementFromTheEnd.java: -------------------------------------------------------------------------------- 1 | package algorithms.linked_lists; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class KthElementFromTheEnd { 7 | static List nodes; 8 | 9 | public static Node getKthLastElement(Node head, int k) { 10 | nodes = new ArrayList<>(); 11 | 12 | numerateNodes(head); 13 | if (nodes.size() < k) // k is too big 14 | return null; 15 | 16 | return nodes.get(k); 17 | } 18 | 19 | public static void numerateNodes(Node node) { 20 | if (node.next == null) { 21 | nodes.add(node); 22 | return; 23 | } 24 | 25 | numerateNodes(node.next); 26 | nodes.add(node); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode/RemoveDuplicatesFromSortedArray.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/remove-duplicates-from-sorted-array 4 | // 26. Remove Duplicates from Sorted Array 5 | 6 | class RemoveDuplicatesFromSortedArray { 7 | public int removeDuplicates(int[] nums) { 8 | int slow = 0; 9 | int fast = 0; 10 | int res = 0; 11 | 12 | while (fast < nums.length) { 13 | res++; 14 | 15 | while (fast < nums.length - 1 && nums[fast] == nums[fast + 1]) 16 | fast++; 17 | 18 | nums[slow] = nums[fast]; 19 | 20 | slow++; 21 | fast++; 22 | } 23 | 24 | return res; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /leetcode/FindTheCelebrity.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/find-the-celebrity/description/ 4 | // 277. Find the Celebrity 5 | 6 | /* The knows API is defined in the parent class Relation. 7 | boolean knows(int a, int b); */ 8 | 9 | public class FindTheCelebrity extends Relation { 10 | public int findCelebrity(int n) { 11 | for (int i = 0; i < n; i++) 12 | if (knows(i, (i + 1) % n) && check((i + 1) % n, n)) 13 | return (i + 1) % n; 14 | 15 | return -1; 16 | } 17 | 18 | public boolean check(int x, int n) { 19 | for (int i = 0; i < n; i++) 20 | if (i != x && knows(x, i)) 21 | return false; 22 | 23 | return true; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /leetcode/PlusOne.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/plus-one/description/ 4 | // 66. Plus One 5 | 6 | class PlusOne { 7 | public int[] plusOne(int[] digits) { 8 | int n = digits.length; 9 | int i = n - 1; 10 | int carry = 1; 11 | while (i >= 0) { 12 | int cur = digits[i] + carry; 13 | digits[i] = cur % 10; 14 | carry = cur / 10; 15 | i--; 16 | } 17 | 18 | if (carry == 0) 19 | return digits; 20 | 21 | int[] res = new int[n + 1]; 22 | 23 | res[0] = 1; 24 | for (i = 1; i < n + 1; i++) 25 | res[i] = digits[i - 1]; 26 | 27 | return res; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /leetcode/SumOfSquareNumbers.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/sum-of-square-numbers/description/ 4 | // 633. Sum of Square Numbers 5 | 6 | import java.util.*; 7 | 8 | class SumOfSquareNumbers { 9 | public boolean judgeSquareSum(int c) { 10 | if (c < 3) 11 | return true; 12 | List list = new ArrayList(); 13 | Set set = new HashSet(); 14 | 15 | int i = 1; 16 | set.add(c); 17 | while (c / i >= i) { 18 | list.add(i * i); 19 | set.add(c - i * i); 20 | if (set.contains(i * i)) 21 | return true; 22 | 23 | i++; 24 | } 25 | 26 | return false; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode/Flatten2DVector.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/flatten-2d-vector/description/ 4 | // 251. Flatten 2D Vector 5 | 6 | import java.util.*; 7 | 8 | public class Flatten2DVector implements Iterator { 9 | 10 | List list; 11 | int index; 12 | 13 | public Flatten2DVector(List> vec2d) { 14 | list = new ArrayList(); 15 | 16 | for (List cur : vec2d) 17 | for(int x : cur) 18 | list.add(x); 19 | 20 | index = 0; 21 | } 22 | 23 | @Override 24 | public Integer next() { 25 | return list.get(index++); 26 | } 27 | 28 | @Override 29 | public boolean hasNext() { 30 | return index < list.size(); 31 | } 32 | } -------------------------------------------------------------------------------- /leetcode/SameTree.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // Given two binary trees, write a function to check if they are the same or not. 4 | // Two binary trees are considered the same if they are structurally identical and the nodes have the same value. 5 | 6 | public class SameTree { 7 | public boolean isSameTree(TreeNode p, TreeNode q) { 8 | if (p == null && q == null) 9 | return true; 10 | 11 | if (p == null || q == null) 12 | return false; 13 | 14 | return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 15 | } 16 | 17 | public class TreeNode { 18 | int val; 19 | TreeNode left; 20 | TreeNode right; 21 | 22 | TreeNode(int x) { val = x; } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /algorithms/combinatorics/Permutation.java: -------------------------------------------------------------------------------- 1 | package algorithms.combinatorics; 2 | 3 | import java.util.*; 4 | 5 | public class Permutation { 6 | public static List nextPermutation(List perm) { 7 | int k = perm.size() - 2; 8 | while (k >= 0 && perm.get(k) >= perm.get(k + 1)) 9 | k--; 10 | 11 | if (k == -1) // all sorted decreasingly, last permutation 12 | return Collections.emptyList(); 13 | 14 | for (int i = perm.size() - 1; i > k; i--) 15 | if (perm.get(i) > perm.get(k)) { 16 | Collections.swap(perm, k, i); 17 | break; 18 | } 19 | 20 | Collections.reverse(perm.subList(k + 1, perm.size())); 21 | 22 | return perm; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /algorithms/linked_lists/RemoveMiddleInLinkedList.java: -------------------------------------------------------------------------------- 1 | package algorithms.linked_lists; 2 | 3 | public class RemoveMiddleInLinkedList { 4 | public static Node removeMiddle(Node head) { 5 | if (head == null || head.next == null) 6 | return null; 7 | 8 | int size = Node.getLength(head); 9 | 10 | if (size == 2) 11 | return head; 12 | 13 | Node prev = head; 14 | Node cur = prev.next; 15 | Node next = cur.next; 16 | int i = 2; 17 | 18 | while (i < (size + 1) / 2) { 19 | prev = cur; 20 | cur = next; 21 | next = cur.next; 22 | i++; 23 | } 24 | 25 | prev.next = next; // cur is deleted 26 | 27 | return head; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /leetcode/SingleNumber.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/single-number 4 | // 136. Single Number 5 | 6 | import java.io.PrintWriter; 7 | 8 | public class SingleNumber { 9 | 10 | public int singleNumber(int[] nums) { 11 | int res = nums[0]; 12 | for (int i = 1; i < nums.length; i++) 13 | res = res ^ nums[i]; 14 | 15 | return res; 16 | } 17 | 18 | 19 | public void solve() { 20 | PrintWriter out = new PrintWriter(System.out); 21 | int[] nums = {1, 3, 3, 2, 5, 2, 1}; 22 | int res = singleNumber(nums); 23 | out.print(res); 24 | out.close(); 25 | } 26 | 27 | public static void main(String[] args) { 28 | new SingleNumber().solve(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /leetcode/FindSmallestLetterGreaterThanTarget.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/find-smallest-letter-greater-than-target/description/ 4 | // 744. Find Smallest Letter Greater Than Target 5 | 6 | public class FindSmallestLetterGreaterThanTarget { 7 | public char nextGreatestLetter(char[] letters, char target) { 8 | int l = 0, r = letters.length - 1, res = letters.length - 1; 9 | 10 | while (l < r) { 11 | int m = l + (r - l) / 2; 12 | if (letters[m] <= target) 13 | l = m + 1; 14 | else { 15 | r = m; 16 | res = Math.min(res, m); 17 | } 18 | } 19 | 20 | return letters[res] <= target ? letters[0] : letters[res]; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /leetcode/GenerateParentheses.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/generate-parentheses/description/ 4 | // 22. Generate Parentheses 5 | 6 | import java.util.*; 7 | 8 | public class GenerateParentheses { 9 | public List generateParenthesis(int n) { 10 | List res = new ArrayList<>(); 11 | rec("", 0, 0, n, res); 12 | return res; 13 | } 14 | 15 | private void rec(String cur, int left, int right, int n, List res) { 16 | if (right > left || right > n || left > n) 17 | return; 18 | 19 | if (left == n && right == n) 20 | res.add(cur); 21 | 22 | rec(cur + "(", left + 1, right, n, res); 23 | rec(cur + ")", left, right + 1, n, res); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /leetcode/GlobalAndLocalInversions.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/global-and-local-inversions/description/ 4 | // 775. Global and Local Inversions 5 | 6 | public class GlobalAndLocalInversions { 7 | public boolean isIdealPermutation(int[] A) { 8 | // to have ideal permutation local and global inversions must be equal 9 | // every local inversion is also a global inversion 10 | // so if at some point we'll have a global inversion that is not a local one 11 | // then we return false 12 | 13 | for (int i = 0; i < A.length; i++) 14 | if (Math.abs(A[i] - i) > 1) // there is a global inversion more than local inversion 15 | return false; 16 | 17 | return true; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /leetcode/LicenseKeyFormatting.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/license-key-formatting/description/ 4 | // 482. License Key Formatting 5 | 6 | public class LicenseKeyFormatting { 7 | public String licenseKeyFormatting(String S, int K) { 8 | StringBuilder st = new StringBuilder(""); 9 | 10 | for (char c : S.toCharArray()) { 11 | if (c == '-') 12 | continue; 13 | 14 | if (c >= 'a' && c <= 'z') 15 | c = Character.toUpperCase(c); 16 | 17 | st.append(c); 18 | } 19 | 20 | int i = st.length() - K; 21 | while (i > 0) { 22 | st.insert(i, '-'); 23 | i -= K; 24 | } 25 | 26 | return st.toString(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode/MergeTwoBinaryTrees.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/merge-two-binary-trees/description/ 4 | // 617. Merge Two Binary Trees 5 | 6 | class MergeTwoBinaryTrees { 7 | class TreeNode { 8 | int val; 9 | TreeNode left; 10 | TreeNode right; 11 | TreeNode(int x) { val = x; } 12 | } 13 | 14 | public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { 15 | if (t1 == null) 16 | return t2; 17 | 18 | if (t2 == null) 19 | return t1; 20 | 21 | TreeNode root = new TreeNode(t1.val + t2.val); 22 | root.left = mergeTrees(t1.left, t2.left); 23 | root.right = mergeTrees(t1.right, t2.right); 24 | 25 | return root; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /leetcode/MergeTwoSortedLists.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/merge-two-sorted-lists/description/ 4 | // 21. Merge Two Sorted Lists 5 | 6 | class MergeTwoSortedLists { 7 | class ListNode { 8 | int val; 9 | ListNode next; 10 | ListNode(int x) { val = x; } 11 | } 12 | 13 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 14 | if (l1 == null) 15 | return l2; 16 | 17 | if (l2 == null) 18 | return l1; 19 | 20 | if (l1.val < l2.val) { 21 | l1.next = mergeTwoLists(l1.next, l2); 22 | return l1; 23 | } else { 24 | l2.next = mergeTwoLists(l1, l2.next); 25 | return l2; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode/DiameterOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/diameter-of-binary-tree/description/ 4 | // 543. Diameter of Binary Tree 5 | 6 | class DiameterOfBinaryTree { 7 | int max = 0; 8 | public int diameterOfBinaryTree(TreeNode root) { 9 | rec(root); 10 | return max; 11 | } 12 | 13 | public int rec(TreeNode x) { 14 | if (x == null) 15 | return 0; 16 | 17 | int left = rec(x.left); 18 | int right = rec(x.right); 19 | max = Math.max(max, left + right); 20 | 21 | return Math.max(left, right) + 1; 22 | } 23 | 24 | class TreeNode { 25 | int val; 26 | TreeNode left; 27 | TreeNode right; 28 | TreeNode(int x) { val = x; } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /leetcode/FirstBadVersion.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/first-bad-version 4 | // 278. First Bad Version 5 | 6 | /* The isBadVersion API is defined in the parent class VersionControl. 7 | boolean isBadVersion(int version); */ 8 | 9 | // dumb class implementation just for the sake of having 10 | 11 | public class FirstBadVersion extends VersionControl { 12 | public int firstBadVersion(int n) { 13 | int l = 1; 14 | int r = n; 15 | while (l < r) { 16 | int m = l + (r-l)/2; 17 | 18 | if (this.isBadVersion(m)) { 19 | r = m; 20 | } else { 21 | l = m + 1; 22 | } 23 | } 24 | 25 | return l; 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode/SymmetricTree.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/symmetric-tree/description/ 4 | // 101. Symmetric Tree 5 | 6 | 7 | class SymmetricTree { 8 | public class TreeNode { 9 | int val; 10 | TreeNode left; 11 | TreeNode right; 12 | TreeNode(int x) { val = x; } 13 | } 14 | 15 | public boolean isSymmetric(TreeNode root) { 16 | return root == null || rec(root.left, root.right); 17 | } 18 | 19 | public boolean rec(TreeNode left, TreeNode right) { 20 | if (left == null && right == null) 21 | return true; 22 | 23 | return left != null && right != null && left.val == right.val && 24 | rec(left.left, right.right) && rec(left.right, right.left); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /leetcode/MaximumAverageSubarrayI.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/maximum-average-subarray-i/description/ 4 | // 643. Maximum Average Subarray I 5 | 6 | public class MaximumAverageSubarrayI { 7 | public double findMaxAverage(int[] nums, int k) { 8 | if (nums.length == 1) 9 | return nums[0]; 10 | 11 | int sum = 0; 12 | double max = -999999999; 13 | 14 | for (int i = 0; i < nums.length; i++) { 15 | sum += nums[i]; 16 | if (i < k - 1) 17 | continue; 18 | 19 | if (i - k >= 0) 20 | sum -= nums[i - k]; 21 | 22 | double cur = sum * 1.0 / k; 23 | max = Math.max(max, cur); 24 | } 25 | 26 | return max; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /ProjectEuler/src/java/001 Euler/src/Solution.java: -------------------------------------------------------------------------------- 1 | import java.io.PrintWriter; 2 | import java.util.*; 3 | 4 | 5 | public class Solution { 6 | 7 | public static long getSum(long n, int period) { 8 | while (n % period != 0) 9 | n--; 10 | long num = n / period; 11 | return (period + n) * num / 2; 12 | } 13 | 14 | public static void main(String[] args) { 15 | Scanner in = new Scanner(System.in); 16 | PrintWriter out = new PrintWriter(System.out); 17 | 18 | int t = in.nextInt(); 19 | while (t > 0) { 20 | long n = in.nextInt() - 1; 21 | long total = getSum(n, 3) + getSum(n, 5) - getSum(n, 15); 22 | out.println(total); 23 | t--; 24 | } 25 | 26 | out.close(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode/LowestCommonAncestorOfBinarySearchTree.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree 4 | // 235. Lowest Common Ancestor of a Binary Search Tree 5 | 6 | class LowestCommonAncestorOfBinarySearchTree { 7 | class TreeNode { 8 | int val; 9 | TreeNode left; 10 | TreeNode right; 11 | TreeNode(int x) { val = x; } 12 | } 13 | 14 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 15 | if (root.val < p.val && root.val < q.val) 16 | return lowestCommonAncestor(root.right, p, q); 17 | else if (root.val > p.val && root.val > q.val) 18 | return lowestCommonAncestor(root.left, p, q); 19 | 20 | return root; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /leetcode/LongestAbsoluteFilePath.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/longest-absolute-file-path 4 | // 388. Longest Absolute File Path 5 | 6 | class LongestAbsoluteFilePath { 7 | public int lengthLongestPath(String input) { 8 | int max = 0; 9 | 10 | String[] lines = input.split("\n"); 11 | int[] stack = new int[lines.length + 1]; // stack[i] - length of i-th line 12 | for (String line : lines) { 13 | int level = line.lastIndexOf("\t") + 1; // how many times "tabbed" 14 | int cur = stack[level] + line.length() - level + 1; 15 | 16 | stack[level + 1] = cur; 17 | 18 | if (line.contains(".")) 19 | max = Math.max(max, cur - 1); 20 | } 21 | 22 | return max; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /algorithms/dynamic_programming/test/MaximumSubarrayTest.java: -------------------------------------------------------------------------------- 1 | import algorithms.dynamic_programming.MaximumSubarray; 2 | import org.junit.Test; 3 | 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | import static org.junit.Assert.assertEquals; 8 | 9 | 10 | public class MaximumSubarrayTest { 11 | @Test 12 | public void firstTest() { 13 | List list = Arrays.asList(5, 10, -3, 6, -20, 15, -10, 6, 5, 3); 14 | int result = MaximumSubarray.getMaxSubArray(list); 15 | assertEquals(19, result); 16 | } 17 | 18 | @Test 19 | public void secondTest() { 20 | List list = Arrays.asList(904, 40, 523, 12, -335, -385, -124, 481, -31); 21 | int result = MaximumSubarray.getMaxSubArray(list); 22 | assertEquals(1479, result); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /leetcode/IntersectionOfTwoArrays.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/intersection-of-two-arrays/description/ 4 | // 349. Intersection of Two Arrays 5 | 6 | import java.util.*; 7 | 8 | public class IntersectionOfTwoArrays { 9 | public int[] intersection(int[] nums1, int[] nums2) { 10 | List res = new ArrayList<>(); 11 | Set set = new HashSet<>(); 12 | for (int x : nums1) 13 | set.add(x); 14 | 15 | for (int x : nums2) 16 | if (set.contains(x)) { 17 | res.add(x); 18 | set.remove(x); 19 | } 20 | 21 | int[] arr = new int[res.size()]; 22 | for (int i = 0; i < res.size(); i++) 23 | arr[i] = res.get(i); 24 | 25 | return arr; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /leetcode/LongestPalindrome.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/longest-palindrome/description/ 4 | // 409. Longest Palindrome 5 | 6 | public class LongestPalindrome { 7 | public int longestPalindrome(String s) { 8 | int res = 0; 9 | 10 | int[] ch = new int[128]; 11 | for (char c : s.toCharArray()) 12 | ch[c]++; 13 | 14 | int odds = 0; 15 | for (int i = 0; i < 128; i++) { 16 | if (ch[i] % 2 == 0) 17 | res += ch[i]; 18 | else { 19 | if (ch[i] > 0) { 20 | odds++; 21 | res += ch[i] - 1; 22 | } 23 | } 24 | } 25 | 26 | if (odds > 0) 27 | res++; 28 | 29 | return res; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /leetcode/ShortestUnsortedContinuousSubarray.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/shortest-unsorted-continuous-subarray/description/ 4 | // 581. Shortest Unsorted Continuous Subarray 5 | 6 | import java.util.Arrays; 7 | 8 | public class ShortestUnsortedContinuousSubarray { 9 | public int findUnsortedSubarray(int[] nums) { 10 | if (nums.length < 2) 11 | return 0; 12 | 13 | int[] init = nums.clone(); 14 | Arrays.sort(nums); 15 | 16 | int i = 0, j = nums.length - 1, n = nums.length; 17 | 18 | while (i < n && init[i] == nums[i]) 19 | i++; 20 | 21 | while (j >= 0 && init[j] == nums[j]) 22 | j--; 23 | 24 | if (i > j) 25 | return 0; 26 | 27 | return j - i + 1; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /codeforces/round320_div2/ProblemA.java: -------------------------------------------------------------------------------- 1 | package codeforces.round320_div2; 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | 6 | public class ProblemA { 7 | 8 | public void solve() { 9 | Scanner in = new Scanner(System.in); 10 | PrintWriter out = new PrintWriter(System.out); 11 | int x = in.nextInt(); 12 | int res = 0; 13 | while (x > 0) { 14 | int cur = 1; 15 | while (cur <= x) 16 | cur = cur * 2; 17 | 18 | if (cur > x) 19 | cur /= 2; 20 | 21 | x -= cur; 22 | res++; 23 | } 24 | 25 | out.print(res); 26 | out.close(); 27 | } 28 | 29 | public static void main(String[] args) { 30 | new codeforces.round305_div2.ProblemA().solve(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /leetcode/CountAndSay.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/count-and-say 4 | // 38. Count and Say 5 | 6 | class CountAndSay { 7 | public String countAndSay(int n) { 8 | if (n == 1) 9 | return "1"; 10 | 11 | char[] prev = countAndSay(n - 1).toCharArray(); 12 | StringBuilder res = new StringBuilder(""); 13 | 14 | char c = prev[0]; 15 | int count = 1; 16 | 17 | for (int i = 1; i < prev.length; i++) { 18 | if (prev[i] == c) 19 | count++; 20 | else { 21 | res.append(count).append(c); 22 | count = 1; 23 | c = prev[i]; 24 | } 25 | } 26 | 27 | res.append(count).append(c); 28 | return res.toString(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Hackerrank/Algorithms/Implementation/src/DesignerPDFViewer.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class DesignerPDFViewer { 5 | public static void main(String[] args) { 6 | new DesignerPDFViewer().solve(); 7 | } 8 | 9 | public void solve() { 10 | Scanner in = new Scanner(System.in); 11 | PrintWriter out = new PrintWriter(System.out); 12 | 13 | HashMap map = new HashMap<>(); 14 | for (int i = 0; i < 26; i++) 15 | map.put((char)('a' + i), in.nextInt()); 16 | 17 | String s = in.next(); 18 | int max = 0; 19 | for (int i = 0; i < s.length(); i++) 20 | max = Math.max(max, map.get(s.charAt(i))); 21 | 22 | out.print(max * s.length()); 23 | 24 | out.close(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /leetcode/UglyNumberII.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/ugly-number-ii 4 | // 264. Ugly Number II 5 | 6 | public class UglyNumberII { 7 | public int nthUglyNumber(int n) { 8 | int[] k = new int[n]; 9 | k[0] = 1; 10 | int t2 = 0; 11 | int t3 = 0; 12 | int t5 = 0; 13 | 14 | for (int i = 1; i < n; i++) { 15 | k[i] = Math.min(Math.min(k[t2]*2, k[t3]*3), k[t5]*5); 16 | 17 | if (k[i] == k[t2] * 2) t2++; 18 | if (k[i] == k[t3] * 3) t3++; 19 | if (k[i] == k[t5] * 5) t5++; 20 | } 21 | 22 | return k[n - 1]; 23 | } 24 | 25 | public static void main(String[] args) { 26 | UglyNumberII s = new UglyNumberII(); 27 | System.out.println(s.nthUglyNumber(1352)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /leetcode/FindAllNumbersDisappearedInAnArray.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/description/ 4 | // 448. Find All Numbers Disappeared in an Array 5 | 6 | import java.util.*; 7 | 8 | class FindAllNumbersDisappearedInAnArray { 9 | public List findDisappearedNumbers(int[] nums) { 10 | List list = new ArrayList(); 11 | 12 | for (int i = 0; i < nums.length; i++) 13 | list.add(i + 1); 14 | 15 | for (int x : nums) 16 | list.set(x - 1, 0); 17 | 18 | int i = list.size() - 1; 19 | while (i >= 0) { 20 | if (list.get(i) == 0) 21 | list.remove(i); 22 | i--; 23 | } 24 | 25 | return list; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /leetcode/TwoSumII.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/ 4 | // 167. Two Sum II - Input array is sorted 5 | 6 | public class TwoSumII { 7 | public int[] twoSum(int[] numbers, int target) { 8 | int left = 0, right = numbers.length - 1; 9 | int[] res = new int[2]; 10 | 11 | while (left < right) { 12 | int sum = numbers[left] + numbers[right]; 13 | 14 | if (sum == target) { 15 | res[0] = left + 1; 16 | res[1] = right + 1; 17 | break; 18 | } else if (sum > target) { 19 | right--; 20 | } else { 21 | left++; 22 | } 23 | } 24 | 25 | return res; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /TopCoder/srm642div2/test/ForgetfulAdditionTest.java: -------------------------------------------------------------------------------- 1 | import org.junit.jupiter.api.Test; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | public class ForgetfulAdditionTest { 6 | @Test 7 | void test0() { 8 | assertEquals(4, new ForgetfulAddition().minNumber("22")); 9 | } 10 | 11 | @Test 12 | void test1() { 13 | assertEquals(15, new ForgetfulAddition().minNumber("123")); 14 | } 15 | 16 | @Test 17 | void test2() { 18 | assertEquals(101, new ForgetfulAddition().minNumber("1289")); 19 | } 20 | 21 | @Test 22 | void test3() { 23 | assertEquals(9067, new ForgetfulAddition().minNumber("31415926")); 24 | } 25 | 26 | @Test 27 | void test4() { 28 | assertEquals(863, new ForgetfulAddition().minNumber("98765")); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /leetcode/MinimumPathSum.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/minimum-path-sum/description/ 4 | // 64. Minimum Path Sum 5 | 6 | public class MinimumPathSum { 7 | public int minPathSum(int[][] grid) { 8 | if (grid.length == 0) 9 | return 0; 10 | 11 | int n = grid.length, m = grid[0].length; 12 | int[][] d = new int[n][m]; 13 | d[0][0] = grid[0][0]; 14 | for (int i = 1; i < n; i++) 15 | d[i][0] = d[i - 1][0] + grid[i][0]; 16 | 17 | for (int j = 1; j < m; j++) 18 | d[0][j] = d[0][j - 1] + grid[0][j]; 19 | 20 | for (int i = 1; i < n; i++) 21 | for (int j = 1; j < m; j++) 22 | d[i][j] = Math.min(d[i - 1][j], d[i][j - 1]) + grid[i][j]; 23 | 24 | return d[n - 1][m - 1]; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /leetcode/PascalsTriangle.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/pascals-triangle/ 4 | // 118. Pascal's Triangle 5 | 6 | import java.util.*; 7 | 8 | public class PascalsTriangle { 9 | public List> generate(int numRows) { 10 | List> res = new ArrayList(); 11 | 12 | for (int i = 0; i < numRows; i++) { 13 | List cur = new ArrayList(); 14 | 15 | cur.add(1); 16 | 17 | if (i > 0) { 18 | List prev = res.get(i - 1); 19 | 20 | for (int j = 0; j < prev.size() - 1; j++) 21 | cur.add(prev.get(j) + prev.get(j + 1)); 22 | 23 | cur.add(1); 24 | } 25 | 26 | res.add(cur); 27 | } 28 | 29 | return res; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /leetcode/MaximumSubarray.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/maximum-subarray/description/ 4 | // 53. Maximum Subarray 5 | 6 | public class MaximumSubarray { 7 | public int maxSubArray(int[] a) { 8 | int n = a.length; 9 | int max = Integer.MIN_VALUE, cur = 0, maxNum = Integer.MIN_VALUE; 10 | boolean neg = true; 11 | for (int i = 0; i < n; i++) { 12 | if (a[i] >= 0) 13 | neg = false; 14 | 15 | maxNum = Math.max(maxNum, a[i]); 16 | 17 | cur += a[i]; 18 | if (cur < 0) 19 | cur = 0; 20 | 21 | max = Math.max(max, cur); 22 | } 23 | 24 | if (neg) 25 | return maxNum; 26 | 27 | return max; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Hackerrank/Algorithms/Sorting/src/ClosestNumbers.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | public class ClosestNumbers { 5 | public static void main(String[] args) { 6 | Scanner in = new Scanner(System.in); 7 | PrintWriter out = new PrintWriter(System.out); 8 | int n = in.nextInt(); 9 | int[] arr = new int[n]; 10 | 11 | for (int i = 0; i < n; i++) 12 | arr[i] = in.nextInt(); 13 | 14 | Arrays.sort(arr); 15 | int minDiff = Integer.MAX_VALUE; 16 | 17 | for (int i = 1; i < n; i++) 18 | minDiff = Math.min(minDiff, arr[i] - arr[i - 1]); 19 | 20 | for (int i = 1; i < n; i++) 21 | if (arr[i] - arr[i - 1] == minDiff) 22 | out.print(arr[i - 1] + " " + arr[i] + " "); 23 | 24 | out.close(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /TopCoder/srm651div2/src/FoxAndSouvenirTheNext.java: -------------------------------------------------------------------------------- 1 | public class FoxAndSouvenirTheNext { 2 | 3 | public String ableToSplit(int[] value) { 4 | int total = 0; 5 | int n = value.length; 6 | 7 | for (int i = 0; i < n; i++) total += value[i]; 8 | 9 | if (total % 2 == 1 || n % 2 == 1) 10 | return "Impossible"; 11 | 12 | byte dp[][] = new byte[50 * 50][50]; 13 | dp[0][0] = 1; 14 | 15 | for (int i = 0; i < value.length; i++) { 16 | for (int j = 0; j <= 50 * 50 / 2; j++) { 17 | for (int k = 0; k < n / 2; k++) { 18 | if (dp[j][k] == 1) 19 | dp[j + value[i]][k + 1] = 1; 20 | } 21 | } 22 | } 23 | 24 | return dp[total / 2][n / 2] == 1 ? "Possible" : "Impossible"; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /algorithms/dynamic_programming/Fibo.java: -------------------------------------------------------------------------------- 1 | package algorithms.dynamic_programming; 2 | 3 | public class Fibo { 4 | public static int fib (int n) { 5 | if (n == 1) 6 | return 0; 7 | 8 | if (n < 4) 9 | return 1; 10 | 11 | int a = 0, b = 1, c = 1; 12 | 13 | for (int i = 3; i <= n; i++) { 14 | c = a + b; 15 | a = b; 16 | b = c; 17 | } 18 | 19 | return c; 20 | } 21 | 22 | public static void main(String[] args) { 23 | final long startTime = System.currentTimeMillis(); 24 | for (int i = 1; i < 48; i++) 25 | System.out.println(i + ": " + fib(i)); 26 | 27 | final long endTime = System.currentTimeMillis(); 28 | System.out.println("Total execution time: " + (endTime - startTime) ); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /leetcode/FindAllNumbersDisappearedInAnArrayII.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/description/ 4 | // 448. Find All Numbers Disappeared in an Array 5 | 6 | import java.util.*; 7 | 8 | class FindAllNumbersDisappearedInAnArrayII { 9 | public List findDisappearedNumbers(int[] nums) { 10 | List list = new ArrayList(); 11 | 12 | for (int i = 0; i < nums.length; i++) { 13 | int index = Math.abs(nums[i]) - 1; 14 | 15 | if (nums[index] > 0) 16 | nums[index] = -nums[index]; 17 | } 18 | 19 | 20 | for (int i = 0; i < nums.length; i++) 21 | if (nums[i] > 0) 22 | list.add(i + 1); 23 | 24 | return list; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /leetcode/LongestContinuousIncreasingSubsequence.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/longest-continuous-increasing-subsequence/description/ 4 | // 674. Longest Continuous Increasing Subsequence 5 | 6 | class LongestContinuousIncreasingSubsequence { 7 | public int findLengthOfLCIS(int[] nums) { 8 | if (nums.length == 0) 9 | return 0; 10 | 11 | int max = 1; 12 | int cur = 1; 13 | int x = nums[0]; 14 | 15 | for (int i = 1; i < nums.length; i++) { 16 | if (x < nums[i]) 17 | cur++; 18 | else 19 | cur = 1; 20 | 21 | x = nums[i]; 22 | 23 | if (max < cur) 24 | max = cur; 25 | } 26 | 27 | return max; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /leetcode/ReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/reverse-linked-list 4 | // 206. Reverse Linked List 5 | 6 | public class ReverseLinkedList { 7 | public class ListNode { 8 | int val; 9 | ListNode next; 10 | ListNode(int x) { val = x; } 11 | } 12 | 13 | public ListNode reverseList(ListNode head) { 14 | if (head == null) 15 | return null; 16 | if (head.next == null) 17 | return head; 18 | 19 | ListNode cur = head.next; 20 | ListNode prev = head; 21 | prev.next = null; // new tail 22 | 23 | while (cur != null) { 24 | ListNode next = cur.next; 25 | cur.next = prev; 26 | prev = cur; 27 | cur = next; 28 | } 29 | 30 | return prev; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /leetcode/LinkedListCycle.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/linked-list-cycle/description/ 4 | // 141. Linked List Cycle 5 | 6 | public class LinkedListCycle { 7 | class ListNode { 8 | int val; 9 | ListNode next; 10 | ListNode(int x) { 11 | val = x; 12 | next = null; 13 | } 14 | } 15 | 16 | public boolean hasCycle(ListNode head) { 17 | if (head == null || head.next == null) 18 | return false; 19 | 20 | ListNode slow = head; 21 | ListNode fast = head; 22 | 23 | while (fast != null && fast.next != null) { 24 | slow = slow.next; 25 | fast = fast.next.next; 26 | 27 | if (slow == fast) 28 | return true; 29 | } 30 | 31 | return false; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /leetcode/SparseMatrixMultiplication.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/sparse-matrix-multiplication/description/ 4 | // 311. Sparse Matrix Multiplication 5 | 6 | class SparseMatrixMultiplication { 7 | public int[][] multiply(int[][] A, int[][] B) { 8 | int n = A.length; 9 | int m = A[0].length; 10 | int k = B[0].length; 11 | 12 | int[][] C = new int[n][k]; 13 | for (int l = 0; l < m; l++) { 14 | for (int i = 0; i < n; i++) { 15 | if (A[i][l] != 0) { 16 | for (int j = 0; j < k; j++) { 17 | if (B[l][j] != 0) 18 | C[i][j] += A[i][l] * B[l][j]; 19 | } 20 | } 21 | } 22 | } 23 | 24 | return C; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /TopCoder/srm653div2/src/CountryGroup.java: -------------------------------------------------------------------------------- 1 | public class CountryGroup { 2 | 3 | public int solve(int[] a) { 4 | int i = 0; 5 | int total = 0; 6 | boolean inconsistent = false; 7 | while (i < a.length && !inconsistent) { 8 | int cur = a[i]; 9 | for (int j = i; j < i + cur; j++) { 10 | if (j >= a.length || a[j] != cur) { 11 | inconsistent = true; 12 | break; 13 | } 14 | } 15 | total++; 16 | i += cur; 17 | } 18 | return inconsistent ? -1 : total; 19 | } 20 | 21 | public static void main(String[] args) { 22 | int[] a = new int[] {4,4,4,4,1,1,2,2,3,3,3}; 23 | int res = new CountryGroup().solve(a); 24 | System.out.println("Result=" + res); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /algorithms/bit_manipulation/Insertion.java: -------------------------------------------------------------------------------- 1 | package algorithms.bit_manipulation; 2 | 3 | import java.io.PrintWriter; 4 | import java.util.Scanner; 5 | 6 | public class Insertion { 7 | public static void main(String[] args) { 8 | new Insertion().solve(); 9 | } 10 | 11 | public void solve() { 12 | Scanner in = new Scanner(System.in); 13 | PrintWriter out = new PrintWriter(System.out); 14 | int n = in.nextInt(); 15 | int m = in.nextInt(); 16 | 17 | int i = in.nextInt(); 18 | int j = in.nextInt(); 19 | 20 | for (int k = i; k <= j; k++) { 21 | boolean curBitIsOne = BitOperations.getBit(m, k - i); 22 | n = curBitIsOne ? BitOperations.setBit(n, k) : BitOperations.clearBit(n, k); 23 | } 24 | 25 | out.print(n); 26 | out.close(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /ProjectEuler/src/python/034 Digit factorials.py: -------------------------------------------------------------------------------- 1 | def is_prime(x): 2 | if x < 2: 3 | return False 4 | 5 | j = 2 6 | while j*j <= x: 7 | if x % j == 0: 8 | return False 9 | j += 1 10 | return True 11 | 12 | 13 | def is_circular(x): 14 | arr = list(str(x)) 15 | 16 | if len(arr) == 1: # numbers under 10 17 | return is_prime(x) 18 | 19 | if not is_prime(x): 20 | return False 21 | 22 | result = True 23 | for k in range(1, len(arr)): 24 | arr.append(arr[0]) 25 | arr.pop(0) 26 | num = int(''.join(arr)) 27 | if not is_prime(num): 28 | result = False 29 | break 30 | 31 | return result 32 | 33 | 34 | count = 0 35 | n = 1000000 36 | for i in range(2, n): 37 | if is_circular(i): 38 | count += 1 39 | 40 | print(count) 41 | -------------------------------------------------------------------------------- /leetcode/PascalsTriangleII.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/pascals-triangle-ii/description/ 4 | // 119. Pascal's Triangle II 5 | 6 | import java.util.*; 7 | 8 | class PascalsTriangleII { 9 | public List getRow(int rowIndex) { 10 | int[][] nums = new int[2][rowIndex + 1]; 11 | nums[0][0] = 1; 12 | nums[1][0] = 1; 13 | int k = 0; 14 | 15 | for (int i = 1; i <= rowIndex; i++) { 16 | for (int j = 1; j < i; j++) 17 | nums[1 - k][j] = nums[k][j] + nums[k][j - 1]; 18 | 19 | nums[1 - k][i] = 1; 20 | k = 1 - k; 21 | } 22 | 23 | List list = new ArrayList(); 24 | for (int x : nums[k]) 25 | list.add(x); 26 | 27 | return list; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /TopCoder/srm467div2/test/ShorterSuperSumTest.java: -------------------------------------------------------------------------------- 1 | import org.junit.jupiter.api.Test; 2 | import static org.junit.jupiter.api.Assertions.assertEquals; 3 | 4 | class ShorterSuperSumTest { 5 | @Test 6 | void test0() { 7 | int k = 1; 8 | int n = 3; 9 | assertEquals(6, new ShorterSuperSum().calculate(k, n)); 10 | } 11 | 12 | @Test 13 | void test1() { 14 | int k = 2; 15 | int n = 3; 16 | assertEquals(10, new ShorterSuperSum().calculate(k, n)); 17 | } 18 | 19 | @Test 20 | void test2() { 21 | int k = 4; 22 | int n = 10; 23 | assertEquals(2002, new ShorterSuperSum().calculate(k, n)); 24 | } 25 | 26 | @Test 27 | void test3() { 28 | int k = 10; 29 | int n = 10; 30 | assertEquals(167960, new ShorterSuperSum().calculate(k, n)); 31 | } 32 | 33 | } -------------------------------------------------------------------------------- /leetcode/FirstUniqueCharacterInAString.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/first-unique-character-in-a-string/description/ 4 | // 387. First Unique Character in a String 5 | 6 | import java.util.*; 7 | 8 | class FirstUniqueCharacterInAString { 9 | public int firstUniqChar(String s) { 10 | char[] c = s.toCharArray(); 11 | 12 | Map map = new HashMap(); 13 | 14 | for (int i = 0; i < c.length; i++) { 15 | int cur = map.containsKey(c[i]) ? map.get(c[i]) : 0; 16 | map.put(c[i], cur + 1); 17 | } 18 | 19 | int res = -1; 20 | for (int i = 0; i < c.length; i++) 21 | if (map.get(c[i]) == 1) { 22 | res = i; 23 | break; 24 | } 25 | 26 | return res; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode/FlipGame.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/flip-game/description/ 4 | // 293. Flip Game 5 | 6 | import java.util.*; 7 | 8 | public class FlipGame { 9 | public List generatePossibleNextMoves(String s) { 10 | if (s.length() < 2) 11 | return new ArrayList(); 12 | 13 | List res = new ArrayList(); 14 | StringBuilder sb = new StringBuilder(s); 15 | 16 | for (int i = 0; i < s.length() - 1; i++) { 17 | if (s.charAt(i) == '+' && s.charAt(i + 1) == '+') { 18 | sb.setCharAt(i, '-'); 19 | sb.setCharAt(i + 1, '-'); 20 | 21 | res.add(sb.toString()); 22 | 23 | sb.setCharAt(i, '+'); 24 | sb.setCharAt(i + 1, '+'); 25 | } 26 | } 27 | 28 | return res; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Hackerrank/Algorithms/Sorting/src/FindTheMedian.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | public class FindTheMedian { 5 | public static void main(String[] args) { 6 | Scanner in = new Scanner(System.in); 7 | PrintWriter out = new PrintWriter(System.out); 8 | int n = in.nextInt(); 9 | int[] arr = new int[n]; 10 | int[] count = new int[20001]; 11 | 12 | for (int i = 0; i < n; i++) { 13 | arr[i] = in.nextInt(); 14 | count[arr[i] + 10001]++; 15 | } 16 | 17 | int c = 0; 18 | for (int i = 0; i <= 20000; i++) { 19 | if (count[i] > 0) 20 | c += count[i]; 21 | if (c > (n - 1) / 2) { 22 | out.print(i - 10001); 23 | break; 24 | } 25 | } 26 | 27 | out.close(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /ProjectEuler/src/python/012 Highly divisible triangular number.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def get_num_of_factors(x): 4 | if x == 1: 5 | return 1 6 | 7 | if x < 4: 8 | return 2 9 | 10 | res = 2 # 1 and x itself 11 | root = int(math.sqrt(x)) + 1 12 | for i in range(2, root): 13 | if x % i == 0: 14 | res += 2 15 | 16 | if x == root*root: 17 | res -= 1 18 | return res 19 | 20 | def highly_divisible_triangular_number(n): 21 | cur_sum = 1 22 | pos = 2 23 | num_factors = get_num_of_factors(cur_sum) 24 | while num_factors <= n: 25 | cur_sum += pos 26 | pos += 1 27 | num_factors = get_num_of_factors(cur_sum) 28 | 29 | return cur_sum 30 | 31 | if __name__ == "__main__": 32 | print(highly_divisible_triangular_number(500)) 33 | # print(get_num_of_factors(76576500)) 34 | -------------------------------------------------------------------------------- /leetcode/BinaryTreePreorderTraversalRecursive.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/binary-tree-preorder-traversal/description/ 4 | // 144. Binary Tree Preorder Traversal 5 | 6 | import java.util.*; 7 | 8 | public class BinaryTreePreorderTraversalRecursive { 9 | public List preorderTraversal(TreeNode root) { 10 | List res = new ArrayList<>(); 11 | rec(root, res); 12 | return res; 13 | } 14 | 15 | private void rec(TreeNode node, List list) { 16 | if (node == null) 17 | return; 18 | 19 | list.add(node.val); 20 | rec(node.left, list); 21 | rec(node.right, list); 22 | } 23 | 24 | public class TreeNode { 25 | int val; 26 | TreeNode left; 27 | TreeNode right; 28 | TreeNode(int x) { val = x; } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /leetcode/ReverseInteger.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/reverse-integer/description/ 4 | // 7. Reverse Integer 5 | 6 | public class ReverseInteger { 7 | public int reverse(int x) { 8 | if (x == Integer.MAX_VALUE || x == Integer.MIN_VALUE) 9 | return 0; 10 | 11 | boolean isNegative = false; 12 | int t = x; 13 | if (x < 0) { 14 | x *= -1; 15 | isNegative = true; 16 | } 17 | 18 | int res = x % 10; 19 | x /= 10; 20 | 21 | while (x > 0) { 22 | res *= 10; 23 | res += x % 10; 24 | x /= 10; 25 | 26 | if (x > 0 && res > (Integer.MAX_VALUE / 10)) 27 | return 0; 28 | } 29 | 30 | if (isNegative) 31 | res *= -1; 32 | 33 | return res; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /leetcode/JudgeRouteCircle.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/judge-route-circle/description/ 4 | // 657. Judge Route Circle 5 | 6 | class JudgeRouteCircle { 7 | public boolean judgeCircle(String moves) { 8 | int x = 0, y = 0; 9 | 10 | for (char c : moves.toCharArray()) { 11 | switch (c) { 12 | case 'U': 13 | y++; 14 | break; 15 | case 'R': 16 | x++; 17 | break; 18 | case 'D': 19 | y--; 20 | break; 21 | case 'L': 22 | x--; 23 | break; 24 | default: 25 | break; 26 | } 27 | } 28 | 29 | return x == 0 && y == 0; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /leetcode/MaxSubArray.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/maximum-subarray 4 | // 53. Maximum Subarray 5 | 6 | public class MaxSubArray { 7 | public int maxSubArray(int[] a) { 8 | boolean allNegative = true; 9 | int maxNegative = Integer.MIN_VALUE; 10 | int result = 0; 11 | int curMax = 0; 12 | 13 | for (int i = 0; i < a.length; i++) { 14 | if (a[i] > 0) 15 | allNegative = false; 16 | else 17 | maxNegative = Math.max(maxNegative, a[i]); 18 | 19 | curMax += a[i]; 20 | 21 | if (curMax < 0) 22 | curMax = 0; 23 | 24 | if (result < curMax) 25 | result = curMax; 26 | } 27 | 28 | if (allNegative) 29 | return maxNegative; 30 | 31 | return result; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /leetcode/NumArray.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/range-sum-query-immutable/description/ 4 | // 303. Range Sum Query - Immutable 5 | 6 | class NumArray { 7 | 8 | int[] sums; 9 | int[] nums; 10 | 11 | public NumArray(int[] nums) { 12 | sums = new int[nums.length]; 13 | this.nums = nums; 14 | 15 | if (nums.length == 0) 16 | return; 17 | 18 | sums[0] = nums[0]; 19 | 20 | for (int i = 1; i < nums.length; i++) 21 | sums[i] = sums[i - 1] + nums[i]; 22 | } 23 | 24 | public int sumRange(int i, int j) { 25 | return sums[j] - sums[i] + nums[i]; 26 | } 27 | } 28 | 29 | /** 30 | * Your NumArray object will be instantiated and called as such: 31 | * NumArray obj = new NumArray(nums); 32 | * int param_1 = obj.sumRange(i,j); 33 | */ 34 | -------------------------------------------------------------------------------- /leetcode/ShortestWordDistance.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/shortest-word-distance/description/ 4 | // 243. Shortest Word Distance 5 | 6 | import java.util.*; 7 | 8 | class ShortestWordDistance { 9 | public int shortestDistance(String[] words, String word1, String word2) { 10 | List list1 = new ArrayList(); 11 | List list2 = new ArrayList(); 12 | 13 | for (int i = 0; i < words.length; i++) 14 | if (words[i].equals(word1)) 15 | list1.add(i); 16 | else if (words[i].equals(word2)) 17 | list2.add(i); 18 | 19 | int min = Integer.MAX_VALUE; 20 | for (Integer x1 : list1) 21 | for (Integer x2 : list2) 22 | min = Math.min(min, Math.abs(x1 - x2)); 23 | 24 | return min; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /leetcode/WordBreak.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/word-break/description/ 4 | // 139. Word Break 5 | 6 | import java.util.*; 7 | 8 | class WordBreak { 9 | public boolean wordBreak(String s, List wordDict) { 10 | int n = s.length(); 11 | Set set = new HashSet(wordDict); 12 | boolean[] dp = new boolean[n + 1]; 13 | 14 | dp[0] = true; // possible for size zero 15 | 16 | for (int i = 1; i <= n; i++) { 17 | for (int j = 0; j < i; j++) { 18 | // try to split "s" into two substrings: s[0..j] and s[j..i] 19 | if (dp[j] && set.contains(s.substring(j, i))) { 20 | dp[i] = true; 21 | break; 22 | } 23 | } 24 | } 25 | 26 | return dp[n]; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Hackerrank/Algorithms/Implementation/src/BonAppetit.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class BonAppetit { 5 | public static void main(String[] args) { 6 | new BonAppetit().solve(); 7 | } 8 | 9 | public void solve() { 10 | Scanner in = new Scanner(System.in); 11 | PrintWriter out = new PrintWriter(System.out); 12 | int n = in.nextInt(); 13 | int k = in.nextInt(); 14 | int[] c = new int[n]; 15 | 16 | int total = 0; 17 | for (int i = 0; i < n; i++) { 18 | c[i] = in.nextInt(); 19 | total += c[i]; 20 | } 21 | 22 | int charged = in.nextInt(); 23 | if ((total - c[k]) / 2 == charged) 24 | out.print("Bon Appetit"); 25 | else 26 | out.print(charged - (total - c[k]) / 2); 27 | 28 | out.close(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /algorithms/dynamic_programming/MinimumEditDistance.java: -------------------------------------------------------------------------------- 1 | package algorithms.dynamic_programming; 2 | 3 | public class MinimumEditDistance { 4 | public static int getDistance(String s1, String s2) { 5 | int[][] d = new int[s1.length() + 1][s2.length() + 1]; 6 | 7 | for (int i = 1; i <= s1.length(); i++) 8 | d[i][0] = i; 9 | 10 | for (int j = 1; j <= s2.length(); j++) 11 | d[0][j] = j; 12 | 13 | for (int i = 1; i <= s1.length(); i++) { 14 | for (int j = 1; j <= s2.length(); j++) { 15 | if (s1.charAt(i - 1) == s2.charAt(j - 1)) 16 | d[i][j] = d[i - 1][j - 1]; 17 | else 18 | d[i][j] = 1 + Math.min(d[i - 1][j - 1], Math.min(d[i][j - 1], d[i - 1][j])); 19 | } 20 | } 21 | 22 | return d[s1.length()][s2.length()]; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /leetcode/FirstMissingPositive.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/first-missing-positive/description/ 4 | // 41. First Missing Positive 5 | 6 | public class FirstMissingPositive { 7 | public int firstMissingPositive(int[] nums) { 8 | int n = nums.length; 9 | 10 | if (n == 0) 11 | return 1; 12 | 13 | for (int i = 0; i < n; i++) { 14 | while (nums[i] - 1 != i && nums[i] - 1 < n && nums[i] - 1 >= 0 && nums[nums[i] - 1] != nums[i]) 15 | swap(nums, i, nums[i] - 1); 16 | } 17 | 18 | for (int i = 0; i < n; i++) 19 | if (nums[i] != i + 1) 20 | return i + 1; 21 | 22 | return n + 1; 23 | } 24 | 25 | private void swap(int[] arr, int i, int j) { 26 | int t = arr[i]; 27 | arr[i] = arr[j]; 28 | arr[j] = t; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /leetcode/HIndexII.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/h-index-ii 4 | // 275. H-Index II 5 | 6 | public class HIndexII { 7 | public int hIndex(int[] citations) { 8 | if (citations.length == 0) 9 | return 0; 10 | else if (citations.length == 1) { 11 | if (citations[0] == 0) 12 | return 0; 13 | else 14 | return 1; 15 | } 16 | 17 | int n = citations.length; 18 | if (n <= citations[0]) 19 | return n; 20 | 21 | int l = 1; 22 | int r = n; 23 | 24 | while (l < r) { 25 | int m = l + (r - l) / 2; 26 | 27 | if (n - m <= citations[m]) { 28 | r = m; 29 | } else { 30 | l = m + 1; 31 | } 32 | } 33 | 34 | return n - r; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /leetcode/Heaters.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/heaters/description/ 4 | // 475. Heaters 5 | 6 | import java.util.TreeSet; 7 | 8 | public class Heaters { 9 | public int findRadius(int[] houses, int[] heaters) { 10 | TreeSet set = new TreeSet(); 11 | int res = 0; 12 | 13 | for (int heater : heaters) 14 | set.add(heater); 15 | 16 | for (int house : houses) { 17 | Integer upperHeater = set.ceiling(house); 18 | Integer lowerHeater = set.floor(house); 19 | 20 | int rightDist = (upperHeater == null ? Integer.MAX_VALUE : upperHeater - house); 21 | int leftDist = (lowerHeater == null ? Integer.MAX_VALUE : house - lowerHeater); 22 | 23 | res = Math.max(res, Math.min(leftDist, rightDist)); 24 | } 25 | 26 | return res; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /TopCoder/srm644div2/src/LostCharacter.java: -------------------------------------------------------------------------------- 1 | public class LostCharacter { 2 | 3 | public boolean compare(String s1, String s2) { 4 | String x1 = ""; 5 | String x2 = ""; 6 | 7 | for (int i = 0; i < s1.length(); i++) 8 | x1 += (s1.charAt(i) == '?') ? "z" : s1.charAt(i); 9 | 10 | for (int i = 0; i < s2.length(); i++) 11 | x2 += (s2.charAt(i) == '?') ? "a" : s2.charAt(i); 12 | 13 | return x1.compareTo(x2) < 0; 14 | } 15 | 16 | public int[] getmins(String[] str) { 17 | int[] res = new int[str.length]; 18 | 19 | for (int i = 0; i < str.length; i++) { 20 | int count = 0; 21 | for (int j = 0; j < str.length; j++) if (i != j) { 22 | if (compare(str[j], str[i])) count++; 23 | } 24 | res[i] = count; 25 | } 26 | return res; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /algorithms/dynamic_programming/ScoresProblem.java: -------------------------------------------------------------------------------- 1 | package algorithms.dynamic_programming; 2 | 3 | public class ScoresProblem { 4 | 5 | public static int countNumberOfScoreCombinations(int n, int[] scores) { 6 | int[] d = new int[n + 1]; 7 | d[0] = 1; 8 | for (int i = 1; i <= n; i++) { 9 | for (int s : scores) 10 | if (i - s >= 0) 11 | d[i] += d[i - s]; 12 | } 13 | 14 | return d[n]; 15 | } 16 | 17 | /* 18 | Counts unique combinations, number of ways to get final score N 19 | */ 20 | public static int numberOfNonRepeatedCombinations(int n, int[] scores) { 21 | int[] d = new int[n + 1]; 22 | d[0] = 1; 23 | for (int score : scores) 24 | for (int i = score; i <= n; i++) 25 | d[i] += d[i - score]; 26 | 27 | return d[n]; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /leetcode/ReadNCharactersGivenRead4.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/read-n-characters-given-read4/description/ 4 | // 157. Read N Characters Given Read4 5 | 6 | public class ReadNCharactersGivenRead4 { 7 | /** 8 | * @param buf Destination buffer 9 | * @param n Maximum number of characters to read 10 | * @return The number of characters read 11 | */ 12 | public int read(char[] buf, int n) { 13 | int total = 0, count = 4; 14 | 15 | while (total < n && count >= 4) { 16 | char[] chunk = new char[4]; 17 | count = Math.min(read4(chunk), n - total); 18 | 19 | for (int i = 0; i < count; i++) 20 | buf[total++] = chunk[i]; 21 | } 22 | 23 | return total; 24 | } 25 | 26 | // dumb method 27 | int read4(char[] buf) { 28 | return 0; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /leetcode/RemoveDuplicateLetters.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/remove-duplicate-letters/description/ 4 | // 316. Remove Duplicate Letters 5 | 6 | public class RemoveDuplicateLetters { 7 | public String removeDuplicateLetters(String s) { 8 | int[] count = new int[26]; 9 | int min = 0; 10 | 11 | for (char c : s.toCharArray()) 12 | count[c - 'a']++; 13 | 14 | for (int i = 0; i < s.length(); i++) { 15 | if (s.charAt(i) < s.charAt(min)) 16 | min = i; 17 | 18 | count[s.charAt(i) - 'a']--; 19 | 20 | if (count[s.charAt(i) - 'a'] == 0) 21 | break; 22 | } 23 | 24 | if (s.length() == 0) 25 | return ""; 26 | 27 | return s.charAt(min) + removeDuplicateLetters(s.substring(min + 1).replaceAll("" + s.charAt(min), "")); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /leetcode/WiggleSort.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/wiggle-sort/description/ 4 | // 280. Wiggle Sort 5 | 6 | public class WiggleSort { 7 | public void wiggleSort(int[] nums) { 8 | int i = 0; 9 | while (i < nums.length) { 10 | int j = i + 1; 11 | while (j < nums.length && nums[j] > nums[i]) 12 | j++; 13 | 14 | if (j < nums.length) 15 | swap(nums, i, j); 16 | 17 | i++; 18 | j = i + 1; 19 | while (j < nums.length && nums[j] < nums[i]) 20 | j++; 21 | 22 | if (j < nums.length) 23 | swap(nums, i, j); 24 | 25 | i++; 26 | } 27 | } 28 | 29 | private void swap(int[] arr, int i, int j) { 30 | int temp = arr[i]; 31 | arr[i] = arr[j]; 32 | arr[j] = temp; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /TopCoder/srm648div2/test/KitayutaMart2Test.java: -------------------------------------------------------------------------------- 1 | import org.junit.jupiter.api.Test; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | public class KitayutaMart2Test { 6 | 7 | @Test 8 | public void test0() { 9 | int K = 100; 10 | int T = 100; 11 | assertEquals(1, new KitayutaMart2().numBought(K, T)); 12 | } 13 | 14 | @Test 15 | public void test1() { 16 | int K = 100; 17 | int T = 300; 18 | assertEquals(2, new KitayutaMart2().numBought(K, T)); 19 | } 20 | 21 | @Test 22 | public void test2() { 23 | int K = 150; 24 | int T = 1050; 25 | assertEquals(3, new KitayutaMart2().numBought(K, T)); 26 | } 27 | 28 | @Test 29 | public void test3() { 30 | int K = 160; 31 | int T = 163680; 32 | assertEquals(10, new KitayutaMart2().numBought(K, T)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Hackerrank/Algorithms/Implementation/src/Kangaroo.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Kangaroo { 5 | public static void main(String[] args) { 6 | new Kangaroo().solve(); 7 | } 8 | 9 | public void solve() { 10 | Scanner in = new Scanner(System.in); 11 | PrintWriter out = new PrintWriter(System.out); 12 | int x1 = in.nextInt(); 13 | int v1 = in.nextInt(); 14 | int x2 = in.nextInt(); 15 | int v2 = in.nextInt(); 16 | 17 | boolean found = false; 18 | 19 | while (true) { 20 | if (x1 == x2) { 21 | found = true; 22 | break; 23 | } 24 | 25 | x1 += v1; 26 | x2 += v2; 27 | 28 | if (x1 > x2) 29 | break; 30 | } 31 | 32 | out.print(found ? "YES" : "NO"); 33 | out.close(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /TopCoder/srm650div2/src/TaroJiroDividing.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.math.*; 3 | 4 | import static java.lang.Math.*; 5 | 6 | public class TaroJiroDividing { 7 | 8 | public int getNumber(int A, int B) { 9 | Map map = new HashMap(); 10 | int res = 0; 11 | while (A % 2 != 1) { 12 | if (map.get(A) == null) 13 | map.put(A, 1); 14 | 15 | A /= 2; 16 | } 17 | map.put(A, 1); 18 | 19 | while (B % 2 != 1) { 20 | if (map.get(B) != null) 21 | res++; 22 | 23 | B /= 2; 24 | } 25 | if (map.get(B) != null) 26 | res++; 27 | 28 | return res; 29 | } 30 | 31 | public static void main(String[] args) { 32 | int res = new TaroJiroDividing().getNumber(7, 4); 33 | System.out.println(res); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /codeforces/round321_div2/ProblemA.java: -------------------------------------------------------------------------------- 1 | package codeforces.round321_div2; 2 | 3 | import java.io.PrintWriter; 4 | import java.util.*; 5 | 6 | public class ProblemA { 7 | 8 | public static void main(String[] args) { 9 | Scanner in = new Scanner(System.in); 10 | PrintWriter out = new PrintWriter(System.out); 11 | 12 | int n = in.nextInt(); 13 | int max = 0; 14 | int cur = 0; 15 | int last = 0; 16 | 17 | for (int i = 0; i < n; i++) { 18 | int x = in.nextInt(); 19 | if (x >= last) { 20 | cur++; 21 | } else { 22 | if (max < cur) 23 | max = cur; 24 | cur = 1; 25 | } 26 | 27 | last = x; 28 | } 29 | if (max < cur) 30 | max = cur; 31 | 32 | out.println(max); 33 | 34 | out.close(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /leetcode/MissingNumber.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/missing-number 4 | // 268. Missing Number 5 | 6 | public class MissingNumber { 7 | public int missingNumber(int[] nums) { 8 | boolean zeroExists = false; 9 | int n = nums.length; 10 | int sum = n * (n + 1) / 2; 11 | for (int i = 0; i < nums.length; i++) { 12 | if (nums[i] == 0) 13 | zeroExists = true; 14 | 15 | sum -= nums[i]; 16 | } 17 | 18 | if (!zeroExists) 19 | return 0; 20 | 21 | return sum; 22 | } 23 | 24 | public void solve() { 25 | int[] nums = {0, 1, 3}; 26 | //int[] nums = {0}; 27 | int res = missingNumber(nums); 28 | 29 | System.out.println(res); 30 | } 31 | 32 | public static void main(String[] args) { 33 | new MissingNumber().solve(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /leetcode/StrobogrammaticNumber.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/strobogrammatic-number/description/ 4 | // 246. Strobogrammatic Number 5 | 6 | public class StrobogrammaticNumber { 7 | public boolean isStrobogrammatic(String num) { 8 | int i = 0, j = num.length() - 1; 9 | 10 | while (i <= j) { 11 | char left = num.charAt(i); 12 | char right = num.charAt(num.length() - 1 - i); 13 | 14 | boolean ok = false; 15 | 16 | if (left == right && (left == '0' || left == '8' || left == '1')) 17 | ok = true; 18 | else if (left != right && (left == '6' && right == '9' || left == '9' && right == '6')) 19 | ok = true; 20 | 21 | if (!ok) 22 | return false; 23 | 24 | i++; 25 | j--; 26 | } 27 | 28 | return true; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /algorithms/linked_lists/RemoveDuplicates.java: -------------------------------------------------------------------------------- 1 | package algorithms.linked_lists; 2 | 3 | import java.util.HashSet; 4 | 5 | public class RemoveDuplicates { 6 | static void removeDuplicates(Node head) { 7 | Node prev = head; 8 | Node cur = prev.next; 9 | HashSet used = new HashSet<>(); 10 | used.add(prev.data); 11 | 12 | if (used.contains(cur.data)) { // first iteration, to cover case of similar first two elements 13 | prev.next = cur.next; 14 | cur = cur.next; 15 | } 16 | 17 | while (cur != null && cur.next != null) { 18 | if (!used.contains(cur.data)) { 19 | used.add(cur.data); 20 | 21 | prev = cur; 22 | cur = cur.next; 23 | } else { 24 | prev.next = cur.next; 25 | cur = cur.next; 26 | } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /algorithms/sets/SetTest.java: -------------------------------------------------------------------------------- 1 | package algorithms.sets; 2 | 3 | import java.util.*; 4 | 5 | public class SetTest { 6 | public static void main(String[] args) { 7 | Set intSet = new TreeSet(); 8 | intSet.add(10); 9 | intSet.add(5); 10 | intSet.add(20); 11 | intSet.add(15); 12 | intSet.add(7); 13 | 14 | Iterator it = intSet.iterator(); 15 | while (it.hasNext()) { 16 | System.out.print(it.next() + " "); 17 | } 18 | 19 | System.out.println(); 20 | 21 | Set charSet = new TreeSet(); 22 | String name = "ALIBEK"; 23 | for (char c : name.toCharArray()) 24 | charSet.add(c); 25 | 26 | Iterator charSetIt = charSet.iterator(); 27 | while (charSetIt.hasNext()) { 28 | System.out.print(charSetIt.next() + " "); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /algorithms/threads/Deadlock.java: -------------------------------------------------------------------------------- 1 | package algorithms.threads; 2 | 3 | public class Deadlock { 4 | static class Friend { 5 | public String name; 6 | 7 | Friend(String name) { 8 | this.name = name; 9 | } 10 | 11 | public synchronized void bow(Friend bower) { 12 | System.out.format("%s: %s has bowed to me%n", this.name, bower.name); 13 | bower.bowBack(bower); 14 | } 15 | 16 | public synchronized void bowBack(Friend bower) { 17 | System.out.format("%s: %s has bowed back to me%n", this.name, bower.name); 18 | } 19 | } 20 | 21 | public static void main(String[] args) { 22 | Friend alibek = new Friend("alibek"); 23 | Friend zhanibek = new Friend("zhanibek"); 24 | 25 | new Thread(() -> alibek.bow(zhanibek)).start(); 26 | new Thread(() -> zhanibek.bow(alibek)).start(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode/NestedListWeightSum.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/nested-list-weight-sum/description/ 4 | // 339. Nested List Weight Sum 5 | 6 | import java.util.*; 7 | 8 | class NestedListWeightSum { 9 | public interface NestedInteger { 10 | public boolean isInteger(); 11 | public List getList(); 12 | public int getInteger(); 13 | } 14 | public int depthSum(List nestedList) { 15 | return getSum(nestedList, 1); 16 | } 17 | 18 | public int getSum(List nestedList, int depth) { 19 | int sum = 0; 20 | for (NestedInteger node : nestedList) { 21 | if (node.isInteger()) 22 | sum += node.getInteger() * depth; 23 | else 24 | sum += getSum(node.getList(), depth + 1); 25 | } 26 | 27 | return sum; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /leetcode/SumOfSquareNumbers2.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/sum-of-square-numbers/description/ 4 | // 633. Sum of Square Numbers 5 | 6 | class SumOfSquareNumbers2 { 7 | public boolean judgeSquareSum(int c) { 8 | // a^2 + b^2 = c 9 | for (long a = 0; a * a <= c; a++) { 10 | int b = c - (int)(a * a); 11 | if (binSearch(0, b, b)) 12 | return true; 13 | } 14 | 15 | return false; 16 | } 17 | 18 | public boolean binSearch(long l, long r, int num) { 19 | if (l > r) 20 | return false; 21 | 22 | long m = l + (r - l) / 2; 23 | 24 | if (m * m == num) 25 | return true; 26 | else if (m * m > num) 27 | return binSearch(l, m - 1, num); 28 | 29 | return binSearch(m + 1, r, num); 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /leetcode/LargestPlusSign.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // 764. Largest Plus Sign 4 | 5 | public class LargestPlusSign { 6 | public int orderOfLargestPlusSign(int N, int[][] mines) { 7 | int res = 0; 8 | boolean[][] grid = new boolean[N][N]; 9 | 10 | for(int[] arr : mines) 11 | grid[arr[0]][arr[1]] = true; 12 | 13 | for(int i = 0; i < N; i++) { 14 | for(int j = 0; j < N; j++) { 15 | int k = 0; 16 | 17 | while ( 18 | i - k >= 0 && i + k < N && j - k >= 0 && j + k < N && 19 | !grid[i-k][j] && 20 | !grid[i + k][j] && 21 | !grid[i][j - k] && 22 | !grid[i][j + k] 23 | ) 24 | k++; 25 | 26 | res = Math.max(res, k); 27 | } 28 | } 29 | 30 | return res; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /leetcode/MonotoneIncreasingDigits.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/monotone-increasing-digits/description/ 4 | // 738. Monotone Increasing Digits 5 | 6 | class MonotoneIncreasingDigits { 7 | public int monotoneIncreasingDigits(int n) { 8 | int shift = findCliff(n); 9 | while (shift != -1) { 10 | n = n - (n % shift) - 1; 11 | shift = findCliff(n); 12 | } 13 | 14 | return n; 15 | } 16 | 17 | public int findCliff(int n) { 18 | int x = n; 19 | int prev = x % 10; 20 | x /= 10; 21 | int count = 1; 22 | 23 | while (x > 0) { 24 | count *= 10; 25 | int cur = x % 10; 26 | if (cur > prev) 27 | return count; 28 | prev = cur; 29 | x /= 10; 30 | } 31 | 32 | return -1; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /leetcode/PerfectSquares.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/perfect-squares 4 | // 279. Perfect Squares 5 | 6 | import java.io.PrintWriter; 7 | 8 | public class PerfectSquares { 9 | public int numSquares(int n) { 10 | int[] dp = new int[n + 1]; 11 | dp[0] = 0; 12 | for (int i = 1; i <= n; i++) 13 | dp[i] = 100000; 14 | 15 | for (int i = 0; i <= n; i++) 16 | for (int j = 1; i + j * j <= n; j++) 17 | dp[i + j * j] = Math.min(dp[i + j * j], dp[i] + 1); 18 | 19 | return dp[n]; 20 | } 21 | 22 | public static void main(String[] args) { 23 | new PerfectSquares().solve(); 24 | } 25 | 26 | public void solve() { 27 | PrintWriter out = new PrintWriter(System.out); 28 | int n = 13; 29 | int res = numSquares(n); 30 | out.print(res); 31 | out.close(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /TopCoder/srm660div2/src/Cyclemin.java: -------------------------------------------------------------------------------- 1 | public class Cyclemin { 2 | 3 | public String insertAs(String s, int k) { 4 | int i = 0; 5 | StringBuilder res = new StringBuilder(s); 6 | while (i < s.length() && k > 0) { 7 | if (s.charAt(i) != 'a') { 8 | k--; 9 | res.setCharAt(i, 'a'); 10 | } 11 | i++; 12 | } 13 | return res.toString(); 14 | } 15 | 16 | public String bestmod(String s, int k) { 17 | StringBuilder cur = new StringBuilder(s); 18 | String minStr = s; 19 | for (int i = 0; i < s.length(); i++) { 20 | cur.append(cur.charAt(0)); 21 | cur.deleteCharAt(0); 22 | String curRes = insertAs(cur.toString(), k); 23 | 24 | if (minStr.compareTo(curRes) > 0) 25 | minStr = curRes; 26 | } 27 | 28 | return minStr; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /leetcode/MinimumDistanceBetweenBSTNodes.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/minimum-distance-between-bst-nodes/description/ 4 | // 783. Minimum Distance Between BST Nodes 5 | 6 | public class MinimumDistanceBetweenBSTNodes { 7 | 8 | int prev = Integer.MAX_VALUE; 9 | int min = Integer.MAX_VALUE; 10 | 11 | public int minDiffInBST(TreeNode root) { 12 | rec(root); 13 | return min; 14 | } 15 | 16 | private void rec(TreeNode node) { 17 | if (node == null) 18 | return; 19 | 20 | rec(node.left); 21 | 22 | if (prev != Integer.MAX_VALUE) 23 | min = Math.min(min, Math.abs(node.val - prev)); 24 | prev = node.val; 25 | rec(node.right); 26 | } 27 | 28 | public class TreeNode { 29 | int val; 30 | TreeNode left; 31 | TreeNode right; 32 | TreeNode(int x) { val = x; } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /leetcode/MinimizeMaxDistanceToGasStation.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/minimize-max-distance-to-gas-station/description/ 4 | // 774. Minimize Max Distance to Gas Station 5 | 6 | public class MinimizeMaxDistanceToGasStation { 7 | final double EPS = 1e-6; 8 | 9 | public double minmaxGasDist(int[] stations, int k) { 10 | int n = stations.length; 11 | double left = 0, right = 1e8; 12 | 13 | while (right - left > EPS) { 14 | int cur = 0; 15 | 16 | // is it possible to get max distance m? 17 | double m = left + (right - left) / 2; 18 | 19 | for (int i = 1; i < n; i++) 20 | cur += (int)(Math.abs(stations[i] - stations[i - 1]) / m); 21 | 22 | if (cur <= k) 23 | right = m; 24 | else 25 | left = m; 26 | } 27 | 28 | return right; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /leetcode/ShortestPalindrome.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/shortest-palindrome/description/ 4 | // 214. Shortest Palindrome 5 | 6 | public class ShortestPalindrome { 7 | public String shortestPalindrome(String s) { 8 | if (s.length() < 2) 9 | return s; 10 | 11 | char[] ch = s.toCharArray(); 12 | int right = ch.length - 1; 13 | while (right > 0 && !isPalindrome(ch, 0, right)) 14 | right--; 15 | 16 | StringBuilder sb = new StringBuilder(s); 17 | for (int i = right + 1; i < ch.length; i++) 18 | sb.insert(0, ch[i]); 19 | 20 | return sb.toString(); 21 | } 22 | 23 | private boolean isPalindrome(char[] ch, int left, int right) { 24 | while (left <= right) { 25 | if (ch[left++] != ch[right--]) 26 | return false; 27 | } 28 | 29 | return true; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /leetcode/CountingBits.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/counting-bits/description/ 4 | // 338. Counting Bits 5 | 6 | class CountingBits { 7 | public int[] countBits(int num) { 8 | if (num == 0) 9 | return new int[]{0}; 10 | 11 | int[] dp = new int[num + 1]; 12 | dp[0] = 0; 13 | dp[1] = 1; 14 | 15 | for (int i = 2; i <= num; i++) { 16 | if ((i & (i - 1)) == 0) { // if this is a power of two, then it has only 1 bit 17 | dp[i] = 1; 18 | continue; 19 | } 20 | 21 | int power = (int)(Math.ceil(Math.log(i) / Math.log(2))); 22 | int closestSmallerPowerOfTwo = (int)Math.pow(2, power - 1); 23 | 24 | dp[i] = dp[closestSmallerPowerOfTwo] + dp[i - closestSmallerPowerOfTwo]; 25 | } 26 | 27 | return dp; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /leetcode/InvertBinaryTree.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/invert-binary-tree/description/ 4 | // 226. Invert Binary Tree 5 | 6 | public class InvertBinaryTree { 7 | public TreeNode invertTree(TreeNode root) { 8 | if (root == null) 9 | return null; 10 | 11 | rec(root); 12 | 13 | return root; 14 | } 15 | 16 | private void rec(TreeNode node) { 17 | if (node == null) 18 | return; 19 | 20 | if (node.left != null || node.right != null) { 21 | TreeNode temp = node.left; 22 | node.left = node.right; 23 | node.right = temp; 24 | 25 | invertTree(node.left); 26 | invertTree(node.right); 27 | } 28 | } 29 | 30 | public class TreeNode { 31 | int val; 32 | TreeNode left; 33 | TreeNode right; 34 | TreeNode(int x) { val = x; } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /leetcode/MoveZeroes.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /* 4 | Move Zeroes problem 5 | 6 | Given an array nums, write a function to move all 0's to the end of it 7 | while maintaining the relative order of the non-zero elements. 8 | 9 | For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. 10 | 11 | Note: 12 | - You must do this in-place without making a copy of the array. 13 | - Minimize the total number of operations. 14 | 15 | */ 16 | 17 | public class MoveZeroes { 18 | public void moveZeroes(int[] nums) { 19 | int n = nums.length; 20 | if (n < 2) 21 | return; 22 | 23 | int j = 0; 24 | for (int i = 0; i < n; i++) { 25 | if (nums[i] != 0) { 26 | int temp = nums[i]; 27 | nums[i] = nums[j]; 28 | nums[j] = temp; 29 | j++; 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /leetcode/FindPeakElement.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/find-peak-element/description/ 4 | // 162. Find Peak Element 5 | 6 | public class FindPeakElement { 7 | public int findPeakElement(int[] nums) { 8 | int n = nums.length; 9 | 10 | if (n < 2) 11 | return 0; 12 | 13 | if (n == 2) 14 | return nums[0] > nums[1] ? 0 : 1; 15 | 16 | int l = 0, r = n - 1, res = 0; 17 | 18 | while (l < r) { 19 | int mid = l + (r - l) / 2; 20 | if (mid == 0 || mid == n - 1) 21 | return mid; 22 | 23 | if (nums[mid] > nums[mid - 1] && nums[mid] > nums[mid + 1]) 24 | return mid; 25 | else if (nums[mid] > nums[mid + 1] && nums[mid] < nums[mid - 1]) 26 | r = mid; 27 | else 28 | l = mid + 1; 29 | } 30 | 31 | return l; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /leetcode/FindMinimumInRotatedSortedArray.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/ 4 | // 153. Find Minimum in Rotated Sorted Array 5 | 6 | public class FindMinimumInRotatedSortedArray { 7 | public int findMin(int[] nums) { 8 | int n = nums.length; 9 | 10 | if (n == 0) 11 | return -1; 12 | 13 | if (n == 1) 14 | return nums[0]; 15 | 16 | if (nums[0] < nums[n - 1]) // array is sorted normally, no rotation happened 17 | return nums[0]; 18 | 19 | int l = 0, r = n - 1; 20 | 21 | while (l < r) { 22 | if (nums[l] < nums[r]) 23 | break; 24 | 25 | int m = l + (r - l) / 2; 26 | 27 | if (nums[m] < nums[r]) 28 | r = m; 29 | else 30 | l = m + 1; 31 | } 32 | 33 | return nums[l]; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /leetcode/LoggerRateLimiter.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/logger-rate-limiter/description/ 4 | // 359. Logger Rate Limiter 5 | 6 | import java.util.*; 7 | 8 | public class LoggerRateLimiter { 9 | Map map; // message -> last time printed 10 | 11 | /** Initialize your data structure here. */ 12 | public LoggerRateLimiter() { 13 | map = new HashMap(); 14 | } 15 | 16 | /** Returns true if the message should be printed in the given timestamp, otherwise returns false. 17 | If this method returns false, the message will not be printed. 18 | The timestamp is in seconds granularity. */ 19 | public boolean shouldPrintMessage(int timestamp, String message) { 20 | if (!map.containsKey(message) || timestamp - map.get(message) >= 10) { 21 | map.put(message, timestamp); 22 | return true; 23 | } 24 | 25 | return false; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /ProjectEuler/src/python/014 Longest Collatz sequence.py: -------------------------------------------------------------------------------- 1 | ans = { 2 | 1: 1, 3 | 2: 2, 4 | 4: 3, 5 | 8: 4, 6 | 16: 5, 7 | 5: 6, 8 | 10: 7, 9 | 20: 8, 10 | 40: 9, 11 | 13: 10 12 | } 13 | 14 | 15 | def rec(num): 16 | if ans.get(num) is None: # need to calculate for current number 17 | cur_res = rec(num // 2) if num % 2 == 0 else rec(3*num + 1) 18 | ans[num] = cur_res + 1 19 | return cur_res + 1 20 | else: 21 | return ans.get(num) # already calculated 22 | 23 | 24 | def solve(): 25 | limit = 1000000 # limit index 26 | cur_ind = 3 27 | ind = 13 # max index 28 | elems = 10 29 | 30 | while cur_ind < limit: 31 | cur_res = rec(cur_ind) 32 | if elems < cur_res: 33 | elems = cur_res 34 | ind = cur_ind 35 | cur_ind += 1 36 | 37 | return ind 38 | 39 | 40 | if __name__ == "__main__": 41 | res = solve() 42 | print(res) 43 | -------------------------------------------------------------------------------- /ProjectEuler/src/python/007 10001st prime.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def is_prime(x): 4 | if x == 1: 5 | return False 6 | 7 | if x < 4: 8 | return True 9 | 10 | if x % 2 == 0: 11 | return False 12 | 13 | if x < 9: 14 | return True 15 | 16 | if x % 3 == 0: 17 | return False 18 | else: 19 | # all prime number can be written in the form of 6k+1 or 6k-1 20 | r = math.floor(math.sqrt(x)) 21 | f = 5 22 | while f <= r: 23 | if x % f == 0: 24 | return False 25 | 26 | if x % (f+2) == 0: 27 | return False 28 | 29 | f += 6 30 | 31 | return True 32 | 33 | def get_nth_prime(n): 34 | count = 0 35 | cur = 1 36 | while count < n: 37 | if is_prime(cur): 38 | count += 1 39 | cur += 1 40 | return cur - 1 41 | 42 | 43 | if __name__ == "__main__": 44 | print(get_nth_prime(10001)) 45 | -------------------------------------------------------------------------------- /algorithms/arrays/RandomShuffle.java: -------------------------------------------------------------------------------- 1 | package algorithms.arrays; 2 | 3 | import java.util.Random; 4 | 5 | public class RandomShuffle { 6 | 7 | public static void main(String[] args) { 8 | int n = 10; 9 | int[] arr = new int[n]; 10 | for (int i = 0; i < n; i++) 11 | arr[i] = i; 12 | 13 | int[] res = shuffleArray(arr); 14 | for (int x : res) 15 | System.out.print(x + " "); 16 | System.out.println(); 17 | } 18 | 19 | public static int[] shuffleArray(int[] arr) { 20 | int n = arr.length; 21 | Random random = new Random(); 22 | 23 | for (int i = 0; i < n; i++) { 24 | int j = random.nextInt(n - i) + i; 25 | swap(arr, i, j); 26 | } 27 | 28 | return arr; 29 | } 30 | 31 | private static void swap(int[] arr, int i, int j) { 32 | int temp = arr[i]; 33 | arr[i] = arr[j]; 34 | arr[j] = temp; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /codeforces/round322_div2/ProblemB.java: -------------------------------------------------------------------------------- 1 | package codeforces.round322_div2; 2 | 3 | import java.io.PrintWriter; 4 | import java.util.*; 5 | 6 | public class ProblemB { 7 | 8 | public static void main(String[] args) { 9 | Scanner in = new Scanner(System.in); 10 | PrintWriter out = new PrintWriter(System.out); 11 | 12 | int n = in.nextInt(); 13 | int[] h = new int[n + 1]; 14 | int[] res = new int[n + 1]; 15 | 16 | for (int i = 1; i <= n; i++) 17 | h[i] = in.nextInt(); 18 | 19 | int max = h[n]; 20 | res[n] = 0; 21 | for (int i = n - 1; i > 0; i--) { 22 | if (max < h[i]) { 23 | res[i] = 0; 24 | max = h[i]; 25 | } else { 26 | res[i] = max - h[i] + 1; 27 | } 28 | } 29 | 30 | for (int i = 1; i <= n; i++) 31 | out.print(res[i] + " "); 32 | 33 | out.close(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /leetcode/IsomorphicStrings.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/isomorphic-strings/description/ 4 | // 205. Isomorphic Strings 5 | 6 | import java.util.*; 7 | 8 | class IsomorphicStrings { 9 | public boolean isIsomorphic(String s, String t) { 10 | char[] c1 = s.toCharArray(); 11 | char[] c2 = t.toCharArray(); 12 | 13 | Map map = new HashMap(); 14 | Set set = new HashSet(); 15 | 16 | for (int i = 0; i < c1.length; i++) { 17 | if (!map.containsKey(c1[i])) { 18 | if (set.contains(c2[i])) 19 | return false; 20 | 21 | map.put(c1[i], c2[i]); 22 | set.add(c2[i]); 23 | } else { 24 | if (map.get(c1[i]) != c2[i]) 25 | return false; 26 | } 27 | } 28 | 29 | return true; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /leetcode/LongestCommonPrefix.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/longest-common-prefix/description/ 4 | // 14. Longest Common Prefix 5 | 6 | public class LongestCommonPrefix { 7 | public String longestCommonPrefix(String[] strs) { 8 | if (strs.length == 0) 9 | return ""; 10 | 11 | StringBuilder res = new StringBuilder(); 12 | 13 | int n = strs.length; 14 | boolean stop = false; 15 | 16 | for (int len = 0; len < strs[0].length(); len++) { 17 | res.append(strs[0].charAt(len)); 18 | 19 | for (int i = 1; i < n; i++) { 20 | if (!strs[i].startsWith(res.toString())) { 21 | res.deleteCharAt(len); 22 | stop = true; 23 | break; 24 | } 25 | } 26 | 27 | if (stop) 28 | break; 29 | } 30 | 31 | return res.toString(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /leetcode/PaintHouseII.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/paint-house-ii/description/ 4 | // 265. Paint House II 5 | 6 | class PaintHouseII { 7 | public int minCostII(int[][] costs) { 8 | int n = costs.length; 9 | 10 | if (n == 0) 11 | return 0; 12 | 13 | int k = costs[0].length; 14 | 15 | for (int i = 1; i < n; i++) { 16 | for (int j = 0; j < k; j++) { 17 | int curMin = Integer.MAX_VALUE; 18 | for (int l = 0; l < k; l++) 19 | if (l != j) 20 | curMin = Math.min(curMin, costs[i - 1][l]); 21 | 22 | costs[i][j] += curMin; 23 | } 24 | } 25 | 26 | int min = Integer.MAX_VALUE; 27 | for (int j = 0; j < k; j++) 28 | min = Math.min(min, costs[n - 1][j]); 29 | 30 | return min; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /algorithms/arrays/test/RotateMatrixTest.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | import static algorithms.arrays.RotateMatrix.rotate; 4 | import static org.junit.Assert.assertArrayEquals; 5 | 6 | public class RotateMatrixTest { 7 | @Test 8 | public void test1() { 9 | int[][] matrix = {{1, 2}, {3, 4}}; 10 | int[][] actual = {{3, 1}, {4, 2}}; 11 | assertArrayEquals(actual, rotate(matrix)); 12 | } 13 | 14 | @Test 15 | public void test2() { 16 | int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; 17 | int[][] actual = {{7, 4, 1}, {8, 5, 2}, {9, 6, 3}}; 18 | assertArrayEquals(actual, rotate(matrix)); 19 | } 20 | 21 | @Test 22 | public void test3() { 23 | int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; 24 | int[][] actual = {{13, 9, 5, 1}, {14, 10, 6, 2}, {15, 11, 7, 3}, {16, 12, 8, 4}}; 25 | assertArrayEquals(actual, rotate(matrix)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /leetcode/MinimumAbsoluteDifferenceInBST.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/ 4 | // 530. Minimum Absolute Difference in BST 5 | 6 | public class MinimumAbsoluteDifferenceInBST { 7 | int min = Integer.MAX_VALUE; 8 | TreeNode prev = null; 9 | 10 | public int getMinimumDifference(TreeNode root) { 11 | if (root == null) 12 | return 0; 13 | rec(root); 14 | return min; 15 | } 16 | 17 | private void rec(TreeNode node) { 18 | if (node == null) 19 | return; 20 | 21 | rec(node.left); 22 | 23 | if (prev != null) 24 | min = Math.min(min, Math.abs(node.val - prev.val)); 25 | prev = node; 26 | 27 | rec(node.right); 28 | } 29 | 30 | public class TreeNode { 31 | int val; 32 | TreeNode left; 33 | TreeNode right; 34 | TreeNode(int x) { val = x; } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /leetcode/AddStrings.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/add-strings/description/ 4 | // 415. Add Strings 5 | 6 | public class AddStrings { 7 | public String addStrings(String num1, String num2) { 8 | StringBuilder sb = new StringBuilder(num1); 9 | num1 = sb.reverse().toString(); 10 | 11 | sb = new StringBuilder(num2); 12 | num2 = sb.reverse().toString(); 13 | 14 | int carry = 0; 15 | 16 | sb = new StringBuilder(""); 17 | 18 | for (int i = 0; i < Math.max(num1.length(), num2.length()); i++) { 19 | int n1 = i < num1.length() ? num1.charAt(i) - '0' : 0; 20 | int n2 = i < num2.length() ? num2.charAt(i) - '0' : 0; 21 | int sum = n1 + n2 + carry; 22 | 23 | carry = sum / 10; 24 | sb.append(sum % 10); 25 | } 26 | 27 | if (carry != 0) 28 | sb.append('1'); 29 | 30 | return sb.reverse().toString(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /TopCoder/srm649div2/src/CartInSupermarketEasy.java: -------------------------------------------------------------------------------- 1 | import static java.lang.Math.*; 2 | 3 | public class CartInSupermarketEasy { 4 | 5 | public static int[][] d = new int[105][105]; 6 | 7 | public static int get(int n, int k) { 8 | if (d[n][k] != -1) 9 | return d[n][k]; 10 | 11 | if (k == 0) return n; 12 | if (n == 1) return n; 13 | 14 | int minVal = 1000000; 15 | 16 | for (int a = 1; a < n; a++) { 17 | int b = n - a; 18 | for (int j = 0; j < k; j++) { 19 | minVal = min(minVal, max(get(a, k - j - 1), get(b, j)) + 1); 20 | } 21 | } 22 | minVal = min(minVal, get(n - 1, k) + 1); 23 | d[n][k] = minVal; 24 | 25 | return d[n][k]; 26 | } 27 | 28 | public int calc(int N, int K) { 29 | for (int i = 0; i <= 100; i++) 30 | for (int j = 0; j <= 100; j++) 31 | d[i][j] = -1; 32 | 33 | return get(N, K); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /codeforces/round334_div2/ProblemB.java: -------------------------------------------------------------------------------- 1 | package codeforces.round334_div2; 2 | 3 | import java.util.*; 4 | import java.io.*; 5 | 6 | public class ProblemB { 7 | 8 | public void solve() { 9 | Scanner in = new Scanner(System.in); 10 | PrintWriter out = new PrintWriter(System.out); 11 | 12 | int n = in.nextInt(); 13 | int k = in.nextInt(); 14 | int[] s = new int[n]; 15 | 16 | for (int i = 0; i < n; i++) 17 | s[i] = in.nextInt(); 18 | 19 | int max = s[n - 1]; 20 | 21 | int indRight = n - k; 22 | int indLeft = n - k - 1; 23 | 24 | while (indLeft >= 0 && indLeft < n) { 25 | max = Math.max(max, s[indLeft] + s[indRight]); 26 | indLeft--; 27 | indRight++; 28 | } 29 | 30 | out.print(max); 31 | out.close(); 32 | } 33 | 34 | public static void main(String[] args) { 35 | new codeforces.round305_div2.ProblemB().solve(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /leetcode/KthSmallestElementInBST.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/ 4 | // 230. Kth Smallest Element in a BST 5 | 6 | class KthSmallestElementInBST { 7 | class TreeNode { 8 | int val; 9 | TreeNode left; 10 | TreeNode right; 11 | TreeNode(int x) { val = x; } 12 | } 13 | 14 | int count = 0; 15 | int res; 16 | boolean found = false; 17 | 18 | public int kthSmallest(TreeNode root, int k) { 19 | res = root.val; 20 | rec(root, k); 21 | return res; 22 | } 23 | 24 | private void rec(TreeNode node, int k) { 25 | if (node == null) 26 | return; 27 | 28 | rec(node.left, k); 29 | 30 | if (found) 31 | return; 32 | 33 | if (++count == k) { 34 | res = node.val; 35 | found = true; 36 | return; 37 | } 38 | 39 | rec(node.right, k); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /leetcode/OddEvenLinkedList.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/odd-even-linked-list/description/ 4 | // 328. Odd Even Linked List 5 | 6 | public class OddEvenLinkedList { 7 | public ListNode oddEvenList(ListNode head) { 8 | if (head == null || head.next == null || head.next.next == null) 9 | return head; 10 | 11 | ListNode first = head; 12 | ListNode second = head.next; 13 | 14 | ListNode headSecond = second; 15 | 16 | while (second != null && second.next != null) { 17 | first.next = second.next; 18 | second.next = second.next.next; 19 | 20 | first = first.next; 21 | second = second.next; 22 | } 23 | 24 | first.next = headSecond; // last link between odd and even nodes 25 | 26 | return head; 27 | } 28 | 29 | class ListNode { 30 | int val; 31 | ListNode next; 32 | ListNode(int x) { val = x; } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /TopCoder/srm652div2/test/ThePermutationGameDiv2Test.java: -------------------------------------------------------------------------------- 1 | import org.junit.jupiter.api.Test; 2 | import static org.junit.jupiter.api.Assertions.assertEquals; 3 | 4 | public class ThePermutationGameDiv2Test { 5 | 6 | @Test 7 | public void test0() { 8 | int N = 2; 9 | assertEquals(2L, new ThePermutationGameDiv2().findMin(N)); 10 | } 11 | 12 | @Test 13 | public void test1() { 14 | int N = 3; 15 | assertEquals(6L, new ThePermutationGameDiv2().findMin(N)); 16 | } 17 | 18 | @Test 19 | public void test2() { 20 | int N = 6; 21 | assertEquals(60L, new ThePermutationGameDiv2().findMin(N)); 22 | } 23 | 24 | @Test 25 | public void test3() { 26 | int N = 11; 27 | assertEquals(27720L, new ThePermutationGameDiv2().findMin(N)); 28 | } 29 | 30 | @Test 31 | public void test4() { 32 | int N = 25; 33 | assertEquals(26771144400L, new ThePermutationGameDiv2().findMin(N)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /leetcode/CanPlaceFlowers.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/can-place-flowers/description/ 4 | // 605. Can Place Flowers 5 | 6 | class CanPlaceFlowers { 7 | public boolean canPlaceFlowers(int[] flowerbed, int n) { 8 | if (n == 0) 9 | return true; 10 | 11 | int len = flowerbed.length; 12 | for (int i = 0; i < len; i++) 13 | if (flowerbed[i] == 1) { 14 | if (i > 0) 15 | flowerbed[i - 1] = 2; 16 | if (i < len - 1) 17 | flowerbed[i + 1] = 2; 18 | } 19 | 20 | for (int i = 0; i < len; i++) { 21 | if (flowerbed[i] == 0) { 22 | n--; 23 | if (n == 0) 24 | return true; 25 | 26 | if (i < len - 1) 27 | flowerbed[i + 1] = 2; 28 | } 29 | } 30 | 31 | return false; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /leetcode/FlattenBinaryTreeToLinkedList.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/ 4 | // 114. Flatten Binary Tree to Linked List 5 | 6 | public class FlattenBinaryTreeToLinkedList { 7 | TreeNode last = null; 8 | 9 | public void flatten(TreeNode root) { 10 | if (root == null) 11 | return; 12 | 13 | rec(root); 14 | } 15 | 16 | private void rec(TreeNode node) { 17 | if (node == null) 18 | return; 19 | 20 | TreeNode left = node.left; 21 | TreeNode right = node.right; 22 | 23 | if (last != null) { 24 | last.right = node; 25 | last.left = null; 26 | } 27 | 28 | last = node; 29 | 30 | rec(left); 31 | rec(right); 32 | } 33 | 34 | public class TreeNode { 35 | int val; 36 | TreeNode left; 37 | TreeNode right; 38 | TreeNode(int x) { val = x; } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /algorithms/dynamic_programming/test/MinimumEditDistanceTest.java: -------------------------------------------------------------------------------- 1 | package algorithms.dynamic_programming.test; 2 | 3 | import algorithms.dynamic_programming.MinimumEditDistance; 4 | import org.junit.Test; 5 | 6 | import static org.junit.Assert.assertEquals; 7 | 8 | public class MinimumEditDistanceTest { 9 | @Test 10 | public void test1() { 11 | String s1 = "Saturday"; 12 | String s2 = "Sundays"; 13 | 14 | int res = MinimumEditDistance.getDistance(s1, s2); 15 | assertEquals(res, 4); 16 | } 17 | 18 | @Test 19 | public void test2() { 20 | String s1 = "Carthorse"; 21 | String s2 = "Orchestra"; 22 | 23 | int res = MinimumEditDistance.getDistance(s1, s2); 24 | assertEquals(res, 8); 25 | } 26 | 27 | @Test 28 | public void test3() { 29 | String s1 = "abcdef"; 30 | String s2 = "azced"; 31 | 32 | int res = MinimumEditDistance.getDistance(s1, s2); 33 | assertEquals(res, 3); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /leetcode/BinaryTreePaths.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/binary-tree-paths/description/ 4 | // 257. Binary Tree Paths 5 | 6 | import java.util.*; 7 | 8 | class BinaryTreePaths { 9 | public List binaryTreePaths(TreeNode root) { 10 | List res = new ArrayList(); 11 | if (root == null) 12 | return res; 13 | 14 | rec(root, "" + root.val, res); 15 | 16 | return res; 17 | } 18 | 19 | public void rec(TreeNode x, String path, List res) { 20 | if (x.left == null && x.right == null) 21 | res.add(path); 22 | 23 | if (x.left != null) 24 | rec(x.left, path + "->" + x.left.val, res); 25 | 26 | if (x.right != null) 27 | rec(x.right, path + "->" + x.right.val, res); 28 | } 29 | 30 | public class TreeNode { 31 | int val; 32 | TreeNode left; 33 | TreeNode right; 34 | TreeNode(int x) { val = x; } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /leetcode/BinaryTreeRightSideView.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/binary-tree-right-side-view/description/ 4 | // 199. Binary Tree Right Side View 5 | 6 | import java.util.*; 7 | 8 | public class BinaryTreeRightSideView { 9 | public List rightSideView(TreeNode root) { 10 | if (root == null) 11 | return new ArrayList<>(); 12 | 13 | List res = new ArrayList<>(); 14 | rec(root, 0, res); 15 | return res; 16 | } 17 | 18 | private void rec(TreeNode node, int depth, List list) { 19 | if (node == null) 20 | return; 21 | 22 | if (depth == list.size()) 23 | list.add(node.val); 24 | 25 | rec(node.right, depth + 1, list); 26 | rec(node.left, depth + 1, list); 27 | } 28 | 29 | public class TreeNode { 30 | int val; 31 | TreeNode left; 32 | TreeNode right; 33 | TreeNode(int x) { val = x; } 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /TopCoder/srm643div2/src/TheKingsArmyDiv2.java: -------------------------------------------------------------------------------- 1 | public class TheKingsArmyDiv2 { 2 | public int getNumber(String[] state) { 3 | boolean atLeastOneHappy = false; 4 | 5 | for (int i = 0; i < state.length; i++) { 6 | String s = state[i]; 7 | 8 | for (int j = 0; j < s.length(); j++) { 9 | if (s.charAt(j) == 'H') { 10 | atLeastOneHappy = true; 11 | if (j < s.length() - 1 && s.charAt(j+1) == 'H') { 12 | return 0; 13 | } else if (j > 0 && s.charAt(j-1) == 'H') { 14 | return 0; 15 | } else if (i > 0 && state[i-1].charAt(j) == 'H') { 16 | return 0; 17 | } else if (i < state.length - 1 && state[i+1].charAt(j) == 'H') { 18 | return 0; 19 | } 20 | } 21 | } 22 | } 23 | 24 | return atLeastOneHappy ? 1 : 2; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /leetcode/AddDigits.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/add-digits/description/ 4 | // 258. Add Digits 5 | 6 | import java.io.PrintWriter; 7 | import java.util.*; 8 | 9 | public class AddDigits { 10 | 11 | public int addDigits(int num) { 12 | while (num > 9) { 13 | int curRes = 0; 14 | int cur = num; 15 | while (cur > 0) { 16 | curRes += cur % 10; 17 | cur /= 10; 18 | } 19 | num = curRes; 20 | } 21 | return num; 22 | } 23 | 24 | public void solve() { 25 | Scanner in = new Scanner(System.in); 26 | PrintWriter out = new PrintWriter(System.out); 27 | int[] test = {99, 25, 999956, 1, 0, 20, 15, 959}; 28 | for (int x: test) 29 | out.println(String.format("%s - %s", x, addDigits(x))); 30 | out.close(); 31 | } 32 | 33 | public static void main(String[] args) { 34 | new AddDigits().solve(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /leetcode/GroupAnagrams.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/group-anagrams/description/ 4 | // 49. Group Anagrams 5 | 6 | import java.util.*; 7 | 8 | class GroupAnagrams { 9 | public List> groupAnagrams(String[] strs) { 10 | Map> map = new HashMap(); 11 | List strings = new ArrayList(); 12 | 13 | for (int i = 0; i < strs.length; i++) { 14 | char[] chr = strs[i].toCharArray(); 15 | Arrays.sort(chr); 16 | String s = String.valueOf(chr); 17 | 18 | if (!map.containsKey(s)) { 19 | map.put(s, new ArrayList()); 20 | strings.add(s); 21 | } 22 | 23 | map.get(s).add(strs[i]); 24 | } 25 | 26 | List> result = new ArrayList(); 27 | for (String s : strings) 28 | result.add(map.get(s)); 29 | 30 | return result; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /TopCoder/srm660div2/test/PrivateD2partyTest.java: -------------------------------------------------------------------------------- 1 | import org.junit.jupiter.api.Test; 2 | import static org.junit.jupiter.api.Assertions.assertEquals; 3 | 4 | public class PrivateD2partyTest { 5 | 6 | @Test 7 | public void test0() { 8 | int[] a = new int[]{0, 1}; 9 | assertEquals(2, new PrivateD2party().getsz(a)); 10 | } 11 | 12 | @Test 13 | public void test1() { 14 | int[] a = new int[]{1, 0}; 15 | assertEquals(1, new PrivateD2party().getsz(a)); 16 | } 17 | 18 | @Test 19 | public void test2() { 20 | int[] a = new int[]{1, 0, 3, 2}; 21 | assertEquals(2, new PrivateD2party().getsz(a)); 22 | } 23 | 24 | @Test 25 | public void test3() { 26 | int[] a = new int[]{5, 2, 2, 4, 5, 0}; 27 | assertEquals(5, new PrivateD2party().getsz(a)); 28 | } 29 | 30 | @Test 31 | public void test4() { 32 | int[] a = new int[]{3, 2, 1, 0, 5, 4}; 33 | assertEquals(3, new PrivateD2party().getsz(a)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /leetcode/FindLargestValueInEachTreeRow.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/find-largest-value-in-each-tree-row/description/ 4 | // 515. Find Largest Value in Each Tree Row 5 | 6 | import java.util.*; 7 | 8 | class FindLargestValueInEachTreeRow { 9 | class TreeNode { 10 | int val; 11 | TreeNode left; 12 | TreeNode right; 13 | TreeNode(int x) { val = x; } 14 | } 15 | 16 | List res; 17 | 18 | public List largestValues(TreeNode root) { 19 | res = new ArrayList(); 20 | rec(root, 0); 21 | return res; 22 | } 23 | 24 | public void rec(TreeNode node, int level) { 25 | if (node == null) 26 | return; 27 | 28 | if (res.size() == level) 29 | res.add(node.val); 30 | else 31 | res.set(level, Math.max(node.val, res.get(level))); 32 | 33 | rec(node.left, level + 1); 34 | rec(node.right, level + 1); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /algorithms/heaps/SortIncreasingDecreasingArray.java: -------------------------------------------------------------------------------- 1 | package algorithms.heaps; 2 | 3 | import java.util.*; 4 | 5 | import static algorithms.heaps.MergeSortedArrays.mergeSortedArrays; 6 | 7 | public class SortIncreasingDecreasingArray { 8 | public static List sort(List nums) { 9 | List> sortedArrays = new ArrayList(); 10 | 11 | int ind = 0; 12 | boolean isIncreasing = true; 13 | 14 | for (int i = 1; i <= nums.size(); i++) { 15 | if (i == nums.size() || (nums.get(i - 1) < nums.get(i) && !isIncreasing) || (nums.get(i - 1) >= nums.get(i) && isIncreasing)) { 16 | List cur = nums.subList(ind, i); 17 | 18 | if (!isIncreasing) 19 | Collections.reverse(cur); 20 | 21 | sortedArrays.add(cur); 22 | isIncreasing = !isIncreasing; 23 | ind = i; 24 | } 25 | } 26 | 27 | return mergeSortedArrays(sortedArrays); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /algorithms/strings/test/IsUniqueTest.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | import static algorithms.strings.IsUnique.*; 4 | import static org.junit.Assert.assertEquals; 5 | 6 | public class IsUniqueTest { 7 | @Test 8 | public void mainTest() { 9 | String str1 = "alibek"; 10 | String str2 = "alibeka"; 11 | String str3 = "alibekzcvcv"; 12 | String str4 = "alibekdtyv"; 13 | 14 | assertEquals(true, isUnique(str1)); 15 | assertEquals(false, isUnique(str2)); 16 | assertEquals(false, isUnique(str3)); 17 | assertEquals(true, isUnique(str4)); 18 | 19 | assertEquals(true, isUnique1(str1)); 20 | assertEquals(false, isUnique1(str2)); 21 | assertEquals(false, isUnique1(str3)); 22 | assertEquals(true, isUnique1(str4)); 23 | 24 | assertEquals(true, isUnique2(str1)); 25 | assertEquals(false, isUnique2(str2)); 26 | assertEquals(false, isUnique2(str3)); 27 | assertEquals(true, isUnique2(str4)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /algorithms/linked_lists/Intersection.java: -------------------------------------------------------------------------------- 1 | package algorithms.linked_lists; 2 | 3 | public class Intersection { 4 | public static Node intersection(Node head1, Node head2) { 5 | if (head1 == null || head2 == null) 6 | return null; 7 | 8 | int size1 = Node.getLength(head1); 9 | int size2 = Node.getLength(head2); 10 | 11 | if (size1 == size2) { 12 | return head1 == head2 ? head1 : null; 13 | } 14 | 15 | Node node1 = size1 < size2 ? head1 : head2; // shorter linked list 16 | Node node2 = size2 > size1 ? head2 : head1; // longer linked list 17 | 18 | while (size2 != size1) { 19 | node2 = node2.next; 20 | size2--; 21 | } 22 | 23 | while (node1 != node2 && node1 != null && node2 != null) { 24 | node1 = node1.next; 25 | node2 = node2.next; 26 | } 27 | 28 | if (node1 == null || node2 == null) 29 | return null; 30 | 31 | return node1; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /leetcode/IntersectionOfTwoArraysII.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/intersection-of-two-arrays-ii/ 4 | // 350. Intersection of Two Arrays II 5 | 6 | import java.util.*; 7 | 8 | public class IntersectionOfTwoArraysII { 9 | public int[] intersect(int[] nums1, int[] nums2) { 10 | Arrays.sort(nums1); 11 | Arrays.sort(nums2); 12 | int ind1 = 0; 13 | int ind2 = 0; 14 | 15 | List list = new ArrayList(); 16 | 17 | while (ind1 < nums1.length && ind2 < nums2.length) { 18 | if (nums1[ind1] == nums2[ind2]) { 19 | list.add(nums1[ind1]); 20 | ind1++; 21 | ind2++; 22 | } else if (nums1[ind1] < nums2[ind2]) 23 | ind1++; 24 | else 25 | ind2++; 26 | } 27 | 28 | int[] arr = new int[list.size()]; 29 | for (int i = 0; i < list.size(); i++) 30 | arr[i] = list.get(i); 31 | 32 | return arr; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /leetcode/SortColors.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/sort-colors/description/ 4 | // 75. Sort Colors 5 | 6 | public class SortColors { 7 | public void sortColors(int[] nums) { 8 | int n = nums.length; 9 | for (int i = 1; i < n; i++) { 10 | if (nums[i] == 0) { 11 | int j = i; 12 | while (j > 0 && nums[j - 1] != 0) { 13 | int t = nums[j]; 14 | nums[j] = nums[j - 1]; 15 | nums[j - 1] = t; 16 | j--; 17 | } 18 | } 19 | } 20 | 21 | for (int i = n - 2; i >= 0; i--) { 22 | if (nums[i] == 2) { 23 | int j = i; 24 | while (j < n - 1 && nums[j + 1] != 2) { 25 | int t = nums[j]; 26 | nums[j] = nums[j + 1]; 27 | nums[j + 1] = t; 28 | j++; 29 | } 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /TopCoder/srm653div2/test/CountryGroupTest.java: -------------------------------------------------------------------------------- 1 | import org.junit.jupiter.api.Test; 2 | import static org.junit.jupiter.api.Assertions.assertEquals; 3 | 4 | public class CountryGroupTest { 5 | 6 | @Test 7 | public void test0() { 8 | int[] a = new int[]{2, 2, 3, 3, 3}; 9 | assertEquals(2, new CountryGroup().solve(a)); 10 | } 11 | 12 | @Test 13 | public void test1() { 14 | int[] a = new int[]{1, 1, 1, 1, 1}; 15 | assertEquals(5, new CountryGroup().solve(a)); 16 | } 17 | 18 | @Test 19 | public void test2() { 20 | int[] a = new int[]{3, 3}; 21 | assertEquals(-1, new CountryGroup().solve(a)); 22 | } 23 | 24 | @Test 25 | public void test3() { 26 | int[] a = new int[]{4, 4, 4, 4, 1, 1, 2, 2, 3, 3, 3}; 27 | assertEquals(5, new CountryGroup().solve(a)); 28 | } 29 | 30 | @Test 31 | public void test4() { 32 | int[] a = new int[]{2, 1, 2, 2, 1, 2}; 33 | assertEquals(-1, new CountryGroup().solve(a)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /leetcode/ConvertSortedArrayToBinarySearchTree.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/ 4 | // 108. Convert Sorted Array to Binary Search Tree 5 | 6 | public class ConvertSortedArrayToBinarySearchTree { 7 | public TreeNode sortedArrayToBST(int[] nums) { 8 | return rec(nums, 0, nums.length - 1); 9 | } 10 | 11 | private TreeNode rec(int[] nums, int left, int right) { 12 | if (left == right) 13 | return new TreeNode(nums[left]); 14 | 15 | if (left > right) 16 | return null; 17 | 18 | int mid = left + (right - left) / 2; 19 | TreeNode node = new TreeNode(nums[mid]); 20 | 21 | node.left = rec(nums, left, mid - 1); 22 | node.right = rec(nums, mid + 1, right); 23 | 24 | return node; 25 | } 26 | 27 | public class TreeNode { 28 | int val; 29 | TreeNode left; 30 | TreeNode right; 31 | TreeNode(int x) { val = x; } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /algorithms/arrays/LookAndSaySequence.java: -------------------------------------------------------------------------------- 1 | package algorithms.arrays; 2 | 3 | import java.util.*; 4 | 5 | public class LookAndSaySequence { 6 | public static List> getLookAndSaySequence(int n) { 7 | if (n == 0) 8 | return new ArrayList<>(); 9 | 10 | assert n >= 0; 11 | 12 | List> res = new ArrayList<>(); 13 | res.add(new ArrayList<>(Arrays.asList(1))); 14 | 15 | for (int i = 0; i < n - 1; i++) { 16 | List cur = new ArrayList<>(); 17 | List list = res.get(res.size() - 1); 18 | int m = list.size(), j = 0; 19 | 20 | while (j < m) { 21 | int k = j + 1; 22 | while (k < m && list.get(j) == list.get(k)) 23 | k++; 24 | 25 | cur.add(k - j); 26 | cur.add(list.get(j)); 27 | 28 | j = k; 29 | } 30 | 31 | res.add(cur); 32 | } 33 | 34 | return res; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /algorithms/strings/URLify.java: -------------------------------------------------------------------------------- 1 | package algorithms.strings; 2 | 3 | /* 4 | Replace all spaces in a string with "%20" 5 | */ 6 | 7 | public class URLify { 8 | public static String convert(char[] c, int trueLength) { 9 | StringBuilder sb = new StringBuilder(); 10 | for (int i = 0; i < trueLength; i++) { 11 | if (c[i] != ' ') 12 | sb.append(c[i]); 13 | else 14 | sb.append("%20"); 15 | } 16 | 17 | return sb.toString(); 18 | } 19 | 20 | public static String convert1(char[] c, int trueLength) { 21 | int end = c.length - 1; 22 | 23 | for (int i = trueLength - 1; i >= 0; i--) { 24 | if (c[i] == ' ') { 25 | c[end] = '0'; 26 | c[end - 1] = '2'; 27 | c[end - 2] = '%'; 28 | end -= 3; 29 | } else { 30 | c[end] = c[i]; 31 | end--; 32 | } 33 | } 34 | 35 | return String.valueOf(c); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /leetcode/MinimumTimeDifference.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/minimum-time-difference/description/ 4 | // 539. Minimum Time Difference 5 | 6 | import java.util.*; 7 | 8 | public class MinimumTimeDifference { 9 | public int findMinDifference(List timePoints) { 10 | int min = Integer.MAX_VALUE; 11 | 12 | Collections.sort(timePoints); 13 | timePoints.add(timePoints.get(0)); 14 | 15 | for (int i = 0; i < timePoints.size() - 1; i++) 16 | min = Math.min(min, diff(timePoints.get(i), timePoints.get(i + 1))); 17 | 18 | return min; 19 | } 20 | 21 | private int diff(String t1, String t2) { 22 | int min1 = timeToMin(t1); 23 | int min2 = timeToMin(t2); 24 | int res = Math.abs(min1 - min2); 25 | return Math.min(res, 1440 - res); 26 | } 27 | 28 | private int timeToMin(String t) { 29 | String[] time = t.split(":"); 30 | return Integer.parseInt(time[0]) * 60 + Integer.parseInt(time[1]); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /algorithms/sorting/QuickSort.java: -------------------------------------------------------------------------------- 1 | package algorithms.sorting; 2 | 3 | public class QuickSort { 4 | public static void sort(int[] arr) { 5 | quickSort(arr, 0, arr.length - 1); 6 | } 7 | 8 | private static void quickSort(int[] arr, int l, int r) { 9 | if (r <= l) 10 | return; 11 | 12 | int ind = partition(arr, l, r); 13 | 14 | quickSort(arr, l, ind - 1); 15 | quickSort(arr, ind + 1, r); 16 | } 17 | 18 | private static int partition(int[] arr, int l, int r) { 19 | int pivot = arr[r]; 20 | int i = 0; 21 | int ind = l; 22 | 23 | while (ind < r) { 24 | if (arr[ind] < pivot) { 25 | swap(arr, ind,l + i); 26 | i++; 27 | } 28 | ind++; 29 | } 30 | swap(arr, l + i, r); 31 | 32 | return l + i; 33 | } 34 | 35 | private static void swap(int[] arr, int i, int j) { 36 | int t = arr[i]; 37 | arr[i] = arr[j]; 38 | arr[j] = t; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /leetcode/NumberOfCornerRectangles.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/number-of-corner-rectangles/description/ 4 | // 751. Number Of Corner Rectangles 5 | 6 | public class NumberOfCornerRectangles { 7 | public int countCornerRectangles(int[][] grid) { 8 | int n = grid.length; 9 | if (n == 0) 10 | return 0; 11 | int m = grid[0].length; 12 | 13 | int res = 0; 14 | 15 | for (int i = 1; i < n; i++) { 16 | for (int j = 1; j < m; j++) { 17 | if (grid[i][j] == 1) { 18 | for (int d1 = 1; i - d1 >= 0; d1++) { 19 | if (grid[i - d1][j] == 1) { 20 | for (int d2 = 1; j - d2 >= 0; d2++) 21 | if (grid[i][j - d2] == 1 && grid[i - d1][j - d2] == 1) 22 | res++; 23 | } 24 | } 25 | } 26 | } 27 | } 28 | 29 | return res; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /leetcode/ValidParentheses.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/valid-parentheses 4 | // 20. Valid Parentheses 5 | 6 | import java.util.*; 7 | 8 | class ValidParentheses { 9 | 10 | public boolean isPair(char br1, char br2) { 11 | return ( 12 | (br1 == '{' && br2 == '}') || 13 | (br1 == '[' && br2 == ']') || 14 | (br1 == '(' && br2 == ')') 15 | ); 16 | } 17 | 18 | public boolean isValid(String s) { 19 | Stack stack = new Stack(); 20 | 21 | for (int i = 0; i < s.length(); i++) { 22 | char c = s.charAt(i); 23 | if (c == '(' || c == '{' || c == '[') 24 | stack.push(c); 25 | else { 26 | if (stack.isEmpty()) 27 | return false; 28 | 29 | if (!isPair(stack.pop(), c)) 30 | return false; 31 | } 32 | } 33 | 34 | return stack.isEmpty(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /leetcode/BinaryTreePreorderTraversalIterative.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/binary-tree-preorder-traversal/description/ 4 | // 144. Binary Tree Preorder Traversal 5 | 6 | import java.util.*; 7 | 8 | public class BinaryTreePreorderTraversalIterative { 9 | public List preorderTraversal(TreeNode root) { 10 | if (root == null) 11 | return new ArrayList<>(); 12 | 13 | List res = new ArrayList<>(); 14 | Stack st = new Stack<>(); 15 | 16 | st.add(root); 17 | while (!st.isEmpty()) { 18 | TreeNode cur = st.pop(); 19 | res.add(cur.val); 20 | 21 | if (cur.right != null) 22 | st.add(cur.right); 23 | 24 | if (cur.left != null) 25 | st.add(cur.left); 26 | } 27 | 28 | return res; 29 | } 30 | public class TreeNode { 31 | int val; 32 | TreeNode left; 33 | TreeNode right; 34 | TreeNode(int x) { val = x; } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /leetcode/IslandPerimeter.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/island-perimeter/description/ 4 | // 463. Island Perimeter 5 | 6 | class IslandPerimeter { 7 | public int islandPerimeter(int[][] grid) { 8 | int ones = 0, total = 0, shares = 0; 9 | int[] dx = {1, -1, 0, 0}, dy = {0, 0, 1, -1}; 10 | 11 | for (int i = 0; i < grid.length; i++) { 12 | for (int j = 0; j < grid[0].length; j++) { 13 | if (grid[i][j] == 1) { 14 | ones++; 15 | 16 | for (int k = 0; k < 4; k++) { 17 | int newx = i + dx[k]; 18 | int newy = j + dy[k]; 19 | 20 | if (newx >= 0 && newx < grid.length && newy >= 0 && newy < grid[0].length && grid[newx][newy] == 1) 21 | shares++; 22 | } 23 | } 24 | } 25 | } 26 | 27 | total = 4 * ones - shares; 28 | 29 | return total; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /leetcode/SecondMinimumNodeInABinaryTree.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/description/ 4 | // 671. Second Minimum Node In a Binary Tree 5 | 6 | 7 | class SecondMinimumNodeInABinaryTree { 8 | public class TreeNode { 9 | int val; 10 | TreeNode left; 11 | TreeNode right; 12 | TreeNode(int x) { val = x; } 13 | } 14 | 15 | int min, init; 16 | 17 | public int findSecondMinimumValue(TreeNode root) { 18 | if (root == null || root.left == null || root.right == null) 19 | return -1; 20 | 21 | min = -1; 22 | init = root.val; 23 | 24 | traverse(root); 25 | 26 | return min; 27 | } 28 | 29 | public void traverse(TreeNode v) { 30 | if (v == null) 31 | return; 32 | 33 | if (v.val > init && (min == -1 || min > v.val)) 34 | min = v.val; 35 | 36 | traverse(v.left); 37 | traverse(v.right); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /TopCoder/srm644div2/test/OkonomiyakiShopTest.java: -------------------------------------------------------------------------------- 1 | import org.junit.jupiter.api.Test; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | public class OkonomiyakiShopTest { 6 | @Test 7 | public void test0() { 8 | int[] osize = new int[]{1, 4, 6, 7, 9}; 9 | int K = 3; 10 | assertEquals(6, new OkonomiyakiShop().count(osize, K)); 11 | } 12 | 13 | @Test 14 | public void test1() { 15 | int[] osize = new int[]{1, 1, 3, 3, 3}; 16 | int K = 2; 17 | assertEquals(10, new OkonomiyakiShop().count(osize, K)); 18 | } 19 | 20 | @Test 21 | public void test2() { 22 | int[] osize = new int[]{1, 5, 9, 14, 20}; 23 | int K = 3; 24 | assertEquals(0, new OkonomiyakiShop().count(osize, K)); 25 | } 26 | 27 | @Test 28 | public void test3() { 29 | int[] osize = new int[]{7, 2, 6, 3, 4, 2, 7, 8, 3, 4, 9, 1, 8, 4, 3, 7, 5, 2, 1, 9, 9, 4, 5}; 30 | int K = 6; 31 | assertEquals(234, new OkonomiyakiShop().count(osize, K)); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /ProjectEuler/src/python/010 Summation of primes.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def is_prime(x): 4 | if x == 1: 5 | return False 6 | 7 | if x < 4: 8 | return True 9 | 10 | if x % 2 == 0: 11 | return False 12 | 13 | if x < 9: 14 | return True 15 | 16 | if x % 3 == 0: 17 | return False 18 | else: 19 | # all prime number can be written in the form of 6k+1 or 6k-1 20 | r = math.floor(math.sqrt(x)) 21 | f = 5 22 | while f <= r: 23 | if x % f == 0: # 6k-1 24 | return False 25 | 26 | if x % (f+2) == 0: # 6k+1 27 | return False 28 | 29 | f += 6 # get next 6k 30 | 31 | return True 32 | 33 | 34 | def summation_of_primes(x): 35 | total = 2 36 | if x < 3: 37 | return total 38 | 39 | cur = 3 40 | while cur < x: 41 | if is_prime(cur): 42 | total += cur 43 | cur += 2 44 | 45 | return total 46 | 47 | if __name__ == "__main__": 48 | print(summation_of_primes(2000000)) 49 | -------------------------------------------------------------------------------- /algorithms/heaps/test/MergeSortedArraysTest.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | import static algorithms.heaps.MergeSortedArrays.mergeSortedArrays; 8 | import static org.junit.Assert.assertEquals; 9 | 10 | public class MergeSortedArraysTest { 11 | @Test 12 | public void test1() { 13 | List l1 = new ArrayList<>(Arrays.asList(1,3,4,7,8,99)); 14 | List l2 = new ArrayList<>(Arrays.asList(11,12,33,48)); 15 | List l3 = new ArrayList<>(Arrays.asList(10,21,38,41)); 16 | List l4 = new ArrayList<>(Arrays.asList(1,2,3,4)); 17 | List> mainList = new ArrayList(); 18 | mainList.add(l1); 19 | mainList.add(l2); 20 | mainList.add(l3); 21 | mainList.add(l4); 22 | 23 | List expectedResult = new ArrayList<>(Arrays.asList(1,1,2,3,3,4,4,7,8,10,11,12,21,33,38,41,48,99)); 24 | 25 | assertEquals(expectedResult, mergeSortedArrays(mainList)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /leetcode/BestMeetingPoint.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/best-meeting-point/description/ 4 | // 296. Best Meeting Point 5 | 6 | import java.util.*; 7 | 8 | class BestMeetingPoint { 9 | public int minTotalDistance(int[][] grid) { 10 | List row = new ArrayList<>(); 11 | List col = new ArrayList<>(); 12 | 13 | int rows = grid.length, cols = grid[0].length; 14 | 15 | for (int i = 0; i < rows; i++) 16 | for (int j = 0; j < cols; j++) 17 | if (grid[i][j] == 1) 18 | row.add(i); 19 | 20 | for (int j = 0; j < cols; j++) 21 | for (int i = 0; i < rows; i++) 22 | if (grid[i][j] == 1) 23 | col.add(j); 24 | 25 | return dist(col) + dist(row); 26 | } 27 | 28 | private int dist(List list) { 29 | int i = 0, j = list.size() - 1, res = 0; 30 | 31 | while (i < j) 32 | res += list.get(j--) - list.get(i++); 33 | 34 | return res; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /leetcode/GuessNumberHigherOrLower.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/guess-number-higher-or-lower/description/ 4 | // 374. Guess Number Higher or Lower 5 | 6 | /* The guess API is defined in the parent class GuessGame. 7 | @param num, your guess 8 | @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 9 | int guess(int num); */ 10 | 11 | // dumb class implementation for the sake of having 12 | class GuessGame { 13 | public int guess(int m) { 14 | return 0; 15 | } 16 | 17 | } 18 | 19 | public class GuessNumberHigherOrLower extends GuessGame { 20 | public int guessNumber(int n) { 21 | int left = 1, right = n; 22 | while (left < right) { 23 | int m = left + (right - left) / 2; 24 | int cur = guess(m); 25 | if (cur < 0) 26 | right = m; 27 | else if (cur > 0) 28 | left = m + 1; 29 | else 30 | return m; 31 | } 32 | 33 | return left; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /leetcode/PrimeNumberOfSetBitsInBinaryRepresentation.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // 762. Prime Number of Set Bits in Binary Representation 4 | 5 | import java.util.*; 6 | 7 | public class PrimeNumberOfSetBitsInBinaryRepresentation { 8 | public int countPrimeSetBits(int L, int R) { 9 | int count = 0; 10 | 11 | Set primes = new HashSet(); 12 | 13 | for (int i = L; i <= R; i++) { 14 | int t = i, cur = 0; 15 | while (t > 0) { 16 | if (t % 2 == 1) 17 | cur++; 18 | t /= 2; 19 | } 20 | 21 | if (primes.contains(cur) || isPrime(cur)) { 22 | count++; 23 | primes.add(cur); 24 | } 25 | } 26 | 27 | return count; 28 | } 29 | 30 | private boolean isPrime(int x) { 31 | if (x < 2) 32 | return false; 33 | 34 | for (int i = 2; i * i <= x; i++) 35 | if (x % i == 0) 36 | return false; 37 | 38 | return true; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /leetcode/StudentAttendanceRecordII.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/student-attendance-record-ii/description/ 4 | // 552. Student Attendance Record II 5 | 6 | public class StudentAttendanceRecordII { 7 | public int checkRecord(int n) { 8 | long a0l0 = 1, a0l1 = 0, a0l2 = 0; 9 | long a1l0 = 0, a1l1 = 0, a1l2 = 0; 10 | 11 | long mod = 1000000007; 12 | 13 | for (int i = 0; i < n; i++) { 14 | long next_a0l0 = (a0l0 + a0l1 + a0l2) % mod; 15 | long next_a0l1 = a0l0; 16 | long next_a0l2 = a0l1; 17 | 18 | long next_a1l0 = (a0l0 + a0l1 + a0l2 + a1l0 + a1l1 + a1l2) % mod; 19 | long next_a1l1 = a1l0; 20 | long next_a1l2 = a1l1; 21 | 22 | a0l0 = next_a0l0; 23 | a0l1 = next_a0l1; 24 | a0l2 = next_a0l2; 25 | a1l0 = next_a1l0; 26 | a1l1 = next_a1l1; 27 | a1l2 = next_a1l2; 28 | } 29 | 30 | return (int)((a0l0 + a0l1 + a0l2 + a1l0 + a1l1 + a1l2) % mod); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /leetcode/CheapestFlightsWithinKStops.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/cheapest-flights-within-k-stops/description/ 4 | // 787. Cheapest Flights Within K Stops 5 | 6 | import java.util.*; 7 | 8 | public class CheapestFlightsWithinKStops { 9 | public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) { 10 | int[] dist = new int[n]; // distance from src to all nodes in K stops 11 | int[] prev = new int[n]; // distance from src to all nodes in K-1 stops 12 | 13 | Arrays.fill(dist, Integer.MAX_VALUE / 2); // very big number, but the max, not to hit the boundaries 14 | Arrays.fill(prev, Integer.MAX_VALUE / 2); 15 | 16 | dist[src] = 0; 17 | prev[src] = 0; 18 | 19 | for (int i = 0; i <= K; i++) { 20 | for (int[] flight : flights) 21 | dist[flight[1]] = Math.min(dist[flight[1]], flight[2] + prev[flight[0]]); 22 | 23 | prev = dist; 24 | } 25 | 26 | return dist[dst] < Integer.MAX_VALUE / 2 ? dist[dst] : -1; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /leetcode/PopulatingNextRightPointersInEachNode.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/populating-next-right-pointers-in-each-node/description/ 4 | // 116. Populating Next Right Pointers in Each Node 5 | 6 | import java.util.*; 7 | 8 | public class PopulatingNextRightPointersInEachNode { 9 | public void connect(TreeLinkNode root) { 10 | List levels = new ArrayList<>(); 11 | rec(root, levels, 0); 12 | } 13 | 14 | private void rec(TreeLinkNode node, List levels, int cur) { 15 | if (node == null) 16 | return; 17 | 18 | if (levels.size() == cur) 19 | levels.add(node); 20 | else { 21 | node.next = levels.get(cur); 22 | levels.set(cur, node); 23 | } 24 | 25 | rec(node.right, levels, cur + 1); 26 | rec(node.left, levels, cur + 1); 27 | } 28 | 29 | public class TreeLinkNode { 30 | int val; 31 | TreeLinkNode left, right, next; 32 | TreeLinkNode(int x) { val = x; } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /leetcode/ClosestBinarySearchTreeValue.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/closest-binary-search-tree-value/description/ 4 | // 270. Closest Binary Search Tree Value 5 | 6 | public class ClosestBinarySearchTreeValue { 7 | double EPS = 1e-7; 8 | int min = Integer.MAX_VALUE; 9 | private double minDiff = Double.MAX_VALUE; 10 | 11 | public int closestValue(TreeNode root, double target) { 12 | rec(root, target); 13 | return min; 14 | } 15 | 16 | private void rec(TreeNode node, double target) { 17 | double diff = Math.abs(node.val * 1.0 - target); 18 | if (Math.abs(diff) < minDiff) { 19 | min = node.val; 20 | minDiff = diff; 21 | } 22 | 23 | if (node.left != null) 24 | rec(node.left, target); 25 | 26 | if (node.right != null) 27 | rec(node.right, target); 28 | } 29 | 30 | public class TreeNode { 31 | int val; 32 | TreeNode left; 33 | TreeNode right; 34 | TreeNode(int x) { val = x; } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /leetcode/EditDistance.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/edit-distance/description/ 4 | // 72. Edit Distance 5 | 6 | public class EditDistance { 7 | public int minDistance(String s1, String s2) { 8 | int n = s1.length(); 9 | int m = s2.length(); 10 | 11 | int[][] dp = new int[n + 1][m + 1]; 12 | 13 | // dp[i][j] - answer for first i chars from s1 and first j chars from s2 14 | 15 | for (int i = 1; i <= n; i++) 16 | dp[i][0] = i; // empty string to i len string - need to add i chars 17 | 18 | for (int j = 1; j <= m; j++) 19 | dp[0][j] = j; // empty string to j len string - need to add j chars 20 | 21 | for (int i = 1; i <= n; i++) 22 | for (int j = 1; j <= m; j++) 23 | if (s1.charAt(i - 1) == s2.charAt(j - 1)) 24 | dp[i][j] = dp[i - 1][j - 1]; 25 | else 26 | dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])) + 1; 27 | 28 | return dp[n][m]; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /leetcode/NumberOfBoomerangs.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/number-of-boomerangs/description/ 4 | // 447. Number of Boomerangs 5 | 6 | import java.util.*; 7 | 8 | public class NumberOfBoomerangs { 9 | public int numberOfBoomerangs(int[][] points) { 10 | int res = 0; 11 | int n = points.length; 12 | 13 | Map map = new HashMap(); // distance -> count 14 | 15 | for (int i = 0; i < n; i++) { 16 | for (int j = 0; j < n; j++) { 17 | 18 | if (i == j) 19 | continue; 20 | 21 | int d = dist(points[i], points[j]); 22 | map.put(d, map.getOrDefault(d, 0) + 1); 23 | } 24 | 25 | for (int val : map.values()) 26 | res += val * (val - 1); 27 | 28 | map.clear(); 29 | } 30 | 31 | return res; 32 | } 33 | 34 | private int dist(int[] p1, int[] p2) { 35 | int x = p1[0] - p2[0]; 36 | int y = p1[1] - p2[1]; 37 | return x * x + y * y; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /leetcode/RelativeRanks.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/relative-ranks/description/ 4 | // 506. Relative Ranks 5 | 6 | import java.util.*; 7 | 8 | public class RelativeRanks { 9 | public String[] findRelativeRanks(int[] nums) { 10 | int n = nums.length; // positive 11 | String[] res = new String[n]; 12 | int[] sorted = nums.clone(); 13 | Arrays.sort(sorted); 14 | Map map = new HashMap(); 15 | for (int i = 0; i < n; i++) 16 | map.put(sorted[i], i); 17 | 18 | for (int i = 0; i < n; i++) { 19 | int pos = map.get(nums[i]); 20 | 21 | if (nums[i] == sorted[n - 1]) 22 | res[i] = "Gold Medal"; 23 | else if (n > 1 && nums[i] == sorted[n - 2]) 24 | res[i] = "Silver Medal"; 25 | else if (n > 2 && nums[i] == sorted[n - 3]) 26 | res[i] = "Bronze Medal"; 27 | else 28 | res[i] = String.valueOf(n - pos); 29 | } 30 | 31 | return res; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /TopCoder/srm646div2/test/TheConsecutiveIntegersDivTwoTest.java: -------------------------------------------------------------------------------- 1 | import org.junit.jupiter.api.Test; 2 | import static org.junit.jupiter.api.Assertions.assertEquals; 3 | 4 | public class TheConsecutiveIntegersDivTwoTest { 5 | 6 | @Test 7 | public void test0() { 8 | int[] numbers = new int[]{4, 47, 7}; 9 | int k = 2; 10 | assertEquals(2, new TheConsecutiveIntegersDivTwo().find(numbers, k)); 11 | } 12 | 13 | @Test 14 | public void test1() { 15 | int[] numbers = new int[]{1, 100}; 16 | int k = 1; 17 | assertEquals(0, new TheConsecutiveIntegersDivTwo().find(numbers, k)); 18 | } 19 | 20 | @Test 21 | public void test2() { 22 | int[] numbers = new int[]{-96, -53, 82, -24, 6, -75}; 23 | int k = 2; 24 | assertEquals(20, new TheConsecutiveIntegersDivTwo().find(numbers, k)); 25 | } 26 | 27 | @Test 28 | public void test3() { 29 | int[] numbers = new int[]{64, -31, -56}; 30 | int k = 2; 31 | assertEquals(24, new TheConsecutiveIntegersDivTwo().find(numbers, k)); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /TopCoder/srm650div2/test/TaroJiroDividingTest.java: -------------------------------------------------------------------------------- 1 | import org.junit.jupiter.api.Test; 2 | import static org.junit.jupiter.api.Assertions.assertEquals; 3 | 4 | public class TaroJiroDividingTest { 5 | 6 | @Test 7 | public void test0() { 8 | int A = 8; 9 | int B = 4; 10 | assertEquals(3, new TaroJiroDividing().getNumber(A, B)); 11 | } 12 | 13 | @Test 14 | public void test1() { 15 | int A = 4; 16 | int B = 7; 17 | assertEquals(0, new TaroJiroDividing().getNumber(A, B)); 18 | } 19 | 20 | @Test 21 | public void test2() { 22 | int A = 12; 23 | int B = 12; 24 | assertEquals(3, new TaroJiroDividing().getNumber(A, B)); 25 | } 26 | 27 | @Test 28 | public void test3() { 29 | int A = 24; 30 | int B = 96; 31 | assertEquals(4, new TaroJiroDividing().getNumber(A, B)); 32 | } 33 | 34 | @Test 35 | public void test4() { 36 | int A = 1000000000; 37 | int B = 999999999; 38 | assertEquals(0, new TaroJiroDividing().getNumber(A, B)); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /leetcode/FlipGameII.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/flip-game-ii/description/ 4 | // 294. Flip Game II 5 | 6 | import java.util.*; 7 | 8 | public class FlipGameII { 9 | public boolean canWin(String s) { 10 | return canWin(s.toCharArray(), new HashMap()); 11 | } 12 | 13 | private boolean canWin(char[] c, Map cache) { 14 | String s = new String(c); 15 | Boolean existing = cache.get(s); 16 | if (existing != null) 17 | return existing; 18 | 19 | for (int i = 0; i < c.length - 1; i++) { 20 | if (c[i] == '+' && c[i + 1] == '+') { 21 | c[i] = '-'; 22 | c[i + 1] = '-'; 23 | boolean subGame = canWin(c, cache); 24 | c[i] = '+'; 25 | c[i + 1] = '+'; 26 | 27 | if (!subGame) { 28 | cache.put(s, true); 29 | return true; 30 | } 31 | } 32 | } 33 | 34 | cache.put(s, false); 35 | return false; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /leetcode/ReverseVowelsOfAString.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | // https://leetcode.com/problems/reverse-vowels-of-a-string/description/ 4 | // 345. Reverse Vowels of a String 5 | 6 | import java.util.*; 7 | 8 | class ReverseVowelsOfAString { 9 | public String reverseVowels(String s) { 10 | Set set = new HashSet(); 11 | set.add('A'); set.add('a'); 12 | set.add('E'); set.add('e'); 13 | set.add('U'); set.add('u'); 14 | set.add('I'); set.add('i'); 15 | set.add('O'); set.add('o'); 16 | 17 | int left = 0, right = s.length() - 1; 18 | char[] c = s.toCharArray(); 19 | 20 | while (left < right) { 21 | while (left < right && !set.contains(c[left])) left++; 22 | while (right > left && !set.contains(c[right])) right--; 23 | 24 | char temp = c[left]; 25 | c[left] = c[right]; 26 | c[right] = temp; 27 | 28 | left++; 29 | right--; 30 | } 31 | 32 | return String.valueOf(c); 33 | } 34 | } 35 | --------------------------------------------------------------------------------