diff --git a/README.md b/README.md index 2bf93af3b..202ae6ff8 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ LeetCode |1825|[Finding MK Average](https://leetcode.com/problems/finding-mk-average/) | [C++](./algorithms/cpp/findingMkAverage/FindingMkAverage.cpp)|Hard| |1824|[Minimum Sideway Jumps](https://leetcode.com/problems/minimum-sideway-jumps/) | [C++](./algorithms/cpp/minimumSidewayJumps/MinimumSidewayJumps.cpp)|Medium| |1823|[Find the Winner of the Circular Game](https://leetcode.com/problems/find-the-winner-of-the-circular-game/) | [C++](./algorithms/cpp/findTheWinnerOfTheCircularGame/FindTheWinnerOfTheCircularGame.cpp)|Medium| -|1822|[Sign of the Product of an Array](https://leetcode.com/problems/sign-of-the-product-of-an-array/) | [C++](./algorithms/cpp/signOfTheProductOfAnArray/SignOfTheProductOfAnArray.cpp)|Easy| +|1822|[Sign of the Product of an Array](https://leetcode.com/problems/sign-of-the-product-of-an-array/) | [C++](./algorithms/cpp/signOfTheProductOfAnArray/SignOfTheProductOfAnArray.cpp), [Java](./algorithms/java/src/SignOfTheProductOfAnArray/SignOfTheProductOfAnArray.java)|Easy| |1819|[Number of Different Subsequences GCDs](https://leetcode.com/problems/number-of-different-subsequences-gcds/) | [C++](./algorithms/cpp/numberOfDifferentSubsequencesGcds/NumberOfDifferentSubsequencesGcds.cpp)|Hard| |1818|[Minimum Absolute Sum Difference](https://leetcode.com/problems/minimum-absolute-sum-difference/) | [C++](./algorithms/cpp/minimumAbsoluteSumDifference/MinimumAbsoluteSumDifference.cpp)|Medium| |1817|[Finding the Users Active Minutes](https://leetcode.com/problems/finding-the-users-active-minutes/) | [C++](./algorithms/cpp/findingTheUsersActiveMinutes/FindingTheUsersActiveMinutes.cpp)|Medium| @@ -142,6 +142,7 @@ LeetCode |1524|[Number of Sub-arrays With Odd Sum](https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/) | [C++](./algorithms/cpp/numberOfSubArraysWithOddSum/NumberOfSubArraysWithOddSum.cpp)|Medium| |1523|[Count Odd Numbers in an Interval Range](https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/) | [C++](./algorithms/cpp/countOddNumbersInAnIntervalRange/CountOddNumbersInAnIntervalRange.cpp)|Easy| |1513|[Number of Substrings With Only 1s](https://leetcode.com/problems/number-of-substrings-with-only-1s/) | [C++](./algorithms/cpp/numberOfSubstringsWithOnly1s/NumberOfSubstringsWithOnly1s.cpp)|Medium| +|1502|[Can Make Arithmetic Progression From Sequence](https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/) | [Java](./algorithms/java/src/CanMakeArithmeticProgressionFromSequence/CanMakeArithmeticProgressionFromSequence.java)|Easy| |1470|[Shuffle the Array](https://leetcode.com/problems/shuffle-the-array/) | [C++](./algorithms/cpp/shuffleTheArray/ShuffleTheArray.cpp)|Easy| |1464|[Maximum Product of Two Elements in an Array](https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/) | [C++](./algorithms/cpp/maximumProductOfTwoElementsInAnArray/MaximumProductOfTwoElementsInAnArray.cpp)|Easy| |1460|[Make Two Arrays Equal by Reversing Sub-arrays](https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays/) | [C++](./algorithms/cpp/twoArraysEqualByReversingSubArrays/MakeTwoArraysEqualByReversingSubArrays.cpp)|Easy| @@ -149,8 +150,11 @@ LeetCode |1375|[Bulb Switcher III](https://leetcode.com/problems/bulb-switcher-iii) | [C++](./algorithms/cpp/bulbSwitcher/BulbSwitcher.III.cpp)|Medium| |1353|[Maximum Number of Events That Can Be Attended](https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/) | [C++](./algorithms/cpp/maximumNumberOfEventsThatCanBeAttended/MaximumNumberOfEventsThatCanBeAttended.cpp)|Medium| |1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance/) | [C++](./algorithms/cpp/filterRestaurantsByVeganFriendlyPriceAndDistance/FilterRestaurantsByVeganFriendlyPriceAndDistance.cpp)|Medium| +|1281|[Subtract the Product and Sum of Digits of an Integer](https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/) | [Java](./algorithms/java/src/SubtractTheProductAndSumOfDigitsOfAnInteger/SubtractTheProductAndSumOfDigitsOfAnInteger.java)|Easy| +|1249|[Minimum Remove to Make Valid Parentheses](https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/) | [Java](./algorithms/java/src/MinimumRemoveToMakeValidParentheses/MinimumRemoveToMakeValidParentheses.java)|Medium| |1207|[Unique Number of Occurrences](https://leetcode.com/problems/unique-number-of-occurrences/) | [C++](./algorithms/cpp/uniqueNumberOfOccurrences/Unique-Number-of-Occurrences.cpp)|Easy| |1170|[Compare Strings by Frequency of the Smallest Character](https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/) | [C++](./algorithms/cpp/compareStringsByFrequencyOfTheSmallestCharacter/CompareStringsByFrequencyOfTheSmallestCharacter.cpp)|Easy| +|1103|[Distribute Candies to People](https://leetcode.com/problems/distribute-candies-to-people/) | [Java](./algorithms/java/src/DistributeCandiesToPeople/DistributeCandiesToPeople.java)|Easy| |1071|[Greatest Common Divisor of Strings](https://leetcode.com/problems/greatest-common-divisor-of-strings/) | [C++](./algorithms/cpp/greatestCommonDivisorOfStrings/GreatestCommonDivisorOfStrings.cpp)|Easy| |1030|[Matrix Cells in Distance Order](https://leetcode.com/problems/matrix-cells-in-distance-order/) | [C++](./algorithms/cpp/matrixCellsInDistanceOrder/MatrixCellsInDistanceOrder.cpp)|Easy| |1029|[Two City Scheduling](https://leetcode.com/problems/two-city-scheduling/) | [C++](./algorithms/cpp/twoCityScheduling/TwoCityScheduling.cpp)|Easy| @@ -241,7 +245,7 @@ LeetCode |418|[SentenceScreenFitting](https://leetcode.com/problems/sentence-screen-fitting/) 🔒 | [C++](./algorithms/cpp/sentenceScreenFitting/sentenceScreenFitting.cpp)|Easy| |416|[Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum/description/) | [C++](./algorithms/cpp/partitionEqualSubsetSum/PartitionEqualSubsetSum.cpp)|Medium| |415|[Add Strings](https://leetcode.com/problems/add-strings/) | [C++](./algorithms/cpp/addStrings/AddStrings.cpp)|Easy| -|414|[Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | [C++](./algorithms/cpp/thirdMaximumNumber/ThirdMaximumNumber.cpp), [Python](./algorithms/python/ThirdMaximumNumber/thirdMax.py)|Easy| +|414|[Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | [C++](./algorithms/cpp/thirdMaximumNumber/ThirdMaximumNumber.cpp), [Python](./algorithms/python/ThirdMaximumNumber/thirdMax.py), [Java](./algorithms/java/src/ThirdMaximumNumber/ThirdMaximumNumber.java)|Easy| |413|[Arithmetic Slices](https://leetcode.com/problems/arithmetic-slices/) | [C++](./algorithms/cpp/arithmeticSlices/ArithmeticSlices.cpp)|Medium| |412|[Fizz Buzz](https://leetcode.com/problems/fizz-buzz/) | [C++](./algorithms/cpp/fizzBuzz/FizzBuzz.cpp)|Easy| |410|[Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum/) | [C++](./algorithms/cpp/splitArrayLargestSum/SplitArrayLargestSum.cpp)|Hard| @@ -260,7 +264,7 @@ LeetCode |395|[Longest Substring with At Least K Repeating Characters](https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/) | [C++](./algorithms/cpp/longestSubstringWithAtLeastKRepeatingCharacters/LongestSubstringWithAtLeastKRepeatingCharacters.cpp)|Medium| |394|[Decode String](https://leetcode.com/problems/decode-string/) | [C++](./algorithms/cpp/decodeString/DecodeString.cpp)|Medium| |393|[UTF-8 Validation](https://leetcode.com/problems/utf-8-validation/) | [C++](./algorithms/cpp/UTF8Validation/UTF8Validation.cpp)|Medium| -|392|[Is Subsequence](https://leetcode.com/problems/is-subsequence/) | [C++](./algorithms/cpp/isSubsequence/IsSubsequence.cpp)|Medium| +|392|[Is Subsequence](https://leetcode.com/problems/is-subsequence/) | [C++](./algorithms/cpp/isSubsequence/IsSubsequence.cpp), [Java](./algorithms/java/src/IsSubsequence/IsSubsequence.java)|Easy| |391|[Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/) | [C++](./algorithms/cpp/perfectRectangle/PerfectRectangle.cpp)|Hard| |390|[Elimination Game](https://leetcode.com/problems/elimination-game/) | [C++](./algorithms/cpp/eliminationGame/EliminationGame.cpp)|Medium| |389|[Find the Difference](https://leetcode.com/problems/find-the-difference/) | [C++](./algorithms/cpp/findTheDifference/FindTheDifference.cpp)|Easy| @@ -284,7 +288,7 @@ LeetCode |345|[Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./algorithms/cpp/reverseVowelsOfAString/reverseVowelsOfAString.cpp)|Easy| |344|[Reverse String](https://leetcode.com/problems/reverse-string/) | [C++](./algorithms/cpp/reverseString/ReverseString.cpp)|Easy| |343|[Integer Break](https://leetcode.com/problems/integer-break/) | [C++](./algorithms/cpp/integerBreak/IntegerBreak.cpp)|Medium| -|342|[Power of Four](https://leetcode.com/problems/power-of-four/) | [C++](./algorithms/cpp/powerOfFour/PowerOfFour.cpp)|Easy| +|342|[Power of Four](https://leetcode.com/problems/power-of-four/) | [C++](./algorithms/cpp/powerOfFour/PowerOfFour.cpp), [Java](./algorithms/java/src/PowerOfFour/PowerOfFour.java)|Easy| |341|[Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator/) | [C++](./algorithms/cpp/flattenNestedListIterator/FlattenNestedListIterator.cpp)|Medium| |338|[Counting Bits](https://leetcode.com/problems/counting-bits/) | [C++](./algorithms/cpp/countingBits/CountingBits.cpp)|Medium| |337|[House Robber III](https://leetcode.com/problems/house-robber-iii/) | [C++](./algorithms/cpp/houseRobber/houseRobberIII.cpp), [Python](./algorithms/python/HouseRobberIII/rob.py)|Medium| @@ -296,7 +300,7 @@ LeetCode |329|[Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/) | [C++](./algorithms/cpp/longestIncreasingPathInAMatrix/LongestIncreasingPathInAMatrix.cpp)|Medium| |328|[Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/) | [C++](./algorithms/cpp/oddEvenLinkedList/OddEvenLinkedList.cpp)|Easy| |327|[Count of Range Sum](https://leetcode.com/problems/count-of-range-sum/) | [C++](./algorithms/cpp/countOfRangeSum/CountOfRangeSum.cpp)|Hard| -|326|[Power of Three](https://leetcode.com/problems/power-of-three/) | [C++](./algorithms/cpp/powerOfThree/PowerOfThree.cpp)|Easy| +|326|[Power of Three](https://leetcode.com/problems/power-of-three/) | [C++](./algorithms/cpp/powerOfThree/PowerOfThree.cpp), [Java](./algorithms/java/src/PowerOfThree/PowerOfThree.java)|Easy| |324|[Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii/) | [C++](./algorithms/cpp/wiggleSort/WiggleSort.II.cpp)|Medium| |322|[Coin Change](https://leetcode.com/problems/coin-change/) | [C++](./algorithms/cpp/coinChange/coinChange.cpp)|Medium| |321|[Create Maximum Number](https://leetcode.com/problems/create-maximum-number/) | [C++](./algorithms/cpp/createMaximumNumber/CreateMaximumNumber.cpp)|Hard| @@ -347,7 +351,7 @@ LeetCode |234|[Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/)| [C++](./algorithms/cpp/palindromeLinkedList/PalindromeLinkedList.cpp)|Easy| |233|[Number of Digit One](https://leetcode.com/problems/number-of-digit-one/)| [C++](./algorithms/cpp/numberOfDigitOne/NumberOfDigitOne.cpp)|Medium| |232|[Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/)| [C++](./algorithms/cpp/implementQueueUsingStacks/ImplementQueueUsingStacks.cpp), [Java](./algorithms/java/src/myQueue/MyQueue.java)|Easy| -|231|[Power of Two](https://leetcode.com/problems/power-of-two/)| [C++](./algorithms/cpp/powerOfTwo/PowerOfTwo.cpp)|Easy| +|231|[Power of Two](https://leetcode.com/problems/power-of-two/)| [C++](./algorithms/cpp/powerOfTwo/PowerOfTwo.cpp), [Java](./algorithms/java/src/PowerOfTwo/PowerOfTwo.java)|Easy| |230|[Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/)| [C++](./algorithms/cpp/kthSmallestElementInaBST/KthSmallestElementInABst.cpp), [Python](./algorithms/python/KthSmallestElementInABST/kthSmallest.py)|Medium| |229|[Majority Element II](https://leetcode.com/problems/majority-element-ii/) | [C++](./algorithms/cpp/majorityElement/majorityElement.II.cpp)|Medium| |228|[Summary Ranges](https://leetcode.com/problems/summary-ranges/)| [C++](./algorithms/cpp/summaryRanges/SummaryRanges.cpp)|Easy| @@ -376,7 +380,7 @@ LeetCode |205|[Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/)| [C++](./algorithms/cpp/isomorphicStrings/IsomorphicStrings.cpp)|Easy| |204|[Count Primes](https://leetcode.com/problems/count-primes/)| [C++](./algorithms/cpp/countPrimes/CountPrimes.cpp)|Easy| |203|[Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/)| [C++](./algorithms/cpp/removeLinkedListElements/RemoveLinkedListElements.cpp)|Easy| -|202|[Happy Number](https://leetcode.com/problems/happy-number/)| [C++](./algorithms/cpp/happyNumber/HappyNumber.cpp), [Python](./algorithms/python/HappyNumber/isHappy.py)|Easy| +|202|[Happy Number](https://leetcode.com/problems/happy-number/)| [C++](./algorithms/cpp/happyNumber/HappyNumber.cpp), [Python](./algorithms/python/HappyNumber/isHappy.py), [Java](./algorithms/java/src/HappyNumber/HappyNumber.java)|Easy| |201|[Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/)| [C++](./algorithms/cpp/bitwiseANDOfNumbersRange/BitwiseAndOfNumbersRange.cpp)|Medium| |200|[Number of Islands](https://leetcode.com/problems/number-of-islands/)| [C++](./algorithms/cpp/numberOfIslands/NumberOfIslands.cpp), [Python](./algorithms/python/NumberOfIslands/numIslands.py)|Medium| |199|[Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/)| [C++](./algorithms/cpp/binaryTreeRightSideView/binaryTreeRightSideView.cpp)|Medium| @@ -391,7 +395,7 @@ LeetCode |174|[Dungeon Game](https://leetcode.com/problems/dungeon-game/) | [C++](./algorithms/cpp/dungeonGame/dungeonGame.cpp)|Hard| |173|[Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/) | [C++](./algorithms/cpp/binarySearchTreeIterator/binarySearchTreeIterator.cpp), [Java](./algorithms/java/src/binarySearchTreeIterator/binarySearchTreeIterator.java), [Python](./algorithms/python/BinarySearchTreeIterator/BSTIterator.py)|Medium| |172|[Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/) | [C++](./algorithms/cpp/factorialTrailingZeroes/factorialTrailingZeroes.cpp)|Easy| -|171|[Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number/) | [C++](./algorithms/cpp/excelSheetColumnNumber/excelSheetColumnNumber.cpp)|Easy| +|171|[Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number/) | [C++](./algorithms/cpp/excelSheetColumnNumber/excelSheetColumnNumber.cpp), [Java](./algorithms/java/src/ExcelSheetColumnNumber/ExcelSheetColumnNumber.java)|Easy| |170|[Two Sum III - Data structure design](https://leetcode.com/problems/two-sum-iii-data-structure-design/) 🔒 | [C++](./algorithms/cpp/twoSum/twoSum.III.cpp)|Easy| |169|[Majority Element](https://leetcode.com/problems/majority-element/) | [C++](./algorithms/cpp/majorityElement/majorityElement.cpp)|Easy| |168|[Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title/) | [C++](./algorithms/cpp/excelSheetColumnTitle/excelSheetColumnTitle.cpp)|Easy| @@ -463,7 +467,7 @@ LeetCode |102|[Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)| [C++](./algorithms/cpp/binaryTreeLevelOrderTraversal/binaryTreeLevelOrderTraversal.cpp), [Java](./algorithms/java/src/binaryTreeLevelOrderTraversal/binaryTreeLevelOrderTraversal.java)|Easy| |101|[Symmetric Tree](https://leetcode.com/problems/symmetric-tree/)| [C++](./algorithms/cpp/symmetricTree/symmetricTree.cpp)|Easy| |100|[Same Tree](https://leetcode.com/problems/same-tree/)| [C++](./algorithms/cpp/sameTree/sameTree.cpp)|Easy| -|99|[Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/)| [C++](./algorithms/cpp/recoverBinarySearchTree/recoverBinarySearchTree.cpp)|Hard| +|99|[Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/)| [C++](./algorithms/cpp/recoverBinarySearchTree/recoverBinarySearchTree.cpp), [Java](./algorithms/java/src/RecoverBinarySearchTree/RecoverBinarySearchTree.java)|Medium| |98|[Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)| [C++](./algorithms/cpp/validateBinarySearchTree/validateBinarySearchTree.cpp), [Java](./algorithms/java/src/validateBinarySearchTree/validateBinarySearchTree.java), [Python](./algorithms/python/ValidateBinarySearchTree/isValidBST.py)|Medium| |97|[Interleaving String](https://leetcode.com/problems/interleaving-string/)| [C++](./algorithms/cpp/interleavingString/interleavingString.cpp)|Hard| |96|[Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/)| [C++](./algorithms/cpp/uniqueBinarySearchTrees/uniqueBinarySearchTrees.cpp), [Python](./algorithms/python/UniqueBinarySearchTrees/numTrees.py)|Medium| @@ -542,15 +546,15 @@ LeetCode |23|[Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/)| [C++](./algorithms/cpp/mergeKSortedLists/mergeKSortedLists.cpp)|Hard| |22|[Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)| [C++](./algorithms/cpp/generateParentheses/generateParentheses.cpp)|Medium| |21|[Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [C++](./algorithms/cpp/mergeTwoSortedList/mergeTwoSortedList.cpp)|Easy| -|20|[Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [C++](./algorithms/cpp/validParentheses/validParentheses.cpp)|Easy| +|20|[Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [C++](./algorithms/cpp/validParentheses/validParentheses.cpp), [Java](./algorithms/java/src/ValidParentheses/ValidParentheses.java)|Easy| |19|[Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)| [C++](./algorithms/cpp/removeNthNodeFromEndOfList/removeNthNodeFromEndOfList.cpp), [Python](./algorithms/python/RemoveNthNodeFromEndOfList/removeNthFromEnd.py)|Easy| |18|[4Sum](https://leetcode.com/problems/4sum/)| [C++](./algorithms/cpp/4Sum/4Sum.cpp)|Medium| |17|[Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)| [C++](./algorithms/cpp/letterCombinationsOfAPhoneNumber/letterCombinationsOfAPhoneNumber.cpp)|Medium| |16|[3Sum Closest](https://leetcode.com/problems/3sum-closest/)| [C++](./algorithms/cpp/3SumClosest/3SumClosest.cpp)|Medium| |15|[3Sum](https://leetcode.com/problems/3sum/)| [C++](./algorithms/cpp/3Sum/3Sum.cpp)|Medium| -|14|[Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/)| [C++](./algorithms/cpp/longestCommonPrefix/longestCommonPrefix.cpp)|Easy| -|13|[Roman to Integer](https://leetcode.com/problems/roman-to-integer/)| [C++](./algorithms/cpp/romanToInteger/romanToInteger.cpp)|Easy| -|12|[Integer to Roman](https://leetcode.com/problems/integer-to-roman/)| [C++](./algorithms/cpp/integerToRoman/integerToRoman.cpp)|Medium| +|14|[Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/)| [C++](./algorithms/cpp/longestCommonPrefix/longestCommonPrefix.cpp), [Java](./algorithms/java/src/LongestCommonPrefix/LongestCommonPrefix.java)|Easy| +|13|[Roman to Integer](https://leetcode.com/problems/roman-to-integer/)| [C++](./algorithms/cpp/romanToInteger/romanToInteger.cpp), [Java](./algorithms/java/src/RomanToInteger/RomanToInteger.java)|Easy| +|12|[Integer to Roman](https://leetcode.com/problems/integer-to-roman/)| [C++](./algorithms/cpp/integerToRoman/integerToRoman.cpp), [Java](./algorithms/java/src/IntegerToRoman/IntegerToRoman.java)|Medium| |11|[Container With Most Water](https://leetcode.com/problems/container-with-most-water/)| [C++](./algorithms/cpp/containerWithMostWater/containerWithMostWater.cpp), [Java](./algorithms/java/src/containerwithmostwater.java)|Medium| |10|[Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching/)| [C++](./algorithms/cpp/regularExpressionMatching/regularExpressionMatching.cpp)|Hard| |9|[Palindrome Number](https://leetcode.com/problems/palindrome-number/)| [C++](./algorithms/cpp/palindromeNumber/palindromeNumber.cpp), [Java](./algorithms/java/src/palindromeNumber/PalindromeNumber.java)|Easy| @@ -558,7 +562,7 @@ LeetCode |7|[Reverse Integer](https://leetcode.com/problems/reverse-integer/)| [C++](./algorithms/cpp/reverseInteger/reverseInteger.cpp)|Easy| |6|[ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/)| [C++](./algorithms/cpp/zigZagConversion/zigZagConversion.cpp)|Easy| |5|[Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/)| [C++](./algorithms/cpp/longestPalindromicSubstring/longestPalindromicSubstring.cpp)|Medium| -|4|[Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/)| [C++](./algorithms/cpp/medianOfTwoSortedArrays/medianOfTwoSortedArrays.cpp)|Hard| +|4|[Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/)| [C++](./algorithms/cpp/medianOfTwoSortedArrays/medianOfTwoSortedArrays.cpp), [Java](./algorithms/java/src/MedianOfTwoSortedArrays/MedianOfTwoSortedArrays.java)|Hard| |3|[Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/)| [C++](./algorithms/cpp/longestSubstringWithoutRepeatingCharacters/longestSubstringWithoutRepeatingCharacters.cpp)|Medium| |2|[Add Two Numbers](https://leetcode.com/problems/add-two-numbers/)| [C++](./algorithms/cpp/addTwoNumbers/addTwoNumbers.cpp)|Medium| |1|[Two Sum](https://leetcode.com/problems/two-sum/)| [C++](./algorithms/cpp/twoSum/twoSum.cpp), [Go](./algorithms/golang/twoSum/twoSum.go)|Easy| diff --git a/algorithms/java/src/CanMakeArithmeticProgressionFromSequence/CanMakeArithmeticProgressionFromSequence.java b/algorithms/java/src/CanMakeArithmeticProgressionFromSequence/CanMakeArithmeticProgressionFromSequence.java new file mode 100644 index 000000000..9792715d1 --- /dev/null +++ b/algorithms/java/src/CanMakeArithmeticProgressionFromSequence/CanMakeArithmeticProgressionFromSequence.java @@ -0,0 +1,57 @@ +// Source : https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 24-04-2022 + +/***************************************************************************************************** + * + * A sequence of numbers is called an arithmetic progression if the + * difference between any two consecutive elements is the same. + * + * Given an array of numbers arr, return true if the array can be + * rearranged to form an arithmetic progression. Otherwise, return false. + * + * Example 1: + * + * Input: arr = [3,5,1] + * Output: true + * Explanation: We can reorder the elements as [1,3,5] or [5,3,1] + * with differences 2 and -2 respectively, between each consecutive elements. + * + * Example 2: + * + * Input: arr = [1,2,4] + * Output: false + * Explanation: There is no way to reorder the elements to obtain an arithmetic progression. + * + * Constraints: + * + * 2 <= arr.length <= 1000 + * -10^6 <= arr[i] <= 10^6 + * + * Explanation of the solution: + * + * 1. We sort the array 'arr' to check the distance between the first two numbers. + * + * 2. We analyze the array looking if all the numbers have the exact same distance + * between them compared to the two first numbers. + ******************************************************************************************************/ + +class Solution { + public boolean canMakeArithmeticProgression(int[] arr) { + int dis, disBase = 0; + boolean yes = true; + Arrays.sort(arr); + for(int i = 0; i < arr.length-1; i++){ + if(i == 0){ + disBase = arr[i+1]-arr[i]; + }else{ + dis = arr[i+1]-arr[i]; + if(dis != disBase){ + yes = false; + break; + } + } + } + return yes; + } +} diff --git a/algorithms/java/src/DistributeCandiesToPeople/DistributeCandiesToPeople.java b/algorithms/java/src/DistributeCandiesToPeople/DistributeCandiesToPeople.java new file mode 100644 index 000000000..f21507281 --- /dev/null +++ b/algorithms/java/src/DistributeCandiesToPeople/DistributeCandiesToPeople.java @@ -0,0 +1,83 @@ +// Source : https://leetcode.com/problems/distribute-candies-to-people/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 22-04-2022 + +/***************************************************************************************************** + * + * We distribute some number of candies, to a row of n = num_people people in the + * following way: + * + * We then give 1 candy to the first person, 2 candies to the second person, and so on until + * we give n candies to the last person. + * + * Then, we go back to the start of the row, giving n + 1 candies to the first person, n + + * 2 candies to the second person, and so on until we give 2 * n candies to the last + * person. + * + * This process repeats (with us giving one more candy each time, and moving to the start of + * the row after we reach the end) until we run out of candies. The last person will receive all + * of our remaining candies (not necessarily one more than the previous gift). + * + * Return an array (of length num_people and sum candies) that represents the final + * distribution of candies. + * + * + * Example 1: + * + * Input: candies = 7, num_people = 4 + * Output: [1,2,3,1] + * Explanation: + * On the first turn, ans[0] += 1, and the array is [1,0,0,0]. + * On the second turn, ans[1] += 2, and the array is [1,2,0,0]. + * On the third turn, ans[2] += 3, and the array is [1,2,3,0]. + * On the fourth turn, ans[3] += 1 (because there is only one candy + * left), and the final array is [1,2,3,1]. + * + * Example 2: + * + * Input: candies = 10, num_people = 3 + * Output: [5,2,3] + * Explanation: + * On the first turn, ans[0] += 1, and the array is [1,0,0]. + * On the second turn, ans[1] += 2, and the array is [1,2,0]. + * On the third turn, ans[2] += 3, and the array is [1,2,3]. + * On the fourth turn, ans[0] += 4, and the final array is [5,2,3]. + * + * + * Constraints: + * + * 1 <= candies <= 10^9 + * 1 <= num_people <= 1000 + * + * Explanation of the solution: + * + * 1. While we have given less candies than the ones we had at the beginning (while(total < candies){...}) + * + * 2. Use count % num_people == 0 to determine the current index of the people. + ******************************************************************************************************/ + +class Solution { + public int[] distributeCandies(int candies, int num_people) { + int[] res = new int[num_people]; //Initialize the array of people + int toGiveCandie = 1, count = 0, total = 0; + while(total < candies){ //While the total candies given is fewer than the candies we have... + if(count % num_people == 0){ //This is to 'reset' de counter to 0 when we reach the last person. + count = 0; + } + if(total + toGiveCandie <= candies){ + //If the number of candies we have already given plus the candies we are + // going to give are less or equal than the total candies... + res[count] += toGiveCandie; //We add the candies to the array (give the candie to the person) + total += toGiveCandie; //We update the candies we have given + toGiveCandie++; //To the next person we will give one more candie + }else{ + //If we don't have the enough candies, we just give the candies left + res[count] += candies-total; + total += candies-total; + toGiveCandie++; + } + count++; + } + return res; //We return the filled array + } +} diff --git a/algorithms/java/src/ExcelSheetColumnNumber/ExcelSheetColumnNumber.java b/algorithms/java/src/ExcelSheetColumnNumber/ExcelSheetColumnNumber.java new file mode 100644 index 000000000..f3b73c6d6 --- /dev/null +++ b/algorithms/java/src/ExcelSheetColumnNumber/ExcelSheetColumnNumber.java @@ -0,0 +1,55 @@ +// Source : https://leetcode.com/problems/excel-sheet-column-number/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 24-04-2022 + +/***************************************************************************************************** + * Given a string columnTitle that represents the column title as appear in an + * Excel sheet, return its corresponding column number. + * + * For example: + * A -> 1 + * B -> 2 + * C -> 3 + * ... + * Z -> 26 + * AA -> 27 + * AB -> 28 + * ... + * + * Example 1: + * + * Input: columnTitle = "A" + * Output: 1 + * + * Example 2: + * + * Input: columnTitle = "AB" + * Output: 28 + * Explanation: + * + * Example 3: + * + * Input: columnTitle = "ZY" + * Output: 701 + * + * 1 <= columnTitle.length <= 7 + * columnTitle consists only of uppercase English letters. + * columnTitle is in the range ["A", "FXSHRXW"] + ******************************************************************************************************/ + +class Solution { + public int titleToNumber(String columnTitle) { + int res = 0, cnt = 0; + String letras = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + int exponente = columnTitle.length()-1; + if(exponente == 0){ + return letras.indexOf(columnTitle)+1; + } + while(exponente != -1){ + res += (int) ((letras.indexOf(String.valueOf(columnTitle.charAt(cnt)))+1)*Math.pow(26, exponente)); + exponente--; + cnt++; + } + return res; + } +} diff --git a/algorithms/java/src/HappyNumber/HappyNumber.java b/algorithms/java/src/HappyNumber/HappyNumber.java new file mode 100644 index 000000000..24efb85cb --- /dev/null +++ b/algorithms/java/src/HappyNumber/HappyNumber.java @@ -0,0 +1,55 @@ +// Source : https://leetcode.com/problems/happy-number/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 24-04-2022 + +/***************************************************************************************************** + * + * Write an algorithm to determine if a number n is happy. + * A happy number is a number defined by the following process: + * + * Starting with any positive integer, replace the number by the sum of the squares of its digits. + * + * Repeat the process until the number equals 1 (where it will stay), + * or it loops endlessly in a cycle which does not include 1. + * + * Those numbers for which this process ends in 1 are happy. + * + * Return true if n is a happy number, and false if not. + * + * Example 1: + * + * Input: n = 19 + * Output: true + * Explanation: +1^2 + 9^2 = 82 +8^2 + 2^2 = 68 +6^2 + 8^2 = 100 +1^2 + 0^2 + 0^2 = 1 + * + * Example 2: + * + * Input: n = 2 + * Output: false + * + * Constraints: + * + * 1 <= n <= 2^31 - 1 + ******************************************************************************************************/ + +class Solution { + public boolean isHappy(int n) { + while(n != 1){ + if(n == 7) + return true; + else if(n <= 9) + return false; + int num = 0; + while(n > 0){ + num += Math.pow(n % 10, 2); + n /= 10; + } + n=num; + } + return true; + } +} diff --git a/algorithms/java/src/IntegerToRoman/IntegerToRoman.java b/algorithms/java/src/IntegerToRoman/IntegerToRoman.java new file mode 100644 index 000000000..9922b50a6 --- /dev/null +++ b/algorithms/java/src/IntegerToRoman/IntegerToRoman.java @@ -0,0 +1,140 @@ +// Source : https://leetcode.com/problems/integer-to-roman/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 23-04-2022 + +/***************************************************************************************************** + * Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. + * + * Symbol Value + * I 1 + * V 5 + * X 10 + * L 50 + * C 100 + * D 500 + * M 1000 + * + * For example, 2 is written as II in Roman numeral, just two one's added + * together. 12 is written as XII, which is simply X + II. The number 27 is + * written as XXVII, which is XX + V + II. + * + * Roman numerals are usually written largest to smallest from left to right. + * However, the numeral for four is not IIII. Instead, the number four is + * written as IV. Because the one is before the five we subtract it making four. + * The same principle applies to the number nine, which is written as IX. There + * are six instances where subtraction is used: + * + * I can be placed before V (5) and X (10) to make 4 and 9. + * X can be placed before L (50) and C (100) to make 40 and 90. + * C can be placed before D (500) and M (1000) to make 400 and 900. + * + * Given an integer, convert it to a roman numeral. + * + * Example 1: + * + * Input: num = 3 + * Output: "III" + * Explanation: 3 is represented as 3 ones. + * + * Example 2: + * + * Input: num = 58 + * Output: "LVIII" + * Explanation: L = 50, V = 5, III = 3. + * + * Example 3: + * + * Input: num = 1994 + * Output: "MCMXCIV" + * Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. + * + * Constraints: + * + * 1 <= num <= 3999 + * + * Explanation of the solution: + * + * We start looking if the number given is bigger than 1000 + * to see if there is going to be a letter 'M' (1000) in the solution. + * + * If the number > 1000 we repeat the process until a maximun of three 'M' + * substracting 1000 to the number each time. + * + * The process is the same for all the letters. + * + * We also analyze special cases such as 'CM' (num < 1000 && num > 899), 'CD' (num < 500 && num > 399), + * 'XC' (num < 100 && num > 89), 'XL' (num < 50 && num > 39), 'IX' (num == 9) and 'IV' (num == 4). + ******************************************************************************************************/ + +class Solution { + public String intToRoman(int num) { + String res = ""; + int cnt = 0; + while(num >= 1000 && cnt < 3){ + res += "M"; + num -= 1000; + cnt++; + } + cnt = 0; + if(num < 1000 && num > 899){ + res += "CM"; + num -= 900; + } + while(num >= 500 && cnt < 3){ + res += "D"; + num -= 500; + cnt++; + } + cnt = 0; + if(num < 500 && num > 399){ + res += "CD"; + num -= 400; + } + while(num >= 100 && cnt < 3){ + res += "C"; + num -= 100; + cnt++; + } + cnt = 0; + if(num < 100 && num > 89){ + res += "XC"; + num -= 90; + } + while(num >= 50 && cnt < 3){ + res += "L"; + num -= 50; + cnt++; + } + cnt = 0; + if(num < 50 && num > 39){ + res += "XL"; + num -= 40; + } + while(num >= 10 && cnt < 3){ + res += "X"; + num -= 10; + cnt++; + } + cnt = 0; + if(num == 9){ + res += "IX"; + num -= 9; + } + while(num >= 5 && cnt < 3){ + res += "V"; + num -= 5; + cnt++; + } + cnt = 0; + if(num == 4){ + res += "IV"; + num -= 4; + } + while(num >= 1 && cnt < 3){ + res += "I"; + num -= 1; + cnt++; + } + return res; + } +} diff --git a/algorithms/java/src/IsSubsequence/IsSubsequence.java b/algorithms/java/src/IsSubsequence/IsSubsequence.java new file mode 100644 index 000000000..6432a545d --- /dev/null +++ b/algorithms/java/src/IsSubsequence/IsSubsequence.java @@ -0,0 +1,60 @@ +// Source : https://leetcode.com/problems/is-subsequence/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 22-04-2022 + +/***************************************************************************************************** + * + * Given two strings s and t, return true if s is a subsequence of t, or false otherwise. + * + * A subsequence of a string is a new string that is formed from the original string by + * deleting some (can be none) of the characters without disturbing the relative positions of + * the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not). + * + * Example 1: + * + * Input: s = "abc", t = "ahbgdc" + * Output: true + * + * Example 2: + * + * Input: s = "axc", t = "ahbgdc" + * Output: false + * + * Constraints: + * + * 0 <= s.length <= 100 + * 0 <= t.length <= 10^4 + * s and t consist only of lowercase English letters. + * + * + * Explanation of the solution: + * + * Firstly we analyze de string 's' char by char, the string 't' is required to contain + * the analized char in order to return true. If 't' does not contains the char, we return false. + * + * Secondly, if 't' contains the char we delete all the letters in 't' until the position of the + * char we have just analized (including the char, that is why we have add the 1 at the t.substring( )) + * and we can also delete from 's' the recently analized char. + * + * Finally, after deleting all the unwanted letters in 't' and 's', if the length of 's' is bigger + * than the length of 't' it means that the string 's' have more chars left to analize than the amount of + * chars 't' contains, as a result we return false. + * + * This is an example of the code: + ******************************************************************************************************/ + +class Solution { + public boolean isSubsequence(String s, String t) { //The explanation is above + for(char i : s.toCharArray()){ + if(!t.contains(String.valueOf(i))){ + return false; + } + t = t.substring(t.indexOf(i)+1); + s = s.substring(1); + if(s.length() > t.length()){ + return false; + } + } + return true; + } +} diff --git a/algorithms/java/src/LongestCommonPrefix/LongestCommonPrefix.java b/algorithms/java/src/LongestCommonPrefix/LongestCommonPrefix.java new file mode 100644 index 000000000..cc79a2506 --- /dev/null +++ b/algorithms/java/src/LongestCommonPrefix/LongestCommonPrefix.java @@ -0,0 +1,59 @@ +// Source : https://leetcode.com/problems/longest-common-prefix/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 22-04-2022 + +/***************************************************************************************************** + * Write a function to find the longest common prefix string amongst an array of strings. + * + * If there is no common prefix, return an empty string "". + * + * Example 1: + * + * Input: strs = ["flower","flow","flight"] + * Output: "fl" + * + * Example 2: + * + * Input: strs = ["dog","racecar","car"] + * Output: "" + * Explanation: There is no common prefix among the input strings. + * + * Constraints: + * + * 1 <= strs.length <= 200 + * 0 <= strs[i].length <= 200 + * strs[i] consists of only lower-case English letters. + * + * Explanation of the solution: + * + * 1. Get the first word in the array 'strs'. As all the words in the array are believed to have + * a common prefix, we compare if the other words have the same prefix (using containsPrefix(word, strs)). + * + * 2. If a word in the array does not contain the same prefix we return false, otherwise (if all the words in 'strs' have the same prefix) we return true. + * If 'contains' is true we have found the prefix, in contrast, if 'contains' is false we continue looking + * for the prefix deleting the last character of the word given and using 'containsPrefix()' again. + ******************************************************************************************************/ + +class Solution { + public String longestCommonPrefix(String[] strs) { + String word = strs[0]; + boolean contains; + while(true){ + contains = containsPrefix(word,strs); + if(!contains){ + word = word.substring(0,word.length()-1); //Delete the last character + }else{ + return word; + } + } + } + + public boolean containsPrefix(String word, String[] strs){ + for(String i : strs){ + if(i.indexOf(word) != 0){ //The prefix must be at the beginning of the word + return false; + } + } + return true; + } +} diff --git a/algorithms/java/src/MedianOfTwoSortedArrays/MedianOfTwoSortedArrays.java b/algorithms/java/src/MedianOfTwoSortedArrays/MedianOfTwoSortedArrays.java new file mode 100644 index 000000000..275807588 --- /dev/null +++ b/algorithms/java/src/MedianOfTwoSortedArrays/MedianOfTwoSortedArrays.java @@ -0,0 +1,57 @@ +// Source : https://leetcode.com/problems/median-of-two-sorted-arrays/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 23-04-2022 + +/***************************************************************************************************** + * + * Given two sorted arrays nums1 and nums2 of size m and n respectively, + * return the median of the two sorted arrays. + * + * The overall run time complexity should be O(log (m+n)). + * + * Example 1: + * + * Input: nums1 = [1,3], nums2 = [2] + * Output: 2.00000 + * Explanation: merged array = [1,2,3] and median is 2. + * + * Example 2: + * + * Input: nums1 = [1,2], nums2 = [3,4] + * Output: 2.50000 + * Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. + * + * + * Constraints: + * + * nums1.length == m + * nums2.length == n + * 0 <= m <= 1000 + * 0 <= n <= 1000 + * 1 <= m + n <= 2000 + * -10^6 <= nums1[i], nums2[i] <= 10^6 + * + * Explanation of the solution: + * + * 1. Concatenate both arrays (int[] concatenate). + * + * 2. Sort the 'concatenate' array. + * + * 3. If 'concatenate' have an odd nuber of elements return the element in the middle, otherwise return the sum of the middle numbers. + ******************************************************************************************************/ + +class Solution { + public double findMedianSortedArrays(int[] nums1, int[] nums2) { + double c; + int[] concatenate = new int[nums1.length + nums2.length]; + System.arraycopy(nums1, 0, concatenate, 0, nums1.length); //Add the first array + System.arraycopy(nums2, 0, concatenate, nums1.length, nums2.length); //Add the second array + Arrays.sort(concatenate); + if (concatenate.length % 2 == 0){ + c = concatenate[concatenate.length/2-1]+concatenate[concatenate.length/2]; + return c/2; + }else { + return concatenate[concatenate.length/2]; + } + } +} diff --git a/algorithms/java/src/MinimumRemoveToMakeValidParentheses/MinimumRemoveToMakeValidParentheses.java b/algorithms/java/src/MinimumRemoveToMakeValidParentheses/MinimumRemoveToMakeValidParentheses.java new file mode 100644 index 000000000..dd44deb13 --- /dev/null +++ b/algorithms/java/src/MinimumRemoveToMakeValidParentheses/MinimumRemoveToMakeValidParentheses.java @@ -0,0 +1,69 @@ +// Source : https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 24-04-2022 + +/***************************************************************************************************** + * + * Given a string s of '(' , ')' and lowercase English characters. + * + * Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) + * so that the resulting parentheses string is valid and return any valid string. + * + * Formally, a parentheses string is valid if and only if: + * It is the empty string, contains only lowercase characters, or + * It can be written as AB (A concatenated with B), where A and B are valid strings, or + * It can be written as (A), where A is a valid string. + * + * Example 1: + * + * Input: s = "lee(t(c)o)de)" + * Output: "lee(t(c)o)de" + * Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted. + * + * Example 2: + * + * Input: s = "a)b(c)d" + * Output: "ab(c)d" + * + * Example 3: + * + * Input: s = "))((" + * Output: "" + * Explanation: An empty string is also valid. + * + * Constraints: + * + * 1 <= s.length <= 10^5 + * s[i] is either'(' , ')', or lowercase English letter. + * + * Explanation of the solution: + * + * 1. Analyze the string to know how many valid parentheses are in 's'. + * +* 2. Analyze again the string and return the string deleting the invalid parentheses. +* +* 3. Return the reversed string. + ******************************************************************************************************/ + +class Solution { + public String minRemoveToMakeValid(String s) { + StringBuilder comprobar = new StringBuilder(); + int open = 0; + for(char c : s.toCharArray()) { + if(c =='(') { + open++; + } + else if(c == ')') { + if(open == 0) continue; + open--; + } + comprobar.append(c); + } + StringBuilder result = new StringBuilder(); + for(int i=comprobar.length()-1 ; i>=0 ; i-- ){ + if(comprobar.charAt(i) == '(' && open-- > 0) continue; + result.append(comprobar.charAt(i)); + } + return result.reverse().toString(); + } +} diff --git a/algorithms/java/src/PowerOfFour/PowerOfFour.java b/algorithms/java/src/PowerOfFour/PowerOfFour.java new file mode 100644 index 000000000..8411f7ae1 --- /dev/null +++ b/algorithms/java/src/PowerOfFour/PowerOfFour.java @@ -0,0 +1,43 @@ +// Source : https://leetcode.com/problems/power-of-four/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 24-04-2022 + +/***************************************************************************************************** + * + * Given an integer n, return true if it is a power of four. Otherwise, return false. + * + * An integer n is a power of four, if there exists an integer x such that n == 4x. + * + * Example 1: + * + * Input: n = 16 + * Output: true + * + * Example 2: + * + * Input: n = 5 + * Output: false + * + * Example 3: + * + * Input: n = 1 + * Output: true + * + * Constraints: + * + * -2^31 <= n <= 2^31 - 1 + * + * Explanation of the solution: + * + * After doing the log4(n), if the result have no decimal part, it means that 'n' is a power of four. + ******************************************************************************************************/ + +class Solution { + public boolean isPowerOfFour(int n) { + double num = Math.log10(n) / Math.log10(4); + if(num % 1 != 0) { + return false; + } + return true; + } +} diff --git a/algorithms/java/src/PowerOfThree/PowerOfThree.java b/algorithms/java/src/PowerOfThree/PowerOfThree.java new file mode 100644 index 000000000..c847e6a98 --- /dev/null +++ b/algorithms/java/src/PowerOfThree/PowerOfThree.java @@ -0,0 +1,43 @@ +// Source : https://leetcode.com/problems/power-of-three/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 24-04-2022 + +/***************************************************************************************************** + * + * Given an integer n, return true if it is a power of three. Otherwise, return false. + * + * An integer n is a power of three, if there exists an integer x such that n == 3x. + * + * Example 1: + * + * Input: n = 27 + * Output: true + * + * Example 2: + * + * Input: n = 0 + * Output: false + * + * Example 3: + * + * Input: n = 9 + * Output: true + * + * Constraints: + * + * -2^31 <= n <= 2^31 - 1 + * + * Explanation of the solution: + * + * After doing the log3(n), if the result have no decimal part, it means that 'n' is a power of three. + ******************************************************************************************************/ + +class Solution { + public boolean isPowerOfThree(int n) { + double num = Math.log10(n) / Math.log10(3); + if(num % 1 != 0){ + return false; + } + return true; + } +} diff --git a/algorithms/java/src/PowerOfTwo/PowerOfTwo.java b/algorithms/java/src/PowerOfTwo/PowerOfTwo.java new file mode 100644 index 000000000..b121c503e --- /dev/null +++ b/algorithms/java/src/PowerOfTwo/PowerOfTwo.java @@ -0,0 +1,45 @@ +// Source : https://leetcode.com/problems/power-of-two/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 24-04-2022 + +/***************************************************************************************************** + * + * Given an integer n, return true if it is a power of two. Otherwise, return false. + * + * An integer n is a power of two, if there exists an integer x such that n == 2x. + * + * Example 1: + * + * Input: n = 1 + * Output: true + * Explanation: 2^0 = 1 + * + * Example 2: + * + * Input: n = 16 + * Output: true + * Explanation: 2^4 = 16 + * + * Example 3: + * + * Input: n = 3 + * Output: false + * + * Constraints: + * + * 1 <= n <= 2^31 - 1 + * + * Explanation of the solution: + * + * After doing the log2(n), if the result have no decimal part, it means that 'n' is a power of two. + ******************************************************************************************************/ + +class Solution { + public boolean isPowerOfTwo(int n) { + double num =Math.log10(n)/ Math.log10(2); + if(num % 1 != 0){ + return false; + } + return true; + } +} diff --git a/algorithms/java/src/RecoverBinarySearchTree/RecoverBinarySearchTree.java b/algorithms/java/src/RecoverBinarySearchTree/RecoverBinarySearchTree.java new file mode 100644 index 000000000..a6deaf4e4 --- /dev/null +++ b/algorithms/java/src/RecoverBinarySearchTree/RecoverBinarySearchTree.java @@ -0,0 +1,69 @@ +// Source : https://leetcode.com/problems/recover-binary-search-tree/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 23-04-2022 + +/***************************************************************************************************** + * + * You are given the root of a binary search tree (BST), where the values of + * exactly two nodes of the tree were swapped by mistake. Recover the tree + * without changing its structure. + * + * Example 1: + * + * Input: root = [1,3,null,null,2] + * Output: [3,1,null,null,2] + * Explanation: 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid. + * + * Example 2: + * + * Input: root = [3,1,4,null,null,2] + * Output: [2,1,4,null,null,3] + * Explanation: 2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid. + * + * Constraints: + * + * The number of nodes in the tree is in the range [2, 1000]. + * -2^31 <= Node.val <= 2^31 - 1 + * + * Explanation of the solution: + * + * 1. Firstly we apply the 'ordenCentralRec(root, new ArrayList<>(), aux1, aux2)' method to extract the + * nodes of the tree in an ArrayList. We read the tree InOrder traversal. + * Note that both aux1 and aux2 value's is Integer.MIN_VALUE so the nodo.val doesn't change. + * + * 2. We check the values obtained in the ArrayList to see which are the changed numbers. + * + * 3. Finally we apply the 'ordenCentralRec(root, new ArrayList<>(), aux1, aux2)' method to extract the + * final version of the binary search tree HAVING changed aux1 and aux2. The method will change the + * nodes values and return the the binary search tree changed. + ******************************************************************************************************/ + +class Solution { + public void recoverTree(TreeNode root) { + int aux1 = Integer.MIN_VALUE, aux2 = Integer.MIN_VALUE; + List nums = ordenCentralRec(root, new ArrayList<>(), aux1, aux2); + for (int i = 0; i < nums.size()-1;i++){ + if (nums.get(i) > nums.get(i+1)){ + if (aux1 == Integer.MIN_VALUE){ + aux1 = nums.get(i); + } + aux2 = nums.get(i+1); + } + } + nums.clear(); + ordenCentralRec(root, nums, aux1, aux2); + } + private List ordenCentralRec(TreeNode nodo, List nums, int aux1, int aux2) { + if (nodo != null) { + if (aux1 == nodo.val){ + nodo.val = aux2; + }else if (aux2 == nodo.val){ + nodo.val = aux1; + } + nums = ordenCentralRec(nodo.left, nums, aux1, aux2); + nums.add(nodo.val); + nums = ordenCentralRec(nodo.right, nums, aux1, aux2); + } + return nums; + } +} diff --git a/algorithms/java/src/RomanToInteger/RomanToInteger.java b/algorithms/java/src/RomanToInteger/RomanToInteger.java new file mode 100644 index 000000000..e6e09e7a0 --- /dev/null +++ b/algorithms/java/src/RomanToInteger/RomanToInteger.java @@ -0,0 +1,120 @@ +// Source : https://leetcode.com/problems/roman-to-integer/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 23-04-2022 + +/***************************************************************************************************** + * Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. + * + * Symbol Value + * I 1 + * V 5 + * X 10 + * L 50 + * C 100 + * D 500 + * M 1000 + * + * For example, 2 is written as II in Roman numeral, just two one's added + * together. 12 is written as XII, which is simply X + II. The number 27 is + * written as XXVII, which is XX + V + II. + * + * Roman numerals are usually written largest to smallest from left to right. + * However, the numeral for four is not IIII. Instead, the number four is + * written as IV. Because the one is before the five we subtract it making four. + * The same principle applies to the number nine, which is written as IX. There + * are six instances where subtraction is used: + * + * I can be placed before V (5) and X (10) to make 4 and 9. + * X can be placed before L (50) and C (100) to make 40 and 90. + * C can be placed before D (500) and M (1000) to make 400 and 900. + * + * Given an integer, convert it to a roman numeral. + * + * Example 1: + * + * Input: s = "III" + * Output: 3 + * Explanation: III = 3. + * + * Example 2: + * + * Input: s = "LVIII" + * Output: 58 + * Explanation: L = 50, V= 5, III = 3. + * + * Example 3: + * + * Input: s = "MCMXCIV" + * Output: 1994 + * Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. + * + * Constraints: + * + * 1 <= s.length <= 15 + * s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M'). + * It is guaranteed that s is a valid roman numeral in the range [1, 3999]. + * + * Explanation of the solution: + * + * Letters 'V' ,'L', 'D' and 'M' can't be subtracted so when they are readed we can just add their values. + * + * In contrast, the letter 'I' can be subtracted at 4 and 9... Example: IV = 4, IX = 9. + * If the letter 'I' is at the end of the number, we just add it's value. + * + * Letter 'X' can be subtracted at 40 and 90... Example: XL = 40, XC = 90. + * + * Letter 'C' can be subtracted at 400 and 900... Example: CD = 400, CM = 900. + * + * I used an array to store the values, but you could perfectly just write the values of it's letters. + * + * While reading the next letter you should check that it's not the last one, I used "if( i != s.length()-1 && ... )" + ******************************************************************************************************/ + +class Solution { + public int romanToInt(String s) { + int[] nums = {1,5,10,50,100,500,1000}; + int res = 0; + for(int i = 0; i < s.length(); i++){ + if(s.charAt(i) == 'I'){ + if(i != s.length()-1 && s.charAt(i+1) == 'V'){ + res += nums[1]-nums[0]; + i++; + }else if(i != s.length()-1 && s.charAt(i+1) == 'X'){ + res += nums[2]-nums[0]; + i++; + }else{ + res += nums[0]; + } + }else if(s.charAt(i) == 'V'){ + res += nums[1]; + }else if(s.charAt(i) == 'X'){ + if(i != s.length()-1 && s.charAt(i+1) == 'C'){ + res += nums[4]-nums[2]; + i++; + }else if(i != s.length()-1 && s.charAt(i+1) == 'L'){ + res += nums[3]-nums[2]; + i++; + }else{ + res += nums[2]; + } + }else if(s.charAt(i) == 'L' ){ + res += nums[3]; + }else if(s.charAt(i) == 'C'){ + if(i != s.length()-1 && s.charAt(i+1) == 'D'){ + res += nums[5]-nums[4]; + i++; + }else if(i != s.length()-1 && s.charAt(i+1) == 'M'){ + res += nums[6]-nums[4]; + i++; + }else{ + res += nums[4]; + } + }else if(s.charAt(i) == 'D'){ + res += nums[5]; + }else if(s.charAt(i) == 'M'){ + res += nums[6]; + } + } + return res; + } +} diff --git a/algorithms/java/src/SignOfTheProductOfAnArray/SignOfTheProductOfAnArray.java b/algorithms/java/src/SignOfTheProductOfAnArray/SignOfTheProductOfAnArray.java new file mode 100644 index 000000000..79f35e484 --- /dev/null +++ b/algorithms/java/src/SignOfTheProductOfAnArray/SignOfTheProductOfAnArray.java @@ -0,0 +1,60 @@ +// Source : https://leetcode.com/problems/sign-of-the-product-of-an-array/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 24-04-2022 + +/***************************************************************************************************** + * + * There is a function signFunc(x) that returns: + * 1 if x is positive. + * -1 if x is negative. + * 0 if x is equal to 0. + * + * You are given an integer array nums. Let product be the product of all values in the array nums. + * + * Return signFunc(product). + * + * Example 1: + * + * Input: nums = [-1,-2,-3,-4,3,2,1] + * Output: 1 + * Explanation: The product of all values in the array is 144, and signFunc(144) = 1 + * + * Example 2: + * + * Input: nums = [1,5,0,2,-3] + * Output: 0 + * Explanation: The product of all values in the array is 0, and signFunc(0) = 0 + * + * Example 3: + * + * Input: nums = [-1,1,-1,1,-1] + * Output: -1 + * Explanation: The product of all values in the array is -1, and signFunc(-1) = -1 + * + * Constraints: + * + * 1 <= nums.length <= 1000 + * -100 <= nums[i] <= 100 + * + * Explanation of the solution: + * + * 1. We analyze all the numbers in 'nums', if we encounter a 0, we return 0. + * + * 2. If we find a negative number we add 1 to de counter 'cnt', once we have finished analyzing, + * we return -1 if there is an odd number of '-' symbols. Otherwise we return 1. + ******************************************************************************************************/ + +class Solution { + public int arraySign(int[] nums) { + String num = ""; + int cnt = 0; + for(int i : nums){ + if(i == 0){ + return 0; + }else if(i < 0){ + cnt++; + } + } + if(cnt % 2 == 0){return 1;}else{return -1;} + } +} diff --git a/algorithms/java/src/SubtractTheProductAndSumOfDigitsOfAnInteger/SubtractTheProductAndSumOfDigitsOfAnInteger.java b/algorithms/java/src/SubtractTheProductAndSumOfDigitsOfAnInteger/SubtractTheProductAndSumOfDigitsOfAnInteger.java new file mode 100644 index 000000000..6258a67f3 --- /dev/null +++ b/algorithms/java/src/SubtractTheProductAndSumOfDigitsOfAnInteger/SubtractTheProductAndSumOfDigitsOfAnInteger.java @@ -0,0 +1,50 @@ +// Source : https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 24-04-2022 + +/***************************************************************************************************** + * + * Given an integer number n, return the difference between the product + * of its digits and the sum of its digits. + * + * Example 1: + * + * Input: n = 234 + * Output: 15 + * Explanation: + * Product of digits = 2 * 3 * 4 = 24 + * Sum of digits = 2 + 3 + 4 = 9 + * Result = 24 - 9 = 15 + * + * Example 2: + * + * Input: n = 4421 + * Output: 21 + * Explanation: + * Product of digits = 4 * 4 * 2 * 1 = 32 + * Sum of digits = 4 + 4 + 2 + 1 = 11 + * Result = 32 - 11 = 21 + * + * Constraints: + * + * 1 <= n <= 10^5 + * + * Explanation of the solution: + * + * 1. We analyze the String 'ns' char by char and we add and multiply both vatiables (product and sum) each time. + * + * 2. We return the subtraction of it. + ******************************************************************************************************/ + +class Solution { + public int subtractProductAndSum(int n) { + int prod = 1, sum = 0,act; + String ns = String.valueOf(n); + for(int i = 0; i < ns.length(); i++){ + act = Integer.parseInt(String.valueOf(ns.charAt(i))); + prod *= act; + sum += act; + } + return prod-sum; + } +} diff --git a/algorithms/java/src/ThirdMaximumNumber/ThirdMaximumNumber.java b/algorithms/java/src/ThirdMaximumNumber/ThirdMaximumNumber.java new file mode 100644 index 000000000..32a731bce --- /dev/null +++ b/algorithms/java/src/ThirdMaximumNumber/ThirdMaximumNumber.java @@ -0,0 +1,72 @@ +// Source : https://leetcode.com/problems/third-maximum-number/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 22-04-2022 + +/***************************************************************************************************** + * + * Given an integer array nums, return the third distinct maximum number in + * this array. If the third maximum does not exist, return the maximum number. + * + * Example 1: + * + * Input: nums = [3,2,1] + * Output: 1 + * Explanation: + * The first distinct maximum is 3. + * The second distinct maximum is 2. + * The third distinct maximum is 1. + * + * Example 2: + * + * Input: nums = [1,2] + * Output: 2 + * Explanation: + * The first distinct maximum is 2. + * The second distinct maximum is 1. + * The third distinct maximum does not exist, so the maximum (2) is returned instead. + * + * Example 3: + * + * Input: nums = [2,2,3,1] + * Output: 1 + * Explanation: + * The first distinct maximum is 3. + * The second distinct maximum is 2 (both 2's are counted together since they have the same value). + * The third distinct maximum is 1. + * + * Constraints: + * + * 1 <= nums.length <= 10^4 + * -2^31 <= nums[i] <= 2^31 - 1 + * + * Explanation of the solution: + * + * 1. We establish the three variables to the (Integer.MIN_VALUE - 1) + * + * 2. We analyze the array 'nums' and we update the variables when a bigger number is found + ******************************************************************************************************/ + +class Solution { + public int thirdMax(int[] nums) { + long max1 = -2147483649L, max2 = -2147483649L, max3 = -2147483649L; + for(int i : nums){ + if(i>max1){ + if(i> max2){ + if(i > max3){ + max1 = max2; + max2 = max3; + max3 = i; + }else if(i!=max3 && i != max2){ + max1 = max2; + max2 = i; + } + }else if(i!=max1 && i!=max2){max1=i;} + } + } + if(max1==-2147483649L){ + return (int)max3; + }else{ + return (int)max1; + } + } +} diff --git a/algorithms/java/src/ValidParentheses/ValidParentheses.java b/algorithms/java/src/ValidParentheses/ValidParentheses.java new file mode 100644 index 000000000..827ba042f --- /dev/null +++ b/algorithms/java/src/ValidParentheses/ValidParentheses.java @@ -0,0 +1,91 @@ +// Source : https://leetcode.com/problems/valid-parentheses/ +// Author : Diego Ruiz Piqueras (Pikeras72) +// Date : 23-04-2022 + +/********************************************************************************************************* + * Given a string s containing just the characters '(', ')', '{', '}', '[' and ']' + * determine if the input string is valid. + * + * An input string is valid if: + * + * 1. Open brackets must be closed by the same type of brackets. + * + * 2. Open brackets must be closed in the correct order. + * + * Example 1: + * + * Input: s = "()" + * Output: true + * + * Example 2: + * + * Input: s = "()[]{}" + * Output: true + * + * Explanation 3: + * + * Input: s = "(]" + * Output: false + * + * Constraints: + * + * 1 <= s.length <= 10^4 + * s consists of parentheses only '()[]{}'. + * + * Explanation of the solution: + * + * 1. We analyze char by char the string 's' given, if we analyze an opening parentheses we can + * include it in the Stack if the last parentheses added to the Stack was not another opening + * parentheses or if the Stack is empty. + * + * 2. If we analyze a closing parentheses and the last introduced parentheses to the Stack is exactly the + * opening parentheses of the one we are analyzing we eliminate the opening parentheses from the Stack. + * Else we return false. + * + * 3. After having analyzed 's', if the Stack is empty it means all parentheses have being closed so we return + * true, if not, we return false; + *************************************************************************************************************/ + +//I HAVE USED AN IF{}ELSE IF{} COMBINATION BUT YOU COULD HAVE USED A SWITCH{} TO CHECK THE TYPE OF PARENTHESES. +class Solution { + public boolean isValid(String s) { + Stack pila = new Stack(); + for (char i : s.toCharArray()){ + if(i == '('){ + pila.add(i); + }else if(i == ')'){ + if (pila.isEmpty()){ + return false; + }else if (pila.peek().equals('(')){ + pila.pop(); + }else { + return false; + } + }else if(i == '['){ + pila.add(i); + }else if(i == ']'){ + if (pila.isEmpty()){ + return false; + }else if (pila.peek().equals('[')){ + pila.pop(); + }else { + return false; + } + }else if(i == '{'){ + pila.add(i); + }else{ + if (pila.isEmpty()){ + return false; + }else if (pila.peek().equals('{')){ + pila.pop(); + }else { + return false; + } + } + } + if (pila.isEmpty()){ + return true; + } + return false; + } +} diff --git a/algorithms/java/src/lengthOfLastWord/LengthOfLastWord.java b/algorithms/java/src/lengthOfLastWord/LengthOfLastWord.java index 2e661629a..793260d0c 100644 --- a/algorithms/java/src/lengthOfLastWord/LengthOfLastWord.java +++ b/algorithms/java/src/lengthOfLastWord/LengthOfLastWord.java @@ -42,3 +42,12 @@ public int lengthOfLastWord(String s) { } } + +// ANOTHER POSIBLE SOLUTION BY: DIEGO RUIZ PIQUERAS (PIKERAS72) + +class Solution { + public int lengthOfLastWord(String s) { + String[] a = s.split(" "); + return a[a.length-1].length(); + } +}