├── Database ├── Easy │ ├── DuplicateEmails.sql │ ├── DeleteDuplicateEmails.sql │ ├── RecyclableAndLowFatProducts.sql │ ├── CombineTwoTables.sql │ ├── CustomersWhoNeverOrder.sql │ ├── EmployeesEarningMoreThanTheirManagers.sql │ ├── FindTotalTimeSpentByEachEmployee.sql │ ├── DailyLeadsAndPartners.sql │ └── RearrangeProductsTable.sql └── Medium │ └── CapitalGainLoss.sql ├── Algorithms ├── Easy │ ├── SmallestEvenMultiple.cpp │ ├── RunningSumOf1dArray.cpp │ ├── FinalValueOfVariableAfterPerformingOperations.cpp │ ├── AddTwoIntegers.cpp │ ├── PowerOfFour.cpp │ ├── PowerOfThree.cpp │ ├── CountOddNumbersInAnIntervalRange.cpp │ ├── PowerOfTwo.cpp │ ├── MaximumProductOfThreeNumbers.cpp │ ├── ReverseString.cpp │ ├── NumberOfSegmentsInAString.cpp │ ├── ToLowerCase.cpp │ ├── MoveZeroes.cpp │ ├── DefangingAnIPAddress.cpp │ ├── AddDigits.cpp │ ├── LargestPerimeterTriangle.cpp │ ├── MajorityElement.cpp │ ├── ContainDuplicates.cpp │ ├── PascalsTriangleII.cpp │ ├── ConvertBinaryNumberInALinkedListToInteger.cpp │ ├── MiddleOfTheLinkedList.cpp │ ├── MaxConsecutiveOnes.cpp │ ├── RemoveDuplicatesFromSortedList.cpp │ ├── SearchInABinaryTree.cpp │ ├── SumOfLeftLeaves.cpp │ ├── ThreeDivisors.cpp │ ├── ConsecutiveCharacters.cpp │ ├── ExcelSheetColumnNumber.cpp │ ├── FirstUniqueCharacterInAString.cpp │ ├── CountingBits.cpp │ ├── InvertBinaryTree.cpp │ ├── MaximumSubarray.cpp │ ├── TransposeMatrix.cpp │ ├── BinaryTreePreorderTraversal.cpp │ ├── ClimbingStairs.cpp │ ├── BinaryTreeInorderTraversal.cpp │ ├── RangeSumOfBST.cpp │ ├── ShuffleTheArray.cpp │ ├── SubtractTheProductAndSumOfDigitsOfAnInteger.cpp │ ├── ValidPerfectSquare.cpp │ ├── FindTheDistanceValueBetweenTwoArrays.cpp │ ├── BinaryTreePostorderTraversal.cpp │ ├── FindTheHighestAltitude.cpp │ ├── RemoveLinkedListElements.cpp │ ├── UglyNumber.cpp │ ├── SortArrayByParity.cpp │ ├── ArrayPartition.cpp │ ├── IsSubSequance.cpp │ ├── RectangleOverlap.cpp │ ├── SearchInsertPosition.cpp │ ├── ConcatenationOfArray.cpp │ ├── PascalsTriangle.cpp │ ├── RansomNote.cpp │ ├── FibonacciNumber.cpp │ ├── MaximumDepthOfBinaryTree.cpp │ ├── ReverseStringII.cpp │ ├── ArrangingCoins.cpp │ ├── FindCenterOfStarGraph.cpp │ ├── LengthOfLastWord.cpp │ ├── LongestPalindrome.cpp │ ├── MaximumAverageSubarrayI.cpp │ ├── ReverseWordsInAStringIII.cpp │ ├── FindTheDifference.cpp │ ├── AddBinary.cpp │ ├── DetectCapital.cpp │ ├── LongestCommonPrefix.cpp │ ├── SingleNumber.cpp │ ├── CanMakeArithmeticProgressionFromSequance.cpp │ ├── MaximumProductOfTwoElementsInAnArray.cpp │ ├── KthMissingPositiveNumber.cpp │ ├── MinStack.cpp │ ├── TwoSumIVInputIsABST.cpp │ ├── SqrtX.cpp │ ├── NaryTreePreorderTraversal.cpp │ ├── MinimumDepthOfBinaryTree.cpp │ ├── CheckIfItIsAStraightLine.cpp │ ├── MatrixDiagonalSum.cpp │ ├── SignOfTheProductOfAnArray.cpp │ ├── DeleteNodeInALinkedList.cpp │ ├── ValidAnagram.cpp │ ├── FindSmallestLetterGreaterThanTarget.cpp │ ├── CheckIfNDoubleExist.cpp │ ├── DiameterOfBinaryTree.cpp │ ├── NimGame.cpp │ ├── CountNegativeNumbersInASortedMatrix.cpp │ ├── MonotonicArray.cpp │ ├── DecryptStringFromAlphabetToIntegerMapping.cpp │ ├── PeakIndexInAMountainArray.cpp │ ├── LargestNumberAtLeastTwiceOfOthers.cpp │ ├── DecompressRunLengthEncodedList.cpp │ ├── RepeatedSubstringPattern.cpp │ ├── ValidPalindromeII.cpp │ ├── SelfDividingNumbers.cpp │ ├── LargestSubstringBetweenTwoEqualCharacters.cpp │ ├── MissingNumber.cpp │ ├── SquaresOfASortedArray.cpp │ ├── PalindromeNumber.cpp │ ├── SumOfAllOddLengthSubarrays.cpp │ ├── LowestCommonAncestorOfBinarySearchTree.cpp │ ├── LongestHarmoniousSubsequence.cpp │ ├── AverageSalaryExcludingTheMinimumAndMaximumSalary.cpp │ ├── DayOfTheYear.cpp │ ├── LongestContinuousIncreasingSubsequence.cpp │ ├── BinaryTreePaths.cpp │ ├── ConstuctTheRectangle.cpp │ ├── AverageOfLevelsInBinaryTree.cpp │ ├── FirstBadVersion.cpp │ ├── FizzBuzz.cpp │ ├── HappyNumber.cpp │ ├── ConvertSortedArrayToBinarySearchTree.cpp │ ├── IsomorphicString.cpp │ ├── MinimumAbsoluteDifference.cpp │ ├── PalindromeLinkedList.cpp │ ├── IntersectionOfTwoArrays.cpp │ ├── GuessNumberHigherOrLow.cpp │ ├── MinCostClimbingStairs.cpp │ ├── ReverseLinkedList.cpp │ ├── GoalParserInterpretation.cpp │ ├── DistributeCandies.cpp │ ├── ToeplitzMatrix.cpp │ ├── FlippingAnImage.cpp │ └── SortIntegersByTheNumberOf1Bits.cpp ├── Medium │ ├── CountPrimes.cpp │ ├── SubarraySumEqualsK.cpp │ ├── RemoveNthNodeFromEndOfList.cpp │ ├── SumOfSquareNumbers.cpp │ ├── SingleNumberII.cpp │ ├── JumpGame.cpp │ ├── RotateArray.cpp │ ├── Triangle.cpp │ ├── TopKFrequentElements.cpp │ ├── TrimABinarySearchTree.cpp │ ├── Subsets.cpp │ ├── Combinations.cpp │ ├── ReverseInteger.cpp │ ├── LetterCasePermutation.cpp │ ├── SortColors.cpp │ ├── JumpGameII.cpp │ ├── MinimumPathSum.cpp │ ├── RotateImage.cpp │ ├── OptimalPartitionOfString.cpp │ ├── LongestSubstringWithoutRepeatingCharacters.cpp │ ├── SwapNodesInPairs.cpp │ ├── NextGreaterNodeInLinkedList.cpp │ ├── MaximalSquare.cpp │ ├── Permutations.cpp │ ├── GenerateParentheses.cpp │ ├── LongestPalindromicSubstring.cpp │ ├── ValidateBinarySearchTree.cpp │ ├── HIndex.cpp │ ├── HouseRobber.cpp │ ├── GroupAnagrams.cpp │ ├── 3SumClosest.cpp │ ├── CoinChange.cpp │ ├── DailyTemperatures.cpp │ ├── 4Sum.cpp │ ├── PermutationInString.cpp │ ├── LargestNumber.cpp │ ├── MergeIntervals.cpp │ ├── LongestSubarrayOf1sAfterDeletingOneElement.cpp │ ├── BinaryTreeLevelOrderTraversal.cpp │ ├── BinaryTreeRightSightView.cpp │ ├── PartitionLabels.cpp │ ├── ContainerWithMostWater.cpp │ ├── UniquePaths.cpp │ └── KthLargestElementInArray.cpp └── Hard │ └── BinaryTreeMaximumPathSum.cpp └── Concurrency └── Easy └── PrintInOrder.cpp /Database/Easy/DuplicateEmails.sql: -------------------------------------------------------------------------------- 1 | SELECT p.email 2 | FROM Person p 3 | GROUP BY p.email 4 | HAVING COUNT(*) > 1 -------------------------------------------------------------------------------- /Database/Easy/DeleteDuplicateEmails.sql: -------------------------------------------------------------------------------- 1 | DELETE p1 2 | FROM Person p1, Person p2 3 | WHERE p1.email = p2.email AND p1.id > p2.id -------------------------------------------------------------------------------- /Database/Easy/RecyclableAndLowFatProducts.sql: -------------------------------------------------------------------------------- 1 | SELECT p.product_id 2 | FROM Products p 3 | WHERE p.low_fats = 'Y' AND p.recyclable = 'Y' -------------------------------------------------------------------------------- /Database/Easy/CombineTwoTables.sql: -------------------------------------------------------------------------------- 1 | SELECT p.firstName, p.lastName, a.city, a.state 2 | FROM Person p 3 | LEFT JOIN Address a ON p.personId = a.personId -------------------------------------------------------------------------------- /Database/Easy/CustomersWhoNeverOrder.sql: -------------------------------------------------------------------------------- 1 | SELECT c.name AS Customers 2 | FROM Customers c 3 | WHERE c.id NOT IN( 4 | SELECT o.customerId 5 | FROM Orders o 6 | ) -------------------------------------------------------------------------------- /Algorithms/Easy/SmallestEvenMultiple.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int smallestEvenMultiple(int n) 4 | { 5 | return (n % 2 == 0) ? n : n * 2; 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /Database/Easy/EmployeesEarningMoreThanTheirManagers.sql: -------------------------------------------------------------------------------- 1 | SELECT e.name AS Employee 2 | FROM Employee e 3 | JOIN Employee em ON e.managerId = em.id AND e.salary > em.salary -------------------------------------------------------------------------------- /Database/Medium/CapitalGainLoss.sql: -------------------------------------------------------------------------------- 1 | SELECT s.stock_name, SUM(IF(s.operation='Buy', -s.price, s.price)) AS capital_gain_loss 2 | FROM Stocks s 3 | GROUP BY s.stock_name 4 | -------------------------------------------------------------------------------- /Database/Easy/FindTotalTimeSpentByEachEmployee.sql: -------------------------------------------------------------------------------- 1 | SELECT e.event_day AS day, e.emp_id, SUM(e.out_time - e.in_time) AS total_time 2 | FROM Employees e 3 | GROUP BY e.event_day, e.emp_id -------------------------------------------------------------------------------- /Database/Easy/DailyLeadsAndPartners.sql: -------------------------------------------------------------------------------- 1 | SELECT date_id, make_name, COUNT(DISTINCT lead_id) AS unique_leads, COUNT(DISTINCT partner_id) AS unique_partners 2 | FROM DailySales 3 | GROUP BY date_id, make_name 4 | -------------------------------------------------------------------------------- /Database/Easy/RearrangeProductsTable.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM ( 2 | SELECT product_id, 'store1' store, store1 AS price FROM Products 3 | UNION 4 | SELECT product_id, 'store2' store, store2 AS price FROM Products 5 | UNION 6 | SELECT product_id, 'store3' store, store3 AS price FROM Products 7 | ) r 8 | WHERE price IS NOT NULL 9 | -------------------------------------------------------------------------------- /Algorithms/Easy/RunningSumOf1dArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | std::vector runningSum(const std::vector& nums) 4 | { 5 | std::vector result; 6 | result.reserve(nums.size()); 7 | result.push_back(nums.front()); 8 | for (size_t i = 1u; i < nums.size(); ++i) 9 | result.push_back(nums[i] + result[i - 1]); 10 | 11 | return result; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Algorithms/Easy/FinalValueOfVariableAfterPerformingOperations.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int finalValueAfterOperations(const std::vector& operations) 4 | { 5 | int result = 0; 6 | for (const auto& operation: operations) { 7 | if (operation.front() == '+' || operation.back() == '+') 8 | ++result; 9 | else 10 | --result; 11 | } 12 | 13 | return result; 14 | } 15 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/AddTwoIntegers.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given two integers num1 and num2, return the sum of the two integers. 4 | 5 | // Example 1: 6 | // Input: num1 = 12, num2 = 5 7 | // Output: 17 8 | // Explanation: num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned. 9 | 10 | // Example 2: 11 | // Input: num1 = -10, num2 = 4 12 | // Output: -6 13 | // Explanation: num1 + num2 = -6, so -6 is returned. 14 | 15 | class Solution { 16 | public: 17 | int sum(int num1, int num2) 18 | { 19 | return num1 + num2; 20 | } 21 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/PowerOfFour.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer n, return true if it is a power of four. Otherwise, return false. 4 | // An integer n is a power of four, if there exists an integer x such that n == 4x. 5 | 6 | // Example 1: 7 | // Input: n = 16 8 | // Output: true 9 | 10 | // Example 2: 11 | // Input: n = 5 12 | // Output: false 13 | 14 | // Example 3: 15 | // Input: n = 1 16 | // Output: true 17 | 18 | class Solution 19 | { 20 | public: 21 | bool isPowerOfFour(int n) 22 | { 23 | return n > 0 && (n & (n - 1)) == 0 && n % 3 == 1; 24 | } 25 | }; 26 | 27 | int main(int argc, char** argv) 28 | { 29 | return EXIT_SUCCESS; 30 | } -------------------------------------------------------------------------------- /Algorithms/Easy/PowerOfThree.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer n, return true if it is a power of three. Otherwise, return false. 4 | // An integer n is a power of three, if there exists an integer x such that n == 3x. 5 | 6 | // Example 1: 7 | // Input: n = 27 8 | // Output: true 9 | 10 | // Example 2: 11 | // Input: n = 0 12 | // Output: false 13 | 14 | // Example 3: 15 | // Input: n = 9 16 | // Output: true 17 | 18 | class Solution 19 | { 20 | public: 21 | bool isPowerOfThree(int n) 22 | { 23 | return n > 0 && 1'162'261'467 % n == 0; // 3^19 24 | } 25 | }; 26 | 27 | int main(int argc, char** argv) 28 | { 29 | return EXIT_SUCCESS; 30 | } -------------------------------------------------------------------------------- /Algorithms/Easy/CountOddNumbersInAnIntervalRange.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive). 4 | 5 | // Example 1: 6 | // Input: low = 3, high = 7 7 | // Output: 3 8 | // Explanation: The odd numbers between 3 and 7 are [3,5,7]. 9 | 10 | // Example 2: 11 | // Input: low = 8, high = 10 12 | // Output: 1 13 | // Explanation: The odd numbers between 8 and 10 are [9]. 14 | 15 | class Solution 16 | { 17 | public: 18 | int countOdds(int low, int high) 19 | { 20 | return (high - low) / 2 + !(low % 2 == 0 && high % 2 == 0); 21 | } 22 | }; 23 | 24 | int main(int argc, char** argv) 25 | { 26 | return EXIT_SUCCESS; 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms/Easy/PowerOfTwo.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer n, return true if it is a power of two. Otherwise, return false. 4 | // An integer n is a power of two, if there exists an integer x such that n == 2x. 5 | 6 | // Example 1: 7 | // Input: n = 1 8 | // Output: true 9 | // Explanation: 20 = 1 10 | 11 | // Example 2: 12 | // Input: n = 16 13 | // Output: true 14 | // Explanation: 24 = 16 15 | 16 | // Example 3: 17 | // Input: n = 3 18 | // Output: false 19 | 20 | // 00000111 21 | // 00001000 22 | // 23 | 24 | class Solution 25 | { 26 | public: 27 | bool isPowerOfTwo(int n) 28 | { 29 | return (n > 0) && !(n & (n - 1)); 30 | } 31 | }; 32 | 33 | int main(int argc, char** argv) 34 | { 35 | return EXIT_SUCCESS; 36 | } 37 | -------------------------------------------------------------------------------- /Algorithms/Easy/MaximumProductOfThreeNumbers.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer array nums, find three numbers whose product is maximum and return the maximum product. 4 | 5 | // Example 1: 6 | // Input: nums = [1,2,3] 7 | // Output: 6 8 | 9 | // Example 2: 10 | // Input: nums = [1,2,3,4] 11 | // Output: 24 12 | 13 | // Example 3: 14 | // Input: nums = [-1,-2,-3] 15 | // Output: -6 16 | 17 | class Solution { 18 | public: 19 | int maximumProduct(std::vector& nums) 20 | { 21 | std::sort(begin(nums), end(nums), std::greater()); 22 | const int first_product = nums[0] * nums[1] * nums[2]; 23 | const int second_product = nums[nums.size() - 1] * nums[nums.size() - 2] * nums[0]; 24 | return std::max(first_product, second_product); 25 | } 26 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/ReverseString.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Write a function that reverses a string. The input string is given as an array of characters s. 4 | // You must do this by modifying the input array in-place with O(1) extra memory. 5 | 6 | // Example 1: 7 | // Input: s = ["h","e","l","l","o"] 8 | // Output: ["o","l","l","e","h"] 9 | 10 | // Example 2: 11 | // Input: s = ["H","a","n","n","a","h"] 12 | // Output: ["h","a","n","n","a","H"] 13 | 14 | class Solution 15 | { 16 | public: 17 | void reverseString(vector& s) 18 | { 19 | const size_t middle = s.size() / 2u; 20 | for (size_t i = 0u; i < middle; ++i) { 21 | std::swap(s[i], s[s.size() - 1 - i]); 22 | } 23 | } 24 | }; 25 | 26 | int main() 27 | { 28 | return EXIT_SUCCESS; 29 | } 30 | -------------------------------------------------------------------------------- /Algorithms/Easy/NumberOfSegmentsInAString.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a string s, return the number of segments in the string. 4 | // A segment is defined to be a contiguous sequence of non-space characters. 5 | 6 | // Example 1: 7 | // Input: s = "Hello, my name is John" 8 | // Output: 5 9 | // Explanation: The five segments are ["Hello,", "my", "name", "is", "John"] 10 | 11 | // Example 2: 12 | // Input: s = "Hello" 13 | // Output: 1 14 | 15 | class Solution 16 | { 17 | public: 18 | int countSegments(std::string s) 19 | { 20 | int count_segments = 0; 21 | for (int i = 0; i < s.size(); ++i) { 22 | if ((i == 0 || std::isspace(s[i - 1])) && !std::isspace(s[i])) 23 | ++count_segments; 24 | } 25 | 26 | return count_segments; 27 | } 28 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/ToLowerCase.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a string s, return the string after replacing every uppercase letter with the same lowercase letter. 4 | 5 | // Example 1: 6 | // Input: s = "Hello" 7 | // Output: "hello" 8 | 9 | // Example 2: 10 | // Input: s = "here" 11 | // Output: "here" 12 | 13 | // Example 3: 14 | // Input: s = "LOVELY" 15 | // Output: "lovely" 16 | 17 | class Solution 18 | { 19 | public: 20 | std::string toLowerCase(std::string s) 21 | { 22 | constexpr uint8_t DIFF = 'a' - 'A'; 23 | for (size_t i = 0u; i < s.size(); ++i) { 24 | if (s[i] >= 'A' && s[i] <= 'Z') 25 | s[i] = s[i] + DIFF; 26 | } 27 | return s; 28 | } 29 | }; 30 | 31 | int main(int argc, char** argv) 32 | { 33 | return EXIT_SUCCESS; 34 | } 35 | -------------------------------------------------------------------------------- /Algorithms/Easy/MoveZeroes.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. 4 | // Note that you must do this in-place without making a copy of the array. 5 | 6 | // Example 1: 7 | // Input: nums = [0,1,0,3,12] 8 | // Output: [1,3,12,0,0] 9 | 10 | // Example 2: 11 | // Input: nums = [0] 12 | // Output: [0] 13 | 14 | class Solution 15 | { 16 | public: 17 | void moveZeroes(vector& nums) 18 | { 19 | for (size_t current = 0u, last_zero = 0u; current < nums.size(); ++current) { 20 | if (nums[current] != 0u) { 21 | std::swap(nums[last_zero++], nums[current]); 22 | } 23 | } 24 | } 25 | }; 26 | 27 | int main(int argc, char** argv) 28 | { 29 | return EXIT_SUCCESS; 30 | } 31 | -------------------------------------------------------------------------------- /Algorithms/Medium/CountPrimes.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer n, return the number of prime numbers that are strictly less than n. 4 | 5 | // Example 1: 6 | // Input: n = 10 7 | // Output: 4 8 | // Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. 9 | 10 | // Example 2: 11 | // Input: n = 0 12 | // Output: 0 13 | 14 | // Example 3: 15 | // Input: n = 1 16 | // Output: 0 17 | 18 | class Solution { 19 | public: 20 | int countPrimes(int n) { 21 | int primes_number = 0; 22 | std::vector numbers(n, true); 23 | for (int i = 2; i < n; ++i) { 24 | if (!numbers[i]) 25 | continue; 26 | 27 | ++primes_number; 28 | for (auto j = (long)i * i; j < n; j += i) 29 | numbers[j] = false; 30 | } 31 | 32 | return primes_number; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Algorithms/Easy/DefangingAnIPAddress.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a valid (IPv4) IP address, return a defanged version of that IP address. 4 | // A defanged IP address replaces every period "." with "[.]". 5 | 6 | // Example 1: 7 | // Input: address = "1.1.1.1" 8 | // Output: "1[.]1[.]1[.]1" 9 | 10 | // Example 2: 11 | // Input: address = "255.100.50.0" 12 | // Output: "255[.]100[.]50[.]0" 13 | 14 | class Solution { 15 | public: 16 | std::string defangIPaddr(std::string address) 17 | { 18 | std::string defangedAddress; 19 | defangedAddress.reserve(address.length() + 2u * 3u); 20 | 21 | for (size_t i = 0u; i < address.length(); ++i) { 22 | if (address[i] == '.') { 23 | defangedAddress += '['; 24 | defangedAddress += address[i]; 25 | defangedAddress += ']'; 26 | } else { 27 | defangedAddress += address[i]; 28 | } 29 | } 30 | 31 | return defangedAddress; 32 | } 33 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/AddDigits.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer num, repeatedly add all its digits until the result has only one digit, and return it. 4 | 5 | // Example 1: 6 | // Input: num = 38 7 | // Output: 2 8 | // Explanation: The process is 9 | // 38 --> 3 + 8 --> 11 10 | // 11 --> 1 + 1 --> 2 11 | // Since 2 has only one digit, return it. 12 | 13 | // Example 2: 14 | // Input: num = 0 15 | // Output: 0 16 | 17 | class Solution 18 | { 19 | public: 20 | int addDigits(int num) 21 | { 22 | while (num > 9) { 23 | int temp = num; 24 | int result = 0; 25 | while (temp != 0) { 26 | result += temp % 10; 27 | temp /= 10; 28 | } 29 | num = result; 30 | } 31 | 32 | return num; 33 | } 34 | }; 35 | 36 | int main(int argc, char** argv) 37 | { 38 | return EXIT_SUCCESS; 39 | } 40 | -------------------------------------------------------------------------------- /Algorithms/Easy/LargestPerimeterTriangle.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0. 4 | 5 | // Example 1: 6 | // Input: nums = [2,1,2] 7 | // Output: 5 8 | 9 | // Example 2: 10 | // Input: nums = [1,2,1] 11 | // Output: 0 12 | 13 | class Solution 14 | { 15 | public: 16 | int largestPerimeter(vector& nums) 17 | { 18 | std::sort(begin(nums), end(nums), std::greater()); 19 | for (size_t i = 0u; i < nums.size() - 2u; ++i) { 20 | if (nums[i] < nums[i + 1] + nums[i + 2]) 21 | return nums[i] + nums[i + 1] + nums[i + 2]; 22 | } 23 | 24 | return 0; 25 | } 26 | }; 27 | 28 | int main(int argc, char** argv) 29 | { 30 | return EXIT_SUCCESS; 31 | } 32 | -------------------------------------------------------------------------------- /Algorithms/Medium/SubarraySumEqualsK.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. 4 | // A subarray is a contiguous non-empty sequence of elements within an array. 5 | 6 | // Example 1: 7 | // Input: nums = [1,1,1], k = 2 8 | // Output: 2 9 | 10 | // Example 2: 11 | // Input: nums = [1,2,3], k = 3 12 | // Output: 2 13 | 14 | class Solution { 15 | public: 16 | int subarraySum(vector& nums, int k) 17 | { 18 | std::unordered_map sums; 19 | sums.emplace(0, 1); 20 | 21 | int result = 0; 22 | int current_sum = 0; 23 | for (const int number: nums) { 24 | current_sum += number; 25 | 26 | const int diff = current_sum - k; 27 | result += sums[diff]; 28 | sums[current_sum]++; 29 | } 30 | 31 | return result; 32 | } 33 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/MajorityElement.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an array nums of size n, return the majority element. 4 | // The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. 5 | 6 | // Example 1: 7 | // Input: nums = [3,2,3] 8 | // Output: 3 9 | 10 | // Example 2: 11 | // Input: nums = [2,2,1,1,1,2,2] 12 | // Output: 2 13 | 14 | class Solution 15 | { 16 | public: 17 | int majorityElement(const std::vector& nums) 18 | { 19 | int count = 0; 20 | int candidate = std::numeric_limits::min(); 21 | for (auto num : nums) { 22 | if (count == 0) { 23 | candidate = num; 24 | } 25 | count += (num == candidate) ? 1 : -1; 26 | } 27 | 28 | return candidate; 29 | } 30 | }; 31 | 32 | int main(int argc, char** argv) 33 | { 34 | return EXIT_SUCCESS; 35 | } -------------------------------------------------------------------------------- /Algorithms/Easy/ContainDuplicates.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. 4 | 5 | // Example 1: 6 | // Input: nums = [1,2,3,1] 7 | // Output: true 8 | 9 | // Example 2: 10 | // Input: nums = [1,2,3,4] 11 | // Output: false 12 | 13 | // Example 3: 14 | // Input: nums = [1,1,1,3,3,4,3,2,4,2] 15 | // Output: true 16 | 17 | class Solution 18 | { 19 | public: 20 | bool containsDuplicate(const vector& nums) 21 | { 22 | std::unordered_set duplicates; 23 | for (const int num : nums) { 24 | if (duplicates.count(num)) { 25 | return true; 26 | } else { 27 | duplicates.insert(num); 28 | } 29 | } 30 | return false; 31 | } 32 | }; 33 | 34 | int main(int argc, char** argv) 35 | { 36 | return EXIT_SUCCESS; 37 | } 38 | -------------------------------------------------------------------------------- /Algorithms/Easy/PascalsTriangleII.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. 4 | // In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: 5 | 6 | // Example 1: 7 | // Input: rowIndex = 3 8 | // Output: [1,3,3,1] 9 | 10 | // Example 2: 11 | // Input: rowIndex = 0 12 | // Output: [1] 13 | 14 | // Example 3: 15 | // Input: rowIndex = 1 16 | // Output: [1,1] 17 | 18 | class Solution 19 | { 20 | public: 21 | std::vector getRow(int row_index) 22 | { 23 | std::vector row(1, 1); 24 | for (size_t i = 0u; i < row_index; ++i) { 25 | row.push_back(1); 26 | for (size_t i = row.size() - 2; i > 0; --i) { 27 | row[i] += row[i - 1]; 28 | } 29 | } 30 | 31 | return row; 32 | } 33 | }; 34 | 35 | int main(int argc, char** argv) 36 | { 37 | return EXIT_SUCCESS; 38 | } -------------------------------------------------------------------------------- /Algorithms/Easy/ConvertBinaryNumberInALinkedListToInteger.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number. 4 | // Return the decimal value of the number in the linked list. 5 | 6 | // Example 1: 7 | // Input: head = [1,0,1] 8 | // Output: 5 9 | // Explanation: (101) in base 2 = (5) in base 10 10 | 11 | // Example 2: 12 | // Input: head = [0] 13 | // Output: 0 14 | 15 | class Solution 16 | { 17 | public: 18 | int getDecimalValue(ListNode* head) 19 | { 20 | int number = head->val; 21 | head = head->next; 22 | 23 | while (head) { 24 | number = (number << 1) | head->val; 25 | head = head->next; 26 | } 27 | 28 | return number; 29 | } 30 | }; 31 | 32 | int main(int argc, char** argv) 33 | { 34 | return EXIT_SUCCESS; 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms/Easy/MiddleOfTheLinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given the head of a singly linked list, return the middle node of the linked list. 4 | // If there are two middle nodes, return the second middle node. 5 | 6 | // Example 1: 7 | // Input: head = [1,2,3,4,5] 8 | // Output: [3,4,5] 9 | // Explanation: The middle node of the list is node 3. 10 | 11 | // Example 2: 12 | // Input: head = [1,2,3,4,5,6] 13 | // Output: [4,5,6] 14 | // Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one. 15 | 16 | class Solution { 17 | public: 18 | ListNode* middleNode(ListNode* head) { 19 | ListNode* slow = head; 20 | ListNode* fast = head; 21 | while (fast && fast->next) { 22 | slow = slow->next; 23 | fast = fast->next->next; 24 | } 25 | 26 | return slow; 27 | } 28 | }; 29 | 30 | int main(int argc, char** argv) 31 | { 32 | return EXIT_SUCCESS; 33 | } 34 | -------------------------------------------------------------------------------- /Algorithms/Easy/MaxConsecutiveOnes.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a binary array nums, return the maximum number of consecutive 1's in the array. 4 | 5 | // Example 1: 6 | // Input: nums = [1,1,0,1,1,1] 7 | // Output: 3 8 | // Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. 9 | 10 | // Example 2: 11 | // Input: nums = [1,0,1,1,0,1] 12 | // Output: 2 13 | 14 | class Solution 15 | { 16 | public: 17 | int findMaxConsecutiveOnes(std::vector& nums) 18 | { 19 | int consecutive_ones = 0; 20 | int max_consecutive_ones = 0; 21 | for (const int num: nums) { 22 | if (num == 1) { 23 | ++consecutive_ones; 24 | max_consecutive_ones = std::max(max_consecutive_ones, consecutive_ones); 25 | } else { 26 | consecutive_ones = 0; 27 | } 28 | } 29 | 30 | return max_consecutive_ones; 31 | } 32 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/RemoveDuplicatesFromSortedList.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well. 4 | 5 | // Example 1: 6 | // Input: head = [1,1,2] 7 | // Output: [1,2] 8 | 9 | // Example 2: 10 | // Input: head = [1,1,2,3,3] 11 | // Output: [1,2,3] 12 | 13 | class Solution { 14 | public: 15 | ListNode* deleteDuplicates(ListNode* head) 16 | { 17 | if (!head) { 18 | return head; 19 | } 20 | 21 | ListNode* iterator = head; 22 | while (iterator && iterator->next) { 23 | if (iterator->val == iterator->next->val) { 24 | iterator->next = iterator->next->next; 25 | } else { 26 | iterator = iterator->next; 27 | } 28 | } 29 | 30 | return head; 31 | } 32 | }; 33 | 34 | int main(int argc, char** argv) 35 | { 36 | return EXIT_SUCCESS; 37 | } 38 | -------------------------------------------------------------------------------- /Algorithms/Easy/SearchInABinaryTree.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // You are given the root of a binary search tree (BST) and an integer val. 4 | // Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null. 5 | 6 | // Example 1: 7 | // Input: root = [4,2,7,1,3], val = 2 8 | // Output: [2,1,3] 9 | 10 | // Example 2: 11 | // Input: root = [4,2,7,1,3], val = 5 12 | // Output: [] 13 | 14 | class Solution { 15 | public: 16 | TreeNode* searchBST(TreeNode* root, int val) 17 | { 18 | TreeNode* node = root; 19 | while (node) { 20 | if (node->val < val) 21 | node = node->right; 22 | else if (node->val > val) 23 | node = node->left; 24 | else 25 | return node; 26 | } 27 | 28 | return nullptr; 29 | } 30 | }; 31 | 32 | int main(int argc, char** argv) 33 | { 34 | return EXIT_SUCCESS; 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms/Easy/SumOfLeftLeaves.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given the root of a binary tree, return the sum of all left leaves. 4 | // A leaf is a node with no children. A left leaf is a leaf that is the left child of another node. 5 | 6 | // Example 1: 7 | // Input: root = [3,9,20,null,null,15,7] 8 | // Output: 24 9 | // Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively. 10 | 11 | // Example 2: 12 | // Input: root = [1] 13 | // Output: 0 14 | 15 | class Solution { 16 | public: 17 | int sumOfLeftLeaves(TreeNode* root) 18 | { 19 | if (!root) { 20 | return 0; 21 | } else if (root->left && !root->left->left && !root->left->right) { 22 | return root->left->val + sumOfLeftLeaves(right); 23 | } else { 24 | return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right); 25 | } 26 | } 27 | }; 28 | 29 | int main(int argc, char** argv) 30 | { 31 | return EXIT_SUCCESS; 32 | } 33 | -------------------------------------------------------------------------------- /Algorithms/Easy/ThreeDivisors.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer n, return true if n has exactly three positive divisors. Otherwise, return false. 4 | // An integer m is a divisor of n if there exists an integer k such that n = k * m. 5 | 6 | // Example 1: 7 | // Input: n = 2 8 | // Output: false 9 | // Explantion: 2 has only two divisors: 1 and 2. 10 | 11 | // Example 2: 12 | // Input: n = 4 13 | // Output: true 14 | // Explantion: 4 has three divisors: 1, 2, and 4. 15 | 16 | class Solution { 17 | public: 18 | bool isThree(int n) 19 | { 20 | if (n < 4) 21 | return false; 22 | 23 | const int n_square = sqrt(n); 24 | return n_square * n_square == n && isPrime(n_square); 25 | } 26 | 27 | bool isPrime(int n) 28 | { 29 | const int n_square = sqrt(n); 30 | for (int i = 2; i <= n_square; ++i) { 31 | if (n % i == 0) 32 | return false; 33 | } 34 | 35 | return true; 36 | } 37 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/ConsecutiveCharacters.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // The power of the string is the maximum length of a non-empty substring that contains only one unique character. 4 | // Given a string s, return the power of s. 5 | 6 | // Example 1: 7 | // Input: s = "leetcode" 8 | // Output: 2 9 | // Explanation: The substring "ee" is of length 2 with the character 'e' only. 10 | 11 | // Example 2: 12 | // Input: s = "abbcccddddeeeeedcba" 13 | // Output: 5 14 | // Explanation: The substring "eeeee" is of length 5 with the character 'e' only. 15 | 16 | class Solution { 17 | public: 18 | int maxPower(const std::string& s) 19 | { 20 | int left = 0; 21 | int max_power = 0; 22 | while (left < s.size()) { 23 | int right = left + 1; 24 | while (right < s.size() && s[left] == s[right]) 25 | ++right; 26 | 27 | max_power = std::max(max_power, right - left); 28 | left = right; 29 | } 30 | 31 | return max_power; 32 | } 33 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/ExcelSheetColumnNumber.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet. 4 | 5 | // For example: 6 | // A -> 1 7 | // B -> 2 8 | // C -> 3 9 | // ... 10 | // Z -> 26 11 | // AA -> 27 12 | // AB -> 28 13 | // ... 14 | 15 | // Example 1: 16 | // Input: columnNumber = 1 17 | // Output: "A" 18 | 19 | // Example 2: 20 | // Input: columnNumber = 28 21 | // Output: "AB" 22 | 23 | // Example 3: 24 | // Input: columnNumber = 701 25 | // Output: "ZY" 26 | 27 | class Solution { 28 | public: 29 | std::string convertToTitle(int column_number) 30 | { 31 | std::string result; 32 | while (column_number > 0) { 33 | result.push_back((column_number - 1) % 26 + 'A'); 34 | column_number = (column_number - 1) / 26; 35 | } 36 | 37 | std::reverse(begin(result), end(result)); 38 | return result; 39 | } 40 | }; 41 | 42 | int main(int argc, char** argv) 43 | { 44 | return EXIT_SUCCESS; 45 | } -------------------------------------------------------------------------------- /Algorithms/Easy/FirstUniqueCharacterInAString.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1. 4 | 5 | // Example 1: 6 | // Input: s = "leetcode" 7 | // Output: 0 8 | 9 | // Example 2: 10 | // Input: s = "loveleetcode" 11 | // Output: 2 12 | 13 | // Example 3: 14 | // Input: s = "aabb" 15 | // Output: -1 16 | 17 | class Solution 18 | { 19 | public: 20 | int firstUniqChar(string s) 21 | { 22 | constexpr size_t ALPHABET_SIZE = 'z' - 'a' + 1u; 23 | std::array symbols{}; 24 | for (const char sym : s) { 25 | const char index = sym - 'a'; 26 | symbols[index] += 1u; 27 | } 28 | 29 | for (size_t i = 0u; i < s.size(); ++i) { 30 | const char sym = s[i]; 31 | const char index = sym - 'a'; 32 | if (symbols[index] == 1) { 33 | return i; 34 | } 35 | } 36 | 37 | return -1; 38 | } 39 | }; 40 | 41 | int main(int argc, char** argv) 42 | { 43 | return EXIT_SUCCESS; 44 | } 45 | -------------------------------------------------------------------------------- /Algorithms/Easy/CountingBits.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i. 4 | 5 | // Example 1: 6 | // Input: n = 2 7 | // Output: [0,1,1] 8 | // Explanation: 9 | // 0 --> 0 10 | // 1 --> 1 11 | // 2 --> 10 12 | 13 | // Example 2: 14 | // Input: n = 5 15 | // Output: [0,1,1,2,1,2] 16 | // Explanation: 17 | // 0 --> 0 18 | // 1 --> 1 19 | // 2 --> 10 20 | // 3 --> 11 21 | // 4 --> 100 22 | // 5 --> 101 23 | 24 | class Solution { 25 | public: 26 | std::vector countBits(int n) 27 | { 28 | size_t offset = 1u; 29 | std::vector dp(n + 1, 0); 30 | for (size_t i = 1u; i < n + 1; ++i) { 31 | if (offset * 2 == i) 32 | offset = i; 33 | 34 | dp[i] = 1 + dp[i - offset]; 35 | } 36 | 37 | return dp; 38 | } 39 | }; 40 | 41 | int main(int argc, char** argv) 42 | { 43 | return EXIT_SUCCESS; 44 | } -------------------------------------------------------------------------------- /Algorithms/Easy/InvertBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given the root of a binary tree, invert the tree, and return its root. 4 | 5 | // Example 1: 6 | // Input: root = [4,2,7,1,3,6,9] 7 | // Output: [4,7,2,9,6,3,1] 8 | 9 | // Example 2: 10 | // Input: root = [2,1,3] 11 | // Output: [2,3,1] 12 | 13 | // Example 3: 14 | // Input: root = [] 15 | // Output: [] 16 | 17 | class Solution 18 | { 19 | public: 20 | TreeNode* invertTree(TreeNode* root) 21 | { 22 | std::function impl; 23 | impl = [] (TreeNode* node) 24 | { 25 | if (node) { 26 | TreeNode* left = node->left; 27 | TreeNode* right = node->right; 28 | node->left = right; 29 | node->right = left; 30 | 31 | impl(node->left); 32 | impl(node->right); 33 | } 34 | }; 35 | 36 | impl(root); 37 | return root; 38 | } 39 | }; 40 | 41 | int main(int argc, char** argv) 42 | { 43 | return EXIT_SUCCESS; 44 | } -------------------------------------------------------------------------------- /Algorithms/Easy/MaximumSubarray.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 4 | // A subarray is a contiguous part of an array. 5 | 6 | // Example 1: 7 | // Input: nums = [-2,1,-3,4,-1,2,1,-5,4] 8 | // Output: 6 9 | // Explanation: [4,-1,2,1] has the largest sum = 6. 10 | 11 | // Example 2: 12 | // Input: nums = [1] 13 | // Output: 1 14 | 15 | // Example 3: 16 | // Input: nums = [5,4,-1,7,8] 17 | // Output: 23 18 | 19 | class Solution 20 | { 21 | public: 22 | int maxSubArray(std::vector& nums) 23 | { 24 | int max_sum = nums[0u]; 25 | int current_sum = max_sum; 26 | for (size_t i = 1u; i < nums.size(); ++i) { 27 | current_sum = std::max(nums[i], current_sum + nums[i]); 28 | max_sum = std::max(max_sum, current_sum); 29 | } 30 | 31 | return max_sum; 32 | } 33 | }; 34 | 35 | int main(int argc, char** argv) 36 | { 37 | return EXIT_SUCCESS; 38 | } 39 | -------------------------------------------------------------------------------- /Algorithms/Easy/TransposeMatrix.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a 2D integer array matrix, return the transpose of matrix. 4 | // The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. 5 | 6 | // Example 1: 7 | // Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] 8 | // Output: [[1,4,7],[2,5,8],[3,6,9]] 9 | 10 | // Example 2: 11 | // Input: matrix = [[1,2,3],[4,5,6]] 12 | // Output: [[1,4],[2,5],[3,6]] 13 | 14 | class Solution 15 | { 16 | public: 17 | std::vector> transpose(std::vector>& matrix) 18 | { 19 | const int rows_size = matrix.size(); 20 | const int cols_size = matrix[0].size(); 21 | std::vector> result(cols_size, std::vector(rows_size)); 22 | 23 | for (int row = 0; row < rows_size; ++row) { 24 | for (int col = 0; col < cols_size; ++col) { 25 | result[col][row] = matrix[row][col]; 26 | } 27 | } 28 | 29 | return result; 30 | } 31 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/BinaryTreePreorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given the root of a binary tree, return the preorder traversal of its nodes' values. 4 | 5 | // Example 1: 6 | // Input: root = [1,null,2,3] 7 | // Output: [1,2,3] 8 | 9 | // Example 2: 10 | // Input: root = [] 11 | // Output: [] 12 | 13 | // Example 3: 14 | // Input: root = [1] 15 | // Output: [1] 16 | 17 | class Solution 18 | { 19 | public: 20 | std::vector preorderTraversal(TreeNode* root) 21 | { 22 | std::vector result; 23 | std::function impl; 24 | impl = [&impl, &result] (TreeNode* node) 25 | { 26 | result.push_back(node->val); 27 | if (node->left) { 28 | impl(node->left); 29 | } 30 | if (node->right) { 31 | impl(node->right); 32 | } 33 | }; 34 | 35 | if (root) { 36 | impl(root); 37 | } 38 | 39 | return result; 40 | } 41 | }; 42 | 43 | int main(int argc, char** argv) 44 | { 45 | return EXIT_SUCCESS; 46 | } -------------------------------------------------------------------------------- /Algorithms/Easy/ClimbingStairs.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // You are climbing a staircase. It takes n steps to reach the top. 4 | // Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 5 | 6 | // Example 1: 7 | // Input: n = 2 8 | // Output: 2 9 | // Explanation: There are two ways to climb to the top. 10 | // 1. 1 step + 1 step 11 | // 2. 2 steps 12 | 13 | // Example 2: 14 | // Input: n = 3 15 | // Output: 3 16 | // Explanation: There are three ways to climb to the top. 17 | // 1. 1 step + 1 step + 1 step 18 | // 2. 1 step + 2 steps 19 | // 3. 2 steps + 1 step 20 | 21 | class Solution 22 | { 23 | public: 24 | int climbStairs(int n) 25 | { 26 | int step1 = 1; 27 | int step2 = 1; 28 | for (size_t i = 2u; i <= n; ++i) { 29 | const int current_step = step1 + step2; 30 | step1 = step2; 31 | step2 = current_step; 32 | } 33 | return step2; 34 | } 35 | }; 36 | 37 | int main(int argc, char** argv) 38 | { 39 | return EXIT_SUCCESS; 40 | } -------------------------------------------------------------------------------- /Algorithms/Easy/BinaryTreeInorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given the root of a binary tree, return the inorder traversal of its nodes' values. 4 | 5 | // Example 1: 6 | // Input: root = [1,null,2,3] 7 | // Output: [1,3,2] 8 | 9 | // Example 2: 10 | // Input: root = [] 11 | // Output: [] 12 | 13 | // Example 3: 14 | // Input: root = [1] 15 | // Output: [1] 16 | 17 | class Solution 18 | { 19 | public: 20 | std::vector inorderTraversal(TreeNode* root) 21 | { 22 | std::vector result; 23 | std::function impl; 24 | impl = [&impl, &result] (TreeNode* node) 25 | { 26 | if (node->left) { 27 | impl(node->left); 28 | } 29 | 30 | result.push_back(node->val); 31 | if (node->right) { 32 | impl(node->right); 33 | } 34 | }; 35 | 36 | if (root) { 37 | impl(root); 38 | } 39 | 40 | return result; 41 | } 42 | }; 43 | 44 | int main(int argc, char** argv) 45 | { 46 | return EXIT_SUCCESS; 47 | } -------------------------------------------------------------------------------- /Algorithms/Easy/RangeSumOfBST.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high]. 4 | 5 | // Example 1: 6 | // Input: root = [10,5,15,3,7,null,18], low = 7, high = 15 7 | // Output: 32 8 | // Explanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32. 9 | 10 | // Example 2: 11 | // Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10 12 | // Output: 23 13 | // Explanation: Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23. 14 | 15 | class Solution 16 | { 17 | public: 18 | int rangeSumBST(TreeNode* root, int low, int high) 19 | { 20 | if (!root) 21 | return 0; 22 | 23 | int current_value = 0; 24 | if (low <= root->val && root->val <= high) 25 | current_value += root->val; 26 | 27 | return current_value + 28 | rangeSumBST(root->left, low, high) + 29 | rangeSumBST(root->right, low, high); 30 | } 31 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/ShuffleTheArray.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn]. 4 | // Return the array in the form [x1,y1,x2,y2,...,xn,yn]. 5 | 6 | // Example 1: 7 | // Input: nums = [2,5,1,3,4,7], n = 3 8 | // Output: [2,3,5,4,1,7] 9 | // Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7]. 10 | 11 | // Example 2: 12 | // Input: nums = [1,2,3,4,4,3,2,1], n = 4 13 | // Output: [1,4,2,3,3,2,4,1] 14 | 15 | // Example 3: 16 | // Input: nums = [1,1,2,2], n = 2 17 | // Output: [1,2,1,2] 18 | 19 | class Solution 20 | { 21 | public: 22 | std::vector shuffle(std::vector& nums, int n) 23 | { 24 | std::vector result; 25 | result.reserve(nums.size()); 26 | for (size_t i = 0u; i < n; ++i) { 27 | result.push_back(nums[i]); 28 | result.push_back(nums[n + i]); 29 | } 30 | return result; 31 | } 32 | }; 33 | 34 | int main(int argc, char** argv) 35 | { 36 | return EXIT_SUCCESS; 37 | } 38 | -------------------------------------------------------------------------------- /Algorithms/Easy/SubtractTheProductAndSumOfDigitsOfAnInteger.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer number n, return the difference between the product of its digits and the sum of its digits. 4 | 5 | // Example 1: 6 | // Input: n = 234 7 | // Output: 15 8 | // Explanation: 9 | // Product of digits = 2 * 3 * 4 = 24 10 | // Sum of digits = 2 + 3 + 4 = 9 11 | // Result = 24 - 9 = 15 12 | 13 | // Example 2: 14 | // Input: n = 4421 15 | // Output: 21 16 | // Explanation: 17 | // Product of digits = 4 * 4 * 2 * 1 = 32 18 | // Sum of digits = 4 + 4 + 2 + 1 = 11 19 | // Result = 32 - 11 = 21 20 | 21 | class Solution 22 | { 23 | public: 24 | int subtractProductAndSum(int n) 25 | { 26 | int sum = 0; 27 | int product = 1; 28 | 29 | while (n) { 30 | const int value = n % 10; 31 | product *= value; 32 | sum += value; 33 | n /= 10; 34 | } 35 | 36 | return product - sum; 37 | } 38 | }; 39 | 40 | int main(int argc, char** argv) 41 | { 42 | return EXIT_SUCCESS; 43 | } 44 | -------------------------------------------------------------------------------- /Algorithms/Easy/ValidPerfectSquare.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a positive integer num, write a function which returns True if num is a perfect square else False. 4 | // Follow up: Do not use any built-in library function such as sqrt. 5 | 6 | // Example 1: 7 | // Input: num = 16 8 | // Output: true 9 | 10 | // Example 2: 11 | // Input: num = 14 12 | // Output: false 13 | 14 | class Solution 15 | { 16 | public: 17 | bool isPerfectSquare(int num) 18 | { 19 | int left = 1; 20 | int right = num; 21 | 22 | while (left <= right) { 23 | const long long middle = left + (right - left) / 2; 24 | const long long target = middle * middle; 25 | if (target < num) { 26 | left = middle + 1; 27 | } else if (target > num) { 28 | right = middle - 1; 29 | } else { 30 | return true; 31 | } 32 | } 33 | 34 | return false; 35 | } 36 | }; 37 | 38 | int main(int argc, char** argv) 39 | { 40 | return EXIT_SUCCESS; 41 | } 42 | -------------------------------------------------------------------------------- /Algorithms/Medium/RemoveNthNodeFromEndOfList.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given the head of a linked list, remove the nth node from the end of the list and return its head. 4 | 5 | // Example 1: 6 | // Input: head = [1,2,3,4,5], n = 2 7 | // Output: [1,2,3,5] 8 | 9 | // Example 2: 10 | // Input: head = [1], n = 1 11 | // Output: [] 12 | 13 | // Example 3: 14 | // Input: head = [1,2], n = 1 15 | // Output: [1] 16 | 17 | class Solution 18 | { 19 | public: 20 | ListNode* removeNthFromEnd(ListNode* head, int n) 21 | { 22 | ListNode* slow = head; 23 | ListNode* fast = head; 24 | for (int i = 0; i < n; ++i) { 25 | fast = fast->next; 26 | } 27 | 28 | if (!fast) { 29 | return head->next; 30 | } 31 | 32 | while (fast->next) { 33 | fast = fast->next; 34 | slow = slow->next; 35 | } 36 | 37 | slow->next = slow->next->next; 38 | return head; 39 | } 40 | }; 41 | 42 | int main(int argc, char** argv) 43 | { 44 | return EXIT_SUCCESS; 45 | } 46 | -------------------------------------------------------------------------------- /Algorithms/Easy/FindTheDistanceValueBetweenTwoArrays.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | class Solution { 4 | public: 5 | int findTheDistanceValue(vector& arr1, vector& arr2, int d) 6 | { 7 | int result = 0; 8 | std::sort(begin(arr2), end(arr2)); 9 | for (const int num : arr1) { 10 | int left = -1; 11 | int right = arr2.size(); 12 | while (right - left > 1) { 13 | const int middle = left + (right - left) / 2; 14 | if (arr2[middle] >= num) { 15 | right = middle; 16 | } else { 17 | left = middle; 18 | } 19 | } 20 | 21 | int min_d = std::numeric_limits::max(); 22 | if (right > 0) 23 | min_d = std::min(min_d, abs(num - arr2[right - 1])); 24 | if (right < arr2.size()) 25 | min_d = std::min(min_d, abs(num - arr2[right])); 26 | if (min_d > d) 27 | ++result; 28 | } 29 | 30 | return result; 31 | } 32 | }; 33 | 34 | int main(int argc, char** argv) 35 | { 36 | return EXIT_SUCCESS; 37 | } 38 | -------------------------------------------------------------------------------- /Algorithms/Easy/BinaryTreePostorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given the root of a binary tree, return the postorder traversal of its nodes' values. 4 | 5 | // Example 1: 6 | // Input: root = [1,null,2,3] 7 | // Output: [3,2,1] 8 | 9 | // Example 2: 10 | // Input: root = [] 11 | // Output: [] 12 | 13 | // Example 3: 14 | // Input: root = [1] 15 | // Output: [1] 16 | 17 | class Solution 18 | { 19 | public: 20 | std::vector postorderTraversal(TreeNode* root) 21 | { 22 | std::vector result; 23 | std::function impl; 24 | impl = [&impl, &result] (TreeNode* node) 25 | { 26 | if (node->left) { 27 | impl(node->left); 28 | } 29 | if (node->right) { 30 | impl(node->right); 31 | } 32 | result.push_back(node->val); 33 | }; 34 | 35 | if (root) { 36 | impl(root); 37 | } 38 | 39 | return result; 40 | } 41 | }; 42 | 43 | int main(int argc, char** argv) 44 | { 45 | return EXIT_SUCCESS; 46 | } 47 | -------------------------------------------------------------------------------- /Algorithms/Easy/FindTheHighestAltitude.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts his trip on point 0 with altitude equal 0. 4 | // You are given an integer array gain of length n where gain[i] is the net gain in altitude between points i​​​​​​ and i + 1 for all (0 <= i < n). Return the highest altitude of a point. 5 | 6 | // Example 1: 7 | // Input: gain = [-5,1,5,0,-7] 8 | // Output: 1 9 | // Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1. 10 | 11 | // Example 2: 12 | // Input: gain = [-4,-3,-2,-1,4,3,2] 13 | // Output: 0 14 | // Explanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0. 15 | 16 | class Solution { 17 | public: 18 | int largestAltitude(std::vector& gain) 19 | { 20 | int altitude = 0; 21 | int highest_altitude = 0; 22 | for (const int value: gain) { 23 | altitude += value; 24 | highest_altitude = std::max(highest_altitude, altitude); 25 | } 26 | 27 | return highest_altitude; 28 | } 29 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/RemoveLinkedListElements.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head. 4 | 5 | // Example 1: p c 6 | // Input: head = [1,2,6,3,4,5,6], val = 6 7 | // Output: [1,2,3,4,5] 8 | 9 | // Example 2: 10 | // Input: head = [], val = 1 11 | // Output: [] 12 | 13 | // Example 3: 14 | // Input: head = [7,7,7,7], val = 7 15 | // Output: [] 16 | 17 | class Solution 18 | { 19 | public: 20 | ListNode* removeElements(ListNode* head, int val) 21 | { 22 | while (head && head->val == val) { 23 | head = head->next; 24 | } 25 | 26 | ListNode* current = head; 27 | while (current && current->next) { 28 | if (current->next->val == val) { 29 | current->next = current->next->next; 30 | } else { 31 | current = current->next; 32 | } 33 | } 34 | 35 | return head; 36 | } 37 | }; 38 | 39 | int main() 40 | { 41 | return EXIT_SUCCESS; 42 | } 43 | -------------------------------------------------------------------------------- /Algorithms/Easy/UglyNumber.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. 4 | // Given an integer n, return true if n is an ugly number. 5 | 6 | // Example 1: 7 | // Input: n = 6 8 | // Output: true 9 | // Explanation: 6 = 2 × 3 10 | 11 | // Example 2: 12 | // Input: n = 1 13 | // Output: true 14 | // Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. 15 | 16 | // Example 3: 17 | // Input: n = 14 18 | // Output: false 19 | // Explanation: 14 is not ugly since it includes the prime factor 7. 20 | 21 | class Solution 22 | { 23 | public: 24 | bool isUgly(int n) 25 | { 26 | if (n <= 0) { 27 | return false; 28 | } 29 | 30 | while (n % 2 == 0) { 31 | n /= 2; 32 | } 33 | while (n % 3 == 0) { 34 | n /= 3; 35 | } 36 | while (n % 5 == 0) { 37 | n /= 5; 38 | } 39 | 40 | return n == 1; 41 | } 42 | }; 43 | 44 | int main(int argc, char** argv) 45 | { 46 | return EXIT_SUCCESS; 47 | } 48 | -------------------------------------------------------------------------------- /Algorithms/Medium/SumOfSquareNumbers.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c. 4 | 5 | // Example 1: 6 | // Input: c = 5 7 | // Output: true 8 | // Explanation: 1 * 1 + 2 * 2 = 5 9 | 10 | // Example 2: 11 | // Input: c = 3 12 | // Output: false 13 | 14 | class Solution 15 | { 16 | public: 17 | bool judgeSquareSum(int c) 18 | { 19 | int left = 0; 20 | int right = std::sqrt(c); 21 | long long left_square = left * left; 22 | long long right_square = right * right; 23 | 24 | while (left <= right) { 25 | const long long expression = left_square + right_square; 26 | if (expression < c) { 27 | ++left; 28 | left_square = left * left; 29 | } else if (expression > c) { 30 | --right; 31 | right_square = right * right; 32 | } else { 33 | return true; 34 | } 35 | } 36 | 37 | return false; 38 | } 39 | }; 40 | 41 | int main(int argc, char** argv) 42 | { 43 | return EXIT_SUCCESS; 44 | } 45 | -------------------------------------------------------------------------------- /Algorithms/Easy/SortArrayByParity.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers. 4 | // Return any array that satisfies this condition. 5 | 6 | // Example 1: 7 | // Input: nums = [3,1,2,4] 8 | // Output: [2,4,3,1] 9 | // Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. 10 | 11 | // Example 2: 12 | // Input: nums = [0] 13 | // Output: [0] 14 | 15 | class Solution 16 | { 17 | public: 18 | std::vector sortArrayByParity(std::vector& nums) 19 | { 20 | size_t left = 0; 21 | size_t right = nums.size() - 1; 22 | while (left < right) { 23 | if (nums[left] % 2 > nums[right] % 2) 24 | std::swap(nums[left], nums[right]); 25 | 26 | if (nums[left] % 2 == 0) 27 | ++left; 28 | if (nums[right] % 2 == 1) 29 | --right; 30 | } 31 | 32 | return nums; 33 | } 34 | }; 35 | 36 | int main(int argc, char** argv) 37 | { 38 | return EXIT_SUCCESS; 39 | } -------------------------------------------------------------------------------- /Algorithms/Medium/SingleNumberII.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it. 4 | // You must implement a solution with a linear runtime complexity and use only constant extra space. 5 | 6 | // Example 1: 7 | // Input: nums = [2,2,3,2] 8 | // Output: 3 9 | 10 | // Example 2: 11 | // Input: nums = [0,1,0,1,0,1,99] 12 | // Output: 99 13 | 14 | class Solution 15 | { 16 | public: 17 | int singleNumber(const std::vector& numbers) 18 | { 19 | std::array representation{ 0 }; 20 | for (int number: numbers) { 21 | for (int i = 0; i < 32; ++i) { 22 | if (number & 1) 23 | ++representation[i]; 24 | 25 | number = number >> 1; 26 | } 27 | } 28 | 29 | int sigle_number = 0; 30 | for (int i = 0; i < 32; ++i) { 31 | if (representation[i] % 3 != 0) 32 | sigle_number += (1 << i); 33 | } 34 | 35 | return sigle_number; 36 | } 37 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/ArrayPartition.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer array nums of 2n integers, group these integers into n pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized. Return the maximized sum. 4 | 5 | // Example 1: 6 | // Input: nums = [1,4,3,2] 7 | // Output: 4 8 | // Explanation: All possible pairings (ignoring the ordering of elements) are: 9 | // 1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3 10 | // 2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3 11 | // 3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4 12 | // So the maximum possible sum is 4. 13 | 14 | // Example 2: 15 | // Input: nums = [6,2,6,5,1,2] 16 | // Output: 9 17 | // Explanation: The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9. 18 | 19 | class Solution 20 | { 21 | public: 22 | int arrayPairSum(std::vector& nums) 23 | { 24 | int sum = 0; 25 | std::sort(begin(nums), end(nums)); 26 | for (int i = 0; i < nums.size(); i += 2) 27 | sum += nums[i]; 28 | 29 | return sum; 30 | } 31 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/IsSubSequance.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given two strings s and t, return true if s is a subsequence of t, or false otherwise. 4 | // 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). 5 | 6 | // Example 1: 7 | // Input: s = "abc", t = "ahbgdc" 8 | // Output: true 9 | 10 | // Example 2: 11 | // Input: s = "axc", t = "ahbgdc" 12 | // Output: false 13 | 14 | class Solution 15 | { 16 | public: 17 | bool isSubsequence(std::string source, std::string target) 18 | { 19 | if (source.empty()) { 20 | return true; 21 | } 22 | 23 | size_t s = 0u; 24 | for (size_t t = s; (t < target.size()) && (s < source.size()); ++t) { 25 | if (source[s] == target[t]) { 26 | ++s; 27 | } 28 | } 29 | 30 | return (s == source.size()); 31 | } 32 | }; 33 | 34 | int main(int argc, char** argv) 35 | { 36 | return EXIT_SUCCESS; 37 | } 38 | -------------------------------------------------------------------------------- /Algorithms/Easy/RectangleOverlap.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis. 4 | // Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap. 5 | // Given two axis-aligned rectangles rec1 and rec2, return true if they overlap, otherwise return false. 6 | 7 | // Example 1: 8 | // Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3] 9 | // Output: true 10 | 11 | // Example 2: 12 | // Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1] 13 | // Output: false 14 | 15 | // Example 3: 16 | // Input: rec1 = [0,0,1,1], rec2 = [2,2,3,3] 17 | // Output: false 18 | 19 | class Solution 20 | { 21 | public: 22 | bool isRectangleOverlap(std::vector& rec1, std::vector& rec2) 23 | { 24 | return rec1[0] < rec2[2] && rec1[1] < rec2[3] && rec2[0] < rec1[2] && rec2[1] < rec1[3]; 25 | } 26 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/SearchInsertPosition.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 4 | // You must write an algorithm with O(log n) runtime complexity. 5 | 6 | // Example 1: 7 | // Input: nums = [1,3,5,6], target = 5 8 | // Output: 2 9 | 10 | // Example 2: 11 | // Input: nums = [1,3,5,6], target = 2 12 | // Output: 1 13 | 14 | // Example 3: 15 | // Input: nums = [1,3,5,6], target = 7 16 | // Output: 4 17 | 18 | class Solution 19 | { 20 | public: 21 | int searchInsert(const std::vector& nums, int target) 22 | { 23 | int left = -1; 24 | int right = nums.size(); 25 | while (right - left > 1) { 26 | const int middle = left + (right - left) / 2; 27 | if (nums[middle] >= target) { 28 | right = middle; 29 | } else { 30 | left = middle; 31 | } 32 | } 33 | 34 | return right; 35 | } 36 | }; 37 | 38 | int main(int argc, char** argv) 39 | { 40 | return EXIT_SUCCESS; 41 | } -------------------------------------------------------------------------------- /Algorithms/Easy/ConcatenationOfArray.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed). 4 | // Specifically, ans is the concatenation of two nums arrays. 5 | // Return the array ans. 6 | 7 | // Example 1: 8 | // Input: nums = [1,2,1] 9 | // Output: [1,2,1,1,2,1] 10 | // Explanation: The array ans is formed as follows: 11 | // - ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]] 12 | // - ans = [1,2,1,1,2,1] 13 | 14 | // Example 2: 15 | // Input: nums = [1,3,2,1] 16 | // Output: [1,3,2,1,1,3,2,1] 17 | // Explanation: The array ans is formed as follows: 18 | // - ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]] 19 | // - ans = [1,3,2,1,1,3,2,1] 20 | 21 | class Solution { 22 | public: 23 | std::vector getConcatenation(const std::vector& nums) 24 | { 25 | const auto size = nums.size(); 26 | std::vector result(size * 2u); 27 | for (size_t i = 0u; i < size; ++i) { 28 | result[i] = nums[i]; 29 | result[i + size] = nums[i]; 30 | } 31 | 32 | return result; 33 | } 34 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/PascalsTriangle.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer numRows, return the first numRows of Pascal's triangle. 4 | // In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: 5 | 6 | // Example 1: 7 | // Input: numRows = 5 8 | // Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] 9 | 10 | // Example 2: 11 | // Input: numRows = 1 12 | // Output: [[1]] 13 | 14 | class Solution 15 | { 16 | public: 17 | std::vector> generate(int numRows) 18 | { 19 | std::vector> result; 20 | result.push_back(std::vector(1, 1)); 21 | for (size_t i = 2u; i <= numRows; ++i) { 22 | const std::vector& prev_row = result[i - 1]; 23 | std::vector current_row(i, 1); 24 | for (size_t i = 1u; i < current_row.size() - 1u) { 25 | current_row[i] = prev_row[i - 1] + prev_row[i]; 26 | } 27 | result.push_back(std::move(current_row)); 28 | } 29 | 30 | return result; 31 | } 32 | }; 33 | 34 | int main(int argc, char** argv) 35 | { 36 | return EXIT_SUCCESS; 37 | } 38 | -------------------------------------------------------------------------------- /Algorithms/Easy/RansomNote.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given two strings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise. 4 | // Each letter in magazine can only be used once in ransomNote. 5 | 6 | // Example 1: 7 | // Input: ransomNote = "a", magazine = "b" 8 | // Output: false 9 | 10 | // Example 2: 11 | // Input: ransomNote = "aa", magazine = "ab" 12 | // Output: false 13 | 14 | // Example 3: 15 | // Input: ransomNote = "aa", magazine = "aab" 16 | // Output: true 17 | 18 | class Solution 19 | { 20 | public: 21 | bool canConstruct(const std::string& ransomNote, const std::string& magazine) 22 | { 23 | std::array loookup{ 0u }; 24 | for (size_t i = 0u; i < magazine.size(); ++i) { 25 | ++loookup[magazine[i] - 'a']; 26 | } 27 | 28 | for (size_t i = 0u; i < ransomNote.size(); ++i) { 29 | if (--loookup[ransomNote[i] - 'a'] < 0) { 30 | return false; 31 | } 32 | } 33 | 34 | return true; 35 | } 36 | }; 37 | 38 | int main(int argc, char** argv) 39 | { 40 | return EXIT_SUCCESS; 41 | } 42 | -------------------------------------------------------------------------------- /Algorithms/Easy/FibonacciNumber.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, 4 | 5 | // F(0) = 0, F(1) = 1 6 | // F(n) = F(n - 1) + F(n - 2), for n > 1. 7 | // Given n, calculate F(n). 8 | 9 | // Example 1: 10 | // Input: n = 2 11 | // Output: 1 12 | // Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. 13 | 14 | // Example 2: 15 | // Input: n = 3 16 | // Output: 2 17 | // Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. 18 | 19 | // Example 3: 20 | // Input: n = 4 21 | // Output: 3 22 | // Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. 23 | 24 | class Solution { 25 | public: 26 | int fib(int n) 27 | { 28 | if (n < 2) 29 | return n; 30 | 31 | int current = 0; 32 | int previous = 1; 33 | int previous_previous = 0; 34 | for (int i = 2; i <= n; i++) { 35 | current = previous + previous_previous; 36 | previous_previous = previous; 37 | previous = current; 38 | } 39 | 40 | return current; 41 | } 42 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/MaximumDepthOfBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | | 3 | // Given the root of a binary tree, return its maximum depth. 4 | // A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 5 | 6 | // Example 1: 7 | // Input: root = [3,9,20,null,null,15,7] 8 | // Output: 3 9 | 10 | // Example 2: 11 | // Input: root = [1,null,2] 12 | // Output: 2 13 | 14 | // Example 3: 15 | // Input: root = [] 16 | // Output: 0 17 | 18 | // Example 4: 19 | // Input: root = [0] 20 | // Output: 1 21 | 22 | class Solution 23 | { 24 | public: 25 | int maxDepth(TreeNode* root) 26 | { 27 | std::function impl; 28 | impl = [&impl](TreeNode* node) 29 | { 30 | if (!node) { 31 | return 0; 32 | } 33 | 34 | const int left = impl(node->left) + 1; 35 | const int right = impl(node->right) + 1; 36 | return std::max(left, right); 37 | }; 38 | 39 | 40 | return impl(root); 41 | } 42 | }; 43 | 44 | int main(int argc, char** argv) 45 | { 46 | return EXIT_SUCCESS; 47 | } 48 | -------------------------------------------------------------------------------- /Algorithms/Easy/ReverseStringII.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string. 4 | // If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the other as original. 5 | 6 | // Example 1: 7 | // Input: s = "abcdefg", k = 2 8 | // Output: "bacdfeg" 9 | 10 | // Example 2: 11 | // Input: s = "abcd", k = 2 12 | // Output: "bacd" 13 | 14 | class Solution 15 | { 16 | public: 17 | void reverse(std::string& str, int left, int right) 18 | { 19 | while (left <= right) 20 | std::swap(str[left++], str[right--]); 21 | } 22 | 23 | std::string reverseStr(std::string s, int k) 24 | { 25 | int left = 0; 26 | while (left < s.size()) { 27 | int right = left + k; 28 | if (right > s.size()) 29 | right = s.size(); 30 | 31 | reverse(s, left, right - 1); 32 | left += 2 * k; 33 | } 34 | 35 | return s; 36 | } 37 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/ArrangingCoins.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete. 4 | // Given the integer n, return the number of complete rows of the staircase you will build. 5 | 6 | // Example 1: 7 | // Input: n = 5 8 | // Output: 2 9 | // Explanation: Because the 3rd row is incomplete, we return 2. 10 | 11 | // Example 2: 12 | // Input: n = 8 13 | // Output: 3 14 | // Explanation: Because the 4th row is incomplete, we return 3. 15 | 16 | class Solution 17 | { 18 | public: 19 | int arrangeCoins(int n) 20 | { 21 | int left = 1; 22 | int right = n; 23 | 24 | while (left <= right) { 25 | const long middle = left + (right - left) / 2; 26 | if (middle * (middle + 1) <= n * 2l) { 27 | left = middle + 1; 28 | } else { 29 | right = middle - 1; 30 | } 31 | } 32 | 33 | return right; 34 | } 35 | }; 36 | 37 | int main(int argc, char** argv) 38 | { 39 | return EXIT_SUCCESS; 40 | } 41 | -------------------------------------------------------------------------------- /Algorithms/Easy/FindCenterOfStarGraph.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a graph where there is one center node and exactly n - 1 edges that connect the center node with every other node. 4 | // You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an edge between the nodes ui and vi. Return the center of the given star graph. 5 | 6 | // Example 1: 7 | // Input: edges = [[1,2],[2,3],[4,2]] 8 | // Output: 2 9 | // Explanation: As shown in the figure above, node 2 is connected to every other node, so 2 is the center. 10 | 11 | // Example 2: 12 | // Input: edges = [[1,2],[5,1],[1,3],[1,4]] 13 | // Output: 1 14 | 15 | class Solution 16 | { 17 | public: 18 | int findCenter(vector>& edges) 19 | { 20 | const int left = edges[0][0]; 21 | const int right = edges[0][1]; 22 | if (edges[1][0] == left || edges[1][1] == left) { 23 | return left; 24 | } else { 25 | return right; 26 | } 27 | } 28 | }; 29 | 30 | int main(int argc, char** argv) 31 | { 32 | return EXIT_SUCCESS; 33 | } 34 | -------------------------------------------------------------------------------- /Algorithms/Easy/LengthOfLastWord.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string. 4 | // A word is a maximal substring consisting of non-space characters only. 5 | 6 | // Example 1: 7 | // Input: s = "Hello World" 8 | // Output: 5 9 | // Explanation: The last word is "World" with length 5. 10 | 11 | // Example 2: 12 | // Input: s = " fly me to the moon " 13 | // Output: 4 14 | // Explanation: The last word is "moon" with length 4. 15 | 16 | // Example 3: 17 | // Input: s = "luffy is still joyboy" 18 | // Output: 6 19 | // Explanation: The last word is "joyboy" with length 6. 20 | 21 | class Solution 22 | { 23 | public: 24 | int lengthOfLastWord(const std::string& s) 25 | { 26 | int length = 0; 27 | int i = s.size() - 1; 28 | 29 | while (s[i] == ' ') { 30 | --i; 31 | } 32 | 33 | while (i >= 0 && s[i] != ' ') { 34 | --i; 35 | ++length; 36 | } 37 | 38 | return length; 39 | } 40 | }; 41 | 42 | int main(int argc, char** argv) 43 | { 44 | return EXIT_SUCCESS; 45 | } 46 | -------------------------------------------------------------------------------- /Algorithms/Easy/LongestPalindrome.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. 4 | // Letters are case sensitive, for example, "Aa" is not considered a palindrome here. 5 | 6 | // Example 1: 7 | // Input: s = "abccccdd" 8 | // Output: 7 9 | // Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7. 10 | 11 | // Example 2: 12 | // Input: s = "a" 13 | // Output: 1 14 | // Explanation: The longest palindrome that can be built is "a", whose length is 1. 15 | 16 | class Solution { 17 | public: 18 | int longestPalindrome(std::string s) 19 | { 20 | if (s.empty()) 21 | return 0; 22 | 23 | std::unordered_map lookup; 24 | for (int i = 0; i < s.size(); ++i) 25 | ++lookup[s[i]]; 26 | 27 | int even = 0; 28 | int odd = 0; 29 | for (const auto it: lookup) { 30 | const int count = it.second; 31 | even += (count & (~1)); 32 | odd |= (count & 1); 33 | } 34 | 35 | return even + odd; 36 | } 37 | }; -------------------------------------------------------------------------------- /Algorithms/Medium/JumpGame.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. 4 | // Return true if you can reach the last index, or false otherwise. 5 | 6 | // Example 1: 7 | // Input: nums = [2,3,1,1,4] 8 | // Output: true 9 | // Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. 10 | 11 | // Example 2: 12 | // Input: nums = [3,2,1,0,4] 13 | // Output: false 14 | // Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. 15 | 16 | class Solution { 17 | public: 18 | bool canJump(const std::vector& nums) 19 | { 20 | int goal_index = nums.size() - 1; 21 | for (int i = goal_index - 1; i >= 0; --i) { 22 | const int count_steps = nums[i]; 23 | if (i + count_steps >= goal_index) 24 | goal_index = i; 25 | } 26 | 27 | return goal_index == 0; 28 | } 29 | }; 30 | 31 | int main(int argc, char** argv) 32 | { 33 | return EXIT_SUCCESS; 34 | } -------------------------------------------------------------------------------- /Algorithms/Easy/MaximumAverageSubarrayI.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // You are given an integer array nums consisting of n elements, and an integer k. 4 | // Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10-5 will be accepted. 5 | 6 | // Example 1: 7 | // Input: nums = [1,12,-5,-6,50,3], k = 4 8 | // Output: 12.75000 9 | // Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75 10 | 11 | // Example 2: 12 | // Input: nums = [5], k = 1 13 | // Output: 5.00000 14 | 15 | class Solution 16 | { 17 | public: 18 | double findMaxAverage(const std::vector& nums, int k) 19 | { 20 | if (k > nums.size()) 21 | return 0; 22 | 23 | int current_sum = 0; 24 | for (int i = 0; i < k; ++i) 25 | current_sum += nums[i]; 26 | 27 | int max_sum = current_sum; 28 | for (int i = k; i < nums.size(); ++i) { 29 | current_sum = current_sum + nums[i] - nums[i - k]; 30 | max_sum = std::max(max_sum, current_sum); 31 | } 32 | 33 | return static_cast(max_sum) / k; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Algorithms/Easy/ReverseWordsInAStringIII.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. 4 | 5 | // Example 1: 6 | // Input: s = "Let's take LeetCode contest" 7 | // Output: "s'teL ekat edoCteeL tsetnoc" 8 | 9 | // Example 2: 10 | // Input: s = "God Ding" 11 | // Output: "doG gniD" 12 | 13 | class Solution 14 | { 15 | public: 16 | string reverseWords(std::string s) 17 | { 18 | size_t word_begin = 0u; 19 | for (size_t i = 0u; i < s.length(); ++i) { 20 | if (s[i] == ' ') { 21 | size_t word_end = i - 1u; 22 | while (word_begin < word_end) { 23 | std::swap(s[word_begin++], s[word_end--]); 24 | } 25 | word_begin = i + 1; 26 | } 27 | } 28 | 29 | size_t word_end = s.length() - 1u; 30 | while (word_begin < word_end) { 31 | std::swap(s[word_begin++], s[word_end--]); 32 | } 33 | 34 | return s; 35 | } 36 | }; 37 | 38 | int main(int argc, char** argv) 39 | { 40 | return EXIT_SUCCESS; 41 | } 42 | -------------------------------------------------------------------------------- /Algorithms/Easy/FindTheDifference.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // You are given two strings s and t. 4 | // String t is generated by random shuffling string s and then add one more letter at a random position. 5 | // Return the letter that was added to t. 6 | 7 | // Example 1: 8 | // Input: s = "abcd", t = "abcde" 9 | // Output: "e" 10 | // Explanation: 'e' is the letter that was added. 11 | 12 | // Example 2: 13 | // Input: s = "", t = "y" 14 | // Output: "y" 15 | 16 | class Solution 17 | { 18 | public: 19 | char findTheDifference(const std::string& s, const std::string& t) 20 | { 21 | constexpr uint8_t ALPHABET_SIZE = 26u; 22 | std::array lookup{ 0u }; 23 | 24 | for (size_t i = 0u; i < t.size(); ++i) 25 | ++lookup[t[i] - 'a']; 26 | 27 | for (size_t i = 0u; i < s.size(); ++i) 28 | --lookup[s[i] - 'a']; 29 | 30 | for (size_t i = 0u; i < ALPHABET_SIZE; ++i) { 31 | if (lookup[i] == 1u) 32 | return static_cast(i + 'a'); 33 | } 34 | 35 | return '!'; 36 | } 37 | }; 38 | 39 | int main(int argc, char** argv) 40 | { 41 | return EXIT_SUCCESS; 42 | } 43 | -------------------------------------------------------------------------------- /Algorithms/Medium/RotateArray.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an array, rotate the array to the right by k steps, where k is non-negative. 4 | 5 | // Example 1: 6 | // Input: nums = [1,2,3,4,5,6,7], k = 3 7 | // Output: [5,6,7,1,2,3,4] 8 | // Explanation: 9 | // rotate 1 steps to the right: [7,1,2,3,4,5,6] 10 | // rotate 2 steps to the right: [6,7,1,2,3,4,5] 11 | // rotate 3 steps to the right: [5,6,7,1,2,3,4] 12 | 13 | // Example 2: 14 | // Input: nums = [-1,-100,3,99], k = 2 15 | // Output: [3,99,-1,-100] 16 | // Explanation: 17 | // rotate 1 steps to the right: [99,-1,-100,3] 18 | // rotate 2 steps to the right: [3,99,-1,-100] 19 | 20 | class Solution 21 | { 22 | public: 23 | void rotate(vector& nums, int k) 24 | { 25 | k = k % nums.size(); 26 | reverse(nums, 0, nums.size() - 1); 27 | reverse(nums, 0, k - 1); 28 | reverse(nums, k, nums.size() - 1); 29 | } 30 | 31 | void reverse(vector& nums, int begin, int end) 32 | { 33 | while (begin < end) { 34 | std::swap(nums[begin++], nums[end--]); 35 | } 36 | } 37 | }; 38 | 39 | int main(int argc, char** argv) 40 | { 41 | return EXIT_SUCCESS; 42 | } 43 | 44 | -------------------------------------------------------------------------------- /Algorithms/Easy/AddBinary.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given two binary strings a and b, return their sum as a binary string. 4 | 5 | // Example 1: 6 | // Input: a = "11", b = "1" 7 | // Output: "100" 8 | 9 | // Example 2: 10 | // Input: a = "1010", b = "1011" 11 | // Output: "10101" 12 | 13 | class Solution 14 | { 15 | public: 16 | std::string addBinary(const std::string& a, const std::string& b) 17 | { 18 | std::string result; 19 | int left = a.size() - 1; 20 | int right = b.size() - 1; 21 | int carry = 0; 22 | 23 | while (left >= 0 || right >= 0) { 24 | int sum = carry; 25 | if (left >= 0) { 26 | sum += a[left--] - '0'; 27 | } 28 | if (right >= 0) { 29 | sum += b[right--] - '0'; 30 | } 31 | result += std::to_string(sum % 2); 32 | carry = sum / 2; 33 | } 34 | 35 | if (carry != 0) { 36 | result += '1'; 37 | } 38 | 39 | std::reverse(begin(result), end(result)); 40 | return result; 41 | } 42 | }; 43 | 44 | int main(int argc, char** argv) 45 | { 46 | return EXIT_SUCCESS; 47 | } 48 | -------------------------------------------------------------------------------- /Algorithms/Easy/DetectCapital.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // We define the usage of capitals in a word to be right when one of the following cases holds: 4 | // All letters in this word are capitals, like "USA". 5 | // All letters in this word are not capitals, like "leetcode". 6 | // Only the first letter in this word is capital, like "Google". 7 | // Given a string word, return true if the usage of capitals in it is right. 8 | 9 | // Example 1: 10 | // Input: word = "USA" 11 | // Output: true 12 | 13 | // Example 2: 14 | // Input: word = "FlaG" 15 | // Output: false 16 | 17 | class Solution 18 | { 19 | public: 20 | bool detectCapitalUse(std::string word) 21 | { 22 | if (word.size() == 1) 23 | return true; 24 | 25 | if (std::isupper(word[0]) && std::isupper(word[1])) { 26 | for (int i = 2; i < word.size(); ++i) { 27 | if (!std::isupper(word[i])) 28 | return false; 29 | } 30 | } else { 31 | for (int i = 1; i < word.size(); ++i) { 32 | if (std::isupper(word[i])) 33 | return false; 34 | } 35 | } 36 | 37 | return true; 38 | } 39 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/LongestCommonPrefix.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Write a function to find the longest common prefix string amongst an array of strings. 4 | // If there is no common prefix, return an empty string "". 5 | 6 | // Example 1: 7 | // Input: strs = ["flower","flow","flight"] 8 | // Output: "fl" 9 | 10 | // Example 2: 11 | // Input: strs = ["dog","racecar","car"] 12 | // Output: "" 13 | // Explanation: There is no common prefix among the input strings. 14 | 15 | class Solution 16 | { 17 | public: 18 | std::string longestCommonPrefix(const std::vector& strs) 19 | { 20 | std::string prefix; 21 | if (strs.empty()) { 22 | return prefix; 23 | } 24 | 25 | for (size_t i = 0u; i < strs[0u].size(); ++i) { 26 | const char symbol = strs[0u][i]; 27 | for (size_t j = 1u; j < strs.size(); ++j) { 28 | if ((strs[j].size() <= i) || (strs[j][i] != symbol)) { 29 | return prefix; 30 | } 31 | } 32 | prefix += symbol; 33 | } 34 | 35 | return prefix; 36 | } 37 | }; 38 | 39 | int main(int argc, char** argv) 40 | { 41 | return EXIT_SUCCESS; 42 | } 43 | -------------------------------------------------------------------------------- /Algorithms/Medium/Triangle.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a triangle array, return the minimum path sum from top to bottom. 4 | // For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row. 5 | 6 | // Example 1: 7 | // Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]] 8 | // Output: 11 9 | // Explanation: The triangle looks like: 10 | // 2 11 | // 3 4 12 | // 6 5 7 13 | // 4 1 8 3 14 | // The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above). 15 | 16 | // Example 2: 17 | // Input: triangle = [[-10]] 18 | // Output: -10 19 | 20 | class Solution 21 | { 22 | public: 23 | int minimumTotal(vector>& triangle) 24 | { 25 | const size_t size = triangle.size(); 26 | std::vector dp(size + 1); 27 | 28 | for (int i = size - 1; i >= 0; --i) { 29 | for (int j = 0; j <= i; ++j) { 30 | dp[j] = std::min(dp[j], dp[j + 1]) + triangle[i][j]; 31 | } 32 | } 33 | 34 | return dp[0]; 35 | } 36 | }; 37 | 38 | int main(int argc, char** argv) 39 | { 40 | return EXIT_SUCCESS; 41 | } 42 | -------------------------------------------------------------------------------- /Algorithms/Easy/SingleNumber.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. 4 | // You must implement a solution with a linear runtime complexity and use only constant extra space. 5 | 6 | // Example 1: 7 | // Input: nums = [2,2,1] 8 | // Output: 1 9 | 10 | // Example 2: 11 | // Input: nums = [4,1,2,1,2] 12 | // Output: 4 13 | 14 | // Example 3: 15 | // Input: nums = [1] 16 | // Output: 1 17 | 18 | class Solution 19 | { 20 | public: 21 | int singleNumber(const std::vector& nums) 22 | { 23 | int single_number = 0; 24 | for (const auto number : nums) { 25 | single_number ^= number; 26 | } 27 | return single_number; 28 | } 29 | }; 30 | 31 | int main(int argc, char** argv) 32 | { 33 | Solution solution; 34 | ASSERT_EQUALS(solution.singleNumber({ 2, 2, 1, 4, 4, 5, 5 }), 1); 35 | ASSERT_EQUALS(solution.singleNumber({ 2, 2, 5, 4, 4, 5, 1 }), 1); 36 | ASSERT_EQUALS(solution.singleNumber({ 2, 2, 5, 4, 1, 5, 4 }), 1); 37 | ASSERT_EQUALS(solution.singleNumber({ 4, 1, 2, 1, 2 }), 4); 38 | ASSERT_EQUALS(solution.singleNumber({ 1 }), 1); 39 | return EXIT_SUCCESS; 40 | } 41 | -------------------------------------------------------------------------------- /Algorithms/Easy/CanMakeArithmeticProgressionFromSequance.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same. 4 | // Given an array of numbers arr, return true if the array can be rearranged to form an arithmetic progression. Otherwise, return false. 5 | 6 | // Example 1: 7 | // Input: arr = [3,5,1] 8 | // Output: true 9 | // Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements. 10 | 11 | // Example 2: 12 | // Input: arr = [1,2,4] 13 | // Output: false 14 | // Explanation: There is no way to reorder the elements to obtain an arithmetic progression. 15 | 16 | class Solution 17 | { 18 | public: 19 | bool canMakeArithmeticProgression(const std::vector& arr) 20 | { 21 | std::sort(begin(arr), end(arr)); 22 | int difference = arr[1] - arr[0]; 23 | for (size_t i = 1u; i < arr.size() - 1u; ++i) { 24 | if (arr[i] + difference != arr[i + 1]) 25 | return false; 26 | } 27 | 28 | return true; 29 | } 30 | }; 31 | 32 | int main(int argc, char** argv) 33 | { 34 | return EXIT_SUCCESS; 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms/Easy/MaximumProductOfTwoElementsInAnArray.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1). 4 | 5 | // Example 1: 6 | // Input: nums = [3,4,5,2] 7 | // Output: 12 8 | // Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. 9 | 10 | // Example 2: 11 | // Input: nums = [1,5,4,5] 12 | // Output: 16 13 | // Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16. 14 | 15 | // Example 3: 16 | // Input: nums = [3,7] 17 | // Output: 12 18 | 19 | class Solution { 20 | public: 21 | int maxProduct(std::vector& nums) 22 | { 23 | int first_max = 0; 24 | int second_max = 0; 25 | for (const int value: nums) { 26 | if (value > first_max) { 27 | second_max = first_max; 28 | first_max = value; 29 | } else if (value > second_max) { 30 | second_max = value; 31 | } 32 | } 33 | 34 | return (first_max - 1) * (second_max - 1); 35 | } 36 | }; -------------------------------------------------------------------------------- /Algorithms/Medium/TopKFrequentElements.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. 4 | 5 | // Example 1: 6 | // Input: nums = [1,1,1,2,2,3], k = 2 7 | // Output: [1,2] 8 | 9 | // Example 2: 10 | // Input: nums = [1], k = 1 11 | // Output: [1] 12 | 13 | class Solution 14 | { 15 | public: 16 | std::vector topKFrequent(std::vector& nums, int k) 17 | { 18 | std::unordered_map frequencies; 19 | for (const auto num: nums) 20 | ++frequencies[num]; 21 | 22 | std::vector> buckets(nums.size() + 1); 23 | for (auto iterator: frequencies) 24 | buckets[iterator.second].push_back(iterator.first); 25 | 26 | std::vector result; 27 | for (ssize_t i = buckets.size() - 1; i >= 0 && k > 0; --i) { 28 | for (size_t j = 0; j < buckets[i].size() && k > 0; ++j) { 29 | result.push_back(buckets[i][j]); 30 | --k; 31 | } 32 | } 33 | 34 | return result; 35 | } 36 | }; 37 | 38 | int main(int argc, char** argv) 39 | { 40 | return EXIT_SUCCESS; 41 | } -------------------------------------------------------------------------------- /Algorithms/Easy/KthMissingPositiveNumber.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an array arr of positive integers sorted in a strictly increasing order, and an integer k. 4 | // Find the kth positive integer that is missing from this array. 5 | 6 | // Example 1: 7 | // Input: arr = [2,3,4,7,11], k = 5 8 | // Output: 9 9 | // Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9. 10 | 11 | // Example 2: 12 | // Input: arr = [1,2,3,4], k = 2 13 | // Output: 6 14 | // Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6. 15 | 16 | class Solution { 17 | public: 18 | int findKthPositive(const std::vector& arr, int k) 19 | { 20 | if (arr[0] > k) { 21 | return k; 22 | } 23 | 24 | int left = 0; 25 | int right = arr.size() - 1; 26 | 27 | while (left <= right) { 28 | const int middle = left + (right - left) / 2; 29 | if (arr[middle] - (middle + 1) < k) { 30 | left = middle + 1; 31 | } else { 32 | right = middle - 1; 33 | } 34 | } 35 | 36 | return left + k; 37 | } 38 | }; 39 | 40 | int main(int argc, char** argv) 41 | { 42 | return EXIT_SUCCESS; 43 | } -------------------------------------------------------------------------------- /Algorithms/Easy/MinStack.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. 4 | // Implement the MinStack class: 5 | 6 | // MinStack() initializes the stack object. 7 | // void push(int val) pushes the element val onto the stack. 8 | // void pop() removes the element on the top of the stack. 9 | // int top() gets the top element of the stack. 10 | // int getMin() retrieves the minimum element in the stack. 11 | 12 | class MinStack 13 | { 14 | public: 15 | MinStack() {} 16 | 17 | void push(int val) 18 | { 19 | if (!m_stack.empty()) { 20 | const int min = std::min(m_stack.top().second, val); 21 | m_stack.push({ val, min }); 22 | } else { 23 | m_stack.push({ val, val }); 24 | } 25 | } 26 | 27 | void pop() 28 | { 29 | m_stack.pop(); 30 | } 31 | 32 | int top() 33 | { 34 | return m_stack.top().first; 35 | } 36 | 37 | int getMin() 38 | { 39 | return m_stack.top().second; 40 | } 41 | private: 42 | std::stack> m_stack; 43 | }; 44 | 45 | int main(int argc, char** argv) 46 | { 47 | return EXIT_SUCCESS; 48 | } 49 | -------------------------------------------------------------------------------- /Algorithms/Medium/TrimABinarySearchTree.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer. 4 | // Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds. 5 | 6 | // Example 1: 7 | // Input: root = [1,0,2], low = 1, high = 2 8 | // Output: [1,null,2] 9 | 10 | // Example 2: 11 | // Input: root = [3,0,4,null,2,null,null,1], low = 1, high = 3 12 | // Output: [3,2,null,1] 13 | 14 | class Solution 15 | { 16 | public: 17 | TreeNode* trimBST(TreeNode* root, int low, int high) 18 | { 19 | if (!root) 20 | return nullptr; 21 | 22 | if (root->val > high) 23 | return trimBST(root->left, low, high); 24 | if (root->val < low) 25 | return trimBST(root->right, low, high); 26 | 27 | root->left = trimBST(root->left, low, high); 28 | root->right = trimBST(root->right, low, high); 29 | return root; 30 | } 31 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/TwoSumIVInputIsABST.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target. 4 | 5 | // Example 1: 6 | // Input: root = [5,3,6,2,4,null,7], k = 9 7 | // Output: true 8 | 9 | // Example 2: 10 | // Input: root = [5,3,6,2,4,null,7], k = 28 11 | // Output: false 12 | 13 | class Solution 14 | { 15 | public: 16 | bool findTarget(TreeNode* root, int k) 17 | { 18 | std::unordered_set lookup; 19 | std::stack stack; 20 | stack.push(root); 21 | 22 | while (!stack.empty()) { 23 | TreeNode* node = stack.top(); 24 | stack.pop(); 25 | 26 | const int diff = k - node->val; 27 | if (lookup.count(diff) == 0) 28 | lookup.insert(node->val); 29 | else 30 | return true; 31 | 32 | if (node->left) 33 | stack.push(node->left); 34 | if (node->right) 35 | stack.push(node->right); 36 | } 37 | 38 | return false; 39 | } 40 | }; 41 | 42 | int main(int argc, char** argv) 43 | { 44 | return EXIT_SUCCESS; 45 | } -------------------------------------------------------------------------------- /Algorithms/Medium/Subsets.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer array nums of unique elements, return all possible 4 | // subsets (the power set). 5 | // The solution set must not contain duplicate subsets. Return the solution in any order. 6 | 7 | // Example 1: 8 | // Input: nums = [1,2,3] 9 | // Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] 10 | 11 | // Example 2: 12 | // Input: nums = [0] 13 | // Output: [[],[0]] 14 | 15 | class Solution 16 | { 17 | public: 18 | std::vector> subsets(const std::vector& nums) 19 | { 20 | vector> result; 21 | std::vector combination; 22 | result.push_back(combination); 23 | 24 | std::function backtracing; 25 | backtracing = [&backtracing, &result, &combination, &nums] (int index) 26 | { 27 | while (index < nums.size()) { 28 | combination.push_back(nums[index]); 29 | result.push_back(combination); 30 | 31 | backtracing(++index); 32 | combination.pop_back(); 33 | } 34 | }; 35 | 36 | backtracing(0); 37 | return result; 38 | } 39 | }; 40 | 41 | int main(int argc, char** argv) 42 | { 43 | return EXIT_SUCCESS; 44 | } -------------------------------------------------------------------------------- /Algorithms/Easy/SqrtX.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a non-negative integer x, compute and return the square root of x. 4 | // Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned. 5 | // Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5. 6 | 7 | // Example 1: 8 | // Input: x = 4 9 | // Output: 2 10 | 11 | // Example 2: 12 | // Input: x = 8 13 | // Output: 2 14 | // Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned. 15 | 16 | class Solution 17 | { 18 | public: 19 | int mySqrt(int x) 20 | { 21 | if (x == 1) 22 | return 1; 23 | 24 | int left = 0; 25 | int right = x; 26 | 27 | while (right - left > 1) { 28 | const long long middle = left + (right - left) / 2; 29 | const long long target = middle * middle; 30 | if (target <= x) { 31 | left = middle; 32 | } else { 33 | right = middle; 34 | } 35 | } 36 | 37 | return left; 38 | } 39 | }; 40 | 41 | int main(int argc, char** argv) 42 | { 43 | return EXIT_SUCCESS; 44 | } 45 | -------------------------------------------------------------------------------- /Algorithms/Medium/Combinations.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given two integers n and k, return all possible combinations of k numbers out of the range [1, n]. 4 | // You may return the answer in any order. 5 | 6 | // Example 1: 7 | // Input: n = 4, k = 2 8 | // Output: 9 | // [ 10 | // [2,4], 11 | // [3,4], 12 | // [2,3], 13 | // [1,2], 14 | // [1,3], 15 | // [1,4], 16 | // ] 17 | 18 | // Example 2: 19 | // Input: n = 1, k = 1 20 | // Output: [[1]] 21 | 22 | class Solution 23 | { 24 | public: 25 | std::vector> combine(int n, int k) 26 | { 27 | std::vector combination; 28 | std::vector> result; 29 | 30 | std::function backtracking; 31 | backtracking = [&combination, k, n] (int number) 32 | { 33 | if (combination.size() == k) 34 | return result.push_back(combination); 35 | 36 | for (int i = number; i <= n; ++i) { 37 | combination.push_back(i); 38 | backtracking(i + 1); 39 | combination.pop_back(); 40 | } 41 | }; 42 | 43 | backtracking(1); 44 | return result; 45 | } 46 | }; 47 | 48 | int main(int argc, char** argv) 49 | { 50 | return EXIT_SUCCESS; 51 | } 52 | -------------------------------------------------------------------------------- /Algorithms/Easy/NaryTreePreorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given the root of an n-ary tree, return the preorder traversal of its nodes' values. 4 | // Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) 5 | 6 | // Example 1: 7 | // Input: root = [1,null,3,2,4,null,5,6] 8 | // Output: [1,3,5,6,2,4] 9 | 10 | // Example 2: 11 | // Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] 12 | // Output: [1,2,3,6,7,11,14,4,8,12,5,9,13,10] 13 | 14 | class Solution 15 | { 16 | public: 17 | std::vector preorder(Node* root) 18 | { 19 | if (!root) { 20 | return {}; 21 | } 22 | 23 | std::vector result; 24 | std::function impl; 25 | impl = [&impl, &result] (Node* node) 26 | { 27 | result.push_back(node->val); 28 | for (auto child: node->children) { 29 | if (child) { 30 | impl(child); 31 | } 32 | } 33 | }; 34 | 35 | impl(root); 36 | return result; 37 | } 38 | }; 39 | 40 | int main(int argc, char** argv) 41 | { 42 | return EXIT_SUCCESS; 43 | } 44 | -------------------------------------------------------------------------------- /Algorithms/Medium/ReverseInteger.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. 4 | // Assume the environment does not allow you to store 64-bit integers (signed or unsigned). 5 | 6 | // Example 1: 7 | // Input: x = 123 8 | // Output: 321 9 | 10 | // Example 2: 11 | // Input: x = -123 12 | // Output: -321 13 | 14 | // Example 3: 15 | // Input: x = 120 16 | // Output: 21 17 | 18 | // Example 4: 19 | // Input: x = 0 20 | // Output: 0 21 | 22 | class Solution 23 | { 24 | public: 25 | int reverse(int x) 26 | { 27 | int reversed_number = 0; 28 | 29 | while (x != 0) { 30 | const int number = x % 10; 31 | x /= 10; 32 | 33 | if (((std::numeric_limits::max() / 10) < reversed_number) || 34 | ((std::numeric_limits::min() / 10) > reversed_number)) { 35 | return 0; 36 | } else { 37 | reversed_number = reversed_number * 10 + number; 38 | } 39 | } 40 | 41 | return reversed_number; 42 | } 43 | }; 44 | 45 | int main(int argc, char** argv) 46 | { 47 | return EXIT_SUCCESS; 48 | } 49 | -------------------------------------------------------------------------------- /Algorithms/Easy/MinimumDepthOfBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a binary tree, find its minimum depth. 4 | // The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 5 | // Note: A leaf is a node with no children. 6 | 7 | // Example 1: 8 | // Input: root = [3,9,20,null,null,15,7] 9 | // Output: 2 10 | 11 | // Example 2: 12 | // Input: root = [2,null,3,null,4,null,5,null,6] 13 | // Output: 5 14 | 15 | class Solution 16 | { 17 | public: 18 | int minDepth(TreeNode* root) 19 | { 20 | std::function impl; 21 | impl = [&impl](TreeNode* node) 22 | { 23 | if (!node) { 24 | return 0; 25 | } 26 | 27 | if ((!node->left) && (!node->right)) { 28 | return 1; 29 | } 30 | 31 | if (!node->left) { 32 | return 1 + impl(node->right); 33 | } 34 | if (!node->right) { 35 | return 1 + impl(node->left); 36 | } 37 | 38 | return 1 + std::min(impl(node->left), impl(node->right)); 39 | }; 40 | 41 | return impl(root); 42 | } 43 | }; 44 | 45 | int main(int argc, char** argv) 46 | { 47 | return EXIT_SUCCESS; 48 | } 49 | -------------------------------------------------------------------------------- /Algorithms/Medium/LetterCasePermutation.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a string s, you can transform every letter individually to be lowercase or uppercase to create another string. 4 | // Return a list of all possible strings we could create. Return the output in any order. 5 | 6 | // Example 1: 7 | // Input: s = "a1b2" 8 | // Output: ["a1b2","a1B2","A1b2","A1B2"] 9 | 10 | // Example 2: 11 | // Input: s = "3z4" 12 | // Output: ["3z4","3Z4"] 13 | 14 | class Solution 15 | { 16 | public: 17 | std::vector letterCasePermutation(string s) 18 | { 19 | std::vector result; 20 | std::function backtracking; 21 | backtracking = [&backtracking, &result, &s](size_t index) 22 | { 23 | if (index == s.size()) 24 | return result.push_back(s); 25 | 26 | backtracking(index + 1); 27 | if (!std::isdigit(s[index])) { 28 | s[index] = std::isupper(s[index]) 29 | ? std::tolower(s[index]) : std::toupper(s[index]); 30 | backtracking(index + 1); 31 | } 32 | }; 33 | 34 | backtracking(0u); 35 | return result; 36 | } 37 | }; 38 | 39 | int main(int argc, char** argv) 40 | { 41 | return EXIT_SUCCESS; 42 | } 43 | -------------------------------------------------------------------------------- /Algorithms/Medium/SortColors.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. 4 | // We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. 5 | // You must solve this problem without using the library's sort function. 6 | 7 | // Example 1: 8 | // Input: nums = [2,0,2,1,1,0] 9 | // Output: [0,0,1,1,2,2] 10 | 11 | // Example 2: 12 | // Input: nums = [2,0,1] 13 | // Output: [0,1,2] 14 | 15 | class Solution 16 | { 17 | public: 18 | void sortColors(std::vector& nums) 19 | { 20 | if (nums.size() <= 1u) { 21 | return; 22 | } 23 | 24 | int left = 0; 25 | int current = 0; 26 | int right = nums.size() - 1; 27 | while (current <= right) { 28 | if (nums[current] == 0) { 29 | std::swap(nums[left++], nums[current++]); 30 | } else if (nums[current] == 2) { 31 | std::swap(nums[right--], nums[current]); 32 | } else { 33 | ++current; 34 | } 35 | } 36 | } 37 | }; 38 | 39 | int main(int argc, char** argv) 40 | { 41 | return EXIT_SUCCESS; 42 | } 43 | -------------------------------------------------------------------------------- /Algorithms/Easy/CheckIfItIsAStraightLine.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. 4 | 5 | // Example 1: 6 | // Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] 7 | // Output: true 8 | 9 | // Example 2: 10 | // Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] 11 | // Output: false 12 | 13 | class Solution 14 | { 15 | public: 16 | bool checkStraightLine(const std::vector>& coordinates) 17 | { 18 | if(coordinates.size() == 2) 19 | return true; 20 | 21 | const int x0 = coordinates[0][0] , x1 = coordinates[1][0]; 22 | const int y0 = coordinates[0][1] , y1 = coordinates[1][1]; 23 | 24 | const int dx = x1 - x0; 25 | const int dy = y1 - y0; 26 | 27 | for (size_t i = 2u; i < coordinates.size(); ++i) { 28 | const int x = coordinates[i][0] , y = coordinates[i][1]; 29 | if (dy * (x - x0) != dx * (y - y0)) { 30 | return false; 31 | } 32 | } 33 | 34 | return true; 35 | } 36 | }; 37 | 38 | int main(int argc, char** argv) 39 | { 40 | return EXIT_SUCCESS; 41 | } 42 | -------------------------------------------------------------------------------- /Algorithms/Easy/MatrixDiagonalSum.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a square matrix mat, return the sum of the matrix diagonals. 4 | // Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. 5 | 6 | // Example 1: 7 | // Input: mat = [[1,2,3], 8 | // [4,5,6], 9 | // [7,8,9]] 10 | // Output: 25 11 | // Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25 12 | // Notice that element mat[1][1] = 5 is counted only once. 13 | 14 | // Example 2: 15 | // 16 | // Input: mat = [[1,1,1,1], 17 | // [1,1,1,1], 18 | // [1,1,1,1], 19 | // [1,1,1,1]] 20 | // Output: 8 21 | 22 | // Example 3: 23 | // Input: mat = [[5]] 24 | // Output: 5 25 | 26 | class Solution 27 | { 28 | public: 29 | int diagonalSum(const std::vector>& mat) 30 | { 31 | int sum = 0; 32 | const size_t size = mat.size(); 33 | 34 | for (size_t i = 0u; i < size; ++i) { 35 | sum += mat[i][size - i - 1]; 36 | sum += mat[i][i]; 37 | } 38 | 39 | return (size % 2 != 0) ? (sum - mat[size / 2][size / 2]) : (sum); 40 | } 41 | }; 42 | 43 | int main(int argc, char** argv) 44 | { 45 | return EXIT_SUCCESS; 46 | } 47 | -------------------------------------------------------------------------------- /Algorithms/Easy/SignOfTheProductOfAnArray.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // There is a function signFunc(x) that returns: 4 | 5 | // 1 if x is positive. 6 | // -1 if x is negative. 7 | // 0 if x is equal to 0. 8 | // You are given an integer array nums. Let product be the product of all values in the array nums. 9 | // Return signFunc(product). 10 | 11 | // Example 1: 12 | // Input: nums = [-1,-2,-3,-4,3,2,1] 13 | // Output: 1 14 | // Explanation: The product of all values in the array is 144, and signFunc(144) = 1 15 | 16 | // Example 2: 17 | // Input: nums = [1,5,0,2,-3] 18 | // Output: 0 19 | // Explanation: The product of all values in the array is 0, and signFunc(0) = 0 20 | 21 | // Example 3: 22 | // Input: nums = [-1,1,-1,1,-1] 23 | // Output: -1 24 | // Explanation: The product of all values in the array is -1, and signFunc(-1) = -1 25 | 26 | class Solution 27 | { 28 | public: 29 | int arraySign(const std::vector& nums) 30 | { 31 | int sign = 1; 32 | for (size_t i = 0u; i < nums.size(); ++i) { 33 | if (nums[i] == 0) 34 | return 0; 35 | else if (nums[i] < 0) 36 | sign = -sign; 37 | } 38 | 39 | return sign; 40 | } 41 | }; 42 | 43 | int main(int argc, char** argv) 44 | { 45 | return EXIT_SUCCESS; 46 | } 47 | -------------------------------------------------------------------------------- /Algorithms/Easy/DeleteNodeInALinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly. 4 | // It is guaranteed that the node to be deleted is not a tail node in the list. 5 | 6 | // Example 1: 7 | // Input: head = [4,5,1,9], node = 5 8 | // Output: [4,1,9] 9 | // Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. 10 | 11 | // Example 2: 12 | // Input: head = [4,5,1,9], node = 1 13 | // Output: [4,5,9] 14 | // Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. 15 | 16 | // Example 3: 17 | // Input: head = [1,2,3,4], node = 3 18 | // Output: [1,2,4] 19 | 20 | // Example 4: 21 | // Input: head = [0,1], node = 0 22 | // Output: [1] 23 | 24 | // Example 5: 25 | // Input: head = [-3,5,-99], node = -3 26 | // Output: [5,-99] 27 | 28 | class Solution 29 | { 30 | public: 31 | void deleteNode(ListNode* node) 32 | { 33 | node->value = node->next->value; 34 | node->next = node->next->next; 35 | } 36 | }; 37 | 38 | int main(int argc, char** argv) 39 | { 40 | return EXIT_SUCCESS; 41 | } 42 | -------------------------------------------------------------------------------- /Algorithms/Easy/ValidAnagram.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given two strings s and t, return true if t is an anagram of s, and false otherwise. 4 | 5 | // Example 1: 6 | // Input: s = "anagram", t = "nagaram" 7 | // Output: true 8 | 9 | // Example 2: 10 | // Input: s = "rat", t = "car" 11 | // Output: false 12 | 13 | class Solution 14 | { 15 | public: 16 | bool isAnagram(const std::string& s, const std::string& t) 17 | { 18 | if (s.size() != t.size()) { 19 | return false; 20 | } 21 | 22 | std::array lookup{ 0 }; 23 | for (size_t i = 0u; i < s.size(); ++i) { 24 | ++lookup[s[i] - 'a']; 25 | --lookup[t[i] - 'a']; 26 | } 27 | 28 | for (size_t i = 0u; i < 26u; ++i) { 29 | if (lookup[i] != 0u) { 30 | return false; 31 | } 32 | } 33 | 34 | return true; 35 | } 36 | }; 37 | 38 | int main(int argc, char** argv) 39 | { 40 | Solution solution; 41 | ASSERT_EQUALS(solution.isAnagram("", ""), true); 42 | ASSERT_EQUALS(solution.isAnagram("anagram", "nagaram"), true); 43 | ASSERT_EQUALS(solution.isAnagram("anagram", "nagaran"), false); 44 | ASSERT_EQUALS(solution.isAnagram("anagram", "nagarana"), false); 45 | return EXIT_SUCCESS; 46 | } 47 | -------------------------------------------------------------------------------- /Algorithms/Easy/FindSmallestLetterGreaterThanTarget.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a characters array letters that is sorted in non-decreasing order and a character target, return the smallest character in the array that is larger than target. 4 | // Note that the letters wrap around. 5 | // For example, if target == 'z' and letters == ['a', 'b'], the answer is 'a'. 6 | 7 | // Example 1: 8 | // Input: letters = ["c","f","j"], target = "a" 9 | // Output: "c" 10 | 11 | // Example 2: 12 | // Input: letters = ["c","f","j"], target = "c" 13 | // Output: "f" 14 | 15 | // Example 3: 16 | // Input: letters = ["c","f","j"], target = "d" 17 | // Output: "f" 18 | 19 | class Solution 20 | { 21 | public: 22 | char nextGreatestLetter(const std::vector& letters, char target) 23 | { 24 | int left = -1; 25 | int right = letters.size(); 26 | 27 | while (right - left > 1) { 28 | const int middle = left + (right - left) / 2; 29 | if (letters[middle] <= target) { 30 | left = middle; 31 | } else { 32 | right = middle; 33 | } 34 | } 35 | 36 | return right != letters.size() ? letters[right] : letters[0u]; 37 | } 38 | }; 39 | 40 | int main(int argc, char** argv) 41 | { 42 | return EXIT_SUCCESS; 43 | } 44 | -------------------------------------------------------------------------------- /Algorithms/Medium/JumpGameII.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an array of non-negative integers nums, you are initially positioned at the first index of the array. 4 | // Each element in the array represents your maximum jump length at that position. 5 | // Your goal is to reach the last index in the minimum number of jumps. 6 | // You can assume that you can always reach the last index. 7 | 8 | // Example 1: 9 | // Input: nums = [2,3,1,1,4] 10 | // Output: 2 11 | // Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. 12 | 13 | // Example 2: 14 | // Input: nums = [2,3,0,1,4] 15 | // Output: 2 16 | 17 | class Solution 18 | { 19 | public: 20 | int jump(const std::vector& nums) 21 | { 22 | size_t left = 0u; 23 | size_t right = 0u; 24 | 25 | int result = 0; 26 | while (right < nums.size() - 1u) { 27 | int farthest = 0; 28 | for (int i = left; i < right + 1; ++i) 29 | farthest = std::max(farthest, nums[i] + i); 30 | left = right + 1; 31 | right = farthest; 32 | ++result; 33 | } 34 | 35 | return result; 36 | } 37 | }; 38 | 39 | int main(int argc, char** argv) 40 | { 41 | return EXIT_SUCCESS; 42 | } -------------------------------------------------------------------------------- /Algorithms/Medium/MinimumPathSum.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. 4 | // Note: You can only move either down or right at any point in time. 5 | 6 | // Example 1: 7 | // Input: grid = [[1,3,1],[1,5,1],[4,2,1]] 8 | // Output: 7 9 | // Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum. 10 | // Output: 7 11 | // Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum. 12 | 13 | // Example 2: 14 | // Input: grid = [[1,2,3],[4,5,6]] 15 | // Output: 12 16 | 17 | class Solution 18 | { 19 | public: 20 | int minPathSum(vector>& grid) 21 | { 22 | for (size_t i = 0u; i < grid.size(); ++i) { 23 | for (size_t j = 0u; j < grid[i].size(); ++j) { 24 | if (i == 0 && j > 0) { 25 | grid[i][j] += grid[i][j - 1]; 26 | } else if (i > 0 && j == 0) { 27 | grid[i][j] += grid[i - 1][j]; 28 | } else if (i > 0 && j > 0) { 29 | grid[i][j] += std::min(grid[i - 1][j], grid[i][j - 1]); 30 | } 31 | } 32 | } 33 | } 34 | }; 35 | 36 | int main(int argc, char** argv) 37 | { 38 | return EXIT_SUCCESS; 39 | } 40 | -------------------------------------------------------------------------------- /Algorithms/Easy/CheckIfNDoubleExist.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M). 4 | 5 | // More formally check if there exists two indices i and j such that : 6 | // i != j 7 | // 0 <= i, j < arr.length 8 | // arr[i] == 2 * arr[j] 9 | 10 | // Example 1: 11 | // Input: arr = [10,2,5,3] 12 | // Output: true 13 | // Explanation: N = 10 is the double of M = 5,that is, 10 = 2 * 5. 14 | 15 | // Example 2: 16 | // Input: arr = [7,1,14,11] 17 | // Output: true 18 | // Explanation: N = 14 is the double of M = 7,that is, 14 = 2 * 7. 19 | 20 | // Example 3: 21 | // Input: arr = [3,1,7,11] 22 | // Output: false 23 | // Explanation: In this case does not exist N and M, such that N = 2 * M. 24 | 25 | class Solution 26 | { 27 | public: 28 | bool checkIfExist(const std::vector& arr) 29 | { 30 | std::unordered_set lookup; 31 | for (const int number : arr) { 32 | if (lookup.count(number * 2) != 0) 33 | return true; 34 | if ((number % 2 == 0) && (lookup.count(number / 2) != 0)) 35 | return true; 36 | lookup.insert(number); 37 | } 38 | 39 | return false; 40 | } 41 | }; 42 | 43 | int main(int argc, char** argv) 44 | { 45 | return EXIT_SUCCESS; 46 | } 47 | -------------------------------------------------------------------------------- /Algorithms/Easy/DiameterOfBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given the root of a binary tree, return the length of the diameter of the tree. 4 | // The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. 5 | // The length of a path between two nodes is represented by the number of edges between them. 6 | 7 | // Example 1: 8 | // Input: root = [1,2,3,4,5] 9 | 10 | // Output: 3 11 | // Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3]. 12 | 13 | // Example 2: 14 | // Input: root = [1,2] 15 | // Output: 1 16 | 17 | class Solution 18 | { 19 | public: 20 | int diameterOfBinaryTree(TreeNode* root) 21 | { 22 | int diameter = 0; 23 | std::function impl; 24 | impl = [&impl, &diameter] (TreeNode* node) 25 | { 26 | if (!node) { 27 | return 0; 28 | } 29 | 30 | const int left = impl(node->left); 31 | const int right = impl(node->right); 32 | diameter = std::max(diameter, left + right); 33 | return std::max(left, right) + 1; 34 | }; 35 | 36 | impl(root); 37 | return diameter; 38 | } 39 | }; 40 | 41 | int main(int argc, char** argv) 42 | { 43 | return EXIT_SUCCESS; 44 | } 45 | -------------------------------------------------------------------------------- /Algorithms/Easy/NimGame.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // You are playing the following Nim Game with your friend: 4 | 5 | // Initially, there is a heap of stones on the table. 6 | // You and your friend will alternate taking turns, and you go first. 7 | // On each turn, the person whose turn it is will remove 1 to 3 stones from the heap. 8 | // The one who removes the last stone is the winner. 9 | // Given n, the number of stones in the heap, return true if you can win the game assuming both you and your friend play optimally, otherwise return false. 10 | 11 | // Example 1: 12 | // Input: n = 4 13 | // Output: false 14 | // Explanation: These are the possible outcomes: 15 | // 1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins. 16 | // 2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins. 17 | // 3. You remove 3 stones. Your friend removes the last stone. Your friend wins. 18 | // In all outcomes, your friend wins. 19 | 20 | // Example 2: 21 | // Input: n = 1 22 | // Output: true 23 | 24 | // Example 3: 25 | // Input: n = 2 26 | // Output: true 27 | 28 | class Solution 29 | { 30 | public: 31 | bool canWinNim(int n) 32 | { 33 | return n % 4 != 0; 34 | } 35 | }; 36 | 37 | int main(int argc, char** argv) 38 | { 39 | return EXIT_SUCCESS; 40 | } -------------------------------------------------------------------------------- /Algorithms/Medium/RotateImage.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). 4 | // You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. 5 | 6 | // Example 1: 7 | // Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] 8 | // Output: [[7,4,1],[8,5,2],[9,6,3]] 9 | 10 | // Example 2: 11 | // Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] 12 | // Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] 13 | 14 | class Solution 15 | { 16 | public: 17 | void rotate(std::vector>& matrix) 18 | { 19 | if (matrix.size() < 2u) { 20 | return; 21 | } 22 | 23 | const size_t size = matrix.size(); 24 | for (size_t i = 0u; i < size; ++i) { 25 | for (size_t j = i; j < size; ++j) { 26 | std::swap(matrix[i][j], matrix[j][i]); 27 | } 28 | } 29 | 30 | for (size_t i = 0u; i < size; ++i) { 31 | for (size_t j = 0u; j < size / 2; ++j) { 32 | std::swap(matrix[i][j], matrix[i][size - 1u - j]); 33 | } 34 | } 35 | } 36 | }; 37 | 38 | int main(int argc. char** argv) 39 | { 40 | return EXIT_SUCCESS; 41 | } 42 | -------------------------------------------------------------------------------- /Algorithms/Medium/OptimalPartitionOfString.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a string s, partition the string into one or more substrings such that the characters in each substring are unique. That is, no letter appears in a single substring more than once. 4 | // Return the minimum number of substrings in such a partition. 5 | // Note that each character should belong to exactly one substring in a partition. 6 | 7 | // Example 1: 8 | // Input: s = "abacaba" 9 | // Output: 4 10 | // Explanation: 11 | // Two possible partitions are ("a","ba","cab","a") and ("ab","a","ca","ba"). 12 | // It can be shown that 4 is the minimum number of substrings needed. 13 | 14 | // Example 2: 15 | // Input: s = "ssssss" 16 | // Output: 6 17 | // Explanation: 18 | // The only valid partition is ("s","s","s","s","s","s"). 19 | 20 | class Solution 21 | { 22 | public: 23 | int partitionString(const std::string& text) 24 | { 25 | std::bitset<26> lookup; 26 | int partitions_number = 0; 27 | for (int i = 0; i < text.size(); ++i) { 28 | const int symbol = text[i] - 'a'; 29 | if (lookup.test(symbol)) { 30 | ++partitions_number; 31 | lookup.reset(); 32 | } 33 | 34 | lookup.set(symbol, 1); 35 | } 36 | 37 | return partitions_number + 1; 38 | } 39 | }; -------------------------------------------------------------------------------- /Algorithms/Medium/LongestSubstringWithoutRepeatingCharacters.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a string s, find the length of the longest substring without repeating characters. 4 | 5 | // Example 1: 6 | // Input: s = "abcabcbb" 7 | // Output: 3 8 | // Explanation: The answer is "abc", with the length of 3. 9 | 10 | // Example 2: 11 | // Input: s = "bbbbb" 12 | // Output: 1 13 | // Explanation: The answer is "b", with the length of 1. 14 | 15 | // Example 3: 16 | // Input: s = "pwwkew" 17 | // Output: 3 18 | // Explanation: The answer is "wke", with the length of 3. 19 | // Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. 20 | 21 | class Solution 22 | { 23 | public: 24 | int lengthOfLongestSubstring(const std::string& s) 25 | { 26 | int left = 0; 27 | int right = 0; 28 | int max = 0; 29 | 30 | std::unordered_set lookup; 31 | while (right < s.size()) { 32 | auto it = lookup.find(); 33 | if (!lookup.count(s[right])) { 34 | lookup.insert(s[right++]); 35 | max = std::max(max, lookup.size()); 36 | } else { 37 | lookup.erase(s[left++]); 38 | } 39 | } 40 | 41 | return max; 42 | } 43 | }; 44 | 45 | int main() 46 | { 47 | return EXIT_SUCCESS; 48 | } 49 | -------------------------------------------------------------------------------- /Algorithms/Medium/SwapNodesInPairs.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.) 4 | 5 | // Example 1: 6 | // Input: head = [1,2,3,4] 7 | // Output: [2,1,4,3] 8 | 9 | // Example 2: 10 | // Input: head = [] 11 | // Output: [] 12 | 13 | // Example 3: 14 | // Input: head = [1] 15 | // Output: [1] 16 | 17 | class Solution { 18 | public: 19 | ListNode* swapPairs(ListNode* head) 20 | { 21 | if (!head || !head->next) 22 | return head; 23 | 24 | ListNode* current = head; 25 | ListNode* previous = nullptr; 26 | ListNode* dummy = head->next; 27 | while (current && current->next) { 28 | ListNode* temp = current; 29 | current = current->next; 30 | 31 | temp->next = current->next; 32 | current->next = temp; 33 | 34 | if (previous) { 35 | previous->next = current; 36 | } 37 | 38 | previous = current->next; 39 | current = temp->next; 40 | } 41 | 42 | return dummy; 43 | } 44 | }; 45 | 46 | int main(int argc, char** argv) 47 | { 48 | return EXIT_SUCCESS; 49 | } -------------------------------------------------------------------------------- /Algorithms/Easy/CountNegativeNumbersInASortedMatrix.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid. 4 | 5 | // Example 1: 6 | // Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]] 7 | // Output: 8 8 | // Explanation: There are 8 negatives number in the matrix. 9 | 10 | // Example 2: 11 | // Input: grid = [[3,2],[1,0]] 12 | // Output: 0 13 | 14 | class Solution 15 | { 16 | public: 17 | int countNegatives(const std::vector>& grid) 18 | { 19 | const int rows_size = grid.size(); 20 | const int cols_size = grid[0].size(); 21 | 22 | int count = 0; 23 | for (int i = rows_size - 1u; i >= 0; --i) { 24 | int left = -1; 25 | int right = cols_size; 26 | while (right - left > 1) { 27 | int middle = left + (right - left) / 2; 28 | if (grid[i][middle] <= -1) { 29 | right = middle; 30 | } else { 31 | left = middle; 32 | } 33 | } 34 | 35 | if (right == cols_size) 36 | break; 37 | 38 | count += cols_size - right; 39 | } 40 | 41 | return count; 42 | } 43 | }; 44 | 45 | int main(int argc, char** argv) 46 | { 47 | return EXIT_SUCCESS; 48 | } 49 | -------------------------------------------------------------------------------- /Algorithms/Easy/MonotonicArray.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // An array is monotonic if it is either monotone increasing or monotone decreasing. 4 | // An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j]. 5 | // Given an integer array nums, return true if the given array is monotonic, or false otherwise. 6 | 7 | // Example 1: 8 | // Input: nums = [1,2,2,3] 9 | // Output: true 10 | 11 | // Example 2: 12 | // Input: nums = [6,5,4,4] 13 | // Output: true 14 | 15 | // Example 3: 16 | // Input: nums = [1,3,2] 17 | // Output: false 18 | 19 | class Solution { 20 | public: 21 | bool isMonotonic(const std::vector& nums) 22 | { 23 | bool increased = false; 24 | bool decreased = false; 25 | for (int i = 1; i < nums.size(); ++i) { 26 | const int current = nums[i]; 27 | const int previous = nums[i - 1]; 28 | if (previous < current) { 29 | if (decreased) 30 | return false; 31 | 32 | increased = true; 33 | } else if (previous > current) { 34 | if (increased) 35 | return false; 36 | 37 | decreased = true; 38 | } 39 | } 40 | 41 | return true; 42 | } 43 | }; -------------------------------------------------------------------------------- /Algorithms/Medium/NextGreaterNodeInLinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // You are given the head of a linked list with n nodes. 4 | // For each node in the list, find the value of the next greater node. That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it. 5 | // Return an integer array answer where answer[i] is the value of the next greater node of the ith node (1-indexed). If the ith node does not have a next greater node, set answer[i] = 0. 6 | 7 | // Example 1: 8 | // Input: head = [2,1,5] 9 | // Output: [5,5,0] 10 | 11 | // Example 2: 12 | // Input: head = [2,7,4,3,5] 13 | // Output: [7,0,5,5,0] 14 | 15 | class Solution 16 | { 17 | public: 18 | std::vector nextLargerNodes(ListNode* head) 19 | { 20 | std::vector values; 21 | while (head) { 22 | values.push_back(head->val); 23 | head = head->next; 24 | } 25 | 26 | std::stack stack; 27 | std::vector result(values.size()); 28 | for (int i = 0; i < values.size(); ++i) { 29 | while (!stack.empty() && values[stack.top()] < values[i]) { 30 | result[stack.top()] = values[i]; 31 | stack.pop(); 32 | } 33 | 34 | stack.push(i); 35 | } 36 | 37 | return result; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /Algorithms/Easy/DecryptStringFromAlphabetToIntegerMapping.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // You are given a string s formed by digits and '#'. We want to map s to English lowercase characters as follows: 4 | // Characters ('a' to 'i') are represented by ('1' to '9') respectively. 5 | // Characters ('j' to 'z') are represented by ('10#' to '26#') respectively. 6 | // Return the string formed after mapping. 7 | // The test cases are generated so that a unique mapping will always exist. 8 | 9 | // Example 1: 10 | // Input: s = "10#11#12" 11 | // Output: "jkab" 12 | // Explanation: "j" -> "10#" , "k" -> "11#" , "a" -> "1" , "b" -> "2". 13 | 14 | // Example 2: 15 | // Input: s = "1326#" 16 | // Output: "acz" 17 | 18 | class Solution 19 | { 20 | public: 21 | string freqAlphabets(const std::string& s) 22 | { 23 | std::string result; 24 | for (size_t i = 0u; i < s.size();) { 25 | if (i + 2 < s.size() && s[i + 2] == '#') { 26 | const size_t number = (s[i] - '0') * 10 + (s[i + 1] - '0'); 27 | result += 'a' + number - 1; 28 | i += 3; 29 | } else { 30 | result += 'a' + (s[i] - '0') - 1; 31 | ++i; 32 | } 33 | } 34 | 35 | return result; 36 | } 37 | }; 38 | 39 | int main(int argc, char** argv) 40 | { 41 | return EXIT_SUCCESS; 42 | } 43 | -------------------------------------------------------------------------------- /Algorithms/Easy/PeakIndexInAMountainArray.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Let's call an array arr a mountain if the following properties hold: 4 | 5 | // arr.length >= 3 6 | // There exists some i with 0 < i < arr.length - 1 such that: 7 | // arr[0] < arr[1] < ... arr[i-1] < arr[i] 8 | // arr[i] > arr[i+1] > ... > arr[arr.length - 1] 9 | // Given an integer array arr that is guaranteed to be a mountain, return any i such that arr[0] < arr[1] < ... arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]. 10 | 11 | // Example 1: 12 | // Input: arr = [0,1,0] 13 | // Output: 1 14 | 15 | // Example 2: 16 | // Input: arr = [0,2,1,0] 17 | // Output: 1 18 | 19 | // Example 3: 20 | // Input: arr = [0,10,5,2] 21 | // Output: 1 22 | 23 | class Solution 24 | { 25 | public: 26 | int peakIndexInMountainArray(const std::vector& arr) 27 | { 28 | int left = 0; 29 | int right = arr.size() - 1; 30 | 31 | while (left != right) { 32 | const int m1 = left + (right - left) / 3; 33 | const int m2 = right - (right - left) / 3; 34 | if (arr[m2] > arr[m1]) { 35 | left = m1 + 1; 36 | } else { 37 | right = m2 - 1; 38 | } 39 | } 40 | 41 | return left; 42 | } 43 | }; 44 | 45 | int main(int argc, char** argv) 46 | { 47 | return EXIT_SUCCESS; 48 | } 49 | -------------------------------------------------------------------------------- /Algorithms/Easy/LargestNumberAtLeastTwiceOfOthers.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // You are given an integer array nums where the largest integer is unique. 4 | // Determine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return -1 otherwise. 5 | 6 | // Example 1: 7 | // Input: nums = [3,6,1,0] 8 | // Output: 1 9 | // Explanation: 6 is the largest integer. 10 | // For every other number in the array x, 6 is at least twice as big as x. 11 | // The index of value 6 is 1, so we return 1. 12 | 13 | // Example 2: 14 | // Input: nums = [1,2,3,4] 15 | // Output: -1 16 | // Explanation: 4 is less than twice the value of 3, so we return -1. 17 | 18 | class Solution 19 | { 20 | public: 21 | int dominantIndex(std::vector& nums) 22 | { 23 | int max_num = 0; 24 | int max_num_idx = -1; 25 | for (int i = 0; i < nums.size(); ++i) { 26 | if (nums[i] >= 2 * max_num) { 27 | max_num_idx = i; 28 | max_num = nums[i]; 29 | } else if (nums[i] > max_num) { 30 | max_num_idx = -1; 31 | max_num = nums[i]; 32 | } else if (nums[i] > max_num / 2) { 33 | max_num_idx = -1; 34 | } 35 | } 36 | 37 | return max_num_idx; 38 | } 39 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/DecompressRunLengthEncodedList.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // We are given a list nums of integers representing a list compressed with run-length encoding. 4 | // Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0). For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list. 5 | // Return the decompressed list. 6 | 7 | // Example 1: 8 | // Input: nums = [1,2,3,4] 9 | // Output: [2,4,4,4] 10 | // Explanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2]. 11 | // The second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4]. 12 | // At the end the concatenation [2] + [4,4,4] is [2,4,4,4]. 13 | 14 | // Example 2: 15 | // Input: nums = [1,1,2,3] 16 | // Output: [1,3,3] 17 | 18 | class Solution 19 | { 20 | public: 21 | std::vector decompressRLElist(std::vector& nums) 22 | { 23 | std::vector result; 24 | for (int i = 0; i < nums.size(); i += 2) { 25 | const int number = nums[i + 1]; 26 | int frequency = nums[i]; 27 | while (frequency > 0) { 28 | result.push_back(number); 29 | --frequency; 30 | } 31 | } 32 | 33 | return result; 34 | } 35 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/RepeatedSubstringPattern.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. 4 | 5 | // Example 1: 6 | // Input: s = "abab" 7 | // Output: true 8 | // Explanation: It is the substring "ab" twice. 9 | 10 | // Example 2: 11 | // Input: s = "aba" 12 | // Output: false 13 | 14 | // Example 3: 15 | // Input: s = "abcabcabcabc" 16 | // Output: true 17 | // Explanation: It is the substring "abc" four times or the substring "abcabc" twice. 18 | 19 | class Solution 20 | { 21 | public: 22 | bool repeatedSubstringPattern(std::string s) 23 | { 24 | std::string temp; 25 | temp.reserve(s.size()); 26 | 27 | int length = s.size(); 28 | for (int i = length / 2; i > 0; --i) { 29 | if (length % i == 0) { 30 | int repeats_number = length / i; 31 | 32 | std::string substring(begin(s), begin(s) + i); 33 | while (repeats_number > 0) { 34 | temp += substring; 35 | --repeats_number; 36 | } 37 | 38 | if (temp == s) 39 | return true; 40 | else 41 | temp.clear(); 42 | } 43 | } 44 | 45 | return false; 46 | } 47 | }; -------------------------------------------------------------------------------- /Algorithms/Medium/MaximalSquare.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. 4 | 5 | // Example 1: 6 | // Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] 7 | // Output: 4 8 | 9 | // Example 2: 10 | // Input: matrix = [["0","1"],["1","0"]] 11 | // Output: 1 12 | 13 | // Example 3: 14 | // Input: matrix = [["0"]] 15 | // Output: 0 16 | 17 | class Solution 18 | { 19 | public: 20 | int maximalSquare(const std::vector>& matrix) 21 | { 22 | const size_t row_size = matrix.size(); 23 | const size_t col_size = matrix[0].size(); 24 | 25 | size_t max_square = 0u; 26 | std::vector> cache(row_size + 1u, std::vector(col_size + 1u, 0u)); 27 | 28 | for (size_t i = 1u; i <= row_size; ++i) { 29 | for (size_t j = 1u; j <= col_size; ++j) { 30 | if (matrix[i - 1][j - 1] == '1') 31 | cache[i][j] = std::min({cache[i - 1][j - 1], cache[i - 1][j], cache[i][j - 1]}) + 1; 32 | max_square = std::max(max_square, cache[i][j]); 33 | } 34 | } 35 | 36 | return max_square * max_square; 37 | } 38 | }; 39 | 40 | int main(int argc, char** argv) 41 | { 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Algorithms/Easy/ValidPalindromeII.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a string s, return true if the s can be palindrome after deleting at most one character from it. 4 | 5 | // Example 1: 6 | // Input: s = "aba" 7 | // Output: true 8 | 9 | // Example 2: 10 | // Input: s = "abca" 11 | // Output: true 12 | // Explanation: You could delete the character 'c'. 13 | 14 | // Example 3: 15 | // Input: s = "abc" 16 | // Output: false 17 | 18 | class Solution { 19 | public: 20 | bool validPalindromeImpl(string s, int left, int right) 21 | { 22 | while (left <= right) { 23 | if (s[left] != s[right]) 24 | return false; 25 | 26 | ++left; 27 | --right; 28 | } 29 | 30 | return true; 31 | } 32 | 33 | bool validPalindrome(string s) 34 | { 35 | int left = 0; 36 | int right = s.size() - 1; 37 | bool was_deleted = false; 38 | while (left <= right) { 39 | if (s[left] != s[right]) { 40 | const bool left_result = validPalindromeImpl(s, left + 1, right); 41 | const bool right_result = validPalindromeImpl(s, left, right - 1); 42 | return left_result || right_result; 43 | } else { 44 | ++left; 45 | --right; 46 | } 47 | } 48 | 49 | return true; 50 | } 51 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/SelfDividingNumbers.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // A self-dividing number is a number that is divisible by every digit it contains. 4 | // For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. 5 | // A self-dividing number is not allowed to contain the digit zero. 6 | // Given two integers left and right, return a list of all the self-dividing numbers in the range [left, right]. 7 | 8 | // Example 1: 9 | // Input: left = 1, right = 22 10 | // Output: [1,2,3,4,5,6,7,8,9,11,12,15,22] 11 | 12 | // Example 2: 13 | // Input: left = 47, right = 85 14 | // Output: [48,55,66,77] 15 | 16 | class Solution 17 | { 18 | public: 19 | bool isSelfDividingNumber(int number) 20 | { 21 | const int source_number = number; 22 | while (number != 0) { 23 | const int digit = number % 10; 24 | if (digit == 0 || source_number % digit != 0) 25 | return false; 26 | 27 | number /= 10; 28 | } 29 | 30 | return true; 31 | } 32 | 33 | std::vector selfDividingNumbers(int left, int right) 34 | { 35 | std::vector result; 36 | for (int number = left; number <= right; ++number) { 37 | if (isSelfDividingNumber(number)) 38 | result.push_back(number); 39 | } 40 | 41 | return result; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /Algorithms/Easy/LargestSubstringBetweenTwoEqualCharacters.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1. 4 | // A substring is a contiguous sequence of characters within a string. 5 | 6 | // Example 1: 7 | // Input: s = "aa" 8 | // Output: 0 9 | // Explanation: The optimal substring here is an empty substring between the two 'a's. 10 | 11 | // Example 2: 12 | // Input: s = "abca" 13 | // Output: 2 14 | // Explanation: The optimal substring here is "bc". 15 | 16 | // Example 3: 17 | // Input: s = "cbzxy" 18 | // Output: -1 19 | // Explanation: There are no characters that appear twice in s. 20 | 21 | class Solution 22 | { 23 | public: 24 | int maxLengthBetweenEqualCharacters(std::string text) 25 | { 26 | int max_length = -1; 27 | std::unordered_map lookup; 28 | for (int i = 0; i < text.size(); ++i) { 29 | const char letter = text[i]; 30 | auto it = lookup.find(letter); 31 | if (it != end(lookup)) { 32 | const int previous_index = it->second; 33 | max_length = std::max(max_length, i - previous_index - 1); 34 | } else { 35 | lookup[letter] = i; 36 | } 37 | } 38 | 39 | return max_length; 40 | } 41 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/MissingNumber.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. 4 | 5 | // Example 1: 6 | // Input: nums = [3,0,1] 7 | // Output: 2 8 | // Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums. 9 | 10 | // Example 2: 11 | // Input: nums = [0,1] 12 | // Output: 2 13 | // Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums. 14 | 15 | // Example 3: 16 | // Input: nums = [9,6,4,2,3,5,7,0,1] 17 | // Output: 8 18 | // Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums. 19 | 20 | class Solution 21 | { 22 | public: 23 | int missingNumber(const std::vector& nums) 24 | { 25 | int amount = 0; 26 | int target_amount = 0; 27 | for (size_t i = 0; i < nums.size(); ++i) { 28 | amount += nums[i]; 29 | target_amount += i; 30 | } 31 | 32 | target_amount += nums.size(); 33 | return target_amount - amount; 34 | } 35 | }; 36 | 37 | int main(int argc, char** argv) 38 | { 39 | return EXIT_SUCCESS; 40 | } 41 | -------------------------------------------------------------------------------- /Algorithms/Easy/SquaresOfASortedArray.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. 4 | 5 | // Example 1: 6 | // Input: nums = [-4,-1,0,3,10] 7 | // Output: [0,1,9,16,100] 8 | // Explanation: After squaring, the array becomes [16,1,0,9,100]. 9 | // After sorting, it becomes [0,1,9,16,100]. 10 | 11 | // Example 2: 12 | // Input: nums = [-7,-3,2,3,11] 13 | // Output: [4,9,9,49,121] 14 | 15 | class Solution 16 | { 17 | public: 18 | std::vector sortedSquares(const std::vector& nums) 19 | { 20 | int left = 0; 21 | int right = nums.size() - 1; 22 | int insert_index = right; 23 | std::vector result(nums.size()); 24 | 25 | while (left <= right) { 26 | const auto left_value = nums[left]; 27 | const auto right_value = nums[right]; 28 | if (abs(left_value) <= abs(right_value)) { 29 | result[insert_index] = right_value * right_value; 30 | --right; 31 | } else { 32 | result[insert_index] = left_value * left_value; 33 | ++left; 34 | } 35 | 36 | --insert_index; 37 | } 38 | 39 | return result; 40 | } 41 | }; 42 | 43 | int main(int argc, char** argv) 44 | { 45 | 46 | } 47 | -------------------------------------------------------------------------------- /Algorithms/Easy/PalindromeNumber.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer x, return true if x is palindrome integer. 4 | // An integer is a palindrome when it reads the same backward as forward. 5 | // For example, 121 is a palindrome while 123 is not. 6 | 7 | // Example 1: 8 | // Input: x = 121 9 | // Output: true 10 | // Explanation: 121 reads as 121 from left to right and from right to left. 11 | 12 | // Example 2: 13 | // Input: x = -121 14 | // Output: false 15 | // Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. 16 | 17 | // Example 3: 18 | // Input: x = 10 19 | // Output: false 20 | // Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 21 | 22 | class Solution 23 | { 24 | public: 25 | bool isPalindrome(int x) 26 | { 27 | if (x < 0) 28 | return false; 29 | 30 | int number = x; 31 | int reversed = 0; 32 | while (x > 0) { 33 | const int digit = x % 10; 34 | if (reversed > std::numeric_limits::max() / 10 || 35 | (reversed == std::numeric_limits::max() / 10 && digit > 7)) 36 | return false; 37 | reversed = reversed * 10 + digit; 38 | x /= 10; 39 | } 40 | 41 | return number == reversed; 42 | } 43 | }; 44 | 45 | int main(int argc, char** argv) 46 | { 47 | return EXIT_SUCCESS; 48 | } -------------------------------------------------------------------------------- /Algorithms/Medium/Permutations.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order. 4 | 5 | // Example 1: 6 | // Input: nums = [1,2,3] 7 | // Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] 8 | 9 | // Example 2: 10 | // Input: nums = [0,1] 11 | // Output: [[0,1],[1,0]] 12 | 13 | // Example 3: 14 | // Input: nums = [1] 15 | // Output: [[1]] 16 | 17 | class Solution 18 | { 19 | public: 20 | std::vector> permute(std::vector& nums) 21 | { 22 | if (nums.size() <= 1u) { 23 | return { nums }; 24 | } 25 | 26 | std::vector> result; 27 | std::function&, size_t)> impl; 28 | impl = [&impl, &result](std::vector& nums, size_t begin) 29 | { 30 | if (begin >= nums.size()) { 31 | result.push_back(nums); 32 | return; 33 | } 34 | 35 | for (size_t i = begin; i < nums.size(); ++i) { 36 | swap(nums[begin], nums[i]); 37 | impl(nums, begin + 1); 38 | swap(nums[begin], nums[i]); 39 | } 40 | }; 41 | 42 | impl(nums, 0u); 43 | return result; 44 | } 45 | }; 46 | 47 | int main(int argc, char** argv) 48 | { 49 | return EXIT_SUCCESS; 50 | } 51 | -------------------------------------------------------------------------------- /Algorithms/Easy/SumOfAllOddLengthSubarrays.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an array of positive integers arr, calculate the sum of all possible odd-length subarrays. 4 | // A subarray is a contiguous subsequence of the array. 5 | // Return the sum of all odd-length subarrays of arr. 6 | 7 | // Example 1: 8 | 9 | // Input: arr = [1,4,2,5,3] 10 | // Output: 58 11 | // Explanation: The odd-length subarrays of arr and their sums are: 12 | // [1] = 1 13 | // [4] = 4 14 | // [2] = 2 15 | // [5] = 5 16 | // [3] = 3 17 | // [1,4,2] = 7 18 | // [4,2,5] = 11 19 | // [2,5,3] = 10 20 | // [1,4,2,5,3] = 15 21 | // If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58 22 | 23 | // Example 2: 24 | // Input: arr = [1,2] 25 | // Output: 3 26 | // Explanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3. 27 | 28 | // Example 3: 29 | // Input: arr = [10,11,12] 30 | // Output: 66 31 | 32 | class Solution 33 | { 34 | public: 35 | int sumOddLengthSubarrays(const std::vector& arr) 36 | { 37 | int sum = 0; 38 | const size_t size = arr.size(); 39 | for (size_t i = 0; i < size; i++) { 40 | const int contribution = ((i + 1) * (size - i) + 1) / 2; 41 | sum += contribution * arr[i]; 42 | } 43 | 44 | return sum; 45 | } 46 | }; 47 | 48 | int main(int argc, char** argv) 49 | { 50 | return EXIT_SUCCESS; 51 | } 52 | -------------------------------------------------------------------------------- /Algorithms/Easy/LowestCommonAncestorOfBinarySearchTree.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. 4 | // According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” 5 | 6 | // Example 1: 7 | // Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 8 | // Output: 6 9 | // Explanation: The LCA of nodes 2 and 8 is 6. 10 | 11 | // Example 2: 12 | // Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 13 | // Output: 2 14 | // Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. 15 | 16 | // Example 3: 17 | // Input: root = [2,1], p = 2, q = 1 18 | // Output: 2 19 | 20 | class Solution 21 | { 22 | public: 23 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) 24 | { 25 | if (p->val < root->val && q->val < root->val) { 26 | return lowestCommonAncestor(root->left, p, q); 27 | } 28 | if (p->val > root->val && q->val > root->val) { 29 | return lowestCommonAncestor(root->right, p, q); 30 | } 31 | return root; 32 | } 33 | }; 34 | 35 | int main(int argc, char** argv) 36 | { 37 | return EXIT_SUCCESS; 38 | } 39 | -------------------------------------------------------------------------------- /Algorithms/Medium/GenerateParentheses.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 4 | 5 | // Example 1: 6 | // Input: n = 3 7 | // Output: ["((()))","(()())","(())()","()(())","()()()"] 8 | 9 | // Example 2: 10 | // Input: n = 1 11 | // Output: ["()"] 12 | 13 | class Solution { 14 | public: 15 | std::vector generateParenthesis(int n) 16 | { 17 | std::string combination; 18 | int opened = 0, closed = 0; 19 | std::vector result; 20 | std::function backtracking; 21 | backtracking = [&backtracking, &result, &combination, n] (int opened, int closed) 22 | { 23 | if (opened == n && closed == n) 24 | return result.push_back(combination); 25 | 26 | if (opened < n) { 27 | combination += '('; 28 | backtracking(opened + 1, closed); 29 | combination.pop_back(); 30 | } 31 | 32 | if (closed < opened) { 33 | combination += ')'; 34 | backtracking(opened, closed + 1); 35 | combination.pop_back(); 36 | } 37 | }; 38 | 39 | backtracking(0, 0); 40 | return result; 41 | } 42 | }; 43 | 44 | int main(int argc, char** argv) 45 | { 46 | return EXIT_SUCCESS; 47 | } -------------------------------------------------------------------------------- /Algorithms/Easy/LongestHarmoniousSubsequence.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1. 4 | // Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences. 5 | // A subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. 6 | 7 | // Example 1: 8 | // Input: nums = [1,3,2,2,5,2,3,7] 9 | // Output: 5 10 | // Explanation: The longest harmonious subsequence is [3,2,2,2,3]. 11 | 12 | // Example 2: 13 | // Input: nums = [1,2,3,4] 14 | // Output: 2 15 | 16 | // Example 3: 17 | // Input: nums = [1,1,1,1] 18 | // Output: 0 19 | 20 | class Solution 21 | { 22 | public: 23 | int findLHS(std::vector& nums) 24 | { 25 | std::sort(begin(nums), end(nums)); 26 | 27 | int left = 0; 28 | int right = 1; 29 | int longest_subsequence = 0; 30 | while (right < nums.size()) { 31 | const int diff = nums[right] - nums[left]; 32 | if (diff == 1) 33 | longest_subsequence = std::max(longest_subsequence, right - left + 1); 34 | 35 | if (diff <= 1) 36 | ++right; 37 | else 38 | ++left; 39 | } 40 | 41 | return longest_subsequence; 42 | } 43 | }; -------------------------------------------------------------------------------- /Algorithms/Medium/LongestPalindromicSubstring.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a string s, return the longest palindromic substring in s. 4 | 5 | // Example 1: 6 | // Input: s = "babad" 7 | // Output: "bab" 8 | // Explanation: "aba" is also a valid answer. 9 | 10 | // Example 2: 11 | // Input: s = "cbbd" 12 | // Output: "bb" 13 | 14 | class Solution 15 | { 16 | public: 17 | std::string longestPalindrome(const std::string& s) 18 | { 19 | int start = 0; 20 | int end = 0; 21 | 22 | for (int i = 0; i < s.size(); ++i) { 23 | const int length_1 = expandFromMiddle(s, i, i); 24 | const int length_2 = expandFromMiddle(s, i, i + 1); 25 | const int length = std::max(length_1, length_2); 26 | if (length > end - start) { 27 | start = i - (length - 1) / 2; 28 | end = i + length / 2; 29 | } 30 | } 31 | 32 | return s.substr(start, end - start + 1); 33 | } 34 | 35 | int expandFromMiddle(const std::string& s, int left, int right) 36 | { 37 | if (left > right) { 38 | return 0; 39 | } 40 | 41 | while (left >= 0 && right < s.size() && s[left] == s[right]) { 42 | --left; 43 | ++right; 44 | } 45 | 46 | return right - left - 1; 47 | } 48 | }; 49 | 50 | int main(int argc, char** argv) 51 | { 52 | return EXIT_SUCCESS; 53 | } 54 | -------------------------------------------------------------------------------- /Algorithms/Medium/ValidateBinarySearchTree.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given the root of a binary tree, determine if it is a valid binary search tree (BST). 4 | // A valid BST is defined as follows: 5 | // The left subtree of a node contains only nodes with keys less than the node's key. 6 | // The right subtree of a node contains only nodes with keys greater than the node's key. 7 | // Both the left and right subtrees must also be binary search trees. 8 | 9 | // Example 1: 10 | // Input: root = [2,1,3] 11 | // Output: true 12 | 13 | // Example 2: 14 | // Input: root = [5,1,4,null,null,3,6] 15 | // Output: false 16 | // Explanation: The root node's value is 5 but its right child's value is 4. 17 | 18 | class Solution 19 | { 20 | public: 21 | bool isValidBST(TreeNode* root) 22 | { 23 | std::function impl; 24 | impl = [&impl] (TreeNode* node, TreeNode* max, TreeNode* min) 25 | { 26 | if (!node) { 27 | return true; 28 | } else if ((max && node->val >= max->val) || (min && node->val <= min->val)) { 29 | return false; 30 | } else { 31 | return impl(node->left, node, min) && impl(node->right, max, node); 32 | } 33 | }; 34 | 35 | return impl(root, nullptr, nullptr); 36 | } 37 | }; 38 | 39 | int main(int argc, char** argv) 40 | { 41 | return EXIT_SUCCESS; 42 | } 43 | -------------------------------------------------------------------------------- /Algorithms/Medium/HIndex.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return the researcher's h-index. 4 | // According to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h such that the given researcher has published at least h papers that have each been cited at least h times. 5 | 6 | // Example 1: 7 | // Input: citations = [3,0,6,1,5] 8 | // Output: 3 9 | // Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. 10 | // Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. 11 | 12 | // Example 2: 13 | // Input: citations = [1,3,1] 14 | // Output: 1 15 | 16 | class Solution 17 | { 18 | public: 19 | int hIndex(std::vector& citations) 20 | { 21 | std::vector frequencies(1000 + 1); 22 | for (const int citation: citations) 23 | ++frequencies[citation]; 24 | 25 | int count = 0; 26 | for (int citation = frequencies.size() - 1; citation >= 0; --citation) { 27 | const int frequency = frequencies[citation]; 28 | count += frequency; 29 | 30 | if (count >= citation) 31 | return citation; 32 | } 33 | 34 | return 0; 35 | } 36 | }; -------------------------------------------------------------------------------- /Algorithms/Medium/HouseRobber.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night. 4 | // Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police. 5 | 6 | // Example 1: 7 | // Input: nums = [1,2,3,1] 8 | // Output: 4 9 | // Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). 10 | // Total amount you can rob = 1 + 3 = 4. 11 | 12 | // Example 2: 13 | // Input: nums = [2,7,9,3,1] 14 | // Output: 12 15 | // Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). 16 | // Total amount you can rob = 2 + 9 + 1 = 12. 17 | 18 | class Solution 19 | { 20 | public: 21 | int rob(vector& nums) 22 | { 23 | if (nums.size() > 1) { 24 | nums[1] = std::max(nums[0], nums[1]); 25 | } 26 | 27 | for (size_t i = 2u; i < nums.size(); ++i) { 28 | nums[i] = std::max(nums[i - 1], nums[i] + nums[i - 2]); 29 | } 30 | 31 | return nums[nums.size() - 1u]; 32 | } 33 | }; 34 | 35 | int main(int argc, char** argv) 36 | { 37 | return EXIT_SUCCESS; 38 | } 39 | -------------------------------------------------------------------------------- /Algorithms/Medium/GroupAnagrams.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an array of strings strs, group the anagrams together. You can return the answer in any order. 4 | // An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 5 | 6 | // Example 1: 7 | // Input: strs = ["eat","tea","tan","ate","nat","bat"] 8 | // Output: [["bat"],["nat","tan"],["ate","eat","tea"]] 9 | 10 | // Example 2: 11 | // Input: strs = [""] 12 | // Output: [[""]] 13 | 14 | // Example 3: 15 | // Input: strs = ["a"] 16 | // Output: [["a"]] 17 | 18 | class Solution 19 | { 20 | public: 21 | std::vector> groupAnagrams(const std::vector& strings) 22 | { 23 | std::vector> result{}; 24 | std::unordered_map> lookup_table{}; 25 | for (const auto& string : strings) { 26 | std::string sorted_string = string; 27 | std::sort(sorted_string.begin(), sorted_string.end()); 28 | lookup_table[sorted_string].push_back(string); 29 | } 30 | 31 | result.reserve(lookup_table.size()); 32 | for (auto&& anagrams : lookup_table) { 33 | result.push_back(std::move(anagrams.second)); 34 | } 35 | 36 | return result; 37 | } 38 | }; 39 | 40 | int main(int argc, char** argv) 41 | { 42 | return EXIT_SUCCESS; 43 | } 44 | -------------------------------------------------------------------------------- /Algorithms/Easy/AverageSalaryExcludingTheMinimumAndMaximumSalary.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // You are given an array of unique integers salary where salary[i] is the salary of the ith employee. 4 | // Return the average salary of employees excluding the minimum and maximum salary. Answers within 10-5 of the actual answer will be accepted. 5 | 6 | // Example 1: 7 | // Input: salary = [4000,3000,1000,2000] 8 | // Output: 2500.00000 9 | // Explanation: Minimum salary and maximum salary are 1000 and 4000 respectively. 10 | // Average salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500 11 | 12 | // Example 2: 13 | // Input: salary = [1000,2000,3000] 14 | // Output: 2000.00000 15 | // Explanation: Minimum salary and maximum salary are 1000 and 3000 respectively. 16 | // Average salary excluding minimum and maximum salary is (2000) / 1 = 2000 17 | 18 | class Solution 19 | { 20 | public: 21 | double average(const std::vector& salary) 22 | { 23 | int min = salary[0]; 24 | int max = salary[0]; 25 | int sum = salary[0]; 26 | 27 | const size_t size = salary.size(); 28 | for (size_t i = 1u; i < size; ++i) { 29 | min = std::min(min, salary[i]); 30 | max = std::max(max, salary[i]); 31 | sum += salary[i]; 32 | } 33 | 34 | return double(sum - max - min) / (size - 2u); 35 | } 36 | }; 37 | 38 | int main(int argc, char** argv) 39 | { 40 | return EXIT_SUCCESS; 41 | } 42 | -------------------------------------------------------------------------------- /Algorithms/Medium/3SumClosest.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. 4 | // Return the sum of the three integers. 5 | // You may assume that each input would have exactly one solution. 6 | 7 | // Example 1: 8 | // Input: nums = [-1,2,1,-4], target = 1 9 | // Output: 2 10 | // Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 11 | 12 | // Example 2: 13 | // Input: nums = [0,0,0], target = 1 14 | // Output: 0 15 | 16 | class Solution 17 | { 18 | public: 19 | int threeSumClosest(std::vector& nums, int target) 20 | { 21 | std::sort(begin(nums), end(nums)); 22 | 23 | int closest_sum = nums[0] + nums[1] + nums[2]; 24 | for (size_t i = 0u; i < nums.size() - 2u; ++i) { 25 | size_t left = i + 1; 26 | size_t right = nums.size() - 1u; 27 | while (left < right) { 28 | const int current_sum = nums[i] + nums[left] + nums[right]; 29 | if (current_sum > target) { 30 | --right; 31 | } else { 32 | ++left; 33 | } 34 | 35 | if (std::abs(target - current_sum) < std::abs(target - closest_sum)) { 36 | closest_sum = current_sum; 37 | } 38 | } 39 | } 40 | 41 | return closest_sum; 42 | } 43 | }; 44 | 45 | int main(int argc, char** argv) 46 | { 47 | return EXIT_SUCCESS; 48 | } -------------------------------------------------------------------------------- /Algorithms/Easy/DayOfTheYear.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year. 4 | 5 | // Example 1: 6 | // Input: date = "2019-01-09" 7 | // Output: 9 8 | // Explanation: Given date is the 9th day of the year in 2019. 9 | 10 | // Example 2: 11 | // Input: date = "2019-02-10" 12 | // Output: 41 13 | 14 | class Solution { 15 | public: 16 | int parseNumber(std::string str) 17 | { 18 | int number = 0; 19 | for (int i = 0; i < str.size(); ++i) 20 | number = (number * 10) + (str[i] - '0'); 21 | 22 | return number; 23 | } 24 | 25 | int dayOfYear(std::string date) 26 | { 27 | std::array months{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; 28 | 29 | const int year = parseNumber(std::string(begin(date), begin(date) + 4)); 30 | const int month = parseNumber(std::string(begin(date) + 5, begin(date) + 7)); 31 | const int day = parseNumber(std::string(begin(date) + 8, begin(date) + 10)); 32 | const bool leap_year = (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0); 33 | 34 | int days_number = 0; 35 | for (int i = 1; i < month; ++i) { 36 | if (i == 2 && leap_year) 37 | days_number += months[i] + 1; 38 | else 39 | days_number += months[i]; 40 | } 41 | 42 | return days_number + day; 43 | } 44 | }; -------------------------------------------------------------------------------- /Algorithms/Hard/BinaryTreeMaximumPathSum.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root. 4 | // The path sum of a path is the sum of the node's values in the path. 5 | // Given the root of a binary tree, return the maximum path sum of any non-empty path. 6 | 7 | // Example 1: 8 | // Input: root = [1,2,3] 9 | // Output: 6 10 | // Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6. 11 | 12 | // Example 2: 13 | // Input: root = [-10,9,20,null,null,15,7] 14 | // Output: 42 15 | // Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42. 16 | 17 | class Solution 18 | { 19 | public: 20 | int maxPathSum(TreeNode* root) 21 | { 22 | int max_path_sum = root->val; 23 | std::function impl; 24 | impl = [&impl, &max_path_sum](TreeNode* node) 25 | { 26 | if (!node) 27 | return 0; 28 | 29 | const int left = std::max(impl(node->left), 0); 30 | const int right = std::max(impl(node->right), 0); 31 | max_path_sum = std::max(max_path_sum, node->val + left + right); 32 | return node->val + std::max(left, right); 33 | }; 34 | 35 | impl(root); 36 | return max_path_sum; 37 | } 38 | }; -------------------------------------------------------------------------------- /Algorithms/Medium/CoinChange.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. 4 | // Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. 5 | // You may assume that you have an infinite number of each kind of coin. 6 | 7 | // Example 1: 8 | // Input: coins = [1,2,5], amount = 11 9 | // Output: 3 10 | // Explanation: 11 = 5 + 5 + 1 11 | 12 | // Example 2: 13 | // Input: coins = [2], amount = 3 14 | // Output: -1 15 | 16 | // Example 3: 17 | // Input: coins = [1], amount = 0 18 | // Output: 0 19 | 20 | class Solution 21 | { 22 | public: 23 | int coinChange(vector& coins, int amount) 24 | { 25 | std::vector dp(amount + 1, amount + 1); 26 | dp[0] = 0; 27 | 28 | std::sort(begin(coins), end(coins)); 29 | for (int i = 1; i < dp.size(); ++i) { 30 | for (const int coin : coins) { 31 | const int diff = i - coin; 32 | if (diff < 0) { 33 | break; 34 | } 35 | 36 | dp[i] = std::min(dp[i], 1 + dp[diff]); 37 | } 38 | } 39 | 40 | return dp[amount] != amount + 1 ? dp[amount] : -1; 41 | } 42 | }; 43 | 44 | int main(int argc, char** argv) 45 | { 46 | return EXIT_SUCCESS; 47 | } -------------------------------------------------------------------------------- /Algorithms/Easy/LongestContinuousIncreasingSubsequence.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an unsorted array of integers nums, return the length of the longest continuous increasing subsequence (i.e. subarray). The subsequence must be strictly increasing. 4 | // A continuous increasing subsequence is defined by two indices l and r (l < r) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < r, nums[i] < nums[i + 1]. 5 | 6 | // Example 1: 7 | // Input: nums = [1,3,5,4,7] 8 | // Output: 3 9 | // Explanation: The longest continuous increasing subsequence is [1,3,5] with length 3. 10 | // Even though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element 4. 11 | 12 | // Example 2: 13 | // Input: nums = [2,2,2,2,2] 14 | // Output: 1 15 | // Explanation: The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly 16 | // increasing. 17 | 18 | class Solution { 19 | public: 20 | int findLengthOfLCIS(const std::vector& nums) 21 | { 22 | int max_length = 0; 23 | int current_length = 0; 24 | for (int i = 1; i < nums.size(); ++i) { 25 | ++current_length; 26 | max_length = std::max(max_length, current_length); 27 | if (nums[i] <= nums[i - 1]) 28 | current_length = 0; 29 | } 30 | 31 | ++current_length; 32 | return std::max(max_length, current_length); 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Algorithms/Easy/BinaryTreePaths.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given the root of a binary tree, return all root-to-leaf paths in any order. 4 | // A leaf is a node with no children. 5 | 6 | // Example 1: 7 | // Input: root = [1,2,3,null,5] 8 | // Output: ["1->2->5","1->3"] 9 | 10 | // Example 2: 11 | // Input: root = [1] 12 | // Output: ["1"] 13 | 14 | class Solution 15 | { 16 | public: 17 | std::vector binaryTreePaths(TreeNode* root) 18 | { 19 | if (!root) { 20 | return std::vector{}; 21 | } 22 | 23 | std::vector result; 24 | std::function impl; 25 | impl = [&impl, result&] (TreeNode* node, std::string_view path) 26 | { 27 | if (!node->left && !node->right) { 28 | std::string new_path = path + std::to_string(node->val); 29 | result.push_back(std::move(new_path)); 30 | } else { 31 | std::string new_path = path + std::to_string(node->val) + "->"; 32 | if (node->left) { 33 | impl(node->left, new_path); 34 | } 35 | if (node->right) { 36 | impl(node->right, new_path); 37 | } 38 | } 39 | }; 40 | 41 | impl(root, ""); 42 | return result; 43 | } 44 | }; 45 | 46 | int main(int argc, char** argv) 47 | { 48 | return EXIT_SUCCESS; 49 | } 50 | -------------------------------------------------------------------------------- /Algorithms/Easy/ConstuctTheRectangle.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // A web developer needs to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements: 4 | 5 | // The area of the rectangular web page you designed must equal to the given target area. 6 | // The width W should not be larger than the length L, which means L >= W. 7 | // The difference between length L and width W should be as small as possible. 8 | // Return an array [L, W] where L and W are the length and width of the web page you designed in sequence. 9 | 10 | // Example 1: 11 | // Input: area = 4 12 | // Output: [2,2] 13 | // Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. 14 | // But according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2. 15 | 16 | // Example 2: 17 | // Input: area = 37 18 | // Output: [37,1] 19 | 20 | // Example 3: 21 | // Input: area = 122122 22 | // Output: [427,286] 23 | 24 | class Solution 25 | { 26 | public: 27 | std::vector constructRectangle(int area) 28 | { 29 | for (int w = (int)sqrt(area); w >= 1; --w) { 30 | if (area % w == 0) 31 | return std::vector{area / w, w}; 32 | } 33 | 34 | return std::vector{ -1, -1 }; 35 | } 36 | }; -------------------------------------------------------------------------------- /Algorithms/Medium/DailyTemperatures.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead. 4 | 5 | // Example 1: 6 | // Input: temperatures = [73,74,75,71,69,72,76,73] 7 | // Output: [1,1,4,2,1,1,0,0] 8 | 9 | // Example 2: 10 | // Input: temperatures = [30,40,50,60] 11 | // Output: [1,1,1,0] 12 | 13 | // Example 3: 14 | // Input: temperatures = [30,60,90] 15 | // Output: [1,1,0] 16 | 17 | class Solution 18 | { 19 | public: 20 | std::vector dailyTemperatures(std::vector& temperatures) 21 | { 22 | std::stack> stack;; 23 | std::vector result(temperatures.size()); 24 | for (int day = temperatures.size() - 1; day >= 0; --day) { 25 | const int current_temperature = temperatures[day]; 26 | while (!stack.empty() && stack.top().first <= current_temperature) 27 | stack.pop(); 28 | 29 | if (!stack.empty()) { 30 | const auto warmer_day = stack.top().second; 31 | result[day] = warmer_day - day; 32 | } else { 33 | result[day] = 0; 34 | } 35 | 36 | stack.emplace(current_temperature, day); 37 | } 38 | 39 | return result; 40 | } 41 | }; -------------------------------------------------------------------------------- /Algorithms/Medium/4Sum.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | class Solution 4 | { 5 | public: 6 | std::vector> fourSum(std::vector& nums, int target) 7 | { 8 | if (nums.size() < 4u) { 9 | return {}; 10 | } 11 | 12 | std::sort(begin(nums), end(nums)); 13 | std::vector> result; 14 | for (size_t i = 0u; i < nums.size() - 3; ++i) { 15 | if (i > 0 && nums[i] == nums[i - 1]) { 16 | continue; 17 | } 18 | 19 | for (size_t j = i + 1; j < nums.size() - 2; ++j) { 20 | if (j > i + 1 && nums[j] == nums[j - 1]) { 21 | continue; 22 | } 23 | 24 | size_t left = j + 1; 25 | size_t right = nums.size() - 1u; 26 | const long long temp_sum = nums[i] + nums[j]; 27 | while (left < right) { 28 | const long long sum = temp_sum + nums[left] + nums[right]; 29 | if (sum > target) { 30 | --right; 31 | } else if (sum < target) { 32 | ++left; 33 | } else { 34 | result.push_back({ nums[i], nums[j], nums[left], nums[right] }); 35 | ++left; 36 | --right; 37 | while (left < right && nums[left] == nums[left - 1]) { 38 | ++left; 39 | } 40 | } 41 | } 42 | } 43 | } 44 | 45 | return result; 46 | } 47 | }; 48 | 49 | int main(int argc, char** argv) 50 | { 51 | return EXIT_SUCCESS; 52 | } -------------------------------------------------------------------------------- /Algorithms/Medium/PermutationInString.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise. 4 | // In other words, return true if one of s1's permutations is the substring of s2. 5 | 6 | // Example 1: 7 | // Input: s1 = "ab", s2 = "eidbaooo" 8 | // Output: true 9 | // Explanation: s2 contains one permutation of s1 ("ba"). 10 | 11 | // Example 2: 12 | // Input: s1 = "ab", s2 = "eidboaoo" 13 | // Output: false 14 | 15 | class Solution 16 | { 17 | public: 18 | bool checkInclusion(const std::string& s1, const std::string& s2) 19 | { 20 | const size_t s1_length = s1.length(); 21 | const size_t s2_length = s2.length(); 22 | 23 | if (s1_length > s2_length) { 24 | return false; 25 | } 26 | 27 | std::array s1_lookup{ 0 }; 28 | std::array s2_lookup{ 0 }; 29 | for (size_t i = 0u; i < s1_length; ++i) { 30 | ++s1_lookup[s1[i] - 'a']; 31 | ++s2_lookup[s2[i] - 'a']; 32 | } 33 | 34 | for (size_t i = 0u; i < s2_length - s1_length; ++i) { 35 | if (s1_lookup == s2_lookup) { 36 | return true; 37 | } 38 | 39 | ++s2_lookup[s2[i + s1_length] - 'a']; 40 | --s2_lookup[s2[i] - 'a']; 41 | } 42 | 43 | return s1_lookup == s2_lookup; 44 | } 45 | }; 46 | 47 | int main(int argc, char** argv) 48 | { 49 | return EXIT_SUCCESS; 50 | } 51 | -------------------------------------------------------------------------------- /Algorithms/Easy/AverageOfLevelsInBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted. 4 | 5 | // Example 1: 6 | // Input: root = [3,9,20,null,null,15,7] 7 | // Output: [3.00000,14.50000,11.00000] 8 | // Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. 9 | // Hence return [3, 14.5, 11]. 10 | 11 | // Example 2: 12 | // Input: root = [3,9,20,15,7] 13 | // Output: [3.00000,14.50000,11.00000] 14 | 15 | class Solution 16 | { 17 | public: 18 | std::vector averageOfLevels(TreeNode* root) 19 | { 20 | if (!root) 21 | return std::vector{}; 22 | 23 | std::vector levels; 24 | std::queue queue; 25 | queue.push(root); 26 | 27 | while (!queue.empty()) { 28 | double level_sum = 0; 29 | const int size = queue.size(); 30 | for (int i = 0; i < size; ++i) { 31 | TreeNode* node = queue.front(); 32 | queue.pop(); 33 | 34 | level_sum += node->val; 35 | if (node->left) 36 | queue.push(node->left); 37 | if (node->right) 38 | queue.push(node->right); 39 | } 40 | 41 | levels.push_back(level_sum / size); 42 | } 43 | 44 | return levels; 45 | } 46 | }; -------------------------------------------------------------------------------- /Algorithms/Medium/LargestNumber.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a list of non-negative integers nums, arrange them such that they form the largest number and return it. 4 | // Since the result may be very large, so you need to return a string instead of an integer. 5 | 6 | // Example 1: 7 | // Input: nums = [10,2] 8 | // Output: "210" 9 | 10 | // Example 2: 11 | // Input: nums = [3,30,34,5,9] 12 | // Output: "9534330" 13 | 14 | class Solution 15 | { 16 | public: 17 | std::string largestNumber(const std::vector& nums) 18 | { 19 | std::vector str_nums(nums.size()); 20 | for (size_t i = 0u; i < nums.size(); ++i) { 21 | str_nums[i] = std::to_string(nums[i]); 22 | } 23 | 24 | auto compare = [] (const std::string& lhs, const std::string& rhs) 25 | { 26 | return lhs + rhs > rhs + lhs; 27 | }; 28 | 29 | std::sort(begin(str_nums), end(str_nums), compare); 30 | 31 | std::string result; 32 | for (auto&& str_num: str_nums) { 33 | result += std::move(str_num); 34 | } 35 | 36 | size_t begin = 0u; 37 | const size_t end = result.size() - 1u; 38 | while (begin < end && result[begin] == '0') { 39 | ++begin; 40 | } 41 | 42 | return std::string(result.begin() + begin, result.end()); 43 | } 44 | }; 45 | 46 | int main(int argc, char** argv) 47 | { 48 | return EXIT_SUCCESS; 49 | } 50 | -------------------------------------------------------------------------------- /Algorithms/Medium/MergeIntervals.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. 4 | 5 | // Example 1: 6 | // Input: intervals = [[1,3],[2,6],[8,10],[15,18]] 7 | // Output: [[1,6],[8,10],[15,18]] 8 | // Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6]. 9 | 10 | // Example 2: 11 | // Input: intervals = [[1,4],[4,5]] 12 | // Output: [[1,5]] 13 | // Explanation: Intervals [1,4] and [4,5] are considered overlapping. 14 | 15 | class Solution 16 | { 17 | public: 18 | std::vector> merge(std::vector>& intervals) 19 | { 20 | if (intervals.size() == 1u) 21 | return intervals; 22 | 23 | std::sort(begin(intervals), end(intervals)); 24 | std::vector> result; 25 | result.push_back(intervals[0]); 26 | 27 | for (size_t i = 1u; i < intervals.size(); ++i) { 28 | auto& next = intervals[i]; 29 | auto& current = result[result.size() - 1u]; 30 | if (next[0] <= current[1]) { 31 | current[1] = std::max(next[1], current[1]); 32 | } else { 33 | result.push_back(next); 34 | } 35 | } 36 | 37 | return result; 38 | } 39 | }; 40 | 41 | int main(int argc, char** argv) 42 | { 43 | return EXIT_SUCCESS; 44 | } -------------------------------------------------------------------------------- /Algorithms/Easy/FirstBadVersion.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. 4 | // Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. 5 | // You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. 6 | 7 | // Example 1: 8 | // Input: n = 5, bad = 4 9 | // Output: 4 10 | // Explanation: 11 | // call isBadVersion(3) -> false 12 | // call isBadVersion(5) -> true 13 | // call isBadVersion(4) -> true 14 | //Then 4 is the first bad version. 15 | 16 | // Example 2: 17 | // Input: n = 1, bad = 1 18 | // Output: 1 19 | 20 | class Solution 21 | { 22 | public: 23 | int firstBadVersion(int n) 24 | { 25 | int left = 0; 26 | int right = n; 27 | while (left < right) { 28 | const int middle = left + (right - left) / 2; 29 | if (!isBadVersion(middle)) { 30 | left = middle + 1; 31 | } else { 32 | right = middle; 33 | } 34 | } 35 | 36 | return left; 37 | } 38 | }; 39 | 40 | int main(int argc, char** argv) 41 | { 42 | return EXIT_SUCCESS; 43 | } 44 | -------------------------------------------------------------------------------- /Algorithms/Easy/FizzBuzz.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer n, return a string array answer (1-indexed) where: 4 | // answer[i] == "FizzBuzz" if i is divisible by 3 and 5. 5 | // answer[i] == "Fizz" if i is divisible by 3. 6 | // answer[i] == "Buzz" if i is divisible by 5. 7 | // answer[i] == i (as a string) if none of the above conditions are true. 8 | 9 | // Example 1: 10 | // Input: n = 3 11 | // Output: ["1","2","Fizz"] 12 | 13 | // Example 2: 14 | // Input: n = 5 15 | // Output: ["1","2","Fizz","4","Buzz"] 16 | 17 | // Example 3: 18 | // Input: n = 15 19 | // Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"] 20 | 21 | class Solution 22 | { 23 | public: 24 | std::vector fizzBuzz(int number) 25 | { 26 | std::vector result; 27 | for (size_t i = 1u; i <= number; ++i) { 28 | const bool divisible_by_3 = i % 3 == 0; 29 | const bool divisible_by_5 = i % 5 == 0; 30 | if (divisible_by_3 && divisible_by_5) { 31 | result.push_back("FizzBuzz"); 32 | } else if (divisible_by_5) { 33 | result.push_back("Buzz"); 34 | } else if (divisible_by_3) { 35 | result.push_back("Fizz"); 36 | } else { 37 | result.push_back(to_string(i)); 38 | } 39 | } 40 | 41 | return result; 42 | } 43 | }; 44 | 45 | 46 | int main(int argc, char** argv) 47 | { 48 | return EXIT_SUCCESS; 49 | } -------------------------------------------------------------------------------- /Algorithms/Medium/LongestSubarrayOf1sAfterDeletingOneElement.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given a binary array nums, you should delete one element from it. 4 | // Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray. 5 | 6 | // Example 1: 7 | // Input: nums = [1,1,0,1] 8 | // Output: 3 9 | // Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's. 10 | 11 | // Example 2: 12 | // Input: nums = [0,1,1,1,0,1,1,0,1] 13 | // Output: 5 14 | // Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1]. 15 | 16 | // Example 3: 17 | // Input: nums = [1,1,1] 18 | // Output: 2 19 | // Explanation: You must delete one element. 20 | 21 | class Solution 22 | { 23 | public: 24 | int longestSubarray(std::vector& nums) 25 | { 26 | if (nums.size() < 2) 27 | return 0; 28 | 29 | int longest_length = 0; 30 | 31 | int left = 0; 32 | int right = 0; 33 | int zeroes_number = 0; 34 | while (right < nums.size()) { 35 | zeroes_number += (nums[right] == 0); 36 | 37 | while (zeroes_number > 1) { 38 | zeroes_number -= (nums[left] == 0); 39 | ++left; 40 | } 41 | 42 | longest_length = std::max(longest_length, right - left + 1); 43 | ++right; 44 | } 45 | 46 | return longest_length - 1; 47 | } 48 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/HappyNumber.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Write an algorithm to determine if a number n is happy. 4 | 5 | // A happy number is a number defined by the following process: 6 | // Starting with any positive integer, replace the number by the sum of the squares of its digits. 7 | // Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. 8 | // Those numbers for which this process ends in 1 are happy. 9 | // Return true if n is a happy number, and false if not. 10 | 11 | // Example 1: 12 | // Input: n = 19 13 | // Output: true 14 | // Explanation: 15 | // 12 + 92 = 82 16 | // 82 + 22 = 68 17 | // 62 + 82 = 100 18 | // 12 + 02 + 02 = 1 19 | 20 | // Example 2: 21 | // Input: n = 2 22 | // Output: false 23 | 24 | class Solution 25 | { 26 | public: 27 | int sumOfSquares(int n) 28 | { 29 | int sum = 0; 30 | while (n != 0) { 31 | const int digit = n % 10; 32 | sum += digit * digit; 33 | n /= 10; 34 | } 35 | 36 | return sum; 37 | } 38 | 39 | bool isHappy(int n) 40 | { 41 | std::unordered_set visited_numbers; 42 | while (visited_numbers.count(n) == 0) { 43 | visited_numbers.insert(n); 44 | n = sumOfSquares(n); 45 | 46 | if (n == 1) 47 | return true; 48 | } 49 | 50 | return false; 51 | } 52 | }; 53 | 54 | int main(int argc, char** argv) 55 | { 56 | return EXIT_SUCCESS; 57 | } 58 | -------------------------------------------------------------------------------- /Algorithms/Medium/BinaryTreeLevelOrderTraversal.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level). 4 | 5 | // Example 1: 6 | // Input: root = [3,9,20,null,null,15,7] 7 | // Output: [[3],[9,20],[15,7]] 8 | 9 | // Example 2: 10 | // Input: root = [1] 11 | // Output: [[1]] 12 | 13 | // Example 3: 14 | // Input: root = [] 15 | // Output: [] 16 | 17 | class Solution 18 | { 19 | public: 20 | std::vector> levelOrder(TreeNode* root) 21 | { 22 | std::vector> result; 23 | if (!root) { 24 | return result; 25 | } 26 | 27 | std::queue queue; 28 | queue.push(root); 29 | while (!queue.empty()) { 30 | const size_t queue_size = queue.size(); 31 | std::vector row(queue_size); 32 | for (size_t i = 0u; i < queue_size; ++i) { 33 | TreeNode* node = queue.front(); 34 | row[i] = node->val; 35 | queue.pop(); 36 | 37 | if (node->left) { 38 | queue.push(node->left); 39 | } 40 | if (node->right) { 41 | queue.push(node->right); 42 | } 43 | } 44 | result.push_back(std::move(row)); 45 | } 46 | 47 | return result; 48 | } 49 | }; 50 | 51 | int main(int argc, char** argv) 52 | { 53 | return EXIT_SUCCESS; 54 | } 55 | -------------------------------------------------------------------------------- /Algorithms/Easy/ConvertSortedArrayToBinarySearchTree.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree. 4 | // A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one. 5 | 6 | // Example 1: 7 | // Input: nums = [-10,-3,0,5,9] 8 | // Output: [0,-3,9,-10,null,5] 9 | // Explanation: [0,-10,5,null,-3,null,9] is also accepted: 10 | 11 | // Example 2: 12 | // Input: nums = [1,3] 13 | // Output: [3,1] 14 | // Explanation: [1,3] and [3,1] are both a height-balanced BSTs. 15 | 16 | class Solution 17 | { 18 | public: 19 | TreeNode* sortedArrayToBST(std::vector& nums) 20 | { 21 | if (nums.empty()) { 22 | return nullptr; 23 | } 24 | 25 | std::function impl; 26 | impl = [&nums, &impl](int left, int right) -> TreeNode* 27 | { 28 | if (left > right) { 29 | return nullptr; 30 | } 31 | 32 | TreeNode* node = new TreeNode; 33 | const int middle = left + (right - left) / 2; 34 | node->val = nums[middle]; 35 | node->left = impl(left, middle - 1); 36 | node->right = impl(middle + 1, right); 37 | return node; 38 | }; 39 | 40 | return impl(0, nums.size() - 1); 41 | } 42 | }; 43 | 44 | int main(int argc, char** argv) 45 | { 46 | return EXIT_SUCCESS; 47 | } 48 | -------------------------------------------------------------------------------- /Algorithms/Easy/IsomorphicString.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given two strings s and t, determine if they are isomorphic. 4 | // Two strings s and t are isomorphic if the characters in s can be replaced to get t. 5 | // All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. 6 | 7 | // Example 1: 8 | // Input: s = "egg", t = "add" 9 | // Output: true 10 | 11 | // Example 2: 12 | // Input: s = "foo", t = "bar" 13 | // Output: false 14 | 15 | // Example 3: 16 | // Input: s = "paper", t = "title" 17 | // Output: true 18 | 19 | class Solution 20 | { 21 | public: 22 | bool isIsomorphic(const std::string& s, const std::string& t) 23 | { 24 | if (s.empty() && t.empty()) { 25 | return true; 26 | } 27 | 28 | if (s.size() != t.size()) { 29 | return false; 30 | } 31 | 32 | std::unordered_map st; 33 | std::unordered_map ts; 34 | for (size_t i = 0u; i < s.size(); ++i) { 35 | const char sc = s[i]; 36 | const char tc = t[i]; 37 | 38 | if ((st.count(sc) && st[sc] != tc) || (ts.count(tc) && ts[tc] != sc)) { 39 | return false; 40 | } 41 | 42 | st[sc] = tc; 43 | ts[tc] = sc; 44 | } 45 | 46 | return true; 47 | } 48 | }; 49 | 50 | int main(int argc, char** argv) 51 | { 52 | return EXIT_SUCCESS; 53 | } 54 | -------------------------------------------------------------------------------- /Algorithms/Medium/BinaryTreeRightSightView.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. 4 | 5 | // Example 1: 6 | // Input: root = [1,2,3,null,5,null,4] 7 | // Output: [1,3,4] 8 | 9 | // Example 2: 10 | // Input: root = [1,null,3] 11 | // Output: [1,3] 12 | 13 | // Example 3: 14 | // Input: root = [] 15 | // Output: [] 16 | 17 | class Solution 18 | { 19 | public: 20 | std::vector rightSideView(TreeNode* root) 21 | { 22 | if (!root) { 23 | return std::vector{}; 24 | } 25 | 26 | std::vector result; 27 | std::queue queue; 28 | queue.push(root); 29 | 30 | while (!queue.empty()) { 31 | const size_t size = queue.size(); 32 | for (size_t i = 0u; i < size; ++i) { 33 | TreeNode* node = queue.front(); 34 | queue.pop(); 35 | 36 | if (i == size - 1u) { 37 | result.push_back(node->val); 38 | } 39 | 40 | if (node->left) { 41 | queue.push(node->left); 42 | } 43 | if (node->right) { 44 | queue.push(node->right); 45 | } 46 | } 47 | } 48 | 49 | return result; 50 | } 51 | }; 52 | 53 | int main(int argc, char** argv) 54 | { 55 | return EXIT_SUCCESS; 56 | } 57 | -------------------------------------------------------------------------------- /Algorithms/Easy/MinimumAbsoluteDifference.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements. 4 | // Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows 5 | 6 | // a, b are from arr 7 | // a < b 8 | // b - a equals to the minimum absolute difference of any two elements in arr 9 | 10 | // Example 1: 11 | // Input: arr = [4,2,1,3] 12 | // Output: [[1,2],[2,3],[3,4]] 13 | // Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order. 14 | 15 | // Example 2: 16 | // Input: arr = [1,3,6,10,15] 17 | // Output: [[1,3]] 18 | 19 | // Example 3: 20 | // Input: arr = [3,8,-10,23,19,-4,-14,27] 21 | // Output: [[-14,-10],[19,23],[23,27]] 22 | 23 | class Solution 24 | { 25 | public: 26 | vector> minimumAbsDifference(vector& arr) { 27 | sort(begin(arr), end(arr)); 28 | int min_difference = std::numeric_limits::max(); 29 | for (size_t i = 1; i < arr.size(); ++i) { 30 | min_difference = std::min(arr[i] - arr[i - 1], min_difference); 31 | } 32 | 33 | vector> result; 34 | for (size_t i = 1; i < arr.size(); ++i) { 35 | if (arr[i] - arr[i - 1] == min_difference) { 36 | result.push_back({ arr[i - 1], arr[i] }); 37 | } 38 | } 39 | return result; 40 | } 41 | }; 42 | 43 | int main(int argc, char** argv) 44 | { 45 | return EXIT_SUCCESS; 46 | } -------------------------------------------------------------------------------- /Algorithms/Easy/PalindromeLinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given the head of a singly linked list, return true if it is a palindrome. 4 | 5 | // Example 1: 6 | // Input: head = [1,2,2,1] 7 | // Output: true 8 | 9 | // Example 2: 10 | // Input: head = [1,2] 11 | // Output: false 12 | 13 | class Solution 14 | { 15 | public: 16 | bool isPalindrome(ListNode* head) 17 | { 18 | if ((!head) || (!head->next)) { 19 | return true; 20 | } 21 | 22 | ListNode* slow = head; 23 | ListNode* fast = head; 24 | while ((fast->next) && (fast->next->next)) { 25 | fast = fast->next->next; 26 | slow = slow->next; 27 | } 28 | 29 | if (fast->next) { 30 | fast = fast->next; 31 | } 32 | 33 | ListNode* reversed = nullptr; 34 | ListNode* reversed_slow = slow->next; 35 | while (reversed_slow) { 36 | ListNode* temp = reversed_slow->next; 37 | reversed_slow->next = reversed; 38 | reversed = reversed_slow; 39 | reversed_slow = temp; 40 | } 41 | 42 | ListNode* l1 = head; 43 | ListNode* l2 = reversed; 44 | while (l1 && l2) { 45 | if (l1->val != l2->val) { 46 | return false; 47 | } 48 | 49 | l1 = l1->next; 50 | l2 = l2->next; 51 | } 52 | 53 | return true; 54 | } 55 | }; 56 | 57 | int main(int argc, char** argv) 58 | { 59 | return EIXT_SUCCESS; 60 | } 61 | -------------------------------------------------------------------------------- /Algorithms/Easy/IntersectionOfTwoArrays.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order. 4 | 5 | // Example 1: 6 | // Input: nums1 = [1,2,2,1], nums2 = [2,2] 7 | // Output: [2] 8 | 9 | // Example 2: 10 | // Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 11 | // Output: [9,4] 12 | // Explanation: [4,9] is also accepted. 13 | 14 | class Solution 15 | { 16 | public: 17 | std::vector intersection(std::vector nums1, std::vector nums2) 18 | { 19 | std::sort(begin(nums1), end(nums1)); 20 | std::sort(begin(nums2), end(nums2)); 21 | 22 | int left = 0; 23 | int right = 0; 24 | std::vector result; 25 | while (left < nums1.size() && right < nums2.size()) { 26 | if (nums1[left] < nums2[right]) { 27 | ++left; 28 | } else if (nums1[left] > nums2[right]) { 29 | ++right; 30 | } else { 31 | result.push_back(nums1[left]); 32 | ++left; 33 | ++right; 34 | 35 | while (left < nums1.size() && 36 | right < nums2.size() && 37 | nums1[left - 1] == nums1[left] && 38 | nums2[right - 1] == nums2[right]) { 39 | ++left; 40 | ++right; 41 | } 42 | } 43 | } 44 | 45 | return result; 46 | } 47 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/GuessNumberHigherOrLow.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // We are playing the Guess Game. The game is as follows: 4 | // I pick a number from 1 to n. You have to guess which number I picked. 5 | // Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. 6 | // You call a pre-defined API int guess(int num), which returns three possible results: 7 | 8 | // -1: Your guess is higher than the number I picked (i.e. num > pick). 9 | // 1: Your guess is lower than the number I picked (i.e. num < pick). 10 | // 0: your guess is equal to the number I picked (i.e. num == pick). 11 | // Return the number that I picked. 12 | 13 | // Example 1: 14 | // Input: n = 10, pick = 6 15 | // Output: 6 16 | 17 | // Example 2: 18 | // Input: n = 1, pick = 1 19 | // Output: 1 20 | 21 | // Example 3: 22 | // Input: n = 2, pick = 1 23 | // Output: 1 24 | 25 | class Solution 26 | { 27 | public: 28 | int guessNumber(int n) 29 | { 30 | int left = 1; 31 | int right = n; 32 | 33 | while (left <= right) { 34 | const int middle = left + (right - left) / 2; 35 | const int result = guess(middle); 36 | if (result == 1) { 37 | left = middle + 1; 38 | } else if (result == -1) { 39 | right = middle - 1; 40 | } else { 41 | return middle; 42 | } 43 | } 44 | 45 | return 0; 46 | } 47 | }; 48 | 49 | int main(int argc, char** argv) 50 | { 51 | return EXIT_SUCCESS; 52 | } 53 | -------------------------------------------------------------------------------- /Algorithms/Easy/MinCostClimbingStairs.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps. 4 | // You can either start from the step with index 0, or the step with index 1. 5 | // Return the minimum cost to reach the top of the floor. 6 | 7 | // Example 1: 8 | // Input: cost = [10,15,20] 9 | // Output: 15 10 | // Explanation: You will start at index 1. 11 | // - Pay 15 and climb two steps to reach the top. 12 | // The total cost is 15. 13 | 14 | // Example 2: 15 | // Input: cost = [1,100,1,1,1,100,1,1,100,1] 16 | // Output: 6 17 | // Explanation: You will start at index 0. 18 | // - Pay 1 and climb two steps to reach index 2. 19 | // - Pay 1 and climb two steps to reach index 4. 20 | // - Pay 1 and climb two steps to reach index 6. 21 | // - Pay 1 and climb one step to reach index 7. 22 | // - Pay 1 and climb two steps to reach index 9. 23 | // - Pay 1 and climb one step to reach the top. 24 | // The total cost is 6. 25 | 26 | class Solution 27 | { 28 | public: 29 | int minCostClimbingStairs(vector& cost) 30 | { 31 | int step1 = 0; 32 | int step2 = cost[0]; 33 | for (size_t i = 2u; i <= cost.size(); ++i) { 34 | const int current_step = cost[i - 1] + std::min(step1, step2); 35 | step1 = step2; 36 | step2 = current_step; 37 | } 38 | return std::min(step1, step2); 39 | } 40 | }; 41 | 42 | int main(int argc, char** argv) 43 | { 44 | return EXIT_SUCCESS; 45 | } -------------------------------------------------------------------------------- /Algorithms/Easy/ReverseLinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given the head of a singly linked list, reverse the list, and return the reversed list. 4 | 5 | // Example 1: 6 | // Input: head = [1,2,3,4,5] 7 | // Output: [5,4,3,2,1] 8 | 9 | // Example 2: 10 | // Input: head = [1,2] 11 | // Output: [2,1] 12 | 13 | // Example 3: 14 | // Input: head = [] 15 | // Output: [] 16 | 17 | class Solution 18 | { 19 | public: 20 | ListNode* reverseList(ListNode* head) 21 | { 22 | if (!head) { 23 | return nullptr; 24 | } 25 | 26 | ListNode* reversed = nullptr; 27 | while (head) { 28 | ListNode* temp = head->next; 29 | head->next = reversed; 30 | reversed = head; 31 | head = temp; 32 | } 33 | 34 | return reversed; 35 | } 36 | }; 37 | 38 | int main(int argc, char** argv) 39 | { 40 | Solution solution; 41 | { 42 | ListNode* list = details::make_list({ 5 }); 43 | ASSERT_EQUALS(solution.reverseList(list), details::make_list({ 5 })); 44 | details::delete_list(list); 45 | } 46 | { 47 | ListNode* list = details::make_list({ 5, 3 } ); 48 | ASSERT_EQUALS(solution.reverseList(list), details::make_list({ 3, 5 })); 49 | details::delete_list(list); 50 | } 51 | { 52 | ListNode* list = details::make_list({ 5, 3, 1 } ); 53 | ASSERT_EQUALS(solution.reverseList(list), details::make_list({ 1, 3, 5 })); 54 | details::delete_list(list); 55 | } 56 | return EXIT_SUCCESS; 57 | } 58 | 59 | -------------------------------------------------------------------------------- /Algorithms/Medium/PartitionLabels.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part. 4 | // Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s. 5 | // Return a list of integers representing the size of these parts. 6 | 7 | // Example 1: 8 | // Input: s = "ababcbacadefegdehijhklij" 9 | // Output: [9,7,8] 10 | // Explanation: 11 | // The partition is "ababcbaca", "defegde", "hijhklij". 12 | // This is a partition so that each letter appears in at most one part. 13 | // A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts. 14 | 15 | // Example 2: 16 | // Input: s = "eccbbbbdec" 17 | // Output: [10] 18 | 19 | class Solution 20 | { 21 | public: 22 | std::vector partitionLabels(std::string text) 23 | { 24 | std::unordered_map last_positions; 25 | for (int i = 0; i < text.size(); ++i) 26 | last_positions[text[i]] = i; 27 | 28 | int end_idx = 0; 29 | int start_idx = 0; 30 | std::vector result; 31 | for (int i = 0; i < text.size(); ++i) { 32 | const int last_idx = last_positions[text[i]]; 33 | end_idx = std::max(end_idx, last_idx); 34 | 35 | if (end_idx == i) { 36 | result.push_back(end_idx - start_idx + 1); 37 | start_idx = i + 1; 38 | } 39 | } 40 | 41 | return result; 42 | } 43 | }; -------------------------------------------------------------------------------- /Algorithms/Medium/ContainerWithMostWater.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). 4 | // Find two lines that together with the x-axis form a container, such that the container contains the most water. 5 | // Return the maximum amount of water a container can store. 6 | // Notice that you may not slant the container. 7 | 8 | // Example 1: 9 | // Input: height = [1,8,6,2,5,4,8,3,7] 10 | // Output: 49 11 | // Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. 12 | 13 | // Example 2: 14 | // Input: height = [1,1] 15 | // Output: 1 16 | 17 | class Solution 18 | { 19 | public: 20 | int maxArea(const std::vector& height) 21 | { 22 | size_t left = 0u; 23 | size_t right = height.size() - 1u; 24 | 25 | int max_area = 0; 26 | while (left < right) { 27 | const int left_height = height[left]; 28 | const int right_height = height[right]; 29 | const int local_max_area = std::min(left_height, right_height) * (right - left); 30 | max_area = std::max(max_area, local_max_area); 31 | 32 | if (left_height <= right_height) { 33 | ++left; 34 | } else { 35 | --right; 36 | } 37 | } 38 | 39 | return max_area; 40 | } 41 | }; 42 | 43 | int main(int argc, char** argv) 44 | { 45 | return EXIT_SUCCESS; 46 | } 47 | -------------------------------------------------------------------------------- /Concurrency/Easy/PrintInOrder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | class Foo 7 | { 8 | public: 9 | void first(std::function printFirst) 10 | { 11 | printFirst(); 12 | ++m_print_state; 13 | m_notifier.notify_all(); 14 | } 15 | 16 | void second(std::function printSecond) 17 | { 18 | std::unique_lock lock(m_mutex); 19 | m_notifier.wait(lock, [this]{ return m_print_state > 0; }); 20 | printSecond(); 21 | ++m_print_state; 22 | m_notifier.notify_one(); 23 | } 24 | 25 | void third(std::function printThird) 26 | { 27 | std::unique_lock lock(m_mutex); 28 | m_notifier.wait(lock, [this]{ return m_print_state > 1; }); 29 | printThird(); 30 | } 31 | private: 32 | std::mutex m_mutex; 33 | std::atomic_int m_print_state = 0; 34 | std::condition_variable m_notifier; 35 | }; 36 | 37 | int main(int argc, char** argv) 38 | { 39 | const auto print_first = [] { std::cout << "first" << std::endl; }; 40 | const auto print_second = [] { std::cout << "second" << std::endl; }; 41 | const auto print_third = [] { std::cout << "third" << std::endl; }; 42 | 43 | Foo foo; 44 | std::thread thread3(&Foo::third, &foo, print_third); 45 | std::thread thread2(&Foo::second, &foo, print_second); 46 | std::thread thread1(&Foo::first, &foo, print_first); 47 | thread1.join(); 48 | thread2.join(); 49 | thread3.join(); 50 | 51 | return EXIT_SUCCESS; 52 | } -------------------------------------------------------------------------------- /Algorithms/Medium/UniquePaths.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. 4 | // Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner. 5 | // The test cases are generated so that the answer will be less than or equal to 2 * 109. 6 | 7 | // Example 1: 8 | // Input: m = 3, n = 7 9 | // Output: 28 10 | 11 | // Example 2: 12 | // Input: m = 3, n = 2 13 | // Output: 3 14 | // Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 15 | // 1. Right -> Down -> Down 16 | // 2. Down -> Down -> Right 17 | // 3. Down -> Right -> Down 18 | 19 | class Solution 20 | { 21 | public: 22 | int uniquePaths(int m, int n) 23 | { 24 | if (m == 1 && n == 1) { 25 | return 1; 26 | } 27 | 28 | std::vector> matrix(m, std::vector(n, 0)); 29 | for (int i = 0; i < m; ++i) { 30 | for (int j = 0; j < n; ++j) { 31 | if (i == 0 && j == 0) { 32 | continue; 33 | } else if (i == 0 || j == 0) { 34 | matrix[i][j] = 1; 35 | } else { 36 | matrix[i][j] = matrix[i - 1][j] + matrix[i][j - 1] 37 | } 38 | } 39 | } 40 | 41 | return matrix[m - 1][n - 1]; 42 | } 43 | }; 44 | 45 | int main(int argc, char** argv) 46 | { 47 | return EXIT_SUCCESS; 48 | } -------------------------------------------------------------------------------- /Algorithms/Easy/GoalParserInterpretation.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // You own a Goal Parser that can interpret a string command. The command consists of an alphabet of "G", "()" and/or "(al)" in some order. The Goal Parser will interpret "G" as the string "G", "()" as the string "o", and "(al)" as the string "al". The interpreted strings are then concatenated in the original order. 4 | // Given the string command, return the Goal Parser's interpretation of command. 5 | 6 | // Example 1: 7 | // Input: command = "G()(al)" 8 | // Output: "Goal" 9 | // Explanation: The Goal Parser interprets the command as follows: 10 | // G -> G 11 | // () -> o 12 | // (al) -> al 13 | // The final concatenated result is "Goal". 14 | 15 | // Example 2: 16 | // Input: command = "G()()()()(al)" 17 | // Output: "Gooooal" 18 | 19 | // Example 3: 20 | // Input: command = "(al)G(al)()()G" 21 | // Output: "alGalooG" 22 | 23 | class Solution 24 | { 25 | public: 26 | std::string interpret(const std::string& command) 27 | { 28 | std::string result; 29 | for (size_t i = 0u; i < command.size();) { 30 | if (command[i] == 'G') { 31 | result += 'G'; 32 | ++i; 33 | } else if ((i < command.size() - 1u) && (command[i] == '(' && command[i + 1] == ')')) { 34 | result += 'o'; 35 | i += 2; 36 | } else { 37 | result += "al"; 38 | i += 4; 39 | } 40 | } 41 | 42 | return result; 43 | } 44 | }; 45 | 46 | int main(int argc, char** argv) 47 | { 48 | return EXIT_SUCCESS; 49 | } 50 | -------------------------------------------------------------------------------- /Algorithms/Medium/KthLargestElementInArray.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an integer array nums and an integer k, return the kth largest element in the array. 4 | // Note that it is the kth largest element in the sorted order, not the kth distinct element. 5 | // You must solve it in O(n) time complexity. 6 | 7 | // Example 1: 8 | // Input: nums = [3,2,1,5,6,4], k = 2 9 | // Output: 5 10 | 11 | // Example 2: 12 | // Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 13 | // Output: 4 14 | 15 | class Solution 16 | { 17 | public: 18 | int quickSelectImpl(std::vector& nums, int l, int r, int k) 19 | { 20 | int left_idx = l; 21 | int right_idx = r; 22 | int pivot_idx = left_idx++; 23 | int pivot = nums[pivot_idx]; 24 | 25 | while (left_idx <= right_idx) { 26 | while (left_idx <= right_idx && nums[left_idx] >= pivot) 27 | ++left_idx; 28 | while (left_idx <= right_idx && nums[right_idx] < pivot) 29 | --right_idx; 30 | 31 | if (left_idx <= right_idx) 32 | std::swap(nums[left_idx], nums[right_idx]); 33 | } 34 | 35 | std::swap(nums[right_idx], nums[pivot_idx]); 36 | 37 | if (right_idx > k) 38 | return quickSelectImpl(nums, l, right_idx - 1, k); 39 | else if (right_idx < k) 40 | return quickSelectImpl(nums, right_idx + 1, r, k); 41 | else 42 | return nums[right_idx]; 43 | } 44 | 45 | int findKthLargest(std::vector& nums, int k) 46 | { 47 | return quickSelectImpl(nums, 0, nums.size() - 1, k - 1); 48 | } 49 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/DistributeCandies.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Alice has n candies, where the ith candy is of type candyType[i]. Alice noticed that she started to gain weight, so she visited a doctor. 4 | // The doctor advised Alice to only eat n / 2 of the candies she has (n is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice. 5 | // Given the integer array candyType of length n, return the maximum number of different types of candies she can eat if she only eats n / 2 of them. 6 | 7 | // Example 1: 8 | // Input: candyType = [1,1,2,2,3,3] 9 | // Output: 3 10 | // Explanation: Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type. 11 | 12 | // Example 2: 13 | // Input: candyType = [1,1,2,3] 14 | // Output: 2 15 | // Explanation: Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types. 16 | 17 | // Example 3: 18 | // Input: candyType = [6,6,6,6] 19 | // Output: 1 20 | // Explanation: Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type. 21 | 22 | class Solution 23 | { 24 | public: 25 | int distributeCandies(std::vector& candy_types) 26 | { 27 | std::unordered_set lookup; 28 | for (const int type: candy_types) 29 | lookup.insert(type); 30 | 31 | const int types_number = lookup.size(); 32 | const int candies_number = candy_types.size(); 33 | return std::min(candies_number / 2, types_number); 34 | } 35 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/ToeplitzMatrix.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false. 4 | // A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements. 5 | 6 | // Example 1: 7 | // Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]] 8 | // Output: true 9 | // Explanation: 10 | // In the above grid, the diagonals are: 11 | // "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]". 12 | // In each diagonal all elements are the same, so the answer is True. 13 | 14 | // Example 2: 15 | // Input: matrix = [[1,2],[2,2]] 16 | // Output: false 17 | // Explanation: 18 | // The diagonal "[1, 2]" has different elements. 19 | 20 | class Solution 21 | { 22 | public: 23 | bool isToeplitzMatrix(std::vector>& matrix) 24 | { 25 | const int rows_size = matrix.size(); 26 | const int cols_size = matrix[0].size(); 27 | for (int row = 0; row < rows_size; ++row) { 28 | for (int col = 0; col < cols_size; ++col) { 29 | if (row == 0 || col == 0) { 30 | const int value = matrix[row][col]; 31 | int r = row + 1; 32 | int c = col + 1; 33 | while (r < rows_size && c < cols_size) { 34 | if (matrix[r][c] != matrix[r - 1][c - 1]) 35 | return false; 36 | 37 | ++r; 38 | ++c; 39 | } 40 | } 41 | } 42 | } 43 | 44 | return true; 45 | } 46 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/FlippingAnImage.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image. 4 | // To flip an image horizontally means that each row of the image is reversed. 5 | // For example, flipping [1,1,0] horizontally results in [0,1,1]. 6 | // To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. 7 | // For example, inverting [0,1,1] results in [1,0,0]. 8 | 9 | // Example 1: 10 | // Input: image = [[1,1,0],[1,0,1],[0,0,0]] 11 | // Output: [[1,0,0],[0,1,0],[1,1,1]] 12 | // Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]]. 13 | // Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]] 14 | 15 | // Example 2: 16 | // Input: image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] 17 | // Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] 18 | // Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]. 19 | // Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] 20 | 21 | class Solution 22 | { 23 | public: 24 | std::vector> flipAndInvertImage(std::vector>& image) 25 | { 26 | const int rows_size = image.size(); 27 | const int cols_size = image[0].size(); 28 | for (int row = 0; row < rows_size; ++row) { 29 | for (int col = 0; col < (cols_size + 1) / 2; ++col) { 30 | int temp = image[row][col]; 31 | image[row][col] = 1 - image[row][cols_size - col - 1]; 32 | image[row][cols_size - col - 1] = 1 - temp; 33 | } 34 | } 35 | 36 | return image; 37 | } 38 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/SortIntegersByTheNumberOf1Bits.cpp: -------------------------------------------------------------------------------- 1 | #include "../Helpers.hpp" 2 | 3 | // You are given an integer array arr. Sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order. 4 | // Return the array after sorting it. 5 | 6 | // Example 1: 7 | // Input: arr = [0,1,2,3,4,5,6,7,8] 8 | // Output: [0,1,2,4,8,3,5,6,7] 9 | // Explantion: [0] is the only integer with 0 bits. 10 | // [1,2,4,8] all have 1 bit. 11 | // [3,5,6] have 2 bits. 12 | // [7] has 3 bits. 13 | // The sorted array by bits is [0,1,2,4,8,3,5,6,7] 14 | 15 | // Example 2: 16 | // Input: arr = [1024,512,256,128,64,32,16,8,4,2,1] 17 | // Output: [1,2,4,8,16,32,64,128,256,512,1024] 18 | // Explantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order. 19 | 20 | class Solution 21 | { 22 | public: 23 | std::vector sortByBits(const std::vector& arr) 24 | { 25 | std::vector> temp; 26 | temp.reserve(arr.size()); 27 | 28 | for (const int value: arr) { 29 | std::bitset bitset(value); 30 | temp.emplace_back(bitset.count(), value); 31 | } 32 | 33 | std::sort(begin(temp), end(temp)); 34 | 35 | std::vector result(temp.size()); 36 | for (size_t i = 0u; i < temp.size(); ++i) { 37 | result[i] = temp[i].second; 38 | } 39 | 40 | return result; 41 | } 42 | }; 43 | 44 | int main(int argc, char** argv) 45 | { 46 | return EXIT_SUCCESS; 47 | } 48 | --------------------------------------------------------------------------------