diff --git a/.gitignore b/.gitignore index 7b8c768..ce3bd8a 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ out venv *.iml +.DS_Store diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4534a6d..fa9f31c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -18,36 +18,4 @@ and then create a pull request with the added solution and updated readme. 2. Say you solve some problem called __cars-and-trucks__ in using your favorite programming language, say Python then simple add a new file called `cars-and-trucks.py` in the `python` directory. -3. In the [README](README.md) file, add a Python logo along with an empty link. -4. Updating the link for the solution will be done by the Project maintainers - (aka. [anishLearnsToCode](https://github.com/anishLearnsToCode)) - -## Programming Language Logos -To add a logo in the [README](README.md) table simply add a link with an embedded picture as -```markdown -[![Python](icon-link)](this link will be filled by the author if the pull request is accepted) -``` - -For the icon link refer to the table below to obtain the link for a specific programming language: - -| Programming Language | Icon | Icon Link| -|:--------------------:|:----:|:----:| -| Java | ![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png) | https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png | -| Python | ![Python](https://img.icons8.com/color/35/000000/python.png) | https://img.icons8.com/color/35/000000/python.png | -| C | ![C](https://img.icons8.com/color/35/000000/c-programming.png) | https://img.icons8.com/color/35/000000/c-programming.png | -| C++ | ![C++](https://img.icons8.com/color/35/000000/c-plus-plus-logo.png) | https://img.icons8.com/color/35/000000/c-plus-plus-logo.png | -| C# | ![C#](https://img.icons8.com/color/35/000000/c-sharp-logo.png) | https://img.icons8.com/color/35/000000/c-sharp-logo.png | -| JavaScript | ![JavaScript](https://img.icons8.com/color/40/000000/javascript.png) | https://img.icons8.com/color/40/000000/javascript.png | -| TypeScript | ![TypeScript](https://img.icons8.com/color/40/000000/typescript.png) | https://img.icons8.com/color/40/000000/typescript.png | -| Ruby | ![Ruby](https://img.icons8.com/office/35/000000/ruby-programming-language.png) | https://img.icons8.com/office/35/000000/ruby-programming-language.png | -| Scala | ![Scala](https://img.icons8.com/dusk/35/000000/scala.png) | https://img.icons8.com/office/35/000000/ruby-programming-language.png | -| PHP | ![PHP](https://img.icons8.com/officel/40/000000/php-logo.png) | https://img.icons8.com/officel/40/000000/php-logo.png | -| Swift | ![Swift](https://img.icons8.com/fluent/40/000000/swift.png) | https://img.icons8.com/fluent/40/000000/swift.png | - - - - - - - - +3. In the [README](README.md) file, do not make any modification. The README file will be modified by __@anishLearnsToCode__. diff --git a/README.md b/README.md index 35c1486..d5aa028 100644 --- a/README.md +++ b/README.md @@ -1,381 +1,987 @@ -# Leetcode Algorithms +# LeetCode Algorithms -![problems-solved](https://img.shields.io/badge/Problems%20Solved-107/1412-1f425f.svg) -![problems-solved-java](https://img.shields.io/badge/Java-107/1412-1abc9c.svg) -![problems-solved-python](https://img.shields.io/badge/Python-20/1412-1abc9c.svg) +![problems-solved](https://img.shields.io/badge/Problems%20Solved-682/2813-1f425f.svg) +![problems-solved-java](https://img.shields.io/badge/Java-752/3215-1abc9c.svg) +![problems-solved-python](https://img.shields.io/badge/Python-204/3215-1abc9c.svg) +![problems-solved-javascript](https://img.shields.io/badge/JavaScript-4/3215-1abc9c.svg) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](CONTRIBUTING.md) +[![cp](https://img.shields.io/badge/also%20see-Competitve%20Programming-1f72ff.svg)](https://github.com/anishLearnsToCode/competitive-programming) + +🔒 = Subscription Content ## Problems -| # Number | Name | Difficulty | Solution | -|:--------:|------|:----------:|:--------:| -| 1 | [Two Sum](https://leetcode.com/problems/two-sum/) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/TwoSum.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/two_sum.py) | -| 7 | [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/ReverseInteger.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/reverse_integer.py) | -| 9 | [PalindromeNumber](https://leetcode.com/problems/palindrome-number/) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/PalindromeNumber.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/palindrome_number.py) | -| 13 | [Roman To Integer](https://leetcode.com/problems/roman-to-integer/) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/RomanToInteger.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/roman_to_integer.py) | -| 14 | [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/LongestCommonPrefix.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/longest_common_prefix.py) | -| 20 | [ValidParentheses](https://leetcode.com/problems/valid-parentheses/) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/ValidParentheses.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/valid_parentheses.py) | -| 21 | [Merge 2 Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/Merge2SortedLists.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/merge_2_sorted_lists.py) | -| 26 | [Remove Duplicates From Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/RemoveDuplicatesFromSortedArray.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/remove_duplicates_from_sorted_array.py) | -| 27 | [Remove Element](https://leetcode.com/problems/remove-element/) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/RemoveElement.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/remove_element.py)| -| 28 | [Needle in Haystack](https://leetcode.com/problems/implement-strstr) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/NeedleInHaystack.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/needle_in_haystack.py) | -| 35 | [Search Inserted Position](https://leetcode.com/problems/search-insert-position/) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/SearchInsertPosition.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/search_insert_position.py) | -| 38 | [Count and Say](https://leetcode.com/problems/count-and-say) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/CountAndSay.java) | -| 53 | [Maximum SubArray](https://leetcode.com/problems/maximum-subarray) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/MaximumSubArray.java) | -| 58 | [Length of Last Word](https://leetcode.com/problems/length-of-last-word) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/LengthOfLastWord.java) | -| 66 | [Plus One](https://leetcode.com/problems/plus-one) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/PlusOne.java) | -| 67 | [Add Binary](https://leetcode.com/problems/add-binary) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/AddBinary.java) | -| 69 | [Sqrt(x)](https://leetcode.com/problems/sqrtx) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/Sqrtx.java) | -| 70 | [Climbing Stairs](https://leetcode.com/problems/climbing-stairs) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/ClimbingStairs.java) | -| 83 | [Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/RemoveDuplicatesFromSortedList.java) | -| 88 | [Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/MergeSortedArray.java) | -| 100 | [Same Tree](https://leetcode.com/problems/same-tree) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/SameTree.java) | -| 101 | [Symmetric Tree](https://leetcode.com/problems/symmetric-tree) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/SymmetricTree.java) | -| 104 | [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/MaximumDepthOfBinaryTree.java) | -| 107 | [Binary Tree Level Order Traversal II](https://leetcode.com/problems/binary-tree-level-order-traversal-ii) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/BinaryTreeLevelOrderTraversalII.java) | -| 108 | [Convert Sorted Array To Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/ConvertSortedArrayToBinarySearchTree.java) | -| 110 | [Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/BalancedBinaryTree.java) | -| 111 | [Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/MinimumDepthOfBinaryTree.java) | -| 112 | [Path Sum](https://leetcode.com/problems/path-sum) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/PathSum.java) | -| 118 | [Pascal's Triangle](https://leetcode.com/problems/pascals-triangle) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/PascalsTriangle.java) | -| 119 | [Pascal's Triangle II](https://leetcode.com/problems/pascals-triangle-ii) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/PascalsTriangleII.java) | -| 121 | [Best Time to Buy and Sell Stocks](https://leetcode.com/problems/best-time-to-buy-and-sell-stock) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/BestTimeToBuyAndSellStock.java) | -| 122 | [Best Time to Buy and Sell Stocks II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/BestTimeToBuyAndSellStockII.java) | -| 125 | [Valid Palindrome](https://leetcode.com/problems/valid-palindrome) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/ValidPalindrome.java) | -| 136 | [Single Number](https://leetcode.com/problems/single-number) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/SingleNumber.java) | -| 141 | [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/LinkedListCycle.java) | -| 155 | [Min Stack](https://leetcode.com/problems/min-stack) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/MinStack.java) | -| 157 | [Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4) | Easy | | -| 160 | [Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/IntersectionOf2LinkedLists.java) | -| 167 | [Two Sum II - Input Array is Sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/TwoSumIIInputArrayIsSorted.java) | -| 168 | [Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/ExcelSheetColumnTitle.java) | -| 169 | [Majority Element](https://leetcode.com/problems/majority-element) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/MajorityElement.java) | -| 170 | [Two Sum III - Data Structure Design](https://leetcode.com/problems/two-sum-iii-data-structure-design) | Easy | | -| 171 | [Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/ExcelSheetColumnNumber.java) | -| 172 | [Factoring Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/FactorialTrailingZeros.java) | -| 189 | [Rotate Array](https://leetcode.com/problems/rotate-array) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/RotateArray.java) | -| 190 | [Reverse Bits](https://leetcode.com/problems/reverse-bits) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/ReverseBits.java) | -| 191 | [Number of One Bits](https://leetcode.com/problems/number-of-1-bits) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/NumberOf1Bit.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/number_of_1_bits.py) | -| 198 | [House Robber](https://leetcode.com/problems/house-robber) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/HouseRobber.java) | -| 202 | [Happy Number](https://leetcode.com/problems/happy-number) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/HappyNumber.java) | -| 203 | [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/RemoveLinkedListElements.java) | -| 204 | [Count Primes](https://leetcode.com/problems/count-primes) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/CountPrimes.java) | -| 205 | [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/IsomorphicStrings.java) | -| 206 | [Reverse Linked Lists](https://leetcode.com/problems/reverse-linked-list) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/ReverseLinkedList.java) | -| 217 | [Contains Duplicate](https://leetcode.com/problems/contains-duplicate) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/ContainsDuplicate.java) | -| 219 | [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/ContainsDuplicateII.java) | -| 225 | [Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/MyStack.java) | -| 226 | [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/InvertBinaryTree.java) | -| 231 | [Power of Two](https://leetcode.com/problems/power-of-two) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/PowerOf2.java) | -| 232 | [Implement Queue Using Stacks]() | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/MyQueue.java) | -| 234 | [Palindrome Linked Lists](https://leetcode.com/problems/palindrome-linked-list) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/PalindromeLinkedList.java) | -| 235 | [Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/LowestCommonAncestorOfBinarySearchTree.java) | -| 237 | [Delete a Node In A Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/DeleteANodeInLinkedList.java) | -| 242 | [Valid Anagram](https://leetcode.com/problems/valid-anagram) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/ValidAnagram.java) | -| 243 | [Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance) | Easy | | -| 246 | [Strobogramatic Number](https://leetcode.com/problems/strobogrammatic-number) | Easy | | -| 252 | [Meeting Rooms](https://leetcode.com/problems/meeting-rooms) | Easy | | -| 256 | [Paint House](https://leetcode.com/problems/paint-house) | Easy | | -| 257 | [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/BinaryTreePaths.java) | -| 258 | [Add Digits](https://leetcode.com/problems/add-digits) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/AddDigits.java) | -| 263 | [Ugly Number](https://leetcode.com/problems/ugly-number) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/UglyNumber.java) | -| 266 | [Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation) | Easy | | -| 268 | [Missing Number](https://leetcode.com/problems/missing-number) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/MissingNumber.java) | -| 270 | [Closest Binary Search Tree Value](https://leetcode.com/problems/closest-binary-search-tree-value) | Easy | | -| 276 | [Paint Fence](https://leetcode.com/problems/paint-fence) | Easy | | -| 278 | [First Bad Version](https://leetcode.com/problems/first-bad-version) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/FirstBadVersion.java) | -| 283 | [Move Zeroes](https://leetcode.com/problems/move-zeroes) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/MoveZeros.java) | -| 290 | [Word Pattern](https://leetcode.com/problems/word-pattern) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/WordPattern.java) | -| 292 | [Nim Game](https://leetcode.com/problems/nim-game) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/NimGame.java) | -| 293 | [Flip Game](https://leetcode.com/problems/flip-game) | Easy | | -| 299 | [Bulls and Cows](https://leetcode.com/problems/bulls-and-cows) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/BullsAndCows.java) | -| 303 | [Range Sum Query - Immutable](https://leetcode.com/problems/range-sum-query-immutable) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/RangeSumQueryImmutable.java) | -| 326 | [Power of Three](https://leetcode.com/problems/power-of-three) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/PowerOfThree.java) | -| 339 | [Nested List Weight Sum](https://leetcode.com/problems/nested-list-weight-sum) | Easy | | -| 342 | [Power of Four](https://leetcode.com/problems/power-of-four) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/PowerOf4.java) | -| 344 | [Reverse A String](https://leetcode.com/problems/reverse-string) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/ReverseString.java) | -| 345 | [Reverse Vowels of A String](https://leetcode.com/problems/reverse-vowels-of-a-string) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/ReverseVowelsOfString.java) | -| 346 | [Moving Average From Data Stream](https://leetcode.com/problems/moving-average-from-data-stream) | Easy | | -| 349 | [Intersection of 2 Arrays](https://leetcode.com/problems/intersection-of-two-arrays) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/IntersectionOfTwoArrays.java) | -| 350 | [Intersection of 2 Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/IntersectionOfTwoArraysII.java) | -| 359 | [Logger Rate Limiter](https://leetcode.com/problems/logger-rate-limiter) | Easy | | -| 367 | [Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/IsPerfectSquare.java) | -| 374 | [Guess Number Higher or Lower](https://leetcode.com/problems/guess-number-higher-or-lower) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/GuessNumberHigherOrLower.java) | -| 383 | [Ransom Note](https://leetcode.com/problems/ransom-note) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/RansomNote.java) | -| 387 | [First Unique Character in String](https://leetcode.com/problems/first-unique-character-in-a-string) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/FirstUniqueCharacter.java) | -| 389 | [Find the Difference](https://leetcode.com/problems/find-the-difference) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/FindTheDifference.java) | -| 392 | [Is Subsequence](https://leetcode.com/problems/is-subsequence) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/IsSubsequence.java) | -| 401 | [Binary Watch](https://leetcode.com/problems/binary-watch) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/BinaryWatch.java) | -| 404 | [Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/SumOfLeftLeaves.java) | -| 405 | [Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/ConvertNumberToHexadecimal.java) | -| 408 | [Valid Word Abbreviation](https://leetcode.com/problems/valid-word-abbreviation) | Easy | | -| 409 | [Longest Palindrome](https://leetcode.com/problems/longest-palindrome) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/LongestPalindrome.java) | -| 412 | [Fizz Buzz](https://leetcode.com/problems/fizz-buzz) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/FizzBuzz.java) | -| 414 | [Third Maximum Number](https://leetcode.com/problems/third-maximum-number) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/ThirdMaximumNumber.java) | -| 415 | [Add Strings](https://leetcode.com/problems/add-strings) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/AddString.java) | -| 422 | [Valid Word Square](https://leetcode.com/problems/valid-word-square) | Easy | | -| 434 | [Number of Segments in a String](https://leetcode.com/problems/number-of-segments-in-a-string) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/NumberOfSegmentsInString.java) | -| 441 | [Arranging Coins](https://leetcode.com/problems/arranging-coins) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/ArrangingCoins.java) | -| 443 | [String Compression](https://leetcode.com/problems/string-compression) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/StringCompression.java) | -| 447 | [Number of Boomerangs](https://leetcode.com/problems/number-of-boomerangs) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/NumberOfBoomerangs.java) | -| 448 | [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/FindAllNumbersDisappearedInAnArray.java) | -| 453 | [Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-moves-to-equal-array-elements) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/MinimumMovesToEqualArrayElements.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/minimum_moves_to_equal_array_element.py) | -| 455 | [Assign Cookies](https://leetcode.com/problems/assign-cookies) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/AssignCookies.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/assign_cookies.py)| -| 459 | [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/RepeatedSubstringPattern.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/repeated_substring_pattern.py) | -| 461 | [Hamming Distance](https://leetcode.com/problems/hamming-distance) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/HammingDistance.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/hamming_distance.py) | -| 463 | [Island Perimeter](https://leetcode.com/problems/island-perimeter) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/IslandPerimeter.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/island_perimeter.py) | -| 475 | [Heaters](https://leetcode.com/problems/heaters) | Medium | | -| 476 | [Number Complement](https://leetcode.com/problems/number-complement) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/NumberComplement.java) | -| 482 | [License Key Formatting](https://leetcode.com/problems/license-key-formatting) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/LicenseKeyFormatting.java) | -| 485 | [Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/MaxConsecutiveOnes.java) | -| 492 | [Construct the Rectangle](https://leetcode.com/problems/construct-the-rectangle) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/ConstructTheRectangle.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/construct_the_rectangle.py) | -| 496 | [Next Greater Element I](https://leetcode.com/problems/next-greater-element-i) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/NextGreaterElementI.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/next_greater_element_i.py) | -| 500 | [Keyboard Row](https://leetcode.com/problems/keyboard-row) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/KeyBoardRow.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/keyboard_row.py) | -| 501 | [Find Mode in Binary Search Tree](https://leetcode.com/problems/find-mode-in-binary-search-tree) | Easy | | -| 504 | [Base 7](https://leetcode.com/problems/base-7) | Easy | | -| 506 | [Relative Ranks](https://leetcode.com/problems/relative-ranks) | Easy | | -| 507 | [Perfect Number](https://leetcode.com/problems/perfect-number) | Easy | | -| 509 | [Fibonacci Number](https://leetcode.com/problems/fibonacci-number) | Easy | | -| 520 | [Detect Capital](https://leetcode.com/problems/detect-capital) | Easy | | -| 521 | [Longest Uncommon Subsequence I](https://leetcode.com/problems/longest-uncommon-subsequence-i) | Easy | | -| 530 | [Minimum Absolute Difference in BST](https://leetcode.com/problems/minimum-absolute-difference-in-bst) | Easy | | -| 532 | [K - Diff Pairs in Array](https://leetcode.com/problems/k-diff-pairs-in-an-array) | Easy | | -| 538 | [Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree) | Easy | | -| 541 | [Reverse String II](https://leetcode.com/problems/reverse-string-ii) | Easy | | -| 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree) | Easy | | -| 551 | [Student Attendance Record I](https://leetcode.com/problems/student-attendance-record-i) | Easy | | -| 557 | [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii) | Easy | | -| 559 | [Maximum Depth of N-Ary Tree](https://leetcode.com/problems/maximum-depth-of-n-ary-tree) | Easy | | -| 561 | [Array Partition I](https://leetcode.com/problems/array-partition-i) | Easy | | -| 563 | [Binary Tree Tilt](https://leetcode.com/problems/binary-tree-tilt) | Easy | | -| 566 | [Reshape The Matrix](https://leetcode.com/problems/reshape-the-matrix) | Easy | | -| 572 | [Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree) | Easy | | -| 575 | [Distribute Candies](https://leetcode.com/problems/distribute-candies) | Easy | | -| 581 | [Shortest Unsorted Continuous Subarray](https://leetcode.com/problems/shortest-unsorted-continuous-subarray) | Easy | | -| 589 | [N-Ary Tree Preorder Traversal](https://leetcode.com/problems/n-ary-tree-preorder-traversal) | Easy | | -| 590 | [N-Ary Tree Postorder Traversal](https://leetcode.com/problems/n-ary-tree-postorder-traversal) | Easy | | -| 594 | [Longest Harmonious Subsequence](https://leetcode.com/problems/longest-harmonious-subsequence) | Easy | | -| 598 | [Range Addition II](https://leetcode.com/problems/range-addition-ii) | Easy | | -| 599 | [Minimum Index Sum of 2 Lists](https://leetcode.com/problems/minimum-index-sum-of-two-lists) | Easy | | -| 604 | [Design Compressed String Iterator](https://leetcode.com/problems/design-compressed-string-iterator) | Easy | | -| 605 | [Can Place Flowers](https://leetcode.com/problems/can-place-flowers) | Easy | | -| 606 | [Construct String from Binary Tree](https://leetcode.com/problems/construct-string-from-binary-tree) | Easy | | -| 617 | [Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees) | Easy | | -| 624 | [Maximum Distance in Arrays](https://leetcode.com/problems/maximum-distance-in-arrays) | Easy | | -| 628 | [Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers) | Easy | | -| 633 | [Sum Square Numbers](https://leetcode.com/problems/sum-of-square-numbers) | Easy | | -| 637 | [Average of Levels in Binary Tree](https://leetcode.com/problems/average-of-levels-in-binary-tree) | Easy | | -| 643 | [Maximum Average SubArray I](https://leetcode.com/problems/maximum-average-subarray-i) | Easy | | -| 645 | [Set Mismatch](https://leetcode.com/problems/set-mismatch) | Easy | | -| 653 | [Two Sum IV - Input is a BST](https://leetcode.com/problems/two-sum-iv-input-is-a-bst) | Easy | | -| 657 | [Robot Return to Origin](https://leetcode.com/problems/robot-return-to-origin) | Easy | | -| 661 | [Image Smoother](https://leetcode.com/problems/image-smoother) | Easy | | -| 665 | [Non Deceasing Array](https://leetcode.com/problems/non-decreasing-array) | Easy | | -| 669 | [Trim a Binary Search Tree](https://leetcode.com/problems/trim-a-binary-search-tree) | Easy | | -| 671 | [Second Minimum Node in Binary Tree](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree) | Easy | | -| 674 | [Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence) | Easy | | -| 680 | [Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii) | Easy | | -| 682 | [Baseball Game](https://leetcode.com/problems/baseball-game) | Easy | | -| 686 | [Repeated String Match](https://leetcode.com/problems/repeated-string-match) | Easy | | -| 687 | [Longest Univalue Path](https://leetcode.com/problems/longest-univalue-path) | Easy | | -| 690 | [Employee Importance](https://leetcode.com/problems/employee-importance) | Easy | | -| 693 | [Binary Number with Alternating Bits](https://leetcode.com/problems/binary-number-with-alternating-bits) | Easy | | -| 696 | [Count Binary Substrings](https://leetcode.com/problems/count-binary-substrings) | Easy | | -| 697 | [Degree of an Array](https://leetcode.com/problems/degree-of-an-array) | Easy | | -| 700 | [Search in a Binary Search Tree](https://leetcode.com/problems/search-in-a-binary-search-tree) | Easy | | -| 703 | [Kth Largest Element in a Stream](https://leetcode.com/problems/kth-largest-element-in-a-stream) | Easy | | -| 704 | [Binary Search](https://leetcode.com/problems/binary-search) | Easy | | -| 705 | [Design HashSet](https://leetcode.com/problems/design-hashset) | Easy | | -| 706 | [Design HashMap](https://leetcode.com/problems/design-hashmap) | Easy | | -| 709 | [To Lower Case](https://leetcode.com/problems/to-lower-case) | Easy | | -| 716 | [Max Stack](https://leetcode.com/problems/max-stack) | Easy | | -| 717 | [1-bit and 2-bit Characters](https://leetcode.com/problems/1-bit-and-2-bit-characters) | Easy | | -| 720 | [Longest Word in Dictionary](https://leetcode.com/problems/longest-word-in-dictionary) | Easy | | -| 724 | [Find Pivot Index](https://leetcode.com/problems/find-pivot-index) | Easy | | -| 728 | [Self Dividing Numbers](https://leetcode.com/problems/self-dividing-numbers) | Easy | | -| 733 | [Flood Fill](https://leetcode.com/problems/flood-fill) | Easy | | -| 734 | [Sentence Similarity](https://leetcode.com/problems/sentence-similarity) | Easy | | -| 744 | [Find Smallest Letter Greater Than Target](https://leetcode.com/problems/find-smallest-letter-greater-than-target) | Easy | | -| 746 | [Min Cost Climbing Stairs](https://leetcode.com/problems/min-cost-climbing-stairs) | Easy | | -| 747 | [Largest Number at least twize of Others](https://leetcode.com/problems/largest-number-at-least-twice-of-others) | Easy | | -| 748 | [Shortest Completing Word](https://leetcode.com/problems/shortest-completing-word) | Easy | | -| 758 | [Bold Words in String](https://leetcode.com/problems/bold-words-in-string) | Easy | | -| 760 | [Find Anagram Mappings](https://leetcode.com/problems/find-anagram-mappings) | Easy | | -| 762 | [Prime Number of Set Bits in Primary Representation](https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation) | Easy | | -| 766 | [Toeplitz Matrix](https://leetcode.com/problems/toeplitz-matrix) | Easy | | -| 771 | [Jewels and Stones](https://leetcode.com/problems/jewels-and-stones) | Easy | | -| 783 | [Minimum Distance Between BST Nodes](https://leetcode.com/problems/minimum-distance-between-bst-nodes) | Easy | | -| 788 | [Rotated Digits](https://leetcode.com/problems/rotated-digits) | Easy | | -| 796 | [Rotate String](https://leetcode.com/problems/rotate-string) | Easy | | -| 800 | [Similar RGB Color](https://leetcode.com/problems/similar-rgb-color) | Easy | | -| 804 | [Unique Morse Code Words](https://leetcode.com/problems/unique-morse-code-words) | Easy | | -| 806 | [Number of Lines to Write String](https://leetcode.com/problems/number-of-lines-to-write-string) | Easy | | -| 811 | [Subdomain Visit Count](https://leetcode.com/problems/subdomain-visit-count) | Easy | | -| 812 | [Largest Triangle Area](https://leetcode.com/problems/largest-triangle-area) | Easy | | -| 819 | [Most Common Word](https://leetcode.com/problems/most-common-word) | Easy | | -| 821 | [Shortest Distance to Character](https://leetcode.com/problems/shortest-distance-to-a-character) | Easy | | -| 824 | [Goat Latin](https://leetcode.com/problems/goat-latin) | Easy | | -| 830 | [Positions of Large Groups](https://leetcode.com/problems/positions-of-large-groups) | Easy | | -| 832 | [Flipping an Image](https://leetcode.com/problems/flipping-an-image) | Easy | | -| 836 | [Rectangle Overlap](https://leetcode.com/problems/rectangle-overlap) | Easy | | -| 840 | [Magic Squares in Grid](https://leetcode.com/problems/magic-squares-in-grid) | Easy | | -| 844 | [Backspace String Compare](https://leetcode.com/problems/backspace-string-compare) | Easy | | -| 849 | [Maximize Distance to Closest Person](https://leetcode.com/problems/maximize-distance-to-closest-person) | Easy | | -| 852 | [Peak Index in Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array) | Easy | | -| 859 | [Buddy Strings](https://leetcode.com/problems/buddy-strings) | Easy | | -| 860 | [Lemonade Change](https://leetcode.com/problems/lemonade-change) | Easy | | -| 867 | [Transpose Matrix](https://leetcode.com/problems/transpose-matrix) | Easy | | -| 868 | [Binary Gap](https://leetcode.com/problems/binary-gap) | Easy | | -| 872 | [Leaf-Similar Trees](https://leetcode.com/problems/leaf-similar-trees) | Easy | | -| 874 | [Walking Robot Simulation](https://leetcode.com/problems/walking-robot-simulation) | Easy | | -| 876 | [Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list) | Easy | | -| 883 | [Projection Area of 3D Shapes](https://leetcode.com/problems/projection-area-of-3d-shapes) | Easy | | -| 884 | [Uncommon Words from 2 Sentences](https://leetcode.com/problems/uncommon-words-from-two-sentences) | Easy | | -| 888 | [Fair Candy Swap](https://leetcode.com/problems/fair-candy-swap) | Easy | | -| 892 | [Surface Area of 3D Shapes](https://leetcode.com/problems/surface-area-of-3d-shapes) | Easy | | -| 893 | [Groups of Special Equivalent Strings](https://leetcode.com/problems/groups-of-special-equivalent-strings) | Easy | | -| 896 | [Monotonic Array](https://leetcode.com/problems/monotonic-array) | Easy | | -| 897 | [Increasing Order Search Tree](https://leetcode.com/problems/increasing-order-search-tree) | Easy | | -| 905 | [Sort Array by Parity](https://leetcode.com/problems/sort-array-by-parity) | Easy | | -| 908 | [Smallest Range I](https://leetcode.com/problems/smallest-range-i) | Easy | | -| 914 | [X of a kind in a Deck of Cards](https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards) | Easy | | -| 917 | [Reverse Only Letters](https://leetcode.com/problems/reverse-only-letters) | Easy | | -| 922 | [Sort Array by Parity II](https://leetcode.com/problems/sort-array-by-parity-ii) | Easy | | -| 925 | [Long Pressed Name](https://leetcode.com/problems/long-pressed-name) | Easy | | -| 929 | [Unique Email Addresses](https://leetcode.com/problems/unique-email-addresses) | Easy | | -| 933 | [Number of Recent Calls](https://leetcode.com/problems/number-of-recent-calls) | Easy | | -| 937 | [Reorder Data In Log Files](https://leetcode.com/problems/reorder-data-in-log-files) | Easy | | -| 938 | [Range Sum of BST](https://leetcode.com/problems/range-sum-of-bst) | Easy | | -| 941 | [Valid Mountain Array](https://leetcode.com/problems/valid-mountain-array) | Easy | | -| 942 | [DI String Match](https://leetcode.com/problems/di-string-match) | Easy | | -| 944 | [Delete Columns to Make Sorted](https://leetcode.com/problems/delete-columns-to-make-sorted) | Easy | | -| 949 | [Largest Time for Given Digits](https://leetcode.com/problems/largest-time-for-given-digits) | Easy | | -| 953 | [Verifying an Alien Dictionary](https://leetcode.com/problems/verifying-an-alien-dictionary) | Easy | | -| 961 | [N-Repeated Elements in Size 2N Array](https://leetcode.com/problems/n-repeated-element-in-size-2n-array) | Easy | | -| 965 | [Univalued Binary Tree](https://leetcode.com/problems/univalued-binary-tree) | Easy | | -| 970 | [Powerful Integers](https://leetcode.com/problems/powerful-integers) | Easy | | -| 976 | [Largest Perimeter Triangle](https://leetcode.com/problems/largest-perimeter-triangle) | Easy | | -| 977 | [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array) | Easy | | -| 985 | [Sum of Even Numbers after Queries](https://leetcode.com/problems/sum-of-even-numbers-after-queries) | Easy | | -| 989 | [Add to Array Form of Integer](https://leetcode.com/problems/add-to-array-form-of-integer) | Easy | | -| 993 | [Cousins in Binary Tree](https://leetcode.com/problems/cousins-in-binary-tree) | Easy | | -| 997 | [Find the Town Judge](https://leetcode.com/problems/find-the-town-judge) | Easy | | -| 999 | [Available Captures for Rook](https://leetcode.com/problems/available-captures-for-rook) | Easy | | -| 1002 | [Find Common Characters](https://leetcode.com/problems/find-common-characters) | Easy | | -| 1005 | [Maximize Sum of Array After K Negations](https://leetcode.com/problems/maximize-sum-of-array-after-k-negations) | Easy | | -| 1009 | [Complement of Base 10 Integer](https://leetcode.com/problems/complement-of-base-10-integer) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/NumberComplement.java) | -| 1010 | [Pairs of Songs With Total Durations Divisible by 60](https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60) | Easy | | -| 1013 | [Partition Array into Three Parts with equal Sum](https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum) | Easy | | -| 1018 | [Binary Prefix Divisible by 5](https://leetcode.com/problems/binary-prefix-divisible-by-5) | Easy | | -| 1021 | [Remove Outermost Parenthesis](https://leetcode.com/problems/remove-outermost-parentheses) | Easy | | -| 1022 | [Sum of Root to Leaf Binary Numbers](https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers) | Easy | | -| 1025 | [Divisor Game](https://leetcode.com/problems/divisor-game) | Easy | | -| 1029 | [Two City Scheduling](https://leetcode.com/problems/two-city-scheduling) | Easy | | -| 1030 | [Matrix Cells in Distance Order](https://leetcode.com/problems/matrix-cells-in-distance-order) | Easy | | -| 1033 | [Moving Stones Until Consecutive](https://leetcode.com/problems/moving-stones-until-consecutive) | Easy | | -| 1037 | [Valid Boomerang](https://leetcode.com/problems/valid-boomerang) | Easy | | -| 1042 | [Flower Planting with no Adjacent](https://leetcode.com/problems/flower-planting-with-no-adjacent) | Easy | | -| 1046 | [Last Stone Weight](https://leetcode.com/problems/last-stone-weight) | Easy | | -| 1047 | [Remove All adjacent Duplicates in String](https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string) | Easy | | -| 1051 | [Height Checker](https://leetcode.com/problems/height-checker) | Easy | | -| 1056 | [Confusing Number](https://leetcode.com/problems/confusing-number) | Easy | | -| 1064 | [Fixed Point](https://leetcode.com/problems/fixed-point) | Easy | | -| 1065 | [Index Pairs of a String](https://leetcode.com/problems/index-pairs-of-a-string) | Easy | | -| 1071 | [Greatest Common Divisors of Strings](https://leetcode.com/problems/greatest-common-divisor-of-strings) | Easy | | -| 1078 | [Occurrence After Bigram](https://leetcode.com/problems/occurrences-after-bigram) | Easy | | -| 1085 | [Sum of Digits in Minimum Number](https://leetcode.com/problems/sum-of-digits-in-the-minimum-number) | Easy | | -| 1086 | [High Five](https://leetcode.com/problems/high-five) | Easy | | -| 1089 | [Duplicate Zeroes](https://leetcode.com/problems/duplicate-zeros) | Easy | | -| 1099 | [Two Sum Less Than K](https://leetcode.com/problems/two-sum-less-than-k) | Easy | | -| 1103 | [Distribute Candies to People](https://leetcode.com/problems/distribute-candies-to-people) | Easy | | -| 1108 | [Defanging an IP Address](https://leetcode.com/problems/defanging-an-ip-address) | Easy | | -| 1118 | [Number of Days in a Month](https://leetcode.com/problems/number-of-days-in-a-month) | Easy | | -| 1119 | [Remove Vowels From String](https://leetcode.com/problems/remove-vowels-from-a-string) | Easy | | -| 1122 | [Relative Sort Array](https://leetcode.com/problems/relative-sort-array) | Easy | | -| 1128 | [Number of Equivalent Domino Pairs](https://leetcode.com/problems/number-of-equivalent-domino-pairs) | Easy | | -| 1133 | [Largest Unique Number](https://leetcode.com/problems/largest-unique-number) | Easy | | -| 1134 | [Armstrong Number](https://leetcode.com/problems/armstrong-number) | Easy | | -| 1137 | [Nth Tribonacci Number]() | Easy | | -| 1150 | [Check if Number is Majority Element in Sorted Array](https://leetcode.com/problems/check-if-a-number-is-majority-element-in-a-sorted-array) | Easy | | -| 1154 | [Day of The Year](https://leetcode.com/problems/day-of-the-year) | Easy | | -| 1160 | [Find Words That Can Be Formed By Characters](https://leetcode.com/problems/find-words-that-can-be-formed-by-characters) | Easy | | -| 1165 | [Single Row Keyboard](https://leetcode.com/problems/single-row-keyboard) | Easy | | -| 1170 | [Compare Strings By Frequency of the Smallest Character](https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character) | Easy | | -| 1175 | [Prime Arrangements](https://leetcode.com/problems/prime-arrangements) | Easy | | -| 1176 | [Diet Plan Performance](https://leetcode.com/problems/diet-plan-performance) | Easy | | -| 1180 | [Count Substrings with only one Distinct Letter](https://leetcode.com/problems/count-substrings-with-only-one-distinct-letter) | Easy | | -| 1184 | [Distance Between Bus Stops](https://leetcode.com/problems/distance-between-bus-stops) | Easy | | -| 1185 | [Day of the Week](https://leetcode.com/problems/day-of-the-week) | Easy | | -| 1189 | [Maximum Number of Balloons](https://leetcode.com/problems/maximum-number-of-balloons) | Easy | | -| 1196 | [How Many Apples Can You Put into the Basket](https://leetcode.com/problems/how-many-apples-can-you-put-into-the-basket) | Easy | | -| 1200 | [Minimum Absolute Difference](https://leetcode.com/problems/minimum-absolute-difference) | Easy | | -| 1207 | [Unique Number of Occurrences](https://leetcode.com/problems/unique-number-of-occurrences) | Easy | | -| 1213 | [Intersection of Three Sorted Arrays](https://leetcode.com/problems/intersection-of-three-sorted-arrays) | Easy | | -| 1217 | [Play With Chips](https://leetcode.com/problems/play-with-chips) | Easy | | -| 1221 | [Split A String In Balanced Strings](https://leetcode.com/problems/split-a-string-in-balanced-strings) | Easy | | -| 1228 | [Missing A Number In Arithmetic Progression](https://leetcode.com/problems/missing-number-in-arithmetic-progression) | Easy | | -| 1232 | [Check If It Is A Straight Line](https://leetcode.com/problems/check-if-it-is-a-straight-line) | Easy | | -| 1237 | [Find Positive Integer Solutions for a Given Equation](https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation) | Easy | | -| 1243 | [Array Transformation](https://leetcode.com/problems/array-transformation) | Easy | | -| 1252 | [Cells With Odd Values In Matrix](https://leetcode.com/problems/cells-with-odd-values-in-a-matrix) | Easy | | -| 1260 | [Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid) | Easy | | -| 1266 | [Minimum Time Visiting All Points](https://leetcode.com/problems/minimum-time-visiting-all-points) | Easy | | -| 1271 | [Hexspeak](https://leetcode.com/problems/hexspeak) | Easy | | -| 1275 | [Find Winner On a Tic Tac Toe Game](https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game) | Easy | | -| 1281 | [Subtract the Product and Sum of Digits of a Integer](https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer) | Easy | | -| 1287 | [Element Appearing More Than 25% in Sorted Array](https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array) | Easy | | -| 1290 | [Convert Binary Number In A Linked List to Integer](https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer) | Easy | | -| 1295 | [Find Numbers With Even Numbers of Digits](https://leetcode.com/problems/find-numbers-with-even-number-of-digits) | Easy | | -| 1299 | [Replace Elements With Greatest Element on Right Side](https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side) | Easy | | -| 1304 | [Find N Unique Integers Sum Up To Zero](https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero) | Easy | | -| 1309 | [Decrypt String From Alphabet To Integer Mapping](https://leetcode.com/problems/decrypt-string-from-alphabet-to-integer-mapping) | Easy | | -| 1313 | [Decompress Run-Length Encoded Strings](https://leetcode.com/problems/decompress-run-length-encoded-list) | Easy | | -| 1317 | [Convert Integer to Sum Of Two Non-Zero Integers](https://leetcode.com/problems/convert-integer-to-the-sum-of-two-no-zero-integers) | Easy | | -| 1323 | [Maximum 69 Number](https://leetcode.com/problems/maximum-69-number) | Easy | | -| 1331 | [Rank Transform of An Array](https://leetcode.com/problems/rank-transform-of-an-array) | Easy | | -| 1332 | [Remove Palindromic Subsequences](https://leetcode.com/problems/remove-palindromic-subsequences) | Easy | | -| 1337 | [The K Weakest Rows In A Matrix](https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix) | Easy | | -| 1342 | [Number of Steps to Reduce a Number to Zero](https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero) | Easy | | -| 1346 | [Check if N and It's Double Exist](https://leetcode.com/problems/check-if-n-and-its-double-exist) | Easy | | -| 1351 | [Count Negative Numbers In A Sorted Matrix](https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix) | Easy | | -| 1356 | [Sort Integers by Number of 1 Bits](https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits) | Easy | | -| 1360 | [Number of Days Between Two Dates](https://leetcode.com/problems/number-of-days-between-two-dates) | Easy | | -| 1365 | [How Many Numbers Are Smaller Than Current Number](https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number) | Easy | | -| 1370 | [Increasing Decreasing String](https://leetcode.com/problems/increasing-decreasing-string) | Easy | | -| 1374 | [Generate A String With Characters That Have Odd Count](https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts) | Easy | | -| 1380 | [Lucky Numbers In A Matrix](https://leetcode.com/problems/lucky-numbers-in-a-matrix) | Easy | | -| 1385 | [Find The Distance Value Between 2 Arrays](https://leetcode.com/problems/find-the-distance-value-between-two-arrays) | Easy | | -| 1389 | [Create Target Array in Given Order](https://leetcode.com/problems/create-target-array-in-the-given-order) | Easy | | -| 1394 | [Find Lucky Integer In An Array](https://leetcode.com/problems/find-lucky-integer-in-an-array) | Easy | | -| 1399 | [Count Largest Group](https://leetcode.com/problems/count-largest-group) | Easy | | -| 1403 | [Minimum Subsequence in Non-Increasing Order](https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order) | Easy | | -| 1408 | [String Matching In An Array](https://leetcode.com/problems/string-matching-in-an-array) | Easy | | -| 1413 | [Minimum Value To Get Positive Step By Step Sum](https://leetcode.com/problems/minimum-value-to-get-positive-step-by-step-sum) | Easy | | -| 1417 | [Reformat The String](https://leetcode.com/problems/reformat-the-string) | Easy | | -| 1422 | [Maximum Score After Splitting A String](https://leetcode.com/problems/maximum-score-after-splitting-a-string) | Easy | | -| 1426 | [Counting Elements](https://leetcode.com/problems/counting-elements) | Easy | | -| 1427 | [Performing String Shifts](https://leetcode.com/problems/perform-string-shifts) | Easy | | -| 1431 | [Kids With The Greatest Number Of Candies](https://leetcode.com/problems/kids-with-the-greatest-number-of-candies) | Easy | | -| 1436 | [Destination City](https://leetcode.com/problems/destination-city) | Easy | | -| 1441 | [Build An Array With Stack Operation](https://leetcode.com/problems/build-an-array-with-stack-operations) | Easy | | -| 1446 | [Consecutive Characters](https://leetcode.com/problems/consecutive-characters) | Easy | | -| 1450 | [Number of Students Doing Homework at Given Time](https://leetcode.com/problems/number-of-students-doing-homework-at-a-given-time) | Easy | | -| 1455 | [Check If Word Occurs as Prefix of any Word in Sentence](https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence) | Easy | | -| 1460 | [Make 2 Arrays Equal by Reversing Sub Arrays](https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays) | Easy | | -| 1464 | [Maximum Product of 2 Elements in Array](https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array) | Easy | | -| 1469 | [Find All Lonely Nodes](https://leetcode.com/problems/find-all-the-lonely-nodes) | Easy | | -| 1470 | [Shuffle The Array](https://leetcode.com/problems/shuffle-the-array) | Easy | | -| 1474 | [Delete N Nodes After M Nodes In A Linked List](https://leetcode.com/problems/delete-n-nodes-after-m-nodes-of-a-linked-list) | Easy | | -| 1475 | [Final Prices With Special Discount in a Shop](https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop) | Easy | | -| 1480 | [Running Sum of 1D Array](https://leetcode.com/problems/running-sum-of-1d-array) | Easy | | -| 1486 | [XOR Operations in An Array](https://leetcode.com/problems/xor-operation-in-an-array) | Easy | | -| 1491 | [Average Salary Excluding the Minimum and Maximum Salary](https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary) | Easy | | -| 1496 | [Path Crossing](https://leetcode.com/problems/path-crossing) | Easy | | -| 1502 | [Can Make Arithmetic Progression From Sequence](https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence) | Easy | | -| 1507 | [Reformat Date](https://leetcode.com/problems/reformat-date) | Easy | | -| 1512 | [Number of Good Pairs](https://leetcode.com/problems/number-of-good-pairs) | Easy | | -| 1518 | [Water Bottles](https://leetcode.com/problems/water-bottles) | Easy | | -| 1523 | [Count Odd Numbers In Interval Range](https://leetcode.com/problems/count-odd-numbers-in-an-interval-range) | Easy | | -| 1528 | [Shuffle Strings](https://leetcode.com/problems/shuffle-string) | Easy | | -| 1534 | [Count Good Triplets](https://leetcode.com/problems/count-good-triplets) | Easy | | -| 1539 | [Kth Missing Positive Number](https://leetcode.com/problems/kth-missing-positive-number) | Easy | | -| 1544 | [Make The String Great](https://leetcode.com/problems/make-the-string-great) | Easy | | +| # | Name | Solution | Youtube | +|:----:|------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|:---------------------------------------------------------------------------------------------------------------------------------:| +| 1 | [Two Sum](https://leetcode.com/problems/two-sum) | [![Java](assets/java.png)](src/TwoSum.java) [![Python](assets/python.png)](python/two_sum.py) | [![java-yt](assets/java-yt.png)](https://youtu.be/9wSL_7NN-A8) [![python-yt](assets/python-yt.png)](https://youtu.be/N5FXCTg0TDE) | +| 2 | [Add Two Numbers](https://leetcode.com/problems/add-two-numbers) | [![Java](assets/java.png)](src/AddTwoNumbers.java) [![js](assets/javascript.png)](javascript/AddTwoNumbers.js) | | +| 3 | [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters) | [![Java](assets/java.png)](src/LongestSubstringWithoutRepeatingCharacters.java) | | +| 5 | [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring) | [![Java](assets/java.png)](src/LongestPalindromicSubstring.java) | | +| 6 | [Zigzag Conversion](https://leetcode.com/problems/zigzag-conversion) | [![Java](assets/java.png)](src/ZigZagConversion.java) | | +| 7 | [Reverse Integer](https://leetcode.com/problems/reverse-integer) | [![Java](assets/java.png)](src/ReverseInteger.java) [![Python](assets/python.png)](python/reverse_integer.py) [![js](assets/javascript.png)](javascript/ReverseInteger.js) | [![java-yt](assets/java-yt.png)](https://youtu.be/7bOhyl5lWjI) [![python-yt](assets/python-yt.png)](https://youtu.be/lmLG30TLcSg) | +| 8 | [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi) | [![Java](assets/java.png)](src/StringToIntegerAtoi.java) | | +| 9 | [Palindrome Number](https://leetcode.com/problems/palindrome-number) | [![Java](assets/java.png)](src/PalindromeNumber.java) [![Python](assets/python.png)](python/palindrome_number.py) [![js](assets/javascript.png)](javascript/PalindromeNumber.js) | | +| 11 | [Container With Most Water](https://leetcode.com/problems/container-with-most-water) | [![Java](assets/java.png)](src/ContainerWitMostWater.java) | | +| 12 | [Integer to Roman](https://leetcode.com/problems/integer-to-roman) | [![Java](assets/java.png)](src/IntegerToRoman.java) | | +| 13 | [Roman To Integer](https://leetcode.com/problems/roman-to-integer/) | [![Java](assets/java.png)](src/RomanToInteger.java) [![Python](assets/python.png)](python/roman_to_integer.py) | [![java-yt](assets/java-yt.png)](https://youtu.be/BCue_mO_81A) [![python-yt](assets/python-yt.png)](https://youtu.be/8h_yGTNvKMA) | +| 14 | [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | [![Java](assets/java.png)](src/LongestCommonPrefix.java) [![Python](assets/python.png)](python/longest_common_prefix.py) | | +| 15 | [3Sum](https://leetcode.com/problems/3sum) | [![Java](assets/java.png)](src/ThreeSum.java) | | +| 16 | [3Sum Closest](https://leetcode.com/problems/3sum-closest) | [![Java](assets/java.png)](src/ThreeSumClosest.java) | | +| 17 | [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number) | [![Java](assets/java.png)](src/LetterCombinationsOfAPhoneNumber.java) | | +| 18 | [4Sum](https://leetcode.com/problems/4sum) | [![Java](assets/java.png)](src/FourSum.java) | | +| 19 | [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list) | [![Java](assets/java.png)](src/RemoveNthNodeFromEndOfList.java) | | +| 20 | [ValidParentheses](https://leetcode.com/problems/valid-parentheses/) | [![Java](assets/java.png)](src/ValidParentheses.java) [![Python](assets/python.png)](python/valid_parentheses.py) | | +| 21 | [Merge 2 Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/) | [![Java](assets/java.png)](src/Merge2SortedLists.java) [![Python](assets/python.png)](python/merge_2_sorted_lists.py) | | +| 22 | [Generate Parentheses](https://leetcode.com/problems/generate-parentheses) | [![Java](assets/java.png)](src/GenerateParentheses.java) | | +| 24 | [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs) | [![Java](assets/java.png)](src/SwapNodesInPairs.java) | | +| 25 | [Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group) | [![Java](assets/java.png)](src/ReverseNodesInKGroup.java) | | +| 26 | [Remove Duplicates From Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array) | [![Java](assets/java.png)](src/RemoveDuplicatesFromSortedArray.java) [![Python](assets/python.png)](python/remove_duplicates_from_sorted_array.py) [![js](assets/javascript.png)](javascript/RemoveDuplicatesFromSortedArray.js) | | +| 27 | [Remove Element](https://leetcode.com/problems/remove-element/) | [![Java](assets/java.png)](src/RemoveElement.java) [![Python](assets/python.png)](python/remove_element.py) | | +| 28 | [Needle in Haystack](https://leetcode.com/problems/implement-strstr) | [![Java](assets/java.png)](src/NeedleInHaystack.java) [![Python](assets/python.png)](python/needle_in_haystack.py) | | +| 29 | [Divide Two Integers](https://leetcode.com/problems/divide-two-integers) | [![Java](assets/java.png)](src/DivideTwoIntegers.java) | | +| 30 | [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words) | [![Java](assets/java.png)](src/SubstringWithConcatenationOfAllWords.java) | | +| 31 | [Next Permutation](https://leetcode.com/problems/next-permutation) | [![Java](assets/java.png)](src/NextPermutation.java) | | +| 33 | [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array) | [![Java](assets/java.png)](src/SearchInRotatedSortedArray.java) | | +| 34 | [Find First and Last Position of Element in Sorted Array](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array) | [![Java](assets/java.png)](src/FindFirstAndLastPositionOfElementInSortedArray.java) | | +| 35 | [Search Inserted Position](https://leetcode.com/problems/search-insert-position/) | [![Java](assets/java.png)](src/SearchInsertPosition.java) [![Python](assets/python.png)](python/search_insert_position.py) | | +| 36 | [Valid Sudoku](https://leetcode.com/problems/valid-sudoku) | [![Java](assets/java.png)](src/ValidSudoku.java) | | +| 37 | [Sudoku Solver](https://leetcode.com/problems/sudoku-solver) | [![Java](assets/java.png)](src/SudokuSolver.java) | | +| 38 | [Count and Say](https://leetcode.com/problems/count-and-say) | [![Java](assets/java.png)](src/CountAndSay.java) [![Python](assets/python.png)](python/count_and_say.py) | | +| 39 | [Combination Sum](https://leetcode.com/problems/combination-sum) | [![Java](assets/java.png)](src/CombinationSum.java) | | +| 40 | [Combination Sum II](https://leetcode.com/problems/combination-sum-ii) | [![Java](assets/java.png)](src/CombinationSumII.java) | | +| 41 | [First Missing Positive](https://leetcode.com/problems/first-missing-positive) | [![Java](assets/java.png)](src/FirstMissingPositive.java) | | +| 42 | [Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water) | [![Java](assets/java.png)](src/TrappingRainwater.java) | | +| 43 | [Multiply Strings](https://leetcode.com/problems/multiply-strings) | [![Java](assets/java.png)](src/MultiplyStrings.java) | | +| 45 | [Jump Game II](https://leetcode.com/problems/jump-game-ii) | [![Java](assets/java.png)](src/JumpGameII.java) | | +| 46 | [Permutations](https://leetcode.com/problems/permutations) | [![Java](assets/java.png)](src/Permutations.java) | | +| 47 | [Permutations II](https://leetcode.com/problems/permutations-ii) | [![Java](assets/java.png)](src/PermutationsII.java) | | +| 48 | [Rotate Image](https://leetcode.com/problems/rotate-image) | [![Java](assets/java.png)](src/RotateImage.java) | | +| 49 | [Group Anagrams](https://leetcode.com/problems/group-anagrams) | [![Java](assets/java.png)](src/GroupAnagrams.java) | | +| 50 | [Pow(x,n)](https://leetcode.com/problems/powx-n) | [![Java](assets/java.png)](src/Powxn.java) | | +| 51 | [N-Queens](https://leetcode.com/problems/n-queens) | [![Java](assets/java.png)](src/NQueens.java) | | +| 51 | [N-Queens II](https://leetcode.com/problems/n-queens-ii) | [![Java](assets/java.png)](src/NQueensII.java) | | +| 53 | [Maximum SubArray](https://leetcode.com/problems/maximum-subarray) | [![Java](assets/java.png)](src/MaximumSubArray.java) [![Python](assets/python.png)](python/maximum_sum_subarray.py) | | +| 54 | [Spiral Matrix](https://leetcode.com/problems/spiral-matrix) | [![Java](assets/java.png)](src/SpiralMatrix.java) | | +| 55 | [Jump Game](https://leetcode.com/problems/jump-game) | [![Java](assets/java.png)](src/JumpGame.java) | | +| 56 | [Merge Intervals](https://leetcode.com/problems/merge-intervals) | [![Java](assets/java.png)](src/MergeIntervals.java) | | +| 57 | [Insert Interval](https://leetcode.com/problems/insert-interval) | [![Java](assets/java.png)](src/InsertInterval.java) | | +| 58 | [Length of Last Word](https://leetcode.com/problems/length-of-last-word) | [![Java](assets/java.png)](src/LengthOfLastWord.java) [![Python](assets/python.png)](python/length_of_last_word.py) | | +| 59 | [Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii) | [![Java](assets/java.png)](src/SpiralMatrixII.java) | | +| 61 | [Rotate List](https://leetcode.com/problems/rotate-list) | [![Java](assets/java.png)](src/RotateList.java) | | +| 62 | [Unique Paths](https://leetcode.com/problems/unique-paths) | [![Java](assets/java.png)](src/UniquePaths.java) | | +| 63 | [Unique Paths II](https://leetcode.com/problems/unique-paths-ii) | [![Java](assets/java.png)](src/UniquePathII.java) | | +| 64 | [Minimum Path Sum](https://leetcode.com/problems/minimum-path-sum) | [![Java](assets/java.png)](src/MinimumPathSum.java) [![Python](assets/python.png)](python/minimum_path_sum.py) | | +| 66 | [Plus One](https://leetcode.com/problems/plus-one) | [![Java](assets/java.png)](src/PlusOne.java) [![Python](assets/python.png)](python/plus_one.py) | | +| 67 | [Add Binary](https://leetcode.com/problems/add-binary) | [![Java](assets/java.png)](src/AddBinary.java) [![Python](assets/python.png)](python/add_binary.py) | | +| 68 | [Text Justification](https://leetcode.com/problems/text-justification) | [![Java](assets/java.png)](src/AddBinary.java) | | +| 69 | [Sqrt(x)](https://leetcode.com/problems/sqrtx) | [![Java](assets/java.png)](src/Sqrtx.java) [![Python](assets/python.png)](python/sqrt.py) | | +| 70 | [Climbing Stairs](https://leetcode.com/problems/climbing-stairs) | [![Java](assets/java.png)](src/ClimbingStairs.java) [![Python](assets/python.png)](python/climbing_stairs.py) | | +| 71 | [Simplify Path](https://leetcode.com/problems/simplify-path) | [![Java](assets/java.png)](src/SimplifyPath.java) | | +| 72 | [Edit Distance](https://leetcode.com/problems/edit-distance) | [![Java](assets/java.png)](src/EditDistance.java) | | +| 73 | [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes) | [![Java](assets/java.png)](src/SetMatrixZeroes.java) | | +| 74 | [Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix) | [![Java](assets/java.png)](src/SearchA2DMatrix.java) | | +| 75 | [Sort Colors](https://leetcode.com/problems/sort-colors) | [![Java](assets/java.png)](src/SortColors.java) | | +| 77 | [Combinations](https://leetcode.com/problems/combinations) | [![Java](assets/java.png)](src/Combinations.java) | | +| 78 | [Subsets](https://leetcode.com/problems/subsets) | [![Java](assets/java.png)](src/Subsets.java) | | +| 79 | [Word Search](https://leetcode.com/problems/word-search) | [![Java](assets/java.png)](src/WordSearch.java) | | +| 80 | [Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii) | [![Java](assets/java.png)](src/RemoveDuplicatesFromSortedArrayII.java) | | +| 81 | [Search in Rotated Sorted Array II](https://leetcode.com/problems/search-in-rotated-sorted-array-ii) | [![Java](assets/java.png)](src/SearchInRotatedSortedArrayII.java) | | +| 82 | [Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii) | [![Java](assets/java.png)](src/RemoveDuplicatesFromSortedListII.java) | | +| 83 | [Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list) | [![Java](assets/java.png)](src/RemoveDuplicatesFromSortedList.java) [![Python](assets/python.png)](python/remove_duplicates_from_linked_list.py) | | +| 86 | [Partition List](https://leetcode.com/problems/partition-list) | [![Java](assets/java.png)](src/PartitionList.java) | | +| 87 | [Scramble String](https://leetcode.com/problems/scramble-string) | [![Python](assets/python.png)](python/scramble_strings.py) | | +| 88 | [Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array) | [![Java](assets/java.png)](src/MergeSortedArray.java) [![Python](assets/python.png)](python/merge_sorted_array.py) | | +| 89 | [Gray Code](https://leetcode.com/problems/gray-code) | [![Java](assets/java.png)](src/GrayCode.java) | | +| 90 | [Subsets II](https://leetcode.com/problems/subsets-ii) | [![Java](assets/java.png)](src/SubsetsII.java) | | +| 91 | [Decode Ways](https://leetcode.com/problems/decode-ways) | [![Java](assets/java.png)](src/DecodeWays.java) | | +| 92 | [Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii) | [![Java](assets/java.png)](src/ReverseLinkedListII.java) | | +| 93 | [Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses) | [![Java](assets/java.png)](src/RestoreIPAddresses.java) | | +| 94 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal) | [![Java](assets/java.png)](src/BinaryTreeInorderTraversal.java) [![Python](assets/python.png)](python/binary_tree_inorder_traversal.py) | | +| 95 | [Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii) | [![Java](assets/java.png)](src/UniqueBinarySearchTreesII.java) | | +| 96 | [Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees) | [![Java](assets/java.png)](src/UniqueBinarySearchTrees.java) | | +| 97 | [Interleaving String](https://leetcode.com/problems/interleaving-string) | [![Java](assets/java.png)](src/InterleavingString.java) | | +| 98 | [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree) | [![Java](assets/java.png)](src/ValidateBinarySearchTree.java) | | +| 99 | [Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree) | [![Java](assets/java.png)](src/RecoverBinarySearchTree.java) | | +| 100 | [Same Tree](https://leetcode.com/problems/same-tree) | [![Java](assets/java.png)](src/SameTree.java) [![Python](assets/python.png)](python/same_tree.py) | | +| 101 | [Symmetric Tree](https://leetcode.com/problems/symmetric-tree) | [![Java](assets/java.png)](src/SymmetricTree.java) [![Python](assets/python.png)](python/symmetric_tree.py) | | +| 102 | [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal) | [![Java](assets/java.png)](src/BinaryTreeLevelOrderTraversal.java) | | +| 103 | [Binary Tree Zigzag Level Order Traversal](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal) | [![Java](assets/java.png)](src/BinaryTreeZigzagLevelOrderTraversal.java) | | +| 104 | [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree) | [![Java](assets/java.png)](src/MaximumDepthOfBinaryTree.java) [![Python](assets/python.png)](python/maximum_depth_of_binary_tree.py) | | +| 105 | [Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal) | [![Java](assets/java.png)](src/ConstructBinaryTreeFromPreorderAndInorderTraversal.java) | | +| 106 | [Construct Binary Tree from Inorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal) | [![Java](assets/java.png)](src/ConstructBinaryTreeFromInorderAndPostorderTraversal.java) | | +| 107 | [Binary Tree Level Order Traversal II](https://leetcode.com/problems/binary-tree-level-order-traversal-ii) | [![Java](assets/java.png)](src/BinaryTreeLevelOrderTraversalII.java) [![Python](assets/python.png)](python/binary_tree_level_order_traversal_ii.py) | | +| 108 | [Convert Sorted Array To Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree) | [![Java](assets/java.png)](src/ConvertSortedArrayToBinarySearchTree.java) [![Python](assets/python.png)](python/converted_sorted_array_to_binary_search_tree.py) | | +| 109 | [Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree) | [![Java](assets/java.png)](src/ConvertSortedListToBinarySearchTree.java) | | +| 110 | [Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree) | [![Java](assets/java.png)](src/BalancedBinaryTree.java) [![Python](assets/python.png)](python/balanced_binary_tree.py) | | +| 111 | [Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree) | [![Java](assets/java.png)](src/MinimumDepthOfBinaryTree.java) [![Python](assets/python.png)](python/minimum_depth_of_binary_tree.py) | | +| 112 | [Path Sum](https://leetcode.com/problems/path-sum) | [![Java](assets/java.png)](src/PathSum.java) [![Python](assets/python.png)](python/path_sum.py) | | +| 113 | [Path Sum II](https://leetcode.com/problems/path-sum-ii) | [![Java](assets/java.png)](src/PathSumII.java) | | +| 114 | [Flatten Binary Tree to Linked List](https://leetcode.com/problems/flatten-binary-tree-to-linked-list) | [![Java](assets/java.png)](src/FlattenBinaryTreeToLinkedList.java) | | +| 116 | [Populating Next Right Pointers in Each Node](https://leetcode.com/problems/populating-next-right-pointers-in-each-node) | [![Java](assets/java.png)](src/PopulatingNextRightPointersInEachNode.java) | | +| 117 | [Populating Next Right Pointers in Each Node II](https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii) | [![Java](assets/java.png)](src/PopulatingNextRightPointersInEachNodeII.java) | | +| 118 | [Pascal's Triangle](https://leetcode.com/problems/pascals-triangle) | [![Java](assets/java.png)](src/PascalsTriangle.java) [![Python](assets/python.png)](python/pascals_triangle.py) | | +| 119 | [Pascal's Triangle II](https://leetcode.com/problems/pascals-triangle-ii) | [![Java](assets/java.png)](src/PascalsTriangleII.java) [![Python](assets/python.png)](python/pascals_triangle_ii.py) | | +| 120 | [Triangle](https://leetcode.com/problems/triangle) | [![Java](assets/java.png)](src/Triangle.java) | | +| 121 | [Best Time to Buy and Sell Stocks](https://leetcode.com/problems/best-time-to-buy-and-sell-stock) | [![Java](assets/java.png)](src/BestTimeToBuyAndSellStock.java) [![Python](assets/python.png)](python/best_time_to_buy_and_sell_stock.py) | | +| 122 | [Best Time to Buy and Sell Stocks II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii) | [![Java](assets/java.png)](src/BestTimeToBuyAndSellStockII.java) [![Python](assets/python.png)](python/best_time_to_buy_and_sell_stock_ii.py) | | +| 123 | [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum) | [![Java](assets/java.png)](src/BinaryTreeMaximumPathSum.java) | | +| 125 | [Valid Palindrome](https://leetcode.com/problems/valid-palindrome) | [![Java](assets/java.png)](src/ValidPalindrome.java) [![Python](assets/python.png)](python/valid_palindrome.py) | | +| 127 | [Word Ladder](https://leetcode.com/problems/word-ladder) | [![Java](assets/java.png)](src/WordLadder.java) | | +| 128 | [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence) | [![Java](assets/java.png)](src/LongestConsecutiveSequence.java) | | +| 129 | [Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers) | [![Java](assets/java.png)](src/SumRootToLeafNumbers.java) | | +| 130 | [Surrounded Regions](https://leetcode.com/problems/surrounded-regions) | [![Java](assets/java.png)](src/SurroundedRegions.java) | | +| 131 | [Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning) | [![Java](assets/java.png)](src/PalindromePartitioning.java) | | +| 133 | [Clone Graph](https://leetcode.com/problems/clone-graph) | [![Java](assets/java.png)](src/CloneGraph.java) [![Python](assets/python.png)](python/clone_graph.py) | | +| 134 | [Gas Station](https://leetcode.com/problems/gas-station) | [![Java](assets/java.png)](src/GasStation.java) | | +| 135 | [Candy](https://leetcode.com/problems/candy) | [![Java](assets/java.png)](src/Candy.java) | | +| 136 | [Single Number](https://leetcode.com/problems/single-number) | [![Java](assets/java.png)](src/SingleNumber.java) [![Python](assets/python.png)](python/single_number.py) | | +| 137 | [Single Number II](https://leetcode.com/problems/single-number-ii) | [![Java](assets/java.png)](src/SingleNumberII.java) | | +| 138 | [Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer) | [![Java](assets/java.png)](src/CopyListWithRandomPointer.java) | | +| 139 | [Word Break](https://leetcode.com/problems/word-break) | [![Java](assets/java.png)](src/WordBreak.java) | | +| 141 | [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle) | [![Java](assets/java.png)](src/LinkedListCycle.java) [![Python](assets/python.png)](python/linked_list_cycle.py) | | +| 142 | [Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii) | [![Java](assets/java.png)](src/LinkedListCycleII.java) | | +| 143 | [Reorder List](https://leetcode.com/problems/reorder-list) | [![Java](assets/java.png)](src/ReorderList.java) | | +| 144 | [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal) | [![Java](assets/java.png)](src/BinaryTreePreOrderTraversal.java) [![Python](assets/python.png)](python/binary_tree_preorder_traversal.py) | | +| 145 | [Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal) | [![Java](assets/java.png)](src/BinaryTreePostorderTraversal.java) [![Python](assets/python.png)](python/binary_tree_postorder_traversal.py) | | +| 146 | [LRU Cache](https://leetcode.com/problems/lru-cache) | [![Java](assets/java.png)](src/LRUCache.java) | | +| 147 | [Insertion Sort List](https://leetcode.com/problems/insertion-sort-list) | [![Java](assets/java.png)](src/InsertionSortList.java) | | +| 148 | [Sort List](https://leetcode.com/problems/sort-list) | [![Java](assets/java.png)](src/SortList.java) | | +| 150 | [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation) | [![Java](assets/java.png)](src/EvaluateReversePolishNotation.java) | | +| 151 | [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string) | [![Java](assets/java.png)](src/ReverseWordsInAString.java) | | +| 152 | [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray) | [![Java](assets/java.png)](src/MaximumProductSubarray.java) | | +| 153 | [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array) | [![Java](assets/java.png)](src/FindMinimumInRotatedSortedArray.java) | | +| 155 | [Min Stack](https://leetcode.com/problems/min-stack) | [![Java](assets/java.png)](src/MinStack.java) [![Python](assets/python.png)](python/min_stack.py) | | +| 156 | 🔒 [Binary Tree Upside Down](https://leetcode.com/problems/binary-tree-upside-down) | | | +| 157 | 🔒 [Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4) | [![Java](assets/java.png)](src/ReadNCharactersGivenRead4java) | | +| 159 | 🔒 [Longest Substring With At Most Two Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters) | | | +| 160 | [Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists) | [![Java](assets/java.png)](src/IntersectionOf2LinkedLists.java) [![Python](assets/python.png)](python/intersecction_of_two_linked_lists.py) | | +| 161 | 🔒 [One Edit Distance](https://leetcode.com/problems/one-edit-distance) | | | +| 162 | [Find Peak Element](https://leetcode.com/problems/find-peak-element) | [![Java](assets/java.png)](src/FindPeakElement.java) | | +| 163 | [Missing Ranges](https://leetcode.com/problems/missing-ranges) | [![Java](assets/java.png)](src/MissingRanges.java) | | +| 164 | [Maximum Gap](https://leetcode.com/problems/maximum-gap) | | | +| 165 | [Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers) | [![Java](assets/java.png)](src/CompareVersionNumbers.java) | | +| 166 | [Fraction to Recurring Decimal](https://leetcode.com/problems/fraction-to-recurring-decimal) | [![Java](assets/java.png)](src/FractionToRecurringDecimal.java) | | +| 167 | [Two Sum II - Input Array is Sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted) | [![Java](assets/java.png)](src/TwoSumIIInputArrayIsSorted.java) [![Python](assets/python.png)](python/two_sum_ii.py) | | +| 168 | [Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title) | [![Java](assets/java.png)](src/ExcelSheetColumnTitle.java) [![Python](assets/python.png)](python/excel_sheet_column_title.py) | | +| 169 | [Majority Element](https://leetcode.com/problems/majority-element) | [![Java](assets/java.png)](src/MajorityElement.java) [![Python](assets/python.png)](python/majority_element.py) | | +| 170 | 🔒 [Two Sum III - Data Structure Design](https://leetcode.com/problems/two-sum-iii-data-structure-design) | [![Java](assets/java.png)](src/TwoSumIIIDataStructureDesign.java) | | +| 171 | [Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number) | [![Java](assets/java.png)](src/ExcelSheetColumnNumber.java) [![Python](assets/python.png)](python/excel_sheet_column_number.py) | | +| 172 | [Factoring Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes) | [![Java](assets/java.png)](src/FactorialTrailingZeros.java) [![Python](assets/python.png)](python/factorial_trailing_zeroes.py) | | +| 173 | [Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator) | [![Java](assets/java.png)](src/BinarySearchTreeIterator.java) | | +| 179 | [Largest Number](https://leetcode.com/problems/largest-number) | [![Java](assets/java.png)](src/LargestNumber.java) | | +| 187 | [Repeated DNA Sequences](https://leetcode.com/problems/repeated-dna-sequences) | [![Java](assets/java.png)](src/RepeatedDNASequences.java) | | +| 189 | [Rotate Array](https://leetcode.com/problems/rotate-array) | [![Java](assets/java.png)](src/RotateArray.java) [![Python](assets/python.png)](python/rotate_array.py) | | +| 190 | [Reverse Bits](https://leetcode.com/problems/reverse-bits) | [![Java](assets/java.png)](src/ReverseBits.java) [![Python](assets/python.png)](python/reverse_bits.py) | | +| 191 | [Number of One Bits](https://leetcode.com/problems/number-of-1-bits) | [![Java](assets/java.png)](src/NumberOf1Bit.java) [![Python](assets/python.png)](python/number_of_1_bits.py) | | +| 198 | [House Robber](https://leetcode.com/problems/house-robber) | [![Java](assets/java.png)](src/HouseRobber.java) [![Python](assets/python.png)](python/house_robber.py) | | +| 199 | [Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view) | [![Java](assets/java.png)](src/BinaryTreeRightSideView.java) | | +| 200 | [Number of Islands](https://leetcode.com/problems/number-of-islands) | [![Java](assets/java.png)](src/NumberOfIslands.java) [![Python](assets/python.png)](python/number_of_islands.py) | | +| 201 | [Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range) | [![Java](assets/java.png)](src/BitwiseANDOfNumbersRange.java) | | +| 202 | [Happy Number](https://leetcode.com/problems/happy-number) | [![Java](assets/java.png)](src/HappyNumber.java) [![Python](assets/python.png)](python/happy_number.py) | | +| 203 | [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements) | [![Java](assets/java.png)](src/RemoveLinkedListElements.java) [![Python](assets/python.png)](python/remove_linked_list_elements.py) | | +| 204 | [Count Primes](https://leetcode.com/problems/count-primes) | [![Java](assets/java.png)](src/CountPrimes.java) [![Python](assets/python.png)](python/count_primes.py) | | +| 205 | [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings) | [![Java](assets/java.png)](src/IsomorphicStrings.java) [![Python](assets/python.png)](python/isomorphic_strings.py) | | +| 206 | [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list) | [![Java](assets/java.png)](src/ReverseLinkedList.java) [![Python](assets/python.png)](python/reverse_linked_list.py) | | +| 207 | [Course Schedule](https://leetcode.com/problems/course-schedule) | [![Java](assets/java.png)](src/CourseSchedule.java) | | +| 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree) | [![Java](assets/java.png)](src/Trie.java) [![Python](assets/python.png)](python/trie.py) | | +| 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum) | [![Java](assets/java.png)](src/MinimumSizeSubarraySum.java) | | +| 210 | [Course Schedule II](https://leetcode.com/problems/course-schedule-ii) | [![Java](assets/java.png)](src/CourseScheduleII.java) | | +| 211 | [Design Add and Search Words Data Structure](https://leetcode.com/problems/design-add-and-search-words-data-structure) | [![Java](assets/java.png)](src/DesignAddAndSearchWordsDataStructure.java) [![Python](assets/python.png)](python/design_add_and_search_words_data_structure.py) | | +| 213 | [House Robber II](https://leetcode.com/problems/house-robber-ii) | [![Java](assets/java.png)](src/HouseRobberII.java) | | +| 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array) | [![Java](assets/java.png)](src/KthLargestElementInAnArray.java) | | +| 216 | [Combination Sum III](https://leetcode.com/problems/combination-sum-iii) | [![Java](assets/java.png)](src/CombinationSumIII.java) | | +| 217 | [Contains Duplicate](https://leetcode.com/problems/contains-duplicate) | [![Java](assets/java.png)](src/ContainsDuplicate.java) [![Python](assets/python.png)](python/contains_duplicate.py) | | +| 218 | [The Skyline Problem](https://leetcode.com/problems/the-skyline-problem) | [![Python](assets/python.png)](python/the_skyline_problem.py) | | +| 219 | [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii) | [![Java](assets/java.png)](src/ContainsDuplicateII.java) [![Python](assets/python.png)](python/contains_duplicate_ii.py) | | +| 220 | [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii) | [![Java](assets/java.png)](src/ContainsDuplicateIII.java) | | +| 221 | [Maximal Square](https://leetcode.com/problems/maximal-square) | [![Java](assets/java.png)](src/MaximalSquare.java) | | +| 222 | [Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes) | [![Java](assets/java.png)](src/CountCompleteTreeNodes.java) | | +| 223 | [Rectangle Area](https://leetcode.com/problems/rectangle-area) | [![Java](assets/java.png)](src/RectangleArea.java) | | +| 224 | [Basic Calculator](https://leetcode.com/problems/basic-calculator) | [![Java](assets/java.png)](src/BasicCalculator.java) | | +| 225 | [Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues) | [![Java](assets/java.png)](src/MyStack.java) [![Python](assets/python.png)](python/implement_stack_using_queues.py) | | +| 226 | [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree) | [![Java](assets/java.png)](src/InvertBinaryTree.java) [![Python](assets/python.png)](python/invert_binary_tree.py) | | +| 227 | [Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii) | [![Java](assets/java.png)](src/BasicCalculatorII.java) | | +| 229 | [Majority Element II](https://leetcode.com/problems/majority-element-ii) | [![Java](assets/java.png)](src/MajorityElementII.java) | | +| 230 | [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst) | [![Java](assets/java.png)](src/KthSmallestElementInABST.java) | | +| 231 | [Power of Two](https://leetcode.com/problems/power-of-two) | [![Java](assets/java.png)](src/PowerOf2.java) [![Python](assets/python.png)](python/is_power_of_2.py) | | +| 232 | [Implement Queue Using Stacks](https://leetcode.com/problems/implement-queue-using-stacks) | [![Java](assets/java.png)](src/MyQueue.java) [![Python](assets/python.png)](python/implement_queue_using_stacks.py) | | +| 234 | [Palindrome Linked Lists](https://leetcode.com/problems/palindrome-linked-list) | [![Java](assets/java.png)](src/PalindromeLinkedList.java) [![Python](assets/python.png)](python/palindrome_linked_list.py) | | +| 235 | [Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree) | [![Java](assets/java.png)](src/LowestCommonAncestorOfBinarySearchTree.java) [![Python](assets/python.png)](python/lowest_common_ancestor_of_bst.py) | | +| 236 | [Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree) | [![Java](assets/java.png)](src/LowestCommonAncestorOfBinaryTree.java) | | +| 237 | [Delete a Node In A Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list) | [![Java](assets/java.png)](src/DeleteANodeInLinkedList.java) [![Python](assets/python.png)](python/delete_node_in_linked_list.py) | | +| 238 | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self) | [![Java](assets/java.png)](src/ProductOfArrayExceptItself.java) | | +| 240 | [Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii) | [![Java](assets/java.png)](src/SearchA2DMatrixII.java) | | +| 241 | [Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses) | | | +| 242 | [Valid Anagram](https://leetcode.com/problems/valid-anagram) | [![Java](assets/java.png)](src/ValidAnagram.java) [![Python](assets/python.png)](python/delete_node_in_linked_list.py) | | +| 243 | 🔒 [Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance) | [![Java](assets/java.png)](src/ShortestWordDistance.java) | | +| 244 | 🔒 [Shortest Word Distance II](https://leetcode.com/problems/shortest-word-distance-ii) | | | +| 245 | 🔒 [Shortest Word Distance III](https://leetcode.com/problems/shortest-word-distance-iii) | | | +| 246 | 🔒 [Strobogrammatic Number](https://leetcode.com/problems/strobogrammatic-number) | [![Java](assets/java.png)](src/StrobogrammaticNumber.java) | | +| 247 | 🔒 [Strobogrammatic Number II](https://leetcode.com/problems/strobogrammatic-number-ii) | | | +| 249 | 🔒 [Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings) | | | +| 250 | 🔒 [Count Univalue Subtrees](https://leetcode.com/problems/count-univalue-subtrees) | | | +| 251 | 🔒 [Flatten 2D Vector](https://leetcode.com/problems/flatten-2d-vector) | | | +| 252 | 🔒 [Meeting Rooms](https://leetcode.com/problems/meeting-rooms) | [![Java](assets/java.png)](src/MeetingRooms.java) | | +| 253 | 🔒 [Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii) | | | +| 254 | 🔒 [Factor Combinations](https://leetcode.com/problems/factor-combinations) | | | +| 255 | 🔒 [Verify Preorder Sequence In Binary Search Tree](https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree) | | | +| 256 | 🔒 [Paint House](https://leetcode.com/problems/paint-house) | | | +| 257 | [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths) | [![Java](assets/java.png)](src/BinaryTreePaths.java) [![Python](assets/python.png)](python/binary_tree_paths.py) | | +| 258 | [Add Digits](https://leetcode.com/problems/add-digits) | [![Java](assets/java.png)](src/AddDigits.java) [![Python](assets/python.png)](python/add_digits.py) | | +| 259 | 🔒 [3Sum Smaller](https://leetcode.com/problems/3sum-smaller) | | | +| 260 | [Single Number III](https://leetcode.com/problems/single-number-iii) | [![Java](assets/java.png)](src/SingleNumberIII.java) | | +| 261 | 🔒 [Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree) | [![Java](assets/java.png)](src/GraphValidTree.java) | | +| 263 | [Ugly Number](https://leetcode.com/problems/ugly-number) | [![Java](assets/java.png)](src/UglyNumber.java) [![Python](assets/python.png)](python/ugly_number.py) | | +| 264 | [Ugly Number II](https://leetcode.com/problems/ugly-number-ii) | [![Java](assets/java.png)](src/UglyNumberII.java) | | +| 266 | 🔒 [Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation) | [![Java](assets/java.png)](src/PalindromePermutation.java) | | +| 267 | 🔒 [Palindrome Permutation II](https://leetcode.com/problems/palindrome-permutation-ii) | | | +| 268 | [Missing Number](https://leetcode.com/problems/missing-number) | [![Java](assets/java.png)](src/MissingNumber.java) [![Python](assets/python.png)](python/missing_number.py) | | +| 269 | [Alien Dictionary](https://leetcode.com/problems/alien-dictionary) | [![Java](assets/java.png)](src/AlienDictionary.java) | | +| 270 | 🔒 [Closest Binary Search Tree Value](https://leetcode.com/problems/closest-binary-search-tree-value) | [![Java](assets/java.png)](src/ClosestBinaryTreeSearchValue.java) | | +| 271 | 🔒 [Encode and Decode Strings](https://leetcode.com/problems/encode-and-decode-strings) | | | +| 274 | [H-Index](https://leetcode.com/problems/h-index) | [![Java](assets/java.png)](src/HIndex.java) | | +| 275 | [H-Index II](https://leetcode.com/problems/h-index-ii) | [![Java](assets/java.png)](src/HIndexII.java) | | +| 276 | 🔒 [Paint Fence](https://leetcode.com/problems/paint-fence) | | | +| 277 | 🔒 [Find The Celebrity](https://leetcode.com/problems/find-the-celebrity) | | | +| 278 | [First Bad Version](https://leetcode.com/problems/first-bad-version) | [![Java](assets/java.png)](src/FirstBadVersion.java) [![Python](assets/python.png)](python/first_bad_version.py) | | +| 279 | [Perfect Squares](https://leetcode.com/problems/perfect-squares) | [![Java](assets/java.png)](src/PerfectSquares.java) | | +| 280 | 🔒 [Wiggle Sort](https://leetcode.com/problems/wiggle-sort) | | | +| 281 | 🔒 [Zigzag Iterator](https://leetcode.com/problems/zigzag-iterator) | | | +| 283 | [Move Zeroes](https://leetcode.com/problems/move-zeroes) | [![Java](assets/java.png)](src/MoveZeros.java) [![Python](assets/python.png)](python/move_zeroes.py) | | +| 284 | [Peeking Iterator](https://leetcode.com/problems/peeking-iterator) | [![Java](assets/java.png)](src/PeekingIterator.java) | | +| 285 | 🔒 [Inorder Successor in BST](https://leetcode.com/problems/inorder-successor-in-bst) | | | +| 286 | 🔒 [Walls and Gates](https://leetcode.com/problems/walls-and-gates) | | | +| 287 | [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number) | [![Java](assets/java.png)](src/FindTheDuplicateNumber.java) | | +| 288 | 🔒 [Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation) | | | +| 289 | [Game of Life](https://leetcode.com/problems/game-of-life) | | | +| 290 | [Word Pattern](https://leetcode.com/problems/word-pattern) | [![Java](assets/java.png)](src/WordPattern.java) [![Python](assets/python.png)](python/word_pattern.py) | | +| 291 | 🔒 [Word Pattern II](https://leetcode.com/problems/word-pattern-ii) | | | +| 292 | [Nim Game](https://leetcode.com/problems/nim-game) | [![Java](assets/java.png)](src/NimGame.java) [![Python](assets/python.png)](python/nim_game.py) | | +| 293 | 🔒 [Flip Game](https://leetcode.com/problems/flip-game) | [![Java](assets/java.png)](src/FlipGame.java) | | +| 294 | 🔒 [Flip Game II](https://leetcode.com/problems/flip-game-ii) | | | +| 298 | 🔒 [Binary Tree Longest Consecutive Sequence](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence) | | | +| 299 | [Bulls and Cows](https://leetcode.com/problems/bulls-and-cows) | [![Java](assets/java.png)](src/BullsAndCows.java) [![Python](assets/python.png)](python/bulls_and_cows.py) | | +| 300 | [Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence) | [![Java](assets/java.png)](src/LongestIncreasingSubsequence.java) | | +| 303 | [Range Sum Query - Immutable](https://leetcode.com/problems/range-sum-query-immutable) | [![Java](assets/java.png)](src/RangeSumQueryImmutable.java) [![Python](assets/python.png)](python/range_sum_query_immutable.py) | | +| 304 | [Range Sum Query 2D - Immutable](https://leetcode.com/problems/range-sum-query-2d-immutable) | | | +| 306 | [Additive Number](https://leetcode.com/problems/additive-number) | | | +| 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable) | | | +| 309 | [Best Time to Buy and Sell Stock with Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown) | | | +| 310 | [Minimum Height Trees](https://leetcode.com/problems/minimum-height-trees) | [![Java](assets/java.png)](src/MinimumHeightTrees.java) | | +| 311 | 🔒 [Sparse Matrix Multiplication](https://leetcode.com/problems/sparse-matrix-multiplication) | | | +| 313 | [Super Ugly Number](https://leetcode.com/problems/super-ugly-number) | | | +| 314 | 🔒 [Binary Tree Vertical Order Traversal](https://leetcode.com/problems/binary-tree-vertical-order-traversal) | | | +| 316 | [Remove Duplicate Letters](https://leetcode.com/problems/remove-duplicate-letters) | | | +| 318 | [Maximum Product of Word Lengths](https://leetcode.com/problems/maximum-product-of-word-lengths) | | | +| 319 | [Bulb Switcher](https://leetcode.com/problems/bulb-switcher) | | | +| 320 | 🔒 [Generalized Abbreviation](https://leetcode.com/problems/generalized-abbreviation) | | | +| 322 | [Coin Change](https://leetcode.com/problems/coin-change) | | | +| 323 | 🔒 [Number of Connected Components in Undirected Graph](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph) | [![Java](assets/java.png)](src/NumberOfConnectedComponentsInAnUndirectedGraph.java) | | +| 324 | [Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii) | | | +| 325 | 🔒 [Maximum Size Subarray Sum Equals K](https://leetcode.com/problems/maximum-size-subarray-sum-equals-k) | | | +| 326 | [Power of Three](https://leetcode.com/problems/power-of-three) | [![Java](assets/java.png)](src/PowerOfThree.java) [![Python](assets/python.png)](python/power_of_three.py) | | +| 328 | [Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list) | | | +| 331 | [Verify Preorder Serialization of a Binary Tree](https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree) | | | +| 331 | 🔒 [Largest BST Subtree](https://leetcode.com/problems/largest-bst-subtree) | | | +| 332 | [Reconstruct Itinerary](https://leetcode.com/problems/reconstruct-itinerary) | [![Java](assets/java.png)](src/ReconstructItinerary.java) | | +| 334 | [Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence) | | | +| 337 | [House Robber III](https://leetcode.com/problems/increasing-triplet-subsequence) | | | +| 338 | [Counting Bits](https://leetcode.com/problems/counting-bits/) | [![Java](assets/java.png)](src/CountingBits.java) [![Python](assets/python.png)](python/counting_bits.py) | | +| 339 | 🔒 [Nested List Weight Sum](https://leetcode.com/problems/nested-list-weight-sum) | | | +| 340 | 🔒 [Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters) | | | +| 341 | [Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator) | | | +| 342 | [Power of Four](https://leetcode.com/problems/power-of-four) | [![Java](assets/java.png)](src/PowerOf4.java) [![Python](assets/python.png)](python/power_of_four.py) | | +| 343 | [Integer Break](https://leetcode.com/problems/integer-break) | | | +| 344 | [Reverse A String](https://leetcode.com/problems/reverse-string) | [![Java](assets/java.png)](src/ReverseString.java) [![Python](assets/python.png)](python/reverse_a_string.py) | | +| 345 | [Reverse Vowels of A String](https://leetcode.com/problems/reverse-vowels-of-a-string) | [![Java](assets/java.png)](src/ReverseVowelsOfString.java) [![Python](assets/python.png)](python/reverse_vowels_of_a_string.py) | | +| 346 | 🔒 [Moving Average From Data Stream](https://leetcode.com/problems/moving-average-from-data-stream) | [![Java](assets/java.png)](src/MovingAverageFromDataStream.java) | | +| 347 | [Top K frequent Elements](https://leetcode.com/problems/top-k-frequent-elements) | | | +| 348 | 🔒 [Design Tic-Tac-Toe](https://leetcode.com/problems/design-tic-tac-toe) | | | +| 349 | [Intersection of 2 Arrays](https://leetcode.com/problems/intersection-of-two-arrays) | [![Java](assets/java.png)](src/IntersectionOfTwoArrays.java) [![Python](assets/python.png)](python/intersection_of_2_array.py) | | +| 350 | [Intersection of 2 Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii) | [![Java](assets/java.png)](src/IntersectionOfTwoArraysII.java) [![Python](assets/python.png)](python/intersection_of_2_arrays_II.py) | | +| 351 | 🔒 [Android Unlock Patterns](https://leetcode.com/problems/android-unlock-patterns) | | | +| 355 | [Design Twitter](https://leetcode.com/problems/design-twitter) | | | +| 357 | [Count Numbers with Unique Digits](https://leetcode.com/problems/count-numbers-with-unique-digits) | | | +| 359 | 🔒 [Logger Rate Limiter](https://leetcode.com/problems/logger-rate-limiter) | [![Java](assets/java.png)](src/LoggerRateLimiter.java) | | +| 367 | [Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square) | [![Java](assets/java.png)](src/ValidPerfectSquare.java) [![Python](assets/python.png)](python/valid_perfect_square.py) | | +| 374 | [Guess Number Higher or Lower](https://leetcode.com/problems/guess-number-higher-or-lower) | [![Java](assets/java.png)](src/GuessNumberHigherOrLower.java) [![Python](assets/python.png)](python/guess_number_higher_or_lower.py) | | +| 380 | [Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1) | [![Java](assets/java.png)](src/InsertDeleteGetRandomO1.java) | | +| 383 | [Ransom Note](https://leetcode.com/problems/ransom-note) | [![Java](assets/java.png)](src/RansomNote.java) [![Python](assets/python.png)](python/ransom_note.py) | | +| 387 | [First Unique Character in String](https://leetcode.com/problems/first-unique-character-in-a-string) | [![Java](assets/java.png)](src/FirstUniqueCharacter.java) [![Python](assets/python.png)](python/first_unique_character_in_string.py) | | +| 389 | [Find the Difference](https://leetcode.com/problems/find-the-difference) | [![Java](assets/java.png)](src/FindTheDifference.java) [![Python](assets/python.png)](python/find_the_difference.py) | | +| 392 | [Is Subsequence](https://leetcode.com/problems/is-subsequence) | [![Java](assets/java.png)](src/IsSubsequence.java) [![Python](assets/python.png)](python/is_subsequence.py) | | +| 399 | [Evaluate Division](https://leetcode.com/problems/evaluate-division) | [![Java](assets/java.png)](src/EvaluateDivision.java) | | +| 401 | [Binary Watch](https://leetcode.com/problems/binary-watch) | [![Java](assets/java.png)](src/BinaryWatch.java) [![Python](assets/python.png)](python/binary_watch.py) | | +| 404 | [Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves) | [![Java](assets/java.png)](src/SumOfLeftLeaves.java) [![Python](assets/python.png)](python/sum_of_left_leaves.py) | | +| 405 | [Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal) | [![Java](assets/java.png)](src/ConvertNumberToHexadecimal.java) [![Python](assets/python.png)](python/convert_a_number_to_hexadecimal.py) | | +| 408 | 🔒 [Valid Word Abbreviation](https://leetcode.com/problems/valid-word-abbreviation) | [![Java](assets/java.png)](src/ValidWordAbbreviation.java) | | +| 409 | [Longest Palindrome](https://leetcode.com/problems/longest-palindrome) | [![Java](assets/java.png)](src/LongestPalindrome.java) [![Python](assets/python.png)](python/longest_palindrome.py) | | +| 412 | [Fizz Buzz](https://leetcode.com/problems/fizz-buzz) | [![Java](assets/java.png)](src/FizzBuzz.java) [![Python](assets/python.png)](python/fizz_buzz.py) | | +| 414 | [Third Maximum Number](https://leetcode.com/problems/third-maximum-number) | [![Java](assets/java.png)](src/ThirdMaximumNumber.java) [![Python](assets/python.png)](python/fizz_buzz.py) | | +| 415 | [Add Strings](https://leetcode.com/problems/add-strings) | [![Java](assets/java.png)](src/AddString.java) [![Python](assets/python.png)](python/add_strings.py) | | +| 422 | 🔒 [Valid Word Square](https://leetcode.com/problems/valid-word-square) | | | +| 429 | 🔒 [N-ary Tree Level Order Traversal](https://leetcode.com/problems/n-ary-tree-level-order-traversal) | [![Java](assets/java.png)](src/NAryTreeLevelOrderTraversal.java) | | +| 430 | [Flatten a Multilevel Doubly Linked List](https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list) | [![Java](assets/java.png)](src/FlattenAMultiLevelDoublyLinkedList.java) | | +| 433 | [Minimum Genetic Mutation](https://leetcode.com/problems/minimum-genetic-mutation) | [![Java](assets/java.png)](src/MinimumGeneticMutation.java) | | +| 434 | [Number of Segments in a String](https://leetcode.com/problems/number-of-segments-in-a-string) | [![Java](assets/java.png)](src/NumberOfSegmentsInString.java) [![Python](assets/python.png)](python/number_of_segments_in_a_string.py) | | +| 441 | [Arranging Coins](https://leetcode.com/problems/arranging-coins) | [![Java](assets/java.png)](src/ArrangingCoins.java) [![Python](assets/python.png)](python/arranging_coins.py) | | +| 443 | [String Compression](https://leetcode.com/problems/string-compression) | [![Java](assets/java.png)](src/StringCompression.java) [![Python](assets/python.png)](python/string_compression.py) | | +| 447 | [Number of Boomerangs](https://leetcode.com/problems/number-of-boomerangs) | [![Java](assets/java.png)](src/NumberOfBoomerangs.java) [![Python](assets/python.png)](python/number_of_boomerangs.py) | | +| 448 | [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array) | [![Java](assets/java.png)](src/FindAllNumbersDisappearedInAnArray.java) [![Python](assets/python.png)](python/find_all_numbers_disappeared_in_an_array.py) | | +| 452 | [Minimum Number of Arrows to Burst Balloons](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons) | [![Java](assets/java.png)](src/MinimumNumberOfArrowsToBurstBalloons.java) | | +| 453 | [Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-moves-to-equal-array-elements) | [![Java](assets/java.png)](src/MinimumMovesToEqualArrayElements.java) [![Python](assets/python.png)](python/minimum_moves_to_equal_array_element.py) | | +| 455 | [Assign Cookies](https://leetcode.com/problems/assign-cookies) | [![Java](assets/java.png)](src/AssignCookies.java) [![Python](assets/python.png)](python/assign_cookies.py) | | +| 459 | [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern) | [![Java](assets/java.png)](src/RepeatedSubstringPattern.java) [![Python](assets/python.png)](python/repeated_substring_pattern.py) | | +| 461 | [Hamming Distance](https://leetcode.com/problems/hamming-distance) | [![Java](assets/java.png)](src/HammingDistance.java) [![Python](assets/python.png)](python/hamming_distance.py) | | +| 463 | [Island Perimeter](https://leetcode.com/problems/island-perimeter) | [![Java](assets/java.png)](src/IslandPerimeter.java) [![Python](assets/python.png)](python/island_perimeter.py) | | +| 475 | [Heaters](https://leetcode.com/problems/heaters) | [![Java](assets/java.png)](src/Heaters.java) [![Python](assets/python.png)](python/heaters.py) | | +| 476 | [Number Complement](https://leetcode.com/problems/number-complement) | [![Java](assets/java.png)](src/NumberComplement.java) [![Python](assets/python.png)](python/number_complement.py) | | +| 482 | [License Key Formatting](https://leetcode.com/problems/license-key-formatting) | [![Java](assets/java.png)](src/LicenseKeyFormatting.java) [![Python](assets/python.png)](python/license_key_formatting.py) | | +| 485 | [Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones) | [![Java](assets/java.png)](src/MaxConsecutiveOnes.java) [![Python](assets/python.png)](python/max_consecutive_ones.py) | | +| 492 | [Construct the Rectangle](https://leetcode.com/problems/construct-the-rectangle) | [![Java](assets/java.png)](src/ConstructTheRectangle.java) [![Python](assets/python.png)](python/construct_the_rectangle.py) | | +| 495 | [Teemo Attacking](https://leetcode.com/problems/teemo-attacking/) | [![Java](assets/java.png)](src/TeemoAttacking.java) [![Python](assets/python.png)](python/teemo_attacking.py) | | +| 496 | [Next Greater Element I](https://leetcode.com/problems/next-greater-element-i) | [![Java](assets/java.png)](src/NextGreaterElementI.java) [![Python](assets/python.png)](python/next_greater_element_i.py) | | +| 499 | [The Maze III](https://leetcode.com/problems/the-maze-iii) | [![Java](assets/java.png)](src/TheMazeIII.java) | | +| 500 | [Keyboard Row](https://leetcode.com/problems/keyboard-row) | [![Java](assets/java.png)](src/KeyBoardRow.java) [![Python](assets/python.png)](python/keyboard_row.py) | | +| 501 | [Find Mode in Binary Search Tree](https://leetcode.com/problems/find-mode-in-binary-search-tree) | [![Java](assets/java.png)](src/FindModeInBinarySearchTree.java) [![Python](assets/python.png)](python/find_mode_in_binary_search_tree.py) | | +| 504 | [Base 7](https://leetcode.com/problems/base-7) | [![Java](assets/java.png)](src/Base7.java) [![Python](assets/python.png)](python/base_7.py) | | +| 505 | [The Maze II](https://leetcode.com/problems/the-maze-ii) | [![Java](assets/java.png)](src/TheMazeII.java) | | +| 506 | [Relative Ranks](https://leetcode.com/problems/relative-ranks) | [![Java](assets/java.png)](src/RelativeRanks.java) [![Python](assets/python.png)](python/relative_ranks.py) | | +| 507 | [Perfect Number](https://leetcode.com/problems/perfect-number) | [![Java](assets/java.png)](src/CheckPerfectNumber.java) [![Python](assets/python.png)](python/check_perfect_number.py) | | +| 509 | [Fibonacci Number](https://leetcode.com/problems/fibonacci-number) | [![Java](assets/java.png)](src/FibonacciNumber.java) [![Python](assets/python.png)](python/fibonacci_number.py) | | +| 520 | [Detect Capital](https://leetcode.com/problems/detect-capital) | [![Java](assets/java.png)](src/DetectCapital.java) [![Python](assets/python.png)](python/detect_capital.py) | | +| 521 | [Longest Uncommon Subsequence I](https://leetcode.com/problems/longest-uncommon-subsequence-i) | [![Java](assets/java.png)](src/LongestUncommonSubsequenceI.java) [![Python](assets/python.png)](python/longest_uncommon_subsequence_I.py) | | +| 530 | [Minimum Absolute Difference in BST](https://leetcode.com/problems/minimum-absolute-difference-in-bst) | [![Java](assets/java.png)](src/MinimumAbsoluteDifferenceInBST.java) [![Python](assets/python.png)](python/minimum_absolute_difference_in_bst.py) | | +| 532 | [K - Diff Pairs in Array](https://leetcode.com/problems/k-diff-pairs-in-an-array) | [![Java](assets/java.png)](src/KDiffPairsInAnArray.java) [![Python](assets/python.png)](python/k_dif_pairs_in_an_array.py) | | +| 538 | [Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree) | [![Java](assets/java.png)](src/ConvertBSTToGreaterTree.java) [![Python](assets/python.png)](python/convert_bst_to_greater_tree.py) | | +| 541 | [Reverse String II](https://leetcode.com/problems/reverse-string-ii) | [![Java](assets/java.png)](src/ReverseStringII.java) [![Python](assets/python.png)](python/reverse_string_ii.py) | | +| 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree) | [![Java](assets/java.png)](src/DiameterOfBinaryTree.java) [![Python](assets/python.png)](python/diameter_of_binary_tree.py) | | +| 547 | [Number of Provinces](https://leetcode.com/problems/number-of-provinces) | [![Java](assets/java.png)](src/NumberOfProvinces.java) | | +| 551 | [Student Attendance Record I](https://leetcode.com/problems/student-attendance-record-i) | [![Java](assets/java.png)](src/StudentAttendanceRecordI.java) [![Python](assets/python.png)](python/student_attendance_record_I.py) | | +| 557 | [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii) | [![Java](assets/java.png)](src/ReverseWordsInStringIII.java) [![Python](assets/python.png)](python/reverse_words_in_string_iii.py) | | +| 559 | [Maximum Depth of N-Ary Tree](https://leetcode.com/problems/maximum-depth-of-n-ary-tree) | [![Java](assets/java.png)](src/MaximumDepthOfNAryTree.java) [![Python](assets/python.png)](python/maximum_depth_of_n_ary_tree.py) | | +| 561 | [Array Partition I](https://leetcode.com/problems/array-partition-i) | [![Java](assets/java.png)](src/ArrayPartitionI.java) [![Python](assets/python.png)](python/array_partiton_I.py) | | +| 563 | [Binary Tree Tilt](https://leetcode.com/problems/binary-tree-tilt) | [![Java](assets/java.png)](src/BinaryTreeTilt.java) [![Python](assets/python.png)](python/binary_tree_tilt.py) | | +| 566 | [Reshape The Matrix](https://leetcode.com/problems/reshape-the-matrix) | [![Java](assets/java.png)](src/ReshapeTheMatrix.java) [![Python](assets/python.png)](python/reshape_the_matrix.py) | | +| 572 | [Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree) | [![Java](assets/java.png)](src/SubtreeOfAnotherTree.java) [![Python](assets/python.png)](python/subtree_of_another_tree.py) | | +| 575 | [Distribute Candies](https://leetcode.com/problems/distribute-candies) | [![Java](assets/java.png)](src/DistributeCandies.java) [![Python](assets/python.png)](python/distribute_candies.py) | | +| 581 | [Shortest Unsorted Continuous Subarray](https://leetcode.com/problems/shortest-unsorted-continuous-subarray) | [![Java](assets/java.png)](src/ShortestUnsortedContinuousSubarray.java) [![Python](assets/python.png)](python/shortest_continuous_unsorted_subarray.py) | | +| 589 | [N-Ary Tree Preorder Traversal](https://leetcode.com/problems/n-ary-tree-preorder-traversal) | [![Java](assets/java.png)](src/NArayTreePreOrderTraversal.java) [![Python](assets/python.png)](python/n_ary_tree_preorder_traversal.py) | | +| 590 | [N-Ary Tree Postorder Traversal](https://leetcode.com/problems/n-ary-tree-postorder-traversal) | [![Java](assets/java.png)](src/NAryTreePostorderTraversal.java) [![Python](assets/python.png)](python/n_ary_tree_postorder_traversal.py) | | +| 594 | [Longest Harmonious Subsequence](https://leetcode.com/problems/longest-harmonious-subsequence) | [![Java](assets/java.png)](src/LongestHarmoniousSubsequence.java) [![Python](assets/python.png)](python/longest_harmonious_subequence.py) | | +| 598 | [Range Addition II](https://leetcode.com/problems/range-addition-ii) | [![Java](assets/java.png)](src/RangeAdditionII.java) [![Python](assets/python.png)](python/range_addition_ii.py) | | +| 599 | [Minimum Index Sum of 2 Lists](https://leetcode.com/problems/minimum-index-sum-of-two-lists) | [![Java](assets/java.png)](src/MinimumIndexSumOfTwoLists.java) [![Python](assets/python.png)](python/minimum_index_sum_of_two_lists.py) | | +| 604 | 🔒 [Design Compressed String Iterator](https://leetcode.com/problems/design-compressed-string-iterator) | | | +| 605 | [Can Place Flowers](https://leetcode.com/problems/can-place-flowers) | [![Java](assets/java.png)](src/CanPlaceFlowers.java) [![Python](assets/python.png)](python/can_place_flowers.py) | | +| 606 | [Construct String from Binary Tree](https://leetcode.com/problems/construct-string-from-binary-tree) | [![Java](assets/java.png)](src/ConstructStringFromBinaryTree.java) [![Python](assets/python.png)](python/construct_string_from_binary_tree.py) | | +| 617 | [Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees) | [![Java](assets/java.png)](src/MergeTwoBinaryTrees.java) [![Python](assets/python.png)](python/merge_two_binary_trees.py) | | +| 624 | 🔒 [Maximum Distance in Arrays](https://leetcode.com/problems/maximum-distance-in-arrays) | | | +| 628 | [Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers) | [![Java](assets/java.png)](src/MaximumProductOfThreeNumbers.java) [![Python](assets/python.png)](python/maximum_product_of_three_numbers.py) | | +| 633 | [Sum Square Numbers](https://leetcode.com/problems/sum-of-square-numbers) | [![Java](assets/java.png)](src/SumOfSquareNumbers.java) [![Python](assets/python.png)](python/sum_of_squares_numbers.py) | | +| 637 | [Average of Levels in Binary Tree](https://leetcode.com/problems/average-of-levels-in-binary-tree) | [![Java](assets/java.png)](src/AverageLevelsOfBinaryTree.java) [![Python](assets/python.png)](python/average_levels_of_binary_tree.py) | | +| 643 | [Maximum Average SubArray I](https://leetcode.com/problems/maximum-average-subarray-i) | [![Java](assets/java.png)](src/MaximumAverageSubArrayI.java) [![Python](assets/python.png)](python/maximum_average_subarray_I.py) | | +| 645 | [Set Mismatch](https://leetcode.com/problems/set-mismatch) | [![Java](assets/java.png)](src/SetMismatch.java) [![Python](assets/python.png)](python/set_mismatch.py) | | +| 653 | [Two Sum IV - Input is a BST](https://leetcode.com/problems/two-sum-iv-input-is-a-bst) | [![Java](assets/java.png)](src/TwoSumIVInputIsABST.java) [![Python](assets/python.png)](python/two_sum_iv.py) | | +| 657 | [Robot Return to Origin](https://leetcode.com/problems/robot-return-to-origin) | [![Java](assets/java.png)](src/RobotReturnToOrigin.java) [![Python](assets/python.png)](python/robot_return_to_origin.py) | | +| 658 | [Find K Closest Elements](https://leetcode.com/problems/find-k-closest-elements) | [![Java](assets/java.png)](src/FindKClosestElements.java) | | +| 661 | [Image Smoother](https://leetcode.com/problems/image-smoother) | [![Java](assets/java.png)](src/ImageSmoother.java) [![Python](assets/python.png)](python/image_smoother.py) | | +| 665 | [Non Deceasing Array](https://leetcode.com/problems/non-decreasing-array) | [![Java](assets/java.png)](src/NonDecreasingArray.java) [![Python](assets/python.png)](python/non_decreasing_array.py) | | +| 669 | [Trim a Binary Search Tree](https://leetcode.com/problems/trim-a-binary-search-tree) | [![Java](assets/java.png)](src/TrimABinarySearchTree.java) [![Python](assets/python.png)](python/trim_a_binary_search_tree.py) | | +| 671 | [Second Minimum Node in Binary Tree](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree) | [![Java](assets/java.png)](src/SecondMinimumNodeInBinaryTree.java) [![Python](assets/python.png)](python/second_minimum_node_in_binary_tree.py) | | +| 674 | [Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence) | [![Java](assets/java.png)](src/LongestContinuousIncreasingSubsequence.java) [![Python](assets/python.png)](python/longest_continuous_increasing_subsequence.py) | | +| 680 | [Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii) | [![Java](assets/java.png)](src/ValidPalindromeII.java) [![Python](assets/python.png)](python/valid_pallindrome_ii.py) | | +| 682 | [Baseball Game](https://leetcode.com/problems/baseball-game) | [![Java](assets/java.png)](src/BaseballGame.java) [![Python](assets/python.png)](python/baseball_game.py) | | +| 684 | [Redundant Connection](https://leetcode.com/problems/redundant-connection) | [![Java](assets/java.png)](src/RedundantConnection.java) | | +| 686 | [Repeated String Match](https://leetcode.com/problems/repeated-string-match) | | | +| 687 | [Longest Univalue Path](https://leetcode.com/problems/longest-univalue-path) | | | +| 688 | [Knight Probability in Chessboard](https://leetcode.com/problems/knight-probability-in-chessboard) | [![Java](assets/java.png)](src/KnightProbabilityInChessboard.java) | | +| 690 | [Employee Importance](https://leetcode.com/problems/employee-importance) | | | +| 693 | [Binary Number with Alternating Bits](https://leetcode.com/problems/binary-number-with-alternating-bits) | [![Java](assets/java.png)](src/BinaryNumberWithAlternatingBits.java) [![Python](assets/python.png)](python/binary_number_with_alternating_bits.py) | | +| 696 | [Count Binary Substrings](https://leetcode.com/problems/count-binary-substrings) | [![Java](assets/java.png)](src/CountBinarySubstrings.java) [![Python](assets/python.png)](python/count_binary_substrings.py) | | +| 697 | [Degree of an Array](https://leetcode.com/problems/degree-of-an-array) | [![Java](assets/java.png)](src/DegreeOfAnArray.java) [![Python](assets/python.png)](python/degree_of_an_array.py) | | +| 700 | [Search in a Binary Search Tree](https://leetcode.com/problems/search-in-a-binary-search-tree) | [![Java](assets/java.png)](src/SearchInBinarySearchTree.java) [![Python](assets/python.png)](python/search_in_binary_search_tree.py) | | +| 702 | [Search In A Sorted Array of Unknown Size](https://leetcode.com/problems/search-in-a-sorted-array-of-unknown-size) | [![Java](assets/java.png)](src/SearchInSortedArrayOfUnknownSize.java) | | +| 703 | [Kth Largest Element in a Stream](https://leetcode.com/problems/kth-largest-element-in-a-stream) | [![Java](assets/java.png)](src/KthLargestElementInAStream.java) [![Python](assets/python.png)](python/k_th_largest_element_in_a_stream.py) | | +| 704 | [Binary Search](https://leetcode.com/problems/binary-search) | [![Java](assets/java.png)](src/BinarySearch.java) [![Python](assets/python.png)](python/binary_search.py) | | +| 705 | [Design HashSet](https://leetcode.com/problems/design-hashset) | [![Java](assets/java.png)](src/DesignHashSet.java) [![Python](assets/python.png)](python/design_hash_set.py) | | +| 706 | [Design HashMap](https://leetcode.com/problems/design-hashmap) | [![Java](assets/java.png)](src/DesignHashMap.java) [![Python](assets/python.png)](python/design_hash_map.py) | | +| 709 | [To Lower Case](https://leetcode.com/problems/to-lower-case) | [![Java](assets/java.png)](src/ToLowerCase.java) [![Python](assets/python.png)](python/to_lower_case.py) | | +| 716 | 🔒 [Max Stack](https://leetcode.com/problems/max-stack) | | | +| 717 | [1-bit and 2-bit Characters](https://leetcode.com/problems/1-bit-and-2-bit-characters) | [![Java](assets/java.png)](src/OneBitAndTwoBitCharacters.java) [![Python](assets/python.png)](python/one_bit_and_two_bit_characters.py) | | +| 718 | [Maximum Length of Repeated Subarray](https://leetcode.com/problems/maximum-length-of-repeated-subarray) | [![Java](assets/java.png)](src/MaximumLengthOfRepeatedSubArray.java) | | +| 720 | [Longest Word in Dictionary](https://leetcode.com/problems/longest-word-in-dictionary) | | | +| 724 | [Find Pivot Index](https://leetcode.com/problems/find-pivot-index) | [![Java](assets/java.png)](src/FindPivotIndex.java) [![Python](assets/python.png)](python/find_pivot_index.py) | | +| 728 | [Self Dividing Numbers](https://leetcode.com/problems/self-dividing-numbers) | [![Java](assets/java.png)](src/SelfDividingNumbers.java) [![Python](assets/python.png)](python/self_dividing_number.py) | | +| 733 | [Flood Fill](https://leetcode.com/problems/flood-fill) | [![Java](assets/java.png)](src/FloodFill.java) [![Python](assets/python.png)](python/flood_fill.py) | | +| 734 | 🔒 [Sentence Similarity](https://leetcode.com/problems/sentence-similarity) | | | +| 743 | [Network Delay Time](https://leetcode.com/problems/network-delay-time) | [![Java](assets/java.png)](src/NetworkDelayTime.java) | | +| 734 | [Sentence Similarity](https://leetcode.com/problems/sentence-similarity) | | | +| 744 | [Find Smallest Letter Greater Than Target](https://leetcode.com/problems/find-smallest-letter-greater-than-target) | [![Java](assets/java.png)](src/FindSmallestLetterGreaterThanTarget.java) [![Python](assets/python.png)](python/find_smallest_letter_greater_than.py) | | +| 746 | [Min Cost Climbing Stairs](https://leetcode.com/problems/min-cost-climbing-stairs) | [![Java](assets/java.png)](src/MinCostClimbingStairs.java) [![Python](assets/python.png)](python/min_cost_climbing_stairs.py) | | +| 747 | [Largest Number at least Twice of Others](https://leetcode.com/problems/largest-number-at-least-twice-of-others) | [![Java](assets/java.png)](src/LargestNumberAtLeastTwiceOfOthers.java) [![Python](assets/python.png)](python/largest_number_at_least_twice_of_others.py) | | +| 748 | [Shortest Completing Word](https://leetcode.com/problems/shortest-completing-word) | [![Java](assets/java.png)](src/ShortestCompletingWord.java) [![Python](assets/python.png)](python/shortest_completing_word.py) | | +| 758 | [Bold Words in String](https://leetcode.com/problems/bold-words-in-string) | | | +| 760 | 🔒 [Find Anagram Mappings](https://leetcode.com/problems/find-anagram-mappings) | | | +| 762 | [Prime Number of Set Bits in Primary Representation](https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation) | [![Java](assets/java.png)](src/PrimeNumberOfSetBitsInBinaryRepresentation.java) [![Python](assets/python.png)](python/prime_number_of_set_bits_in_binary_representation.py) | | +| 766 | [Toeplitz Matrix](https://leetcode.com/problems/toeplitz-matrix) | [![Java](assets/java.png)](src/ToeplitzMatrix.java) [![Python](assets/python.png)](python/toeplitz_matrix.py) | | +| 771 | [Jewels and Stones](https://leetcode.com/problems/jewels-and-stones) | [![Java](assets/java.png)](src/JewelsAndStones.java) [![Python](assets/python.png)](python/jewels_and_stones.py) | | +| 783 | [Minimum Distance Between BST Nodes](https://leetcode.com/problems/minimum-distance-between-bst-nodes) | [![Java](assets/java.png)](src/MinimumAbsoluteDifferenceInBST.java) [![Python](assets/python.png)](python/minimum_distance_between_bst_nodes.py) | | +| 787 | [Cheapest Flights Within K Stops](https://leetcode.com/problems/cheapest-flights-within-k-stops) | [![Java](assets/java.png)](src/CheapestFlightsWithinKStops.java) | | +| 788 | [Rotated Digits](https://leetcode.com/problems/rotated-digits) | | | +| 796 | [Rotate String](https://leetcode.com/problems/rotate-string) | [![Java](assets/java.png)](src/RotateString.java) | | +| 797 | [All Paths From Source to Target](https://leetcode.com/problems/all-paths-from-source-to-target) | [![Java](assets/java.png)](src/AllPathsFromSourceToTarget.java) | | +| 800 | 🔒 [Similar RGB Color](https://leetcode.com/problems/similar-rgb-color) | | | +| 804 | [Unique Morse Code Words](https://leetcode.com/problems/unique-morse-code-words) | [![Java](assets/java.png)](src/UniqueMorseCodeWords.java) | | +| 806 | [Number of Lines to Write String](https://leetcode.com/problems/number-of-lines-to-write-string) | [![Java](assets/java.png)](src/NumberOfLinesToWriteInString.java) | | +| 811 | [Subdomain Visit Count](https://leetcode.com/problems/subdomain-visit-count) | | | +| 812 | [Largest Triangle Area](https://leetcode.com/problems/largest-triangle-area) | [![Java](assets/java.png)](src/LargestTriangleArea.java) | | +| 819 | [Most Common Word](https://leetcode.com/problems/most-common-word) | [![Java](assets/java.png)](src/MostCommonWord.java) | | +| 821 | [Shortest Distance to Character](https://leetcode.com/problems/shortest-distance-to-a-character) | [![Java](assets/java.png)](src/ShortestDistanceToACharacter.java) | | +| 824 | [Goat Latin](https://leetcode.com/problems/goat-latin) | [![Java](assets/java.png)](src/GoatLatin.java) | | +| 830 | [Positions of Large Groups](https://leetcode.com/problems/positions-of-large-groups) | [![Java](assets/java.png)](src/PositionsOfLargeGroups.java) | | +| 832 | [Flipping an Image](https://leetcode.com/problems/flipping-an-image) | [![Java](assets/java.png)](src/FlippingAnImage.java) | | +| 836 | [Rectangle Overlap](https://leetcode.com/problems/rectangle-overlap) | [![Java](assets/java.png)](src/RectangleOverlap.java) | | +| 840 | [Magic Squares in Grid](https://leetcode.com/problems/magic-squares-in-grid) | | | +| 844 | [Backspace String Compare](https://leetcode.com/problems/backspace-string-compare) | [![Java](assets/java.png)](src/BackspaceStringCompare.java) | | +| 849 | [Maximize Distance to Closest Person](https://leetcode.com/problems/maximize-distance-to-closest-person) | | | +| 852 | [Peak Index in Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array) | [![Java](assets/java.png)](src/PeakIndexInMountainArray.java) | | +| 859 | [Buddy Strings](https://leetcode.com/problems/buddy-strings) | [![Java](assets/java.png)](src/BuddyStrings.java) | | +| 860 | [Lemonade Change](https://leetcode.com/problems/lemonade-change) | [![Java](assets/java.png)](src/LemonadeChange.java) | | +| 867 | [Transpose Matrix](https://leetcode.com/problems/transpose-matrix) | [![Java](assets/java.png)](src/TransposeMatrix.java) | | +| 868 | [Binary Gap](https://leetcode.com/problems/binary-gap) | [![Java](assets/java.png)](src/BinaryGap.java) | | +| 872 | [Leaf-Similar Trees](https://leetcode.com/problems/leaf-similar-trees) | [![Java](assets/java.png)](src/LeafSimilarTrees.java) | | +| 874 | [Walking Robot Simulation](https://leetcode.com/problems/walking-robot-simulation) | | | +| 876 | [Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list) | [![Java](assets/java.png)](src/MiddleOfTheLinkedList.java) | | +| 881 | [Boats to Save People](https://leetcode.com/problems/boats-to-save-people) | [![Python](assets/python.png)](python/boats_to_save_people.py) | | +| 883 | [Projection Area of 3D Shapes](https://leetcode.com/problems/projection-area-of-3d-shapes) | [![Java](assets/java.png)](src/ProjectionAreaOf3DShapes.java) | | +| 884 | [Uncommon Words from 2 Sentences](https://leetcode.com/problems/uncommon-words-from-two-sentences) | [![Java](assets/java.png)](src/UncommonWordsFromTwoSentences.java) | | +| 888 | [Fair Candy Swap](https://leetcode.com/problems/fair-candy-swap) | [![Java](assets/java.png)](src/FairCandySwap.java) | | +| 892 | [Surface Area of 3D Shapes](https://leetcode.com/problems/surface-area-of-3d-shapes) | [![Java](assets/java.png)](src/SurfaceAreaOf3DShapes.java) | | +| 893 | [Groups of Special Equivalent Strings](https://leetcode.com/problems/groups-of-special-equivalent-strings) | | | +| 896 | [Monotonic Array](https://leetcode.com/problems/monotonic-array) | [![Java](assets/java.png)](src/MonotonicArray.java) | | +| 897 | [Increasing Order Search Tree](https://leetcode.com/problems/increasing-order-search-tree) | [![Java](assets/java.png)](src/IncreasingOrderSearchTree.java) | | +| 905 | [Sort Array by Parity](https://leetcode.com/problems/sort-array-by-parity) | | | +| 908 | [Smallest Range I](https://leetcode.com/problems/smallest-range-i) | [![Java](assets/java.png)](src/SmallestRangeI.java) | | +| 909 | [Snakes and Ladders](https://leetcode.com/problems/snakes-and-ladders) | [![Java](assets/java.png)](src/SnakesAndLadders.java) | | +| 914 | [X of a kind in a Deck of Cards](https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards) | [![Java](assets/java.png)](src/XOfAKindInADeckOfCards.java) | | +| 917 | [Reverse Only Letters](https://leetcode.com/problems/reverse-only-letters) | [![Java](assets/java.png)](src/ReverseOnlyLetters.java) | | +| 922 | [Sort Array by Parity II](https://leetcode.com/problems/sort-array-by-parity-ii) | [![Java](assets/java.png)](src/SortArrayByParityII.java) | | +| 925 | [Long Pressed Name](https://leetcode.com/problems/long-pressed-name) | [![Java](assets/java.png)](src/LongPressedName.java) | | +| 929 | [Unique Email Addresses](https://leetcode.com/problems/unique-email-addresses) | [![Java](assets/java.png)](src/UniqueEmailAddresses.java) | | +| 933 | [Number of Recent Calls](https://leetcode.com/problems/number-of-recent-calls) | [![Java](assets/java.png)](src/NumberOfRecentCalls.java) | | +| 937 | [Reorder Data In Log Files](https://leetcode.com/problems/reorder-data-in-log-files) | [![Java](assets/java.png)](src/ReorderDataInLogFiles.java) | | +| 938 | [Range Sum of BST](https://leetcode.com/problems/range-sum-of-bst) | [![Java](assets/java.png)](src/RangeSumOfBST.java) | | +| 941 | [Valid Mountain Array](https://leetcode.com/problems/valid-mountain-array) | [![Java](assets/java.png)](src/ValidMountainArray.java) [![Python](assets/python.png)](python/valid_mountain_array.py) | | +| 942 | [DI String Match](https://leetcode.com/problems/di-string-match) | [![Java](assets/java.png)](src/DIStringMatch.java) | | +| 944 | [Delete Columns to Make Sorted](https://leetcode.com/problems/delete-columns-to-make-sorted) | [![Java](assets/java.png)](src/DeleteColumnsToMakeSorted.java) | | +| 949 | [Largest Time for Given Digits](https://leetcode.com/problems/largest-time-for-given-digits) | | | +| 952 | [Largest Component Size by Common Factor](https://leetcode.com/problems/largest-component-size-by-common-factor) | [![Java](assets/java.png)](src/LargestComponentSizeByCommonFactor.java) | | +| 953 | [Verifying an Alien Dictionary](https://leetcode.com/problems/verifying-an-alien-dictionary) | [![Java](assets/java.png)](src/VerifyAnAlienDictionary.java) | | +| 961 | [N-Repeated Elements in Size 2N Array](https://leetcode.com/problems/n-repeated-element-in-size-2n-array) | [![Java](assets/java.png)](src/NRepeatedElementInSizeNArray.java) | | +| 965 | [Univalued Binary Tree](https://leetcode.com/problems/univalued-binary-tree) | [![Java](assets/java.png)](src/UnivaluedBinaryTree.java) | | +| 970 | [Powerful Integers](https://leetcode.com/problems/powerful-integers) | | | +| 976 | [Largest Perimeter Triangle](https://leetcode.com/problems/largest-perimeter-triangle) | [![Java](assets/java.png)](src/LargestPerimeterTriangle.java) | | +| 977 | [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array) | | | +| 983 | [Minimum Cost For Tickets](https://leetcode.com/problems/minimum-cost-for-tickets) | [![Python](assets/python.png)](python/minimum_cost_for_tickets.py) | | +| 985 | [Sum of Even Numbers after Queries](https://leetcode.com/problems/sum-of-even-numbers-after-queries) | | | +| 989 | [Add to Array Form of Integer](https://leetcode.com/problems/add-to-array-form-of-integer) | [![Java](assets/java.png)](src/AddToArrayFormOfInteger.java) | | +| 993 | [Cousins in Binary Tree](https://leetcode.com/problems/cousins-in-binary-tree) | [![Java](assets/java.png)](src/CousinsInBinaryTree.java) | | +| 994 | [Rotting Oranges](https://leetcode.com/problems/rotting-oranges) | [![Java](assets/java.png)](src/RottingOranges.java) | | +| 997 | [Find the Town Judge](https://leetcode.com/problems/find-the-town-judge) | [![Java](assets/java.png)](src/FindTheTownJudge.java) | | +| 999 | [Available Captures for Rook](https://leetcode.com/problems/available-captures-for-rook) | [![Java](assets/java.png)](src/AvailableCapturesForRook.java) | | +| 1002 | [Find Common Characters](https://leetcode.com/problems/find-common-characters) | [![Java](assets/java.png)](src/FindCommonCharacters.java) | | +| 1005 | [Maximize Sum of Array After K Negations](https://leetcode.com/problems/maximize-sum-of-array-after-k-negations) | [![Java](assets/java.png)](src/MaximizeSumOfArrayAfterKNegations.java) | | +| 1009 | [Complement of Base 10 Integer](https://leetcode.com/problems/complement-of-base-10-integer) | [![Java](assets/java.png)](src/NumberComplement.java) | | +| 1010 | [Pairs of Songs With Total Durations Divisible by 60](https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60) | [![Java](assets/java.png)](src/PartitionArrayIntoThreePartsWithEqualSum.java) | | +| 1013 | [Partition Array into Three Parts with equal Sum](https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum) | | | +| 1018 | [Binary Prefix Divisible by 5](https://leetcode.com/problems/binary-prefix-divisible-by-5) | [![Java](assets/java.png)](src/BinaryPrefixDivisibleBy5.java) | | +| 1020 | [Number of Enclaves](https://leetcode.com/problems/number-of-enclaves) | [![Python](assets/python.png)](python/number_of_enclaves.py) | | +| 1021 | [Remove Outermost Parenthesis](https://leetcode.com/problems/remove-outermost-parentheses) | [![Java](assets/java.png)](src/RemoveOutermostParentheses.java) | | +| 1022 | [Sum of Root to Leaf Binary Numbers](https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers) | [![Java](assets/java.png)](src/SumOfRootToLeafBinaryNumbers.java) | | +| 1025 | [Divisor Game](https://leetcode.com/problems/divisor-game) | [![Java](assets/java.png)](src/DivisorGame.java) | | +| 1029 | [Two City Scheduling](https://leetcode.com/problems/two-city-scheduling) | | | +| 1030 | [Matrix Cells in Distance Order](https://leetcode.com/problems/matrix-cells-in-distance-order) | [![Java](assets/java.png)](src/MatrixCellsInDistanceOrder.java) | | +| 1033 | [Moving Stones Until Consecutive](https://leetcode.com/problems/moving-stones-until-consecutive) | | | +| 1037 | [Valid Boomerang](https://leetcode.com/problems/valid-boomerang) | [![Java](assets/java.png)](src/ValidBoomerang.java) | | +| 1042 | [Flower Planting with no Adjacent](https://leetcode.com/problems/flower-planting-with-no-adjacent) | | | +| 1046 | [Last Stone Weight](https://leetcode.com/problems/last-stone-weight) | [![Java](assets/java.png)](src/LastStoneWeight.java) | | +| 1047 | [Remove All adjacent Duplicates in String](https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string) | [![Java](assets/java.png)](src/RemoveAllAdjacentDuplicatesInAString.java) | | +| 1051 | [Height Checker](https://leetcode.com/problems/height-checker) | | | +| 1056 | 🔒 [Confusing Number](https://leetcode.com/problems/confusing-number) | | | +| 1059 | 🔒 [All Paths From Source Lead To Destination](https://leetcode.com/problems/all-paths-from-source-lead-to-destination) | [![Java](assets/java.png)](src/AllPathsFromSourceLeadToDestination.java) | | +| 1064 | 🔒 [Fixed Point](https://leetcode.com/problems/fixed-point) | | | +| 1065 | 🔒 [Index Pairs of a String](https://leetcode.com/problems/index-pairs-of-a-string) | | | +| 1071 | [Greatest Common Divisors of Strings](https://leetcode.com/problems/greatest-common-divisor-of-strings) | [![Java](assets/java.png)](src/GreatestCommonDivisorOfStrings.java) | | +| 1078 | [Occurrence After Bigram](https://leetcode.com/problems/occurrences-after-bigram) | [![Java](assets/java.png)](src/OccurrencesAfterBigram.java) | | +| 1085 | 🔒 [Sum of Digits in Minimum Number](https://leetcode.com/problems/sum-of-digits-in-the-minimum-number) | | | +| 1086 | 🔒 [High Five](https://leetcode.com/problems/high-five) | | | +| 1089 | [Duplicate Zeroes](https://leetcode.com/problems/duplicate-zeros) | [![Java](assets/java.png)](src/DuplicateZeros.java) | | +| 1091 | [Shortest Path in Binary Matrix](https://leetcode.com/problems/shortest-path-in-binary-matrix) | [![Java](assets/java.png)](src/ShortestPathInBinaryMatrix.java) | | +| 1099 | 🔒 [Two Sum Less Than K](https://leetcode.com/problems/two-sum-less-than-k) | | | +| 1101 | [The Earliest Moment When Everyone Become Friend](https://leetcode.com/problems/the-earliest-moment-when-everyone-become-friends) | [![Java](assets/java.png)](src/TheEarliestMomentWhenEveryoneBecomeFriends.java) | | +| 1103 | [Distribute Candies to People](https://leetcode.com/problems/distribute-candies-to-people) | [![Java](assets/java.png)](src/DistributeCandiesToPeople.java) | | +| 1108 | [Defanging an IP Address](https://leetcode.com/problems/defanging-an-ip-address) | [![Java](assets/java.png)](src/DefangingAnIPAddress.java) | | +| 1118 | 🔒 [Number of Days in a Month](https://leetcode.com/problems/number-of-days-in-a-month) | | | +| 1119 | 🔒 [Remove Vowels From String](https://leetcode.com/problems/remove-vowels-from-a-string) | | | +| 1122 | [Relative Sort Array](https://leetcode.com/problems/relative-sort-array) | [![Java](assets/java.png)](src/RelativeSortArray.java) | | +| 1128 | [Number of Equivalent Domino Pairs](https://leetcode.com/problems/number-of-equivalent-domino-pairs) | [![Java](assets/java.png)](src/NumberOfEquivalentDominoPairs.java) | | +| 1133 | 🔒 [Largest Unique Number](https://leetcode.com/problems/largest-unique-number) | | | +| 1134 | 🔒 [Armstrong Number](https://leetcode.com/problems/armstrong-number) | | | +| 1136 | 🔒 [Parallel Courses](https://leetcode.com/problems/parallel-courses) | [![Java](assets/java.png)](src/ParallelCourses.java) | | +| 1137 | [Nth Tribonacci Number](https://leetcode.com/problems/n-th-tribonacci-number) | [![Java](assets/java.png)](src/NthTribonacciNumber.java) | | +| 1143 | [Longest Common Subsequence](https://leetcode.com/problems/longest-common-subsequence) | [![Java](assets/java.png)](src/LongestCommonSubsequence.java) | | +| 1150 | [Check if Number is Majority Element in Sorted Array](https://leetcode.com/problems/check-if-a-number-is-majority-element-in-a-sorted-array) | | | +| 1154 | [Day of The Year](https://leetcode.com/problems/day-of-the-year) | [![Java](assets/java.png)](src/DayOfTheYear.java) | | +| 1160 | [Find Words That Can Be Formed By Characters](https://leetcode.com/problems/find-words-that-can-be-formed-by-characters) | | | +| 1165 | [Single Row Keyboard](https://leetcode.com/problems/single-row-keyboard) | [![Java](assets/java.png)](src/FindWordsThatCanBeFormedByCharacters.java) | | +| 1168 | [Optimize Water Distribution in a Village](https://leetcode.com/problems/optimize-water-distribution-in-a-village) | [![Java](assets/java.png)](src/OptimizeWaterDistributionInAVillage.java) | | +| 1170 | [Compare Strings By Frequency of the Smallest Character](https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character) | | | +| 1175 | [Prime Arrangements](https://leetcode.com/problems/prime-arrangements) | [![Java](assets/java.png)](src/PrimeArrangements.java) | | +| 1176 | 🔒 [Diet Plan Performance](https://leetcode.com/problems/diet-plan-performance) | | | +| 1180 | 🔒 [Count Substrings with only one Distinct Letter](https://leetcode.com/problems/count-substrings-with-only-one-distinct-letter) | | | +| 1184 | [Distance Between Bus Stops](https://leetcode.com/problems/distance-between-bus-stops) | [![Java](assets/java.png)](src/DistanceBetweenBusStops.java) | | +| 1185 | [Day of the Week](https://leetcode.com/problems/day-of-the-week) | [![Java](assets/java.png)](src/DayOfWeek.java) | | +| 1189 | [Maximum Number of Balloons](https://leetcode.com/problems/maximum-number-of-balloons) | [![Java](assets/java.png)](src/MaximumNumberOfBalloons.java) | | +| 1196 | 🔒 [How Many Apples Can You Put into the Basket](https://leetcode.com/problems/how-many-apples-can-you-put-into-the-basket) | | | +| 1200 | [Minimum Absolute Difference](https://leetcode.com/problems/minimum-absolute-difference) | [![Java](assets/java.png)](src/MinimumAbsoluteDifference.java) | | +| 1201 | [Ugly Number III](https://leetcode.com/problems/ugly-number-iii) | [![Java](assets/java.png)](src/UglyNumberIII.java) | | +| 1202 | [Smallest String With Swaps](https://leetcode.com/problems/smallest-string-with-swaps) | [![Java](assets/java.png)](src/SmallestStringWithSwaps.java) | | +| 1207 | [Unique Number of Occurrences](https://leetcode.com/problems/unique-number-of-occurrences) | [![Java](assets/java.png)](src/UniqueNumberOfOccurrences.java) | | +| 1213 | 🔒 [Intersection of Three Sorted Arrays](https://leetcode.com/problems/intersection-of-three-sorted-arrays) | | | +| 1217 | [Minimum Cost to Move Chips to The Same Position](https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position) | [![Java](assets/java.png)](src/MinimumCostToMoveChipsToTheSamePosition.java) | | +| 1221 | [Split A String In Balanced Strings](https://leetcode.com/problems/split-a-string-in-balanced-strings) | [![Java](assets/java.png)](src/SplitAStringInBalancedStrings.java) | | +| 1228 | 🔒 [Missing A Number In Arithmetic Progression](https://leetcode.com/problems/missing-number-in-arithmetic-progression) | | | +| 1232 | [Check If It Is A Straight Line](https://leetcode.com/problems/check-if-it-is-a-straight-line) | [![Java](assets/java.png)](src/CheckIfItIsASStraightLine.java) | | +| 1237 | [Find Positive Integer Solutions for a Given Equation](https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation) | | | +| 1243 | 🔒 [Array Transformation](https://leetcode.com/problems/array-transformation) | | | +| 1249 | [Minimum Remove to Make Valid Parentheses](https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses) | [![Java](assets/java.png)](src/MinimumRemoveToMakeValidParentheses.java) | | +| 1252 | [Cells With Odd Values In Matrix](https://leetcode.com/problems/cells-with-odd-values-in-a-matrix) | [![Java](assets/java.png)](src/CellsWithOddValuesInMatrix.java) | | +| 1254 | [Number of Closed Islands](https://leetcode.com/problems/number-of-closed-islands) | [![Python](assets/python.png)](python/number_of_closed_islands.py) | | +| 1260 | [Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid) | [![Java](assets/java.png)](src/Shift2DGrid.java) | | +| 1266 | [Minimum Time Visiting All Points](https://leetcode.com/problems/minimum-time-visiting-all-points) | [![Java](assets/java.png)](src/MinimumTimeVisitingAllPoints.java) | | +| 1271 | 🔒 [Hexspeak](https://leetcode.com/problems/hexspeak) | | | +| 1275 | [Find Winner On a Tic Tac Toe Game](https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game) | [![Java](assets/java.png)](src/FindWinnerOnATicTacToeGame.java) | | +| 1281 | [Subtract the Product and Sum of Digits of a Integer](https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer) | [![Java](assets/java.png)](src/SubtractTheProductAndSumOfDigitsOfAnInteger.java) | | +| 1287 | [Element Appearing More Than 25% in Sorted Array](https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array) | [![Java](assets/java.png)](src/ElementAppearingMoreThan25PercentInSortedArray.java) | | +| 1290 | [Convert Binary Number In A Linked List to Integer](https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer) | [![Java](assets/java.png)](src/ConvertBinaryNumberInLinkedListToInteger.java) | | +| 1295 | [Find Numbers With Even Numbers of Digits](https://leetcode.com/problems/find-numbers-with-even-number-of-digits) | [![Java](assets/java.png)](src/FindNumbersWithEvenNumbersOfDigits.java) [![Python](assets/python.png)](python/find_numbers_with_even_number_of_digits.py) | | +| 1299 | [Replace Elements With Greatest Element on Right Side](https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side) | [![Java](assets/java.png)](src/ReplaceElementWithGreatestElementOnRightSide.java) [![Python](assets/python.png)](python/replace_element_with_greatest_element_on_right_hand_side.py) | | +| 1304 | [Find N Unique Integers Sum Up To Zero](https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero) | [![Java](assets/java.png)](src/FindNUniqueIntegersSumUpToZero.java) | | +| 1309 | [Decrypt String From Alphabet To Integer Mapping](https://leetcode.com/problems/decrypt-string-from-alphabet-to-integer-mapping) | [![Java](assets/java.png)](src/DecryptStringFromAlphabetToIntegerMapping.java) | | +| 1313 | [Decompress Run-Length Encoded Strings](https://leetcode.com/problems/decompress-run-length-encoded-list) | [![Java](assets/java.png)](src/DecompressRunLengthEncodedList.java) | | +| 1317 | [Convert Integer to Sum Of Two Non-Zero Integers](https://leetcode.com/problems/convert-integer-to-the-sum-of-two-no-zero-integers) | [![Java](assets/java.png)](src/ConvertIntegerToTheSumOfTwoNoZeroIntegers.java) | | +| 1319 | [Number of Operations to Make Network Connected](https://leetcode.com/problems/number-of-operations-to-make-network-connected) | [![Python](assets/python.png)](python/no_of_operations_to_make_network_connected.py) | | +| 1323 | [Maximum 69 Number](https://leetcode.com/problems/maximum-69-number) | [![Java](assets/java.png)](src/Maximum69Number.java) | | +| 1331 | [Rank Transform of An Array](https://leetcode.com/problems/rank-transform-of-an-array) | [![Java](assets/java.png)](src/RankTransformOfArray.java) | | +| 1332 | [Remove Palindromic Subsequences](https://leetcode.com/problems/remove-palindromic-subsequences) | [![Java](assets/java.png)](src/RemovePalindromicSubSequences.java) | | +| 1337 | [The K Weakest Rows In A Matrix](https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix) | [![Java](assets/java.png)](src/TheKWeakestRowsInAMatrix.java) | | +| 1342 | [Number of Steps to Reduce a Number to Zero](https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero) | [![Java](assets/java.png)](src/NumberOfStepsToReduceANumberToZero.java) | | +| 1346 | [Check if N and It's Double Exist](https://leetcode.com/problems/check-if-n-and-its-double-exist) | [![Java](assets/java.png)](src/CheckIfNAndItsDoubleExist.java) [![Python](assets/python.png)](python/check_if_n_and_its_double_exist.py) | | +| 1351 | [Count Negative Numbers In A Sorted Matrix](https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix) | [![Java](assets/java.png)](src/CountNegativeNumbersInSortedMatrix.java) | | +| 1356 | [Sort Integers by Number of 1 Bits](https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits) | [![Java](assets/java.png)](src/SortIntegersByTheNumberOf1Bits.java) | | +| 1360 | [Number of Days Between Two Dates](https://leetcode.com/problems/number-of-days-between-two-dates) | [![Java](assets/java.png)](src/NumberOfDaysBetweenTwoDates.java) | | +| 1365 | [How Many Numbers Are Smaller Than Current Number](https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number) | [![Java](assets/java.png)](src/HowManyNumbersAreSmallerThanCurrentNumber.java) | | +| 1370 | [Increasing Decreasing String](https://leetcode.com/problems/increasing-decreasing-string) | [![Java](assets/java.png)](src/IncreasingDecreasingString.java) | | +| 1374 | [Generate A String With Characters That Have Odd Count](https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts) | [![Java](assets/java.png)](src/GenerateAStringWithCharactersThatHaveOddCounts.java) | | +| 1376 | [Time Needed to Inform All Employees](https://leetcode.com/problems/time-needed-to-inform-all-employees) | [![Java](assets/java.png)](src/TimeNeededToInformAllEmployees.java) | | +| 1379 | [Find a Corresponding Node of a Binary Tree in a Clone of That Tree](https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree) | [![Java](assets/java.png)](src/FindACorrespondingNodeOfABinaryTreeInACloneOfThatTree.java) | | +| 1380 | [Lucky Numbers In A Matrix](https://leetcode.com/problems/lucky-numbers-in-a-matrix) | [![Java](assets/java.png)](src/LuckyNumbersInAMatrix.java) | | +| 1385 | [Find The Distance Value Between 2 Arrays](https://leetcode.com/problems/find-the-distance-value-between-two-arrays) | [![Java](assets/java.png)](src/FindTheDistanceValuesBetweenTwoArrays.java) | | +| 1389 | [Create Target Array in Given Order](https://leetcode.com/problems/create-target-array-in-the-given-order) | [![Java](assets/java.png)](src/CreateTargetArrayInGivenOrder.java) | | +| 1394 | [Find Lucky Integer In An Array](https://leetcode.com/problems/find-lucky-integer-in-an-array) | [![Java](assets/java.png)](src/FindTheLuckyIntegerInAnArray.java) | | +| 1399 | [Count Largest Group](https://leetcode.com/problems/count-largest-group) | [![Java](assets/java.png)](src/CountLargestGroup.java) | | +| 1402 | [Reducing Dishes](https://leetcode.com/problems/reducing-dishes) | [![Python](assets/python.png)](python/reducing_dishes.py) | | +| 1403 | [Minimum Subsequence in Non-Increasing Order](https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order) | [![Java](assets/java.png)](src/MinimumSubSequenceInNonIncreasingOrder.java) | | +| 1408 | [String Matching In An Array](https://leetcode.com/problems/string-matching-in-an-array) | [![Java](assets/java.png)](src/StringMatchingInAnArray.java) | | +| 1413 | [Minimum Value To Get Positive Step By Step Sum](https://leetcode.com/problems/minimum-value-to-get-positive-step-by-step-sum) | [![Java](assets/java.png)](src/MinimumValueToGetPositiveStepByStepSum.java) | | +| 1417 | [Reformat The String](https://leetcode.com/problems/reformat-the-string) | [![Java](assets/java.png)](src/ReformatTheString.java) | | +| 1422 | [Maximum Score After Splitting A String](https://leetcode.com/problems/maximum-score-after-splitting-a-string) | [![Java](assets/java.png)](src/MaximumScoreAfterSplittingAString.java) | | +| 1426 | 🔒 [Counting Elements](https://leetcode.com/problems/counting-elements) | | | +| 1427 | 🔒 [Performing String Shifts](https://leetcode.com/problems/perform-string-shifts) | | | +| 1431 | [Kids With The Greatest Number Of Candies](https://leetcode.com/problems/kids-with-the-greatest-number-of-candies) | [![Java](assets/java.png)](src/KidsWithTheGreatestNumberOfCandies.java) | | +| 1436 | [Destination City](https://leetcode.com/problems/destination-city) | [![Java](assets/java.png)](src/DestinationCity.java) | | +| 1437 | [Check If All 1's Are at Least Length K Places Away](https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away) | [![Java](assets/java.png)](src/CheckIfAll1sAreAtLeastKPlacesAway.java) | | +| 1441 | [Build An Array With Stack Operation](https://leetcode.com/problems/build-an-array-with-stack-operations) | [![Java](assets/java.png)](src/BuildAnArrayWithStackOperations.java) | | +| 1444 | [Number of Ways of Cutting a Pizza](https://leetcode.com/problems/number-of-ways-of-cutting-a-pizza) | [![Python](assets/python.png)](python/number_of_ways_of_cutting_pizza.py) | | +| 1446 | [Consecutive Characters](https://leetcode.com/problems/consecutive-characters) | [![Java](assets/java.png)](src/ConsecutiveCharacters.java) | | +| 1450 | [Number of Students Doing Homework at Given Time](https://leetcode.com/problems/number-of-students-doing-homework-at-a-given-time) | [![Java](assets/java.png)](src/NumberOfStudentsDoingHomeworkAtGivenTime.java) | | +| 1455 | [Check If Word Occurs as Prefix of any Word in Sentence](https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence) | [![Java](assets/java.png)](src/CheckIfAWordOccursAsAPrefixOfAnyWordInASentence.java) | | +| 1460 | [Make 2 Arrays Equal by Reversing Sub Arrays](https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays) | [![Java](assets/java.png)](src/MakeTwoArraysEqualByReversingSubArrays.java) | | +| 1464 | [Maximum Product of 2 Elements in Array](https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array) | [![Java](assets/java.png)](src/MaximumProductOfTwoElementsInArray.java) | | +| 1466 | [Reorder Routes to Make All Paths Lead to the City Zero](https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero) | [![Java](assets/java.png)](src/MaximumProductOfTwoElementsInArray.java) | | +| 1469 | 🔒 [Find All Lonely Nodes](https://leetcode.com/problems/find-all-the-lonely-nodes) | [![Python](assets/python.png)](python/reorder_routes_to_make_all_paths_lead_to_city_zero.py) | | +| 1470 | [Shuffle The Array](https://leetcode.com/problems/shuffle-the-array) | [![Java](assets/java.png)](src/ShuffleTheArray.java) | | +| 1472 | [Design Browser History](https://leetcode.com/problems/design-browser-history) | [![Java](assets/java.png)](src/DesignBrowserHistory.java) [![Python](assets/python.png)](python/design_browser_history.py) | | +| 1474 | 🔒 [Delete N Nodes After M Nodes In A Linked List](https://leetcode.com/problems/delete-n-nodes-after-m-nodes-of-a-linked-list) | | | +| 1475 | [Final Prices With Special Discount in a Shop](https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop) | [![Java](assets/java.png)](src/FinalPricesWithASpecialDiscountInAShop.java) | | +| 1480 | [Running Sum of 1D Array](https://leetcode.com/problems/running-sum-of-1d-array) | [![Java](assets/java.png)](src/RunningSumOf1DArray.java) | | +| 1486 | [XOR Operations in An Array](https://leetcode.com/problems/xor-operation-in-an-array) | [![Java](assets/java.png)](src/XOROperationInAnArray.java) | | +| 1491 | [Average Salary Excluding the Minimum and Maximum Salary](https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary) | [![Java](assets/java.png)](src/AverageSalaryExcludingTheMinimumAndMaximumSalary.java) | | +| 1496 | [Path Crossing](https://leetcode.com/problems/path-crossing) | [![Java](assets/java.png)](src/PathCrossing.java) | | +| 1502 | [Can Make Arithmetic Progression From Sequence](https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence) | [![Java](assets/java.png)](src/CanMakeArithmeticProgressionFromSequence.java) | | +| 1507 | [Reformat Date](https://leetcode.com/problems/reformat-date) | [![Java](assets/java.png)](src/ReformatDate.java) | | +| 1512 | [Number of Good Pairs](https://leetcode.com/problems/number-of-good-pairs) | [![Java](assets/java.png)](src/NumberOfGoodPairs.java) | | +| 1514 | [Path with Maximum Probability](https://leetcode.com/problems/path-with-maximum-probability) | [![Java](assets/java.png)](src/PathWithMaximumProbability.java) | | +| 1518 | [Water Bottles](https://leetcode.com/problems/water-bottles) | [![Java](assets/java.png)](src/WaterBottles.java) | | +| 1523 | [Count Odd Numbers In Interval Range](https://leetcode.com/problems/count-odd-numbers-in-an-interval-range) | [![Java](assets/java.png)](src/CountOddNumbersInIntervalRange.java) | | +| 1528 | [Shuffle Strings](https://leetcode.com/problems/shuffle-string) | [![Java](assets/java.png)](src/ShuffleString.java) | | +| 1534 | [Count Good Triplets](https://leetcode.com/problems/count-good-triplets) | [![Java](assets/java.png)](src/CountGoodTriplets.java) | | +| 1539 | [Kth Missing Positive Number](https://leetcode.com/problems/kth-missing-positive-number) | [![Java](assets/java.png)](src/KthMissingPositiveNumber.java) | | +| 1544 | [Make The String Great](https://leetcode.com/problems/make-the-string-great) | [![Java](assets/java.png)](src/MakeTheStringGreat.java) | | +| 1550 | [Three Consecutive Odds](https://leetcode.com/problems/three-consecutive-odds) | [![Java](assets/java.png)](src/ThreeConsecutiveOdds.java) | | +| 1556 | [Thousand Separator](https://leetcode.com/problems/thousand-separator) | [![Java](assets/java.png)](src/ThousandSeparator.java) | | +| 1560 | [Most Visited Sector in a Circular Track](https://leetcode.com/problems/most-visited-sector-in-a-circular-track) | [![Java](assets/java.png)](src/MostVisitedSectorInACircularTrack.java) | | +| 1566 | [Detect Pattern of Length M Repeated K or More Times](https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times) | [![Java](assets/java.png)](src/DetectPatternOfLengthMRepeatedKOrMoreTimes.java) | | +| 1572 | [Matrix Diagonal Sum](https://leetcode.com/problems/matrix-diagonal-sum) | [![Java](assets/java.png)](src/MatrixDiagonalSum.java) | | +| 1576 | [Replace All ?'s to Avoid Consecutive Repeating Characters](https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters) | [![Java](assets/java.png)](src/ReplaceAllToAvoidConsecutiveRepeatingCharacters.java) | | +| 1582 | [Special Positions in a Binary Matrix](https://leetcode.com/problems/special-positions-in-a-binary-matrix) | [![Java](assets/java.png)](src/SpecialPositionInABinaryMatrix.java) | | +| 1584 | [Min Cost to Connect All Points](https://leetcode.com/problems/min-cost-to-connect-all-points) | [![Java](assets/java.png)](src/MinCostToConnectAllPoints.java) | | +| 1588 | [Sum of All Odd Length Subarrays](https://leetcode.com/problems/sum-of-all-odd-length-subarrays) | [![Java](assets/java.png)](src/SumOfAllOddLengthSubArrays.java) | | +| 1592 | [Rearrange Spaces Between Words](https://leetcode.com/problems/rearrange-spaces-between-words) | [![Java](assets/java.png)](src/RearrangeSpacesBetweenWords.java) | | +| 1598 | [Crawler Log Folder](https://leetcode.com/problems/crawler-log-folder) | [![Java](assets/java.png)](src/CrawlerLogFolder.java) | | +| 1600 | [Throne Inheritance](https://leetcode.com/problems/throne-inheritance) | [![Java](assets/java.png)](src/ThroneInheritance.java) | | +| 1603 | [Design Parking System](https://leetcode.com/problems/design-parking-system) | [![Java](assets/java.png)](src/DesignParkingSystem.java) | | +| 1608 | [Special Array With X Elements Greater Than or Equal X](https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x) | [![Java](assets/java.png)](src/SpecialArrayWithXElementsGreaterThanEqualToX.java) | | +| 1614 | [Maximum Nesting Depth of the Parentheses](https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses) | [![Java](assets/java.png)](src/MaximumNestingDepthOfTheParentheses.java) | | +| 1619 | [Mean of Array After Removing Some Elements](https://leetcode.com/problems/mean-of-array-after-removing-some-elements) | [![Java](assets/java.png)](src/MeanOfArrayAfterRemovingSomeElements.java) | | +| 1624 | [Largest Substring Between Two Equal Characters](https://leetcode.com/problems/largest-substring-between-two-equal-characters) | [![Java](assets/java.png)](src/LargestSubStringBetweenTwoEqualCharacters.java) | | +| 1629 | [Slowest Key](https://leetcode.com/problems/slowest-key) | [![Java](assets/java.png)](src/SlowestKey.java) | | +| 1631 | [Path With Minimum Effort](https://leetcode.com/problems/path-with-minimum-effort) | [![Java](assets/java.png)](src/PathWithMinimumEffort.java) | | +| 1636 | [Sort Array by Increasing Frequency](https://leetcode.com/problems/sort-array-by-increasing-frequency) | [![Java](assets/java.png)](src/SortArrayByIncreasingFrequency.java) | | +| 1637 | [Widest Vertical Area Between Two Points Containing No Points](https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points) | [![Java](assets/java.png)](src/WidestVerticalAreaBetweenTwoPointsContainingNoPoints.java) | | +| 1640 | [Check Array Formation Through Concatenation](https://leetcode.com/problems/check-array-formation-through-concatenation) | [![Java](assets/java.png)](src/CheckArrayFormationThroughConcatenation.java) | | +| 1646 | [Get Maximum in Generated Array](https://leetcode.com/problems/get-maximum-in-generated-array) | [![Java](assets/java.png)](src/GetMaximumInGeneratedArray.java) | | +| 1652 | [Defuse the Bomb](https://leetcode.com/problems/defuse-the-bomb) | [![Java](assets/java.png)](src/DefuseTheBomb.java) | | +| 1656 | [Design an Ordered Stream](https://leetcode.com/problems/design-an-ordered-stream) | [![Java](assets/java.png)](src/DesignAnOrderedStream.java) | | +| 1662 | [Check If Two String Arrays are Equivalent](https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent) | [![Java](assets/java.png)](src/CheckIfTwoStringArraysAreEquivalent.java) | | +| 1668 | [Maximum Repeating Substring](https://leetcode.com/problems/maximum-repeating-substring) | [![Java](assets/java.png)](src/MaximumRepeatingSubString.java) | | +| 1672 | [Richest Customer Wealth](https://leetcode.com/problems/richest-customer-wealth) | [![Java](assets/java.png)](src/RichestCustomerWealth.java) | | +| 1678 | [Goal Parser Interpretation](https://leetcode.com/problems/goal-parser-interpretation) | [![Java](assets/java.png)](src/GoalParserInterpretation.java) | | +| 1684 | [Count the Number of Consistent Strings](https://leetcode.com/problems/count-the-number-of-consistent-strings) | [![Java](assets/java.png)](src/CountTheNumberOfConsistentStrings.java) | | +| 1688 | [Count of Matches in Tournament](https://leetcode.com/problems/count-of-matches-in-tournament) | [![Java](assets/java.png)](src/CountOfMatchesInTournament.java) | | +| 1694 | [Reformat Phone Number](https://leetcode.com/problems/reformat-phone-number) | [![Java](assets/java.png)](src/ReformatPhoneNumber.java) | | +| 1700 | [Number of Students Unable to Eat Lunch](https://leetcode.com/problems/number-of-students-unable-to-eat-lunch) | [![Java](assets/java.png)](src/NumberOfStudentsUnableToEatLunch.java) | | +| 1704 | [Determine if String Halves Are Alike](https://leetcode.com/problems/determine-if-string-halves-are-alike) | [![Java](assets/java.png)](src/DetermineIfStringHalvesAreAlike.java) | | +| 1708 | 🔒 [Largest Subarray Length K](https://leetcode.com/problems/largest-subarray-length-k/) | | | +| 1710 | [Maximum Units on a Truck](https://leetcode.com/problems/maximum-units-on-a-truck/) | [![Java](assets/java.png)](src/MaximumUnitsOnATruck.java) | | +| 1716 | [Calculate Money in Leetcode Bank](https://leetcode.com/problems/calculate-money-in-leetcode-bank) | [![Java](assets/java.png)](src/CalculateMoneyInLeetCodeBank.java) | | +| 1720 | [Decode XORed Array](https://leetcode.com/problems/decode-xored-array) | [![Java](assets/java.png)](src/DecodeXORedArray.java) | | +| 1725 | [Number Of Rectangles That Can Form The Largest Square](https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square) | [![Java](assets/java.png)](src/NumberOfRectanglesThatCanFormTheLargestSquare.java) | | +| 1732 | [Find the Highest Altitude](https://leetcode.com/problems/find-the-highest-altitude) | [![Java](assets/java.png)](src/FindTheHighestAltitude.java) | | +| 1736 | [Latest Time by Replacing Hidden Digits](https://leetcode.com/problems/latest-time-by-replacing-hidden-digits) | [![Java](assets/java.png)](src/LatestTimeByReplacingHiddenDigits.java) | | +| 1742 | [Maximum Number of Balls in a Box](https://leetcode.com/problems/maximum-number-of-balls-in-a-box) | [![Java](assets/java.png)](src/MaximumNumberOfBallsInABox.java) | | +| 1748 | [Sum of Unique Elements](https://leetcode.com/problems/sum-of-unique-elements) | [![Java](assets/java.png)](src/SumOfUniqueElements.java) | | +| 1752 | [Check if Array Is Sorted and Rotated](https://leetcode.com/problems/check-if-array-is-sorted-and-rotated) | [![Java](assets/java.png)](src/CheckIfArrayIsSortedAndRotated.java) | | +| 1758 | [Minimum Changes To Make Alternating Binary String](https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string) | [![Java](assets/java.png)](src/MinimumChangesToMakeAlternatingBinaryString.java) | | +| 1763 | [Longest Nice Substring](https://leetcode.com/problems/longest-nice-substring) | [![Java](assets/java.png)](src/LongestNiceSubstring.java) | | +| 1768 | [Merge Strings Alternately](https://leetcode.com/problems/merge-strings-alternately) | [![Java](assets/java.png)](src/MergeStringsAlternately.java) | | +| 1773 | [Count Items Matching a Rule](https://leetcode.com/problems/count-items-matching-a-rule) | [![Java](assets/java.png)](src/CountItemsMatchingARule.java) | | +| 1779 | [Find Nearest Point That Has the Same X or Y Coordinate](https://leetcode.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate) | [![Java](assets/java.png)](src/FindNearestPointThatHasTheSameXOrYCoordinate.java) | | +| 1784 | [Check if Binary String Has at Most One Segment of Ones](https://leetcode.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones) | [![Java](assets/java.png)](src/CheckIfBinaryStringHasAtMostOneSegmentOfOnes.java) | | +| 1790 | [Check if One String Swap Can Make Strings Equal](https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal) | [![Java](assets/java.png)](src/CheckIfOneStringSwapCanMakeStringsEqual.java) | | +| 1791 | [Find Center of Star Graph](https://leetcode.com/problems/find-center-of-star-graph) | [![Java](assets/java.png)](src/FindCenterOfStarGraph.java) | | +| 1796 | [Second Largest Digit in a String](https://leetcode.com/problems/second-largest-digit-in-a-string) | [![Java](assets/java.png)](src/SecondLargestDigitInAString.java) | | +| 1800 | [Maximum Ascending Subarray Sum](https://leetcode.com/problems/maximum-ascending-subarray-sum) | [![Java](assets/java.png)](src/MaximumAscendingSubArraySum.java) | | +| 1805 | [Number of Different Integers in a String](https://leetcode.com/problems/number-of-different-integers-in-a-string) | [![Java](assets/java.png)](src/NumberOfDifferentIntegersInString.java) | | +| 1812 | [Determine Color of a Chessboard Square](https://leetcode.com/problems/determine-color-of-a-chessboard-square) | [![Java](assets/java.png)](src/DetermineColorOfChessboardSquare.java) | | +| 1816 | [Truncate Sentence](https://leetcode.com/problems/truncate-sentence) | [![Java](assets/java.png)](src/TruncateSentences.java) | | +| 1822 | [Sign of the Product of an Array](https://leetcode.com/problems/sign-of-the-product-of-an-array) | [![Java](assets/java.png)](src/SignOfTheProductOfAnArray.java) | | +| 1826 | 🔒 [Faulty Sensor](https://leetcode.com/problems/faulty-sensor) | | | +| 1827 | [Minimum Operations to Make the Array Increasing](https://leetcode.com/problems/minimum-operations-to-make-the-array-increasing) | [![Java](assets/java.png)](src/MinimumOperationsToMakeTheArrayIncreasing.java) | | +| 1832 | [Check if the Sentence Is Pangram](https://leetcode.com/problems/check-if-the-sentence-is-pangram) | [![Java](assets/java.png)](src/CheckIfSentenceIsPangram.java) | | +| 1837 | [Sum of Digits in Base K](https://leetcode.com/problems/sum-of-digits-in-base-k) | [![Java](assets/java.png)](src/SumOfDigitsInBaseK.java) | | +| 1844 | [Replace All Digits with Characters](https://leetcode.com/problems/replace-all-digits-with-characters) | [![Java](assets/java.png)](src/ReplaceAllDigitsWithCharacters.java) | | +| 1848 | [Minimum Distance to the Target Element](https://leetcode.com/problems/minimum-distance-to-the-target-element) | [![Java](assets/java.png)](src/MinimumDistanceToTheTargetElement.java) | | +| 1854 | [Maximum Population Year](https://leetcode.com/problems/maximum-population-year) | [![Java](assets/java.png)](src/MaximumPopulationYear.java) | | +| 1859 | [Sorting the Sentence](https://leetcode.com/problems/sorting-the-sentence) | [![Java](assets/java.png)](src/SortingTheSentence.java) | | +| 1863 | [Sum of All Subset XOR Totals](https://leetcode.com/problems/sum-of-all-subset-xor-totals) | [![Java](assets/java.png)](src/SumOfAllSubsetXORTotals.java) | | +| 1869 | [Longer Contiguous Segments of Ones than Zeros](https://leetcode.com/problems/longer-contiguous-segments-of-ones-than-zeros) | [![Java](assets/java.png)](src/LongerContiguousSegmentOfOnesThanZeros.java) | | +| 1876 | [Substrings of Size Three with Distinct Characters](https://leetcode.com/problems/substrings-of-size-three-with-distinct-characters) | [![Java](assets/java.png)](src/SubstringsOfSizeThreeWithDistinctCharacters.java) | | +| 1880 | [Check if Word Equals Summation of Two Words](https://leetcode.com/problems/check-if-word-equals-summation-of-two-words) | [![Java](assets/java.png)](src/CheckIfWordEqualsSummationOfTwoWords.java) | | +| 1886 | [Determine Whether Matrix Can Be Obtained By Rotation](https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation) | [![Java](assets/java.png)](src/DetermineWhetherMatrixCanBeObtainedByRotation.java) | | +| 1893 | [Check if All the Integers in a Range Are Covered](https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered) | [![Java](assets/java.png)](src/CheckIfAllTheIntegersInARangeAreCovered.java) | | +| 1897 | [Redistribute Characters to Make All Strings Equal](https://leetcode.com/problems/redistribute-characters-to-make-all-strings-equal) | [![Java](assets/java.png)](src/RedistributeCharactersToMakeAllStringsEqual.java) | | +| 1903 | [Largest Odd Number in String](https://leetcode.com/problems/largest-odd-number-in-string) | [![Java](assets/java.png)](src/LargestOddNumberInString.java) | | +| 1909 | [Remove One Element to Make the Array Strictly Increasing](https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing) | [![Java](assets/java.png)](src/RemoveOneElementToMakeTheArrayStrictlyIncreasing.java) | | +| 1913 | [Maximum Product Difference Between Two Pairs](https://leetcode.com/problems/maximum-product-difference-between-two-pairs) | [![Java](assets/java.png)](src/MaximumProductDifferenceBetweenTwoPairs.java) | | +| 1920 | [Build Array from Permutation](https://leetcode.com/problems/build-array-from-permutation) | [![Java](assets/java.png)](src/BuildArrayFromPermutation.java) | | +| 1925 | [Count Square Sum Triples](https://leetcode.com/problems/count-square-sum-triples) | [![Java](assets/java.png)](src/CountSquareSumTriplets.java) | | +| 1929 | [Concatenation of Array](https://leetcode.com/problems/concatenation-of-array) | [![Java](assets/java.png)](src/ConcatenationOfArray.java) | | +| 1933 | 🔒 [Check If String Is Decomposable Into Value EqualSubstrings](https://leetcode.com/problems/check-if-string-is-decomposable-into-value-equal-substring) | | | +| 1935 | [Maximum Number of Words You Can Type](https://leetcode.com/problems/maximum-number-of-words-you-can-type) | [![Java](assets/java.png)](src/MaximumNumberOfWordsYouCanType.java) | | +| 1941 | [Check if All Characters Have Equal Number of Occurrences](https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences) | [![Java](assets/java.png)](src/CheckIfAllCharactersHaveEqualNumberOfOccurrences.java) | | +| 1945 | [Sum of Digits of String After Convert](https://leetcode.com/problems/sum-of-digits-of-string-after-convert) | [![Java](assets/java.png)](src/SumOfDigitsOfStringAfterConvert.java) | | +| 1952 | [Three Divisors](https://leetcode.com/problems/three-divisors) | [![Java](assets/java.png)](src/ThreeDivisors.java) | | +| 1957 | [Delete Characters to Make Fancy String](https://leetcode.com/problems/delete-characters-to-make-fancy-string) | [![Java](assets/java.png)](src/DeleteCharactersToMakeFancyString.java) | | +| 1961 | [Check If String Is a Prefix of Array](https://leetcode.com/problems/check-if-string-is-a-prefix-of-array) | [![Java](assets/java.png)](src/CheckIfStringIsAPrefixOfArray.java) | | +| 1967 | [Number of Strings That Appear as Substrings in Word](https://leetcode.com/problems/number-of-strings-that-appear-as-substrings-in-word) | [![Java](assets/java.png)](src/NumberOfStringsThatAppearAsSubstringsInWord.java) | | +| 1971 | [Find if Path Exists in Graph](https://leetcode.com/problems/find-if-path-exists-in-graph) | [![Java](assets/java.png)](src/FindIfPathExistsInGraph.java) | | +| 1974 | [Minimum Time to Type Word Using Special Typewriter](https://leetcode.com/problems/minimum-time-to-type-word-using-special-typewriter) | [![Java](assets/java.png)](src/MinimumTimeToTypeWordUsingSpecialTypewriter.java) | | +| 1979 | [Find Greatest Common Divisor of Array](https://leetcode.com/problems/find-greatest-common-divisor-of-array) | [![Java](assets/java.png)](src/FindGreatestCommonDivisorOfArray.java) | | +| 1984 | [Minimum Difference Between Highest and Lowest of K Scores](https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores) | [![Java](assets/java.png)](src/MinimumDifferenceBetweenHighestAndLowestOfKScores.java) | | +| 1991 | [Find the Middle Index in Array](https://leetcode.com/problems/find-the-middle-index-in-array) | [![Java](assets/java.png)](src/FindTheMiddleIndexInArray.java) | | +| 1995 | [Count Special Quadruplets](https://leetcode.com/problems/count-special-quadruplets) | [![Java](assets/java.png)](src/CountSpecialQuadruplets.java) | | +| 2000 | [Reverse Prefix of Word](https://leetcode.com/problems/reverse-prefix-of-word) | [![Java](assets/java.png)](src/ReversePrefixOfWord.java) | | +| 2006 | [Count Number of Pairs With Absolute Difference K](https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k) | [![Java](assets/java.png)](src/CountNumberOfPairsWithAbsoluteDifferenceK.java) | | +| 2011 | [Final Value of Variable After Performing Operations](https://leetcode.com/problems/final-value-of-variable-after-performing-operations) | [![Java](assets/java.png)](src/FinalValueOfVariableAfterPerformingOperations.java) | | +| 2016 | [Maximum Difference Between Increasing Elements](https://leetcode.com/problems/maximum-difference-between-increasing-elements) | [![Java](assets/java.png)](src/MaximumDifferenceBetweenIncreasingElements.java) | | +| 2022 | [Convert 1D Array Into 2D Array](https://leetcode.com/problems/convert-1d-array-into-2d-array) | [![Java](assets/java.png)](src/Convert1DArrayInto2DArray.java) | | +| 2027 | [Minimum Moves to Convert String](https://leetcode.com/problems/minimum-moves-to-convert-string) | [![Java](assets/java.png)](src/MinimumMovesToConvertString.java) | | +| 2032 | [Two Out of Three](https://leetcode.com/problems/two-out-of-three) | [![Java](assets/java.png)](src/TwoOutOfThree.java) | | +| 2037 | [Minimum Number of Moves to Seat Everyone](https://leetcode.com/problems/minimum-number-of-moves-to-seat-everyone) | [![Java](assets/java.png)](src/MinimumNumberOfMovesToSeatEveryone.java) | | +| 2042 | [Check if Numbers Are Ascending in a Sentence](https://leetcode.com/problems/check-if-numbers-are-ascending-in-a-sentence) | [![Java](assets/java.png)](src/CheckIfNumbersAreAscendingInASentence.java) | | +| 2047 | [Number of Valid Words in a Sentence](https://leetcode.com/problems/number-of-valid-words-in-a-sentence) | [![Java](assets/java.png)](src/NumberOfValidWordsInASentence.java) | | +| 2053 | [Kth Distinct String in an Array](https://leetcode.com/problems/kth-distinct-string-in-an-array) | [![Java](assets/java.png)](src/KthDistinctStringInAnArray.java) | | +| 2057 | [Smallest Index With Equal Value](https://leetcode.com/problems/smallest-index-with-equal-value) | [![Java](assets/java.png)](src/SmallestIndexWithEqualValue.java) | | +| 2062 | [Count Vowel Substrings of a String](https://leetcode.com/problems/count-vowel-substrings-of-a-string) | [![Java](assets/java.png)](src/CountVowelSubstringsOfAString.java) | | +| 2068 | [Check Whether Two Strings are Almost Equivalent](https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent) | [![Java](assets/java.png)](src/CheckWhetherTwoStringsAreAlmostEquivalent.java) | | +| 2073 | [Time Needed to Buy Tickets](https://leetcode.com/problems/time-needed-to-buy-tickets) | [![Java](assets/java.png)](src/TimeNeededToBuyTickets.java) | | +| 2078 | [Two Furthest Houses With Different Colors](https://leetcode.com/problems/two-furthest-houses-with-different-colors) | [![Java](assets/java.png)](src/TwoFurthestHousesWithDifferentColors.java) | | +| 2085 | [Count Common Words With One Occurrence](https://leetcode.com/problems/count-common-words-with-one-occurrence) | [![Java](assets/java.png)](src/CountCommonWordsWithOneOccurrence.java) | | +| 2089 | [Find Target Indices After Sorting Array](https://leetcode.com/problems/find-target-indices-after-sorting-array) | [![Java](assets/java.png)](src/FindTargetIndicesAfterSortingArray.java) | | +| 2093 | [Minimum Cost To Reach City With Discounts](https://leetcode.com/problems/minimum-cost-to-reach-city-with-discounts) | [![Java](assets/java.png)](src/MinimumCostToReachCityWithDiscounts.java) | | +| 2094 | [Finding 3-Digit Even Numbers](https://leetcode.com/problems/finding-3-digit-even-numbers) | [![Java](assets/java.png)](src/Finding3DigitEvenNumbers.java) | | +| 2099 | [Find Subsequence of Length K With the Largest Sum](https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum) | [![Java](assets/java.png)](src/FindSubsequenceOfLengthKWithTheLargestSum.java) | | +| 2103 | [Rings and Rods](https://leetcode.com/problems/rings-and-rods) | [![Java](assets/java.png)](src/RingsAndRods.java) | | +| 2108 | [Find First Palindromic String in the Array](https://leetcode.com/problems/find-first-palindromic-string-in-the-array) | [![Java](assets/java.png)](src/FindFirstPalindromicStringInArray.java) | | +| 2114 | [Maximum Number of Words Found in Sentences](https://leetcode.com/problems/maximum-number-of-words-found-in-sentences) | [![Java](assets/java.png)](src/MaximumNumberOfWordsFoundInSentences.java) | | +| 2119 | [A Number After a Double Reversal](https://leetcode.com/problems/a-number-after-a-double-reversal) | [![Java](assets/java.png)](src/ANumberAfterADoubleReversal.java) | | +| 2124 | [Check if All A's Appears Before All B's](https://leetcode.com/problems/check-if-all-as-appears-before-all-bs) | [![Java](assets/java.png)](src/CheckIfAllTheAsAppearBeforeAllTheBs.java) | | +| 2129 | [Capitalize the Title](https://leetcode.com/problems/capitalize-the-title) | [![Java](assets/java.png)](src/CapitalizeTheTitle.java) | | +| 2133 | [Check if Every Row and Column Contains All Numbers](https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers) | [![Java](assets/java.png)](src/CheckIfEveryRowAndEveryColumnContainAllNumbers.java) | | +| 2138 | [Divide a String Into Groups of Size k](https://leetcode.com/problems/divide-a-string-into-groups-of-size-k) | [![Java](assets/java.png)](src/DivideTheStringIntoGroupsOfSizeK.java) | | +| 2144 | [Minimum Cost of Buying Candies With Discount](https://leetcode.com/problems/minimum-cost-of-buying-candies-with-discount) | [![Java](assets/java.png)](src/MinimumCostOfBuyingCandiesWithDiscount.java) | | +| 2148 | [Count Elements With Strictly Smaller and Greater Elements](https://leetcode.com/problems/count-elements-with-strictly-smaller-and-greater-elements) | [![Java](assets/java.png)](src/CountElementsWithStrictlySmallerAndGreaterElements.java) | | +| 2154 | [Keep Multiplying Found Values by Two](https://leetcode.com/problems/keep-multiplying-found-values-by-two) | [![Java](assets/java.png)](src/KeepMultiplyingFoundValuesByTwo.java) | | +| 2160 | [Minimum Sum of Four Digit Number After Splitting Digits](https://leetcode.com/problems/minimum-sum-of-four-digit-number-after-splitting-digits) | [![Java](assets/java.png)](src/MinimumSumOfFourDigitNumberAfterSplittingDigits.java) | | +| 2164 | [Sort Even and Odd Indices Independently](https://leetcode.com/problems/sort-even-and-odd-indices-independently) | [![Java](assets/java.png)](src/SortEvenAndOddIndicesIndependently.java) | | +| 2169 | [Count Operations to Obtain Zero](https://leetcode.com/problems/count-operations-to-obtain-zero) | [![Java](assets/java.png)](src/CountOperationsToObtainZero.java) | | +| 2176 | [Count Equal and Divisible Pairs in an Array](https://leetcode.com/problems/count-equal-and-divisible-pairs-in-an-array) | [![Java](assets/java.png)](src/CountEqualAndDivisiblePairsInAnArray.java) | | +| 2180 | [Count Integers With Even Digit Sum](https://leetcode.com/problems/count-integers-with-even-digit-sum) | [![Java](assets/java.png)](src/CountIntegersWithEvenDigitSum.java) | | +| 2185 | [Counting Words With a Given Prefix](https://leetcode.com/problems/counting-words-with-a-given-prefix) | [![Java](assets/java.png)](src/CountingWordsWithAGivenPrefix.java) | | +| 2190 | [Most Frequent Number Following Key In an Array](https://leetcode.com/problems/most-frequent-number-following-key-in-an-array) | [![Java](assets/java.png)](src/MostFrequentNumberFollowingKeyInAnArray.java) | | +| 2194 | [Cells in a Range on an Excel Sheet](https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet) | [![Java](assets/java.png)](src/CellsInARangeOnAnExcelSheet.java) | | +| 2200 | [Find All K-Distant Indices in an Array](https://leetcode.com/problems/find-all-k-distant-indices-in-an-array) | [![Java](assets/java.png)](src/FindAllKDistantIndicesInAnArray.java) | | +| 2206 | [Divide Array Into Equal Pairs](https://leetcode.com/problems/divide-array-into-equal-pairs) | [![Java](assets/java.png)](src/DivideArrayIntoEqualPairs.java) | | +| 2210 | [Count Hills and Valleys in an Array](https://leetcode.com/problems/count-hills-and-valleys-in-an-array) | [![Java](assets/java.png)](src/CountHillsAndValleysInAnArray.java) | | +| 2215 | [Find the Difference of Two Arrays](https://leetcode.com/problems/find-the-difference-of-two-arrays) | [![Java](assets/java.png)](src/FindTheDifferenceOfTwoArrays.java) | | +| 2220 | [Minimum Bit Flips to Convert Number](https://leetcode.com/problems/minimum-bit-flips-to-convert-number) | [![Java](assets/java.png)](src/MinimumBitFlipsToConvertNumber.java) | | +| 2224 | [Minimum Number of Operations to Convert Time](https://leetcode.com/problems/minimum-number-of-operations-to-convert-time) | [![Java](assets/java.png)](src/MinimumNumberOfOperationsToConvertTime.java) | | +| 2229 | 🔒 [Check if an array is consecutive](https://leetcode.com/problems/check-if-an-array-is-consecutive) | | | +| 2231 | [Largest Number After Digit Swaps by Parity](https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity) | [![Java](assets/java.png)](src/LargestNumberAfterDigitSwapsByParity.java) | | +| 2235 | [Add Two Integers](https://leetcode.com/problems/add-two-integers) | [![Java](assets/java.png)](src/AddTwoIntegers.java) | | +| 2236 | [Root Equals Sum of Children](https://leetcode.com/problems/root-equals-sum-of-children) | [![Java](assets/java.png)](src/RootEqualsSumOfChildren.java) | | +| 2239 | [Find Closest Number to Zero](https://leetcode.com/problems/find-closest-number-to-zero) | [![Java](assets/java.png)](src/FindClosestNumberToZero.java) | | +| 2243 | [Calculate Digit Sum of a String](https://leetcode.com/problems/calculate-digit-sum-of-a-string) | [![Java](assets/java.png)](src/CalculateDigitSumOfAString.java) | | +| 2248 | [Intersection of Multiple Arrays](https://leetcode.com/problems/intersection-of-multiple-arrays) | [![Java](assets/java.png)](src/IntersectionOfMultipleArrays.java) | | +| 2255 | [Count Prefixes of a Given String](https://leetcode.com/problems/count-prefixes-of-a-given-string) | [![Java](assets/java.png)](src/CountPrefixesOfAGivenString.java) | | +| 2259 | [Remove Digit From Number to Maximize Result](https://leetcode.com/problems/remove-digit-from-number-to-maximize-result) | [![Java](assets/java.png)](src/RemoveDigitFromNumberToMaximizeResult.java) | | +| 2264 | [Largest 3-Same-Digit Number in String](https://leetcode.com/problems/largest-3-same-digit-number-in-string) | [![Java](assets/java.png)](src/Largest3SameDigitNumberInString.java) | | +| 2269 | [Find the K-Beauty of a Number](https://leetcode.com/problems/find-the-k-beauty-of-a-number) | [![Java](assets/java.png)](src/FindTheKBeautyOfANumber.java) | | +| 2273 | [Find Resultant Array After Removing Anagrams](https://leetcode.com/problems/find-resultant-array-after-removing-anagrams) | [![Java](assets/java.png)](src/FindResultantArrayAfterRemovingAnagrams.java) | | +| 2278 | [Percentage of Letter in String](https://leetcode.com/problems/percentage-of-letter-in-string) | [![Java](assets/java.png)](src/PercentageOfLetterInString.java) | | +| 2283 | [Check if Number Has Equal Digit Count and Digit Value](https://leetcode.com/problems/check-if-number-has-equal-digit-count-and-digit-value) | [![Java](assets/java.png)](src/CheckIfNumberHasEqualDigitCountAndDigitValue.java) | | +| 2287 | [Rearrange Characters to Make Target String](https://leetcode.com/problems/rearrange-characters-to-make-target-string) | [![Java](assets/java.png)](src/RearrangeCharactersToMakeTargetString.java) | | +| 2293 | [Min Max Game](https://leetcode.com/problems/min-max-game) | [![Java](assets/java.png)](src/MinMaxGame.java) | | +| 2299 | [Strong Password Checker II](https://leetcode.com/problems/strong-password-checker-ii) | [![Java](assets/java.png)](src/StrongPasswordCheckerII.java) | | +| 2300 | [Successful Pairs of Spells and Potions](https://leetcode.com/problems/successful-pairs-of-spells-and-potions) | [![Python](assets/python.png)](python/successfull_pairs_of_spells_and_potions.py) | | +| 2303 | [Calculate Amount Paid in Taxes](https://leetcode.com/problems/calculate-amount-paid-in-taxes) | [![Java](assets/java.png)](src/CalculateAmountPaidInTaxes.java) | | +| 2309 | [Greatest English Letter in Upper and Lower Case](https://leetcode.com/problems/greatest-english-letter-in-upper-and-lower-case) | [![Java](assets/java.png)](src/GreatestEnglishLetterInUpperAndLowerCase.java) | | +| 2315 | [Count Asterisks](https://leetcode.com/problems/count-asterisks) | [![Java](assets/java.png)](src/CountAsterisks.java) [![Python](assets/python.png)](python/successfull_pairs_of_spells_and_potions.py) | | +| 2316 | [Count Unreachable Pairs of Nodes in an Undirected Graph](https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph) | [![Python](assets/python.png)](python/count_unreachable_pair_of_node_in_an_undirectable_graph.py) | | +| 2319 | [Check if Matrix Is X-Matrix](https://leetcode.com/problems/check-if-matrix-is-x-matrix) | [![Java](assets/java.png)](src/CountAsterisks.java) | | +| 2325 | [Decode the Message](https://leetcode.com/problems/decode-the-message) | [![Java](assets/java.png)](src/DecodeTheMessage.java) | | +| 2331 | [Evaluate Boolean Binary Tree](https://leetcode.com/problems/evaluate-boolean-binary-tree) | [![Java](assets/java.png)](src/EvaluateBooleanBinaryTree.java) | | +| 2335 | [Minimum Amount of Time to Fill Cups](https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups) | [![Java](assets/java.png)](src/MinimumAmountOfTimeToFillCups.java) | | +| 2439 | [Minimize Maximum of Array](https://leetcode.com/problems/minimize-maximum-of-array) | [![Python](assets/python.png)](python/minimize_maximum_of_array.py) | | +| 2341 | [Maximum Number of Pairs in Array](https://leetcode.com/problems/maximum-number-of-pairs-in-array) | [![Java](assets/java.png)](src/MaximumNumberOfPairsInArray.java) | | +| 2347 | [Best Poker Hand](https://leetcode.com/problems/best-poker-hand) | [![Java](assets/java.png)](src/BestPokerHand.java) | | +| 2348 | [Number of Zero-Filled Subarrays](https://leetcode.com/problems/number-of-zero-filled-subarrays) | [![Python](assets/python.png)](python/number_of_zero_filled_subarrays.py) | | +| 2351 | [First Letter to Appear Twice](https://leetcode.com/problems/first-letter-to-appear-twice) | [![Java](assets/java.png)](src/FirstLetterToAppearTwice.java) | | +| 2357 | [Make Array Zero by Subtracting Equal Amounts](https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts) | [![Java](assets/java.png)](src/MakeArrayZeroBySubtractingEqualAmounts.java) | | +| 2360 | [Longest Cycle in a Graph](https://leetcode.com/problems/longest-cycle-in-a-graph) | [![Python](assets/python.png)](python/longest_cycle_in_graph.py) | | +| 2363 | [Merge Similar Items](https://leetcode.com/problems/merge-similar-items) | [![Java](assets/java.png)](src/MergeSimilarItems.java) | | +| 2367 | [Number of Arithmetic Triplets](https://leetcode.com/problems/number-of-arithmetic-triplets) | [![Java](assets/java.png)](src/NumberOfArithmeticTriplets.java) | | +| 2373 | [Largest Local Values in a Matrix](https://leetcode.com/problems/largest-local-values-in-a-matrix) | [![Java](assets/java.png)](src/LargestLocalValuesInAMatrix.java) | | +| 2379 | [Minimum Recolors to Get K Consecutive Black Blocks](https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks) | [![Java](assets/java.png)](src/MinimumRecolorsToGetKConsecutiveBlackBlocks.java) | | +| 2383 | [Minimum Hours of Training to Win a Competition](https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition) | [![Java](assets/java.png)](src/MinimumHoursOfTrainingToWinACompetition.java) | | +| 2389 | [Longest Subsequence With Limited Sum](https://leetcode.com/problems/longest-subsequence-with-limited-sum) | [![Java](assets/java.png)](src/LongestSubsequenceWithLimitedSum.java) | | +| 2395 | [Find Subarrays With Equal Sum](https://leetcode.com/problems/find-subarrays-with-equal-sum) | [![Java](assets/java.png)](src/FindSubarraysWithEqualSum.java) | | +| 2399 | [Check Distances Between Same Letters](https://leetcode.com/problems/check-distances-between-same-letters) | [![Java](assets/java.png)](src/CheckDistancesBetweenSameLetters.java) | | +| 2404 | [Most Frequent Even Element](https://leetcode.com/problems/most-frequent-even-element) | [![Java](assets/java.png)](src/MostFrequentEvenElement.java) | | +| 2409 | [Count Days Spent Together](https://leetcode.com/problems/count-days-spent-together) | [![Java](assets/java.png)](src/CountDaysSpentTogether.java) | | +| 2413 | [Smallest Even Multiple](https://leetcode.com/problems/smallest-even-multiple) | [![Java](assets/java.png)](src/SmallestEvenMultiple.java) | | +| 2418 | [Sort the People](https://leetcode.com/problems/sort-the-people) | [![Java](assets/java.png)](src/SortThePeople.java) | | +| 2423 | [Remove Letter To Equalize Frequency](https://leetcode.com/problems/remove-letter-to-equalize-frequency) | [![Java](assets/java.png)](src/RemoveLetterToEqualizeFrequency.java) | | +| 2427 | [Number of Common Factors](https://leetcode.com/problems/number-of-common-factors) | [![Java](assets/java.png)](src/NumberOfCommonFactors.java) | | +| 2432 | [The Employee That Worked on the Longest Task](https://leetcode.com/problems/the-employee-that-worked-on-the-longest-task) | [![Java](assets/java.png)](src/TheEmployeeThatWorkedOnTheLongestTask.java) | | +| 2437 | [Number of Valid Clock Times](https://leetcode.com/problems/number-of-valid-clock-times) | [![Java](assets/java.png)](src/NumberOfValidClockTimes.java) | | +| 2441 | [Largest Positive Integer That Exists With Its Negative](https://leetcode.com/problems/largest-positive-integer-that-exists-with-its-negative) | [![Java](assets/java.png)](src/LargestPositiveIntegerThatExistsWithItsNegative.java) | | +| 2446 | [Determine if Two Events Have Conflict](https://leetcode.com/problems/determine-if-two-events-have-conflict) | [![Java](assets/java.png)](src/DetermineIfTwoEventsHaveConflict.java) | | +| 2451 | [Odd String Difference](https://leetcode.com/problems/odd-string-difference) | [![Java](assets/java.png)](src/OddStringDifference.java) | | +| 2455 | [Average Value of Even Numbers That Are Divisible by Three](https://leetcode.com/problems/average-value-of-even-numbers-that-are-divisible-by-three) | [![Java](assets/java.png)](src/AverageValueOfEvenNumbersThatAreDivisibleByThree.java) | | +| 2460 | [Apply Operations to an Array](https://leetcode.com/problems/apply-operations-to-an-array) | [![Java](assets/java.png)](src/ApplyOperationsToAnArray.java) | | +| 2465 | [Number of Distinct Averages](https://leetcode.com/problems/number-of-distinct-averages) | [![Java](assets/java.png)](src/NumberOfDistinctAverages.java) | | +| 2466 | [Count Ways To Build Good Strings](https://leetcode.com/problems/count-ways-to-build-good-strings) | | | +| 2469 | [Convert the Temperature](https://leetcode.com/problems/convert-the-temperature) | [![Java](assets/java.png)](src/ConvertTheTemperature.java) | | +| 2475 | [Number of Unequal Triplets in Array](https://leetcode.com/problems/number-of-unequal-triplets-in-array) | [![Java](assets/java.png)](src/NumberOfUnequalTripletsInArray.java) | | +| 2481 | [Minimum Cuts to Divide a Circle](https://leetcode.com/problems/minimum-cuts-to-divide-a-circle) | [![Java](assets/java.png)](src/MinimumCutsToDivideACircle.java) | | +| 2485 | [Find the Pivot Integer](https://leetcode.com/problems/find-the-pivot-integer) | [![Java](assets/java.png)](src/FindThePivotInteger.java) | | +| 2490 | [Circular Sentence](https://leetcode.com/problems/circular-sentence) | [![Java](assets/java.png)](src/CircularSentence.java) | | +| 2492 | [Minimum Score of a Path Between Two Cities](https://leetcode.com/problems/minimum-score-of-a-path-between-two-cities) | [![Python](assets/python.png)](python/minimum_score_of_a_path_between_two_cities.py) | | +| 2496 | [Maximum Value of a String in an Array](https://leetcode.com/problems/maximum-value-of-a-string-in-an-array) | [![Java](assets/java.png)](src/MaximumValueOfAStringInAnArray.java) | | +| 2500 | [Delete Greatest Value in Each Row](https://leetcode.com/problems/delete-greatest-value-in-each-row) | [![Java](assets/java.png)](src/DeleteGreatestValueInEachRow.java) | | +| 2506 | [Count Pairs Of Similar Strings](https://leetcode.com/problems/count-pairs-of-similar-strings) | [![Java](assets/java.png)](src/CountPairsOfSimilarStrings.java) | | +| 2511 | [Maximum Enemy Forts That Can Be Captured](https://leetcode.com/problems/maximum-enemy-forts-that-can-be-captured) | [![Java](assets/java.png)](src/MaximumEnemyFortsThatCanBeCaptured.java) | | +| 2515 | [Shortest Distance to Target String in a Circular Array](https://leetcode.com/problems/shortest-distance-to-target-string-in-a-circular-array) | [![Java](assets/java.png)](src/ShortestDistanceToTargetStringInACircularArray.java) | | +| 2520 | [Count the Digits That Divide a Number](https://leetcode.com/problems/count-the-digits-that-divide-a-number) | [![Java](assets/java.png)](src/CountTheDigitsThatDivideANumber.java) | | +| 2525 | [Categorize Box According to Criteria](https://leetcode.com/problems/categorize-box-according-to-criteria) | [![Java](assets/java.png)](src/CategorizeBoxAccordingToCriteria.java) | | +| 2529 | [Maximum Count of Positive Integer and Negative Integer](https://leetcode.com/problems/maximum-count-of-positive-integer-and-negative-integer) | [![Java](assets/java.png)](src/MaximumCountOfPositiveIntegerAndNegativeInteger.java) | | +| 2535 | [Difference Between Element Sum and Digit Sum of an Array](https://leetcode.com/problems/difference-between-element-sum-and-digit-sum-of-an-array) | [![Java](assets/java.png)](src/DifferenceBetweenElementSumAndDigitSumOfAnArray.java) | | +| 2540 | [Minimum Common Value](https://leetcode.com/problems/minimum-common-value) | [![Java](assets/java.png)](src/MinimumCommonValue.java) | | +| 2544 | [Alternating Digit Sum](https://leetcode.com/problems/alternating-digit-sum) | [![Java](assets/java.png)](src/AlternatingDigitSum.java) | | +| 2549 | [Count Distinct Numbers on Board](https://leetcode.com/problems/count-distinct-numbers-on-board) | [![Java](assets/java.png)](src/CountDistinctNumbersOnBoard.java) | | +| 2553 | [Separate the Digits in an Array](https://leetcode.com/problems/separate-the-digits-in-an-array) | [![Java](assets/java.png)](src/SeparateTheDigitsInAnArray.java) | | +| 2558 | [Take Gifts From the Richest Pile](https://leetcode.com/problems/take-gifts-from-the-richest-pile) | [![Java](assets/java.png)](src/TakeGiftsFromTheRichestPile.java) | | +| 2562 | [Find the Array Concatenation Value](https://leetcode.com/problems/find-the-array-concatenation-value) | [![Java](assets/java.png)](src/FindTheArrayConcatenationValue.java) | | +| 2566 | [Maximum Difference by Remapping a Digit](https://leetcode.com/problems/maximum-difference-by-remapping-a-digit) | [![Java](assets/java.png)](src/MaximumDifferenceByRemappingADigit.java) | | +| 2570 | [Merge Two 2D Arrays by Summing Values](https://leetcode.com/problems/merge-two-2d-arrays-by-summing-values) | [![Java](assets/java.png)](src/MergeTwo2DArraysBySummingValues.java) | | +| 2574 | [Left and Right Sum Differences](https://leetcode.com/problems/left-and-right-sum-differences) | [![Java](assets/java.png)](src/LeftAndRightSumDifferences.java) | | +| 2578 | [Split With Minimum Sum](https://leetcode.com/problems/split-with-minimum-sum) | [![Java](assets/java.png)](src/SplitWithMinimumSum.java) | | +| 2582 | [Pass the Pillow](https://leetcode.com/problems/pass-the-pillow) | [![Java](assets/java.png)](src/PassThePillow.java) | | +| 2586 | [Count the Number of Vowel Strings in Range](https://leetcode.com/problems/count-the-number-of-vowel-strings-in-range) | [![Java](assets/java.png)](src/CountTheNumberOfVowelStringsInRange.java) | | +| 2591 | [Distribute Money to Maximum Children](https://leetcode.com/problems/distribute-money-to-maximum-children) | [![Java](assets/java.png)](src/DistributeMoneyToMaximumChildren.java) | | +| 2595 | [Number of Even and Odd Bits](https://leetcode.com/problems/number-of-even-and-odd-bits) | [![Java](assets/java.png)](src/NumberOfEvenAndOddBits.java) | | +| 2600 | [K Items With the Maximum Sum](https://leetcode.com/problems/k-items-with-the-maximum-sum) | [![Java](assets/java.png)](src/KItemsWithTheMaximumSum.java) | | +| 2605 | [Form Smallest Number From Two Digit Arrays](https://leetcode.com/problems/form-smallest-number-from-two-digit-arrays) | [![Java](assets/java.png)](src/FormSmallestNumberFromTwoDigitArrays.java) | | +| 2609 | [Find the Longest Balanced Substring of a Binary String](https://leetcode.com/problems/find-the-longest-balanced-substring-of-a-binary-string) | [![Java](assets/java.png)](src/FindTheLongestBalancedSubstringOfABinaryString.java) | | +| 2614 | [Prime In Diagonal](https://leetcode.com/problems/prime-in-diagonal) | [![Java](assets/java.png)](src/PrimeInDiagonal.java) | | +| 2639 | [Find the Width of Columns of a Grid](https://leetcode.com/problems/find-the-width-of-columns-of-a-grid) | [![Java](assets/java.png)](src/FindTheWidthOfColumnsOfAGrid.java) | | +| 2643 | [Row With Maximum Ones](https://leetcode.com/problems/row-with-maximum-ones) | [![Java](assets/java.png)](src/RowWithMaximumOnes.java) | | +| 2644 | [Find the Maximum Divisibility Score](https://leetcode.com/problems/find-the-maximum-divisibility-score) | [![Java](assets/java.png)](src/FindTheMaximumDivisibilityScore.java) | | +| 2651 | [Calculate Delayed Arrival Time](https://leetcode.com/problems/calculate-delayed-arrival-time) | [![Java](assets/java.png)](src/CalculateDelayedArrivalTime.java) | | +| 2652 | [Sum Multiples](https://leetcode.com/problems/sum-multiples) | [![Java](assets/java.png)](src/SumMultiples.java) | | +| 2656 | [Maximum Sum With Exactly K Elements](https://leetcode.com/problems/maximum-sum-with-exactly-k-elements) | [![Java](assets/java.png)](src/MaximumSumWithExactlyKElements.java) | | +| 2660 | [Determine the Winner of a Bowling Game](https://leetcode.com/problems/determine-the-winner-of-a-bowling-game) | [![Java](assets/java.png)](src/DetermineTheWinnerOfABowlingGame.java) | | +| 2670 | [Find the Distinct Difference Array](https://leetcode.com/problems/find-the-distinct-difference-array) | [![Java](assets/java.png)](src/FindTheDistinctDifferenceArray.java) | | +| 2678 | [Number of Senior Citizens](https://leetcode.com/problems/number-of-senior-citizens) | [![Java](assets/java.png)](src/NumberOfSeniorCitizens.java) | | +| 2682 | [Find the Losers of the Circular Game](https://leetcode.com/problems/find-the-losers-of-the-circular-game) | [![Java](assets/java.png)](src/FindTheLosersOfTheCircularGame.java) | | +| 2689 | 🔒 [Extract Kth Character From The Rope Tree](https://leetcode.com/problems/extract-kth-character-from-the-rope-tree) | | | +| 2696 | [Minimum String Length After Removing Substrings](https://leetcode.com/problems/minimum-string-length-after-removing-substrings) | [![Java](assets/java.png)](src/MinimumStringLengthAfterRemovingSubstrings.java) | | +| 2697 | [Lexicographically Smallest Palindrome](https://leetcode.com/problems/lexicographically-smallest-palindrome) | [![Java](assets/java.png)](src/LexicographicallySmallestPalindrome.java) | | +| 2706 | [Buy Two Chocolates](https://leetcode.com/problems/buy-two-chocolates) | [![Java](assets/java.png)](src/BuyTwoChocolates.java) | | +| 2710 | [Remove Trailing Zeros From a String](https://leetcode.com/problems/remove-trailing-zeros-from-a-string) | [![Java](assets/java.png)](src/RemoveTrailingZerosFromAString.java) | | +| 2716 | [Minimize String Length](https://leetcode.com/problems/minimize-string-length) | [![Java](assets/java.png)](src/MinimizeStringLength.java) | | +| 2717 | [Semi-Ordered Permutation](https://leetcode.com/problems/semi-ordered-permutation) | [![Java](assets/java.png)](src/SemiOrderedPermutation.java) | | +| 2728 | 🔒 [Count Houses in a Circular Street](https://leetcode.com/problems/count-houses-in-a-circular-street) | | | +| 2729 | [Check if The Number is Fascinating](https://leetcode.com/problems/check-if-the-number-is-fascinating) | [![Java](assets/java.png)](src/CheckIfTheNumberIsFascinating.java) | | +| 2733 | [Neither Minimum nor Maximum](https://leetcode.com/problems/neither-minimum-nor-maximum) | [![Java](assets/java.png)](src/NeitherMinimumNorMaximum.java) | | +| 2739 | [Total Distance Traveled](https://leetcode.com/problems/total-distance-traveled) | [![Java](assets/java.png)](src/TotalDistanceTraveled.java) | | +| 2744 | [Find Maximum Number of String Pairs](https://leetcode.com/problems/find-maximum-number-of-string-pairs) | [![Java](assets/java.png)](src/FindMaximumNumberOfStringPairs.java) | | +| 2748 | [Number of Beautiful Pairs](https://leetcode.com/problems/number-of-beautiful-pairs) | [![Java](assets/java.png)](src/NumberOfBeautifulPairs.java) | | +| 2760 | [Longest Even Odd Subarray With Threshold](https://leetcode.com/problems/longest-even-odd-subarray-with-threshold) | [![Java](assets/java.png)](src/LongestEvenOddSubarrayWithThreshold.java) | | +| 2765 | [Longest Alternating Subarray](https://leetcode.com/problems/longest-alternating-subarray) | [![Java](assets/java.png)](src/LongestAlternatingSubarray.java) | | +| 2769 | [Find the Maximum Achievable Number](https://leetcode.com/problems/find-the-maximum-achievable-number) | [![Java](assets/java.png)](src/FindTheMaximumAchievableNumber.java) | | +| 2778 | [Sum of Squares of Special Elements](https://leetcode.com/problems/sum-of-squares-of-special-elements) | [![Java](assets/java.png)](src/SumOfSquaresOfSpecialElements.java) | | +| 2784 | [Check if Array is Good](https://leetcode.com/problems/check-if-array-is-good) | [![Java](assets/java.png)](src/CheckIfArrayIsGood.java) | | +| 2788 | [Split Strings by Separator](https://leetcode.com/problems/split-strings-by-separator) | [![Java](assets/java.png)](src/SplitStringsBySeparator.java) | | +| 2798 | [Number of Employees Who Met the Target](https://leetcode.com/problems/number-of-employees-who-met-the-target) | [![Java](assets/java.png)](src/NumberOfEmployeesWhoMetTheTarget.java) | | +| 2806 | [Account Balance After Rounded Purchase](https://leetcode.com/problems/account-balance-after-rounded-purchase) | [![Java](assets/java.png)](src/AccountBalanceAfterRoundedPurchase.java) | | +| 2810 | [Faulty Keyboard](https://leetcode.com/problems/faulty-keyboard) | [![Java](assets/java.png)](src/FaultyKeyboard.java) | | +| 2815 | [Max Pair Sum in an Array](https://leetcode.com/problems/max-pair-sum-in-an-array) | [![Java](assets/java.png)](src/MaxPairSumInAnArray.java) | | +| 2824 | [Count Pairs Whose Sum is Less than Target](https://leetcode.com/problems/count-pairs-whose-sum-is-less-than-target) | [![Java](assets/java.png)](src/CountPairsWhoseSumIsLessThanTarget.java) | | +| 2828 | [Check if a String Is an Acronym of Words](https://leetcode.com/problems/check-if-a-string-is-an-acronym-of-words) | [![Java](assets/java.png)](src/CheckIfAStringIsAnAcronymOfWords.java) | | +| 2833 | [Furthest Point From Origin](https://leetcode.com/problems/furthest-point-from-origin) | [![Java](assets/java.png)](src/FurthestPointFromOrigin.java) | | +| 2839 | [Check if Strings Can be Made Equal With Operations I](https://leetcode.com/problems/check-if-strings-can-be-made-equal-with-operations-i) | [![Java](assets/java.png)](src/CheckIfStringsCanBeMadeEqualWithOperationsI.java) | | +| 2843 | [Count Symmetric Integers](https://leetcode.com/problems/count-symmetric-integers) | [![Java](assets/java.png)](src/CountSymmetricIntegers.java) | | +| 2848 | [Points That Intersect With Cars](https://leetcode.com/problems/points-that-intersect-with-cars) | [![Java](assets/java.png)](src/PointsThatIntersectWithCars.java) | | +| 2855 | [Minimum Right Shifts to Sort the Array](https://leetcode.com/problems/minimum-right-shifts-to-sort-the-array) | [![Java](assets/java.png)](src/MinimumRightShiftsToSortTheArray.java) | | +| 2859 | [Sum of Values at Indices With K Set Bits](https://leetcode.com/problems/sum-of-values-at-indices-with-k-set-bits) | [![Java](assets/java.png)](src/SumOfValuesAtIndicesWithKSetBits.java) | | +| 2864 | [Maximum Odd Binary Number](https://leetcode.com/problems/maximum-odd-binary-number) | [![Java](assets/java.png)](src/MaximumOddBinaryNumber.java) | | +| 2869 | [Minimum Operations to Collect Elements](https://leetcode.com/problems/minimum-operations-to-collect-elements) | [![Java](assets/java.png)](src/MinimumOperationsToCollectElements.java) | | +| 2873 | [Maximum Value of an Ordered Triplet I](https://leetcode.com/problems/maximum-value-of-an-ordered-triplet-i) | [![Java](assets/java.png)](src/MaximumValueOfAnOrderedTripletI.java) | | +| 2894 | [Divisible and Non-divisible Sums Difference](https://leetcode.com/problems/divisible-and-non-divisible-sums-difference) | [![Java](assets/java.png)](src/DivisibleAndNonDivisibleSumsDifference.java) | | +| 2899 | [Last Visited Integers](https://leetcode.com/problems/last-visited-integers) | [![Java](assets/java.png)](src/LastVisitedIntegers.java) | | +| 2900 | [Longest Unequal Adjacent Groups Subsequence I](https://leetcode.com/problems/longest-unequal-adjacent-groups-subsequence-i) | [![Java](assets/java.png)](src/LongestUnequalAdjacentGroupsSubsequenceI.java) | | +| 2903 | [Find Indices With Index and Value Difference I](https://leetcode.com/problems/find-indices-with-index-and-value-difference-i) | [![Java](assets/java.png)](src/FindIndicesWithIndexAndValueDifferenceI.java) | | +| 2908 | [Minimum Sum of Mountain Triplets I](https://leetcode.com/problems/minimum-sum-of-mountain-triplets-i) | [![Java](assets/java.png)](src/MinimumSumOfMountainTripletsI.java) | | +| 2913 | [Subarrays Distinct Element Sum of Squares I](https://leetcode.com/problems/subarrays-distinct-element-sum-of-squares-i) | [![Java](assets/java.png)](src/SubarraysDistinctElementSumOfSquaresI.java) | | +| 2917 | [Find the K-or of an Array](https://leetcode.com/problems/find-the-k-or-of-an-array) | [![Java](assets/java.png)](src/FindTheKOrOfAnArray.java) | | +| 2923 | [Find Champion I](https://leetcode.com/problems/find-champion-i) | [![Java](assets/java.png)](src/FindChampionI.java) | | +| 2928 | [Distribute Candies Among Children I](https://leetcode.com/problems/distribute-candies-among-children-i) | [![Java](assets/java.png)](src/DistributeCandiesAmongChildrenI.java) | | +| 2932 | [Maximum Strong Pair XOR I](https://leetcode.com/problems/maximum-strong-pair-xor-i) | [![Java](assets/java.png)](src/MaximumStrongPairXORI.java) | | +| 2937 | [Make Three Strings Equal](https://leetcode.com/problems/make-three-strings-equal) | [![Java](assets/java.png)](src/MakeThreeStringsEqual.java) | | +| 2942 | [Find Words Containing Character](https://leetcode.com/problems/find-words-containing-character) | [![Java](assets/java.png)](src/FindWordsContainingCharacter.java) | | +| 2946 | [Matrix Similarity After Cyclic Shifts](https://leetcode.com/problems/matrix-similarity-after-cyclic-shifts) | [![Java](assets/java.png)](src/MatrixSimilarityAfterCyclicShifts.java) | | +| 2951 | [Find the Peaks](https://leetcode.com/problems/find-the-peaks) | [![Java](assets/java.png)](src/FindThePeaks.java) | | +| 2956 | [Find Common Elements Between Two Arrays](https://leetcode.com/problems/find-common-elements-between-two-arrays) | [![Java](assets/java.png)](src/FindCommonElementsBetweenTwoArrays.java) | | +| 2960 | [Count Tested Devices After Test Operations](https://leetcode.com/problems/count-tested-devices-after-test-operations) | [![Java](assets/java.png)](src/CountTestedDevicesAfterTestOperations.java) | | +| 2965 | [Find Missing and Repeated Values](https://leetcode.com/problems/find-missing-and-repeated-values) | [![Java](assets/java.png)](src/FindMissingAndRepeatedValues.java) | | +| 2970 | [Count the Number of Irremovable Subarrays I](https://leetcode.com/problems/count-the-number-of-incremovable-subarrays-i) | [![Java](assets/java.png)](src/CountTheNumberOfIncremovableSubarraysI.java) | | +| 2974 | [Minimum Number Game](https://leetcode.com/problems/minimum-number-game) | [![Java](assets/java.png)](src/MinimumNumberGame.java) | | +| 2980 | [Check if Bitwise OR Has Trailing Zeros](https://leetcode.com/problems/check-if-bitwise-or-has-trailing-zeros) | [![Java](assets/java.png)](src/CheckIfBitwiseORHasTrailingZeros.java) | | +| 2996 | [Smallest Missing Integer Greater Than Sequential Prefix Sum](https://leetcode.com/problems/smallest-missing-integer-greater-than-sequential-prefix-sum) | [![Java](assets/java.png)](src/SmallestMissingIntegerGreaterThanSequentialPrefixSum.java) | | +| 3000 | [Maximum Area of Longest Diagonal Rectangle](https://leetcode.com/problems/maximum-area-of-longest-diagonal-rectangle) | [![Java](assets/java.png)](src/MaximumAreaOfLongestDiagonalRectangle.java) | | +| 3005 | [Count Elements With Maximum Frequency](https://leetcode.com/problems/count-elements-with-maximum-frequency) | [![Java](assets/java.png)](src/CountElementsWithMaximumFrequency.java) | | +| 3010 | [Divide an Array Into Subarrays With Minimum Cost I](https://leetcode.com/problems/divide-an-array-into-subarrays-with-minimum-cost-i) | [![Java](assets/java.png)](src/DivideAnArrayIntoSubarraysWithMinimumCostI.java) | | +| 3014 | [Minimum Number of Pushes to Type Word I](https://leetcode.com/problems/minimum-number-of-pushes-to-type-word-i) | [![Java](assets/java.png)](src/MinimumNumberOfPushesToTypeWordI.java) | | +| 3019 | [Number of Changing Keys](https://leetcode.com/problems/number-of-changing-keys) | [![Java](assets/java.png)](src/NumberOfChangingKeys.java) | | +| 3024 | [Type of Triangle](https://leetcode.com/problems/type-of-triangle) | [![Java](assets/java.png)](src/TypeOfTriangle.java) | | +| 3028 | [Ant on the Boundary](https://leetcode.com/problems/ant-on-the-boundary) | [![Java](assets/java.png)](src/AntOnTheBoundary.java) | | +| 3032 | 🔒 [Count Numbers With Unique Digits II](https://leetcode.com/problems/count-numbers-with-unique-digits-ii) | | | +| 3033 | [Modify the Matrix](https://leetcode.com/problems/modify-the-matrix) | [![Java](assets/java.png)](src/ModifyTheMatrix.java) | | +| 3038 | [Maximum Number of Operations With the Same Score I](https://leetcode.com/problems/maximum-number-of-operations-with-the-same-score-i) | [![Java](assets/java.png)](src/MaximumNumberOfOperationsWithTheSameScoreI.java) | | +| 3042 | [Count Prefix and Suffix Pairs I](https://leetcode.com/problems/count-prefix-and-suffix-pairs-i) | [![Java](assets/java.png)](src/CountPrefixAndSuffixPairsI.java) | | +| 3046 | [Split the Array](https://leetcode.com/problems/split-the-array) | [![Java](assets/java.png)](src/SplitTheArray.java) | | +| 3062 | 🔒 [Winner of the Linked List Game](https://leetcode.com/problems/winner-of-the-linked-list-game) | | | +| 3063 | 🔒 [Linked List Frequency](https://leetcode.com/problems/linked-list-frequency) | | | +| 3065 | [Minimum Operations to Exceed Threshold Value I](https://leetcode.com/problems/minimum-operations-to-exceed-threshold-value-i) | [![Java](assets/java.png)](src/MinimumOperationsToExceedThresholdValueI.java) | | +| 3069 | [Distribute Elements Into Two Arrays I](https://leetcode.com/problems/distribute-elements-into-two-arrays-i) | [![Java](assets/java.png)](src/DistributeElementsIntoTwoArraysI.java) | | +| 3074 | [Apple Redistribution into Boxes](https://leetcode.com/problems/apple-redistribution-into-boxes) | [![Java](assets/java.png)](src/AppleRedistributionIntoBoxes.java) | | +| 3079 | [Find the Sum of Encrypted Integers](https://leetcode.com/problems/find-the-sum-of-encrypted-integers) | [![Java](assets/java.png)](src/FindTheSumOfEncryptedIntegers.java) | | +| 3083 | [Existence of a Substring in a String and Its Reverse](https://leetcode.com/problems/existence-of-a-substring-in-a-string-and-its-reverse) | [![Java](assets/java.png)](src/ExistenceOfASubstringInAStringAndItsReverse.java) | | +| 3090 | [Maximum Length Substring With Two Occurrences](https://leetcode.com/problems/maximum-length-substring-with-two-occurrences) | [![Java](assets/java.png)](src/MaximumLengthSubstringWithTwoOccurrences.java) | | +| 3095 | [Shortest Subarray With OR at Least K I](https://leetcode.com/problems/shortest-subarray-with-or-at-least-k-i) | [![Java](assets/java.png)](src/ShortestSubarrayWithORAtLeastKI.java) | | +| 3099 | [Harshad Number](https://leetcode.com/problems/harshad-number) | [![Java](assets/java.png)](src/HarshadNumber.java) | | +| 3105 | [Longest Strictly Increasing or Strictly Decreasing Subarray](https://leetcode.com/problems/longest-strictly-increasing-or-strictly-decreasing-subarray) | [![Java](assets/java.png)](src/LongestStrictlyIncreasingOrStrictlyDecreasingSubarray.java) | | +| 3110 | [Score of a String](https://leetcode.com/problems/score-of-a-string) | [![Java](assets/java.png)](src/ScoreOfAString.java) | | +| 3114 | [Latest Time You Can Obtain After Replacing Characters](https://leetcode.com/problems/latest-time-you-can-obtain-after-replacing-characters) | [![Java](assets/java.png)](src/LatestTimeYouCanObtainAfterReplacingCharacters.java) | | +| 3120 | [Count the Number of Special Characters I](https://leetcode.com/problems/count-the-number-of-special-characters-i) | [![Java](assets/java.png)](src/CountTheNumberOfSpecialCharactersI.java) | | +| 3127 | [Make a Square with the Same Color](https://leetcode.com/problems/make-a-square-with-the-same-color) | [![Java](assets/java.png)](src/MakeASquareWithTheSameColor.java) | | +| 3131 | [Find the Integer Added to Array I](https://leetcode.com/problems/find-the-integer-added-to-array-i) | [![Java](assets/java.png)](src/FindTheIntegerAddedToArrayI.java) | | +| 3136 | [Valid Word](https://leetcode.com/problems/valid-word) | [![Java](assets/java.png)](src/ValidWord.java) | | +| 3142 | [Check if Grid Satisfies Conditions](https://leetcode.com/problems/check-if-grid-satisfies-conditions) | [![Java](assets/java.png)](src/CheckIfGridSatisfiesConditions.java) | | +| 3146 | [Permutation Difference between Two Strings](https://leetcode.com/problems/permutation-difference-between-two-strings) | [![Java](assets/java.png)](src/PermutationDifferenceBetweenTwoStrings.java) | | +| 3151 | [Special Array I](https://leetcode.com/problems/special-array-i) | [![Java](assets/java.png)](src/SpecialArrayI.java) | | +| 3158 | [Find the XOR of Numbers Which Appear Twice](https://leetcode.com/problems/find-the-xor-of-numbers-which-appear-twice) | [![Java](assets/java.png)](src/FindTheXOROfNumbersWhichAppearTwice.java) | | +| 3162 | [Find the Number of Good Pairs I](https://leetcode.com/problems/find-the-number-of-good-pairs-i) | [![Java](assets/java.png)](src/FindTheNumberOfGoodPairsI.java) | | +| 3168 | [Minimum Number of Chairs in a Waiting Room](https://leetcode.com/problems/minimum-number-of-chairs-in-a-waiting-room) | [![Java](assets/java.png)](src/MinimumNumberOfChairsInAWaitingRoom.java) | | +| 3173 | 🔒 [Bitwise OR of Adjacent Elements](https://leetcode.com/problems/bitwise-or-of-adjacent-elements) | | | +| 3174 | [Clear Digits](https://leetcode.com/problems/clear-digits) | [![Java](assets/java.png)](src/ClearDigits.java) | | +| 3178 | [Find the Child Who Has the Ball After K Seconds](https://leetcode.com/problems/find-the-child-who-has-the-ball-after-k-seconds) | [![Java](assets/java.png)](src/FindTheChildWhoHasTheBallAfterKSeconds.java) | | +| 3184 | [Count Pairs That Form a Complete Day I](https://leetcode.com/problems/count-pairs-that-form-a-complete-day-i) | [![Java](assets/java.png)](src/CountPairsThatFormACompleteDayI.java) | | +| 3190 | [Find Minimum Operations to Make All Elements Divisible by Three](https://leetcode.com/problems/find-minimum-operations-to-make-all-elements-divisible-by-three) | [![Java](assets/java.png)](src/FindMinimumOperationsToMakeAllElementsDivisibleByThree.java) | | +| 3194 | [Minimum Average of Smallest and Largest Elements](https://leetcode.com/problems/minimum-average-of-smallest-and-largest-elements) | [![Java](assets/java.png)](src/MinimumAverageOfSmallestAndLargestElements.java) | | +| 3199 | 🔒 [Count Triplets With Even XOR Set Bits I](https://leetcode.com/problems/count-triplets-with-even-xor-set-bits-i) | | | +| 3200 | [Maximum Height of a Triangle](https://leetcode.com/problems/maximum-height-of-a-triangle) | [![Java](assets/java.png)](src/MaximumHeightOfATriangle.java) | | +| 3206 | [Alternating Groups I](https://leetcode.com/problems/alternating-groups-i) | [![Java](assets/java.png)](src/AlternatingGroupsI.java) | | +| 3210 | [Find the Encrypted String](https://leetcode.com/problems/find-the-encrypted-string) | [![Java](assets/java.png)](src/FindTheEncryptedString.java) | | +| 3216 | [Lexicographically Smallest String After a Swap](https://leetcode.com/problems/lexicographically-smallest-string-after-a-swap) | [![Java](assets/java.png)](src/LexicographicallySmallestStringAfterASwap.java) | | +| 3222 | [Find the Winning Player in Coin Game](https://leetcode.com/problems/find-the-winning-player-in-coin-game) | [![Java](assets/java.png)](src/FindTheWinningPlayerInCoinGame.java) | | +| 3226 | [Number of Bit Changes to Make Two Integers Equal](https://leetcode.com/problems/number-of-bit-changes-to-make-two-integers-equal) | [![Java](assets/java.png)](src/NumberOfBitChangesToMakeTwoIntegersEqual.java) | | +| 3232 | [Find if Digit Game Can Be Won](https://leetcode.com/problems/find-if-digit-game-can-be-won) | | | +| 3238 | [Find the Number of Winning Players](https://leetcode.com/problems/find-the-number-of-winning-players) | | | +| 3242 | [Design Neighbor Sum Service](https://leetcode.com/problems/design-neighbor-sum-service) | | | +| 3248 | [Snake in Matrix](https://leetcode.com/problems/snake-in-matrix) | | | +| 3258 | [Count Substrings That Satisfy K-Constraint I](https://leetcode.com/problems/count-substrings-that-satisfy-k-constraint-i) | | | +| 3263 | 🔒 [Convert Doubly Linked List To Array I](https://leetcode.com/problems/convert-doubly-linked-list-to-array-i) | | | +| 3270 | [Find the Key of the Numbers](https://leetcode.com/problems/find-the-key-of-the-numbers) | | | +| 3274 | [Check if Two Chessboard Squares Have the Same Color](https://leetcode.com/problems/check-if-two-chessboard-squares-have-the-same-color) | | | +| 3280 | [Convert Date to Binary](https://leetcode.com/problems/convert-date-to-binary) | | | +| 3285 | [Find Indices of Stable Mountains](https://leetcode.com/problems/find-indices-of-stable-mountains) | | | +| 3289 | [The Two Sneaky Numbers of Digitville](https://leetcode.com/problems/the-two-sneaky-numbers-of-digitville) | | | +| 3300 | [Minimum Element After Replacement With Digit Sum](https://leetcode.com/problems/minimum-element-after-replacement-with-digit-sum) | | | +| 3304 | [Find the K-th Character in String Game I](https://leetcode.com/problems/find-the-k-th-character-in-string-game-i) | | | +| 3314 | [Construct the Minimum Bitwise Array I](https://leetcode.com/problems/construct-the-minimum-bitwise-array-i) | | | +| 3318 | [Find X-Sum of All K-Long Subarrays I](https://leetcode.com/problems/find-x-sum-of-all-k-long-subarrays-i) | | | +| 3330 | [Find the Original Typed String I](https://leetcode.com/problems/find-the-original-typed-string-i) | | | +| 3340 | [Check Balanced String](https://leetcode.com/problems/check-balanced-string) | | | diff --git a/assets/java-yt-icon.jpg b/assets/java-yt-icon.jpg new file mode 100644 index 0000000..399f4a4 Binary files /dev/null and b/assets/java-yt-icon.jpg differ diff --git a/assets/java-yt-icon.psd b/assets/java-yt-icon.psd new file mode 100644 index 0000000..dca6126 Binary files /dev/null and b/assets/java-yt-icon.psd differ diff --git a/assets/java-yt.png b/assets/java-yt.png new file mode 100644 index 0000000..07d061d Binary files /dev/null and b/assets/java-yt.png differ diff --git a/assets/java.png b/assets/java.png new file mode 100644 index 0000000..434661a Binary files /dev/null and b/assets/java.png differ diff --git a/assets/javascript.png b/assets/javascript.png new file mode 100644 index 0000000..70978bc Binary files /dev/null and b/assets/javascript.png differ diff --git a/assets/python-yt-icon.psd b/assets/python-yt-icon.psd new file mode 100644 index 0000000..6a30846 Binary files /dev/null and b/assets/python-yt-icon.psd differ diff --git a/assets/python-yt.png b/assets/python-yt.png new file mode 100644 index 0000000..392ba92 Binary files /dev/null and b/assets/python-yt.png differ diff --git a/assets/python.png b/assets/python.png new file mode 100644 index 0000000..2bd7a0a Binary files /dev/null and b/assets/python.png differ diff --git a/assets/yt-45.png b/assets/yt-45.png new file mode 100644 index 0000000..eaaf408 Binary files /dev/null and b/assets/yt-45.png differ diff --git a/assets/yt-50.png b/assets/yt-50.png new file mode 100644 index 0000000..79bdcfd Binary files /dev/null and b/assets/yt-50.png differ diff --git a/assets/yt.png b/assets/yt.png new file mode 100644 index 0000000..d81aad0 Binary files /dev/null and b/assets/yt.png differ diff --git a/javascript/AddTwoNumbers.js b/javascript/AddTwoNumbers.js new file mode 100644 index 0000000..2068a40 --- /dev/null +++ b/javascript/AddTwoNumbers.js @@ -0,0 +1,39 @@ +// https://leetcode.com/problems/add-two-numbers/ +// T: O(max(|l1|, |l2|)) +// S: O(max(|l1|, |l2|)) + +const addTwoNumbers = (l1, l2) => { + let p1 = l1; + let p2 = l2; + let carry = 0; + let result_node = new ListNode(-1); + let pointer = result_node; + while (p1 || p2 || carry !== 0) { + let sum = 0; + if (p1 !== null && p2 !== null) { + sum = p1.val + p2.val; + p1 = p1.next; + p2 = p2.next; + } else if (p1 !== null) { + sum = p1.val; + p1 = p1.next; + } else if (p2 !== null) { + sum = p2.val; + p2 = p2.next; + } + + if (carry !== 0) { + sum = sum + carry; + carry = 0; + } + + if (sum > 9) { + carry = Math.floor(sum / 10); + sum = sum % 10; + } + + pointer.next = new ListNode(sum); + pointer = pointer.next; + } + return result_node.next; +}; diff --git a/javascript/PalindromeNumber.js b/javascript/PalindromeNumber.js new file mode 100644 index 0000000..1779c43 --- /dev/null +++ b/javascript/PalindromeNumber.js @@ -0,0 +1,18 @@ +// https://leetcode.com/problems/palindrome-number +// T: O(log(n)) +// S: O(1) + +const isPalindrome = x => { + if (x < 0 || (x % 10 === 0 && x !== 0)) { + return false; + } + let result = x; + let sum = 0; + while (x !== 0) { + let remainder = x % 10; + sum = sum * 10 + remainder; + x = Math.floor(x / 10); + } + + return sum === result; +}; diff --git a/javascript/RemoveDuplicatesFromSortedArray.js b/javascript/RemoveDuplicatesFromSortedArray.js new file mode 100644 index 0000000..27f75b1 --- /dev/null +++ b/javascript/RemoveDuplicatesFromSortedArray.js @@ -0,0 +1,14 @@ +// https://leetcode.com/problems/remove-duplicates-from-sorted-array/ +// T: O(N) +// S: O(1) + +const removeDuplicates = (nums) => { + let index = 0; + for (let i = 1; i < nums.length; i++) { + if (nums[index] < nums[i]) { + nums[index + 1] = nums[i]; + index++; + } + } + return index + 1; +}; diff --git a/javascript/ReverseInteger.js b/javascript/ReverseInteger.js new file mode 100644 index 0000000..8851b80 --- /dev/null +++ b/javascript/ReverseInteger.js @@ -0,0 +1,22 @@ +// https://leetcode.com/problems/reverse-integer +// T: O(log(n)) +// S: O(1) + +const INTEGER_MAX_VAL = 2147483647; + +const reverse = x => { + let result = 0; + const isNegative = x <= 0; + let absNumber = Math.abs(x); + + while (absNumber !== 0) { + let remainder = absNumber % 10; + absNumber = Math.floor(absNumber / 10); + result = result * 10 + remainder; + if (result > INTEGER_MAX_VAL) { + return 0; + } + } + + return isNegative ? -result : result; +}; diff --git a/programming-language-logos.md b/programming-language-logos.md new file mode 100644 index 0000000..29996e9 --- /dev/null +++ b/programming-language-logos.md @@ -0,0 +1,21 @@ +## Programming Language Logos +To add a logo in the [README](README.md) table simply add a link with an embedded picture as +```markdown +[![Python](icon-link)](this link will be filled by the author if the pull request is accepted) +``` + +For the icon link refer to the table below to obtain the link for a specific programming language: + +| Programming Language | Icon | Icon Link | +|:--------------------:|:------------------------------------------------------------------------------:|:---------------------------------------------------------------------:| +| Java | ![Java](assets/java.png) | assets/java.png | +| Python | ![Python](assets/python.png) | assets/python.png | +| C | ![C](https://img.icons8.com/color/35/000000/c-programming.png) | https://img.icons8.com/color/35/000000/c-programming.png | +| C++ | ![C++](https://img.icons8.com/color/35/000000/c-plus-plus-logo.png) | https://img.icons8.com/color/35/000000/c-plus-plus-logo.png | +| C# | ![C#](https://img.icons8.com/color/35/000000/c-sharp-logo.png) | https://img.icons8.com/color/35/000000/c-sharp-logo.png | +| JavaScript | ![JavaScript](https://img.icons8.com/color/40/000000/javascript.png) | https://img.icons8.com/color/40/000000/javascript.png | +| TypeScript | ![TypeScript](https://img.icons8.com/color/40/000000/typescript.png) | https://img.icons8.com/color/40/000000/typescript.png | +| Ruby | ![Ruby](https://img.icons8.com/office/35/000000/ruby-programming-language.png) | https://img.icons8.com/office/35/000000/ruby-programming-language.png | +| Scala | ![Scala](https://img.icons8.com/dusk/35/000000/scala.png) | https://img.icons8.com/office/35/000000/ruby-programming-language.png | +| PHP | ![PHP](https://img.icons8.com/officel/40/000000/php-logo.png) | https://img.icons8.com/officel/40/000000/php-logo.png | +| Swift | ![Swift](https://img.icons8.com/fluent/40/000000/swift.png) | https://img.icons8.com/fluent/40/000000/swift.png | diff --git a/python/add_binary.py b/python/add_binary.py new file mode 100644 index 0000000..a99f439 --- /dev/null +++ b/python/add_binary.py @@ -0,0 +1,4 @@ +class Solution: + def addBinary(self, a: str, b: str) -> str: + return bin(int(a, base=2) + int(b, base=2))[2:] + diff --git a/python/add_digits.py b/python/add_digits.py new file mode 100644 index 0000000..3b139ed --- /dev/null +++ b/python/add_digits.py @@ -0,0 +1,6 @@ +class Solution: + def addDigits(self, num: int) -> int: + number_str = str(num) + if len(number_str) == 1: + return num + return self.addDigits(sum(int(digit) for digit in number_str)) diff --git a/python/add_strings.py b/python/add_strings.py new file mode 100644 index 0000000..108a0aa --- /dev/null +++ b/python/add_strings.py @@ -0,0 +1,18 @@ +class Solution: + def str_to_int(self, number: str) -> int: + value = 0 + for character in number: + value = 10 * value + ord(character) - 48 + return value + + def int_to_str(self, number: int) -> str: + if number == 0: + return '0' + value = '' + while number > 0: + value = str(number % 10) + value + number //= 10 + return value + + def addStrings(self, num1: str, num2: str) -> str: + return self.int_to_str(self.str_to_int(num1) + self.str_to_int(num2)) diff --git a/python/arranging_coins.py b/python/arranging_coins.py new file mode 100644 index 0000000..4833455 --- /dev/null +++ b/python/arranging_coins.py @@ -0,0 +1,6 @@ +import math + + +class Solution: + def arrangeCoins(self, n: int) -> int: + return math.floor((math.sqrt(8 * n + 1) - 1) / 2) diff --git a/python/array_partiton_I.py b/python/array_partiton_I.py new file mode 100644 index 0000000..492f8a5 --- /dev/null +++ b/python/array_partiton_I.py @@ -0,0 +1,10 @@ +from typing import List + + +class Solution: + def arrayPairSum(self, nums: List[int]) -> int: + nums.sort() + result = 0 + for i in range(0, len(nums) // 2): + result += min(nums[2 * i], nums[2 * i + 1]) + return result diff --git a/python/average_levels_of_binary_tree.py b/python/average_levels_of_binary_tree.py new file mode 100644 index 0000000..894122b --- /dev/null +++ b/python/average_levels_of_binary_tree.py @@ -0,0 +1,34 @@ +# Definition for a binary tree node. +from typing import List +from collections import deque + + +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def averageOfLevels(self, root: TreeNode) -> List[float]: + result = [0] + queue = deque() + queue.append(root) + queue.append(None) + count = 0 + while queue: + current = queue.popleft() + if current is None and len(queue) == 0: break + if current is None: + queue.append(None) + result[-1] /= count + result.append(0) + count = 0 + continue + count += 1 + if current.left is not None: queue.append(current.left) + if current.right is not None: queue.append(current.right) + result[-1] += current.val + result[-1] /= count + return result diff --git a/python/balanced_binary_tree.py b/python/balanced_binary_tree.py new file mode 100644 index 0000000..217cab4 --- /dev/null +++ b/python/balanced_binary_tree.py @@ -0,0 +1,24 @@ +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def _is_balanced(self, root: TreeNode) -> int: + if root is None: + return 0 + + left_height = self._is_balanced(root.left) + right_height = self._is_balanced(root.right) + if left_height == -1 or right_height == -1 or abs(left_height - right_height) > 1: + return -1 + + return 1 + max(left_height, right_height) + + def isBalanced(self, root: TreeNode) -> bool: + if root is None: + return True + return self._is_balanced(root) is not -1 diff --git a/python/base_7.py b/python/base_7.py new file mode 100644 index 0000000..5a598ab --- /dev/null +++ b/python/base_7.py @@ -0,0 +1,11 @@ +class Solution: + def convertToBase7(self, num: int) -> str: + if num == 0: + return '0' + is_negative = num < 0 + num = -num if is_negative else num + result = '' + while num > 0: + result = str(num % 7) + result + num //= 7 + return ('-' if is_negative else '') + result diff --git a/python/baseball_game.py b/python/baseball_game.py new file mode 100644 index 0000000..2b048ea --- /dev/null +++ b/python/baseball_game.py @@ -0,0 +1,16 @@ +from typing import List +from collections import deque + +class Solution: + def calPoints(self, ops: List[str]) -> int: + items = deque() + for operation in ops: + if operation == '+': + items.append(items[len(items) - 1] + items[len(items) - 2]) + elif operation == 'D': + items.append(items[len(items) - 1] * 2) + elif operation == 'C': + items.pop() + else: + items.append(int(operation)) + return sum(items) diff --git a/python/best_time_to_buy_and_sell_stock.py b/python/best_time_to_buy_and_sell_stock.py new file mode 100644 index 0000000..c7b614d --- /dev/null +++ b/python/best_time_to_buy_and_sell_stock.py @@ -0,0 +1,10 @@ +from typing import List + + +class Solution: + def maxProfit(self, prices: List[int]) -> int: + max_profit, buy_price = 0, prices[0] + for price in prices: + max_profit = max(max_profit, price - buy_price) + buy_price = min(buy_price, price) + return max_profit diff --git a/python/best_time_to_buy_and_sell_stock_ii.py b/python/best_time_to_buy_and_sell_stock_ii.py new file mode 100644 index 0000000..a218dff --- /dev/null +++ b/python/best_time_to_buy_and_sell_stock_ii.py @@ -0,0 +1,15 @@ +from typing import List + + +class Solution: + def maxProfit(self, prices: List[int]) -> int: + buy_price, sell_price, profit = prices[0], prices[0], 0 + for price in prices: + if price < sell_price: + profit += sell_price - buy_price + buy_price = price + sell_price = price + else: + sell_price = price + profit += sell_price - buy_price + return profit diff --git a/python/binary_number_with_alternating_bits.py b/python/binary_number_with_alternating_bits.py new file mode 100644 index 0000000..0178b7d --- /dev/null +++ b/python/binary_number_with_alternating_bits.py @@ -0,0 +1,9 @@ +class Solution: + def hasAlternatingBits(self, n: int) -> bool: + lastDigit = n % 2 + while n > 0: + n //= 2 + current = n % 2 + if lastDigit == current: return False + lastDigit = current + return True diff --git a/python/binary_search.py b/python/binary_search.py new file mode 100644 index 0000000..6596f53 --- /dev/null +++ b/python/binary_search.py @@ -0,0 +1,12 @@ +from typing import List + + +class Solution: + def search(self, array: List[int], target: int) -> int: + left, right = 0, len(array) - 1 + while left <= right: + middle = left + (right - left) // 2 + if array[middle] == target: return middle + elif array[middle] > target: right = middle - 1 + else: left = middle + 1 + return -1 diff --git a/python/binary_tree_inorder_traversal.py b/python/binary_tree_inorder_traversal.py new file mode 100644 index 0000000..4c18454 --- /dev/null +++ b/python/binary_tree_inorder_traversal.py @@ -0,0 +1,23 @@ +from typing import Optional, List + + +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + + +class Solution: + def _inorder_traversal(self, root: TreeNode, list: List[int]) -> None: + if root == None: return + self._inorder_traversal(root.left, list) + list.append(root.val) + self._inorder_traversal(root.right, list) + + def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + result = [] + self._inorder_traversal(root, result) + return result diff --git a/python/binary_tree_level_order_traversal_ii.py b/python/binary_tree_level_order_traversal_ii.py new file mode 100644 index 0000000..b3e5534 --- /dev/null +++ b/python/binary_tree_level_order_traversal_ii.py @@ -0,0 +1,35 @@ +# Definition for a binary tree node. +from typing import List +from collections import deque + + +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: + if root is None: + return [] + + queue = deque() + queue.append(root) + result = [] + current_level = [] + + while len(queue): + current_level_length = len(queue) + for _ in range(current_level_length): + current = queue.popleft() + current_level.append(current.val) + if current.left: + queue.append(current.left) + if current.right: + queue.append(current.right) + result.append(current_level) + current_level = [] + + return result[::-1] diff --git a/python/binary_tree_paths.py b/python/binary_tree_paths.py new file mode 100644 index 0000000..e770cb4 --- /dev/null +++ b/python/binary_tree_paths.py @@ -0,0 +1,28 @@ +from typing import List + + +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def is_leaf_node(self, root: TreeNode) -> bool: + return root.left is None and root.right is None + + def binary_tree_paths(self, root: TreeNode, current_path: str, results: List[str]): + if root is None: + return + if self.is_leaf_node(root): + results.append(f'{current_path}->{root.val}'[2:]) + return + self.binary_tree_paths(root.left, f'{current_path}->{root.val}', results) + self.binary_tree_paths(root.right, f'{current_path}->{root.val}', results) + + def binaryTreePaths(self, root: TreeNode) -> List[str]: + result = [] + self.binary_tree_paths(root, '', results=result) + return result diff --git a/python/binary_tree_postorder_traversal.py b/python/binary_tree_postorder_traversal.py new file mode 100644 index 0000000..2eb5392 --- /dev/null +++ b/python/binary_tree_postorder_traversal.py @@ -0,0 +1,22 @@ +# Definition for a binary tree node. +from typing import Optional, List + + +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def _postorder_traversal(self, root: Optional[TreeNode], list: List[int]) -> None: + if root is None: return + self._postorder_traversal(root.left, list) + self._postorder_traversal(root.right, list) + list.append(root.val) + + def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + result = [] + self._postorder_traversal(root, result) + return result diff --git a/python/binary_tree_preorder_traversal.py b/python/binary_tree_preorder_traversal.py new file mode 100644 index 0000000..9db1c32 --- /dev/null +++ b/python/binary_tree_preorder_traversal.py @@ -0,0 +1,22 @@ +# Definition for a binary tree node. +from typing import Optional, List + + +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def _preorder_traversal(self, root: Optional[TreeNode], list: List[int]) -> None: + if root is None: return + list.append(root.val) + self._preorder_traversal(root.left, list) + self._preorder_traversal(root.right, list) + + def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + result = [] + self._preorder_traversal(root, result) + return result diff --git a/python/binary_tree_tilt.py b/python/binary_tree_tilt.py new file mode 100644 index 0000000..89d5f23 --- /dev/null +++ b/python/binary_tree_tilt.py @@ -0,0 +1,21 @@ +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def __init__(self): + self.sumTilts = 0 + + def computeTilts(self, root: TreeNode) -> int: + if root is None: return 0 + leftSum, rightSum = self.computeTilts(root.left), self.computeTilts(root.right) + self.sumTilts += abs(leftSum - rightSum) + return leftSum + rightSum + root.val + + def findTilt(self, root: TreeNode) -> int: + self.computeTilts(root) + return self.sumTilts diff --git a/python/binary_watch.py b/python/binary_watch.py new file mode 100644 index 0000000..df70d0e --- /dev/null +++ b/python/binary_watch.py @@ -0,0 +1,5 @@ +class Solution: + def readBinaryWatch(self, num): + return ['%d:%02d' % (h, m) + for h in range(12) for m in range(60) + if (bin(h) + bin(m)).count('1') == num] diff --git a/python/boats_to_save_people.py b/python/boats_to_save_people.py new file mode 100644 index 0000000..5d795e8 --- /dev/null +++ b/python/boats_to_save_people.py @@ -0,0 +1,14 @@ +# https://leetcode.com/problems/boats-to-save-people/description/ +# T: O(nlogn) where n is the length of people +# S: O(logn) for sorting + +class Solution: + def numRescueBoats(self, people: List[int], limit: int) -> int: + people.sort() + left, right, ans = 0, len(people) - 1, 0 + while left <= right: + ans += 1 + if people[left] + people[right] <= limit: + left+=1 + right-=1 + return ans diff --git a/python/bulls_and_cows.py b/python/bulls_and_cows.py new file mode 100644 index 0000000..b1b6123 --- /dev/null +++ b/python/bulls_and_cows.py @@ -0,0 +1,23 @@ +from string import digits +from typing import Dict + + +class Solution: + def get_digit_frequency(self, number: str) -> Dict[str, int]: + freq = {} + for digit in number: + freq[digit] = freq.get(digit, 0) + 1 + return freq + + def getHint(self, secret: str, guess: str) -> str: + bulls = {} + frequency_secret = self.get_digit_frequency(secret) + frequency_guess = self.get_digit_frequency(guess) + for s, g in zip(secret, guess): + if s == g: + bulls[s] = bulls.get(s, 0) + 1 + total_bulls = sum(bulls.values()) + total_cows = 0 + for i in digits: + total_cows += min(frequency_secret.get(i, 0), frequency_guess.get(i, 0)) - bulls.get(i, 0) + return f'{total_bulls}A{total_cows}B' diff --git a/python/can_place_flowers.py b/python/can_place_flowers.py new file mode 100644 index 0000000..03865bd --- /dev/null +++ b/python/can_place_flowers.py @@ -0,0 +1,14 @@ +from typing import List + + +class Solution: + def flowerBedCapacity(self, flowerbed: List[int]) -> int: + capacity = 0 + for index, value in enumerate(flowerbed): + if value != 1 and (index == 0 or flowerbed[index - 1] == 0) and (index == len(flowerbed) - 1 or flowerbed[index + 1] == 0): + capacity += 1 + flowerbed[index] = 1 + return capacity + + def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: + return self.flowerBedCapacity(flowerbed) >= n diff --git a/python/check_if_n_and_its_double_exist.py b/python/check_if_n_and_its_double_exist.py new file mode 100644 index 0000000..0a677c8 --- /dev/null +++ b/python/check_if_n_and_its_double_exist.py @@ -0,0 +1,11 @@ +from typing import List + + +class Solution: + def checkIfExist(self, arr: List[int]) -> bool: + elements = set() + for number in arr: + if 2 * number in elements or (number % 2 == 0 and number // 2 in elements): + return True + elements.add(number) + return False diff --git a/python/check_perfect_number.py b/python/check_perfect_number.py new file mode 100644 index 0000000..51d6a17 --- /dev/null +++ b/python/check_perfect_number.py @@ -0,0 +1,10 @@ +class Solution: + def checkPerfectNumber(self, num: int) -> bool: + if num == 1: return False + + divisior_sum, divisior = 0, 1 + while divisior * divisior <= num: + if num % divisior == 0: + divisior_sum += (divisior + num // divisior) + divisior += 1 + return divisior_sum == num diff --git a/python/climbing_stairs.py b/python/climbing_stairs.py new file mode 100644 index 0000000..6bc24a6 --- /dev/null +++ b/python/climbing_stairs.py @@ -0,0 +1,5 @@ +def climbStairs(n: int) -> int: + prev, current = 1, 1 + for i in range(n - 1): + prev, current = current, prev + current + return current diff --git a/python/clone_graph.py b/python/clone_graph.py new file mode 100644 index 0000000..35fd538 --- /dev/null +++ b/python/clone_graph.py @@ -0,0 +1,19 @@ +# https://leetcode.com/problems/clone-graph/description/ +# T: O(n) where n is the number of nodes in the graph +# S: O(n) where n is the number of nodes in the graph + +class Solution: + def cloneGraph(self, node: 'Node') -> 'Node': + if not node: + return node + d = {node.val: Node(node.val, [])} + q = deque([node]) + while q: + cur_node = q.pop() + cur_res = d[cur_node.val] + for n in cur_node.neighbors: + if n.val not in d: + q.append(n) + d[n.val] = Node(n.val, []) + cur_res.neighbors.append(d[n.val]) + return d[node.val] diff --git a/python/construct_string_from_binary_tree.py b/python/construct_string_from_binary_tree.py new file mode 100644 index 0000000..c7a5683 --- /dev/null +++ b/python/construct_string_from_binary_tree.py @@ -0,0 +1,14 @@ +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def tree2str(self, root: TreeNode) -> str: + if root is None: return '' + if root.left is None and root.right is None: return f'{root.val}' + if root.right is None: return f'{root.val}({self.tree2str(root.left)})' + return f'{root.val}({self.tree2str(root.left)})({self.tree2str(root.right)})' diff --git a/python/contains_duplicate.py b/python/contains_duplicate.py new file mode 100644 index 0000000..c58e2fe --- /dev/null +++ b/python/contains_duplicate.py @@ -0,0 +1,11 @@ +from typing import List + + +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + numbers = set() + for number in nums: + if number in numbers: + return True + numbers.add(number) + return False diff --git a/python/contains_duplicate_ii.py b/python/contains_duplicate_ii.py new file mode 100644 index 0000000..c09fa35 --- /dev/null +++ b/python/contains_duplicate_ii.py @@ -0,0 +1,11 @@ +from typing import List + + +class Solution: + def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: + position = {} + for index, number in enumerate(nums): + if number in position and abs(index - position[number]) <= k: + return True + position[number] = index + return False diff --git a/python/convert_a_number_to_hexadecimal.py b/python/convert_a_number_to_hexadecimal.py new file mode 100644 index 0000000..f1386bd --- /dev/null +++ b/python/convert_a_number_to_hexadecimal.py @@ -0,0 +1,14 @@ +class Solution: + def __init__(self): + self.hex_chars = [str(i) for i in range(10)] + [chr(97 + i) for i in range(7)] + + def toHex(self, num: int) -> str: + if num == 0: + return '0' + if num < 0: + num = 2 ** 32 + num + result = '' + while num != 0: + result = self.hex_chars[num & 15] + result + num = (num >> 4) + return result diff --git a/python/convert_bst_to_greater_tree.py b/python/convert_bst_to_greater_tree.py new file mode 100644 index 0000000..0ddffee --- /dev/null +++ b/python/convert_bst_to_greater_tree.py @@ -0,0 +1,22 @@ +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def __init__(self): + self.value = 0 + + def computeGreaterTree(self, root: TreeNode): + if root is None: return + self.computeGreaterTree(root.right) + root.val += self.value + self.value = root.val + self.computeGreaterTree(root.left) + + def convertBST(self, root: TreeNode) -> TreeNode: + self.computeGreaterTree(root) + return root diff --git a/python/converted_sorted_array_to_binary_search_tree.py b/python/converted_sorted_array_to_binary_search_tree.py new file mode 100644 index 0000000..3ffdf70 --- /dev/null +++ b/python/converted_sorted_array_to_binary_search_tree.py @@ -0,0 +1,27 @@ +# Definition for a binary tree node. +from typing import List, Optional + + +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + def __repr__(self): + return f'Tree(val={self.val})' + + +class Solution: + def sorted_array_to_bst(self, array: List[int], start: int, end: int) -> Optional[TreeNode]: + if end == start: + return None + + middle = (start + end) // 2 + root = TreeNode(val=array[middle]) + root.left = self.sorted_array_to_bst(array, start, middle) + root.right = self.sorted_array_to_bst(array, middle + 1, end) + return root + + def sortedArrayToBST(self, nums: List[int]) -> TreeNode: + return self.sorted_array_to_bst(nums, 0, len(nums)) diff --git a/python/count_and_say.py b/python/count_and_say.py new file mode 100644 index 0000000..db8a076 --- /dev/null +++ b/python/count_and_say.py @@ -0,0 +1,19 @@ +class Solution: + def countAndSay(self, n: int) -> str: + if n == 1: + return '1' + + previous = self.countAndSay(n - 1) + # print('previous', n - 1, previous) + current = previous[0] + frequency = 0 + result = '' + for number in previous: + if number == current: + frequency += 1 + else: + result += f'{frequency}{current}' + frequency = 1 + current = number + result += f'{frequency}{current}' if frequency > 0 else '' + return result diff --git a/python/count_binary_substrings.py b/python/count_binary_substrings.py new file mode 100644 index 0000000..d0b07bb --- /dev/null +++ b/python/count_binary_substrings.py @@ -0,0 +1,11 @@ +class Solution: + def countBinarySubstrings(self, s: str) -> int: + binarySubstrings, previous, current = 0, 0, 1 + index = 1 + while index < len(s): + if s[index - 1] != s[index]: + binarySubstrings += min(previous, current) + previous, current = current, 1 + else: current += 1 + index += 1 + return binarySubstrings + min(previous, current) diff --git a/python/count_primes.py b/python/count_primes.py new file mode 100644 index 0000000..afba245 --- /dev/null +++ b/python/count_primes.py @@ -0,0 +1,15 @@ +from typing import List + + +class Solution: + def _get_prime_sieve(self, size: int) -> List[int]: + sieve = [1] * (max(size, 2)) + sieve[0], sieve[1] = 0, 0 + for number in range(2, len(sieve)): + if sieve[number]: + for dividend in range(number ** 2, len(sieve), number): + sieve[dividend] = 0 + return sieve + + def countPrimes(self, n: int) -> int: + return sum(self._get_prime_sieve(n)) diff --git a/python/count_unreachable_pair_of_node_in_an_undirectable_graph.py b/python/count_unreachable_pair_of_node_in_an_undirectable_graph.py new file mode 100644 index 0000000..22fde48 --- /dev/null +++ b/python/count_unreachable_pair_of_node_in_an_undirectable_graph.py @@ -0,0 +1,49 @@ +# https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/description/ +# T: O(N + E) where N is the number of nodes and E is the number of edges +# S: O(N + E) where N is the number of nodes and E is the number of edges + +from collections import defaultdict +class Solution: + def __init__(self): + self.graph = defaultdict(list) + self.visited = set() + self.n = 0 + + def add_edge(self, u, v): + self.graph[u].append(v) + self.graph[v].append(u) + + def dfs(self, v, component): + self.visited.add(v) + component.append(v) + for neighbor in self.graph[v]: + if neighbor not in self.visited: + self.dfs(neighbor, component) + + def find_components(self): + components = [] + for v in range(self.n): + if v not in self.visited: + component = [] + self.dfs(v, component) + components.append(component) + + return components + + def countPairs(self, n, edges): + for u, v in edges: + self.add_edge(u, v) + self.n = n + component_lengths = [] + components = self.find_components() + for component in components: + component_lengths.append(len(component)) + print(components, component_lengths) + + k = sum(component_lengths) + sol = 0 + for l in component_lengths: + sol+=((k-l)*l) + sol = sol//2 + + return sol diff --git a/python/counting_bits.py b/python/counting_bits.py new file mode 100644 index 0000000..25add66 --- /dev/null +++ b/python/counting_bits.py @@ -0,0 +1,15 @@ +from typing import List + + +class Solution: + def countBits(self, n: int) -> List[int]: + result = [0] * (n + 1) + if len(result) > 1: result[1] = 1 + i, k = 0, 2 + while k < len(result): + i = 0 + while i < k and i + k < len(result): + result[i + k] = 1 + result[i] + i += 1 + k *= 2 + return result diff --git a/python/degree_of_an_array.py b/python/degree_of_an_array.py new file mode 100644 index 0000000..88b7b48 --- /dev/null +++ b/python/degree_of_an_array.py @@ -0,0 +1,25 @@ +from collections import Counter +from typing import List, Dict + + +class Solution: + def getLeftPosition(self, array: List[int]) -> Dict[int, int]: + positions = {} + for index, element in enumerate(array): + if element not in positions: + positions[element] = index + return positions + + def getRightPosition(self, array: List[int]) -> Dict[int, int]: + return {number : index for index, number in enumerate(array)} + + def findShortestSubArray(self, numbers: List[int]) -> int: + frequencies = Counter(numbers) + leftMost = self.getLeftPosition(numbers) + rightMost = self.getRightPosition(numbers) + maxFrequency = max(frequencies.values()) + result = float('inf') + for number, frequency in frequencies.items(): + if frequency == maxFrequency: + result = min(result, rightMost[number] - leftMost[number] + 1) + return result diff --git a/python/delete_node_in_linked_list.py b/python/delete_node_in_linked_list.py new file mode 100644 index 0000000..43efe6b --- /dev/null +++ b/python/delete_node_in_linked_list.py @@ -0,0 +1,18 @@ +# Definition for singly-linked list. +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + + +class Solution: + def deleteNode(self, node: ListNode) -> None: + """ + :type node: ListNode + :rtype: void Do not return anything, modify node in-place instead. + """ + while node is not None and node.next is not None and node.next.next is not None: + node.val = node.next.val + node = node.next + node.val = node.next.val + node.next = None diff --git a/python/design_add_and_search_words_data_structure.py b/python/design_add_and_search_words_data_structure.py new file mode 100644 index 0000000..23326bf --- /dev/null +++ b/python/design_add_and_search_words_data_structure.py @@ -0,0 +1,36 @@ +class Trienode: + def __init__(self): + self.children = {} + self.word = False + +class WordDictionary: + + def __init__(self): + self.root = Trienode() + + + def addWord(self, word: str) -> None: + ptr = self.root + for ch in word: + if ch not in ptr.children: + ptr.children[ch] = Trienode() + ptr = ptr.children[ch] + ptr.word = True + + + def search(self, word: str) -> bool: + def dfs(j, root): + curr = root + for i in range(j, len(word)): + ch = word[i] + if ch == ".": + for child in curr.children.values(): + if dfs(i+1, child): + return True + return False + else: + if ch not in curr.children: + return False + curr = curr.children[ch] + return curr.word + return dfs(0, self.root) diff --git a/python/design_browser_history.py b/python/design_browser_history.py new file mode 100644 index 0000000..918683a --- /dev/null +++ b/python/design_browser_history.py @@ -0,0 +1,18 @@ +class BrowserHistory: + + def __init__(self, homepage: str): + self.history = [homepage] + self.ptr = 0 + + def visit(self, url: str) -> None: + self.ptr += 1 + self.history = self.history[:self.ptr] + self.history.append(url) + + def back(self, steps: int) -> str: + self.ptr = max(0, self.ptr - steps) + return self.history[self.ptr] + + def forward(self, steps: int) -> str: + self.ptr = min(len(self.history) - 1, self.ptr + steps) + return self.history[self.ptr] diff --git a/python/design_hash_map.py b/python/design_hash_map.py new file mode 100644 index 0000000..7a2f55a --- /dev/null +++ b/python/design_hash_map.py @@ -0,0 +1,52 @@ +class Bucket: + def __init__(self): + self.list = [] + + def __str__(self): + return self.list.__str__() + + def contains(self, key: int) -> bool: + for listKey, value in self.list: + if key == listKey: + return True + return False + + def put(self, key: int, value: int) -> None: + changed = False + for index, (listKey, _) in enumerate(self.list): + if listKey == key: + self.list[index] = (key, value) + changed = True + break + if not changed: + self.list.append((key, value)) + + def remove(self, key: int) -> None: + if self.contains(key): + self.list.remove((key, self.get(key))) + + def get(self, key: int) -> int: + if self.contains(key): + for listKey, value in self.list: + if listKey == key: + return value + return -1 + + +class MyHashMap: + + def __init__(self): + self.initial_size = 100 + self.buckets = [Bucket() for _ in range(self.initial_size)] + + def _hashCode(self, number: int) -> int: + return number % len(self.buckets) + + def put(self, key: int, value: int) -> None: + self.buckets[self._hashCode(key)].put(key, value) + + def get(self, key: int) -> int: + return self.buckets[self._hashCode(key)].get(key) + + def remove(self, key: int) -> None: + self.buckets[self._hashCode(key)].remove(key) diff --git a/python/design_hash_set.py b/python/design_hash_set.py new file mode 100644 index 0000000..452bfb1 --- /dev/null +++ b/python/design_hash_set.py @@ -0,0 +1,32 @@ +class Bucket: + def __init__(self): + self.list = [] + + def contains(self, element: int) -> bool: + return element in self.list + + def add(self, element: int) -> None: + self.list.append(element) + + def remove(self, element: int) -> None: + if self.contains(element): + self.list.remove(element) + + +class MyHashSet: + def __init__(self): + self._initial_size = 100 + self.size = 0 + self.buckets = [Bucket() for _ in range(self._initial_size)] + + def add(self, key: int) -> None: + hashCode = key % len(self.buckets) + if not self.buckets[hashCode].contains(key): + self.buckets[hashCode].add(key) + self.size += 1 + + def remove(self, key: int) -> None: + self.buckets[key % len(self.buckets)].remove(key) + + def contains(self, key: int) -> bool: + return self.buckets[key % len(self.buckets)].contains(key) diff --git a/python/detect_capital.py b/python/detect_capital.py new file mode 100644 index 0000000..5d1323a --- /dev/null +++ b/python/detect_capital.py @@ -0,0 +1,9 @@ +class Solution: + def detectCapitalUse(self, word: str) -> bool: + return word.isupper() or word.islower() or word[0].isupper() and self.isLower(word, 1) + + def isLower(self, word: str, start: int) -> bool: + for index in range(start, len(word)): + if word[index].isupper(): + return False + return True diff --git a/python/diameter_of_binary_tree.py b/python/diameter_of_binary_tree.py new file mode 100644 index 0000000..bbc6f05 --- /dev/null +++ b/python/diameter_of_binary_tree.py @@ -0,0 +1,22 @@ +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def __init__(self): + self.diameter = 0 + + def computerDiameterOfBinaryTree(self, root: TreeNode) -> int: + if root is None: return 0 + leftHeight = self.computerDiameterOfBinaryTree(root.left) + rightHeight = self.computerDiameterOfBinaryTree(root.right) + self.diameter = max(self.diameter, leftHeight + rightHeight) + return 1 + max(leftHeight, rightHeight) + + def diameterOfBinaryTree(self, root: TreeNode) -> int: + self.computerDiameterOfBinaryTree(root) + return self.diameter diff --git a/python/distribute_candies.py b/python/distribute_candies.py new file mode 100644 index 0000000..dd77d40 --- /dev/null +++ b/python/distribute_candies.py @@ -0,0 +1,6 @@ +from typing import List + + +class Solution: + def distributeCandies(self, candyType: List[int]) -> int: + return min(len(candyType) // 2, len(set(candyType))) diff --git a/python/excel_sheet_column_number.py b/python/excel_sheet_column_number.py new file mode 100644 index 0000000..8f69cff --- /dev/null +++ b/python/excel_sheet_column_number.py @@ -0,0 +1,6 @@ +class Solution: + def titleToNumber(self, columnTitle: str) -> int: + value = 0 + for character in columnTitle: + value = 26 * value + ord(character) - 64 + return value diff --git a/python/excel_sheet_column_title.py b/python/excel_sheet_column_title.py new file mode 100644 index 0000000..d4c4d3a --- /dev/null +++ b/python/excel_sheet_column_title.py @@ -0,0 +1,7 @@ +class Solution: + def convertToTitle(self, columnNumber: int) -> str: + column_title = '' + while columnNumber > 0: + columnNumber, digit = divmod(columnNumber - 1, 26) + column_title = chr(digit + 65) + column_title + return column_title diff --git a/python/factorial_trailing_zeroes.py b/python/factorial_trailing_zeroes.py new file mode 100644 index 0000000..6751ffc --- /dev/null +++ b/python/factorial_trailing_zeroes.py @@ -0,0 +1,7 @@ +class Solution: + def trailingZeroes(self, n: int) -> int: + divisor, count = 5, 0 + while divisor <= n: + count += n // divisor + divisor *= 5 + return count diff --git a/python/fibonacci_number.py b/python/fibonacci_number.py new file mode 100644 index 0000000..a602ef8 --- /dev/null +++ b/python/fibonacci_number.py @@ -0,0 +1,6 @@ +class Solution: + def fib(self, n: int) -> int: + prev, current = 0, 1 + for i in range(n): + prev, current = current, prev + current + return prev diff --git a/python/find_all_numbers_disappeared_in_an_array.py b/python/find_all_numbers_disappeared_in_an_array.py new file mode 100644 index 0000000..1c5970f --- /dev/null +++ b/python/find_all_numbers_disappeared_in_an_array.py @@ -0,0 +1,11 @@ +from typing import List + + +class Solution: + def findDisappearedNumbers(self, nums: List[int]) -> List[int]: + numbers = set(nums) + result = [] + for number in range(1, len(nums) + 1): + if number not in numbers: + result.append(number) + return result diff --git a/python/find_mode_in_binary_search_tree.py b/python/find_mode_in_binary_search_tree.py new file mode 100644 index 0000000..a1ad6ab --- /dev/null +++ b/python/find_mode_in_binary_search_tree.py @@ -0,0 +1,37 @@ +# Definition for a binary tree node. +from typing import List + + +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def __init__(self): + self.count = 1 + self.previous = None + self.max = 0 + + def find_mode(self, root: TreeNode, modes: List[int]): + if root is None: + return + self.find_mode(root.left, modes) + if self.previous: + self.count = self.count + 1 if root.val == self.previous.val else 1 + if self.count > self.max: + self.max = self.count + modes.clear() + modes.append(root.val) + elif self.count == self.max: + modes.append(root.val) + self.previous = root + self.find_mode(root.right, modes) + + def findMode(self, root: TreeNode) -> List[int]: + if root is None: return [] + result = [] + self.find_mode(root, result) + return result diff --git a/python/find_numbers_with_even_number_of_digits.py b/python/find_numbers_with_even_number_of_digits.py new file mode 100644 index 0000000..7c9b4a6 --- /dev/null +++ b/python/find_numbers_with_even_number_of_digits.py @@ -0,0 +1,19 @@ +from typing import List + + +class Solution: + def findNumbers(self, nums: List[int]) -> int: + evenDigitNumbers = 0 + for number in nums: + if self.numberOfDigits(number) % 2 == 0: + evenDigitNumbers += 1 + return evenDigitNumbers + + def numberOfDigits(self, number: int) -> int: + if number == 0: + return 1 + digits = 0 + while number != 0: + number //= 10 + digits += 1 + return digits diff --git a/python/find_pivot_index.py b/python/find_pivot_index.py new file mode 100644 index 0000000..4f19ddc --- /dev/null +++ b/python/find_pivot_index.py @@ -0,0 +1,14 @@ +from typing import List + + +class Solution: + def pivotIndex(self, nums: List[int]) -> int: + leftSum, rightSum = 0, sum(nums) + index = 0 + while index < len(nums): + leftSum += nums[index - 1] if index - 1 >= 0 else 0 + rightSum -= nums[index] + if leftSum == rightSum: + return index + index += 1 + return -1 diff --git a/python/find_smallest_letter_greater_than.py b/python/find_smallest_letter_greater_than.py new file mode 100644 index 0000000..75d31cc --- /dev/null +++ b/python/find_smallest_letter_greater_than.py @@ -0,0 +1,11 @@ +from typing import List + + +class Solution: + def nextGreatestLetter(self, letters: List[str], target: str) -> str: + left, right = 0, len(letters) - 1 + while left <= right: + middle = left + (right - left) // 2 + if letters[middle] <= target: left = middle + 1 + else: right = middle - 1 + return letters[left % len(letters)] diff --git a/python/find_the_difference.py b/python/find_the_difference.py new file mode 100644 index 0000000..3813e18 --- /dev/null +++ b/python/find_the_difference.py @@ -0,0 +1,6 @@ +class Solution: + def ascii_sum(self, string: str) -> int: + return sum(ord(character) for character in string) + + def findTheDifference(self, s: str, t: str) -> str: + return chr(self.ascii_sum(t) - self.ascii_sum(s)) diff --git a/python/first_bad_version.py b/python/first_bad_version.py new file mode 100644 index 0000000..25766aa --- /dev/null +++ b/python/first_bad_version.py @@ -0,0 +1,21 @@ +# The isBadVersion API is already defined for you. +# @param version, an integer +# @return an integer +def isBadVersion(version): + return None + + +class Solution: + def firstBadVersion(self, n: int) -> int: + """ + :type n: int + :rtype: int + """ + left, right = 0, n + while left <= right: + middle = left + (right - left) // 2 + if isBadVersion(middle): + right = middle - 1 + else: + left = middle + 1 + return left diff --git a/python/first_unique_character_in_string.py b/python/first_unique_character_in_string.py new file mode 100644 index 0000000..6043a21 --- /dev/null +++ b/python/first_unique_character_in_string.py @@ -0,0 +1,9 @@ +class Solution: + def firstUniqChar(self, s: str) -> int: + frequencies = {} + for index, character in enumerate(s): + frequencies[character] = frequencies.get(character, 0) + 1 + for index, character in enumerate(s): + if frequencies[character] == 1: + return index + return -1 diff --git a/python/fizz_buzz.py b/python/fizz_buzz.py new file mode 100644 index 0000000..62a42c4 --- /dev/null +++ b/python/fizz_buzz.py @@ -0,0 +1,16 @@ +from typing import List + + +class Solution: + def fizzBuzz(self, n: int) -> List[str]: + result = [] + for i in range(1, n + 1): + if i % 15 == 0: + result.append('FizzBuzz') + elif i % 3 == 0: + result.append('Fizz') + elif i % 5 == 0: + result.append('Buzz') + else: + result.append(str(i)) + return result diff --git a/python/flood_fill.py b/python/flood_fill.py new file mode 100644 index 0000000..c61646a --- /dev/null +++ b/python/flood_fill.py @@ -0,0 +1,22 @@ +from typing import List + + +class Solution: + + def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]: + self.image = image + self.height = len(image) + self.width = len(image[0]) + self.newColor = newColor + if image[sr][sc] != newColor: + self.oldColor = image[sr][sc] + self.colorPixel(row=sr, column=sc) + return image + + def colorPixel(self, row: int, column: int) -> None: + if self.image[row][column] != self.newColor: + self.image[row][column] = self.newColor + if row - 1 >= 0 and self.image[row - 1][column] == self.oldColor: self.colorPixel(row - 1, column) + if column + 1 < self.width and self.image[row][column + 1] == self.oldColor: self.colorPixel(row, column + 1) + if row + 1 < self.height and self.image[row + 1][column] == self.oldColor: self.colorPixel(row + 1, column) + if column - 1 >= 0 and self.image[row][column - 1] == self.oldColor: self.colorPixel(row, column - 1) diff --git a/python/guess_number_higher_or_lower.py b/python/guess_number_higher_or_lower.py new file mode 100644 index 0000000..ce8cb38 --- /dev/null +++ b/python/guess_number_higher_or_lower.py @@ -0,0 +1,22 @@ +# The guess API is already defined for you. +# @param num, your guess +# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 + +def guess(num: int) -> int: + # temp purposes + return 0 + + +class Solution: + def guessNumber(self, n: int) -> int: + left, right = 1, n + while left <= right: + middle = (left + right) // 2 + hypothesis = guess(middle) + if hypothesis == 0: + return middle + elif hypothesis == 1: + left = middle + 1 + else: + right = middle - 1 + return 0 diff --git a/python/happy_number.py b/python/happy_number.py new file mode 100644 index 0000000..898f2ff --- /dev/null +++ b/python/happy_number.py @@ -0,0 +1,12 @@ +class Solution: + def _is_happy(self, number: int, previously_used: set) -> bool: + if number is 1: + return True + new_number = sum(int(digit) ** 2 for digit in str(number)) + if new_number in previously_used: + return False + previously_used.add(new_number) + return self._is_happy(new_number, previously_used) + + def isHappy(self, n: int) -> bool: + return self._is_happy(number=n, previously_used={n}) diff --git a/python/heaters.py b/python/heaters.py new file mode 100644 index 0000000..0086221 --- /dev/null +++ b/python/heaters.py @@ -0,0 +1,24 @@ +from typing import List + + +class Solution: + def binary_search(self, array: List[int], element: int) -> int: + left, right = 0, len(array) - 1 + while left <= right: + middle = (left + right) // 2 + if array[middle] == element: return middle + elif array[middle] < element: left = middle + 1 + else: right = middle - 1 + return left + + def findRadius(self, houses: List[int], heaters: List[int]) -> int: + heaters.sort() + minRadius, infinity = 0, float('inf') + for house in houses: + index = self.binary_search(heaters, house) + if index < len(heaters) and house == heaters[index]: + continue + leftRadius = infinity if index == 0 else house - heaters[index - 1] + rightRadius = infinity if index == len(heaters) else heaters[index] - house + minRadius = max(minRadius, min(leftRadius, rightRadius)) + return minRadius diff --git a/python/house_robber.py b/python/house_robber.py new file mode 100644 index 0000000..c7b71e5 --- /dev/null +++ b/python/house_robber.py @@ -0,0 +1,10 @@ +from typing import List + + +class Solution: + def rob(self, nums: List[int]) -> int: + a, b, max_amount = 0, nums[0], nums[0] + for index in range(1, len(nums)): + max_amount = max(a + nums[index], b) + a, b = b, max_amount + return max_amount diff --git a/python/image_smoother.py b/python/image_smoother.py new file mode 100644 index 0000000..8cbd41b --- /dev/null +++ b/python/image_smoother.py @@ -0,0 +1,16 @@ +from typing import List + + +class Solution: + def imageSmoother(self, img: List[List[int]]) -> List[List[int]]: + rows, columns = len(img), len(img[0]) + result = [[0 for i in range(columns)] for j in range(rows)] + for row in range(rows): + for column in range(columns): + k_sum, count = 0, 0 + for k_row in range(row if row == 0 else row - 1, (row if row == rows - 1 else row + 1) + 1): + for k_column in range(column if column == 0 else column - 1, (column if column == columns - 1 else column + 1) + 1): + k_sum += img[k_row][k_column] + count += 1 + result[row][column] = k_sum // count + return result diff --git a/python/implement_queue_using_stacks.py b/python/implement_queue_using_stacks.py new file mode 100644 index 0000000..58f11cf --- /dev/null +++ b/python/implement_queue_using_stacks.py @@ -0,0 +1,45 @@ +from collections import deque + + +class MyQueue: + def __init__(self): + """ + Initialize your data structure here. + """ + self.s1 = deque() + self.s2 = deque() + + def push(self, x: int) -> None: + """ + Push element x to the back of queue. + """ + while len(self.s1) > 0: + self.s2.append(self.s1.pop()) + self.s1.append(x) + while len(self.s2) > 0: + self.s1.append(self.s2.pop()) + + def pop(self) -> int: + """ + Removes the element from in front of queue and returns that element. + """ + return self.s1.pop() + + def peek(self) -> int: + """ + Get the front element. + """ + return self.s1[-1] + + def empty(self) -> bool: + """ + Returns whether the queue is empty. + """ + return len(self.s1) == 0 + +# Your MyQueue object will be instantiated and called as such: +# obj = MyQueue() +# obj.push(x) +# param_2 = obj.pop() +# param_3 = obj.peek() +# param_4 = obj.empty() \ No newline at end of file diff --git a/python/implement_stack_using_queues.py b/python/implement_stack_using_queues.py new file mode 100644 index 0000000..8d47c3c --- /dev/null +++ b/python/implement_stack_using_queues.py @@ -0,0 +1,41 @@ +from collections import deque + + +class MyStack: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.queue = deque() + + def push(self, x: int) -> None: + """ + Push element x onto stack. + """ + self.queue.append(x) + + def pop(self) -> int: + """ + Removes the element on top of the stack and returns that element. + """ + return self.queue.pop() + + def top(self) -> int: + """ + Get the top element. + """ + return self.queue[-1] + + def empty(self) -> bool: + """ + Returns whether the stack is empty. + """ + return len(self.queue) == 0 + +# Your MyStack object will be instantiated and called as such: +# obj = MyStack() +# obj.push(x) +# param_2 = obj.pop() +# param_3 = obj.top() +# param_4 = obj.empty() \ No newline at end of file diff --git a/python/intersecction_of_two_linked_lists.py b/python/intersecction_of_two_linked_lists.py new file mode 100644 index 0000000..8b771ab --- /dev/null +++ b/python/intersecction_of_two_linked_lists.py @@ -0,0 +1,22 @@ +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + + +class Solution: + def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: + runner_1, runner_2 = headA, headB + + while runner_1 is not runner_2: + if runner_1 is None: + runner_1 = headB + else: + runner_1 = runner_1.next + + if runner_2 is None: + runner_2 = headA + else: + runner_2 = runner_2.next + + return None if runner_1 is None else runner_1 diff --git a/python/intersection_of_2_array.py b/python/intersection_of_2_array.py new file mode 100644 index 0000000..d5d44f7 --- /dev/null +++ b/python/intersection_of_2_array.py @@ -0,0 +1,8 @@ +from typing import List + + +class Solution: + def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: + nums_1_unique = set(nums1) + nums_2_unique = set(nums2) + return list(nums_1_unique.intersection(nums_2_unique)) diff --git a/python/intersection_of_2_arrays_II.py b/python/intersection_of_2_arrays_II.py new file mode 100644 index 0000000..96fa3a0 --- /dev/null +++ b/python/intersection_of_2_arrays_II.py @@ -0,0 +1,19 @@ +from typing import List, Dict + + +class Solution: + def get_frequency(self, numbers: List[int]) -> Dict[int, int]: + frequency = {} + for number in numbers: + frequency[number] = frequency.get(number, 0) + 1 + return frequency + + def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: + result = [] + nums1, nums2 = (nums1, nums2) if len(nums1) < len(nums2) else (nums2, nums1) + nums_1_freq = self.get_frequency(nums1) + for number in nums2: + if nums_1_freq.get(number, 0) >= 1: + result.append(number) + nums_1_freq[number] -= 1 + return result diff --git a/python/invert_binary_tree.py b/python/invert_binary_tree.py new file mode 100644 index 0000000..8c726e5 --- /dev/null +++ b/python/invert_binary_tree.py @@ -0,0 +1,17 @@ +# Definition for a binary tree node. +from typing import Optional + + +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def invertTree(self, root: TreeNode) -> Optional[TreeNode]: + if root is None: + return None + root.left, root.right = self.invertTree(root.right), self.invertTree(root.left) + return root diff --git a/python/is_power_of_2.py b/python/is_power_of_2.py new file mode 100644 index 0000000..2f0f086 --- /dev/null +++ b/python/is_power_of_2.py @@ -0,0 +1,13 @@ +class Solution: + def isPowerOfTwo(self, n: int) -> bool: + if n == 1: + return True + if n == 0: + return False + if n % 2 == 1: + return False + return self.isPowerOfTwo(n // 2) + + # alternate version + # def isPowerOfTwo(self, n: int) -> bool: + # return n > 0 and (n & (n - 1)) == 0 \ No newline at end of file diff --git a/python/is_subsequence.py b/python/is_subsequence.py new file mode 100644 index 0000000..adf416f --- /dev/null +++ b/python/is_subsequence.py @@ -0,0 +1,8 @@ +class Solution: + def isSubsequence(self, s: str, t: str) -> bool: + i, j = 0, 0 + while i < len(s) and j < len(t): + if s[i] == t[j]: + i += 1 + j += 1 + return i == len(s) diff --git a/python/isomorphic_strings.py b/python/isomorphic_strings.py new file mode 100644 index 0000000..5200671 --- /dev/null +++ b/python/isomorphic_strings.py @@ -0,0 +1,17 @@ +from typing import Dict + + +class Solution: + def isIsomorphic(self, s: str, t: str) -> bool: + mapping = {} + mapped_chars = set() + for char_s, char_t in zip(s, t): + if char_s in mapping: + if mapping[char_s] != char_t: + return False + else: + if char_t in mapped_chars: + return False + mapping[char_s] = char_t + mapped_chars.add(char_t) + return True diff --git a/python/jewels_and_stones.py b/python/jewels_and_stones.py new file mode 100644 index 0000000..cb5954c --- /dev/null +++ b/python/jewels_and_stones.py @@ -0,0 +1,8 @@ +class Solution: + def numJewelsInStones(self, jewels: str, stones: str) -> int: + jewelTypes = set(jewels) + result = 0 + for stone in stones: + if stone in jewelTypes: + result += 1 + return result diff --git a/python/k_dif_pairs_in_an_array.py b/python/k_dif_pairs_in_an_array.py new file mode 100644 index 0000000..ece3056 --- /dev/null +++ b/python/k_dif_pairs_in_an_array.py @@ -0,0 +1,20 @@ +from typing import List + + +class Solution: + def findPairs(self, nums: List[int], k: int) -> int: + pairs = 0 + if k == 0: + frequencies = {} + for number in nums: + frequencies[number] = frequencies.get(number, 0) + 1 + for frequency in frequencies.values(): + pairs += 1 if frequency > 1 else 0 + else: + numbers = set() + for number in nums: + if number not in numbers: + pairs += 1 if (number - k) in numbers else 0 + pairs += 1 if (number + k) in numbers else 0 + numbers.add(number) + return pairs diff --git a/python/k_th_largest_element_in_a_stream.py b/python/k_th_largest_element_in_a_stream.py new file mode 100644 index 0000000..a0a3828 --- /dev/null +++ b/python/k_th_largest_element_in_a_stream.py @@ -0,0 +1,18 @@ +import heapq +from typing import List + + +class KthLargest: + def __init__(self, k: int, nums: List[int]): + self.heap = [] + self.heap_size = k + for element in nums: + heapq.heappush(self.heap, element) + while len(self.heap) > self.heap_size: + heapq.heappop(self.heap) + + def add(self, val: int) -> int: + heapq.heappush(self.heap, val) + while len(self.heap) > self.heap_size: + heapq.heappop(self.heap) + return self.heap[0] diff --git a/python/largest_number_at_least_twice_of_others.py b/python/largest_number_at_least_twice_of_others.py new file mode 100644 index 0000000..e053492 --- /dev/null +++ b/python/largest_number_at_least_twice_of_others.py @@ -0,0 +1,18 @@ +from typing import List, Tuple + + +class Solution: + def dominantIndex(self, nums: List[int]) -> int: + largest, largestIndex = self.getMax(nums) + for number in nums: + if number != largest and 2 * number > largest: + return -1 + return largestIndex + + def getMax(self, array: List[int]) -> Tuple[int, int]: + largest, largestIndex = -float('inf'), -1 + for index, element in enumerate(array): + if element > largest: + largest = element + largestIndex = index + return largest, largestIndex diff --git a/python/length_of_last_word.py b/python/length_of_last_word.py new file mode 100644 index 0000000..8617a91 --- /dev/null +++ b/python/length_of_last_word.py @@ -0,0 +1,9 @@ +def length_last_word(s: str) -> int: + s = s.strip() + for index in range(len(s) - 1, -1, -1): + if s[index] == ' ': + return len(s) - index - 1 + return len(s) + + +print(length_last_word(input())) diff --git a/python/license_key_formatting.py b/python/license_key_formatting.py new file mode 100644 index 0000000..47a94bc --- /dev/null +++ b/python/license_key_formatting.py @@ -0,0 +1,4 @@ +class Solution: + def licenseKeyFormatting(self, s: str, k: int) -> str: + s = s.replace('-', '').upper()[::-1] + return '-'.join(s[i:i + k] for i in range(0, len(s), k))[::-1] diff --git a/python/linked_list_cycle.py b/python/linked_list_cycle.py new file mode 100644 index 0000000..f2872d4 --- /dev/null +++ b/python/linked_list_cycle.py @@ -0,0 +1,21 @@ +# Definition for singly-linked list. +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + + +class Solution: + def not_null(self, head: ListNode) -> bool: + return head is not None + + def hasCycle(self, head: ListNode) -> bool: + if head is None: + return False + slow, fast = head, head.next + while self.not_null(slow) and self.not_null(fast) and self.not_null(slow.next) and self.not_null(fast.next): + if slow is fast: + return True + slow = slow.next + fast = fast.next.next + return False diff --git a/python/longest_continuous_increasing_subsequence.py b/python/longest_continuous_increasing_subsequence.py new file mode 100644 index 0000000..ada7bf6 --- /dev/null +++ b/python/longest_continuous_increasing_subsequence.py @@ -0,0 +1,13 @@ +from typing import List + + +class Solution: + def findLengthOfLCIS(self, nums: List[int]) -> int: + current, result = 1, 1 + for index in range(1, len(nums)): + if nums[index] > nums[index - 1]: + current += 1 + result = max(result, current) + else: + current = 1 + return result diff --git a/python/longest_cycle_in_graph.py b/python/longest_cycle_in_graph.py new file mode 100644 index 0000000..07af343 --- /dev/null +++ b/python/longest_cycle_in_graph.py @@ -0,0 +1,28 @@ +# https://leetcode.com/problems/longest-cycle-in-a-graph/description/ +# T:O(N) where N is the number of nodes in the graph +# S:O(N) where N is the number of nodes in the graph + +class Solution: + def __init__(self): + self.answer = -1 + + def dfs(self, node, edges, dist, visit): + visit[node] = True + neighbor = edges[node] + + if neighbor != -1 and not visit[neighbor]: + dist[neighbor] = dist[node] + 1 + self.dfs(neighbor, edges, dist, visit) + elif neighbor != -1 and neighbor in dist: + self.answer = max(self.answer, dist[node] - dist[neighbor] + 1) + + def longestCycle(self, edges): + n = len(edges) + visit = [False] * n + + for i in range(n): + if not visit[i]: + dist = {i: 1} + self.dfs(i, edges, dist, visit) + + return self.answer diff --git a/python/longest_harmonious_subequence.py b/python/longest_harmonious_subequence.py new file mode 100644 index 0000000..ae57947 --- /dev/null +++ b/python/longest_harmonious_subequence.py @@ -0,0 +1,15 @@ +from collections import Counter +from typing import List + + +class Solution: + def findLHS(self, array: List[int]) -> int: + frequencies = Counter(array) + result = 0 + for value, frequency in frequencies.items(): + result = max( + result, + frequencies.get(value - 1) + frequency if value - 1 in frequencies else 0, + frequencies.get(value + 1) + frequency if value + 1 in frequencies else 0 + ) + return result diff --git a/python/longest_palindrome.py b/python/longest_palindrome.py new file mode 100644 index 0000000..41c66fb --- /dev/null +++ b/python/longest_palindrome.py @@ -0,0 +1,10 @@ +class Solution: + def isPalindrome(self, number: int) -> bool: + if number == 0: return True + if number % 10 == 0 or number < 0: return False + + right = 0 + while number > right: + right = 10 * right + number % 10 + number //= 10 + return number == right or (number == right // 10) diff --git a/python/longest_uncommon_subsequence_I.py b/python/longest_uncommon_subsequence_I.py new file mode 100644 index 0000000..b107546 --- /dev/null +++ b/python/longest_uncommon_subsequence_I.py @@ -0,0 +1,4 @@ +class Solution: + def findLUSlength(self, a: str, b: str) -> int: + if a == b: return -1 + return max(len(a), len(b)) diff --git a/python/lowest_common_ancestor_of_bst.py b/python/lowest_common_ancestor_of_bst.py new file mode 100644 index 0000000..dce7ad6 --- /dev/null +++ b/python/lowest_common_ancestor_of_bst.py @@ -0,0 +1,29 @@ +from collections import deque + + +# Definition for a binary tree node. +class TreeNode: + def __init__(self, x): + self.val = x + self.left = None + self.right = None + + +class Solution: + def get_path_to(self, root: TreeNode, node: TreeNode) -> deque: + path = deque() + while root.val != node.val: + path.append(root) + root = root.left if root.val > node.val else root.right + path.append(root) + return path + + def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode: + path_p = self.get_path_to(root, p) + path_q = self.get_path_to(root, q) + index = 0 + for node_p, node_q in zip(path_p, path_q): + if node_p is not node_q: + break + index += 1 + return path_p[index - 1] diff --git a/python/majority_element.py b/python/majority_element.py new file mode 100644 index 0000000..10326bd --- /dev/null +++ b/python/majority_element.py @@ -0,0 +1,12 @@ +from typing import List + + +class Solution: + def majorityElement(self, nums: List[int]) -> int: + element, count = nums[0], 0 + for number in nums: + count += 1 if number == element else -1 + if count == 0: + element = number + count = 1 + return element diff --git a/python/max_consecutive_ones.py b/python/max_consecutive_ones.py new file mode 100644 index 0000000..4424606 --- /dev/null +++ b/python/max_consecutive_ones.py @@ -0,0 +1,14 @@ +from typing import List + + +class Solution: + def findMaxConsecutiveOnes(self, nums: List[int]) -> int: + max_ones, current = 0, 0 + for number in nums: + if number == 1: + current += 1 + else: + max_ones = max(max_ones, current) + current = 0 + max_ones = max(max_ones, current) + return max_ones diff --git a/python/maximum_average_subarray_I.py b/python/maximum_average_subarray_I.py new file mode 100644 index 0000000..7af6ab8 --- /dev/null +++ b/python/maximum_average_subarray_I.py @@ -0,0 +1,11 @@ +from typing import List + + +class Solution: + def findMaxAverage(self, nums: List[int], k: int) -> float: + moving_sum = sum(nums[i] for i in range(k)) + result = moving_sum + for i in range(len(nums) - k): + moving_sum += nums[k + i] - nums[i] + result = max(result, moving_sum) + return result / k diff --git a/python/maximum_depth_of_binary_tree.py b/python/maximum_depth_of_binary_tree.py new file mode 100644 index 0000000..7911611 --- /dev/null +++ b/python/maximum_depth_of_binary_tree.py @@ -0,0 +1,13 @@ +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def maxDepth(self, root: TreeNode) -> int: + if root is None: + return 0 + return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) diff --git a/python/maximum_depth_of_n_ary_tree.py b/python/maximum_depth_of_n_ary_tree.py new file mode 100644 index 0000000..d084998 --- /dev/null +++ b/python/maximum_depth_of_n_ary_tree.py @@ -0,0 +1,14 @@ +# Definition for a Node. +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children + + +class Solution: + def maxDepth(self, root: Node) -> int: + if root is None: return 0 + max_depth = 0 + for child in root.children: + max_depth = max(max_depth, self.maxDepth(child)) + return 1 + max_depth diff --git a/python/maximum_product_of_three_numbers.py b/python/maximum_product_of_three_numbers.py new file mode 100644 index 0000000..50cb201 --- /dev/null +++ b/python/maximum_product_of_three_numbers.py @@ -0,0 +1,24 @@ +from typing import List + + +class Solution: + def maximumProduct(self, array: List[int]) -> int: + positive_1, positive_2, positive_3 = (-float('inf'), ) * 3 + negative_1, negative_2 = (float('inf'), ) * 2 + for number in array: + if number > positive_1: + positive_3 = positive_2 + positive_2 = positive_1 + positive_1 = number + elif number > positive_2: + positive_3 = positive_2 + positive_2 = number + elif number > positive_3: + positive_3 = number + if number < negative_1: + negative_2 = negative_1 + negative_1 = number + elif number < negative_2: + negative_2 = number + + return max(positive_1 * positive_2 * positive_3, negative_1 * negative_2 * positive_1) diff --git a/python/maximum_sum_subarray.py b/python/maximum_sum_subarray.py new file mode 100644 index 0000000..8eecc3f --- /dev/null +++ b/python/maximum_sum_subarray.py @@ -0,0 +1,12 @@ +# Kadane's Algorithm +from typing import List + + +class Solution: + def maxSubArray(self, array: List[int]) -> int: + max_sum, current_sum = -float('infinity'), 0 + for element in array: + current_sum += element + max_sum = max(current_sum, max_sum) + current_sum = max(current_sum, 0) + return int(max_sum) diff --git a/python/merge_sorted_array.py b/python/merge_sorted_array.py new file mode 100644 index 0000000..ec333fd --- /dev/null +++ b/python/merge_sorted_array.py @@ -0,0 +1,25 @@ +from typing import List + + +class Solution: + def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: + result = [0] * (m + n) + i, j, k = 0, 0, 0 + while i < m and j < n: + if nums1[i] < nums2[j]: + result[k] = nums1[i] + i += 1 + else: + result[k] = nums2[j] + j += 1 + k += 1 + while i < m: + result[k] = nums1[i] + i += 1 + k += 1 + while j < n: + result[k] = nums2[j] + j += 1 + k += 1 + for i in range(m + n): + nums1[i] = result[i] diff --git a/python/merge_two_binary_trees.py b/python/merge_two_binary_trees.py new file mode 100644 index 0000000..01bfbed --- /dev/null +++ b/python/merge_two_binary_trees.py @@ -0,0 +1,16 @@ +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode: + if root1 is None: return root2 + if root2 is None: return root1 + root1.val += root2.val + root1.left = self.mergeTrees(root1.left, root2.left) + root1.right = self.mergeTrees(root1.right, root2.right) + return root1 diff --git a/python/min_cost_climbing_stairs.py b/python/min_cost_climbing_stairs.py new file mode 100644 index 0000000..5ce9a1e --- /dev/null +++ b/python/min_cost_climbing_stairs.py @@ -0,0 +1,11 @@ +from typing import List + + +class Solution: + def minCostClimbingStairs(self, cost: List[int]) -> int: + previousCost, currentCost = cost[0], cost[1] + index = 2 + while index < len(cost): + previousCost, currentCost = currentCost, min(previousCost, currentCost) + cost[index] + index += 1 + return min(previousCost, currentCost) diff --git a/python/min_stack.py b/python/min_stack.py new file mode 100644 index 0000000..a080dd7 --- /dev/null +++ b/python/min_stack.py @@ -0,0 +1,32 @@ +class Node: + def __init__(self, val, min, previous): + self.val = val + self.next = next + self.min = min + self.previous = previous + +class MinStack: + + def __init__(self): + """ + initialize your data structure here. + """ + self.current = None + + def push(self, val: int) -> None: + if self.current is None: + self.current = Node(val, val, None) + else: + self.current.next = Node(val, min(val, self.current.min), self.current) + self.current = self.current.next + + def pop(self) -> None: + val = self.current.val + self.current = self.current.previous + return val + + def top(self) -> int: + return self.current.val + + def getMin(self) -> int: + return self.current.min diff --git a/python/minimize_maximum_of_array.py b/python/minimize_maximum_of_array.py new file mode 100644 index 0000000..d9e0c27 --- /dev/null +++ b/python/minimize_maximum_of_array.py @@ -0,0 +1,12 @@ +# https://leetcode.com/problems/minimize-maximum-of-array/description/ +# T:O(n) where n is the number of elements in the array +# S:O(1) + +class Solution: + def minimizeArrayValue(self, nums: List[int]) -> int: + minimumValue = 0 + prefixSum = 0 + for i, num in enumerate(nums): + prefixSum += num + minimumValue = max(minimumValue,((prefixSum+i)//(i+1))) + return minimumValue diff --git a/python/minimum_absolute_difference_in_bst.py b/python/minimum_absolute_difference_in_bst.py new file mode 100644 index 0000000..3f216b4 --- /dev/null +++ b/python/minimum_absolute_difference_in_bst.py @@ -0,0 +1,21 @@ +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def __init__(self): + self.infinity = float('inf') + self.result = self.infinity + + def computeMinimumAbsDifference(self, root: TreeNode, left: float, right: float): + if root is None: return + self.result = min(self.result, root.val - left, right- root.val) + self.computeMinimumAbsDifference(root.left, left, root.val) + self.computeMinimumAbsDifference(root.right, root.val, right) + + def getMinimumDifference(self, root: TreeNode) -> int: + self.computeMinimumAbsDifference(root, -self.infinity, self.infinity) + return int(self.result) diff --git a/python/minimum_cost_for_tickets.py b/python/minimum_cost_for_tickets.py new file mode 100644 index 0000000..8a88372 --- /dev/null +++ b/python/minimum_cost_for_tickets.py @@ -0,0 +1,26 @@ +# https://leetcode.com/problems/minimum-cost-for-tickets/description/ +# T: O(N) where N is the last day of travel +# S: O(N) where N is the last day of travel + +class Solution: + def mincostTickets(self, days, costs): + # Create a list of size days[-1] + 1 and initialize it with 0's + dp = [0] * (days[-1] + 1) + + # Create a set of travel days + travel_days = set(days) + + # Iterate over the range of 1 to len(dp) with a step of 1 + for i in range(1, len(dp)): + # If the current day is not in the set of travel days + if i not in travel_days: + # Set its cost to the cost of traveling on the previous day + dp[i] = dp[i - 1] + else: + # Calculate the minimum cost for traveling on that day + dp[i] = min(dp[max(0, i - 1)] + costs[0], + dp[max(0, i - 7)] + costs[1], + dp[max(0, i - 30)] + costs[2]) + + # Return the last element of this list which will be the minimum cost of travel for all days + return dp[-1] diff --git a/python/minimum_depth_of_binary_tree.py b/python/minimum_depth_of_binary_tree.py new file mode 100644 index 0000000..985cff9 --- /dev/null +++ b/python/minimum_depth_of_binary_tree.py @@ -0,0 +1,17 @@ +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def minDepth(self, root: TreeNode) -> int: + if root is None: + return 0 + if root.left is None: + return 1 + self.minDepth(root.right) + if root.right is None: + return 1 + self.minDepth(root.left) + return 1 + min(self.minDepth(root.left), self.minDepth(root.right)) \ No newline at end of file diff --git a/python/minimum_distance_between_bst_nodes.py b/python/minimum_distance_between_bst_nodes.py new file mode 100644 index 0000000..0cc5736 --- /dev/null +++ b/python/minimum_distance_between_bst_nodes.py @@ -0,0 +1,22 @@ +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def __init__(self): + self.infinity = float('inf') + self.result = self.infinity + + def computeMinimumAbsDifference(self, root: TreeNode, left: float, right: float): + if root is None: return + self.result = min(self.result, root.val - left, right- root.val) + self.computeMinimumAbsDifference(root.left, left, root.val) + self.computeMinimumAbsDifference(root.right, root.val, right) + + def minDiffInBST(self, root: TreeNode) -> int: + self.computeMinimumAbsDifference(root, -self.infinity, self.infinity) + return int(self.result) diff --git a/python/minimum_index_sum_of_two_lists.py b/python/minimum_index_sum_of_two_lists.py new file mode 100644 index 0000000..d58b523 --- /dev/null +++ b/python/minimum_index_sum_of_two_lists.py @@ -0,0 +1,17 @@ +from typing import List + + +class Solution: + def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]: + restaurant1_2_indices = {} + index_sum = float('inf') + result = [] + for index, restaurant in enumerate(list1): + restaurant1_2_indices[restaurant] = index + for index, restaurant in enumerate(list2): + if index + restaurant1_2_indices.get(restaurant, float('inf')) < index_sum: + index_sum = index + restaurant1_2_indices[restaurant] + result = [restaurant] + elif index + restaurant1_2_indices.get(restaurant, float('inf')) == index_sum: + result.append(restaurant) + return result diff --git a/python/minimum_path_sum.py b/python/minimum_path_sum.py new file mode 100644 index 0000000..af71159 --- /dev/null +++ b/python/minimum_path_sum.py @@ -0,0 +1,19 @@ +# https://leetcode.com/problems/minimum-path-sum/ +# T: O(m*n) where n is the number of rows and m is the number of columns +# S: O(1) + +class Solution: + def minPathSum(self, grid): + rows, columns = len(grid), len(grid[0]) + + for column in range(columns - 2, -1, -1): + grid[rows - 1][column] += grid[rows - 1][column + 1] + + for row in range(rows - 2, -1, -1): + grid[row][columns - 1] += grid[row + 1][columns - 1] + + for row in range(rows - 2, -1, -1): + for column in range(columns - 2, -1, -1): + grid[row][column] += min(grid[row + 1][column], grid[row][column + 1]) + + return grid[0][0] diff --git a/python/minimum_score_of_a_path_between_two_cities.py b/python/minimum_score_of_a_path_between_two_cities.py new file mode 100644 index 0000000..37cfc10 --- /dev/null +++ b/python/minimum_score_of_a_path_between_two_cities.py @@ -0,0 +1,34 @@ +# https://leetcode.com/problems/minimum-score-of-a-path-between-two-cities/ +# T: O(N + M) where N is the number of nodes and M is the number of edges +# S: O(N + M) where N is the number of nodes and M is the number of edges + +from collections import deque + +class Solution: + def __init__(self): + self.min_dist = 1e14 + + def minScore(self, n: int, roads) -> int: + graph = {} + vis = [False]*n + for x, y, d in roads: + if x in graph: + graph[x].append((y, d)) + else: + graph[x] = [(y, d)] + if y in graph: + graph[y].append((x, d)) + else: + graph[y] = [(x, d)] + + visited = set() + queue = deque([1]) + + while queue: + node = queue.popleft() + for adj, score in graph[node]: + if adj not in visited: + queue.append(adj) + visited.add(adj) + self.min_dist = min(self.min_dist, score) + return self.min_dist diff --git a/python/missing_number.py b/python/missing_number.py new file mode 100644 index 0000000..51b3bb4 --- /dev/null +++ b/python/missing_number.py @@ -0,0 +1,8 @@ +from typing import List + + +class Solution: + def missingNumber(self, nums: List[int]) -> int: + n = len(nums) + acttual_sum = (n * (n + 1)) // 2 + return acttual_sum - sum(nums) diff --git a/python/move_zeroes.py b/python/move_zeroes.py new file mode 100644 index 0000000..e469ed1 --- /dev/null +++ b/python/move_zeroes.py @@ -0,0 +1,16 @@ +from typing import List + + +class Solution: + def moveZeroes(self, nums: List[int]) -> None: + if len(nums) == 1: + return + i, j = 0, 1 + while True: + while i < len(nums) and nums[i] != 0: + i += 1 + while j < len(nums) and (nums[j] == 0 or j < i): + j += 1 + if i >= len(nums) or j >= len(nums): + break + nums[i], nums[j] = nums[j], 0 diff --git a/python/n_ary_tree_postorder_traversal.py b/python/n_ary_tree_postorder_traversal.py new file mode 100644 index 0000000..bc7f82a --- /dev/null +++ b/python/n_ary_tree_postorder_traversal.py @@ -0,0 +1,23 @@ +# Definition for a Node. +from typing import List + + +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children + + +class Solution: + def __init__(self): + self.result = [] + + def postorderTraversal(self, root: Node) -> None: + if root is None: return None + for child in root.children: + self.postorderTraversal(child) + self.result.append(root.val) + + def postorder(self, root: Node) -> List[int]: + self.postorderTraversal(root) + return self.result diff --git a/python/n_ary_tree_preorder_traversal.py b/python/n_ary_tree_preorder_traversal.py new file mode 100644 index 0000000..0426b50 --- /dev/null +++ b/python/n_ary_tree_preorder_traversal.py @@ -0,0 +1,23 @@ +# Definition for a Node. +from typing import List + + +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children + + +class Solution: + def __init__(self): + self.result = [] + + def preorderTraversal(self, root: Node) -> None: + if root is None: return None + self.result.append(root.val) + for child in root.children: + self.preorderTraversal(child) + + def preorder(self, root: Node) -> List[int]: + self.preorderTraversal(root) + return self.result diff --git a/python/nim_game.py b/python/nim_game.py new file mode 100644 index 0000000..990afa9 --- /dev/null +++ b/python/nim_game.py @@ -0,0 +1,3 @@ +class Solution: + def canWinNim(self, n: int) -> bool: + return n % 4 is not 0 diff --git a/python/no_of_operations_to_make_network_connected.py b/python/no_of_operations_to_make_network_connected.py new file mode 100644 index 0000000..f5cec37 --- /dev/null +++ b/python/no_of_operations_to_make_network_connected.py @@ -0,0 +1,35 @@ +# https://leetcode.com/problems/number-of-operations-to-make-network-connected/description/ +# T: O(M) where M is the number of connections +# S: O(N) where N is the number of nodes + +class Solution: + def makeConnected(self, n, connections) -> int: + if len(connections) < n-1: + return -1 + if n == 1: + return 0 + graph = {} + for a, b in connections: + if a in graph: + graph[a].append(b) + else: + graph[a] = [b] + + if b in graph: + graph[b].append(a) + else: + graph[b] = [a] + + visited = [0] * n + + def dfs(node): + if visited[node]: + return 0 + visited[node] = 1 + if node in graph: + for num in graph[node]: + dfs(num) + return 1 + + + return sum(dfs(node) for node in range(n)) - 1 diff --git a/python/non_decreasing_array.py b/python/non_decreasing_array.py new file mode 100644 index 0000000..cdaaf60 --- /dev/null +++ b/python/non_decreasing_array.py @@ -0,0 +1,13 @@ +from typing import List + + +class Solution: + def checkPossibility(self, nums: List[int]) -> bool: + handled_decreasing = False + for index in range(len(nums) - 1): + if nums[index] > nums[index + 1]: + if handled_decreasing: return False + handled_decreasing = True + if index - 1 >= 0 and nums[index - 1] > nums[index + 1] and index + 2 < len(nums) and nums[index] > nums[index + 2]: + return False + return True diff --git a/python/number_complement.py b/python/number_complement.py new file mode 100644 index 0000000..1e7ad0a --- /dev/null +++ b/python/number_complement.py @@ -0,0 +1,12 @@ +class Solution: + def highest_one_bit(self, i: int) -> int: + i |= (i >> 1) + i |= (i >> 2) + i |= (i >> 4) + i |= (i >> 8) + i |= (i >> 16) + return i - (i >> 1) + + def findComplement(self, number: int) -> int: + return ~number & (self.highest_one_bit(number) - 1) + diff --git a/python/number_of_boomerangs.py b/python/number_of_boomerangs.py new file mode 100644 index 0000000..4e716b1 --- /dev/null +++ b/python/number_of_boomerangs.py @@ -0,0 +1,20 @@ +from typing import List + + +class Solution: + def get_distance(self, p1: List[int], p2: List[int]) -> int: + x1, y1 = p1 + x2, y2 = p2 + dx, dy = x2 - x1, y2 - y1 + return dx ** 2 + dy ** 2 + + def numberOfBoomerangs(self, points: List[List[int]]) -> int: + result = 0 + for p1 in points: + distance_frequency = {} + for p2 in points: + distance = self.get_distance(p1, p2) + distance_frequency[distance] = distance_frequency.get(distance, 0) + 1 + for frequency in distance_frequency.values(): + result += frequency * (frequency - 1) + return result diff --git a/python/number_of_closed_islands.py b/python/number_of_closed_islands.py new file mode 100644 index 0000000..88944ab --- /dev/null +++ b/python/number_of_closed_islands.py @@ -0,0 +1,30 @@ +# https://leetcode.com/problems/number-of-closed-islands/description/ +# T: O(m*n) +# S: O(m*n) + +class Solution: + def closedIsland(self, grid: List[List[int]]) -> int: + m = len(grid) + n = len(grid[0]) + visit = [[False] * n for _ in range(m)] + count = 0 + + def dfs(x: int, y: int, m: int, n: int, grid: List[List[int]], visit: List[List[bool]]) -> bool: + if x < 0 or x >= m or y < 0 or y >= n: + # (x, y) is a boundary cell. + return False + if grid[x][y] == 1 or visit[x][y]: + # (x, y) is not a valid cell to visit. + return True + visit[x][y] = True + isClosed = True + for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]: + isClosed &= dfs(x + dx, y + dy, m, n, grid, visit) + return isClosed + + for i in range(m): + for j in range(n): + if grid[i][j] == 0 and not visit[i][j] and dfs(i, j, m, n, grid, visit): + count += 1 + + return count diff --git a/python/number_of_enclaves.py b/python/number_of_enclaves.py new file mode 100644 index 0000000..73f6248 --- /dev/null +++ b/python/number_of_enclaves.py @@ -0,0 +1,42 @@ +# https://leetcode.com/problems/number-of-enclaves/description/ +# T: O(m*n) +# S: O(m*n) + +from typing import List + +class Solution: + def dfs(self, x: int, y: int, m: int, n: int, grid: List[List[int]], visit: List[List[bool]]): + if x < 0 or x >= m or y < 0 or y >= n or visit[x][y] or grid[x][y] == 0: + return + visit[x][y] = True + self.dfs(x+1, y, m, n, grid, visit) + self.dfs(x-1, y, m, n, grid, visit) + self.dfs(x, y+1, m, n, grid, visit) + self.dfs(x, y-1, m, n, grid, visit) + + def numEnclaves(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + visit = [[False for _ in range(n)] for _ in range(m)] + + # Traverse the first and last columns. + for i in range(m): + if grid[i][0] == 1 and not visit[i][0]: + self.dfs(i, 0, m, n, grid, visit) + if grid[i][n-1] == 1 and not visit[i][n-1]: + self.dfs(i, n-1, m, n, grid, visit) + + # Traverse the first and last rows. + for j in range(n): + if grid[0][j] == 1 and not visit[0][j]: + self.dfs(0, j, m, n, grid, visit) + if grid[m-1][j] == 1 and not visit[m-1][j]: + self.dfs(m-1, j, m, n, grid, visit) + + # Count the number of unvisited land cells. + count = 0 + for i in range(m): + for j in range(n): + if grid[i][j] == 1 and not visit[i][j]: + count += 1 + + return count diff --git a/python/number_of_islands.py b/python/number_of_islands.py new file mode 100644 index 0000000..76d2814 --- /dev/null +++ b/python/number_of_islands.py @@ -0,0 +1,24 @@ +# https://leetcode.com/problems/number-of-islands/description/ +# T: O(MN) where M is the number of rows and N is the number of columns. +# S: O(MN) where M is the number of rows and N is the number of columns. + +def numIslands(self, grid): + if not grid: + return 0 + + count = 0 + for i in range(len(grid)): + for j in range(len(grid[0])): + if grid[i][j] == '1': + self.dfs(grid, i, j) + count += 1 + return count + +def dfs(self, grid, i, j): + if i<0 or j<0 or i>=len(grid) or j>=len(grid[0]) or grid[i][j] != '1': + return + grid[i][j] = '#' + self.dfs(grid, i+1, j) + self.dfs(grid, i-1, j) + self.dfs(grid, i, j+1) + self.dfs(grid, i, j-1) diff --git a/python/number_of_segments_in_a_string.py b/python/number_of_segments_in_a_string.py new file mode 100644 index 0000000..ce40742 --- /dev/null +++ b/python/number_of_segments_in_a_string.py @@ -0,0 +1,11 @@ +class Solution: + def countSegments(self, s: str) -> int: + counting, segments = False, 0 + for character in s: + if counting and character == ' ': + counting = False + continue + if not counting and character != ' ': + segments += 1 + counting = True + return segments diff --git a/python/number_of_ways_of_cutting_pizza.py b/python/number_of_ways_of_cutting_pizza.py new file mode 100644 index 0000000..d4fe288 --- /dev/null +++ b/python/number_of_ways_of_cutting_pizza.py @@ -0,0 +1,24 @@ +# https://leetcode.com/problems/number-of-ways-of-cutting-a-pizza/ +# T: O(k*r*c*(m+n)) where k is the number of cuts, r and c are the number of rows and columns in the pizza, and m and n are the number of rows and columns in the preSum array. +# S: O(k*r*c) where k is the number of cuts, and r and c are the number of rows and columns in the pizza. + +class Solution: + def ways(self, pizza: List[str], K: int) -> int: + m, n, MOD = len(pizza), len(pizza[0]), 10 ** 9 + 7 + preSum = [[0] * (n + 1) for _ in range(m + 1)] + for r in range(m - 1, -1, -1): + for c in range(n - 1, -1, -1): + preSum[r][c] = preSum[r][c + 1] + preSum[r + 1][c] - preSum[r + 1][c + 1] + (pizza[r][c] == 'A') + @lru_cache(None) + def dp(k, r, c): + if preSum[r][c] == 0: return 0 + if k == 0: return 1 + ans = 0 + for nr in range(r + 1, m): + if preSum[r][c] - preSum[nr][c] > 0: + ans = (ans + dp(k - 1, nr, c)) % MOD + for nc in range(c + 1, n): + if preSum[r][c] - preSum[r][nc] > 0: + ans = (ans + dp(k - 1, r, nc)) % MOD + return ans + return dp(K - 1, 0, 0) diff --git a/python/number_of_zero_filled_subarrays.py b/python/number_of_zero_filled_subarrays.py new file mode 100644 index 0000000..1438c11 --- /dev/null +++ b/python/number_of_zero_filled_subarrays.py @@ -0,0 +1,19 @@ +# https://leetcode.com/problems/number-of-zero-filled-subarrays/ +# T: O(N) where N is the length of nums +# S: O(1) + +class Solution: + def zeroFilledSubarray(self, nums) -> int: + count = 0 + i = 0 + while i < len(nums): + if nums[i] == 0: + j = i + while j < len(nums) and nums[j] == 0: + j += 1 + count += (j - i) * (j - i + 1) // 2 + i = j + else: + i = i+1 + + return count diff --git a/python/one_bit_and_two_bit_characters.py b/python/one_bit_and_two_bit_characters.py new file mode 100644 index 0000000..a0adf0f --- /dev/null +++ b/python/one_bit_and_two_bit_characters.py @@ -0,0 +1,11 @@ +from typing import List + + +class Solution: + def isOneBitCharacter(self, bits: List[int]) -> bool: + count = 0 + index = len(bits) - 2 + while index >= 0 and bits[index] != 0: + if bits[index] == 1: count += 1 + index -= 1 + return count % 2 == 0 diff --git a/python/palindrome_linked_list.py b/python/palindrome_linked_list.py new file mode 100644 index 0000000..52b8a29 --- /dev/null +++ b/python/palindrome_linked_list.py @@ -0,0 +1,42 @@ +# Definition for singly-linked list. +from typing import Optional + + +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + + +class Solution: + def length(self, head: ListNode) -> int: + count = 0 + while head is not None: + count += 1 + head = head.next + return count + + def reverse(self, head: ListNode) -> Optional[ListNode]: + if head is None or head.next is None: + return head + a, b, c = head, head.next, head.next.next + a.next = None + while c is not None: + b.next = a + a, b, c = b, c, c.next + b.next = a + return b + + def isPalindrome(self, head: ListNode) -> bool: + list_length = self.length(head) + first_half = head + second_half = head + for i in range((list_length + 1) // 2): + second_half = second_half.next + second_half = self.reverse(second_half) + while second_half is not None: + if first_half.val != second_half.val: + return False + second_half = second_half.next + first_half = first_half.next + return True diff --git a/python/palindrome_number.py b/python/palindrome_number.py index 1d4feba..21e447c 100644 --- a/python/palindrome_number.py +++ b/python/palindrome_number.py @@ -1,7 +1,19 @@ +import math + + class Solution: def isPalindrome(self, number: int) -> bool: - number = str(number) - for i in range(len(number) // 2): - if number[i] != number[- (i + 1)]: + if number < 0: return False + if number == 0: return True + + length = math.floor(math.log(number, 10) + 1) + divisor = 10 ** (length - 1) + modulo = 1 + for i in range(length // 2): + left = (number // divisor) % 10 + right = (number % (10 * modulo)) // modulo + if left != right: return False + divisor //= 10 + modulo *= 10 return True diff --git a/python/pascals_triangle.py b/python/pascals_triangle.py new file mode 100644 index 0000000..d2b959c --- /dev/null +++ b/python/pascals_triangle.py @@ -0,0 +1,13 @@ +from typing import List + + +class Solution: + def generate(self, numRows: int) -> List[List[int]]: + ans = [None] * numRows + for i in range(numRows): + row, mid = [1] * (i + 1), (i >> 1) + 1 + for j in range(1, mid): + val = ans[i - 1][j - 1] + ans[i-1][j] + row[j], row[len(row) - j-1] = val, val + ans[i] = row + return ans diff --git a/python/pascals_triangle_ii.py b/python/pascals_triangle_ii.py new file mode 100644 index 0000000..4a561b0 --- /dev/null +++ b/python/pascals_triangle_ii.py @@ -0,0 +1,12 @@ +from typing import List + + +class Solution: + def getRow(self, rowIndex: int) -> List[int]: + result = [1] * (rowIndex + 1) + val = 1 + for i in range(1, rowIndex): + val *= (rowIndex + 1 - i) + val //= i + result[i] = val + return result diff --git a/python/path_sum.py b/python/path_sum.py new file mode 100644 index 0000000..bf1e7bc --- /dev/null +++ b/python/path_sum.py @@ -0,0 +1,30 @@ +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def _is_leaf_node(self, node: TreeNode) -> bool: + return node.left is None and node.right is None + + def _has_path_sum(self, root: TreeNode, target: int, currentSum: int) -> bool: + if root is None: + return False + currentSum += root.val + if self._is_leaf_node(root): + return currentSum == target + return self._has_path_sum(root.left, target, currentSum) or \ + self._has_path_sum(root.right, target, currentSum) + + def hasPathSum(self, root: TreeNode, targetSum: int) -> bool: + if root is None: + return False + return self._has_path_sum(root, targetSum, 0) + + +root = TreeNode(val=1) +root.right = TreeNode(val=2) +print(Solution().hasPathSum(root, 3)) diff --git a/python/plus_one.py b/python/plus_one.py new file mode 100644 index 0000000..7ba5443 --- /dev/null +++ b/python/plus_one.py @@ -0,0 +1,15 @@ +from typing import List + + +def plusOne(digits: List[int]) -> List[int]: + carry = 1 + for index in range(len(digits) - 1, -1, -1): + result = digits[index] + carry + digits[index] = result % 10 + carry = result // 10 + if carry == 0: + return digits + return [1, *digits] + + +print(plusOne([int(digit) for digit in input()])) diff --git a/python/power_of_four.py b/python/power_of_four.py new file mode 100644 index 0000000..5302247 --- /dev/null +++ b/python/power_of_four.py @@ -0,0 +1,9 @@ +class Solution: + def isPowerOfFour(self, n: int) -> bool: + if n <= 0: + return False + if n == 1: + return True + while n % 4 == 0: + n //= 4 + return n == 1 diff --git a/python/power_of_three.py b/python/power_of_three.py new file mode 100644 index 0000000..8b1a2c0 --- /dev/null +++ b/python/power_of_three.py @@ -0,0 +1,9 @@ +class Solution: + def isPowerOfThree(self, n: int) -> bool: + if n <= 0: + return False + if n == 1: + return True + while n % 3 == 0: + n //= 3 + return n == 1 diff --git a/python/prime_number_of_set_bits_in_binary_representation.py b/python/prime_number_of_set_bits_in_binary_representation.py new file mode 100644 index 0000000..1be06d6 --- /dev/null +++ b/python/prime_number_of_set_bits_in_binary_representation.py @@ -0,0 +1,22 @@ +class Solution: + def __init__(self): + self.isPrime = [ + 0, 0, 1, 1, 0, 1, 0, + 1, 0, 0, 0, 1, 0, + 1, 0, 0, 0, 1, 0, + 1, 0, 0, 0, 1, 0 + ] + + def countPrimeSetBits(self, left: int, right: int) -> int: + primeSetBits = 0 + for number in range(left, right + 1): + if self.isPrime[self.setBits(number)] == 1: + primeSetBits += 1 + return primeSetBits + + def setBits(self, number: int) -> int: + result = 0 + while number > 0: + result += number & 1 + number >>= 1 + return result diff --git a/python/range_addition_ii.py b/python/range_addition_ii.py new file mode 100644 index 0000000..41cf38c --- /dev/null +++ b/python/range_addition_ii.py @@ -0,0 +1,9 @@ +from typing import List + + +class Solution: + def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int: + for operation in ops: + m = min(m, operation[0]) + n = min(n, operation[0]) + return m * n diff --git a/python/range_sum_query_immutable.py b/python/range_sum_query_immutable.py new file mode 100644 index 0000000..b131d75 --- /dev/null +++ b/python/range_sum_query_immutable.py @@ -0,0 +1,12 @@ +from typing import List + + +class NumArray: + + def __init__(self, nums: List[int]): + self.sum_till = [0] * (len(nums) + 1) + for index, number in enumerate(nums): + self.sum_till[index + 1] = self.sum_till[index] + number + + def sumRange(self, left: int, right: int) -> int: + return self.sum_till[right + 1] - self.sum_till[left] diff --git a/python/ransom_note.py b/python/ransom_note.py new file mode 100644 index 0000000..b14fb21 --- /dev/null +++ b/python/ransom_note.py @@ -0,0 +1,18 @@ +from typing import Dict + + +class Solution: + def get_char_frequency(self, string: str) -> Dict[str, int]: + frequency = {} + for character in string: + frequency[character] = frequency.get(character, 0) + 1 + return frequency + + def canConstruct(self, ransomNote: str, magazine: str) -> bool: + magazine_characters = self.get_char_frequency(magazine) + for character in ransomNote: + if magazine_characters.get(character, 0) == 0: + return False + else: + magazine_characters[character] -= 1 + return True diff --git a/python/reducing_dishes.py b/python/reducing_dishes.py new file mode 100644 index 0000000..bafc396 --- /dev/null +++ b/python/reducing_dishes.py @@ -0,0 +1,17 @@ +# https://leetcode.com/problems/reducing-dishes/ +# T: O(nlogn) where n is the length of satisfaction +# S: O(1) + +class Solution: + def maxSatisfaction(self, satisfaction: List[int]) -> int: + satisfaction.sort(reverse = True) + n = len(satisfaction) + presum , res = 0, 0 + + for i in range(n): + presum += satisfaction[i] + if presum < 0: + break + res = res + presum + + return res diff --git a/python/relative_ranks.py b/python/relative_ranks.py new file mode 100644 index 0000000..8908858 --- /dev/null +++ b/python/relative_ranks.py @@ -0,0 +1,20 @@ +from typing import List + + +class Solution: + def get_rank(self, position: int) -> str: + if position == 1: return 'Gold Medal' + if position == 2: return 'Silver Medal' + if position == 3: return 'Bronze Medal' + return str(position) + + def findRelativeRanks(self, score: List[int]) -> List[str]: + numbers = [(index, val) for index, val in enumerate(score)] + numbers.sort(key=lambda x: x[1], reverse=True) + value_to_index = {} + for index, (_, value) in enumerate(numbers): + value_to_index[value] = index + result = [''] * len(score) + for index, value in enumerate(score): + result[index] = self.get_rank(value_to_index[value] + 1) + return result diff --git a/python/remove_duplicates_from_linked_list.py b/python/remove_duplicates_from_linked_list.py new file mode 100644 index 0000000..2990e38 --- /dev/null +++ b/python/remove_duplicates_from_linked_list.py @@ -0,0 +1,16 @@ +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + + +def deleteDuplicates(head: ListNode) -> ListNode: + if head is None: + return None + current = head + while current is not None: + if current.val == current.next.val: + current.next = current.next.next + else: + current = current.next + return head diff --git a/python/remove_linked_list_elements.py b/python/remove_linked_list_elements.py new file mode 100644 index 0000000..9ffcf55 --- /dev/null +++ b/python/remove_linked_list_elements.py @@ -0,0 +1,20 @@ +from typing import Union + + +# Definition for singly-linked list. +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + + +class Solution: + def removeElements(self, head: ListNode, val: int) -> Union[None, ListNode]: + current = ListNode(val=0, next=head) + start = current + while current is not None and current.next is not None: + if current.next.val == val: + current.next = current.next.next + else: + current = current.next + return start.next diff --git a/python/reorder_routes_to_make_all_paths_lead_to_city_zero.py b/python/reorder_routes_to_make_all_paths_lead_to_city_zero.py new file mode 100644 index 0000000..1c89b52 --- /dev/null +++ b/python/reorder_routes_to_make_all_paths_lead_to_city_zero.py @@ -0,0 +1,26 @@ +# https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/description/ +# T: O(N) where N is the number of nodes in the graph +# S: O(N) where N is the number of nodes in the graph + +class Solution: + def __init__(self): + self.reorders = 0 + + def minReorder(self, n, connections): + edges = {(u, v) for u, v in connections} + graph = {i:[] for i in range(n)} + for u, v in connections: + graph[u].append(v) + graph[v].append(u) + visit = set() + visit.add(0) + def dfs(graph, edges, visit, city): + for node in graph[city]: + if node in visit: + continue + if (node, city) not in edges: + self.reorders+=1 + visit.add(node) + dfs(graph, edges, visit, node) + dfs(graph, edges, visit, 0) + return self.reorders diff --git a/python/replace_element_with_greatest_element_on_right_hand_side.py b/python/replace_element_with_greatest_element_on_right_hand_side.py new file mode 100644 index 0000000..2335259 --- /dev/null +++ b/python/replace_element_with_greatest_element_on_right_hand_side.py @@ -0,0 +1,13 @@ +from typing import List + + +class Solution: + def replaceElements(self, array: List[int]) -> List[int]: + result = [0] * len(array) + result[len(result) - 1] = -1 + index, greatest = len(array) - 2, array[len(array) - 1] + while index >= 0: + result[index] = greatest + greatest = max(greatest, array[index]) + index -= 1 + return result diff --git a/python/reshape_the_matrix.py b/python/reshape_the_matrix.py new file mode 100644 index 0000000..9edd722 --- /dev/null +++ b/python/reshape_the_matrix.py @@ -0,0 +1,13 @@ +from typing import List + + +class Solution: + def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]: + if r * c != len(mat) * len(mat[0]) or (r == len(mat) and c == len(mat[0])): return mat + result = [[0] * c for _ in range(r)] + k = 0 + for i in range(len(mat)): + for j in range(len(mat[0])): + result[k // c][k % c] = mat[i][j] + k += 1 + return result diff --git a/python/reverse_a_string.py b/python/reverse_a_string.py new file mode 100644 index 0000000..f323fbe --- /dev/null +++ b/python/reverse_a_string.py @@ -0,0 +1,7 @@ +from typing import List + + +class Solution: + def reverseString(self, s: List[str]) -> None: + for index in range(len(s) // 2): + s[index], s[len(s) - index - 1] = s[len(s) - index - 1], s[index] diff --git a/python/reverse_bits.py b/python/reverse_bits.py new file mode 100644 index 0000000..ad24511 --- /dev/null +++ b/python/reverse_bits.py @@ -0,0 +1,7 @@ +class Solution: + def reverseBits(self, n: int) -> int: + binary_str = bin(n)[2:] + binary_str = '0' * (32 - len(binary_str)) + binary_str + print(binary_str) + reverse = binary_str[::-1] + return int(reverse, base=2) diff --git a/python/reverse_linked_list.py b/python/reverse_linked_list.py new file mode 100644 index 0000000..eb941f7 --- /dev/null +++ b/python/reverse_linked_list.py @@ -0,0 +1,21 @@ +from typing import Optional + + +# Definition for singly-linked list. +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + + +class Solution: + def reverseList(self, head: ListNode) -> Optional[ListNode]: + if head is None or head.next is None: + return head + a, b, c = head, head.next, head.next.next + a.next = None + while c is not None: + b.next = a + a, b, c = b, c, c.next + b.next = a + return b diff --git a/python/reverse_string_ii.py b/python/reverse_string_ii.py new file mode 100644 index 0000000..abc1a1b --- /dev/null +++ b/python/reverse_string_ii.py @@ -0,0 +1,15 @@ +class Solution: + def reverseStr(self, s: str, k: int) -> str: + result = '' + index = 0 + while index < len(s): + reverse_len = min(k, len(s) - index) + for i in range(index + reverse_len - 1, index - 1, -1): + result += s[i] + index += k + for i in range(index, index + k): + if i >= len(s): + break + result += s[i] + index += k + return result diff --git a/python/reverse_vowels_of_a_string.py b/python/reverse_vowels_of_a_string.py new file mode 100644 index 0000000..c4b19da --- /dev/null +++ b/python/reverse_vowels_of_a_string.py @@ -0,0 +1,34 @@ +import re + + +class Solution: + def __init__(self): + self.vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'} + + def is_vowel(self, character: str) -> bool: + return character in self.vowels + + def index_in_range(self, l: iter, index: int) -> bool: + return 0 <= index < len(l) + + # 2 pointer approach + # def reverseVowels(self, s: str) -> str: + # characters = [character for character in s] + # left, right = 0, len(characters) - 1 + # while left < right: + # while left < right and not self.is_vowel(s[left]): + # left += 1 + # while left < right and not self.is_vowel(s[right]): + # right -= 1 + # if left < right: + # characters[left], characters[right] = characters[right], characters[left] + # left += 1 + # right -= 1 + # return ''.join(characters) + + # faster method + def reverseVowels(self, s): + vowels = re.findall('(?i)[aeiou]', s) + return re.sub('(?i)[aeiou]', lambda m: vowels.pop(), s) + +print(Solution().reverseVowels('aA')) diff --git a/python/reverse_words_in_string_iii.py b/python/reverse_words_in_string_iii.py new file mode 100644 index 0000000..a73d252 --- /dev/null +++ b/python/reverse_words_in_string_iii.py @@ -0,0 +1,6 @@ +class Solution: + def reverseWords(self, s: str) -> str: + result = '' + for word in s.split(): + result += word[::-1] + ' ' + return result[:-1] diff --git a/python/robot_return_to_origin.py b/python/robot_return_to_origin.py new file mode 100644 index 0000000..8c111be --- /dev/null +++ b/python/robot_return_to_origin.py @@ -0,0 +1,9 @@ +class Solution: + def judgeCircle(self, moves: str) -> bool: + vertical, horizontal = 0, 0 + for move in moves: + if move == 'U': vertical += 1 + elif move == 'D': vertical -= 1 + elif move == 'R': horizontal += 1 + elif move == 'L': horizontal -= 1 + return vertical == 0 and horizontal == 0 diff --git a/python/rotate_array.py b/python/rotate_array.py new file mode 100644 index 0000000..0ecd64e --- /dev/null +++ b/python/rotate_array.py @@ -0,0 +1,31 @@ +from typing import List + + +class Solution: + def rotate(self, nums: List[int], k: int) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + k %= len(nums) + if k == 0: + return + temp = nums[-k:] + for i in range(len(nums) - 1, k - 1, -1): + nums[i] = nums[i - k] + for i, val in enumerate(temp): + nums[i] = val + + def reverse(self, A, i, j): + while i < j: + A[i], A[j] = A[j], A[i] + i += 1 + j -= 1 + + # this is method no. 2 to solve it with O(1) space complexity + def rotate_2(self, A, k): + L = len(A) + k %= L + if k: + self.reverse(A, 0, L - 1) + self.reverse(A, 0, k - 1) + self.reverse(A, k, L - 1) diff --git a/python/same_tree.py b/python/same_tree.py new file mode 100644 index 0000000..fd3a398 --- /dev/null +++ b/python/same_tree.py @@ -0,0 +1,13 @@ +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: + if p is None or q is None: + return p == q + return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) diff --git a/python/scramble_strings.py b/python/scramble_strings.py new file mode 100644 index 0000000..35046e5 --- /dev/null +++ b/python/scramble_strings.py @@ -0,0 +1,46 @@ +# https://leetcode.com/problems/scramble-string/description/ +# T: O(n^4) where n is the number of characters in the string +# S: O(n^3) where n is the number of characters in the string + +from collections import defaultdict + +class Solution: + def isScramble(self, s1: str, s2: str) -> bool: + cache = dict() + return self.helper(s1, s2, cache) + + def helper(self, s1: str, s2: str, cache: dict) -> bool: + key = (s1,s2) + key_r = (s2,s1) + if key in cache: + return cache[key] + if key_r in cache: + return cache[key_r] + # If not cached + n = len(s1) + # Base case + if sorted(s1) != sorted(s2): + cache[key] = False + return False + if n <= 3: + cache[key] = True + return True + # split sting for comparision + count_s1 = defaultdict(int) + count_s2 = defaultdict(int) + count_s2_r = defaultdict(int) + + for i in range(1, n): + count_s1[s1[i-1]] += 1 + count_s2[s2[i-1]] += 1 + count_s2_r[s2[-i]] += 1 + + if count_s1 == count_s2: + cache[key] = self.helper(s1[0:i], s2[0:i], cache) and self.helper(s1[i:n], s2[i:n], cache) + if cache[key]: + return True + if count_s1 == count_s2_r: + cache[key] = self.helper(s1[0:i], s2[n-i:n], cache) and self.helper(s1[i:n], s2[0:n-i], cache) + if cache[key]: + return True + return False diff --git a/python/search_in_binary_search_tree.py b/python/search_in_binary_search_tree.py new file mode 100644 index 0000000..288ba8f --- /dev/null +++ b/python/search_in_binary_search_tree.py @@ -0,0 +1,15 @@ +# Definition for a binary tree node. +from typing import Optional + + +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: + if root is None or root.val == val: return root + return self.searchBST(root.right, val) if root.val < val else self.searchBST(root.left, val) diff --git a/python/second_minimum_node_in_binary_tree.py b/python/second_minimum_node_in_binary_tree.py new file mode 100644 index 0000000..242fcfc --- /dev/null +++ b/python/second_minimum_node_in_binary_tree.py @@ -0,0 +1,30 @@ +from heapq import heappop, heappush + +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def addNodesToSet(self, root: TreeNode, elements: set) -> None: + if root is None: return + elements.add(root.val) + self.addNodesToSet(root.left, elements) + self.addNodesToSet(root.right, elements) + + def unique_elements(self, root: TreeNode) -> set: + elements = set() + self.addNodesToSet(root, elements) + return elements + + def findSecondMinimumValue(self, root: TreeNode) -> int: + elements = self.unique_elements(root) + if len(elements) < 2: return -1 + heap = [] + for element in elements: + heappush(heap, element) + heappop(heap) + return heappop(heap) diff --git a/python/self_dividing_number.py b/python/self_dividing_number.py new file mode 100644 index 0000000..ca3eec6 --- /dev/null +++ b/python/self_dividing_number.py @@ -0,0 +1,17 @@ +from typing import List + + +class Solution: + def isSelfDividing(self, number: int) -> bool: + for digit in str(number): + digit = int(digit) + if digit == 0 or number % digit != 0: + return False + return True + + def selfDividingNumbers(self, left: int, right: int) -> List[int]: + result = [] + for number in range(left, right + 1): + if self.isSelfDividing(number): + result.append(number) + return result diff --git a/python/set_mismatch.py b/python/set_mismatch.py new file mode 100644 index 0000000..01b60dc --- /dev/null +++ b/python/set_mismatch.py @@ -0,0 +1,14 @@ +from typing import List + + +class Solution: + def findErrorNums(self, nums: List[int]) -> List[int]: + repeated, missing = 0, 0 + for number in nums: + if nums[abs(number) - 1] < 0: repeated = number + else: nums[abs(number) - 1] *= -1 + for index in range(len(nums)): + if nums[index] > 0: + missing = index + 1 + break + return [abs(repeated), missing] diff --git a/python/shortest_completing_word.py b/python/shortest_completing_word.py new file mode 100644 index 0000000..273670d --- /dev/null +++ b/python/shortest_completing_word.py @@ -0,0 +1,31 @@ +from typing import List + + +class Solution: + def __init__(self): + self.primes = [ + 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, + 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101 + ] + + def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str: + licenseHash = self.getHash(licensePlate) + resultIndex, shortestLen = -1, float('inf') + for index, word in enumerate(words): + if len(word) < shortestLen and self.coversAllChars(word, licenseHash): + resultIndex = index + shortestLen = len(word) + return words[resultIndex] + + def getHash(self, string: str) -> int: + result = 1 + for char in string.lower(): + if char.isalpha(): + result *= self.primes[ord(char) - ord('a')] + return result + + def coversAllChars(self, word: str, hash: int) -> bool: + result = 1 + for character in word: + result = (result * self.primes[ord(character) - ord('a')]) % hash + return result == 0 diff --git a/python/shortest_continuous_unsorted_subarray.py b/python/shortest_continuous_unsorted_subarray.py new file mode 100644 index 0000000..d8dc001 --- /dev/null +++ b/python/shortest_continuous_unsorted_subarray.py @@ -0,0 +1,12 @@ +from typing import List + + +class Solution: + def findUnsortedSubarray(self, array: List[int]) -> int: + l, r, maximum, minimum = len(array), 0, array[0], array[-1] + for index, value in enumerate(array): + if value < maximum: r = index + 1 + else: maximum = value + if array[len(array) - index - 1] > minimum: l = len(array) - 2 - index + else: minimum = array[len(array) - index - 1] + return max(0, r - l - 1) diff --git a/python/single_number.py b/python/single_number.py new file mode 100644 index 0000000..e8044b2 --- /dev/null +++ b/python/single_number.py @@ -0,0 +1,9 @@ +from typing import List + + +class Solution: + def singleNumber(self, nums: List[int]) -> int: + val = 0 + for number in nums: + val ^= number + return val diff --git a/python/sqrt.py b/python/sqrt.py new file mode 100644 index 0000000..43bbc95 --- /dev/null +++ b/python/sqrt.py @@ -0,0 +1,32 @@ +def mySqrt(x: int) -> int: + left, right, ans = 0, x, 0 + while left <= right: + middle = left + (right - left) // 2 + result = middle ** 2 + if result == x: + return middle + elif result > x: + right = middle - 1 + else: + ans = middle + left = middle + 1 + return ans + + +# faster method, herons formula approach +def heron_approximation(x: int) -> int: + if x is 0 or x is 1: + return x + guess = x / 2 + epsilon = 10 ** -4 + while True: + new_guess = 0.5 * (guess + x / guess) + if abs(guess - new_guess) < epsilon: + return int(guess) + guess = new_guess + + +# print(mySqrt(int(8))) + +for i in range(50): + print(f'sqrt({i})={mySqrt(i)}') diff --git a/python/string_compression.py b/python/string_compression.py new file mode 100644 index 0000000..aea332e --- /dev/null +++ b/python/string_compression.py @@ -0,0 +1,27 @@ +from typing import List +from collections import deque + + +class Solution: + def compress(self, chars: List[str]) -> int: + compressed_strings = deque() + current_char, count,length = chars[0], 0, 0 + for character in chars: + if character == current_char: + count += 1 + else: + compressed_strings.append((current_char, str(count))) + length += 1 + (len(str(count)) if count > 1 else 0) + current_char = character + count = 1 + compressed_strings.append((current_char, str(count))) + length += 1 + (len(str(count)) if count > 1 else 0) + + i = 0 + for compressed_string in compressed_strings: + character, count = compressed_string + chars[i] = character + if int(count) > 1: + chars[i + 1:i + 1 + len(count)] = count + i += 1 + (len(count) if int(count) > 1 else 0) + return length diff --git a/python/student_attendance_record_I.py b/python/student_attendance_record_I.py new file mode 100644 index 0000000..12f7a87 --- /dev/null +++ b/python/student_attendance_record_I.py @@ -0,0 +1,11 @@ +class Solution: + def checkRecord(self, s: str) -> bool: + consecutiveLate, absent = 0, 0 + for character in s: + if character == 'L': + consecutiveLate += 1 + else: + if character == 'A': absent += 1 + consecutiveLate = 0 + if consecutiveLate >= 3 or absent >= 2: return False + return True diff --git a/python/subtree_of_another_tree.py b/python/subtree_of_another_tree.py new file mode 100644 index 0000000..0c48fef --- /dev/null +++ b/python/subtree_of_another_tree.py @@ -0,0 +1,18 @@ +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def areSame(self, root1: TreeNode, root2: TreeNode) -> bool: + if root1 is None and root2 is None: return True + if root1 is None or root2 is None: return False + return root1.val == root2.val and self.areSame(root1.left, root2.left) and self.areSame(root1.right, root2.right) + + def isSubtree(self, root: TreeNode, subRoot: TreeNode) -> bool: + if root is None: return False + if root.val == subRoot.val and self.areSame(root, subRoot): return True + return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot) diff --git a/python/successfull_pairs_of_spells_and_potions.py b/python/successfull_pairs_of_spells_and_potions.py new file mode 100644 index 0000000..fd5ad16 --- /dev/null +++ b/python/successfull_pairs_of_spells_and_potions.py @@ -0,0 +1,8 @@ +# https://leetcode.com/problems/successful-pairs-of-spells-and-potions/editorial/ +# T: O((n + m)logm) where n is the number of spells and m is the number of potions +# S: O(m) where m is the number of potions + +class Solution: + def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: + potions.sort() + return [len(potions) - bisect_left(potions, (success + x - 1) // x) for x in spells] diff --git a/python/sum_of_left_leaves.py b/python/sum_of_left_leaves.py new file mode 100644 index 0000000..d504ec7 --- /dev/null +++ b/python/sum_of_left_leaves.py @@ -0,0 +1,21 @@ +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def is_leaf_node(self, root: TreeNode) -> bool: + return root.left is None and root.right is None + + def sum_left_leaves(self, root: TreeNode, is_left_branch: bool) -> int: + if root is None: + return 0 + if self.is_leaf_node(root) and is_left_branch: + return root.val + return self.sum_left_leaves(root.left, is_left_branch=True) + self.sum_left_leaves(root.right, is_left_branch=False) + + def sumOfLeftLeaves(self, root: TreeNode) -> int: + return self.sum_left_leaves(root, is_left_branch=False) diff --git a/python/sum_of_squares_numbers.py b/python/sum_of_squares_numbers.py new file mode 100644 index 0000000..5a66c95 --- /dev/null +++ b/python/sum_of_squares_numbers.py @@ -0,0 +1,12 @@ +class Solution: + def judgeSquareSum(self, c: int) -> bool: + i = 2 + while i * i <= c: + if c % i == 0: + count = 0 + while c % i == 0: + count += 1 + c //= i + if i % 4 == 3 and count % 2 == 1: return False + i += 1 + return c % 4 != 3 diff --git a/python/summary_ranges.py b/python/summary_ranges.py new file mode 100644 index 0000000..9adb1c9 --- /dev/null +++ b/python/summary_ranges.py @@ -0,0 +1,18 @@ +from typing import List + + +class Solution: + def getRangeString(self, start: int, end: int) -> str: + return f'{start}' if start == end else f'{start}->{end}' + + def summaryRanges(self, array: List[int]) -> List[str]: + if len(array) == 0: return [] + result = [] + startIndex, index = 0, 1 + while index < len(array): + if array[index] > array[startIndex] + (index - startIndex): + result.append(self.getRangeString(array[startIndex], array[index - 1])) + startIndex = index + index += 1 + result.append(self.getRangeString(array[startIndex], array[len(array) - 1])) + return result diff --git a/python/symmetric_tree.py b/python/symmetric_tree.py new file mode 100644 index 0000000..5e20b96 --- /dev/null +++ b/python/symmetric_tree.py @@ -0,0 +1,17 @@ +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def is_symmetric(self, left: TreeNode, right: TreeNode) -> bool: + if left and right: + return left.val == right.val and self.is_symmetric(left.left, right.right) \ + and self.is_symmetric(left.right, right.left) + return left == right + + def isSymmetric(self, root: TreeNode) -> bool: + return root is None or self.is_symmetric(root.left, root.right) diff --git a/python/teemo_attacking.py b/python/teemo_attacking.py new file mode 100644 index 0000000..bfdecf5 --- /dev/null +++ b/python/teemo_attacking.py @@ -0,0 +1,15 @@ +from typing import List + + +class Solution: + def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int: + poisonDuration = 0 + index, current = 0, timeSeries[0] - 1 + while index < len(timeSeries): + poisonDuration += duration - (current - timeSeries[index] + 1) + current = max( + timeSeries[index] + duration - 1, + timeSeries[index + 1] - 1 if index < len(timeSeries) - 1 else 0 + ) + index += 1 + return poisonDuration diff --git a/python/the_skyline_problem.py b/python/the_skyline_problem.py new file mode 100644 index 0000000..91e2aad --- /dev/null +++ b/python/the_skyline_problem.py @@ -0,0 +1,29 @@ +# https://leetcode.com/problems/the-skyline-problem/ +# T: O(NlogN) where N is the number of buildings +# S: O(N) where N is the number of buildings + +import bisect + +class Solution: + def getSkyline(self, buildings): + h = [] + for b in buildings: + h.append((b[0], -b[2])) + h.append((b[1], b[2])) + + h.sort() + prev = cur = 0 + m = [0] + res = [] + + for i in h: + if i[1] < 0: + bisect.insort(m, -i[1]) + else: + m.remove(i[1]) + cur = max(m) + if cur != prev: + res.append([i[0], cur]) + prev = cur + + return res diff --git a/python/third_maximum_number.py b/python/third_maximum_number.py new file mode 100644 index 0000000..08ffe53 --- /dev/null +++ b/python/third_maximum_number.py @@ -0,0 +1,15 @@ +from typing import List +import heapq + + +class Solution: + def thirdMax(self, nums: List[int]) -> int: + distinct = set(nums) + if len(distinct) < 3: + return max(distinct) + heap = [] + for number in distinct: + heapq.heappush(heap, -number) + heapq.heappop(heap) + heapq.heappop(heap) + return heapq.heappop(heap) diff --git a/python/to_lower_case.py b/python/to_lower_case.py new file mode 100644 index 0000000..235db06 --- /dev/null +++ b/python/to_lower_case.py @@ -0,0 +1,15 @@ +class Solution: + def isAlphabet(self, character: str) -> bool: + return self.isUpperCase(character) or self.isLowerCase(character) + + def isUpperCase(self, character: str) -> bool: + return 65 <= ord(character) <= 90 + + def isLowerCase(self, character: str) -> bool: + return 97 <= ord(character) <= 122 + + def toLowerCase(self, s: str) -> str: + result = '' + for character in s: + result += chr(ord(character) + 32) if self.isAlphabet(character) and self.isUpperCase(character) else character + return result diff --git a/python/toeplitz_matrix.py b/python/toeplitz_matrix.py new file mode 100644 index 0000000..c227ca9 --- /dev/null +++ b/python/toeplitz_matrix.py @@ -0,0 +1,21 @@ +from typing import List + + +class Solution: + def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: + columns, rows = len(matrix[0]), len(matrix) + for column in range(columns - 1): + current = matrix[0][column] + for row in range(1, rows): + if column + row >= columns: + break + if matrix[row][column + row] != current: + return False + for row in range(1, rows - 1): + current = matrix[row][0] + for column in range(1, columns): + if row + column >= rows: + break + if matrix[row + column][column] != current: + return False + return True diff --git a/python/trie.py b/python/trie.py new file mode 100644 index 0000000..ef9b4ed --- /dev/null +++ b/python/trie.py @@ -0,0 +1,38 @@ +# https://leetcode.com/problems/implement-trie-prefix-tree/ +# T: O(N) where N is the length of the word +# S: O(MN) where M is the number of words, N is the maximum length of the word + +class TrieNode: + def __init__(self): + self.children = {} + self.is_word = False + +class Trie: + + def __init__(self): + self.root = TrieNode() + + def insert(self, word: str) -> None: + node = self.root + for char in word: + if char not in node.children: + node.children[char] = TrieNode() + node = node.children[char] + node.is_word = True + + def search(self, word: str) -> bool: + node = self.root + for char in word: + if char not in node.children: + return False + node = node.children[char] + return node.is_word + + + def startsWith(self, prefix: str) -> bool: + node = self.root + for char in prefix: + if char not in node.children: + return False + node = node.children[char] + return True diff --git a/python/trim_a_binary_search_tree.py b/python/trim_a_binary_search_tree.py new file mode 100644 index 0000000..d205d52 --- /dev/null +++ b/python/trim_a_binary_search_tree.py @@ -0,0 +1,16 @@ +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode: + if root is None: return None + if root.val < low: return self.trimBST(root.right, low, high) + if root.val > high: return self.trimBST(root.left, low, high) + root.left = self.trimBST(root.left, low, high) + root.right = self.trimBST(root.right, low, high) + return root diff --git a/python/two_sum.py b/python/two_sum.py index 3d229e4..31ff6da 100644 --- a/python/two_sum.py +++ b/python/two_sum.py @@ -6,14 +6,9 @@ def twoSum(self, nums: List[int], target: int) -> List[int]: # saving indices in a map for every corresponding number positions_map = {} for index, number in enumerate(nums): - positions = positions_map.get(number, []) - positions.append(index) - positions_map[number] = positions + positions_map[number] = index for index, number in enumerate(nums): required = target - number - if required in positions_map: - positions = positions_map[required] - for i in positions: - if i != index: - return [index, i] + if required in positions_map and positions_map[required] != index: + return [index, positions_map[required]] diff --git a/python/two_sum_ii.py b/python/two_sum_ii.py new file mode 100644 index 0000000..55f34c3 --- /dev/null +++ b/python/two_sum_ii.py @@ -0,0 +1,13 @@ +from typing import List + + +class Solution: + def twoSum(self, numbers: List[int], target: int) -> List[int]: + left, right = 0, len(numbers) - 1 + while left < right: + if numbers[left] + numbers[right] == target: + return [left + 1, right + 1] + elif numbers[left] + numbers[right] < target: + left += 1 + else: + right -= 1 diff --git a/python/two_sum_iv.py b/python/two_sum_iv.py new file mode 100644 index 0000000..69769ed --- /dev/null +++ b/python/two_sum_iv.py @@ -0,0 +1,17 @@ +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +class Solution: + def __init__(self): + self.elements = set() + + def findTarget(self, root: TreeNode, k: int) -> bool: + if root is None: return False + if k - root.val in self.elements: return True + self.elements.add(root.val) + return self.findTarget(root.left, k) or self.findTarget(root.right, k) diff --git a/python/ugly_number.py b/python/ugly_number.py new file mode 100644 index 0000000..9c73f46 --- /dev/null +++ b/python/ugly_number.py @@ -0,0 +1,11 @@ +class Solution: + def eliminate_prime_factor(self, number: int, prime_factor: int) -> int: + while number % prime_factor == 0 and number != 0: + number //= prime_factor + return number + + def isUgly(self, n: int) -> bool: + n = self.eliminate_prime_factor(n, 2) + n = self.eliminate_prime_factor(n, 3) + n = self.eliminate_prime_factor(n, 5) + return n == 1 diff --git a/python/valid_anagram.py b/python/valid_anagram.py new file mode 100644 index 0000000..9236cd9 --- /dev/null +++ b/python/valid_anagram.py @@ -0,0 +1,16 @@ +from typing import Dict + + +class Solution: + def character_frequency(self, string: str) -> Dict[str, int]: + frequencies = {} + for character in string: + frequencies[character] = frequencies.get(character, 0) + 1 + return frequencies + + def isAnagram(self, s: str, t: str) -> bool: + if len(s) != len(t): + return False + char_freq_s = self.character_frequency(s) + char_freq_t = self.character_frequency(t) + return char_freq_s == char_freq_t diff --git a/python/valid_mountain_array.py b/python/valid_mountain_array.py new file mode 100644 index 0000000..e51a26a --- /dev/null +++ b/python/valid_mountain_array.py @@ -0,0 +1,16 @@ +from typing import List + + +class Solution: + def validMountainArray(self, numbers: List[int]) -> bool: + isIncreasing = True + index = 1 + while index < len(numbers): + if numbers[index] == numbers[index - 1]: return False + if numbers[index] < numbers[index - 1] and isIncreasing: + if index == 1: return False + isIncreasing = False + if numbers[index] > numbers[index - 1] and not isIncreasing: + return False + index += 1 + return not isIncreasing diff --git a/python/valid_palindrome.py b/python/valid_palindrome.py new file mode 100644 index 0000000..cd365e6 --- /dev/null +++ b/python/valid_palindrome.py @@ -0,0 +1,10 @@ +import string + + +class Solution: + def isPalindrome(self, s: str) -> bool: + for x in string.punctuation: + s = s.replace(x, '') + + s = s.replace(' ', '').lower() + return s == s[::-1] diff --git a/python/valid_pallindrome_ii.py b/python/valid_pallindrome_ii.py new file mode 100644 index 0000000..d6df738 --- /dev/null +++ b/python/valid_pallindrome_ii.py @@ -0,0 +1,17 @@ +class Solution: + def isPalindrome(self, s: str, left: int, right: int) -> bool: + while left < right: + if s[left] != s[right]: return False + left += 1 + right -= 1 + return True + + def validPalindrome(self, s: str) -> bool: + left, right = 0, len(s) - 1 + while left < right: + if s[left] != s[right]: + if self.isPalindrome(s, left + 1, right): return True + return self.isPalindrome(s, left, right - 1) + left += 1 + right -= 1 + return True \ No newline at end of file diff --git a/python/valid_perfect_square.py b/python/valid_perfect_square.py new file mode 100644 index 0000000..9097a9f --- /dev/null +++ b/python/valid_perfect_square.py @@ -0,0 +1,24 @@ +class Solution: + # binary search method + def isPerfectSquare(self, number: int) -> bool: + if number == 1: + return True + left, right = 0, number // 2 + while left <= right: + middle = (left + right) // 2 + mid_square = middle * middle + if mid_square == number: + return True + elif mid_square < number: + left = middle + 1 + else: + right = middle - 1 + return False + + # Newton's Method + # def isPerfectSquare(self, number: int) -> bool: + # r = number + # while r * r > number: + # r = (r + number / r) // 2 + # return r * r == number + diff --git a/python/word_pattern.py b/python/word_pattern.py new file mode 100644 index 0000000..cabfaf2 --- /dev/null +++ b/python/word_pattern.py @@ -0,0 +1,20 @@ +class Solution: + def wordPattern(self, pattern: str, s: str) -> bool: + words = s.split() + if len(words) != len(pattern): + return False + mapping = {} + used_words = set() + for character, word in zip(pattern, words): + if character in mapping: + if mapping[character] != word: + return False + elif word in used_words: + return False + else: + mapping[character] = word + used_words.add(word) + return True + + +print(Solution().wordPattern('abba', 'dog dog dog dog')) diff --git a/src/ANumberAfterADoubleReversal.java b/src/ANumberAfterADoubleReversal.java new file mode 100644 index 0000000..830cd56 --- /dev/null +++ b/src/ANumberAfterADoubleReversal.java @@ -0,0 +1,10 @@ +// https://leetcode.com/problems/a-number-after-a-double-reversal +// T: O(1) +// S: O(1) + +public class ANumberAfterADoubleReversal { + public boolean isSameAfterReversals(int num) { + if (num == 0) return true; + return num % 10 != 0; + } +} diff --git a/src/AccountBalanceAfterRoundedPurchase.java b/src/AccountBalanceAfterRoundedPurchase.java new file mode 100644 index 0000000..f8fd19e --- /dev/null +++ b/src/AccountBalanceAfterRoundedPurchase.java @@ -0,0 +1,10 @@ +// https://leetcode.com/problems/account-balance-after-rounded-purchase +// T: O(1) +// S: O(1) + +public class AccountBalanceAfterRoundedPurchase { + public int accountBalanceAfterPurchase(int purchaseAmount) { + final int purchaseAmountRounded = (int) (Math.round(purchaseAmount / 10.0) * 10); + return 100 - purchaseAmountRounded; + } +} diff --git a/src/AddToArrayFormOfInteger.java b/src/AddToArrayFormOfInteger.java new file mode 100644 index 0000000..b571ec8 --- /dev/null +++ b/src/AddToArrayFormOfInteger.java @@ -0,0 +1,22 @@ +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class AddToArrayFormOfInteger { + public List addToArrayForm(int[] num, int k) { + List result = new ArrayList<>(); + int sum; + for (int i = num.length - 1, carry = 0 ; i >= 0 || carry > 0 || k > 0 ; i--, k /= 10) { + sum = get(num, i) + carry + k % 10; + result.add(sum % 10); + carry = sum / 10; + } + Collections.reverse(result); + return result; + } + + private int get(int[] array, int index) { + if (index < 0) return 0; + return array[index]; + } +} diff --git a/src/AddTwoIntegers.java b/src/AddTwoIntegers.java new file mode 100644 index 0000000..db38d42 --- /dev/null +++ b/src/AddTwoIntegers.java @@ -0,0 +1,9 @@ +// https://leetcode.com/problems/add-two-integers +// T: O(1) +// S: O(1) + +public class AddTwoIntegers { + public int sum(int num1, int num2) { + return num1 + num2; + } +} diff --git a/src/AddTwoNumbers.java b/src/AddTwoNumbers.java new file mode 100644 index 0000000..d2d7661 --- /dev/null +++ b/src/AddTwoNumbers.java @@ -0,0 +1,36 @@ +// https://leetcode.com/problems/add-two-numbers +// T: O(max(|l1|, |l2|)) +// S: O(max(|l1|, |l2|)) + +public class AddTwoNumbers { + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { + ListNode result = new ListNode(); + ListNode current = result; + int carry = 0; + + while (l1 != null || l2 != null) { + current.next = new ListNode(); + current = current.next; + int sum = get(l1) + get(l2) + carry; + current.val = sum % 10; + carry = sum / 10; + l1 = next(l1); + l2 = next(l2); + } + if (carry > 0) { + current.next = new ListNode(carry); + } + + return result.next; + } + + private ListNode next(ListNode node) { + if (node == null) return null; + return node.next; + } + + private int get(ListNode node) { + if (node == null) return 0; + return node.val; + } +} diff --git a/src/AlienDictionary.java b/src/AlienDictionary.java new file mode 100644 index 0000000..9090889 --- /dev/null +++ b/src/AlienDictionary.java @@ -0,0 +1,68 @@ +// https://leetcode.com/problems/alien-dictionary +// C = length of all words added together +// T: O(C) +// S: O(1) + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Queue; + +public class AlienDictionary { + public String alienOrder(String[] words) { + + // Step 0: Create data structures and find all unique letters. + Map> adjList = new HashMap<>(); + Map counts = new HashMap<>(); + for (String word : words) { + for (char c : word.toCharArray()) { + counts.put(c, 0); + adjList.put(c, new ArrayList<>()); + } + } + + // Step 1: Find all edges. + for (int i = 0; i < words.length - 1; i++) { + String word1 = words[i]; + String word2 = words[i + 1]; + // Check that word2 is not a prefix of word1. + if (word1.length() > word2.length() && word1.startsWith(word2)) { + return ""; + } + // Find the first non match and insert the corresponding relation. + for (int j = 0; j < Math.min(word1.length(), word2.length()); j++) { + if (word1.charAt(j) != word2.charAt(j)) { + adjList.get(word1.charAt(j)).add(word2.charAt(j)); + counts.put(word2.charAt(j), counts.get(word2.charAt(j)) + 1); + break; + } + } + } + + // Step 2: Breadth-first search. + StringBuilder sb = new StringBuilder(); + Queue queue = new LinkedList<>(); + for (Character c : counts.keySet()) { + if (counts.get(c).equals(0)) { + queue.add(c); + } + } + while (!queue.isEmpty()) { + Character c = queue.remove(); + sb.append(c); + for (Character next : adjList.get(c)) { + counts.put(next, counts.get(next) - 1); + if (counts.get(next).equals(0)) { + queue.add(next); + } + } + } + + if (sb.length() < counts.size()) { + return ""; + } + return sb.toString(); + } +} diff --git a/src/AllPathsFromSourceLeadToDestination.java b/src/AllPathsFromSourceLeadToDestination.java new file mode 100644 index 0000000..82dd89f --- /dev/null +++ b/src/AllPathsFromSourceLeadToDestination.java @@ -0,0 +1,53 @@ +// https://leetcode.com/problems/all-paths-from-source-lead-to-destination +// T: O(V + E) +// S: O(V) + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class AllPathsFromSourceLeadToDestination { + // We don't use the state WHITE as such anywhere. Instead, the "null" value in the states array below is a substitute for WHITE. + enum Color { GRAY, BLACK }; + + public boolean leadsToDestination(int n, int[][] edges, int source, int destination) { + Map> graph = buildGraph(edges); + return leadsToDestination(graph, source, destination, new Color[n]); + } + + private boolean leadsToDestination(Map> graph, int node, int target, Color[] states) { + // If the state is GRAY, this is a backward edge and hence, it creates a loop. + if (states[node] != null) { + return states[node] == Color.BLACK; + } + + // If this is a leaf node, it should be equal to the destination. + if (!graph.containsKey(node)) { + return node == target; + } + + // Now, we are processing this node. So we mark it as GRAY + states[node] = Color.GRAY; + + for (int next : graph.get(node)) { + if (!leadsToDestination(graph, next, target, states)) { + return false; + } + } + + states[node] = Color.BLACK; + return true; + } + + private Map> buildGraph(int[][] edges) { + final Map> graph = new HashMap<>(); + for (int[] edge : edges) { + final int from = edge[0], to = edge[1]; + final Set neighbours = graph.getOrDefault(from, new HashSet<>()); + neighbours.add(to); + graph.putIfAbsent(from, neighbours); + } + return graph; + } +} diff --git a/src/AllPathsFromSourceToTarget.java b/src/AllPathsFromSourceToTarget.java new file mode 100644 index 0000000..f970fea --- /dev/null +++ b/src/AllPathsFromSourceToTarget.java @@ -0,0 +1,28 @@ +// https://leetcode.com/problems/all-paths-from-source-to-target +// maximum edges for DAG = V-1, possible paths = 2^(V-1), for every path we clone path O(V) +// T: O(2^V * V) +// S: O(V) + +import java.util.ArrayList; +import java.util.List; + +public class AllPathsFromSourceToTarget { + public List> allPathsSourceTarget(int[][] graph) { + final List> result = new ArrayList<>(); + final int n = graph.length; + dfs(graph, 0, n - 1, new ArrayList<>() {{ add(0); }}, result); + return result; + } + + private static void dfs(int[][] graph, int current, int target, List path, List> result) { + if (current == target) { + result.add(new ArrayList<>(path)); + return; + } + for (int edge : graph[current]) { + path.add(edge); + dfs(graph, edge, target, path, result); + path.removeLast(); + } + } +} diff --git a/src/AlternatingDigitSum.java b/src/AlternatingDigitSum.java new file mode 100644 index 0000000..45c4ec5 --- /dev/null +++ b/src/AlternatingDigitSum.java @@ -0,0 +1,14 @@ +// https://leetcode.com/problems/alternating-digit-sum +// T: O(log(n)) +// S: O(1) + +public class AlternatingDigitSum { + public int alternateDigitSum(int n) { + final String number = n + ""; + int sum = 0; + for (int index = 0, parity = 1 ; index < number.length() ; index++, parity *= -1) { + sum += parity * (number.charAt(index) - '0'); + } + return sum; + } +} diff --git a/src/AlternatingGroupsI.java b/src/AlternatingGroupsI.java new file mode 100644 index 0000000..af13e71 --- /dev/null +++ b/src/AlternatingGroupsI.java @@ -0,0 +1,19 @@ +// https://leetcode.com/problems/alternating-groups-i +// T: O(N) +// S: O(1) + +public class AlternatingGroupsI { + public int numberOfAlternatingGroups(int[] colors) { + int groups = 0; + for (int i = 0 ; i < colors.length ; i++) { + if (isAlternating(colors, i)) { + groups++; + } + } + return groups; + } + private static boolean isAlternating(int[] colors, int startIndex) { + return colors[startIndex] == colors[(startIndex + 2) % colors.length] && + colors[startIndex] != colors[(startIndex + 1) % colors.length]; + } +} diff --git a/src/AntOnTheBoundary.java b/src/AntOnTheBoundary.java new file mode 100644 index 0000000..0920f7c --- /dev/null +++ b/src/AntOnTheBoundary.java @@ -0,0 +1,16 @@ +// https://leetcode.com/problems/ant-on-the-boundary +// T: O(N) +// S: O(1) + +public class AntOnTheBoundary { + public int returnToBoundaryCount(int[] array) { + int onTheBoundary = 0, distance = 0; + for (int element : array) { + distance += element; + if (distance == 0) { + onTheBoundary++; + } + } + return onTheBoundary; + } +} diff --git a/src/AppleRedistributionIntoBoxes.java b/src/AppleRedistributionIntoBoxes.java new file mode 100644 index 0000000..ebb707c --- /dev/null +++ b/src/AppleRedistributionIntoBoxes.java @@ -0,0 +1,23 @@ +// https://leetcode.com/problems/apple-redistribution-into-boxes +// N = |apples|, M = |capacity| +// T: O(N + M log(M)) +// S: O(log(M)) + +import java.util.Arrays; + +public class AppleRedistributionIntoBoxes { + public int minimumBoxes(int[] apple, int[] capacity) { + int totalApples = Arrays.stream(apple).sum(); + Arrays.sort(capacity); + + int boxesRequired = 0; + for (int i = capacity.length - 1 ; i >= 0 ; i--) { + if (totalApples <= 0) { + break; + } + totalApples -= capacity[i]; + boxesRequired++; + } + return boxesRequired; + } +} diff --git a/src/ApplyOperationsToAnArray.java b/src/ApplyOperationsToAnArray.java new file mode 100644 index 0000000..5b73b7f --- /dev/null +++ b/src/ApplyOperationsToAnArray.java @@ -0,0 +1,31 @@ +// https://leetcode.com/problems/apply-operations-to-an-array +// T: O(N) +// S: O(N) + +public class ApplyOperationsToAnArray { + public int[] applyOperations(int[] array) { + final int[] result = new int[array.length]; + int j = 0; + for (int i = 0, previous = array[0] ; i < array.length - 1 ; i++) { + if (previous == 0) { + previous = array[i + 1]; + continue; + } + + if (previous == array[i + 1]) { + result[j++] = 2 * array[i]; + previous = 0; + continue; + } + + result[j++] = array[i]; + previous = array[i + 1]; + } + + if (array[array.length - 2] != array[array.length - 1]) { + result[j] = array[array.length - 1]; + } + + return result; + } +} diff --git a/src/ArrayPartitionI.java b/src/ArrayPartitionI.java new file mode 100644 index 0000000..d4506a9 --- /dev/null +++ b/src/ArrayPartitionI.java @@ -0,0 +1,12 @@ +import java.util.Arrays; + +public class ArrayPartitionI { + public int arrayPairSum(int[] nums) { + Arrays.sort(nums); + int result = 0; + for (int index = 0 ; index < nums.length ; index += 2) { + result += Math.min(nums[index], nums[index + 1]); + } + return result; + } +} diff --git a/src/AvailableCapturesForRook.java b/src/AvailableCapturesForRook.java new file mode 100644 index 0000000..a5142c1 --- /dev/null +++ b/src/AvailableCapturesForRook.java @@ -0,0 +1,64 @@ +public class AvailableCapturesForRook { + private static final class Position { + private final int row; + private final int column; + + private Position(int row, int column) { + this.row = row; + this.column = column; + } + } + + private static final char ROOK = 'R'; + private static final char BISHOP = 'B'; + private static final char PAWN = 'p'; + + public int numRookCaptures(char[][] board) { + Position rookPosition = getPosition(board, ROOK); + return (canCapturePawnInNorth(board, rookPosition) ? 1 : 0) + + (canCapturePawnInWest(board, rookPosition) ? 1 : 0) + + (canCapturePawnInSouth(board, rookPosition) ? 1 : 0) + + (canCapturePawnInEast(board, rookPosition) ? 1 : 0); + } + + private Position getPosition(char[][] board, char piece) { + for (int row = 0 ; row < board.length ; row++) { + for (int column = 0 ; column < board[0].length ; column++) { + if (board[row][column] == piece) return new Position(row, column); + } + } + return null; + } + + private boolean canCapturePawnInNorth(char[][] board, Position rookPosition) { + for (int row = rookPosition.row - 1 ; row >= 0 ; row--) { + if (board[row][rookPosition.column] == BISHOP) return false; + if (board[row][rookPosition.column] == PAWN) return true; + } + return false; + } + + private boolean canCapturePawnInSouth(char[][] board, Position rookPosition) { + for (int row = rookPosition.row + 1 ; row < board.length ; row++) { + if (board[row][rookPosition.column] == BISHOP) return false; + if (board[row][rookPosition.column] == PAWN) return true; + } + return false; + } + + private boolean canCapturePawnInWest(char[][] board, Position rookPosition) { + for (int column = rookPosition.column + 1 ; column < board[0].length ; column++) { + if (board[rookPosition.row][column] == BISHOP) return false; + if (board[rookPosition.row][column] == PAWN) return true; + } + return false; + } + + private boolean canCapturePawnInEast(char[][] board, Position rookPosition) { + for (int column = rookPosition.column - 1 ; column >= 0 ; column--) { + if (board[rookPosition.row][column] == BISHOP) return false; + if (board[rookPosition.row][column] == PAWN) return true; + } + return false; + } +} diff --git a/src/AverageLevelsOfBinaryTree.java b/src/AverageLevelsOfBinaryTree.java new file mode 100644 index 0000000..7b9e70f --- /dev/null +++ b/src/AverageLevelsOfBinaryTree.java @@ -0,0 +1,32 @@ +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + +public class AverageLevelsOfBinaryTree { + public List averageOfLevels(TreeNode root) { + Queue queue = new LinkedList<>(); + queue.add(root); + queue.add(null); + int count = 0; + List result = new ArrayList<>(); + result.add(0.0); + while (!queue.isEmpty()) { + TreeNode current = queue.poll(); + if (current == null && queue.isEmpty()) break; + if (current == null) { + queue.add(null); + result.set(result.size() - 1, result.get(result.size() - 1) / count); + result.add(0.0); + count = 0; + continue; + } + count++; + if (current.left != null) queue.add(current.left); + if (current.right != null) queue.add(current.right); + result.set(result.size() - 1, result.get(result.size() - 1) + current.val); + } + result.set(result.size() - 1, result.get(result.size() - 1) / count); + return result; + } +} diff --git a/src/AverageSalaryExcludingTheMinimumAndMaximumSalary.java b/src/AverageSalaryExcludingTheMinimumAndMaximumSalary.java new file mode 100644 index 0000000..86c8564 --- /dev/null +++ b/src/AverageSalaryExcludingTheMinimumAndMaximumSalary.java @@ -0,0 +1,15 @@ +import java.util.Arrays; +import java.util.Set; + +public class AverageSalaryExcludingTheMinimumAndMaximumSalary { + public double average(int[] salaries) { + final int maxSalary = Arrays.stream(salaries).max().getAsInt(); + final int minSalary = Arrays.stream(salaries).min().getAsInt(); + final Set exclude = Set.of(minSalary, maxSalary); + int sumSalary = 0; + for (int salary : salaries) { + if (!exclude.contains(salary)) sumSalary += salary; + } + return (double) sumSalary / (salaries.length - 2); + } +} diff --git a/src/AverageValueOfEvenNumbersThatAreDivisibleByThree.java b/src/AverageValueOfEvenNumbersThatAreDivisibleByThree.java new file mode 100644 index 0000000..cb3beab --- /dev/null +++ b/src/AverageValueOfEvenNumbersThatAreDivisibleByThree.java @@ -0,0 +1,16 @@ +// https://leetcode.com/problems/average-value-of-even-numbers-that-are-divisible-by-three +// T: O(N) +// S: O(1) + +public class AverageValueOfEvenNumbersThatAreDivisibleByThree { + public int averageValue(int[] array) { + int sum = 0, count = 0; + for (int element : array) { + if (element % 6 == 0) { + sum += element; + count++; + } + } + return count == 0 ? 0 : sum / count; + } +} diff --git a/src/BackspaceStringCompare.java b/src/BackspaceStringCompare.java new file mode 100644 index 0000000..a537593 --- /dev/null +++ b/src/BackspaceStringCompare.java @@ -0,0 +1,23 @@ +public class BackspaceStringCompare { + public boolean backspaceCompare(String s, String t) { + int i = nextCharIndex(s, s.length()), j = nextCharIndex(t, t.length()); + while (i >= 0 && j >= 0) { + if (s.charAt(i) != t.charAt(j)) return false; + i = nextCharIndex(s, i); + j = nextCharIndex(t, j); + } + return i == -1 && j == -1; + } + + private int nextCharIndex(String string, int currentIndex) { + for (int buffer = 0 ; buffer >= 0 ; currentIndex--) { + if (currentIndex == 0) { + currentIndex = -1; + break; + } + if (string.charAt(currentIndex - 1) == '#') buffer++; + else buffer--; + } + return currentIndex; + } +} diff --git a/src/BalancedBinaryTree.java b/src/BalancedBinaryTree.java index 6497146..3d1929f 100644 --- a/src/BalancedBinaryTree.java +++ b/src/BalancedBinaryTree.java @@ -1,9 +1,4 @@ public class BalancedBinaryTree { - private static class TreeNode { - int val; - TreeNode left; - TreeNode right; - } public static boolean isBalanced(TreeNode root) { return height(root) != -1; diff --git a/src/Base7.java b/src/Base7.java new file mode 100644 index 0000000..a0428d6 --- /dev/null +++ b/src/Base7.java @@ -0,0 +1,19 @@ +public class Base7 { + public static String convertToBase7(int number) { + if (number == 0) return "0"; + StringBuilder result = new StringBuilder(); + boolean isNegative = number < 0; + if (isNegative) { + number *= -1; + } + while (number > 0) { + result.append(number % 7); + number /= 7; + } + return result.append(isNegative ? "-" : "").reverse().toString(); + } + + public static void main(String[] args) { + System.out.println(convertToBase7(-7)); + } +} diff --git a/src/BaseballGame.java b/src/BaseballGame.java new file mode 100644 index 0000000..f5a7209 --- /dev/null +++ b/src/BaseballGame.java @@ -0,0 +1,28 @@ +import java.util.LinkedList; +import java.util.List; + +public class BaseballGame { + public int calPoints(String[] ops) { + List queue = new LinkedList<>(); + for (String operation : ops) { + if (operation.equals("+")) { + queue.add(queue.get(queue.size() - 1) + queue.get(queue.size() - 2)); + } else if (operation.equals("D")) { + queue.add(queue.get(queue.size() - 1) * 2); + } else if (operation.equals("C")) { + queue.remove(queue.size() - 1); + } else { + queue.add(Integer.valueOf(operation)); + } + } + return sum(queue); + } + + private int sum(List list) { + int sum = 0; + for (int element : list) { + sum += element; + } + return sum; + } +} diff --git a/src/BasicCalculator.java b/src/BasicCalculator.java new file mode 100644 index 0000000..ea9c270 --- /dev/null +++ b/src/BasicCalculator.java @@ -0,0 +1,38 @@ +import java.util.Stack; + +class BasicCalculator { + public int calculate(String s) { + final Stack stack = new Stack(); + int number = 0; + int result = 0; // For the ongoing result + int sign = 1; // 1 means positive, -1 means negative + + for (int i = 0; i < s.length(); i++) { + final char ch = s.charAt(i); + + if (Character.isDigit(ch)) { + number = 10 * number + (ch - '0'); + } else if (isOperator(ch)) { + result += sign * number; + number = 0; + sign = ch == '+' ? 1 : -1; + } else if (ch == '(') { + stack.push(result); + stack.push(sign); + sign = 1; + result = 0; + } else if (ch == ')') { + result += sign * number; + result *= stack.pop(); + result += stack.pop(); + number = 0; + } + } + + return result + (sign * number); + } + + private static boolean isOperator(char c) { + return c == '+' || c == '-'; + } +} \ No newline at end of file diff --git a/src/BasicCalculatorII.java b/src/BasicCalculatorII.java new file mode 100644 index 0000000..2751f13 --- /dev/null +++ b/src/BasicCalculatorII.java @@ -0,0 +1,88 @@ +// https://leetcode.com/problems/basic-calculator-ii +// extremely innovative approach, using a grammar to evaluate expressions +// T: O(N) +// S: O(1) + +import java.util.Set; + +public class BasicCalculatorII { + private static final char ADDITION = '+'; + private static final char SUBTRACTION = '-'; + private static final char MULTIPLICATION = '*'; + private static final char DIVISION = '/'; + private static final char SPACE = ' '; + + private static final Set ADDITIVE_OPERATORS = Set.of(ADDITION, SUBTRACTION); + private static final Set MULTIPLICATIVE_OPERATORS = Set.of(MULTIPLICATION, DIVISION); + + private String expression; + private int index; + + public int calculate(String s) { + this.expression = s; + this.index = 0; + return addition(); + } + + private int addition() { + int sum = multiplication(); + while (index < expression.length() && isAdditiveOperator(expression.charAt(index))) { + char operator = expression.charAt(index++); + sum = applyOperator(sum, multiplication(), operator); + } + return sum; + } + + private int multiplication() { + int result = toNumber(); + while (index < expression.length() && isMultiplicativeOperator(expression.charAt(index))) { + char operator = expression.charAt(index++); + result = applyOperator(result, toNumber(), operator); + } + return result; + } + + private int toNumber() { + int number = 0; + while (index < expression.length() && isDigitOrSpace(expression.charAt(index))) { + if (isSpace(expression.charAt(index))) { + index++; + continue; + } + number *= 10; + number += toDigit(expression.charAt(index)); + index++; + } + return number; + } + + private int toDigit(char digit) { + return digit - '0'; + } + + private boolean isDigitOrSpace(char c) { + return Character.isDigit(c) || isSpace(c); + } + + private boolean isSpace(char c) { + return c == SPACE; + } + + private int applyOperator(int a, int b, char operator) { + return switch (operator) { + case ADDITION -> a + b; + case SUBTRACTION -> a - b; + case MULTIPLICATION -> a * b; + case DIVISION -> a / b; + default -> throw new IllegalStateException("Unexpected value: " + operator); + }; + } + + private boolean isAdditiveOperator(char operator) { + return ADDITIVE_OPERATORS.contains(operator); + } + + private boolean isMultiplicativeOperator(char operator) { + return MULTIPLICATIVE_OPERATORS.contains(operator); + } +} diff --git a/src/BestPokerHand.java b/src/BestPokerHand.java new file mode 100644 index 0000000..0388bac --- /dev/null +++ b/src/BestPokerHand.java @@ -0,0 +1,42 @@ +// https://leetcode.com/problems/best-poker-hand +// T: O(1) +// S: O(1) + +import java.util.HashMap; +import java.util.Map; + +public class BestPokerHand { + public String bestHand(int[] ranks, char[] suits) { + if (sameSuit(suits)) { + return "Flush"; + } + + final Map frequencies = getFrequencies(ranks); + final int maxFrequency = frequencies.values().stream().max(Integer::compare).get(); + + if (maxFrequency >= 3) { + return "Three of a Kind"; + } + if (maxFrequency == 2) { + return "Pair"; + } + + return "High Card"; + } + + private Map getFrequencies(int[] ranks) { + final Map frequencies = new HashMap<>(); + for (int rank : ranks) { + frequencies.put(rank, frequencies.getOrDefault(rank, 0) + 1); + } + return frequencies; + } + + private boolean sameSuit(char[] suits) { + char first = suits[0]; + for (char suit : suits) { + if (suit != first) return false; + } + return true; + } +} diff --git a/src/BestTimeToBuyAndSellStock.java b/src/BestTimeToBuyAndSellStock.java index e25419b..1e84d42 100644 --- a/src/BestTimeToBuyAndSellStock.java +++ b/src/BestTimeToBuyAndSellStock.java @@ -1,3 +1,7 @@ +// https://leetcode.com/problems/best-time-to-buy-and-sell-stock +// T: O(n) +// S: O(1) + public class BestTimeToBuyAndSellStock { public int maxProfit(int[] prices) { if (prices.length == 0) { diff --git a/src/BinaryGap.java b/src/BinaryGap.java new file mode 100644 index 0000000..cc2502d --- /dev/null +++ b/src/BinaryGap.java @@ -0,0 +1,15 @@ +public class BinaryGap { + public int binaryGap(int n) { + int result = Integer.MIN_VALUE, index = 0, prev = -1; + while (n > 0) { + if ((n & 1) == 1) { + if (prev == -1) prev = index; + result = Math.max(result, index - prev); + prev = index; + } + n >>= 1; + index++; + } + return result; + } +} diff --git a/src/BinaryNumberWithAlternatingBits.java b/src/BinaryNumberWithAlternatingBits.java new file mode 100644 index 0000000..e1098c6 --- /dev/null +++ b/src/BinaryNumberWithAlternatingBits.java @@ -0,0 +1,12 @@ +public class BinaryNumberWithAlternatingBits { + public boolean hasAlternatingBits(int number) { + int lastDigit = number % 2, current; + while (number > 0) { + number >>= 1; + current = number % 2; + if (lastDigit == current) return false; + lastDigit = current; + } + return true; + } +} diff --git a/src/BinaryPrefixDivisibleBy5.java b/src/BinaryPrefixDivisibleBy5.java new file mode 100644 index 0000000..d70c01d --- /dev/null +++ b/src/BinaryPrefixDivisibleBy5.java @@ -0,0 +1,23 @@ +import java.util.ArrayList; +import java.util.List; + +public class BinaryPrefixDivisibleBy5 { + private static final int[][] stateFlow = { + {0, 1}, + {2, 3}, + {4, 0}, + {1, 2}, + {3, 4} + }; + + public List prefixesDivBy5(int[] binaryArray) { + final List result = new ArrayList<>(); + int state = binaryArray[0]; + for (int index = 0 ; index < binaryArray.length - 1 ; index++) { + result.add(state == 0); + state = stateFlow[state][binaryArray[index + 1]]; + } + result.add(state == 0); + return result; + } +} diff --git a/src/BinarySearch.java b/src/BinarySearch.java new file mode 100644 index 0000000..19ddd73 --- /dev/null +++ b/src/BinarySearch.java @@ -0,0 +1,17 @@ +// https://leetcode.com/problems/binary-search +// T: O(logN) +// S: O(1) + +public class BinarySearch { + public int search(int[] array, int val) { + int left = 0, right = array.length - 1, middle; + while (left <= right) { + middle = left + (right - left) / 2; + if (array[middle] == val) return middle; + else if (array[middle] > val) right = middle - 1; + else left = middle + 1; + } + + return -1; + } +} diff --git a/src/BinarySearchTreeIterator.java b/src/BinarySearchTreeIterator.java new file mode 100644 index 0000000..69258cd --- /dev/null +++ b/src/BinarySearchTreeIterator.java @@ -0,0 +1,34 @@ +// https://leetcode.com/problems/binary-search-tree-iterator +// T: O(N) +// T(next): O(1) +// T(hasNext): O(1) +// S: O(log(N)) + +import java.util.Stack; + +public class BinarySearchTreeIterator { + + public static final class BSTIterator { + private final Stack stack = new Stack<>(); + + public BSTIterator(TreeNode root) { + addLeftNodesPathToStack(root); + } + + public int next() { + final TreeNode node = stack.pop(); + addLeftNodesPathToStack(node.right); + return node.val; + } + + public boolean hasNext() { + return !stack.isEmpty(); + } + + private void addLeftNodesPathToStack(TreeNode root) { + if (root == null) return; + stack.push(root); + addLeftNodesPathToStack(root.left); + } + } +} diff --git a/src/BinaryTreeInorderTraversal.java b/src/BinaryTreeInorderTraversal.java new file mode 100644 index 0000000..2b30d4f --- /dev/null +++ b/src/BinaryTreeInorderTraversal.java @@ -0,0 +1,17 @@ +import java.util.ArrayList; +import java.util.List; + +public class BinaryTreeInorderTraversal { + public List inorderTraversal(TreeNode root) { + List result = new ArrayList<>(); + inorderTraversal(root, result); + return result; + } + + private void inorderTraversal(TreeNode root, List list) { + if (root == null) return; + inorderTraversal(root.left, list); + list.add(root.val); + inorderTraversal(root.right, list); + } +} diff --git a/src/BinaryTreeLevelOrderTraversal.java b/src/BinaryTreeLevelOrderTraversal.java new file mode 100644 index 0000000..a6c07f6 --- /dev/null +++ b/src/BinaryTreeLevelOrderTraversal.java @@ -0,0 +1,38 @@ +// https://leetcode.com/problems/binary-tree-level-order-traversal +// T: O(n) +// S: O(n) + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + +public class BinaryTreeLevelOrderTraversal { + public List> levelOrder(TreeNode root) { + if (root == null) { + return List.of(); + } + + final Queue queue = new LinkedList<>(); + queue.add(root); + queue.add(null); + final List> result = new ArrayList<>(); + List level = new ArrayList<>(); + + while (!queue.isEmpty()) { + TreeNode current = queue.poll(); + if (current == null) { + result.add(level); + if (!queue.isEmpty()) { + queue.add(null); + level = new ArrayList<>(); + } + } else { + level.add(current.val); + if (current.left != null) queue.add(current.left); + if (current.right != null) queue.add(current.right); + } + } + return result; + } +} diff --git a/src/BinaryTreeLevelOrderTraversalII.java b/src/BinaryTreeLevelOrderTraversalII.java index 3ba166b..e87a467 100644 --- a/src/BinaryTreeLevelOrderTraversalII.java +++ b/src/BinaryTreeLevelOrderTraversalII.java @@ -5,11 +5,6 @@ import java.util.Queue; public class BinaryTreeLevelOrderTraversalII { - private static class TreeNode { - int val; - TreeNode left; - TreeNode right; - } private static class Pair { TreeNode tree; diff --git a/src/BinaryTreeMaximumPathSum.java b/src/BinaryTreeMaximumPathSum.java new file mode 100644 index 0000000..cbc3ecb --- /dev/null +++ b/src/BinaryTreeMaximumPathSum.java @@ -0,0 +1,29 @@ +// https://leetcode.com/problems/binary-tree-maximum-path-sum +// T: O(N) +// S: O(logN) + +public class BinaryTreeMaximumPathSum { + private static int result = Integer.MIN_VALUE; + + public int maxPathSum(TreeNode root) { + result = Integer.MIN_VALUE; + if (root == null) { + return 0; + } + maxSum(root); + return result; + } + + private static int maxSum(TreeNode root) { + if (root == null) { + return 0; + } + + final int maxSumLeftSubtree = Math.max(maxSum(root.left), 0); + final int maxSumRightSubtree = Math.max(maxSum(root.right), 0); + final int maxPathSum = root.val + maxSumLeftSubtree + maxSumRightSubtree; + result = Math.max(result, maxPathSum); + + return Math.max(root.val + maxSumLeftSubtree, root.val + maxSumRightSubtree); + } +} diff --git a/src/BinaryTreePaths.java b/src/BinaryTreePaths.java index 72cc649..3a9225f 100644 --- a/src/BinaryTreePaths.java +++ b/src/BinaryTreePaths.java @@ -2,24 +2,10 @@ import java.util.List; public class BinaryTreePaths { - public static void main(String[] args) { - String[] array = {"hello", "1", "2"}; - List list = new ArrayList<>(); - list.add("1"); - list.add("2"); - list.add("3"); - System.out.println(String.join("->", list)); - } - - private static class TreeNode { - int val; - TreeNode left; - TreeNode right; - } public static List binaryTreePaths(TreeNode root) { List result = new ArrayList<>(); - binaryTreePaths(root, new ArrayList(), result); + binaryTreePaths(root, new ArrayList<>(), result); return result; } diff --git a/src/BinaryTreePostorderTraversal.java b/src/BinaryTreePostorderTraversal.java new file mode 100644 index 0000000..5672d1e --- /dev/null +++ b/src/BinaryTreePostorderTraversal.java @@ -0,0 +1,17 @@ +import java.util.ArrayList; +import java.util.List; + +public class BinaryTreePostorderTraversal { + public List postorderTraversal(TreeNode root) { + List result = new ArrayList<>(); + postorderTraversal(root, result); + return result; + } + + private void postorderTraversal(TreeNode root, List list) { + if (root == null) return; + postorderTraversal(root.left, list); + postorderTraversal(root.right, list); + list.add(root.val); + } +} diff --git a/src/BinaryTreePreOrderTraversal.java b/src/BinaryTreePreOrderTraversal.java new file mode 100644 index 0000000..232f7cd --- /dev/null +++ b/src/BinaryTreePreOrderTraversal.java @@ -0,0 +1,17 @@ +import java.util.ArrayList; +import java.util.List; + +public class BinaryTreePreOrderTraversal { + public List preorderTraversal(TreeNode root) { + List result = new ArrayList<>(); + preorderTraversal(root, result); + return result; + } + + private void preorderTraversal(TreeNode root, List list) { + if (root == null) return; + list.add(root.val); + preorderTraversal(root.left, list); + preorderTraversal(root.right, list); + } +} diff --git a/src/BinaryTreeRightSideView.java b/src/BinaryTreeRightSideView.java new file mode 100644 index 0000000..eee78cd --- /dev/null +++ b/src/BinaryTreeRightSideView.java @@ -0,0 +1,22 @@ +// https://leetcode.com/problems/binary-tree-right-side-view +// T: O(n) +// S: O(log(n)) + +import java.util.ArrayList; +import java.util.List; + +public class BinaryTreeRightSideView { + public List rightSideView(TreeNode root) { + final List result = new ArrayList<>(); + rightSideView(root, result, 0); + return result; + } + + private void rightSideView(TreeNode root, final List result, int level) { + if (root == null) return; + if (level == result.size()) result.add(root.val); + + rightSideView(root.right, result, level + 1); + rightSideView(root.left, result, level + 1); + } +} diff --git a/src/BinaryTreeTilt.java b/src/BinaryTreeTilt.java new file mode 100644 index 0000000..daa4b77 --- /dev/null +++ b/src/BinaryTreeTilt.java @@ -0,0 +1,16 @@ +public class BinaryTreeTilt { + public int sumTilts = 0; + + public int findTilt(TreeNode root) { + computeTilt(root); + return sumTilts; + } + + private int computeTilt(TreeNode root) { + if (root == null) return 0; + int leftSum = computeTilt(root.left); + int rightSum = computeTilt(root.right); + sumTilts += Math.abs(leftSum - rightSum); + return leftSum + rightSum + root.val; + } +} diff --git a/src/BinaryTreeZigzagLevelOrderTraversal.java b/src/BinaryTreeZigzagLevelOrderTraversal.java new file mode 100644 index 0000000..6e919ee --- /dev/null +++ b/src/BinaryTreeZigzagLevelOrderTraversal.java @@ -0,0 +1,50 @@ +// https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal +// T: O(n) +// S: O(n) + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + +public class BinaryTreeZigzagLevelOrderTraversal { + public List> zigzagLevelOrder(TreeNode root) { + if (root == null) return Collections.EMPTY_LIST; + + final List> result = new ArrayList<>(); + final Queue queue = new LinkedList<>(); + queue.add(root); + queue.add(null); + + List level = new ArrayList<>(); + + while (!queue.isEmpty()) { + final TreeNode current = queue.poll(); + if (current == null) { + result.add(level); + level = new LinkedList<>(); + if (!queue.isEmpty()) { + queue.add(null); + } + continue; + } + level.add(current.val); + addChildrenInQueue(queue, current); + } + + zigZagOrder(result); + return result; + } + + private void zigZagOrder(List> levels) { + for (int i = 1 ; i < levels.size() ; i += 2) { + Collections.reverse(levels.get(i)); + } + } + + private void addChildrenInQueue(Queue queue, TreeNode root) { + if (root.left != null) queue.add(root.left); + if (root.right != null) queue.add(root.right); + } +} diff --git a/src/BitwiseANDOfNumbersRange.java b/src/BitwiseANDOfNumbersRange.java new file mode 100644 index 0000000..3dfef1b --- /dev/null +++ b/src/BitwiseANDOfNumbersRange.java @@ -0,0 +1,16 @@ +// https://leetcode.com/problems/bitwise-and-of-numbers-range +// T: O(log(left)) +// S: O(1) + +public class BitwiseANDOfNumbersRange { + public int rangeBitwiseAnd(int left, int right) { + int moveFactor = 0; + while(left != right){ + left >>= 1; + right >>= 1; + moveFactor++; + } + + return left << moveFactor; + } +} diff --git a/src/BuddyStrings.java b/src/BuddyStrings.java new file mode 100644 index 0000000..25e5562 --- /dev/null +++ b/src/BuddyStrings.java @@ -0,0 +1,30 @@ +import java.util.Arrays; + +public class BuddyStrings { + public boolean buddyStrings(String s, String goal) { + if (s.length() != goal.length()) return false; + final int[] characterFrequencies = new int[26]; + final int[] need = new int[26]; + int differences = 0; + char c; + for (int index = 0 ; index < s.length() ; index++) { + c = s.charAt(index); + characterFrequencies[c - 'a']++; + if (c != goal.charAt(index)) { + differences++; + need[goal.charAt(index) - 'a']++; + need[c - 'a']--; + } + } + if (differences == 1 || differences > 2) return false; + if (differences == 0 && oneCharOccurrsMoreThanOnce(characterFrequencies)) return true; + return differences == 2 && Arrays.stream(need).allMatch(val -> val == 0); + } + + private boolean oneCharOccurrsMoreThanOnce(int[] frequencies) { + for (int frequency : frequencies) { + if (frequency > 1) return true; + } + return false; + } +} diff --git a/src/BuildAnArrayWithStackOperations.java b/src/BuildAnArrayWithStackOperations.java new file mode 100644 index 0000000..47e89ef --- /dev/null +++ b/src/BuildAnArrayWithStackOperations.java @@ -0,0 +1,28 @@ +import java.util.ArrayList; +import java.util.List; + +public class BuildAnArrayWithStackOperations { + private static final String PUSH = "Push"; + private static final String POP = "Pop"; + + public List buildArray(int[] target, int n) { + List result = new ArrayList<>(); + for (int index = 0, lastNumber = 0 ; index < target.length ; index++) { + popKNumbers(result, target[index] - 1 - lastNumber); + pushCurrentNumber(result); + lastNumber = target[index]; + } + return result; + } + + private void popKNumbers(List list, int k) { + while (k-- > 0) { + list.add(PUSH); + list.add(POP); + } + } + + private void pushCurrentNumber(List list) { + list.add(PUSH); + } +} diff --git a/src/BuildArrayFromPermutation.java b/src/BuildArrayFromPermutation.java new file mode 100644 index 0000000..5787cd8 --- /dev/null +++ b/src/BuildArrayFromPermutation.java @@ -0,0 +1,13 @@ +// https://leetcode.com/problems/build-array-from-permutation +// T: O(N) +// S: O(N) + +public class BuildArrayFromPermutation { + public int[] buildArray(int[] nums) { + final int[] result = new int[nums.length]; + for (int i = 0 ; i < nums.length ; i++) { + result[i] = nums[nums[i]]; + } + return result; + } +} diff --git a/src/BuyTwoChocolates.java b/src/BuyTwoChocolates.java new file mode 100644 index 0000000..ccb466e --- /dev/null +++ b/src/BuyTwoChocolates.java @@ -0,0 +1,19 @@ +// https://leetcode.com/problems/buy-two-chocolates +// T: O(N) +// S: O(1) + +public class BuyTwoChocolates { + public int buyChoco(int[] prices, int money) { + int minimum = Integer.MAX_VALUE, secondMinimum = Integer.MAX_VALUE; + for (int price : prices) { + if (price <= minimum) { + secondMinimum = minimum; + minimum = price; + } else if (price < secondMinimum) { + secondMinimum = price; + } + } + if (minimum + secondMinimum > money) return money; + return money - (minimum + secondMinimum); + } +} diff --git a/src/CalculateAmountPaidInTaxes.java b/src/CalculateAmountPaidInTaxes.java new file mode 100644 index 0000000..9f16980 --- /dev/null +++ b/src/CalculateAmountPaidInTaxes.java @@ -0,0 +1,17 @@ +// https://leetcode.com/problems/calculate-amount-paid-in-taxes +// T: O(|brackets|) +// S: O(1) + +public class CalculateAmountPaidInTaxes { + public double calculateTax(int[][] brackets, int income) { + double tax = 0; + int ceiling = 0; + for (int i = 0 ; i < brackets.length && income > 0 ; i++) { + final int taxableIncome = Math.min(brackets[i][0] - ceiling, income); + income -= taxableIncome; + ceiling = brackets[i][0]; + tax += taxableIncome * ((double) brackets[i][1] / 100); + } + return tax; + } +} diff --git a/src/CalculateDelayedArrivalTime.java b/src/CalculateDelayedArrivalTime.java new file mode 100644 index 0000000..58b259c --- /dev/null +++ b/src/CalculateDelayedArrivalTime.java @@ -0,0 +1,9 @@ +// https://leetcode.com/problems/calculate-delayed-arrival-time +// T: O(1) +// S: O(1) + +public class CalculateDelayedArrivalTime { + public int findDelayedArrivalTime(int arrivalTime, int delayedTime) { + return (arrivalTime + delayedTime) % 24; + } +} diff --git a/src/CalculateDigitSumOfAString.java b/src/CalculateDigitSumOfAString.java new file mode 100644 index 0000000..020a06f --- /dev/null +++ b/src/CalculateDigitSumOfAString.java @@ -0,0 +1,28 @@ +// https://leetcode.com/problems/calculate-digit-sum-of-a-string +// T: O(log(n)) +// S: O(log(n)) + +public class CalculateDigitSumOfAString { + public String digitSum(String s, int k) { + if (s.length() <= k) return s; + final StringBuilder result = new StringBuilder(); + for (int i = 0 ; i < s.length() ; i += k) { + final String group = s.substring(i, Math.min(i + k, s.length())); + final int groupSum = digitSum(group); + result.append(groupSum); + } + return digitSum(result.toString(), k); + } + + private int digitSum(String number) { + int sum = 0; + for (int index = 0 ; index < number.length() ; index++) { + sum += toInt(number.charAt(index)); + } + return sum; + } + + private int toInt(char x) { + return x - '0'; + } +} diff --git a/src/CalculateMoneyInLeetCodeBank.java b/src/CalculateMoneyInLeetCodeBank.java new file mode 100644 index 0000000..a75bd41 --- /dev/null +++ b/src/CalculateMoneyInLeetCodeBank.java @@ -0,0 +1,19 @@ +public class CalculateMoneyInLeetCodeBank { + private static final int SUM_7 = 28; + + public int totalMoney (int n) { + final int r = ceil((double) n / 7); + return r * SUM_7 + + 7 * summation(r - 1) + - (summation(6 + r) - summation(n % 7 == 0 ? 6 + r : r - 1 + n % 7)); + } + + private int ceil(double d) { + return (int) Math.ceil(d); + } + + private int summation(int x) { + if (x <= 0) return 0; + return (x * (x + 1)) / 2; + } +} diff --git a/src/CanMakeArithmeticProgressionFromSequence.java b/src/CanMakeArithmeticProgressionFromSequence.java new file mode 100644 index 0000000..31ea161 --- /dev/null +++ b/src/CanMakeArithmeticProgressionFromSequence.java @@ -0,0 +1,24 @@ +// https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/ +// T: O(n) +// S: O(n) + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +public class CanMakeArithmeticProgressionFromSequence { + public boolean canMakeArithmeticProgression(int[] array) { + final int a = Arrays.stream(array).min().getAsInt(); + final int l = Arrays.stream(array).max().getAsInt(); + if (a == l) return true; + if ((l - a) % (array.length - 1) != 0) return false; + final int d = (l - a) / (array.length - 1); + Set elements = new HashSet<>(); + for (int number : array) { + if (elements.contains(number)) return false; + if ((number - a) % d != 0)return false; + elements.add(number); + } + return true; + } +} diff --git a/src/CanPlaceFlowers.java b/src/CanPlaceFlowers.java new file mode 100644 index 0000000..e752b79 --- /dev/null +++ b/src/CanPlaceFlowers.java @@ -0,0 +1,16 @@ +public class CanPlaceFlowers { + public boolean canPlaceFlowers(int[] flowerbed, int n) { + return flowersCapacity(flowerbed) >= n; + } + + private int flowersCapacity(int[] flowerbed) { + int capacity = 0; + for (int index = 0 ; index < flowerbed.length ; index++) { + if ((flowerbed[index] != 1) && (index == 0 || flowerbed[index - 1] == 0) && (index == flowerbed.length - 1 || flowerbed[index + 1] == 0)) { + capacity++; + flowerbed[index] = 1; + } + } + return capacity; + } +} diff --git a/src/Candy.java b/src/Candy.java new file mode 100644 index 0000000..defcad4 --- /dev/null +++ b/src/Candy.java @@ -0,0 +1,27 @@ +// https://leetcode.com/problems/candy +// T: O(N) +// S: O(N) + +import java.util.Arrays; + +public class Candy { + public int candy(int[] ratings) { + final int[] candies = new int[ratings.length]; + + // left pass + for (int i = 1 ; i < ratings.length ; i++) { + if (ratings[i] > ratings[i - 1]) { + candies[i] = candies[i - 1] + 1; + } + } + + // right pass + for (int i = ratings.length - 2 ; i >= 0 ; i--) { + if (ratings[i] > ratings[i + 1]) { + candies[i] = Math.max(candies[i], candies[i + 1] + 1); + } + } + + return Arrays.stream(candies).sum() + ratings.length; + } +} diff --git a/src/CapitalizeTheTitle.java b/src/CapitalizeTheTitle.java new file mode 100644 index 0000000..3ec3e3b --- /dev/null +++ b/src/CapitalizeTheTitle.java @@ -0,0 +1,15 @@ +// https://leetcode.com/problems/capitalize-the-title +// T: O(|s|) +// S: O(|s|) + +public class CapitalizeTheTitle { + public String capitalizeTitle(String title) { + final StringBuilder result = new StringBuilder(); + final String[] words = title.split(" "); + for (String word : words) { + if (word.length() <= 2) result.append(word.toLowerCase()).append(' '); + else result.append(word.substring(0, 1).toUpperCase()).append(word.substring(1).toLowerCase()).append(' '); + } + return result.delete(result.length() - 1, result.length()).toString(); + } +} diff --git a/src/CategorizeBoxAccordingToCriteria.java b/src/CategorizeBoxAccordingToCriteria.java new file mode 100644 index 0000000..52ffd7e --- /dev/null +++ b/src/CategorizeBoxAccordingToCriteria.java @@ -0,0 +1,20 @@ +// https://leetcode.com/problems/categorize-box-according-to-criteria +// T: O(1) +// S: O(1) + +public class CategorizeBoxAccordingToCriteria { + public String categorizeBox(int length, int width, int height, int mass) { + final boolean isBulky = isBulky(length, width, height, mass); + final boolean isHeavy = mass >= 100; + + if (isBulky && isHeavy) return "Both"; + if (!isBulky && !isHeavy) return "Neither"; + if (isBulky) return "Bulky"; + return "Heavy"; + } + + private boolean isBulky(long length, long width, long height, long mass) { + long volume = length * width * height; + return length >= 10_000 || width >= 10_000 || height >= 10_000 || mass >= 10_000 || volume >= 1_000_000_000; + } +} diff --git a/src/CellsInARangeOnAnExcelSheet.java b/src/CellsInARangeOnAnExcelSheet.java new file mode 100644 index 0000000..cd7f813 --- /dev/null +++ b/src/CellsInARangeOnAnExcelSheet.java @@ -0,0 +1,25 @@ +// https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet +// T: O(1) +// S: O(1) + +import java.util.ArrayList; +import java.util.List; + +public class CellsInARangeOnAnExcelSheet { + public List cellsInRange(String s) { + final char column1 = s.charAt(0); + final char column2 = s.charAt(3); + final int row1 = s.charAt(1) - '0'; + final int row2 = s.charAt(4) - '0'; + + final List result = new ArrayList<>(); + + for (char column = column1 ; column <= column2 ; column++) { + for (int row = row1 ; row <= row2 ; row++) { + result.add((column + "") + row); + } + } + + return result; + } +} diff --git a/src/CellsWithOddValuesInMatrix.java b/src/CellsWithOddValuesInMatrix.java new file mode 100644 index 0000000..8a94e7a --- /dev/null +++ b/src/CellsWithOddValuesInMatrix.java @@ -0,0 +1,22 @@ +public class CellsWithOddValuesInMatrix { + public int oddCells(int m, int n, int[][] operations) { + final byte[] rowState = new byte[m]; + final byte[] columnState = new byte[n]; + for (int[] operation : operations) { + rowState[operation[0]] ^= 1; + columnState[operation[1]] ^= 1; + } + int oddElements = 0; + final int shiftedColumns = sum(columnState); + for (int row : rowState) { + oddElements += row == 0 ? shiftedColumns : n - shiftedColumns; + } + return oddElements; + } + + private int sum(byte[] array) { + int sum = 0; + for (byte element : array) sum += element; + return sum; + } +} diff --git a/src/CheapestFlightsWithinKStops.java b/src/CheapestFlightsWithinKStops.java new file mode 100644 index 0000000..82d5931 --- /dev/null +++ b/src/CheapestFlightsWithinKStops.java @@ -0,0 +1,44 @@ +// https://leetcode.com/problems/cheapest-flights-within-k-stops +// T: O((N + E) * K) +// S: O(N) + +import java.util.Arrays; + +public class CheapestFlightsWithinKStops { + + public static int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { + final int[] distances = bellmanFord(flights, n, k, src); + return distances[dst] == Integer.MAX_VALUE ? -1 : distances[dst]; + } + + // T: O(N * K + E * K) = T: O((N + E) * K) S: O(N) + private static int[] bellmanFord(int[][] edges, int n, int k, int source) { + int[] distances = initializeDistances(n); + distances[source] = 0; + for (int i = 0 ; i < k + 1 ; i++) { + final int[] temp = cloneArray(distances); + for (int[] edge : edges) { + final int from = edge[0], to = edge[1], weight = edge[2]; + if (distances[from] != Integer.MAX_VALUE) { + temp[to] = Math.min(temp[to], distances[from] + weight); + } + } + distances = temp; + } + return distances; + } + + // T: O(N), S: O(N) + private static int[] initializeDistances(int n) { + final int[] distances = new int[n]; + Arrays.fill(distances, Integer.MAX_VALUE); + return distances; + } + + // T: O(N), S: O(N) + private static int[] cloneArray(int[] array) { + final int[] result = new int[array.length]; + System.arraycopy(array, 0, result, 0, array.length); + return result; + } +} diff --git a/src/CheckArrayFormationThroughConcatenation.java b/src/CheckArrayFormationThroughConcatenation.java new file mode 100644 index 0000000..b3ac07b --- /dev/null +++ b/src/CheckArrayFormationThroughConcatenation.java @@ -0,0 +1,24 @@ +import java.util.HashMap; +import java.util.Map; + +public class CheckArrayFormationThroughConcatenation { + public boolean canFormArray(int[] arr, int[][] pieces) { + final Map positions = getPositions(arr); + for (int[] piece : pieces) { + if (!positions.containsKey(piece[0])) return false; + if (positions.get(piece[0]) + piece.length > arr.length) return false; + for (int i = 0, j = positions.get(piece[0]); i < piece.length ; i++, j++) { + if (piece[i] != arr[j]) return false; + } + } + return true; + } + + private Map getPositions(int[] array) { + final Map positions = new HashMap<>(); + for (int index = 0 ; index < array.length ; index++) { + positions.put(array[index], index); + } + return positions; + } +} diff --git a/src/CheckDistancesBetweenSameLetters.java b/src/CheckDistancesBetweenSameLetters.java new file mode 100644 index 0000000..349109e --- /dev/null +++ b/src/CheckDistancesBetweenSameLetters.java @@ -0,0 +1,22 @@ +// https://leetcode.com/problems/check-distances-between-same-letters +// T: O(N) +// S: O(1) + +import java.util.HashMap; +import java.util.Map; + +public class CheckDistancesBetweenSameLetters { + public boolean checkDistances(String s, int[] distances) { + final Map firstOccurrenceIndex = new HashMap<>(); + for (int index = 0 ; index < s.length() ; index++) { + char letter = s.charAt(index); + if (firstOccurrenceIndex.containsKey(letter)) { + int distance = index - firstOccurrenceIndex.get(letter) - 1; + if (distance != distances[letter - 'a']) { + return false; + } + } else firstOccurrenceIndex.put(letter, index); + } + return true; + } +} diff --git a/src/CheckIfAStringIsAnAcronymOfWords.java b/src/CheckIfAStringIsAnAcronymOfWords.java new file mode 100644 index 0000000..4402f61 --- /dev/null +++ b/src/CheckIfAStringIsAnAcronymOfWords.java @@ -0,0 +1,21 @@ +// https://leetcode.com/problems/check-if-a-string-is-an-acronym-of-words +// T: O(N) +// S: O(1) + +import java.util.List; + +public class CheckIfAStringIsAnAcronymOfWords { + public boolean isAcronym(List words, String s) { + if (words.size() != s.length()) { + return false; + } + + for (int i = 0 ; i < words.size() ; i++) { + if (words.get(i).charAt(0) != s.charAt(i)) { + return false; + } + } + + return true; + } +} diff --git a/src/CheckIfAWordOccursAsAPrefixOfAnyWordInASentence.java b/src/CheckIfAWordOccursAsAPrefixOfAnyWordInASentence.java new file mode 100644 index 0000000..9ef9ec0 --- /dev/null +++ b/src/CheckIfAWordOccursAsAPrefixOfAnyWordInASentence.java @@ -0,0 +1,21 @@ +public class CheckIfAWordOccursAsAPrefixOfAnyWordInASentence { + public int isPrefixOfWord(String sentence, String searchWord) { + int matchIndex = -1; + do { + matchIndex = sentence.indexOf(searchWord, matchIndex + 1); + if (matchIndex == -1) return -1; + if (matchIndex == 0 || sentence.charAt(matchIndex - 1) == ' ') { + return spacesUpto(sentence, matchIndex) + 1; + } + } while (matchIndex < sentence.length()); + return -1; + } + + private static int spacesUpto(String string, int endIndex) { + int spaces = 0; + for (int index = 0 ; index < endIndex ; index++) { + if (string.charAt(index) == ' ') spaces++; + } + return spaces; + } +} diff --git a/src/CheckIfAll1sAreAtLeastKPlacesAway.java b/src/CheckIfAll1sAreAtLeastKPlacesAway.java new file mode 100644 index 0000000..d5e1696 --- /dev/null +++ b/src/CheckIfAll1sAreAtLeastKPlacesAway.java @@ -0,0 +1,14 @@ +public class CheckIfAll1sAreAtLeastKPlacesAway { + public boolean kLengthApart(int[] nums, int k) { + int index = 0; + while (index < nums.length && nums[index] != 1) index++; + index++; + for ( int distance = 0 ; index < nums.length ; index++) { + if (nums[index] == 1) { + if (distance < k) return false; + distance = 0; + } else distance++; + } + return true; + } +} diff --git a/src/CheckIfAllCharactersHaveEqualNumberOfOccurrences.java b/src/CheckIfAllCharactersHaveEqualNumberOfOccurrences.java new file mode 100644 index 0000000..ab3e523 --- /dev/null +++ b/src/CheckIfAllCharactersHaveEqualNumberOfOccurrences.java @@ -0,0 +1,25 @@ +// https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences +// T: O(|s|) +// S: O(1) + +import java.util.HashMap; +import java.util.Map; + +public class CheckIfAllCharactersHaveEqualNumberOfOccurrences { + public boolean areOccurrencesEqual(String s) { + final Map charFrequencies = getCharacterFrequencies(s); + int commonFrequency = charFrequencies.get(s.charAt(0)); + for (int frequency : charFrequencies.values()) { + if (frequency != commonFrequency) return false; + } + return true; + } + + private Map getCharacterFrequencies(String s) { + final Map characterFrequencies = new HashMap<>(26); + for (int i = 0 ; i < s.length() ; i++) { + characterFrequencies.put(s.charAt(i), characterFrequencies.getOrDefault(s.charAt(i), 0) + 1); + } + return characterFrequencies; + } +} diff --git a/src/CheckIfAllTheAsAppearBeforeAllTheBs.java b/src/CheckIfAllTheAsAppearBeforeAllTheBs.java new file mode 100644 index 0000000..49ce502 --- /dev/null +++ b/src/CheckIfAllTheAsAppearBeforeAllTheBs.java @@ -0,0 +1,14 @@ +// https://leetcode.com/problems/check-if-all-as-appears-before-all-bs +// T: O(|s|) +// S: O(1) + +public class CheckIfAllTheAsAppearBeforeAllTheBs { + public boolean checkString(String s) { + boolean seenB = false; + for (int index = 0 ; index < s.length() ; index++) { + if (s.charAt(index) == 'b') seenB = true; + if (s.charAt(index) == 'a' && seenB) return false; + } + return true; + } +} diff --git a/src/CheckIfAllTheIntegersInARangeAreCovered.java b/src/CheckIfAllTheIntegersInARangeAreCovered.java new file mode 100644 index 0000000..91669e3 --- /dev/null +++ b/src/CheckIfAllTheIntegersInARangeAreCovered.java @@ -0,0 +1,27 @@ +// https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered +// T:O(|ranges| + |right - left|) +// S: O(1) + +public class CheckIfAllTheIntegersInARangeAreCovered { + public boolean isCovered(int[][] ranges, int left, int right) { + final int[] covered = new int[51]; + for (int[] range : ranges) { + covered[range[0] - 1]++; + covered[range[1]]--; + } + final int[] isCovered = runningSum(covered); + for (int i = left ; i <= right ; i++) { + if(isCovered[i - 1] <= 0) return false; + } + return true; + } + + private static int[] runningSum(int[] array) { + final int[] sum = new int[array.length]; + sum[0] = array[0]; + for (int i = 1 ; i < array.length ; i++) { + sum[i] = sum[i - 1] + array[i]; + } + return sum; + } +} diff --git a/src/CheckIfArrayIsGood.java b/src/CheckIfArrayIsGood.java new file mode 100644 index 0000000..f7d3140 --- /dev/null +++ b/src/CheckIfArrayIsGood.java @@ -0,0 +1,26 @@ +// https://leetcode.com/problems/check-if-array-is-good +// T: O(N) +// S: O(N) + +import java.util.HashMap; +import java.util.Map; + +public class CheckIfArrayIsGood { + public boolean isGood(int[] array) { + final Map frequencies = getFrequencies(array); + for (int i = 1 ; i < array.length - 1 ; i++) { + if (frequencies.getOrDefault(i, 0) != 1) { + return false; + } + } + return frequencies.getOrDefault(array.length - 1, 0) == 2; + } + + private Map getFrequencies(int[] array) { + final Map result = new HashMap<>(); + for (int element : array) { + result.put(element, result.getOrDefault(element, 0) + 1); + } + return result; + } +} diff --git a/src/CheckIfArrayIsSortedAndRotated.java b/src/CheckIfArrayIsSortedAndRotated.java new file mode 100644 index 0000000..dee8f41 --- /dev/null +++ b/src/CheckIfArrayIsSortedAndRotated.java @@ -0,0 +1,9 @@ +public class CheckIfArrayIsSortedAndRotated { + public boolean check(int[] array) { + int slope = 0; + for (int index = 0 ; index < array.length - 1 ; index++) { + if (array[index] > array[index + 1]) slope++; + } + return slope == 0 || (slope == 1 && array[array.length - 1] <= array[0]); + } +} diff --git a/src/CheckIfBinaryStringHasAtMostOneSegmentOfOnes.java b/src/CheckIfBinaryStringHasAtMostOneSegmentOfOnes.java new file mode 100644 index 0000000..d8a60b6 --- /dev/null +++ b/src/CheckIfBinaryStringHasAtMostOneSegmentOfOnes.java @@ -0,0 +1,15 @@ +public class CheckIfBinaryStringHasAtMostOneSegmentOfOnes { + public boolean checkOnesSegment(String s) { + int segments = 0; + boolean isInSegment = false; + for (int index = 0 ; index < s.length() ; index++) { + if (!isInSegment && s.charAt(index) == '1') { + isInSegment = true; + segments++; + } else if (isInSegment && s.charAt(index) == '0') { + isInSegment = false; + } + } + return segments <= 1; + } +} diff --git a/src/CheckIfBitwiseORHasTrailingZeros.java b/src/CheckIfBitwiseORHasTrailingZeros.java new file mode 100644 index 0000000..1fcaece --- /dev/null +++ b/src/CheckIfBitwiseORHasTrailingZeros.java @@ -0,0 +1,18 @@ +// https://leetcode.com/problems/check-if-bitwise-or-has-trailing-zeros +// T: O(N) +// S: O(1) + +public class CheckIfBitwiseORHasTrailingZeros { + public boolean hasTrailingZeros(int[] array) { + int evenNumbers = 0; + for (int element : array) { + if (element % 2 == 0) { + evenNumbers++; + } + if (evenNumbers == 2) { + return true; + } + } + return false; + } +} diff --git a/src/CheckIfEveryRowAndEveryColumnContainAllNumbers.java b/src/CheckIfEveryRowAndEveryColumnContainAllNumbers.java new file mode 100644 index 0000000..f7cbd82 --- /dev/null +++ b/src/CheckIfEveryRowAndEveryColumnContainAllNumbers.java @@ -0,0 +1,41 @@ +import java.util.HashSet; +import java.util.Set; + +public class CheckIfEveryRowAndEveryColumnContainAllNumbers { + private int n; + + public boolean checkValid(int[][] matrix) { + this.n = matrix.length; + return checkAllRows(matrix) && checkAllColumns(matrix); + } + + private boolean checkAllRows(int[][] matrix) { + for (int[] row : matrix) { + if (!isRowValid(row)) return false; + } + return true; + } + + private boolean isRowValid(int[] row) { + final Set numbers = new HashSet<>(); + for (int element: row) { + if (element <= 0 || element > n) return false; + if (numbers.contains(element)) return false; + numbers.add(element); + } + return true; + } + + private boolean checkAllColumns(int[][] matrix) { + for (int column = 0 ; column < n ; column++) { + final Set numbers = new HashSet<>(); + for (int row = 0 ; row < n ; row++) { + int element = matrix[row][column]; + if (element < 0 || element > n) return false; + if (numbers.contains(element)) return false; + numbers.add(element); + } + } + return true; + } +} diff --git a/src/CheckIfGridSatisfiesConditions.java b/src/CheckIfGridSatisfiesConditions.java new file mode 100644 index 0000000..76acc40 --- /dev/null +++ b/src/CheckIfGridSatisfiesConditions.java @@ -0,0 +1,19 @@ +// https://leetcode.com/problems/check-if-grid-satisfies-conditions +// T: O(m * n) +// S: O(1) + +public class CheckIfGridSatisfiesConditions { + public boolean satisfiesConditions(int[][] grid) { + for (int i = 0 ; i < grid.length ; i++) { + for (int j = 0 ; j < grid[i].length ; j++) { + if (j + 1 < grid[i].length && grid[i][j] == grid[i][j + 1]) { + return false; + } + if (i + 1 < grid.length && grid[i][j] != grid[i + 1][j]) { + return false; + } + } + } + return true; + } +} diff --git a/src/CheckIfItIsASStraightLine.java b/src/CheckIfItIsASStraightLine.java new file mode 100644 index 0000000..a52ba25 --- /dev/null +++ b/src/CheckIfItIsASStraightLine.java @@ -0,0 +1,16 @@ +public class CheckIfItIsASStraightLine { + public boolean checkStraightLine(int[][] coordinates) { + for (int i = 0 ; i < coordinates.length - 2 ; i++) { + if (!isOnStraightLine(coordinates[i], coordinates[i + 1], coordinates[i + 2])) { + return false; + } + } + return true; + } + + private boolean isOnStraightLine(int[] p1, int[] p2, int[] p3) { + if (p1[0] == p2[0] && p2[0] == p3[0]) return true; + if (p1[1] == p2[1] && p2[1] == p3[1]) return true; + return (p2[1] - p1[1]) * (p3[0] - p2[0]) == (p3[1] - p2[1]) * (p2[0] - p1[0]); + } +} diff --git a/src/CheckIfMatrixIsXMatrix.java b/src/CheckIfMatrixIsXMatrix.java new file mode 100644 index 0000000..bf5fd5a --- /dev/null +++ b/src/CheckIfMatrixIsXMatrix.java @@ -0,0 +1,20 @@ +// https://leetcode.com/problems/check-if-matrix-is-x-matrix +// T: O(n * n) +// S: O(1) + +public class CheckIfMatrixIsXMatrix { + public boolean checkXMatrix(int[][] grid) { + for (int row = 0 ; row < grid.length ; row++) { + for (int column = 0 ; column < grid.length ; column++) { + if (isDiagonalCell(row, column, grid.length)) { + if (grid[row][column] == 0) return false; + } else if (grid[row][column] != 0) return false; + } + } + return true; + } + + private boolean isDiagonalCell(int row, int column, int length) { + return row == column || column == length - row - 1; + } +} diff --git a/src/CheckIfNAndItsDoubleExist.java b/src/CheckIfNAndItsDoubleExist.java new file mode 100644 index 0000000..e7306ea --- /dev/null +++ b/src/CheckIfNAndItsDoubleExist.java @@ -0,0 +1,15 @@ +import java.util.HashSet; +import java.util.Set; + +public class CheckIfNAndItsDoubleExist { + public boolean checkIfExist(int[] array) { + Set elements = new HashSet<>(); + for(int element : array) { + if (elements.contains(element * 2) || (element % 2 == 0 && elements.contains(element / 2))) { + return true; + } + elements.add(element); + } + return false; + } +} diff --git a/src/CheckIfNumberHasEqualDigitCountAndDigitValue.java b/src/CheckIfNumberHasEqualDigitCountAndDigitValue.java new file mode 100644 index 0000000..9d07c85 --- /dev/null +++ b/src/CheckIfNumberHasEqualDigitCountAndDigitValue.java @@ -0,0 +1,27 @@ +// https://leetcode.com/problems/check-if-number-has-equal-digit-count-and-digit-value +// T: O(|num|) +// S: O(1) + +import java.util.HashMap; +import java.util.Map; + +public class CheckIfNumberHasEqualDigitCountAndDigitValue { + public boolean digitCount(String num) { + final Map digitFrequencies = getDigitFrequencies(num); + for (int index = 0 ; index < num.length() ; index++) { + if ((num.charAt(index) - '0') != digitFrequencies.getOrDefault(index, 0)) { + return false; + } + } + return true; + } + + private Map getDigitFrequencies(String number) { + final Map frequencies = new HashMap<>(); + for (int i = 0 ; i < number.length() ; i++) { + final int digit = number.charAt(i) - '0'; + frequencies.put(digit, frequencies.getOrDefault(digit, 0) + 1); + } + return frequencies; + } +} diff --git a/src/CheckIfNumbersAreAscendingInASentence.java b/src/CheckIfNumbersAreAscendingInASentence.java new file mode 100644 index 0000000..e1177c5 --- /dev/null +++ b/src/CheckIfNumbersAreAscendingInASentence.java @@ -0,0 +1,40 @@ +// https://leetcode.com/problems/check-if-numbers-are-ascending-in-a-sentence +// T: O(|s|) +// S: O(|s|) + +import java.util.LinkedList; +import java.util.Queue; + +public class CheckIfNumbersAreAscendingInASentence { + public boolean areNumbersAscending(String s) { + StringBuilder word = new StringBuilder(); + final Queue numbers = new LinkedList<>(); + for (int i = 0 ; i < s.length() ; i++) { + if (s.charAt(i) == ' ') { + if (isNumber(word)) { + if (!numbers.isEmpty() && lessThanEqual(word.toString(), numbers.peek())) { + return false; + } + numbers.poll(); + numbers.add(word.toString()); + } + word = new StringBuilder(); + } else word.append(s.charAt(i)); + } + return !isNumber(word) || numbers.isEmpty() || !lessThanEqual(word.toString(), numbers.peek()); + } + + private boolean isNumber(StringBuilder s) { + return Character.isDigit(s.charAt(0)); + } + + private boolean lessThanEqual(String s, String o) { + if (s.length() < o.length()) return true; + if (s.length() > o.length()) return false; + for (int i = 0 ; i < s.length() ; i++) { + if (s.charAt(i) < o.charAt(i)) return true; + if (s.charAt(i) > o.charAt(i)) return false; + } + return true; + } +} diff --git a/src/CheckIfOneStringSwapCanMakeStringsEqual.java b/src/CheckIfOneStringSwapCanMakeStringsEqual.java new file mode 100644 index 0000000..9fc984e --- /dev/null +++ b/src/CheckIfOneStringSwapCanMakeStringsEqual.java @@ -0,0 +1,20 @@ +import java.util.LinkedList; +import java.util.Queue; + +public class CheckIfOneStringSwapCanMakeStringsEqual { + public boolean areAlmostEqual(String s1, String s2) { + if (s1.length() != s2.length()) return false; + final Queue differencesIndex = new LinkedList<>(); + for (int i = 0 ; i < s1.length() ; i++) { + if (s1.charAt(i) != s2.charAt(i)) { + differencesIndex.add(i); + } + } + return differencesIndex.size() == 0 || (differencesIndex.size() == 2 && areSameChars(s1, s2, differencesIndex)); + } + + private boolean areSameChars(String s1, String s2, Queue differenceIndexes) { + final int i = differenceIndexes.poll() , j = differenceIndexes.poll(); + return s1.charAt(i) == s2.charAt(j) && s1.charAt(j) == s2.charAt(i); + } +} diff --git a/src/CheckIfSentenceIsPangram.java b/src/CheckIfSentenceIsPangram.java new file mode 100644 index 0000000..bddc470 --- /dev/null +++ b/src/CheckIfSentenceIsPangram.java @@ -0,0 +1,21 @@ +// https://leetcode.com/problems/check-if-the-sentence-is-pangram +// T: O(|s|) +// S: O(1) + +import java.util.HashSet; +import java.util.Set; + +public class CheckIfSentenceIsPangram { + public boolean checkIfPangram(String sentence) { + final Set letters = getLetters(sentence); + return letters.size() == 26; + } + + private Set getLetters(String s) { + final Set letters = new HashSet<>(); + for (int index = 0 ; index < s.length() ; index++) { + letters.add(s.charAt(index)); + } + return letters; + } +} diff --git a/src/CheckIfStringIsAPrefixOfArray.java b/src/CheckIfStringIsAPrefixOfArray.java new file mode 100644 index 0000000..6047b6c --- /dev/null +++ b/src/CheckIfStringIsAPrefixOfArray.java @@ -0,0 +1,18 @@ +// https://leetcode.com/problems/check-if-string-is-a-prefix-of-array +// T : O(|s|) +// S : O(1) + +public class CheckIfStringIsAPrefixOfArray { + public boolean isPrefixString(String s, String[] words) { + int w = 0, j = 0; + for (int i = 0 ; i < s.length() && w < words.length ; i++) { + if (s.charAt(i) != words[w].charAt(j)) return false; + if (j == words[w].length() - 1) { + if (w == words.length - 1 && i + 1 < s.length()) return false; + w++; + j = 0; + } else j++; + } + return j == 0; + } +} diff --git a/src/CheckIfStringsCanBeMadeEqualWithOperationsI.java b/src/CheckIfStringsCanBeMadeEqualWithOperationsI.java new file mode 100644 index 0000000..9136586 --- /dev/null +++ b/src/CheckIfStringsCanBeMadeEqualWithOperationsI.java @@ -0,0 +1,17 @@ +// https://leetcode.com/problems/check-if-strings-can-be-made-equal-with-operations-i +// T: O(N) +// S: O(1) + +public class CheckIfStringsCanBeMadeEqualWithOperationsI { + public boolean canBeEqual(String s1, String s2) { + for (int i = 0 ; i < s1.length() - 2 ; i++) { + if ( + (s1.charAt(i) == s2.charAt(i) && s1.charAt(i + 2) == s2.charAt(i + 2) || + (s1.charAt(i) == s2.charAt(i + 2) && s1.charAt(i + 2) == s2.charAt(i)))) { + continue; + } + return false; + } + return true; + } +} diff --git a/src/CheckIfTheNumberIsFascinating.java b/src/CheckIfTheNumberIsFascinating.java new file mode 100644 index 0000000..e642aba --- /dev/null +++ b/src/CheckIfTheNumberIsFascinating.java @@ -0,0 +1,22 @@ +// https://leetcode.com/problems/check-if-the-number-is-fascinating +// T: O(log(N)) +// S: O(1) + +import java.util.HashSet; +import java.util.Set; + +public class CheckIfTheNumberIsFascinating { + public boolean isFascinating(int number) { + final String modifiedNumber = "" + number + (2 * number) + (3 * number); + final Set digits = toSet(modifiedNumber); + return digits.size() == 9 && !digits.contains('0') && modifiedNumber.length() == 9; + } + + private Set toSet(String str) { + final Set set = new HashSet<>(); + for (int i = 0 ; i < str.length() ; i++) { + set.add(str.charAt(i)); + } + return set; + } +} diff --git a/src/CheckIfTwoStringArraysAreEquivalent.java b/src/CheckIfTwoStringArraysAreEquivalent.java new file mode 100644 index 0000000..1226451 --- /dev/null +++ b/src/CheckIfTwoStringArraysAreEquivalent.java @@ -0,0 +1,21 @@ +public class CheckIfTwoStringArraysAreEquivalent { + public boolean arrayStringsAreEqual(String[] word1, String[] word2) { + for (int w1 = 0, w2 = 0, i = 0, j = 0 ; w1 < word1.length && w2 < word2.length ; ) { + if (word1[w1].charAt(i) != word2[w2].charAt(j)) return false; + if (i == word1[w1].length() - 1) { + w1++; + i = 0; + } else { + i++; + } + if (j == word2[w2].length() - 1) { + w2++; + j = 0; + } else { + j++; + } + if (w1 == word1.length && w2 == word2.length) return true; + } + return false; + } +} diff --git a/src/CheckIfWordEqualsSummationOfTwoWords.java b/src/CheckIfWordEqualsSummationOfTwoWords.java new file mode 100644 index 0000000..bd381f2 --- /dev/null +++ b/src/CheckIfWordEqualsSummationOfTwoWords.java @@ -0,0 +1,18 @@ +// https://leetcode.com/problems/check-if-word-equals-summation-of-two-words +// T: O(|f1| + |f2| + |f3|) +// S: O(1) + +public class CheckIfWordEqualsSummationOfTwoWords { + public boolean isSumEqual(String firstWord, String secondWord, String targetWord) { + return toNumber(firstWord) + toNumber(secondWord) == toNumber(targetWord); + } + + private int toNumber(String s) { + int sum = 0; + for (int i = 0 ; i < s.length() ; i++) { + sum *= 10; + sum += s.charAt(i) - 'a'; + } + return sum; + } +} diff --git a/src/CheckPerfectNumber.java b/src/CheckPerfectNumber.java new file mode 100644 index 0000000..113e4b1 --- /dev/null +++ b/src/CheckPerfectNumber.java @@ -0,0 +1,13 @@ +public class CheckPerfectNumber { + public boolean checkPerfectNumber(int number) { + if (number == 1) return false; + + int sum = 0; + for (int divisor = 2 ; divisor * divisor <= number ; divisor++) { + if (number % divisor == 0) { + sum += divisor + number / divisor; + } + } + return sum + 1 == number; + } +} diff --git a/src/CheckWhetherTwoStringsAreAlmostEquivalent.java b/src/CheckWhetherTwoStringsAreAlmostEquivalent.java new file mode 100644 index 0000000..c537e8f --- /dev/null +++ b/src/CheckWhetherTwoStringsAreAlmostEquivalent.java @@ -0,0 +1,28 @@ +// https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent +// T: O(|word1| + |word2|) +// S: O(1) + +import java.util.HashMap; +import java.util.Map; + +public class CheckWhetherTwoStringsAreAlmostEquivalent { + public boolean checkAlmostEquivalent(String word1, String word2) { + final Map word1Frequencies = getFrequencies(word1); + final Map word2Frequencies = getFrequencies(word2); + for (char c = 'a' ; c <= 'z' ; c++) { + if (Math.abs(word1Frequencies.getOrDefault(c, 0) - word2Frequencies.getOrDefault(c, 0)) + > 3) { + return false; + } + } + return true; + } + + private Map getFrequencies(String s) { + final Map frequencies = new HashMap<>(); + for (int i = 0 ; i < s.length() ; i++) { + frequencies.put(s.charAt(i), frequencies.getOrDefault(s.charAt(i), 0) + 1); + } + return frequencies; + } +} diff --git a/src/CircularSentence.java b/src/CircularSentence.java new file mode 100644 index 0000000..2c531ea --- /dev/null +++ b/src/CircularSentence.java @@ -0,0 +1,15 @@ +// https://leetcode.com/problems/circular-sentence +// T: O(N) +// S: O(1) + +public class CircularSentence { + public boolean isCircularSentence(String sentence) { + for (int index = 0 ; index < sentence.length() ; index++) { + char letter = sentence.charAt(index); + if (letter == ' ' && sentence.charAt(index - 1) != sentence.charAt(index + 1)) { + return false; + } + } + return sentence.charAt(0) == sentence.charAt(sentence.length() - 1); + } +} diff --git a/src/ClearDigits.java b/src/ClearDigits.java new file mode 100644 index 0000000..9d2bdbd --- /dev/null +++ b/src/ClearDigits.java @@ -0,0 +1,18 @@ +// https://leetcode.com/problems/clear-digits +// T: O(N) +// S: O(N) + +public class ClearDigits { + public String clearDigits(String s) { + final StringBuilder builder = new StringBuilder(); + for (int i = 0, chars = 0, digits = 0 ; i < s.length() ; i++) { + if (Character.isDigit(s.charAt(i))) { + builder.deleteCharAt(builder.length() - 1); + } else { + builder.append(s.charAt(i)); + } + } + + return builder.toString(); + } +} diff --git a/src/CloneGraph.java b/src/CloneGraph.java new file mode 100644 index 0000000..ff96466 --- /dev/null +++ b/src/CloneGraph.java @@ -0,0 +1,59 @@ +// https://leetcode.com/problems/clone-graph +// T: O(n) +// S: O(n) + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class CloneGraph { + private static final class Node { + public int val; + public List neighbors; + + public Node() { + val = 0; + neighbors = new ArrayList<>(); + } + + public Node(int val) { + this.val = val; + neighbors = new ArrayList<>(); + } + + public Node(int val, ArrayList neighbors) { + this.val = val; + this.neighbors = neighbors; + } + } + + public Node cloneGraph(Node node) { + if (node == null) return null; + final Map graph = new HashMap<>(); + cloneGraph(node, new HashSet<>(), graph); + return graph.get(node.val); + } + + private void cloneGraph(Node node, Set visited, Map newGraph) { + if (node == null) return; + if (visited.contains(node.val)) return; + visited.add(node.val); + + Node current = getNode(newGraph, node.val); + for (Node adjacent : node.neighbors) { + Node newNeighbour = getNode(newGraph, adjacent.val); + current.neighbors.add(newNeighbour); + cloneGraph(adjacent, visited, newGraph); + } + } + + private Node getNode(Map graph, int value) { + if (graph.containsKey(value)) return graph.get(value); + Node node = new Node(value); + graph.put(value, node); + return node; + } +} diff --git a/src/ClosestBinaryTreeSearchValue.java b/src/ClosestBinaryTreeSearchValue.java new file mode 100644 index 0000000..3135f3c --- /dev/null +++ b/src/ClosestBinaryTreeSearchValue.java @@ -0,0 +1,36 @@ +// https://leetcode.com/problems/closest-binary-search-tree-value +// T: O(logN) +// S: O(logN) + +public class ClosestBinaryTreeSearchValue { + private static int result = Integer.MAX_VALUE; + + public int closestValue(TreeNode root, double target) { + result = Integer.MAX_VALUE; + computeClosestValue(root, target); + return result; + } + + private static void computeClosestValue(TreeNode root, double target) { + if (root == null) { + return; + } + + if (root.val == target) { + result = root.val; + return; + } + + if (Math.abs(root.val - target) == Math.abs(result - target) && root.val < result) { + result = root.val; + } else if (Math.abs(root.val - target) < Math.abs(result - target)) { + result = root.val; + } + + if (root.val < target) { + computeClosestValue(root.right, target); + } else { + computeClosestValue(root.left, target); + } + } +} diff --git a/src/CombinationSum.java b/src/CombinationSum.java new file mode 100644 index 0000000..d9df7e0 --- /dev/null +++ b/src/CombinationSum.java @@ -0,0 +1,32 @@ +// https://leetcode.com/problems/combination-sum +// M = smallest candidate +// T: O(|candidates| ^ (target / M)) +// S: O(target / M) // not sure tho --> if anyone has any idea please feel free to contact me + +import java.util.ArrayList; +import java.util.List; + +public class CombinationSum { + private final List> result = new ArrayList<>(); + private int[] candidates; + private int target; + + public List> combinationSum(int[] candidates, int target) { + this.candidates = candidates; + this.target = target; + combinationSum(new ArrayList<>(), 0, 0); + return result; + } + + public void combinationSum(List current, int sum, int index) { + if (sum == target) { + result.add(current); + return; + } else if (sum > target) return; + for (int i = index ; i < candidates.length ; i++) { + List newCandidate = new ArrayList<>(current); + newCandidate.add(candidates[i]); + combinationSum(newCandidate, sum + candidates[i], i); + } + } +} diff --git a/src/CombinationSumII.java b/src/CombinationSumII.java new file mode 100644 index 0000000..c6cda11 --- /dev/null +++ b/src/CombinationSumII.java @@ -0,0 +1,39 @@ +// https://leetcode.com/problems/combination-sum-ii +// T: O(2^N) +// S: O(N) + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +public class CombinationSumII { + public List> combinationSum2(int[] candidates, int target) { + List> results = new ArrayList<>(); + LinkedList comb = new LinkedList<>(); + Arrays.sort(candidates); + backtrack(candidates, comb, target, 0, results); + return results; + } + + private void backtrack(int[] candidates, LinkedList comb, + int remain, int curr, + List> results) { + if (remain == 0) { + results.add(new ArrayList(comb)); + return; + } + + for (int nextCurr = curr; nextCurr < candidates.length; ++nextCurr) { + if (nextCurr > curr && candidates[nextCurr] == candidates[nextCurr - 1]) + continue; + + int pick = candidates[nextCurr]; + if (remain - pick < 0) break; + + comb.addLast(pick); + backtrack(candidates, comb, remain - pick, nextCurr + 1, results); + comb.removeLast(); + } + } +} diff --git a/src/CombinationSumIII.java b/src/CombinationSumIII.java new file mode 100644 index 0000000..5854615 --- /dev/null +++ b/src/CombinationSumIII.java @@ -0,0 +1,37 @@ +// https://leetcode.com/problems/combination-sum-iii +// T: O(9^k) +// S: O(k) + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +public class CombinationSumIII { + private final List> result = new ArrayList<>(); + private int sum; + + public List> combinationSum3(int k, int n) { + sum = n; + combinationSum(1, Math.min(sum / 2, 9), 0, k - 1, new LinkedList<>()); + return result; + } + + private void combinationSum(int start, int end, int currentSum, int k, LinkedList current) { + if (k == 0) { + if (currentSum < sum && sum - currentSum >= start && sum - currentSum <= 9) { + current.add(sum - currentSum); + result.add(new ArrayList<>(current)); + current.pollLast(); + } + return; + } + + for (int i = start ; i <= end ; i++) { + current.add(i); + currentSum += i; + combinationSum(i + 1, Math.min((sum - currentSum) / 2, 9), currentSum, k - 1, current); + currentSum -= i; + current.pollLast(); + } + } +} diff --git a/src/Combinations.java b/src/Combinations.java new file mode 100644 index 0000000..d2e9f6a --- /dev/null +++ b/src/Combinations.java @@ -0,0 +1,31 @@ +// https://leetcode.com/problems/combinations +// T: O(k * 2^n) +// S: O(k) + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +public class Combinations { + public List> combine(int n, int k) { + final List> result = new ArrayList<>(); + createCombinations(n, k, result); + return result; + } + + private void createCombinations(int n, int k, List> result) { + addCombinations(n, 1, k, result, new LinkedList<>()); + } + + private void addCombinations(int n, int current, int length, List> result, LinkedList combination) { + if (combination.size() == length) { + result.add(new ArrayList<>(combination)); + return; + } + if (current > n) return; + combination.add(current); + addCombinations(n, current + 1, length, result, combination); + combination.removeLast(); + addCombinations(n, current + 1, length, result, combination); + } +} diff --git a/src/CompareVersionNumbers.java b/src/CompareVersionNumbers.java new file mode 100644 index 0000000..52ddbb5 --- /dev/null +++ b/src/CompareVersionNumbers.java @@ -0,0 +1,37 @@ +// https://leetcode.com/problems/compare-version-numbers +// T: O(|v1| + |v2|) +// S: O(v1 + v2) + +import java.util.ArrayList; +import java.util.List; + +public class CompareVersionNumbers { + public static int compareVersion(String version1, String version2) { + final List revisions1 = getRevisions(version1); + final List revisions2 = getRevisions(version2); + return compareVersion(revisions1, revisions2); + } + + public static int compareVersion(List version1, List version2) { + int length = Math.max(version1.size(), version2.size()); + for (int i = 0 ; i < length ; i++){ + if (get(version1, i) < get(version2, i)) return -1; + else if (get(version1, i) > get(version2, i)) return 1; + } + return 0; + } + + private static int get(List list, int index) { + if (index >= list.size()) return 0; + return list.get(index); + } + + private static List getRevisions(String version) { + final String[] revisions = version.split("\\."); + final List result = new ArrayList<>(); + for (String revision : revisions) { + result.add(Integer.parseInt(revision)); + } + return result; + } +} diff --git a/src/ConcatenationOfArray.java b/src/ConcatenationOfArray.java new file mode 100644 index 0000000..b5df06d --- /dev/null +++ b/src/ConcatenationOfArray.java @@ -0,0 +1,12 @@ +// https://leetcode.com/problems/concatenation-of-array +// T: O(N) +// S: O(N) + +public class ConcatenationOfArray { + public int[] getConcatenation(int[] nums) { + final int[] result = new int[nums.length * 2]; + for (int i = 0 ; i < nums.length ; i++) result[i] = nums[i]; + for (int i = nums.length ; i < result.length ; i++) result[i] = nums[i - nums.length]; + return result; + } +} diff --git a/src/ConsecutiveCharacters.java b/src/ConsecutiveCharacters.java new file mode 100644 index 0000000..98f7154 --- /dev/null +++ b/src/ConsecutiveCharacters.java @@ -0,0 +1,15 @@ +public class ConsecutiveCharacters { + public int maxPower(String s) { + int power = 1; + char current = s.charAt(0); + for (int index = 1, frequency = 1 ; index < s.length() ; index++) { + if (s.charAt(index) == current) frequency++; + else { + current = s.charAt(index); + frequency = 1; + } + power = Math.max(power, frequency); + } + return power; + } +} diff --git a/src/ConstructBinaryTreeFromInorderAndPostorderTraversal.java b/src/ConstructBinaryTreeFromInorderAndPostorderTraversal.java new file mode 100644 index 0000000..e43d546 --- /dev/null +++ b/src/ConstructBinaryTreeFromInorderAndPostorderTraversal.java @@ -0,0 +1,34 @@ +// https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal +// T: O(n) +// S: O(n) + +import java.util.HashMap; +import java.util.Map; + +public class ConstructBinaryTreeFromInorderAndPostorderTraversal { + Map inOrderIndices; + int[] postOrder; + + public TreeNode buildTree(int[] inorder, int[] postorder) { + this.inOrderIndices = getIndicesMap(inorder); + this.postOrder = postorder; + return buildTreePostIn(0, inorder.length - 1, 0, postorder.length - 1); + } + + private TreeNode buildTreePostIn(int inOrderStart, int inOrderEnd, int postOrderStart, int postOrderEnd) { + if (postOrderStart > postOrderEnd || inOrderStart > inOrderEnd) return null; + final TreeNode root = new TreeNode(postOrder[postOrderEnd]); + int ri = inOrderIndices.get(postOrder[postOrderEnd]); + root.left = buildTreePostIn(inOrderStart, ri - 1, postOrderStart, postOrderStart + ri - inOrderStart - 1); + root.right = buildTreePostIn(ri + 1, inOrderEnd, postOrderStart + ri - inOrderStart, postOrderEnd - 1); + return root; + } + + private Map getIndicesMap(int[] array) { + final Map result = new HashMap<>(array.length); + for (int index = 0 ; index < array.length ; index++) { + result.put(array[index], index); + } + return result; + } +} diff --git a/src/ConstructBinaryTreeFromPreorderAndInorderTraversal.java b/src/ConstructBinaryTreeFromPreorderAndInorderTraversal.java new file mode 100644 index 0000000..739cd2a --- /dev/null +++ b/src/ConstructBinaryTreeFromPreorderAndInorderTraversal.java @@ -0,0 +1,34 @@ +// https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal +// T: O(n) +// S: O(n) + +import java.util.HashMap; +import java.util.Map; + +public class ConstructBinaryTreeFromPreorderAndInorderTraversal { + int preOrderIndex = 0; + Map inOrderIndices; + + public TreeNode buildTree(int[] preorder, int[] inorder) { + inOrderIndices = buildValueToIndexMap(inorder); + return buildTree(preorder, inorder, 0, preorder.length); + } + + private TreeNode buildTree(int[] preOrder, int[] inOrder, int start, int end) { + if (start == end) return null; + + int inOrderIndex = inOrderIndices.get(preOrder[preOrderIndex]); + final TreeNode root = new TreeNode(preOrder[preOrderIndex++]); + root.left = buildTree(preOrder, inOrder, start, inOrderIndex); + root.right = buildTree(preOrder, inOrder, inOrderIndex + 1, end); + return root; + } + + private Map buildValueToIndexMap(int[] array) { + final Map result = new HashMap<>(); + for (int index = 0 ; index < array.length ; index++) { + result.put(array[index], index); + } + return result; + } +} diff --git a/src/ConstructStringFromBinaryTree.java b/src/ConstructStringFromBinaryTree.java new file mode 100644 index 0000000..33f6904 --- /dev/null +++ b/src/ConstructStringFromBinaryTree.java @@ -0,0 +1,8 @@ +public class ConstructStringFromBinaryTree { + public String tree2str(TreeNode root) { + if (root == null) return ""; + if (root.left == null && root.right == null) return root.val + ""; + return root.val + "(" + tree2str(root.left) + ")" + + (root.right == null ? "" : "(" + tree2str(root.right) + ")"); + } +} diff --git a/src/ContainerWitMostWater.java b/src/ContainerWitMostWater.java new file mode 100644 index 0000000..d2d1a3a --- /dev/null +++ b/src/ContainerWitMostWater.java @@ -0,0 +1,15 @@ +// https://leetcode.com/problems/container-with-most-water +// T: O(n) +// S: O(1) + +public class ContainerWitMostWater { + public static int maxArea(int[] height) { + int water = 0; + for (int i = 0, j = height.length - 1; i < j; ) { + water = Math.max(water, Math.min(height[i], height[j]) * (j - i)); + if (height[i] > height[j]) j--; + else i++; + } + return water; + } +} diff --git a/src/ContainsDuplicate.java b/src/ContainsDuplicate.java index 9a1571e..fe925c7 100644 --- a/src/ContainsDuplicate.java +++ b/src/ContainsDuplicate.java @@ -1,3 +1,7 @@ +// https://leetcode.com/problems/contains-duplicate +// T: O(N) +// S: O(N) + import java.util.HashSet; import java.util.Set; diff --git a/src/ContainsDuplicateIII.java b/src/ContainsDuplicateIII.java new file mode 100644 index 0000000..1acbb60 --- /dev/null +++ b/src/ContainsDuplicateIII.java @@ -0,0 +1,34 @@ +// https://leetcode.com/problems/contains-duplicate-iii +// T: O(N) +// S: O(N) + +import java.util.HashMap; +import java.util.Map; + +public class ContainsDuplicateIII { + + private long getID(long i, long w) { + return i < 0 ? (i + 1) / w - 1 : i / w; + } + + public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { + if (k == 0) return false; + + final Map buckets = new HashMap<>(); + final long w = (long) t + 1; + + for (int i = 0; i < nums.length; ++i) { + long m = getID(nums[i], w); + if (buckets.containsKey(m)) + return true; + if (buckets.containsKey(m - 1) && Math.abs(nums[i] - buckets.get(m - 1)) < w) + return true; + if (buckets.containsKey(m + 1) && Math.abs(nums[i] - buckets.get(m + 1)) < w) + return true; + buckets.put(m, (long)nums[i]); + if (i >= k) buckets.remove(getID(nums[i - k], w)); + } + + return false; + } +} diff --git a/src/Convert1DArrayInto2DArray.java b/src/Convert1DArrayInto2DArray.java new file mode 100644 index 0000000..5930be3 --- /dev/null +++ b/src/Convert1DArrayInto2DArray.java @@ -0,0 +1,16 @@ +// https://leetcode.com/problems/convert-1d-array-into-2d-array +// T: O(n * m) +// S: O(n * m) + +public class Convert1DArrayInto2DArray { + public int[][] construct2DArray(int[] original, int m, int n) { + if (m * n != original.length) return new int[0][]; + final int[][] result = new int[m][n]; + for (int i = 0 ; i < m ; i++) { + for (int j = 0 ; j < n ; j++) { + result[i][j] = original[n * i + j]; + } + } + return result; + } +} diff --git a/src/ConvertBSTToGreaterTree.java b/src/ConvertBSTToGreaterTree.java new file mode 100644 index 0000000..005ef91 --- /dev/null +++ b/src/ConvertBSTToGreaterTree.java @@ -0,0 +1,15 @@ +public class ConvertBSTToGreaterTree { + int value = 0; + + public TreeNode convertBST(TreeNode root) { + computeGreaterTree(root); + return root; + } + + private void computeGreaterTree(TreeNode root) { + if (root == null) return; + computeGreaterTree(root.right); + root.val += value; + computeGreaterTree(root.left); + } +} diff --git a/src/ConvertBinaryNumberInLinkedListToInteger.java b/src/ConvertBinaryNumberInLinkedListToInteger.java new file mode 100644 index 0000000..d3cc201 --- /dev/null +++ b/src/ConvertBinaryNumberInLinkedListToInteger.java @@ -0,0 +1,11 @@ +public class ConvertBinaryNumberInLinkedListToInteger { + public int getDecimalValue(ListNode head) { + int value = 0; + while (head != null) { + value <<= 1; + value += head.val; + head = head.next; + } + return value; + } +} diff --git a/src/ConvertIntegerToTheSumOfTwoNoZeroIntegers.java b/src/ConvertIntegerToTheSumOfTwoNoZeroIntegers.java new file mode 100644 index 0000000..9d5aa3f --- /dev/null +++ b/src/ConvertIntegerToTheSumOfTwoNoZeroIntegers.java @@ -0,0 +1,18 @@ +public class ConvertIntegerToTheSumOfTwoNoZeroIntegers { + public int[] getNoZeroIntegers(int n) { + for (int i = 1 ; i <= n / 2 ; i++) { + if (isNonZeroInteger(i) && isNonZeroInteger(n - i)) { + return new int[] {i, n - i}; + } + } + return new int[0]; + } + + private boolean isNonZeroInteger(int n) { + while (n > 0) { + if (n % 10 == 0) return false; + n /= 10; + } + return true; + } +} diff --git a/src/ConvertSortedArrayToBinarySearchTree.java b/src/ConvertSortedArrayToBinarySearchTree.java index db17b39..2d1aa2d 100644 --- a/src/ConvertSortedArrayToBinarySearchTree.java +++ b/src/ConvertSortedArrayToBinarySearchTree.java @@ -1,19 +1,4 @@ public class ConvertSortedArrayToBinarySearchTree { - private static class TreeNode { - int val; - TreeNode left; - TreeNode right; - - TreeNode(int val) { - this.val = val; - } - - TreeNode(int val, TreeNode left, TreeNode right) { - this.val = val; - this.left = left; - this.right = right; - } - } public static TreeNode sortedArrayToBST(int[] array) { return sortedArrayToBST(array, 0, array.length); diff --git a/src/ConvertSortedListToBinarySearchTree.java b/src/ConvertSortedListToBinarySearchTree.java new file mode 100644 index 0000000..d485735 --- /dev/null +++ b/src/ConvertSortedListToBinarySearchTree.java @@ -0,0 +1,36 @@ +// https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree +// T: O(n) +// S: O(n) + +import java.util.ArrayList; +import java.util.List; + +public class ConvertSortedListToBinarySearchTree { + public TreeNode sortedListToBST(ListNode head) { + final List list = toList(head); + return listToBST(list); + } + + private TreeNode listToBST(List list) { + return listToBST(list, 0, list.size()); + } + + private TreeNode listToBST(List list, int start, int end) { + if (start == end) return null; + + final int middle = start + (end - start) / 2; + final TreeNode root = new TreeNode(list.get(middle)); + root.left = listToBST(list, start, middle); + root.right = listToBST(list, middle + 1, end); + return root; + } + + private List toList(ListNode head) { + final List result = new ArrayList<>(); + while (head != null) { + result.add(head.val); + head = head.next; + } + return result; + } +} diff --git a/src/ConvertTheTemperature.java b/src/ConvertTheTemperature.java new file mode 100644 index 0000000..bed0850 --- /dev/null +++ b/src/ConvertTheTemperature.java @@ -0,0 +1,17 @@ +// https://leetcode.com/problems/convert-the-temperature +// T: O(1) +// S: O(1) + +public class ConvertTheTemperature { + public double[] convertTemperature(double celsius) { + return new double[] { celsiusToKelvin(celsius), celsiusToFahrenheit(celsius) }; + } + + private double celsiusToFahrenheit(double celsius) { + return celsius * 1.8 + 32.00; + } + + private double celsiusToKelvin(double celsius) { + return celsius + 273.15; + } +} diff --git a/src/CopyListWithRandomPointer.java b/src/CopyListWithRandomPointer.java new file mode 100644 index 0000000..9be7db0 --- /dev/null +++ b/src/CopyListWithRandomPointer.java @@ -0,0 +1,57 @@ +// https://leetcode.com/problems/copy-list-with-random-pointer +// T: O(N) +// S: O(1) + +import java.util.HashMap; +import java.util.Map; + +public class CopyListWithRandomPointer { + public static final class Node { + int val; + Node next; + Node random; + + public Node(int val) { + this.val = val; + this.next = null; + this.random = null; + } + } + + public Node copyRandomList(Node head) { + if (head == null) { + return null; + } + + createWeavedList(head); + linkRandomPointersForNewNodes(head); + return unweaveList(head); + } + + // A->B->C --> A->A'->B->B' + private static void createWeavedList(Node head) { + for (Node i = head; i != null ; i = i.next.next) { + Node newNode = new Node(i.val); + newNode.next = i.next; + i.next = newNode; + } + } + + private static void linkRandomPointersForNewNodes(Node head) { + for (Node i = head; i != null ; i = i.next.next) { + if (i.random == null) { + continue; + } + i.next.random = i.random.next; + } + } + + private static Node unweaveList(Node head) { + final Node pointerNew = head.next; + for (Node old = head, i = head.next; i != null && old != null ; i = i.next, old = old.next) { + old.next = old.next == null ? null : old.next.next; + i.next = i.next == null ? null : i.next.next; + } + return pointerNew; + } +} diff --git a/src/CountAndSay.java b/src/CountAndSay.java index 25606f7..7bea157 100644 --- a/src/CountAndSay.java +++ b/src/CountAndSay.java @@ -1,6 +1,5 @@ import java.util.ArrayList; import java.util.List; -import java.util.Scanner; public class CountAndSay { private static String countAndSay(int number) { diff --git a/src/CountAsterisks.java b/src/CountAsterisks.java new file mode 100644 index 0000000..f164cfa --- /dev/null +++ b/src/CountAsterisks.java @@ -0,0 +1,26 @@ +// https://leetcode.com/problems/count-asterisks +// T: O(|s|) +// S: O(1) + +public class CountAsterisks { + public int countAsterisks(String s) { + boolean seenPipe = false; + int count = 0, pipeBuffer = 0; + + for (int index = 0 ; index < s.length() ; index++) { + if (s.charAt(index) == '|') { + if (seenPipe) { + pipeBuffer = 0; + } + seenPipe = !seenPipe; + } + + if (s.charAt(index) == '*') { + if (seenPipe) pipeBuffer++; + else count++; + } + } + + return count + pipeBuffer; + } +} diff --git a/src/CountBinarySubstrings.java b/src/CountBinarySubstrings.java new file mode 100644 index 0000000..3934446 --- /dev/null +++ b/src/CountBinarySubstrings.java @@ -0,0 +1,13 @@ +public class CountBinarySubstrings { + public int countBinarySubstrings(String string) { + int binarySubStrings = 0, prev = 0, current = 1; + for (int index = 1 ; index < string.length() ; index++) { + if (string.charAt(index - 1) != string.charAt(index)) { + binarySubStrings += Math.min(prev, current); + prev = current; + current = 1; + } else current++; + } + return binarySubStrings + Math.min(prev, current); + } +} diff --git a/src/CountCommonWordsWithOneOccurrence.java b/src/CountCommonWordsWithOneOccurrence.java new file mode 100644 index 0000000..1e9bf77 --- /dev/null +++ b/src/CountCommonWordsWithOneOccurrence.java @@ -0,0 +1,28 @@ +// https://leetcode.com/problems/count-common-words-with-one-occurrence +// T: O(|words1| + |words2|) +// S: O(|words1| + |words2|) + +import java.util.HashMap; +import java.util.Map; + +public class CountCommonWordsWithOneOccurrence { + public int countWords(String[] words1, String[] words2) { + final Map words1Frequency = getFrequencies(words1); + final Map words2Frequency = getFrequencies(words2); + int words = 0; + for (Map.Entry entry: words1Frequency.entrySet()) { + if (entry.getValue() == 1 && words2Frequency.getOrDefault(entry.getKey(), 0) == 1) { + words++; + } + } + return words; + } + + private Map getFrequencies(String[] array) { + final Map frequencies = new HashMap<>(); + for (String s : array) { + frequencies.put(s, frequencies.getOrDefault(s, 0) + 1); + } + return frequencies; + } +} diff --git a/src/CountCompleteTreeNodes.java b/src/CountCompleteTreeNodes.java new file mode 100644 index 0000000..0a1176f --- /dev/null +++ b/src/CountCompleteTreeNodes.java @@ -0,0 +1,48 @@ +// https://leetcode.com/problems/count-complete-tree-nodes +// T: O(log(n) ^ 2) +// S: O(log(n)) + +public class CountCompleteTreeNodes { + public int countNodes(TreeNode root) { + if (root == null) { + return 0; + } + + final int depth = depthTree(root) - 1; + if (depth == 0) { + return 1; + } + + int left = 0, right = (int) Math.pow(2, depth) - 1, middle; + while (left <= right) { + middle = left + (right - left) / 2; + if (exists(root, depth, middle)) left = middle + 1; + else right = middle - 1; + } + + return (int) Math.pow(2, depth) - 1 + left; + } + + private static boolean exists(TreeNode root, int depth, int index) { + TreeNode current = root; + int value = -1; + for (int i = 0 ; i < depth ; i++) { + final int middle = (int) Math.pow(2, depth - 1 - i); + if (index > value + middle) { + current = current.right; + value += middle; + } else { + current = current.left; + } + } + return current != null; + } + + private static int depthTree(TreeNode root) { + if (root == null) { + return 0; + } + + return 1 + Math.max(depthTree(root.left), depthTree(root.right)); + } +} diff --git a/src/CountDaysSpentTogether.java b/src/CountDaysSpentTogether.java new file mode 100644 index 0000000..9c018d4 --- /dev/null +++ b/src/CountDaysSpentTogether.java @@ -0,0 +1,23 @@ +// https://leetcode.com/problems/count-days-spent-together +// T: O(1) +// S: O(1) + +import java.time.LocalDate; + +public class CountDaysSpentTogether { + public int countDaysTogether(String arriveAlice, String leaveAlice, String arriveBob, String leaveBob){ + final long aliceArrive = getEpochDay(arriveAlice); + final long aliceLeave = getEpochDay(leaveAlice); + final long bobArrive = getEpochDay(arriveBob); + final long bobLeave = getEpochDay(leaveBob); + + //No intersection of days + if(aliceLeave < bobArrive || bobLeave < aliceArrive) return 0; + + return (int) ((Math.min(aliceLeave, bobLeave) - Math.max(aliceArrive, bobArrive)) + 1); + } + + private long getEpochDay(String mmDD) { + return LocalDate.of(2021,Integer.parseInt(mmDD.substring(0,2)),Integer.parseInt(mmDD.substring(3,5))).toEpochDay(); + } +} diff --git a/src/CountDistinctNumbersOnBoard.java b/src/CountDistinctNumbersOnBoard.java new file mode 100644 index 0000000..0924043 --- /dev/null +++ b/src/CountDistinctNumbersOnBoard.java @@ -0,0 +1,10 @@ +// https://leetcode.com/problems/count-distinct-numbers-on-board +// T: O(1) +// S: O(1) + +public class CountDistinctNumbersOnBoard { + public int distinctIntegers(int n) { + if (n <= 2) return 0; + return n - 1; + } +} diff --git a/src/CountElementsWithMaximumFrequency.java b/src/CountElementsWithMaximumFrequency.java new file mode 100644 index 0000000..6671636 --- /dev/null +++ b/src/CountElementsWithMaximumFrequency.java @@ -0,0 +1,36 @@ +// https://leetcode.com/problems/count-elements-with-maximum-frequency +// T: O(N) +// S: O(N) + +import java.util.HashMap; +import java.util.Map; + +public class CountElementsWithMaximumFrequency { + public int maxFrequencyElements(int[] array) { + final Map frequencies = computeFrequencies(array); + final int maxFrequency = getMaxFrequency(frequencies); + return numberOfElementsWithFrequency(frequencies, maxFrequency); + } + + private static Map computeFrequencies(int[] array) { + final Map map = new HashMap<>(); + for (int element : array) { + map.put(element, map.getOrDefault(element, 0) + 1); + } + return map; + } + + private static int getMaxFrequency(final Map frequencies) { + return frequencies.values().stream().max(Integer::compareTo).get(); + } + + private static int numberOfElementsWithFrequency(Map frequencies, int frequency) { + int sum = 0; + for (Map.Entry entry : frequencies.entrySet()) { + if (entry.getValue() == frequency) { + sum += frequency; + } + } + return sum; + } +} diff --git a/src/CountElementsWithStrictlySmallerAndGreaterElements.java b/src/CountElementsWithStrictlySmallerAndGreaterElements.java new file mode 100644 index 0000000..da0300f --- /dev/null +++ b/src/CountElementsWithStrictlySmallerAndGreaterElements.java @@ -0,0 +1,16 @@ +// https://leetcode.com/problems/count-elements-with-strictly-smaller-and-greater-elements +// T: O(n log(n)) +// S: O(log(n)) + +import java.util.Arrays; + +public class CountElementsWithStrictlySmallerAndGreaterElements { + public int countElements(int[] nums) { + Arrays.sort(nums); + int count = 0; + for (int index = 1 ; index < nums.length - 1 ; index++) { + if (nums[0] != nums[index] && nums[index] != nums[nums.length - 1]) count++; + } + return count; + } +} diff --git a/src/CountEqualAndDivisiblePairsInAnArray.java b/src/CountEqualAndDivisiblePairsInAnArray.java new file mode 100644 index 0000000..37cd998 --- /dev/null +++ b/src/CountEqualAndDivisiblePairsInAnArray.java @@ -0,0 +1,15 @@ +// https://leetcode.com/problems/count-equal-and-divisible-pairs-in-an-array +// T: O(n^2) +// S: O(1) + +public class CountEqualAndDivisiblePairsInAnArray { + public int countPairs(int[] nums, int k) { + int pairs = 0; + for (int i = 0 ; i < nums.length ; i ++) { + for (int j = i + 1 ; j < nums.length ; j++) { + if (nums[i] == nums[j] && (i * j) % k == 0) pairs++; + } + } + return pairs; + } +} diff --git a/src/CountGoodTriplets.java b/src/CountGoodTriplets.java new file mode 100644 index 0000000..475c29d --- /dev/null +++ b/src/CountGoodTriplets.java @@ -0,0 +1,19 @@ +// https://leetcode.com/problems/count-good-triplets +// T: O(n^3) +// S: O(1) + +public class CountGoodTriplets { + public int countGoodTriplets(int[] arr, int a, int b, int c) { + int goodTriplets = 0; + for (int i = 0 ; i < arr.length ; i++) { + for (int j = i + 1 ; j < arr.length ; j++) { + for (int k = j + 1 ; k < arr.length ; k++) { + if (Math.abs(arr[i] - arr[j]) <= a && Math.abs(arr[j] - arr[k]) <= b && Math.abs(arr[i] - arr[k]) <= c) { + goodTriplets++; + } + } + } + } + return goodTriplets; + } +} diff --git a/src/CountHillsAndValleysInAnArray.java b/src/CountHillsAndValleysInAnArray.java new file mode 100644 index 0000000..7744a5e --- /dev/null +++ b/src/CountHillsAndValleysInAnArray.java @@ -0,0 +1,14 @@ +// https://leetcode.com/problems/count-hills-and-valleys-in-an-array + +public class CountHillsAndValleysInAnArray { + public int countHillValley(int[] array) { + int result = 0, left = array[0]; + for (int index = 1 ; index < array.length - 1; index++) { + if ((left < array[index] && array[index] > array[index + 1]) || (left > array[index] && array[index] < array[index + 1])) { + result++; + left = array[index]; + } + } + return result; + } +} diff --git a/src/CountIntegersWithEvenDigitSum.java b/src/CountIntegersWithEvenDigitSum.java new file mode 100644 index 0000000..fd33346 --- /dev/null +++ b/src/CountIntegersWithEvenDigitSum.java @@ -0,0 +1,14 @@ +// https://leetcode.com/problems/count-integers-with-even-digit-sum +// T: O(1) +// S: O(1) + +public class CountIntegersWithEvenDigitSum { + public int countEven(int num) { + final int group = num / 10; + return 5 * group - 1 + (num % 10 + 1 + series(group)) / 2; + } + + private int series(int group) { + return (group % 10 + (group % 100) / 10 + (group % 1000) / 100 + 1) % 2; + } +} diff --git a/src/CountItemsMatchingARule.java b/src/CountItemsMatchingARule.java new file mode 100644 index 0000000..741ad54 --- /dev/null +++ b/src/CountItemsMatchingARule.java @@ -0,0 +1,24 @@ +import java.util.List; + +public class CountItemsMatchingARule { + public int countMatches(List> items, String ruleKey, String ruleValue) { + return countMatches(items, getRuleIndex(ruleKey), ruleValue); + } + + private int countMatches(List> items, int ruleIndex, String ruleValue) { + int matches = 0; + for (List item : items) { + if (item.get(ruleIndex).equals(ruleValue)) matches++; + } + return matches; + } + + private int getRuleIndex(String key) { + return switch (key) { + case "type" -> 0; + case "color" -> 1; + case "name" -> 2; + default -> -1; + }; + } +} diff --git a/src/CountLargestGroup.java b/src/CountLargestGroup.java new file mode 100644 index 0000000..70c940f --- /dev/null +++ b/src/CountLargestGroup.java @@ -0,0 +1,36 @@ +import java.util.HashMap; +import java.util.Map; + +public class CountLargestGroup { + public int countLargestGroup(int n) { + Map sumOfDigitsFrequencies = getFrequenciesOfSumOfDigits(n); + int largestGroupSize = 0, largestGroupFrequency = 0; + for (int groupSize : sumOfDigitsFrequencies.values()) { + if (groupSize > largestGroupSize) { + largestGroupSize = groupSize; + largestGroupFrequency = 1; + } else if (largestGroupSize == groupSize) { + largestGroupFrequency++; + } + } + return largestGroupFrequency; + } + + private Map getFrequenciesOfSumOfDigits(int N) { + Map frequencies = new HashMap<>(); + for (int number = 1 ; number <= N ; number++) { + int sumOfDigits = sumOfDigits(number); + frequencies.put(sumOfDigits, frequencies.getOrDefault(sumOfDigits, 0) + 1); + } + return frequencies; + } + + private int sumOfDigits(int number) { + int sum = 0; + while (number > 0) { + sum += number % 10; + number /= 10; + } + return sum; + } +} diff --git a/src/CountNegativeNumbersInSortedMatrix.java b/src/CountNegativeNumbersInSortedMatrix.java new file mode 100644 index 0000000..cad7784 --- /dev/null +++ b/src/CountNegativeNumbersInSortedMatrix.java @@ -0,0 +1,17 @@ +public class CountNegativeNumbersInSortedMatrix { + public int countNegatives(int[][] grid) { + final int rows = grid.length, columns = grid[0].length; + int negativeNumbers = 0, negativeColumnIndex = columns; + for (int[] row : grid) { + negativeNumbers += columns; + for (int column = 0 ; column < negativeColumnIndex ; column++) { + if (row[column] < 0) { + negativeColumnIndex = column; + break; + } + negativeNumbers--; + } + } + return negativeNumbers; + } +} diff --git a/src/CountNumberOfPairsWithAbsoluteDifferenceK.java b/src/CountNumberOfPairsWithAbsoluteDifferenceK.java new file mode 100644 index 0000000..52b6ede --- /dev/null +++ b/src/CountNumberOfPairsWithAbsoluteDifferenceK.java @@ -0,0 +1,19 @@ +// https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k +// T: O(N) +// S: O(N) + +import java.util.HashMap; +import java.util.Map; + +public class CountNumberOfPairsWithAbsoluteDifferenceK { + public int countKDifference(int[] nums, int k) { + final Map frequency = new HashMap<>(); + int pairs = 0; + for (int element : nums) { + pairs += frequency.getOrDefault(element - k, 0); + pairs += frequency.getOrDefault(element + k, 0); + frequency.put(element, frequency.getOrDefault(element, 0) + 1); + } + return pairs; + } +} diff --git a/src/CountOddNumbersInIntervalRange.java b/src/CountOddNumbersInIntervalRange.java new file mode 100644 index 0000000..56fadc0 --- /dev/null +++ b/src/CountOddNumbersInIntervalRange.java @@ -0,0 +1,7 @@ +public class CountOddNumbersInIntervalRange { + public int countOdds(int low, int high) { + final int count = high - low + 1; + if ((count & 1) == 0) return count / 2; + return count / 2 + (low & 1); + } +} diff --git a/src/CountOfMatchesInTournament.java b/src/CountOfMatchesInTournament.java new file mode 100644 index 0000000..9c2ce71 --- /dev/null +++ b/src/CountOfMatchesInTournament.java @@ -0,0 +1,10 @@ +// https://leetcode.com/problems/count-of-matches-in-tournament +// T: O(log N) +// S: O(log N) + +public class CountOfMatchesInTournament { + public int numberOfMatches(int n) { + if (n == 1) return 0; + return n / 2 + numberOfMatches(n - n / 2); + } +} diff --git a/src/CountOperationsToObtainZero.java b/src/CountOperationsToObtainZero.java new file mode 100644 index 0000000..9d0109c --- /dev/null +++ b/src/CountOperationsToObtainZero.java @@ -0,0 +1,16 @@ +// https://leetcode.com/problems/count-operations-to-obtain-zero +// T: O(max(a, b)) +// S: O(1) + +public class CountOperationsToObtainZero { + public int countOperations(int num1, int num2) { + int operations = 0; + while (num1 != 0 && num2 != 0) { + operations++; + if (num1 >= num2) { + num1 -= num2; + } else num2 -= num1; + } + return operations; + } +} diff --git a/src/CountPairsOfSimilarStrings.java b/src/CountPairsOfSimilarStrings.java new file mode 100644 index 0000000..ab5ef27 --- /dev/null +++ b/src/CountPairsOfSimilarStrings.java @@ -0,0 +1,29 @@ +// https://leetcode.com/problems/count-pairs-of-similar-strings +// T: O(|words| * |words[i]|) +// S: O(|words|) + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class CountPairsOfSimilarStrings { + public int similarPairs(String[] words) { + Map, Integer> frequency = new HashMap<>(); + int pairs = 0; + for (String word : words) { + final Set letters = getLetters(word); + pairs += frequency.getOrDefault(letters, 0); + frequency.put(letters, frequency.getOrDefault(letters, 0) + 1); + } + return pairs; + } + + private Set getLetters(String word) { + final Set set = new HashSet<>(); + for (int index = 0 ; index < word.length() ; index++) { + set.add(word.charAt(index)); + } + return set; + } +} diff --git a/src/CountPairsThatFormACompleteDayI.java b/src/CountPairsThatFormACompleteDayI.java new file mode 100644 index 0000000..16fe939 --- /dev/null +++ b/src/CountPairsThatFormACompleteDayI.java @@ -0,0 +1,22 @@ +// https://leetcode.com/problems/count-pairs-that-form-a-complete-day-i +// T: O(N) +// S: O(N) + +import java.util.HashMap; +import java.util.Map; + +public class CountPairsThatFormACompleteDayI { + public int countCompleteDayPairs(int[] hours) { + final Map frequencies = new HashMap<>(); + int pairs = 0; + + for (int element : hours) { + int required = (24 - (element % 24)) % 24; + int current = element % 24; + pairs += frequencies.getOrDefault(required, 0); + frequencies.put(current, frequencies.getOrDefault(current, 0) + 1); + } + + return pairs; + } +} diff --git a/src/CountPairsWhoseSumIsLessThanTarget.java b/src/CountPairsWhoseSumIsLessThanTarget.java new file mode 100644 index 0000000..25c2f1e --- /dev/null +++ b/src/CountPairsWhoseSumIsLessThanTarget.java @@ -0,0 +1,21 @@ +// https://leetcode.com/problems/count-pairs-whose-sum-is-less-than-target/description +// T: O(NlogN) +// S: O(logN) + +import java.util.List; + +public class CountPairsWhoseSumIsLessThanTarget { + public int countPairs(List nums, int target) { + int pairs = 0; + nums.sort(Integer::compareTo); + for (int i = 0, j = nums.size() - 1 ; i < j ; ) { + if (nums.get(i) + nums.get(j) < target) { + pairs += j - i; + i++; + } else { + j--; + } + } + return pairs; + } +} diff --git a/src/CountPrefixAndSuffixPairsI.java b/src/CountPrefixAndSuffixPairsI.java new file mode 100644 index 0000000..c53fb4b --- /dev/null +++ b/src/CountPrefixAndSuffixPairsI.java @@ -0,0 +1,39 @@ +// https://leetcode.com/problems/count-prefix-and-suffix-pairs-i +// T: O(|words|^2 * |words[i].length|) +// S: O(1) + +public class CountPrefixAndSuffixPairsI { + public int countPrefixSuffixPairs(String[] words) { + int pairs = 0; + for (int i = 0 ; i < words.length ; i++) { + for (int j = i + 1 ; j < words.length ; j++) { + if (isPrefixAndSuffix(words[i], words[j])) { + pairs++; + } + } + } + return pairs; + } + + private static boolean isPrefixAndSuffix(String a, String b) { + if (a.length() > b.length()) { + return false; + } + + // prefix + for (int i = 0 ; i < a.length() ; i++) { + if (a.charAt(i) != b.charAt(i)) { + return false; + } + } + + //suffix + for (int i = 0; i < a.length() ; i++) { + if (a.charAt(i) != b.charAt(b.length() - a.length() + i)) { + return false; + } + } + + return true; + } +} diff --git a/src/CountPrefixesOfAGivenString.java b/src/CountPrefixesOfAGivenString.java new file mode 100644 index 0000000..7c20c35 --- /dev/null +++ b/src/CountPrefixesOfAGivenString.java @@ -0,0 +1,13 @@ +// https://leetcode.com/problems/count-prefixes-of-a-given-string +// T: O(|words| * |s|) +// S: O(1) + +public class CountPrefixesOfAGivenString { + public int countPrefixes(String[] words, String s) { + int result = 0; + for (String word : words) { + if (s.startsWith(word)) result++; + } + return result; + } +} diff --git a/src/CountPrimes.java b/src/CountPrimes.java index 90fbbbf..f9cbbf0 100644 --- a/src/CountPrimes.java +++ b/src/CountPrimes.java @@ -1,3 +1,7 @@ +// https://leetcode.com/problems/count-primes +// T: O(n log(log(n))) +// S: O(n) + public class CountPrimes { public static int countPrimes(int number) { diff --git a/src/CountSpecialQuadruplets.java b/src/CountSpecialQuadruplets.java new file mode 100644 index 0000000..870bcc7 --- /dev/null +++ b/src/CountSpecialQuadruplets.java @@ -0,0 +1,27 @@ +// https://leetcode.com/problems/count-special-quadruplets +// T: O(N^2) +// S: O(N^2) + +import java.util.HashMap; +import java.util.Map; + +public class CountSpecialQuadruplets { + public int countQuadruplets(int[] nums) { + final Map differenceFreq = new HashMap<>(); + differenceFreq.put(nums[nums.length -1] - nums[nums.length - 2], 1); + int quadruplets = 0; + + for (int b = nums.length - 3 ; b > 0 ; b--) { + for (int a = b - 1 ; a >= 0 ; a--) { + quadruplets += differenceFreq.getOrDefault(nums[a] + nums[b], 0); + } + + for (int x = b + 1 ; x < nums.length ; x++) { + int difference = nums[x] - nums[b]; + differenceFreq.put(difference, differenceFreq.getOrDefault(difference, 0) + 1); + } + } + + return quadruplets; + } +} diff --git a/src/CountSquareSumTriplets.java b/src/CountSquareSumTriplets.java new file mode 100644 index 0000000..055079f --- /dev/null +++ b/src/CountSquareSumTriplets.java @@ -0,0 +1,16 @@ +// https://leetcode.com/problems/count-square-sum-triples +// T: O(n ^ 2) +// S: O(1) + +public class CountSquareSumTriplets { + public int countTriples(int n) { + int triplets = 0; + for (int i = 1 ; i <= n - 2 ; i++) { + for (int j = i + 1 ; j <= n - 1 ; j++) { + int sqrt = (int) Math.sqrt(i * i + j * j); + if (sqrt <= n && sqrt * sqrt == i * i + j * j) triplets++; + } + } + return 2 * triplets; + } +} diff --git a/src/CountSymmetricIntegers.java b/src/CountSymmetricIntegers.java new file mode 100644 index 0000000..6b5f692 --- /dev/null +++ b/src/CountSymmetricIntegers.java @@ -0,0 +1,33 @@ +// https://leetcode.com/problems/count-symmetric-integers +// T: O(N) +// S: O(1) + +public class CountSymmetricIntegers { + public int countSymmetricIntegers(int low, int high) { + int count = 0; + for (int start = low ; start <= high ; start++) { + final String number = start + ""; + if (isSymmetric(number)) { + count++; + } + } + return count; + } + + private static boolean isSymmetric(String number) { + if (number.length() % 2 != 0) { + return false; + } + final String firstHalf = number.substring(0, number.length() / 2); + final String secondHalf = number.substring(number.length() / 2); + return sumOfDigits(firstHalf) == sumOfDigits(secondHalf); + } + + private static int sumOfDigits(final String number) { + int sum = 0; + for (int i = 0 ; i < number.length() ; i++) { + sum += number.charAt(i) - '0'; + } + return sum; + } +} diff --git a/src/CountTestedDevicesAfterTestOperations.java b/src/CountTestedDevicesAfterTestOperations.java new file mode 100644 index 0000000..e5086f5 --- /dev/null +++ b/src/CountTestedDevicesAfterTestOperations.java @@ -0,0 +1,16 @@ +// https://leetcode.com/problems/count-tested-devices-after-test-operations +// T: O(N) +// S: O(1) + +public class CountTestedDevicesAfterTestOperations { + public int countTestedDevices(int[] batteryPercentages) { + int testedDevices = 0; + for (int percentage : batteryPercentages) { + if (percentage - testedDevices > 0) { + testedDevices++; + } + } + + return testedDevices; + } +} diff --git a/src/CountTheDigitsThatDivideANumber.java b/src/CountTheDigitsThatDivideANumber.java new file mode 100644 index 0000000..861e170 --- /dev/null +++ b/src/CountTheDigitsThatDivideANumber.java @@ -0,0 +1,15 @@ +// https://leetcode.com/problems/count-the-digits-that-divide-a-number +// T: O(log(N)) +// S: O(1) + +public class CountTheDigitsThatDivideANumber { + public int countDigits(int num) { + final String number = num + ""; + int divisors = 0; + for (int index = 0 ; index < number.length() ; index++) { + int digit = number.charAt(index) - '0'; + if (num % digit == 0) divisors++; + } + return divisors; + } +} diff --git a/src/CountTheNumberOfConsistentStrings.java b/src/CountTheNumberOfConsistentStrings.java new file mode 100644 index 0000000..d29f7ef --- /dev/null +++ b/src/CountTheNumberOfConsistentStrings.java @@ -0,0 +1,35 @@ +// T: O(allowed + words * word) +// S: O(allowed) + +import java.util.HashSet; +import java.util.Set; + +public class CountTheNumberOfConsistentStrings { + public int countConsistentStrings(String allowed, String[] words) { + final Set allowedCharacters = getCharacters(allowed); + int consistentStrings = 0; + for (String word :words) { + if (allCharsPresentIn(word, allowedCharacters)) { + consistentStrings++; + } + } + return consistentStrings; + } + + private Set getCharacters(String string) { + final Set set = new HashSet<>(); + for (int index = 0 ; index < string.length() ; index++) { + set.add(string.charAt(index)); + } + return set; + } + + private boolean allCharsPresentIn(String string, Set allowedChars) { + for (int index = 0 ; index < string.length() ; index++) { + if (!allowedChars.contains(string.charAt(index))) { + return false; + } + } + return true; + } +} diff --git a/src/CountTheNumberOfIncremovableSubarraysI.java b/src/CountTheNumberOfIncremovableSubarraysI.java new file mode 100644 index 0000000..0956657 --- /dev/null +++ b/src/CountTheNumberOfIncremovableSubarraysI.java @@ -0,0 +1,45 @@ +// https://leetcode.com/problems/count-the-number-of-incremovable-subarrays-i +// T: O(N^3) +// S: O(1) + +import java.util.Enumeration; + +public class CountTheNumberOfIncremovableSubarraysI { + public static int incremovableSubarrayCount(int[] array) { + int numberIncremovableSubarrays = 0; + for (int i = 0 ; i < array.length ; i++) { + for (int j = i ; j < array.length ; j++) { + // we consider subarray [i,j] and check for array - subarray whether it is strictly + // increasing or not + if (isStrictlyIncreasing(array, i, j)) { + numberIncremovableSubarrays += array.length - (i == j ? i : j); + break; + } + } + } + + return numberIncremovableSubarrays; + } + + private static boolean isStrictlyIncreasing(int[] array, int i, int j) { + for (int index = 0, previous = -1 ; index < array.length ; index++) { + if (index == i) { + index = j; + continue; + } + if (previous == -1) { + previous = array[index]; + continue; + } + if (array[index] <= previous) { + return false; + } + previous = array[index]; + } + return true; + } + + public static void main(String[] args) { + System.out.println(incremovableSubarrayCount(new int[] { 1, 2, 3, 4 })); + } +} diff --git a/src/CountTheNumberOfSpecialCharactersI.java b/src/CountTheNumberOfSpecialCharactersI.java new file mode 100644 index 0000000..538a318 --- /dev/null +++ b/src/CountTheNumberOfSpecialCharactersI.java @@ -0,0 +1,32 @@ +// https://leetcode.com/problems/count-the-number-of-special-characters-i +// T: O(N) +// S: O(1) + +import java.util.HashSet; +import java.util.Set; + +public class CountTheNumberOfSpecialCharactersI { + public int numberOfSpecialChars(String word) { + final Set characters = new HashSet<>(); + final Set alreadyCounted = new HashSet<>(); + int specialChars = 0; + + for (int i = 0 ; i < word.length() ; i++) { + characters.add(word.charAt(i)); + if (characters.contains(inverse(word.charAt(i))) && !alreadyCounted.contains(word.charAt(i))) { + specialChars++; + alreadyCounted.add(word.charAt(i)); + alreadyCounted.add(inverse(word.charAt(i))); + } + } + + return specialChars; + } + + private static char inverse(char c) { + if (Character.isLowerCase(c)) { + return Character.toUpperCase(c); + } + return Character.toLowerCase(c); + } +} diff --git a/src/CountTheNumberOfVowelStringsInRange.java b/src/CountTheNumberOfVowelStringsInRange.java new file mode 100644 index 0000000..05c1780 --- /dev/null +++ b/src/CountTheNumberOfVowelStringsInRange.java @@ -0,0 +1,27 @@ +// https://leetcode.com/problems/count-the-number-of-vowel-strings-in-range +// T: O(N) +// S: O(1) + +import java.util.Set; + +public class CountTheNumberOfVowelStringsInRange { + private final static Set VOWELS = Set.of('a', 'e', 'i', 'o', 'u'); + + public int vowelStrings(String[] words, int left, int right) { + int vowelStrings = 0; + for (int i = left ; i <= right ; i++) { + if (isVowelString(words[i])) { + vowelStrings++; + } + } + return vowelStrings; + } + + private boolean isVowelString(String word) { + return isVowel(word.charAt(0)) && isVowel(word.charAt(word.length() - 1)); + } + + private boolean isVowel(char c) { + return VOWELS.contains(c); + } +} diff --git a/src/CountVowelSubstringsOfAString.java b/src/CountVowelSubstringsOfAString.java new file mode 100644 index 0000000..f8599e2 --- /dev/null +++ b/src/CountVowelSubstringsOfAString.java @@ -0,0 +1,51 @@ +// https://leetcode.com/problems/count-vowel-substrings-of-a-string +// T: O(|word|) +// S: O(|word|) + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +public class CountVowelSubstringsOfAString { + private static final Set VOWELS = Set.of('a', 'e', 'i', 'o','u'); + + public static int countVowelSubstrings(String word) { + int vowelSubstrings = 0; + final Map vowels = new HashMap<>(); + for (int j = 0 ; j < word.length() ; j++) { + if (isVowel(word.charAt(j))) { + addToMap(vowels, word.charAt(j)); + for (int i = j + 1, k = j ; i < word.length() ; i++) { + if (isVowel(word.charAt(i))) { + addToMap(vowels, word.charAt(i)); + for ( ; k < i && vowels.size() == 5 ; k++) { + removeFromMap(vowels, word.charAt(k)); + } + vowelSubstrings += k - j; + if (i == word.length() - 1) { + j = i; + } + } else { + j = i; + vowels.clear(); + break; + } + } + } + } + return vowelSubstrings; + } + + private static boolean isVowel(char c) { + return VOWELS.contains(c); + } + + private static void addToMap(Map frequencies, char c) { + frequencies.put(c, frequencies.getOrDefault(c, 0) + 1); + } + + private static void removeFromMap(Map frequencies, char c) { + if (frequencies.getOrDefault(c, 0) == 1) frequencies.remove(c); + else frequencies.put(c, frequencies.get(c) - 1); + } +} diff --git a/src/CountingBits.java b/src/CountingBits.java new file mode 100644 index 0000000..b2c7825 --- /dev/null +++ b/src/CountingBits.java @@ -0,0 +1,12 @@ +public class CountingBits { + public static int[] countBits(int n) { + int[] result = new int[n + 1]; + if (result.length > 1) result[1] = 1; + for (int k = 2 ; k < result.length ; k *= 2) { + for (int i = 0 ; i < k && i + k < result.length; i++) { + result[k + i] = 1 + result[i]; + } + } + return result; + } +} diff --git a/src/CountingWordsWithAGivenPrefix.java b/src/CountingWordsWithAGivenPrefix.java new file mode 100644 index 0000000..613d1dc --- /dev/null +++ b/src/CountingWordsWithAGivenPrefix.java @@ -0,0 +1,9 @@ +public class CountingWordsWithAGivenPrefix { + public int prefixCount(String[] words, String prefix) { + int count = 0; + for (String word : words) { + if (word.startsWith(prefix)) count++; + } + return count; + } +} diff --git a/src/CourseSchedule.java b/src/CourseSchedule.java new file mode 100644 index 0000000..45047e2 --- /dev/null +++ b/src/CourseSchedule.java @@ -0,0 +1,66 @@ +// https://leetcode.com/problems/course-schedule +// T: O(|pre-requisites| + numCourses) +// S: O(numCourses) + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Queue; + +public class CourseSchedule { + public boolean canFinish(int numCourses, int[][] prerequisites) { + final int[] inDegree = getInDegreeValues(prerequisites, numCourses); + final Queue queue = queueWithInDegree0Vertices(inDegree); + final Map> graph = getDependencyGraph(prerequisites); + + while (!queue.isEmpty()) { + int vertex = queue.poll(); + if (graph.containsKey(vertex)) { + for (int adjacent : graph.get(vertex)) { + inDegree[adjacent]--; + if (inDegree[adjacent] == 0) queue.add(adjacent); + } + } + } + + return allAreZero(inDegree); + } + + private boolean allAreZero(int[] array) { + for (int element : array) { + if (element != 0) return false; + } + return true; + } + + private Queue queueWithInDegree0Vertices(int[] inDegrees) { + final Queue queue = new LinkedList<>(); + for (int i = 0; i < inDegrees.length; i++) { + if (inDegrees[i] == 0) { + queue.add(i); + } + } + return queue; + } + + private static int[] getInDegreeValues(int[][] preRequisites, int numCourses) { + int[] result = new int[numCourses]; + for (int[] preRequisite: preRequisites) { + result[preRequisite[1]]++; + } + return result; + } + + private static Map> getDependencyGraph(int[][] prerequisites) { + final Map> dependencyGraph = new HashMap<>(); + for (int[] prerequisite : prerequisites) { + if (!dependencyGraph.containsKey(prerequisite[0])) { + dependencyGraph.put(prerequisite[0], new ArrayList<>()); + } + dependencyGraph.get(prerequisite[0]).add(prerequisite[1]); + } + return dependencyGraph; + } +} diff --git a/src/CourseScheduleII.java b/src/CourseScheduleII.java new file mode 100644 index 0000000..2a76d56 --- /dev/null +++ b/src/CourseScheduleII.java @@ -0,0 +1,101 @@ +// https://leetcode.com/problems/course-schedule-ii +// T: O(V + E) --> O(numCourses + |preReq|) +// S: O(V + E) --> O(numCourses + |preReq|) + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Queue; +import java.util.Set; + +public class CourseScheduleII { + private static final class Vertex { + private final int data; + private final Set edges = new HashSet<>(); + private int outDegree = 0; + + Vertex(int data) { + this.data = data; + } + + private void addEdge(Edge edge) { + edges.add(edge); + if (edge.from == this) outDegree++; + } + + private void removeEdge(Edge edge) { + edges.remove(edge); + if (edge.from == this) outDegree--; + } + + private boolean hasDependency() { + return outDegree > 0; + } + } + + private record Edge(Vertex from, Vertex to) { } + + public int[] findOrder(int numCourses, int[][] prerequisites) { + final Map graph = createGraphWithNVertices(numCourses); + mapPrerequisitesInGraph(graph, prerequisites); + List topologicalOrder = topologicalSort(graph); + return topologicalOrder.size() == numCourses ? toArray(topologicalOrder) : new int[] { }; + } + + private List topologicalSort(Map graph) { + final Queue queue = zeroDependencyVertices(graph); + final List order = new ArrayList<>(); + + while (!queue.isEmpty()) { + Vertex vertex = queue.poll(); + order.add(vertex.data); + for (Edge edge : vertex.edges) { + edge.from.removeEdge(edge); + if (!edge.from.hasDependency()) { + queue.add(edge.from); + } + } + } + + return order; + } + + private Queue zeroDependencyVertices(Map graph) { + final Queue queue = new LinkedList<>(); + for (Vertex vertex : graph.values()) { + if (!vertex.hasDependency()) { + queue.add(vertex); + } + } + return queue; + } + + private void mapPrerequisitesInGraph(Map graph, int[][] prerequisites) { + for (int[] preRequisite : prerequisites) { + Vertex from = graph.get(preRequisite[0]); + Vertex to = graph.get(preRequisite[1]); + Edge edge = new Edge(from, to); + from.addEdge(edge); + to.addEdge(edge); + } + } + + private Map createGraphWithNVertices(int n) { + final Map graph = new HashMap<>(); + for (int i = 0 ; i < n ; i++) { + graph.put(i, new Vertex(i)); + } + return graph; + } + + private int[] toArray(List list) { + final int[] array = new int[list.size()]; + for (int i = 0 ; i < array.length ; i++) { + array[i] = list.get(i); + } + return array; + } +} diff --git a/src/CousinsInBinaryTree.java b/src/CousinsInBinaryTree.java new file mode 100644 index 0000000..4c72704 --- /dev/null +++ b/src/CousinsInBinaryTree.java @@ -0,0 +1,40 @@ +public class CousinsInBinaryTree { + + public boolean isCousins(TreeNode root, int x, int y) { + NodeInfo X = getNodeInfo(root, x); + NodeInfo Y = getNodeInfo(root, y); + return X.depth == Y.depth && X.parent != Y.parent; + } + + private NodeInfo getNodeInfo(TreeNode root, int val) { + if (root == null) return null; + if (root.val == val) return new NodeInfo(null, 0); + if (val(root.left) == val || val(root.right) == val) return new NodeInfo(root, 1); + NodeInfo left = getNodeInfo(root.left, val); + NodeInfo right = getNodeInfo(root.right, val); + if (left != null) { + left.depth++; + return left; + } + if (right != null) { + right.depth++; + return right; + } + return null; + } + + private int val(TreeNode root) { + if (root == null) return 0; + return root.val; + } + + private static class NodeInfo { + TreeNode parent; + int depth; + + NodeInfo(final TreeNode parent, final int depth) { + this.parent = parent; + this.depth = depth; + } + } +} diff --git a/src/CrawlerLogFolder.java b/src/CrawlerLogFolder.java new file mode 100644 index 0000000..4d2f168 --- /dev/null +++ b/src/CrawlerLogFolder.java @@ -0,0 +1,16 @@ +public class CrawlerLogFolder { + private static final String GO_UP = "../"; + private static final String REMAIN_WHERE_YOU_ARE = "./"; + + public int minOperations(String[] logs) { + int level = 0; + for (String log : logs) { + if (GO_UP.equals(log)) { + level = Math.max(0, level - 1); + } else if (!REMAIN_WHERE_YOU_ARE.equals(log)){ + level++; + } + } + return level; + } +} diff --git a/src/CreateTargetArrayInGivenOrder.java b/src/CreateTargetArrayInGivenOrder.java new file mode 100644 index 0000000..d8fe8bb --- /dev/null +++ b/src/CreateTargetArrayInGivenOrder.java @@ -0,0 +1,20 @@ +import java.util.ArrayList; +import java.util.List; + +public class CreateTargetArrayInGivenOrder { + public int[] createTargetArray(int[] nums, int[] index) { + List result = new ArrayList<>(); + for (int i = 0 ; i < index.length ; i++) { + result.add(index[i], nums[i]); + } + return toArray(result); + } + + private int[] toArray(List list) { + int[] array = new int[list.size()]; + for (int index = 0 ; index < array.length ; index++) { + array[index] = list.get(index); + } + return array; + } +} diff --git a/src/DIStringMatch.java b/src/DIStringMatch.java new file mode 100644 index 0000000..a166522 --- /dev/null +++ b/src/DIStringMatch.java @@ -0,0 +1,14 @@ +public class DIStringMatch { + public int[] diStringMatch(String s) { + int[] result = new int[s.length() + 1]; + int current = 0; + for (int i = 0 ; i < s.length() ; i++) { + if (s.charAt(i) == 'I') result[i] = current++; + } + result[result.length - 1] = current++; + for (int i = s.length() - 1 ; i >= 0 ; i--) { + if (s.charAt(i) == 'D') result[i] = current++; + } + return result; + } +} diff --git a/src/DayOfTheYear.java b/src/DayOfTheYear.java new file mode 100644 index 0000000..860b8f1 --- /dev/null +++ b/src/DayOfTheYear.java @@ -0,0 +1,26 @@ +public class DayOfTheYear { + private static final int[] DAYS_UPTO_MONTH_IN_STD_YEAR = { + 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 + }; + + private static final int[] DAYS_UPTO_MONTH_IN_LEAP_YEAR = { + 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 + }; + + public int dayOfYear(String date) { + String[] dateParts = date.split("-"); + final int year = Integer.parseInt(dateParts[0]); + final int month = Integer.parseInt(dateParts[1]); + final int day = Integer.parseInt(dateParts[2]); + if (isLeapYear(year)) { + return DAYS_UPTO_MONTH_IN_LEAP_YEAR[month - 1] + day; + } + return DAYS_UPTO_MONTH_IN_STD_YEAR[month - 1] + day; + } + + private boolean isLeapYear(int year) { + if (year % 400 == 0) return true; + if (year % 100 == 0) return false; + return year % 4 == 0; + } +} diff --git a/src/DayOfWeek.java b/src/DayOfWeek.java new file mode 100644 index 0000000..4ee1316 --- /dev/null +++ b/src/DayOfWeek.java @@ -0,0 +1,16 @@ +import java.time.LocalDate; + +public class DayOfWeek { + public String dayOfTheWeek(int day, int month, int year) { + LocalDate date = LocalDate.of(year, month, day); + return switch (date.getDayOfWeek()) { + case MONDAY -> "Monday"; + case TUESDAY -> "Tuesday"; + case WEDNESDAY -> "Wednesday"; + case THURSDAY -> "Thursday"; + case FRIDAY -> "Friday"; + case SATURDAY -> "Saturday"; + case SUNDAY -> "Sunday"; + }; + } +} diff --git a/src/DecodeTheMessage.java b/src/DecodeTheMessage.java new file mode 100644 index 0000000..f8efdb2 --- /dev/null +++ b/src/DecodeTheMessage.java @@ -0,0 +1,35 @@ +// https://leetcode.com/problems/decode-the-message +// T: O(|key| + |message|) +// S: O(1) + +import java.util.HashMap; +import java.util.Map; + +public class DecodeTheMessage { + public String decodeMessage(String key, String message) { + final Map mapping = getSubstitutionMap(key); + final StringBuilder result = new StringBuilder(); + System.out.println(mapping); + + for (int index = 0 ; index < message.length() ; index++) { + if (message.charAt(index) == ' ') { + result.append(' '); + } else { + result.append(mapping.get(message.charAt(index))); + } + } + + return result.toString(); + } + + private Map getSubstitutionMap(String key) { + final Map result = new HashMap<>(); + char letter = 'a'; + for (int index = 0 ; index < key.length() ; index++) { + if (!result.containsKey(key.charAt(index)) && key.charAt(index) != ' ') { + result.put(key.charAt(index), letter++); + } + } + return result; + } +} diff --git a/src/DecodeWays.java b/src/DecodeWays.java new file mode 100644 index 0000000..a7bb841 --- /dev/null +++ b/src/DecodeWays.java @@ -0,0 +1,27 @@ +// https://leetcode.com/problems/decode-ways +// T: O(n) +// S: O(1) + +public class DecodeWays { + private static final char ZERO = '0'; + + public int numDecodings(String s) { + int previous = 1, current, temp; + current = s.charAt(s.length() - 1) > ZERO ? 1 : 0; + for (int i = s.length() - 2 ; i >= 0 ; i--) { + if (s.charAt(i) == ZERO) { + previous = current; + current = 0; + } else { + temp = current; + current += isValidAlphabet(s.charAt(i), s.charAt(i + 1)) ? previous : 0; + previous = temp; + } + } + return current; + } + + private boolean isValidAlphabet(char a, char b) { + return (a - ZERO) * 10 + (b - ZERO) <= 26; + } +} diff --git a/src/DecodeXORedArray.java b/src/DecodeXORedArray.java new file mode 100644 index 0000000..d287e28 --- /dev/null +++ b/src/DecodeXORedArray.java @@ -0,0 +1,12 @@ +public class DecodeXORedArray { + public int[] decode(int[] encoded, int first) { + final int[] result = new int[encoded.length + 1]; + result[0] = first; + int next = first, i = 1; + for (int element : encoded) { + next = element ^ next; + result[i++] = next; + } + return result; + } +} diff --git a/src/DecompressRunLengthEncodedList.java b/src/DecompressRunLengthEncodedList.java new file mode 100644 index 0000000..964a5bc --- /dev/null +++ b/src/DecompressRunLengthEncodedList.java @@ -0,0 +1,20 @@ +public class DecompressRunLengthEncodedList { + public int[] decompressRLElist(int[] nums) { + final int totalElements = sumOfFrequency(nums); + final int[] result = new int[totalElements]; + for (int i = 1, k = 0; i < nums.length ; i += 2) { + for (int j = 0 ; j < nums[i - 1] ; j++) { + result[k++] = nums[i]; + } + } + return result; + } + + private int sumOfFrequency(int[] array) { + int sum = 0; + for (int i = 0 ; i < array.length ; i += 2) { + sum += array[i]; + } + return sum; + } +} diff --git a/src/DecryptStringFromAlphabetToIntegerMapping.java b/src/DecryptStringFromAlphabetToIntegerMapping.java new file mode 100644 index 0000000..9a3323c --- /dev/null +++ b/src/DecryptStringFromAlphabetToIntegerMapping.java @@ -0,0 +1,36 @@ +import java.util.LinkedList; +import java.util.Queue; + +public class DecryptStringFromAlphabetToIntegerMapping { + public String freqAlphabets(String s) { + final StringBuilder result = new StringBuilder(); + final Queue queue = new LinkedList<>(); + for (int index = 0 ; index < s.length() ; index++) { + if (queue.size() == 2) { + if (s.charAt(index) == '#') { + result.append(numberToChar(queue.poll(), queue.poll())); + continue; + } else { + result.append(numberToChar(queue.poll())); + } + } + queue.add(s.charAt(index)); + } + while (!queue.isEmpty()) { + result.append(numberToChar(queue.poll())); + } + return result.toString(); + } + + private char numberToChar(char a, char b) { + return numberToChar(10 * (a - '0') + (b - '0')); + } + + private char numberToChar(char digit) { + return numberToChar(digit - '0'); + } + + private char numberToChar(int digit) { + return (char) (digit + 'a' - 1); + } +} diff --git a/src/DefangingAnIPAddress.java b/src/DefangingAnIPAddress.java new file mode 100644 index 0000000..32262a7 --- /dev/null +++ b/src/DefangingAnIPAddress.java @@ -0,0 +1,9 @@ +public class DefangingAnIPAddress { + public String defangIPaddr(String address) { + StringBuilder result = new StringBuilder(); + for (int i = 0 ; i < address.length() ; i++) { + result.append(address.charAt(i) == '.' ? "[.]" : address.charAt(i)); + } + return result.toString(); + } +} diff --git a/src/DefuseTheBomb.java b/src/DefuseTheBomb.java new file mode 100644 index 0000000..45c0ba4 --- /dev/null +++ b/src/DefuseTheBomb.java @@ -0,0 +1,56 @@ +public class DefuseTheBomb { + public int[] decrypt(int[] code, int k) { + if (k == 0) return new int[code.length]; + final Code codeData = new Code(code); + final int[] result = new int[code.length]; + if (k > 0) { + for (int index = 0 ; index < result.length ; index++) { + result[index] = codeData.getSlice(index + 1, index + k); + } + } else { + for (int index = 0 ; index < result.length ; index++) { + result[index] = codeData.getSlice(index + k, index - 1); + } + } + return result; + } + + private static final class Code { + private final int[] sum; + private final int codeSum; + + Code(int[] code) { + this.sum = computeSum(code); + this.codeSum = sum[sum.length - 1]; + } + + private int[] computeSum(int[] array) { + final int[] sum = new int[array.length]; + sum[0] = array[0]; + for (int index = 1 ; index < array.length ; index++) { + sum[index] = sum[index - 1] + array[index]; + } + return sum; + } + + private int getIndex(int index) { + return (index + sum.length) % sum.length; + } + + private int getSlice(int start, int end) { + final int startIndex = getIndex(start), endIndex = getIndex(end); + if (startIndex <= endIndex) { + return sum[endIndex] - (startIndex == 0 ? 0: sum[startIndex - 1]); + } + return codeSum - sum[startIndex - 1] + sum[endIndex]; + } + + private int[] getFullSumArray(int length) { + final int[] array = new int[length]; + for (int index = 0 ; index < length ; index++) { + array[index] = codeSum; + } + return array; + } + } +} diff --git a/src/DegreeOfAnArray.java b/src/DegreeOfAnArray.java new file mode 100644 index 0000000..0e62f4d --- /dev/null +++ b/src/DegreeOfAnArray.java @@ -0,0 +1,45 @@ +import java.util.HashMap; +import java.util.Map; + +public class DegreeOfAnArray { + public int findShortestSubArray(int[] numbers) { + Map frequencies = getFrequencies(numbers); + Map leftMostPosition = getLeftMostPositionOf(numbers); + Map rightMostPosition = getRightMostPositionOf(numbers); + int maxFrequency = frequencies.values().stream().max(Integer::compareTo).get(); + int result = Integer.MAX_VALUE, element = 0; + for (Map.Entry entry : frequencies.entrySet()) { + if (entry.getValue() == maxFrequency) { + element = entry.getKey(); + result = Math.min(result, rightMostPosition.get(element) - leftMostPosition.get(element) + 1); + } + } + return result; + } + + private Map getFrequencies(int[] array) { + Map result = new HashMap<>(); + for (int element : array) { + result.put(element, result.getOrDefault(element, 0) + 1); + } + return result; + } + + private Map getLeftMostPositionOf(int[] array) { + Map result = new HashMap<>(); + for (int index = 0 ; index < array.length ; index++) { + if (!result.containsKey(array[index])) { + result.put(array[index], index); + } + } + return result; + } + + private Map getRightMostPositionOf(int[] array) { + Map result = new HashMap<>(); + for (int index = 0 ; index < array.length ; index++) { + result.put(array[index], index); + } + return result; + } +} diff --git a/src/DeleteANodeInLinkedList.java b/src/DeleteANodeInLinkedList.java index 349aa89..24a02ec 100644 --- a/src/DeleteANodeInLinkedList.java +++ b/src/DeleteANodeInLinkedList.java @@ -1,8 +1,4 @@ public class DeleteANodeInLinkedList { - private static class ListNode { - int val; - ListNode next; - } public static void deleteNode(ListNode node) { ListNode current = node; diff --git a/src/DeleteCharactersToMakeFancyString.java b/src/DeleteCharactersToMakeFancyString.java new file mode 100644 index 0000000..c725859 --- /dev/null +++ b/src/DeleteCharactersToMakeFancyString.java @@ -0,0 +1,19 @@ +// https://leetcode.com/problems/delete-characters-to-make-fancy-string +// T: O(|s|) +// S: O(|s|) + +public class DeleteCharactersToMakeFancyString { + public String makeFancyString(String s) { + char current = s.charAt(0); + final StringBuilder result = new StringBuilder().append(current); + for (int i = 1, count = 1 ; i < s.length() ; i++) { + if (s.charAt(i) == current) count++; + else { + count = 1; + current = s.charAt(i); + } + if (count < 3) result.append(current); + } + return result.toString(); + } +} diff --git a/src/DeleteColumnsToMakeSorted.java b/src/DeleteColumnsToMakeSorted.java new file mode 100644 index 0000000..742829d --- /dev/null +++ b/src/DeleteColumnsToMakeSorted.java @@ -0,0 +1,17 @@ +public class DeleteColumnsToMakeSorted { + public int minDeletionSize(String[] strings) { + final int columns = strings[0].length(); + int deletions = 0; + for (int column = 0 ; column < columns ; column++) { + if (!isSorted(strings, column)) deletions++; + } + return deletions; + } + + private boolean isSorted(String[] strings, int column) { + for (int row = 1 ; row < strings.length ; row++) { + if (strings[row].charAt(column) < strings[row - 1].charAt(column)) return false; + } + return true; + } +} diff --git a/src/DeleteGreatestValueInEachRow.java b/src/DeleteGreatestValueInEachRow.java new file mode 100644 index 0000000..db8efbc --- /dev/null +++ b/src/DeleteGreatestValueInEachRow.java @@ -0,0 +1,34 @@ +// https://leetcode.com/problems/delete-greatest-value-in-each-row +// T: O(mn * log(N)) +// S: O(log(n)) + +import java.util.Arrays; + +public class DeleteGreatestValueInEachRow { + public int deleteGreatestValue(int[][] grid) { + final int columns = grid[0].length; + int maxDeletions = 0; + + sortAllRows(grid); + + for (int column = 0 ; column < columns ; column++) { + maxDeletions += columnMax(grid, column); + } + + return maxDeletions; + } + + private int columnMax(int[][] grid, int column) { + int max = Integer.MIN_VALUE; + for (int[] row : grid) { + max = Math.max(max, row[column]); + } + return max; + } + + private void sortAllRows(int[][] grid) { + for (int[] row : grid) { + Arrays.sort(row); + } + } +} diff --git a/src/DesignAddAndSearchWordsDataStructure.java b/src/DesignAddAndSearchWordsDataStructure.java new file mode 100644 index 0000000..8c35fc4 --- /dev/null +++ b/src/DesignAddAndSearchWordsDataStructure.java @@ -0,0 +1,81 @@ +// https://leetcode.com/problems/design-add-and-search-words-data-structure +// S: O(sum |word|_i) +/* + trie.add(String word) + T: O(word) + + trie.contains(String word) + T: O(26^3 * word) = O(k * word) = O(word) + */ +/* + word_dict.addWord(String word) + T: O(word) + + word_dict.search(String word) + T: O(word) + */ + +import java.util.HashSet; +import java.util.Set; + +public class DesignAddAndSearchWordsDataStructure { + private static final class WordDictionary { + + private final Trie trie = new Trie(); + private final Set words = new HashSet<>(); + + public void addWord(String word) { + words.add(word); + trie.add(word); + } + + public boolean search(String word) { + if (!containsDots(word)) return words.contains(word); + return trie.contains(word); + } + + private boolean containsDots(String word) { + for (int i = 0 ; i < word.length() ; i++) { + if (word.charAt(i) == '.') return true; + } + return false; + } + } + + private static final class Trie { + final Trie[] children = new Trie[26]; + boolean isWord = false; + + public void add(String s) { + add(s, 0); + } + + private void add(String s, int index) { + if (index == s.length()) { + isWord = true; + return; + } + char c = s.charAt(index); + if (children[c - 'a'] == null) children[c - 'a'] = new Trie(); + children[c - 'a'].add(s, index + 1); + } + + public boolean contains(String s) { + return contains(s, 0); + } + + private boolean contains(String s, int index) { + if (index == s.length()) return isWord; + char character = s.charAt(index); + if (character != '.') { + return children[character - 'a'] != null && children[character - 'a'].contains(s, index + 1); + } + for (Trie child : children) { + if (child != null && child.contains(s, index + 1)) { + return true; + } + } + return false; + } + } +} diff --git a/src/DesignAnOrderedStream.java b/src/DesignAnOrderedStream.java new file mode 100644 index 0000000..b01fa25 --- /dev/null +++ b/src/DesignAnOrderedStream.java @@ -0,0 +1,26 @@ +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class DesignAnOrderedStream { + class OrderedStream { + private final String[] array; + private int pointer = 1; + + public OrderedStream(int n) { + this.array = new String[n + 1]; + } + + public List insert(int key, String value) { + array[key] = value; + if (pointer == key) { + final List list = new ArrayList<>(); + while (pointer < array.length && array[pointer] != null) { + list.add(array[pointer++]); + } + return list; + } + return Collections.emptyList(); + } + } +} diff --git a/src/DesignBrowserHistory.java b/src/DesignBrowserHistory.java new file mode 100644 index 0000000..4e1c946 --- /dev/null +++ b/src/DesignBrowserHistory.java @@ -0,0 +1,29 @@ +import java.util.ArrayList; +import java.util.List; + +class BrowserHistory { + private List history; + private int ptr; + + public BrowserHistory(String homepage) { + this.history = new ArrayList<>(); + this.history.add(homepage); + this.ptr = 0; + } + + public void visit(String url) { + this.ptr++; + this.history = this.history.subList(0, this.ptr); + this.history.add(url); + } + + public String back(int steps) { + this.ptr = Math.max(0, this.ptr - steps); + return this.history.get(this.ptr); + } + + public String forward(int steps) { + this.ptr = Math.min(this.history.size() - 1, this.ptr + steps); + return this.history.get(this.ptr); + } +} diff --git a/src/DesignHashMap.java b/src/DesignHashMap.java new file mode 100644 index 0000000..a7824b1 --- /dev/null +++ b/src/DesignHashMap.java @@ -0,0 +1,81 @@ +import java.util.LinkedList; +import java.util.Objects; +import java.util.Queue; + +public class DesignHashMap { + class MyHashMap { + + private final int initialSize = 100; + private final Bucket[] buckets = new Bucket[initialSize]; + + public MyHashMap() { + for (int index = 0 ; index < buckets.length ; index++) { + buckets[index] = new Bucket(); + } + } + + public void put(int key, int value) { + int hashCode = key % buckets.length; + buckets[hashCode].put(key, value); + } + + public int get(int key) { + return buckets[key % buckets.length].get(key); + } + + public void remove(int key) { + buckets[key % buckets.length].remove(key); + } + + private class Bucket { + Queue list = new LinkedList<>(); + + + public boolean contains(int element) { + return list.stream().anyMatch(pair -> pair.key == element); + } + + public void put(int key, int value) { + if (contains(key)) { + Pair match = list.stream().filter(pair -> pair.key == key).findFirst().get(); + match.value = value; + } else { + list.add(new Pair(key, value)); + } + } + + public int get(int key) { + return contains(key) ? list.stream().filter(pair -> pair.key == key).findFirst().get().value : -1; + } + + public void remove(int key) { + if (contains(key)) { + list.remove(new Pair(key, get(key))); + } + } + } + + private class Pair { + private final int key; + private int value; + + Pair(int key, int value) { + this.key = key; + this.value = value; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Pair pair = (Pair) o; + return key == pair.key && value == pair.value; + } + + @Override + public int hashCode() { + return Objects.hash(key, value); + } + } + } +} diff --git a/src/DesignHashSet.java b/src/DesignHashSet.java new file mode 100644 index 0000000..3642db4 --- /dev/null +++ b/src/DesignHashSet.java @@ -0,0 +1,61 @@ +import java.util.LinkedList; +import java.util.Queue; + +public class DesignHashSet { + class MyHashSet { + + private static final int INITIAL_SIZE = 100; + private final Bucket[] buckets; + private int size = 0; + + public MyHashSet() { + this.buckets = new Bucket[INITIAL_SIZE]; + initializeBuckets(); + } + + public MyHashSet(int initialSize) { + this.buckets = new Bucket[initialSize]; + initializeBuckets(); + } + + public void add(int element) { + int hash = element % buckets.length; + if (!buckets[hash].contains(element)) { + buckets[hash].add(element); + this.size++; + } + } + + public void remove(int element) { + buckets[element % buckets.length].remove(element); + } + + public boolean contains(int element) { + return buckets[element % buckets.length].contains(element); + } + + private void initializeBuckets() { + for (int index = 0 ; index < buckets.length ; index++) { + buckets[index] = new Bucket(); + } + } + + private class Bucket { + Queue list = new LinkedList<>(); + + public boolean contains(int element) { + return list.contains(element); + } + + public void add(int element) { + if (!this.contains(element)) { + list.add(element); + } + } + + public void remove(int element) { + list.remove(element); + } + } + } +} diff --git a/src/DesignParkingSystem.java b/src/DesignParkingSystem.java new file mode 100644 index 0000000..152f1fb --- /dev/null +++ b/src/DesignParkingSystem.java @@ -0,0 +1,19 @@ +public class DesignParkingSystem { + class ParkingSystem { + private final int[] carSpots = new int[3]; + + public ParkingSystem(int big, int medium, int small) { + this.carSpots[0] = big; + this.carSpots[1] = medium; + this.carSpots[2] = small; + } + + public boolean addCar(int carType) { + if (carSpots[carType - 1] > 0) { + carSpots[carType - 1]--; + return true; + } + return false; + } + } +} diff --git a/src/DestinationCity.java b/src/DestinationCity.java new file mode 100644 index 0000000..d9b8a31 --- /dev/null +++ b/src/DestinationCity.java @@ -0,0 +1,19 @@ +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class DestinationCity { + public String destCity(List> paths) { + final Set cities = new HashSet<>(); + final Set departureCities = new HashSet<>(); + for (List path : paths) { + cities.add(path.get(0)); + cities.add(path.get(1)); + departureCities.add(path.get(0)); + } + for (String city : cities) { + if (!departureCities.contains(city)) return city; + } + return null; + } +} diff --git a/src/DetectCapital.java b/src/DetectCapital.java new file mode 100644 index 0000000..9bf8de4 --- /dev/null +++ b/src/DetectCapital.java @@ -0,0 +1,27 @@ +public class DetectCapital { + public boolean detectCapitalUse(String word) { + return isAllCaps(word) || isAllLowerCase(word, 0) || firstCharIsCapital(word); + } + + private boolean isAllCaps(String string) { + for (int index = 0 ; index < string.length() ; index++) { + if (Character.isLowerCase(string.charAt(index))) { + return false; + } + } + return true; + } + + private boolean isAllLowerCase(String string, int start) { + for (int index = start ; index < string.length() ; index++) { + if (Character.isUpperCase(string.charAt(index))) { + return false; + } + } + return true; + } + + private boolean firstCharIsCapital(String string) { + return Character.isUpperCase(string.charAt(0)) && isAllLowerCase(string, 1); + } +} diff --git a/src/DetectPatternOfLengthMRepeatedKOrMoreTimes.java b/src/DetectPatternOfLengthMRepeatedKOrMoreTimes.java new file mode 100644 index 0000000..b65af17 --- /dev/null +++ b/src/DetectPatternOfLengthMRepeatedKOrMoreTimes.java @@ -0,0 +1,35 @@ +// https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times +// T: O(nm^2k) +// s: O(1) + +public class DetectPatternOfLengthMRepeatedKOrMoreTimes { + public boolean containsPattern(int[] arr, int m, int k) { + if (m * k > arr.length || m > arr.length) return false; + if (k == 1) return true; + + for (int i = 0 ; i < arr.length - m * k + 1 ; i++) { + if (consistsOfPattern(arr, i, m, k)) { + return true; + } + } + return false; + } + + private boolean consistsOfPattern(int[] array, int startIndex, int patternLen, int k) { + for (int j = startIndex + patternLen ; j <= startIndex + (k - 1) * patternLen ; j += patternLen) { + if (!arrayIsSame(array, startIndex, j, patternLen)) { + return false; + } + } + return true; + } + + private boolean arrayIsSame(int[] array, int i, int j, int patternLen) { + for (int k = 0 ; k < patternLen ; k++) { + if (array[i + k] != array[j + k]) { + return false; + } + } + return true; + } +} diff --git a/src/DetermineColorOfChessboardSquare.java b/src/DetermineColorOfChessboardSquare.java new file mode 100644 index 0000000..e6b6735 --- /dev/null +++ b/src/DetermineColorOfChessboardSquare.java @@ -0,0 +1,5 @@ +public class DetermineColorOfChessboardSquare { + public boolean squareIsWhite(String coordinates) { + return ((coordinates.charAt(0) - 'a') + (coordinates.charAt(1) - '1')) % 2 == 1; + } +} diff --git a/src/DetermineIfStringHalvesAreAlike.java b/src/DetermineIfStringHalvesAreAlike.java new file mode 100644 index 0000000..9e7f75f --- /dev/null +++ b/src/DetermineIfStringHalvesAreAlike.java @@ -0,0 +1,23 @@ +import java.util.Set; + +public class DetermineIfStringHalvesAreAlike { + private static final Set VOWELS = Set.of('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'); + + public boolean halvesAreAlike(String s) { + return numberOfVowels(s, 0, s.length() / 2) == numberOfVowels(s, s.length() / 2); + } + + private int numberOfVowels(String s, int startIndex) { + return numberOfVowels(s, startIndex, s.length()); + } + + private int numberOfVowels(String s, int startIndex, int endIndex) { + int count = 0; + for (int index = startIndex ; index < endIndex ; index++) { + if (VOWELS.contains(s.charAt(index))) { + count++; + } + } + return count; + } +} diff --git a/src/DetermineIfTwoEventsHaveConflict.java b/src/DetermineIfTwoEventsHaveConflict.java new file mode 100644 index 0000000..3f71f0c --- /dev/null +++ b/src/DetermineIfTwoEventsHaveConflict.java @@ -0,0 +1,32 @@ +// https://leetcode.com/problems/determine-if-two-events-have-conflict +// T: O(1) +// S: O(1) + +public class DetermineIfTwoEventsHaveConflict { + public boolean haveConflict(String[] event1, String[] event2) { + final int[] event1EpochMinutes = getEpochMinutes(event1); + final int[] event2EpochMinutes = getEpochMinutes(event2); + return isIntersecting(event1EpochMinutes, event2EpochMinutes); + } + + private boolean isIntersecting(int[] event1, int[] event2) { + return Math.min(event1[1], event2[1]) >= Math.max(event1[0], event2[0]); + } + + private int[] getEpochMinutes(String[] event) { + return new int[] { getEpochMinutes(event[0]), getEpochMinutes(event[1])}; + } + + private int getEpochMinutes(String event) { + final String hh = event.substring(0, 2), mm = event.substring(3); + return toInt(hh) * 60 + toInt(mm); + } + + private int toInt(String string) { + int result = 0; + for (int index = 0 ; index < string.length() ; index++) { + result = 10 * result + (string.charAt(index) - '0'); + } + return result; + } +} diff --git a/src/DetermineTheWinnerOfABowlingGame.java b/src/DetermineTheWinnerOfABowlingGame.java new file mode 100644 index 0000000..03d2b8a --- /dev/null +++ b/src/DetermineTheWinnerOfABowlingGame.java @@ -0,0 +1,29 @@ +// https://leetcode.com/problems/determine-the-winner-of-a-bowling-game +// T: O(n) +// S: O(1) + +public class DetermineTheWinnerOfABowlingGame { + public int isWinner(int[] player1, int[] player2) { + final int score1 = getPlayerScore(player1); + final int score2 = getPlayerScore(player2); + if (score1 > score2) return 1; + if (score1 < score2) return 2; + return 0; + } + + private int getPlayerScore(int[] scores) { + int total = 0, seen10 = 0; + for (int score : scores) { + if (seen10 > 0) { + total += 2 * score; + seen10--; + } else { + total += score; + } + if (score == 10) { + seen10 = 2; + } + } + return total; + } +} diff --git a/src/DetermineWhetherMatrixCanBeObtainedByRotation.java b/src/DetermineWhetherMatrixCanBeObtainedByRotation.java new file mode 100644 index 0000000..4844d88 --- /dev/null +++ b/src/DetermineWhetherMatrixCanBeObtainedByRotation.java @@ -0,0 +1,24 @@ +public class DetermineWhetherMatrixCanBeObtainedByRotation { + public boolean findRotation(int[][] mat, int[][] target) { + boolean[] c = getTrueArray(4); + int n = mat.length; + for(int i = 0 ; i < n ; i++) { + for(int j = 0 ; j < n ; j++) { + if (mat[i][j] != target[i][j]) c[0]=false; + if (mat[i][j] != target[n-j-1][i]) c[1]=false; + if (mat[i][j] != target[n-i-1][n-j-1]) c[2]=false; + if (mat[i][j] != target[j][n-i-1]) c[3]=false; + } + } + + return c[0] || c[1] || c[2] || c[3]; + } + + private boolean[] getTrueArray(int size) { + boolean[] array = new boolean[size]; + for (int i = 0 ; i < size ; i++) { + array[i] = true; + } + return array; + } +} diff --git a/src/DiameterOfBinaryTree.java b/src/DiameterOfBinaryTree.java new file mode 100644 index 0000000..e86402e --- /dev/null +++ b/src/DiameterOfBinaryTree.java @@ -0,0 +1,16 @@ +public class DiameterOfBinaryTree { + int diameter = 0; + + public int diameterOfBinaryTree(TreeNode root) { + computerDiameterOfBinaryTree(root); + return diameter; + } + + private int computerDiameterOfBinaryTree(TreeNode root) { + if (root == null) return 0; + int leftHeight = computerDiameterOfBinaryTree(root.left); + int rightHeight = computerDiameterOfBinaryTree(root.right); + diameter = Math.max(diameter, leftHeight + rightHeight); + return 1 + Math.max(leftHeight, rightHeight); + } +} diff --git a/src/DifferenceBetweenElementSumAndDigitSumOfAnArray.java b/src/DifferenceBetweenElementSumAndDigitSumOfAnArray.java new file mode 100644 index 0000000..397d413 --- /dev/null +++ b/src/DifferenceBetweenElementSumAndDigitSumOfAnArray.java @@ -0,0 +1,31 @@ +// https://leetcode.com/problems/difference-between-element-sum-and-digit-sum-of-an-array +// T: O(N) +// S: O(1) + +import java.util.Arrays; + +public class DifferenceBetweenElementSumAndDigitSumOfAnArray { + public int differenceOfSum(int[] nums) { + final int elementSum = Arrays.stream(nums).sum(); + final int digitSum = getDigitSum(nums); + return Math.abs(elementSum - digitSum); + } + + private int getDigitSum(int[] array) { + int sum = 0; + for (int number : array) { + sum += getDigitSum(number); + } + return sum; + } + + private int getDigitSum(int number) { + final String num = number + ""; + int sum = 0; + for (int index = 0 ; index < num.length() ; index++) { + int digit = num.charAt(index) - '0'; + sum += digit; + } + return sum; + } +} diff --git a/src/DistanceBetweenBusStops.java b/src/DistanceBetweenBusStops.java new file mode 100644 index 0000000..023bafb --- /dev/null +++ b/src/DistanceBetweenBusStops.java @@ -0,0 +1,17 @@ +import java.util.Arrays; + +public class DistanceBetweenBusStops { + public int distanceBetweenBusStops(int[] distance, int start, int destination) { + final int totalDistance = Arrays.stream(distance).sum(); + final int path1 = getDistance(distance, start, destination); + return Math.min(path1, totalDistance - path1); + } + + private int getDistance(int[] distances, int start, int end) { + int distance = 0; + for (int i = start ; i != end ; i = (i + 1) % distances.length) { + distance += distances[i]; + } + return distance; + } +} diff --git a/src/DistributeCandies.java b/src/DistributeCandies.java new file mode 100644 index 0000000..8f157ab --- /dev/null +++ b/src/DistributeCandies.java @@ -0,0 +1,13 @@ +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +public class DistributeCandies { + public int distributeCandies(int[] candyType) { + Set candyTypes = new HashSet<>(); + for (int type : candyType) { + candyTypes.add(type); + } + return Math.min(candyType.length / 2, candyTypes.size()); + } +} diff --git a/src/DistributeCandiesAmongChildrenI.java b/src/DistributeCandiesAmongChildrenI.java new file mode 100644 index 0000000..89e50e8 --- /dev/null +++ b/src/DistributeCandiesAmongChildrenI.java @@ -0,0 +1,30 @@ +// https://leetcode.com/problems/distribute-candies-among-children-i +// n = number of slots, c = candies +// T: O(n ^ c) +// S: O(c) + +public class DistributeCandiesAmongChildrenI { + public int distributeCandies(int n, int limit) { + // Check if n is greater than 3 times limit + if (n > 3 * limit) { + return 0; + } + + int ans = nC2(n + 2); + + if (n > limit) { + ans -= 3 * nC2(n - limit + 1); + } + + if (n - 2 >= 2 * limit) { + ans += 3 * nC2(n - 2 * limit); + } + + // Return the final result + return ans; + } + + private static int nC2(int n) { + return (n * (n - 1)) / 2; + } +} diff --git a/src/DistributeCandiesToPeople.java b/src/DistributeCandiesToPeople.java new file mode 100644 index 0000000..e26ca49 --- /dev/null +++ b/src/DistributeCandiesToPeople.java @@ -0,0 +1,10 @@ +public class DistributeCandiesToPeople { + public int[] distributeCandies(int candies, int people) { + final int[] result = new int[people]; + for (int i = 0, k = 1 ; candies > 0 ; k++, i = (i + 1) % people) { + result[i] += Math.min(candies, k); + candies -= Math.min(candies, k); + } + return result; + } +} diff --git a/src/DistributeElementsIntoTwoArraysI.java b/src/DistributeElementsIntoTwoArraysI.java new file mode 100644 index 0000000..4584f66 --- /dev/null +++ b/src/DistributeElementsIntoTwoArraysI.java @@ -0,0 +1,37 @@ +// https://leetcode.com/problems/distribute-elements-into-two-arrays-i +// T: O(N) +// S: O(N) + +import java.util.ArrayList; +import java.util.List; + +public class DistributeElementsIntoTwoArraysI { + public int[] resultArray(int[] array) { + final List array1 = new ArrayList<>(); + final List array2 = new ArrayList<>(); + + array1.add(array[0]); + array2.add(array[1]); + + for (int i = 2 ; i < array.length ; i++) { + if (array1.get(array1.size() - 1) > array2.get(array2.size() - 1)) { + array1.add(array[i]); + } else { + array2.add(array[i]); + } + } + + return concatenate(array1, array2); + } + + private static int[] concatenate(List array1, List array2) { + final int[] result = new int[array1.size() + array2.size()]; + for (int i = 0 ; i < array1.size() ; i++) { + result[i] = array1.get(i); + } + for (int i = 0 ; i < array2.size() ; i++) { + result[array1.size() + i] = array2.get(i); + } + return result; + } +} diff --git a/src/DistributeMoneyToMaximumChildren.java b/src/DistributeMoneyToMaximumChildren.java new file mode 100644 index 0000000..7c35b0a --- /dev/null +++ b/src/DistributeMoneyToMaximumChildren.java @@ -0,0 +1,23 @@ +// https://leetcode.com/problems/distribute-money-to-maximum-children +// T: O(1) +// S: O(1) + +public class DistributeMoneyToMaximumChildren { + public int distMoney(int money, int children) { + if (children > money) return -1; + + int childrenReceiving8 = Math.min((money - children) / 7, children); + final int childrenNotReceiving8 = children - childrenReceiving8; + final int moneyLeft = money - 8 * childrenReceiving8; + + if (childrenNotReceiving8 == 1 && moneyLeft == 4) { + childrenReceiving8--; + } + + if (children == childrenReceiving8 && (money / 8 != children || money % 8 != 0)) { + childrenReceiving8--; + } + + return childrenReceiving8; + } +} diff --git a/src/DivideAnArrayIntoSubarraysWithMinimumCostI.java b/src/DivideAnArrayIntoSubarraysWithMinimumCostI.java new file mode 100644 index 0000000..908d9db --- /dev/null +++ b/src/DivideAnArrayIntoSubarraysWithMinimumCostI.java @@ -0,0 +1,18 @@ +// https://leetcode.com/problems/divide-an-array-into-subarrays-with-minimum-cost-i +// T: O(N) +// S: O(1) + +public class DivideAnArrayIntoSubarraysWithMinimumCostI { + public int minimumCost(int[] array) { + int smallest = Integer.MAX_VALUE, secondSmallest = Integer.MAX_VALUE; + for (int i = 1 ; i < array.length ; i++) { + if (array[i] < smallest) { + secondSmallest = smallest; + smallest = array[i]; + } else if (array[i] < secondSmallest) { + secondSmallest = array[i]; + } + } + return array[0] + smallest + secondSmallest; + } +} diff --git a/src/DivideArrayIntoEqualPairs.java b/src/DivideArrayIntoEqualPairs.java new file mode 100644 index 0000000..0d75bfa --- /dev/null +++ b/src/DivideArrayIntoEqualPairs.java @@ -0,0 +1,28 @@ +// https://leetcode.com/problems/divide-array-into-equal-pairs +// T: O(N) +// S: O(N) + +import java.util.HashMap; +import java.util.Map; + +public class DivideArrayIntoEqualPairs { + public static boolean divideArray(int[] array) { + final Map frequencies = getFrequencies(array); + return allFrequenciesAreEven(frequencies); + } + + private static boolean allFrequenciesAreEven(Map frequencies) { + for (int frequency : frequencies.values()) { + if (frequency % 2 == 1) return false; + } + return true; + } + + private static Map getFrequencies(int[] array) { + final Map result = new HashMap<>(); + for (int element : array) { + result.put(element, result.getOrDefault(element, 0) + 1); + } + return result; + } +} diff --git a/src/DivideTheStringIntoGroupsOfSizeK.java b/src/DivideTheStringIntoGroupsOfSizeK.java new file mode 100644 index 0000000..9e4ee5a --- /dev/null +++ b/src/DivideTheStringIntoGroupsOfSizeK.java @@ -0,0 +1,22 @@ +// https://leetcode.com/problems/divide-a-string-into-groups-of-size-k +// T: O(s) +// S: O(s) + +public class DivideTheStringIntoGroupsOfSizeK { + public String[] divideString(String s, int k, char fill) { + final String filler = fill + ""; + final int groups = (int) Math.ceil((double) s.length() / k); + final String[] result = new String[groups]; + + for (int i = 0 ; i < groups ; i++) { + if (i == result.length - 1) { + if (s.length() - k * i < k) result[i] = s.substring(k * i) + filler.repeat(k - s.length() + k * i); + else result[i] = s.substring(k * i); + } else { + result[i] = s.substring(k * i, k * i + k); + } + } + + return result; + } +} diff --git a/src/DivideTwoIntegers.java b/src/DivideTwoIntegers.java new file mode 100644 index 0000000..ce2be9f --- /dev/null +++ b/src/DivideTwoIntegers.java @@ -0,0 +1,16 @@ +// https://leetcode.com/problems/divide-two-integers +// T: O(A / B) +// S: O(1) + +public class DivideTwoIntegers { + public int divide(int A, int B) { + if (A == 1 << 31 && B == -1) return (1 << 31) - 1; + int a = Math.abs(A), b = Math.abs(B), res = 0, x = 0; + while (a - b >= 0) { + for (x = 0; a - (b << x << 1) >= 0; x++); + res += 1 << x; + a -= b << x; + } + return (A > 0) == (B > 0) ? res : -res; + } +} diff --git a/src/DivisibleAndNonDivisibleSumsDifference.java b/src/DivisibleAndNonDivisibleSumsDifference.java new file mode 100644 index 0000000..f5e44ab --- /dev/null +++ b/src/DivisibleAndNonDivisibleSumsDifference.java @@ -0,0 +1,22 @@ +// https://leetcode.com/problems/divisible-and-non-divisible-sums-difference +// T: O(N) +// S: O(1) + +public class DivisibleAndNonDivisibleSumsDifference { + public int differenceOfSums(int n, int m) { + final int sumDivisibleIntegers = getSumOfDivisibleIntegers(n, m); + final int sumNonDivisibleIntegers = (n * (n + 1)) / 2 - sumDivisibleIntegers; + + return sumNonDivisibleIntegers - sumDivisibleIntegers; + } + + private static int getSumOfDivisibleIntegers(int n, int m) { + int sum = 0; + for (int i = 1 ; i <= n ; i++) { + if (i % m == 0) { + sum += i; + } + } + return sum; + } + } diff --git a/src/DivisorGame.java b/src/DivisorGame.java new file mode 100644 index 0000000..d21f85c --- /dev/null +++ b/src/DivisorGame.java @@ -0,0 +1,5 @@ +public class DivisorGame { + public boolean divisorGame(int n) { + return (n & 1) == 0; + } +} diff --git a/src/DuplicateZeros.java b/src/DuplicateZeros.java new file mode 100644 index 0000000..a897f9e --- /dev/null +++ b/src/DuplicateZeros.java @@ -0,0 +1,21 @@ +public class DuplicateZeros { + public void duplicateZeros(int[] array) { + int removals = 0, k = array.length - 1; + for (int i = 0 ; i < array.length - removals ; i++) { + if (array[i] == 0) { + if (i == array.length - 1 - removals) { + array[k--] = 0; + } + removals++; + } + } + for (int i = array.length - 1 - removals ; i >= 0 ; i--, k--) { + if (array[i] == 0) { + array[k] = array[k - 1] = 0; + k--; + } else { + array[k] = array[i]; + } + } + } +} diff --git a/src/EditDistance.java b/src/EditDistance.java new file mode 100644 index 0000000..b5681db --- /dev/null +++ b/src/EditDistance.java @@ -0,0 +1,42 @@ +// https://leetcode.com/problems/edit-distance +// T: O(m * n) +// S: O(m * n) + +public class EditDistance { + public int minDistance(String word1, String word2) { + if (word1.isEmpty()) return word2.length(); + if (word2.isEmpty()) return word1.length(); + + final int rows = word1.length() + 1, columns = word2.length() + 1; + final int[][] dp = new int[rows][columns]; + + dp[0][0] = 0; + + // first row + for (int column = 1 ; column < columns ; column++) { + dp[0][column] = column; + } + + // first column + for (int row = 1 ; row < rows ; row++) { + dp[row][0] = row; + } + + // rest of table + for (int row = 1 ; row < rows ; row++) { + for (int column = 1 ; column < columns ; column++) { + if (word1.charAt(row - 1) == word2.charAt(column - 1)) { + dp[row][column] = dp[row - 1][column - 1]; + } else { + dp[row][column] = min(dp[row - 1][column - 1], dp[row - 1][column], dp[row][column - 1]) + 1; + } + } + } + + return dp[rows - 1][columns - 1]; + } + + private int min(int a, int b, int c) { + return Math.min(Math.min(a, b), c); + } +} diff --git a/src/EdmondsKarp.java b/src/EdmondsKarp.java new file mode 100644 index 0000000..ae630ad --- /dev/null +++ b/src/EdmondsKarp.java @@ -0,0 +1,72 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + +public class EdmondsKarp { + private static int[][] adj_matrix; + + private static int edmonds_karp(int n, int source, int sink) { + int[] parent = initializeParent(n); + int max_flow = 0; + + while (bfs(n, source, sink, parent)) { + int path_flow = Integer.MAX_VALUE; + int s = sink; + while (s != source) { + path_flow = Math.min(path_flow, adj_matrix[parent[s]][s]); + s = parent[s]; + } + max_flow += path_flow; + + int v = sink; + while (v != source) { + int u = parent[v]; + adj_matrix[u][v] -= path_flow; + adj_matrix[v][u] += path_flow; + v = parent[v]; + } + + List path = new ArrayList<>(); + v = sink; + while (v != source) { + path.add(v); + v = parent[v]; + } + path.add(source); + path = path.reversed(); + System.out.println(path); + + parent = initializeParent(n); + } + + return max_flow; + } + + private static int[] initializeParent(int n) { + final int[] result = new int[n]; + Arrays.fill(result, -1); + return result; + } + + private static boolean bfs(int n, int s, int t, int[] parent) { + final boolean[] visited = new boolean[n]; + final Queue queue = new LinkedList<>() {{ add(s); }}; + visited[s] = true; + + while (!queue.isEmpty()) { + int u = queue.poll(); + for (int i = 0 ; i < n ; i++) { + final int value = adj_matrix[u][i]; + if (!visited[i] && value > 0) { + queue.add(i); + visited[i] = true; + parent[i] = u; + } + } + } + + return visited[t]; + } +} diff --git a/src/ElementAppearingMoreThan25PercentInSortedArray.java b/src/ElementAppearingMoreThan25PercentInSortedArray.java new file mode 100644 index 0000000..1edf61b --- /dev/null +++ b/src/ElementAppearingMoreThan25PercentInSortedArray.java @@ -0,0 +1,13 @@ +public class ElementAppearingMoreThan25PercentInSortedArray { + public int findSpecialInteger(int[] array) { + if (array.length <= 3) return array[0]; + final int specialIntegerFrequency = array.length / 4 + 1; + for (int i = 1, current = 1 ; i < array.length ; i++) { + if (array[i] ==array[i - 1]) current++; + else current = 1; + + if (current >= specialIntegerFrequency) return array[i]; + } + return -1; + } +} diff --git a/src/EvaluateBooleanBinaryTree.java b/src/EvaluateBooleanBinaryTree.java new file mode 100644 index 0000000..474702e --- /dev/null +++ b/src/EvaluateBooleanBinaryTree.java @@ -0,0 +1,21 @@ +// https://leetcode.com/problems/evaluate-boolean-binary-tree +// T: O(N) +// S: O(log(N)) + +public class EvaluateBooleanBinaryTree { + public boolean evaluateTree(TreeNode root) { + if (isLeafNode(root)) { + return root.val == 1; + } + + if (root.val == 2) { + return evaluateTree(root.left) || evaluateTree(root.right); + } + + return evaluateTree(root.left) && evaluateTree(root.right); + } + + private boolean isLeafNode(TreeNode root) { + return root.left == null && root.right == null; + } +} diff --git a/src/EvaluateDivision.java b/src/EvaluateDivision.java new file mode 100644 index 0000000..20dcc0c --- /dev/null +++ b/src/EvaluateDivision.java @@ -0,0 +1,67 @@ +// https://leetcode.com/problems/evaluate-division +// N = |equations|, M = |queries| +// T: O(N + M*N) = O(MN) +// S: O(N + M) + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class EvaluateDivision { + public static double[] calcEquation(List> equations, double[] values, List> queries) { + final Map> graph = createGraph(equations, values); + return computeQueries(graph, queries); + } + + private static Map> createGraph(List> equations, double[] values) { + final Map> result = new HashMap<>(); + for (int i = 0 ; i < equations.size() ; i++) { + final List equation = equations.get(i); + final String dividend = equation.get(0), divisor = equation.get(1); + result.putIfAbsent(dividend, new HashMap<>()); + result.putIfAbsent(divisor, new HashMap<>()); + result.get(dividend).put(divisor, values[i]); + result.get(divisor).put(dividend, 1 / values[i]); + } + return result; + } + + private static double[] computeQueries(Map> graph, List> queries) { + final double[] result = new double[queries.size()]; + for (int i = 0 ; i < queries.size() ; i++) { + final List query = queries.get(i); + final String dividend = query.get(0), divisor = query.get(1); + if (!graph.containsKey(dividend) || !graph.containsKey(divisor)) { + result[i] = -1; + } else if (dividend.equals(divisor)) { + result[i] = 1; + } else { + result[i] = computeDfs(graph, dividend, divisor); + } + } + return result; + } + + private static double computeDfs(Map> graph, String dividend, String divisor) { + return dfs(graph, dividend, divisor, 1, new HashSet<>()); + } + + private static double dfs(Map> graph, String current, String target, double product, Set visited) { + if (current.equals(target)) { + return product; + } + if (visited.contains(current)) { + return -1; + } + visited.add(current); + for (Map.Entry edges : graph.get(current).entrySet()) { + final double result = dfs(graph, edges.getKey(), target, product * edges.getValue(), visited); + if (result != -1) { + return result; + } + } + return -1; + } +} diff --git a/src/EvaluateReversePolishNotation.java b/src/EvaluateReversePolishNotation.java new file mode 100644 index 0000000..8562731 --- /dev/null +++ b/src/EvaluateReversePolishNotation.java @@ -0,0 +1,48 @@ +// https://leetcode.com/problems/evaluate-reverse-polish-notation +// T: O(N) +// S: O(N) + +import java.util.Set; +import java.util.Stack; + +public class EvaluateReversePolishNotation { + private static final String ADDITION = "+"; + private static final String SUBTRACTION = "-"; + private static final String MULTIPLICATION = "*"; + private static final String DIVISION = "/"; + + private static final Set OPERATORS = Set.of( + ADDITION, + SUBTRACTION, + MULTIPLICATION, + DIVISION + ); + + public static int evalRPN(String[] tokens) { + Stack stack = new Stack<>(); + for (String token : tokens) { + if (isOperator(token)) { + int number1 = stack.pop(); + int number2 = stack.pop(); + stack.push(apply(number2, number1, token)); + } else { + stack.push(Integer.parseInt(token)); + } + } + return stack.pop(); + } + + private static boolean isOperator(String token) { + return OPERATORS.contains(token); + } + + private static int apply(int a, int b, String operator) { + return switch (operator) { + case ADDITION -> a + b; + case SUBTRACTION -> a - b; + case MULTIPLICATION -> a * b; + case DIVISION -> a / b; + default -> 0; + }; + } +} diff --git a/src/ExistenceOfASubstringInAStringAndItsReverse.java b/src/ExistenceOfASubstringInAStringAndItsReverse.java new file mode 100644 index 0000000..1753057 --- /dev/null +++ b/src/ExistenceOfASubstringInAStringAndItsReverse.java @@ -0,0 +1,24 @@ +// https://leetcode.com/problems/existence-of-a-substring-in-a-string-and-its-reverse +// T: O(N^2) +// S: O(1) + +public class ExistenceOfASubstringInAStringAndItsReverse { + public boolean isSubstringPresent(String s) { + for (int i = 0 ; i < s.length() - 1 ; i++) { + final String substring = s.substring(i, i + 2); + if (reverseStringContains(s, substring)) { + return true; + } + } + return false; + } + + private static boolean reverseStringContains(String s, String substring) { + for (int i = s.length() - 1 ; i > 0 ; i--) { + if (s.charAt(i) == substring.charAt(0) && s.charAt(i - 1) == substring.charAt(1)) { + return true; + } + } + return false; + } +} diff --git a/src/FairCandySwap.java b/src/FairCandySwap.java new file mode 100644 index 0000000..bc2f223 --- /dev/null +++ b/src/FairCandySwap.java @@ -0,0 +1,16 @@ +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +public class FairCandySwap { + public int[] fairCandySwap(int[] aliceSizes, int[] bobSizes) { + final int difference = Arrays.stream(aliceSizes).sum() - Arrays.stream(bobSizes).sum(); + final int required = difference / 2; + Set bobCandies = new HashSet<>(); + for (int candy : bobSizes) bobCandies.add(candy); + for (int candy : aliceSizes) { + if (bobCandies.contains(candy - required)) return new int[] {candy, candy - required}; + } + return new int[] {}; + } +} diff --git a/src/FaultyKeyboard.java b/src/FaultyKeyboard.java new file mode 100644 index 0000000..f476f4c --- /dev/null +++ b/src/FaultyKeyboard.java @@ -0,0 +1,18 @@ +// https://leetcode.com/problems/faulty-keyboard +// T: O(N^2) +// S: O(N) + +public class FaultyKeyboard { + public String finalString(String s) { + final StringBuilder stringBuilder = new StringBuilder(); + for (int i = 0 ; i < s.length() ; i++) { + char character = s.charAt(i); + if (character == 'i') { + stringBuilder.reverse(); + } else { + stringBuilder.append(character); + } + } + return stringBuilder.toString(); + } +} diff --git a/src/FibonacciNumber.java b/src/FibonacciNumber.java new file mode 100644 index 0000000..b8970ba --- /dev/null +++ b/src/FibonacciNumber.java @@ -0,0 +1,11 @@ +public class FibonacciNumber { + public int fib(int n) { + int previous = 0, current = 1, temp1; + for (int i = 0 ; i < n ; i++) { + temp1 = current; + current = previous + current; + previous = temp1; + } + return previous; + } +} diff --git a/src/FinalPricesWithASpecialDiscountInAShop.java b/src/FinalPricesWithASpecialDiscountInAShop.java new file mode 100644 index 0000000..f3eb4ae --- /dev/null +++ b/src/FinalPricesWithASpecialDiscountInAShop.java @@ -0,0 +1,26 @@ +import java.util.Stack; + +public class FinalPricesWithASpecialDiscountInAShop { + public int[] finalPrices(int[] prices) { + final Stack stack = new Stack<>(); + for (int index = 0 ; index < prices.length ; index++) { + int price = prices[index]; + while (!stack.isEmpty() && stack.peek().price >= price) { + Price top = stack.pop(); + prices[top.index] = top.price - price; + } + stack.push(new Price(price, index)); + } + return prices; + } + + private static final class Price { + private final int price; + private final int index; + + private Price(int price, int index) { + this.price = price; + this.index = index; + } + } +} diff --git a/src/FinalValueOfVariableAfterPerformingOperations.java b/src/FinalValueOfVariableAfterPerformingOperations.java new file mode 100644 index 0000000..4e763b2 --- /dev/null +++ b/src/FinalValueOfVariableAfterPerformingOperations.java @@ -0,0 +1,21 @@ +// https://leetcode.com/problems/final-value-of-variable-after-performing-operations +// T: O(|operations|) +// S: O(1) + +public class FinalValueOfVariableAfterPerformingOperations { + public int finalValueAfterOperations(String[] operations) { + int x = 0; + for (String operation : operations) { + x = apply(x, operation); + } + return x; + } + + private int apply(int x, String operation) { + return switch (operation) { + case "++X", "X++" -> x + 1; + case "--X", "X--" -> x - 1; + default -> x; + }; + } +} diff --git a/src/FindACorrespondingNodeOfABinaryTreeInACloneOfThatTree.java b/src/FindACorrespondingNodeOfABinaryTreeInACloneOfThatTree.java new file mode 100644 index 0000000..7a55bd4 --- /dev/null +++ b/src/FindACorrespondingNodeOfABinaryTreeInACloneOfThatTree.java @@ -0,0 +1,19 @@ +// https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree +// T: O(N) +// S: O(log(n)) + +public class FindACorrespondingNodeOfABinaryTreeInACloneOfThatTree { + public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target) { + if (original == null) { + return null; + } + + if (original == target) return cloned; + + TreeNode leftAnswer = getTargetCopy(original.left, cloned.left, target); + TreeNode rightAnswer = getTargetCopy(original.right, cloned.right, target); + + if (leftAnswer != null) return leftAnswer; + return rightAnswer; + } +} diff --git a/src/FindAllKDistantIndicesInAnArray.java b/src/FindAllKDistantIndicesInAnArray.java new file mode 100644 index 0000000..360df96 --- /dev/null +++ b/src/FindAllKDistantIndicesInAnArray.java @@ -0,0 +1,24 @@ +// https://leetcode.com/problems/find-all-k-distant-indices-in-an-array +// T: O(N) +// S: O(N) + +import java.util.ArrayList; +import java.util.List; + +public class FindAllKDistantIndicesInAnArray { + public List findKDistantIndices(int[] array, int key, int k) { + final List result = new ArrayList<>(); + + for (int index = 0 ; index < array.length ; index++) { + if (array[index] == key) { + int startIndex = Math.max(result.isEmpty() ? 0 : result.get(result.size() - 1) + 1, index - k); + int endIndex = Math.min(index + k, array.length - 1); + for (int i = startIndex ; i <= endIndex ; i++) { + result.add(i); + } + } + } + + return result; + } +} diff --git a/src/FindCenterOfStarGraph.java b/src/FindCenterOfStarGraph.java new file mode 100644 index 0000000..2b5ff50 --- /dev/null +++ b/src/FindCenterOfStarGraph.java @@ -0,0 +1,10 @@ +public class FindCenterOfStarGraph { + public int findCenter(int[][] edges) { + return commonVertex(edges[0], edges[1]); + } + + private int commonVertex(int[] e1, int[] e2) { + if (e1[0] == e2[0] || e1[0] == e2[1]) return e1[0]; + return e1[1]; + } +} diff --git a/src/FindChampionI.java b/src/FindChampionI.java new file mode 100644 index 0000000..c02fd16 --- /dev/null +++ b/src/FindChampionI.java @@ -0,0 +1,26 @@ +// https://leetcode.com/problems/find-champion-i +// T: O(|grid.length| ^ 2) +// S: O(1) + +public class FindChampionI { + public int findChampion(int[][] grid) { + for (int row = 0 ; row < grid.length ; row++) { + if (isChampion(grid, row)) { + return row; + } + } + return -1; + } + + private static boolean isChampion(int[][] grid, int row) { + for (int i = 0 ; i < grid.length ; i++) { + if (i == row) { + continue; + } + if (grid[row][i] == 0) { + return false; + } + } + return true; + } +} diff --git a/src/FindClosestNumberToZero.java b/src/FindClosestNumberToZero.java new file mode 100644 index 0000000..62a59fe --- /dev/null +++ b/src/FindClosestNumberToZero.java @@ -0,0 +1,18 @@ +// https://leetcode.com/problems/find-closest-number-to-zero +// T: O(N) +// S: O(1) + +public class FindClosestNumberToZero { + public int findClosestNumber(int[] array) { + int nearest = Integer.MAX_VALUE; + for (int element : array) { + if (Math.abs(element) < Math.abs(nearest)) { + nearest = element; + } else if (Math.abs(element) == Math.abs(nearest)) { + nearest = Math.max(nearest, element); + } + } + + return nearest; + } +} diff --git a/src/FindCommonCharacters.java b/src/FindCommonCharacters.java new file mode 100644 index 0000000..1fb2e71 --- /dev/null +++ b/src/FindCommonCharacters.java @@ -0,0 +1,38 @@ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class FindCommonCharacters { + public List commonChars(String[] words) { + Map commonChars = getCharsFrequency(words[0]); + Map wordChars; + for (int i = 1 ; i < words.length ; i++) { + wordChars = getCharsFrequency(words[i]); + for (char letter : commonChars.keySet()) { + commonChars.put(letter, Math.min(commonChars.get(letter), wordChars.getOrDefault(letter, 0))); + } + } + return toList(commonChars); + } + + private List toList(Map characters) { + List result = new ArrayList<>(); + for (Map.Entry entry : characters.entrySet()) { + if (entry.getValue() > 0) { + for (int i = 0 ; i < entry.getValue() ; i++) result.add(entry.getKey() + ""); + } + } + return result; + } + + private Map getCharsFrequency(String string) { + Map result = new HashMap<>(); + char character; + for (int index = 0 ; index < string.length() ; index++) { + character = string.charAt(index); + result.put(character, result.getOrDefault(character, 0) + 1); + } + return result; + } +} diff --git a/src/FindCommonElementsBetweenTwoArrays.java b/src/FindCommonElementsBetweenTwoArrays.java new file mode 100644 index 0000000..e9d5f40 --- /dev/null +++ b/src/FindCommonElementsBetweenTwoArrays.java @@ -0,0 +1,34 @@ +// https://leetcode.com/problems/find-common-elements-between-two-arrays +// m = |array1|, n = |array2| +// T: O(m + n) +// S: O(m + n) + +import java.util.HashSet; +import java.util.Set; + +public class FindCommonElementsBetweenTwoArrays { + public int[] findIntersectionValues(int[] array1, int[] array2) { + final Set set1 = toSet(array1); + final Set set2 = toSet(array2); + + return new int[] { commonElements(array1, set2), commonElements(array2, set1) }; + } + + private static Set toSet(int[] array) { + final Set set = new HashSet<>(); + for (int element : array) { + set.add(element); + } + return set; + } + + private static int commonElements(int[] array, Set set) { + int count = 0; + for (int element : array) { + if (set.contains(element)) { + count++; + } + } + return count; + } +} diff --git a/src/FindFirstAndLastPositionOfElementInSortedArray.java b/src/FindFirstAndLastPositionOfElementInSortedArray.java new file mode 100644 index 0000000..f2fc5e7 --- /dev/null +++ b/src/FindFirstAndLastPositionOfElementInSortedArray.java @@ -0,0 +1,38 @@ +// https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array +// T: O(logN) +// S: O(1) + +public class FindFirstAndLastPositionOfElementInSortedArray { + public int[] searchRange(int[] nums, int target) { + return new int[] { + leftMostIndex(nums, target), + rightMostIndex(nums, target) + }; + } + + private int leftMostIndex(int[] array, int target) { + int left = 0, right = array.length - 1, middle; + while (left <= right) { + middle = left + (right - left) / 2; + if (array[middle] == target) { + if (middle - 1 >= 0 && array[middle - 1] == target) right = middle - 1; + else return middle; + } else if (array[middle] > target) right = middle - 1; + else left = middle + 1; + } + return -1; + } + + private int rightMostIndex(int[] array, int target) { + int left = 0, right = array.length - 1, middle; + while (left <= right) { + middle = left + (right - left) / 2; + if (array[middle] == target) { + if (middle + 1 < array.length && array[middle + 1] == target) left = middle + 1; + else return middle; + } else if (array[middle] > target) right = middle - 1; + else left = middle + 1; + } + return -1; + } +} diff --git a/src/FindFirstPalindromicStringInArray.java b/src/FindFirstPalindromicStringInArray.java new file mode 100644 index 0000000..1060b82 --- /dev/null +++ b/src/FindFirstPalindromicStringInArray.java @@ -0,0 +1,23 @@ +// https://leetcode.com/problems/find-first-palindromic-string-in-the-array +// T: O(|words| * len(words[i])) +// S: O(1) + +public class FindFirstPalindromicStringInArray { + public String firstPalindrome(String[] words) { + for (String word : words) { + if (isPalindrome(word)) { + return word; + } + } + return ""; + } + + private boolean isPalindrome(String s) { + for (int i = 0; i < s.length() / 2 ; i++) { + if (s.charAt(i) != s.charAt(s.length() - 1 - i)) { + return false; + } + } + return true; + } +} diff --git a/src/FindGreatestCommonDivisorOfArray.java b/src/FindGreatestCommonDivisorOfArray.java new file mode 100644 index 0000000..bdc59dd --- /dev/null +++ b/src/FindGreatestCommonDivisorOfArray.java @@ -0,0 +1,18 @@ +// https://leetcode.com/problems/find-greatest-common-divisor-of-array +// T: O(N) +// S: O(1) + +import java.util.Arrays; + +public class FindGreatestCommonDivisorOfArray { + public int findGCD(int[] nums) { + return gcd( + Arrays.stream(nums).max().getAsInt(), + Arrays.stream(nums).min().getAsInt() + ); + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/src/FindIfPathExistsInGraph.java b/src/FindIfPathExistsInGraph.java new file mode 100644 index 0000000..f84fbf8 --- /dev/null +++ b/src/FindIfPathExistsInGraph.java @@ -0,0 +1,63 @@ +// https://leetcode.com/problems/find-if-path-exists-in-graph +// T: O(V + E) +// S: O(V + E) + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class FindIfPathExistsInGraph { + public boolean validPath(int n, int[][] edges, int start, int end) { + UnDirectedGraph graph = UnDirectedGraph.from(n, edges); + return graph.pathFrom(start, end); + } + + private static final class UnDirectedGraph { + private final Map vertices = new HashMap<>(); + + public static UnDirectedGraph from(int vertices, int[][] edges) { + UnDirectedGraph graph = new UnDirectedGraph(vertices); + for (int[] edge : edges) { + graph.vertices.get(edge[0]).addEdge(edge[1]); + graph.vertices.get(edge[1]).addEdge(edge[0]); + } + return graph; + } + + private UnDirectedGraph(int vertices) { + for (int i = 0 ; i < vertices ; i++) { + this.vertices.put(i, new Vertex(i)); + } + } + + public boolean pathFrom(int start, int end) { + return pathTo(vertices.get(start), end, new HashSet<>()); + } + + private boolean pathTo(Vertex from, int to, Set visited) { + if (visited.contains(from.value)) return false; + if (from.value == to) return true; + visited.add(from.value); + for (int edge : from.edges) { + if (pathTo(vertices.get(edge), to, visited)) { + return true; + } + } + return false; + } + + private static final class Vertex { + private final int value; + private final Set edges = new HashSet<>(); + + Vertex(int value) { + this.value = value; + } + + public void addEdge(int to) { + edges.add(to); + } + } + } +} diff --git a/src/FindIndicesWithIndexAndValueDifferenceI.java b/src/FindIndicesWithIndexAndValueDifferenceI.java new file mode 100644 index 0000000..04aa592 --- /dev/null +++ b/src/FindIndicesWithIndexAndValueDifferenceI.java @@ -0,0 +1,16 @@ +// https://leetcode.com/problems/find-indices-with-index-and-value-difference-i +// T: O(N^2) +// S: O(1) + +public class FindIndicesWithIndexAndValueDifferenceI { + public int[] findIndices(int[] array, int indexDifference, int valueDifference) { + for (int i = 0 ; i < array.length ; i++) { + for (int j = i + indexDifference ; j < array.length ; j++) { + if (Math.abs(array[i] - array[j]) >= valueDifference) { + return new int[] { i, j }; + } + } + } + return new int[] { -1, -1}; + } +} diff --git a/src/FindKClosestElements.java b/src/FindKClosestElements.java new file mode 100644 index 0000000..8d9f5b0 --- /dev/null +++ b/src/FindKClosestElements.java @@ -0,0 +1,41 @@ +// https://leetcode.com/problems/find-k-closest-elements +// T: O(logN + KLogK) +// S: O(logK) + +import java.util.ArrayList; +import java.util.List; + +public class FindKClosestElements { + public static List findClosestElements(int[] array, int k, int x) { + final int index = binarySearch(array, x); + final List result = new ArrayList<>(); + + for (int left = index - 1, right = index ; k > 0 ; k--) { + if (left == -1) { + result.add(array[right++]); + } else if (right == array.length) { + result.add(array[left--]); + } else { + if (Math.abs(array[left] - x) <= Math.abs(array[right] - x)) { + result.add(array[left--]); + } else { + result.add(array[right++]); + } + } + } + + result.sort(Integer::compareTo); + return result; + } + + private static int binarySearch(int[] array, int x) { + int left = 0, right = array.length - 1, middle; + while (left <= right) { + middle = left + (right - left) / 2; + if (array[middle] == x) return middle; + else if (array[middle] < x) left = middle + 1; + else right = middle - 1; + } + return left; + } +} diff --git a/src/FindMaximumNumberOfStringPairs.java b/src/FindMaximumNumberOfStringPairs.java new file mode 100644 index 0000000..50053c6 --- /dev/null +++ b/src/FindMaximumNumberOfStringPairs.java @@ -0,0 +1,23 @@ +// https://leetcode.com/problems/find-maximum-number-of-string-pairs +// T: O(N * |s|) +// S: O(N * |s|) + +import java.util.HashSet; +import java.util.Set; + +public class FindMaximumNumberOfStringPairs { + public int maximumNumberOfStringPairs(String[] words) { + final Set strings = new HashSet<>(); + int pairs = 0; + for (String word : words) { + final String reversed = new StringBuilder(word).reverse().toString(); + if (strings.contains(reversed)) { + pairs++; + strings.remove(reversed); + } else { + strings.add(word); + } + } + return pairs; + } +} diff --git a/src/FindMinimumInRotatedSortedArray.java b/src/FindMinimumInRotatedSortedArray.java new file mode 100644 index 0000000..ba9cdad --- /dev/null +++ b/src/FindMinimumInRotatedSortedArray.java @@ -0,0 +1,19 @@ +// https://leetcode.com/problems/find-minimum-in-rotated-sorted-array +// T: O(log(N)) +// T: O(1) + +public class FindMinimumInRotatedSortedArray { + public int findMin(int[] nums) { + return nums[binarySearchPivotIndex(nums)]; + } + + private static int binarySearchPivotIndex(int[] array) { + int left = 0, right = array.length - 1, middle; + while (left <= right) { + middle = left + (right - left) / 2; + if (array[middle] > array[array.length - 1]) left = middle + 1; + else right = middle - 1; + } + return left; + } +} diff --git a/src/FindMinimumOperationsToMakeAllElementsDivisibleByThree.java b/src/FindMinimumOperationsToMakeAllElementsDivisibleByThree.java new file mode 100644 index 0000000..837e5ae --- /dev/null +++ b/src/FindMinimumOperationsToMakeAllElementsDivisibleByThree.java @@ -0,0 +1,15 @@ +// https://leetcode.com/problems/find-minimum-operations-to-make-all-elements-divisible-by-three +// T: O(N) +// S: O(1) + +public class FindMinimumOperationsToMakeAllElementsDivisibleByThree { + public int minimumOperations(int[] array) { + int minOperations = 0; + for (int element : array) { + if (element % 3 != 0) { + minOperations++; + } + } + return minOperations; + } +} diff --git a/src/FindMissingAndRepeatedValues.java b/src/FindMissingAndRepeatedValues.java new file mode 100644 index 0000000..848f9cb --- /dev/null +++ b/src/FindMissingAndRepeatedValues.java @@ -0,0 +1,29 @@ +// https://leetcode.com/problems/find-missing-and-repeated-values +// T: O(N*N) +// S: O(N*N) + +import java.util.HashSet; +import java.util.Set; + +public class FindMissingAndRepeatedValues { + public int[] findMissingAndRepeatedValues(int[][] grid) { + final int rows = grid.length, elements = rows * rows; + int expectedSum = (elements * (elements + 1)) / 2, actualSum = 0; + final Set numbers = new HashSet<>(); + int repeatingElement = 0; + + for (int[] row : grid) { + for (int element : row) { + if (numbers.contains(element)) { + repeatingElement = element; + } + numbers.add(element); + actualSum += element; + } + } + + int missingElement = expectedSum - actualSum + repeatingElement; + + return new int[] { repeatingElement, missingElement }; + } +} diff --git a/src/FindModeInBinarySearchTree.java b/src/FindModeInBinarySearchTree.java new file mode 100644 index 0000000..7982ef2 --- /dev/null +++ b/src/FindModeInBinarySearchTree.java @@ -0,0 +1,50 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class FindModeInBinarySearchTree { + private static TreeNode previous; + private static int count = 1; + private static int mode = 0; + + public static int[] findMode(TreeNode root) { + if (root == null) { + return new int[0]; + } + + List modes = new ArrayList<>(); + findMode(root, modes); + int[] result = new int[modes.size()]; + for(int index = 0 ; index < modes.size() ; index++) { + result[index] = modes.get(index); + } + previous = null; + count = 1; + mode = 0; + return result; + } + + private static void findMode(TreeNode root, List modes) { + if (root == null) { + return; + } + findMode(root.left, modes); + if (previous != null) { + count = root.val == previous.val ? count + 1 : 1; + } + if (count > mode) { + mode = count; + modes.clear(); + modes.add(root.val); + } else if (count == mode) { + modes.add(root.val); + } + previous = root; + findMode(root.right, modes); + } + + public static void main(String[] args) { + TreeNode root = new TreeNode(0); + System.out.println(Arrays.toString(findMode(root))); + } +} diff --git a/src/FindNUniqueIntegersSumUpToZero.java b/src/FindNUniqueIntegersSumUpToZero.java new file mode 100644 index 0000000..0e8acda --- /dev/null +++ b/src/FindNUniqueIntegersSumUpToZero.java @@ -0,0 +1,11 @@ +public class FindNUniqueIntegersSumUpToZero { + public int[] sumZero(int n) { + final int[] result = new int[n]; + for (int i = 0, k = 1 ; i + 1 < result.length ; i += 2, k++) { + result[i] = k; + result[i + 1] = -k; + } + if ((n & 1) == 1) result[n - 1] = 0; + return result; + } +} diff --git a/src/FindNearestPointThatHasTheSameXOrYCoordinate.java b/src/FindNearestPointThatHasTheSameXOrYCoordinate.java new file mode 100644 index 0000000..77ee645 --- /dev/null +++ b/src/FindNearestPointThatHasTheSameXOrYCoordinate.java @@ -0,0 +1,20 @@ +public class FindNearestPointThatHasTheSameXOrYCoordinate { + public int nearestValidPoint(int x, int y, int[][] points) { + int minDistance = Integer.MAX_VALUE, minIndex = -1; + for (int index = 0 ; index < points.length ; index++) { + int[] point = points[index]; + if (point[0] == x || point[1] == y) { + int distance = manhattanDistance(x, y, point); + if (distance < minDistance) { + minDistance = distance; + minIndex = index; + } + } + } + return minIndex; + } + + private int manhattanDistance(int x, int y, int[] point) { + return Math.abs(x - point[0]) + Math.abs(y - point[1]); + } +} diff --git a/src/FindNumbersWithEvenNumbersOfDigits.java b/src/FindNumbersWithEvenNumbersOfDigits.java new file mode 100644 index 0000000..a8831bf --- /dev/null +++ b/src/FindNumbersWithEvenNumbersOfDigits.java @@ -0,0 +1,19 @@ +public class FindNumbersWithEvenNumbersOfDigits { + public int findNumbers(int[] array) { + int evenDigitNumbers = 0; + for (int number : array) { + if (numberOfDigits(number) % 2 == 0) evenDigitNumbers++; + } + return evenDigitNumbers; + } + + private int numberOfDigits(int number) { + if (number == 0) return 1; + int digits = 0; + while (number != 0) { + number /= 10; + digits++; + } + return digits; + } +} diff --git a/src/FindPeakElement.java b/src/FindPeakElement.java new file mode 100644 index 0000000..886a192 --- /dev/null +++ b/src/FindPeakElement.java @@ -0,0 +1,21 @@ +// https://leetcode.com/problems/find-peak-element +// T: O(log(N)) +// S: O(1) + +public class FindPeakElement { + public int findPeakElement(int[] nums) { + int left = 0, right = nums.length - 1, middle; + while (left <= right) { + middle = left + (right - left) / 2; + if (isPeak(nums, middle)) return middle; + else if (middle + 1 < nums.length && nums[middle] < nums[middle + 1]) left = middle + 1; + else right = middle - 1; + } + return -1; + } + + private static boolean isPeak(int[] array, int x) { + return (x - 1 < 0 || array[x - 1] < array[x]) + && (x + 1 >= array.length || array[x] > array[x + 1]); + } +} diff --git a/src/FindPivotIndex.java b/src/FindPivotIndex.java new file mode 100644 index 0000000..3c5b97e --- /dev/null +++ b/src/FindPivotIndex.java @@ -0,0 +1,15 @@ +import java.util.Arrays; + +public class FindPivotIndex { + public int pivotIndex(int[] array) { + int sum = Arrays.stream(array).sum(); + for (int index = 0, leftSum = 0 ; index < array.length ; index++) { + leftSum += index - 1 >= 0 ? array[index - 1] : 0; + sum -= array[index]; + if (leftSum == sum) { + return index; + } + } + return -1; + } +} diff --git a/src/FindResultantArrayAfterRemovingAnagrams.java b/src/FindResultantArrayAfterRemovingAnagrams.java new file mode 100644 index 0000000..c96803b --- /dev/null +++ b/src/FindResultantArrayAfterRemovingAnagrams.java @@ -0,0 +1,33 @@ +// https://leetcode.com/problems/find-resultant-array-after-removing-anagrams +// T: O(|words| * |words[i]|) +// S: O(|words[i]|) + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class FindResultantArrayAfterRemovingAnagrams { + public List removeAnagrams(String[] words) { + final List result = new ArrayList<>(); + result.add(words[0]); + Map wordSignature = getCharacterFrequencies(words[0]); + for (int index = 1 ; index < words.length ; index++) { + final String word = words[index]; + final Map wordCharFrequencies = getCharacterFrequencies(word); + if (!wordCharFrequencies.equals(wordSignature)) { + result.add(word); + wordSignature = wordCharFrequencies; + } + } + return result; + } + + private Map getCharacterFrequencies(String string) { + final Map result = new HashMap<>(); + for (int index = 0 ; index < string.length() ; index++) { + result.put(string.charAt(index), result.getOrDefault(string.charAt(index), 0) + 1); + } + return result; + } +} diff --git a/src/FindSmallestLetterGreaterThanTarget.java b/src/FindSmallestLetterGreaterThanTarget.java new file mode 100644 index 0000000..f364665 --- /dev/null +++ b/src/FindSmallestLetterGreaterThanTarget.java @@ -0,0 +1,11 @@ +public class FindSmallestLetterGreaterThanTarget { + public char nextGreatestLetter(char[] letters, char target) { + int left = 0, right = letters.length - 1, middle; + while (left <= right) { + middle = left + (right - left) / 2; + if (letters[middle] <= target) left = middle + 1; + else right = middle - 1; + } + return letters[left % letters.length]; + } +} diff --git a/src/FindSubarraysWithEqualSum.java b/src/FindSubarraysWithEqualSum.java new file mode 100644 index 0000000..4db4790 --- /dev/null +++ b/src/FindSubarraysWithEqualSum.java @@ -0,0 +1,20 @@ +// https://leetcode.com/problems/find-subarrays-with-equal-sum +// T: O(N) +// S: O(N) + +import java.util.HashSet; +import java.util.Set; + +public class FindSubarraysWithEqualSum { + public boolean findSubarrays(int[] array) { + final Set subarraySum = new HashSet<>(); + for (int i = 0 ; i < array.length - 1 ; i++) { + int sum = array[i] + array[i + 1]; + if (subarraySum.contains(sum)) { + return true; + } + subarraySum.add(sum); + } + return false; + } +} diff --git a/src/FindSubsequenceOfLengthKWithTheLargestSum.java b/src/FindSubsequenceOfLengthKWithTheLargestSum.java new file mode 100644 index 0000000..386c787 --- /dev/null +++ b/src/FindSubsequenceOfLengthKWithTheLargestSum.java @@ -0,0 +1,51 @@ +// https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum +// T: O(nloogn + klogk) +// S: o(n) + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +public class FindSubsequenceOfLengthKWithTheLargestSum { + public int[] maxSubsequence(int[] nums, int k) { + Listnumbers = toNumbersList(nums); + numbers.sort(Comparator.comparingInt(a -> a.value)); + List topK = getLastK(numbers, k); + topK.sort(Comparator.comparing(a -> a.index)); + return toArray(topK); + } + + private List toNumbersList(int[] array) { + final List numbers = new ArrayList<>(array.length); + for (int index = 0 ; index < array.length ; index++) { + numbers.add(new Number(array[index], index)); + } + return numbers; + } + + private List getLastK(List numbers, int k) { + final List result = new ArrayList<>(); + for (int i = 0 ; i < k ; i++) { + result.add(numbers.get(numbers.size() - 1 - i)); + } + return result; + } + + private int[] toArray(List numbers) { + final int[] array = new int[numbers.size()]; + for (int i = 0 ; i < array.length ; i++) { + array[i] = numbers.get(i).value; + } + return array; + } + + private static final class Number { + private final int value; + private final int index; + + private Number(int value, int index) { + this.value = value; + this.index = index; + } + } +} diff --git a/src/FindTargetIndicesAfterSortingArray.java b/src/FindTargetIndicesAfterSortingArray.java new file mode 100644 index 0000000..7132914 --- /dev/null +++ b/src/FindTargetIndicesAfterSortingArray.java @@ -0,0 +1,35 @@ +// https://leetcode.com/problems/find-target-indices-after-sorting-array +// T: O(|nums|) +// S: O(|nums|) + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class FindTargetIndicesAfterSortingArray { + public List targetIndices(int[] nums, int target) { + final Map frequency = getFrequency(nums); + int index = 0; + for (int i = 0 ; i < target ; i++) { + index += frequency.getOrDefault(i, 0); + } + return indices(index, frequency.getOrDefault(target, 0)); + } + + private Map getFrequency(int[] array) { + final Map result = new HashMap<>(); + for (int element : array) { + result.put(element, result.getOrDefault(element, 0) + 1); + } + return result; + } + + private List indices(int start, int length) { + final List result = new ArrayList<>(length); + for (int i = 0 ; i < length ; i++) { + result.add(start++); + } + return result; + } +} diff --git a/src/FindTheArrayConcatenationValue.java b/src/FindTheArrayConcatenationValue.java new file mode 100644 index 0000000..5d1c6b8 --- /dev/null +++ b/src/FindTheArrayConcatenationValue.java @@ -0,0 +1,19 @@ +// https://leetcode.com/problems/find-the-array-concatenation-value +// T: O(N) +// S: O(1) + +public class FindTheArrayConcatenationValue { + public long findTheArrayConcVal(int[] nums) { + long result = 0; + + for (int i = 0 ; i < nums.length / 2 ; i++) { + result += Integer.parseInt(nums[i] + "" + nums[nums.length - 1 - i]); + } + + if (nums.length % 2 == 1) { + result += nums[nums.length / 2]; + } + + return result; + } +} diff --git a/src/FindTheChildWhoHasTheBallAfterKSeconds.java b/src/FindTheChildWhoHasTheBallAfterKSeconds.java new file mode 100644 index 0000000..600698f --- /dev/null +++ b/src/FindTheChildWhoHasTheBallAfterKSeconds.java @@ -0,0 +1,13 @@ +// https://leetcode.com/problems/find-the-child-who-has-the-ball-after-k-seconds +// T: O(1) +// S: O(1) + +public class FindTheChildWhoHasTheBallAfterKSeconds { + public int numberOfChild(int n, int k) { + final boolean isLeftDirection = (k / (n - 1)) % 2 == 0; + if (isLeftDirection) { + return k % (n - 1); + } + return n - 1 - (k % (n - 1)); + } +} diff --git a/src/FindTheDifferenceOfTwoArrays.java b/src/FindTheDifferenceOfTwoArrays.java new file mode 100644 index 0000000..7508702 --- /dev/null +++ b/src/FindTheDifferenceOfTwoArrays.java @@ -0,0 +1,35 @@ +// https://leetcode.com/problems/find-the-difference-of-two-arrays +// T: O(N + M) +// S: O(N + M) + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class FindTheDifferenceOfTwoArrays { + public List> findDifference(int[] nums1, int[] nums2) { + final Set numbers1 = getSetFrom(nums1); + final Set numbers2 = getSetFrom(nums2); + final List distinctElementsInNums1 = difference(numbers1, numbers2); + final List distinctElementsInNums2 = difference(numbers2, numbers1); + + return List.of(distinctElementsInNums1, distinctElementsInNums2); + } + + private Set getSetFrom(int[] array) { + final Set set = new HashSet<>(); + for (int element : array) { + set.add(element); + } + return set; + } + + private List difference(Set set1, Set set2) { + final List result = new ArrayList<>(); + for (int element : set1) { + if (!set2.contains(element)) result.add(element); + } + return result; + } +} diff --git a/src/FindTheDistanceValuesBetweenTwoArrays.java b/src/FindTheDistanceValuesBetweenTwoArrays.java new file mode 100644 index 0000000..46617a2 --- /dev/null +++ b/src/FindTheDistanceValuesBetweenTwoArrays.java @@ -0,0 +1,32 @@ +import java.util.TreeSet; + +public class FindTheDistanceValuesBetweenTwoArrays { + public int findTheDistanceValue(int[] arr1, int[] arr2, int d) { + TreeSet set = new TreeSet<>(); + for (int number : arr2) { + set.add(number); + } + int distanceValue = 0; + for (int number : arr1) { + if (smallerOrEqual(set, number) < number - d && largerOrEqual(set, number) > number + d) { + distanceValue++; + } + } + return distanceValue; + } + + private int smallerOrEqual(TreeSet set, int number) { + if (set.contains(number)) return number; + return valIfNull(set.lower(number), Integer.MIN_VALUE); + } + + private int largerOrEqual(TreeSet set, int number) { + if (set.contains(number)) return number; + return valIfNull(set.higher(number), Integer.MAX_VALUE); + } + + private int valIfNull(Integer value, int defaultValue) { + if (value == null) return defaultValue; + return value; + } +} diff --git a/src/FindTheDistinctDifferenceArray.java b/src/FindTheDistinctDifferenceArray.java new file mode 100644 index 0000000..99369ed --- /dev/null +++ b/src/FindTheDistinctDifferenceArray.java @@ -0,0 +1,42 @@ +// https://leetcode.com/problems/find-the-distinct-difference-array +// N: length of array +// T: O(N) +// S: O(N) + +import java.util.HashMap; +import java.util.Map; + +public class FindTheDistinctDifferenceArray { + public int[] distinctDifferenceArray(int[] nums) { + final Map leftFrequencies = new HashMap<>(); + final Map rightFrequencies = getNumberFrequencies(nums); + final int[] result = new int[nums.length]; + int k = 0; + for (int element : nums) { + addToFrequency(leftFrequencies, element); + removeFromFrequency(rightFrequencies, element); + result[k++] = leftFrequencies.size() - rightFrequencies.size(); + } + return result; + } + + private void removeFromFrequency(Map frequencies, int element) { + if (frequencies.get(element) == 1) { + frequencies.remove(element); + } else { + frequencies.put(element, frequencies.getOrDefault(element, 0) - 1); + } + } + + private void addToFrequency(Map frequencies, int element) { + frequencies.put(element, frequencies.getOrDefault(element, 0) + 1); + } + + private Map getNumberFrequencies(int[] array) { + final Map result = new HashMap<>(); + for (int element : array) { + result.put(element, result.getOrDefault(element, 0) + 1); + } + return result; + } +} diff --git a/src/FindTheDuplicateNumber.java b/src/FindTheDuplicateNumber.java new file mode 100644 index 0000000..c86f050 --- /dev/null +++ b/src/FindTheDuplicateNumber.java @@ -0,0 +1,26 @@ +// https://leetcode.com/problems/find-the-duplicate-number +// T: O(N) +// S: O(1) + +public class FindTheDuplicateNumber { + public static int findDuplicate(int[] nums) { + int tortoise = nums[0]; + int hare = nums[0]; + + do { + tortoise = nums[tortoise]; + hare = nums[nums[hare]]; + } while (tortoise != hare); + + // Find the "entrance" to the cycle. + tortoise = nums[0]; + + while (tortoise != hare) { + tortoise = nums[tortoise]; + hare = nums[hare]; + } + + return hare; + } +} + diff --git a/src/FindTheEncryptedString.java b/src/FindTheEncryptedString.java new file mode 100644 index 0000000..9facfb5 --- /dev/null +++ b/src/FindTheEncryptedString.java @@ -0,0 +1,21 @@ +// https://leetcode.com/problems/find-the-encrypted-string +// T: O(|s|) +// S: O(|s|) + +public class FindTheEncryptedString { + public String getEncryptedString(String s, int k) { + final int rotations = k % s.length(); + if (rotations == 0) { + return s; + } + return rotateString(s, rotations); + } + + private static String rotateString(String s, int rotations) { + final StringBuilder builder = new StringBuilder(); + for (int i = 0 ; i < s.length() ; i++) { + builder.append(s.charAt((i + rotations) % s.length())); + } + return builder.toString(); + } +} diff --git a/src/FindTheHighestAltitude.java b/src/FindTheHighestAltitude.java new file mode 100644 index 0000000..542969b --- /dev/null +++ b/src/FindTheHighestAltitude.java @@ -0,0 +1,14 @@ +// https://leetcode.com/problems/find-the-highest-altitude +// T: O(N) +// S: O(1) + +public class FindTheHighestAltitude { + public int largestAltitude(int[] gains) { + int highestAltitude = 0, current = 0; + for (int gain : gains) { + current+= gain; + highestAltitude = Math.max(highestAltitude, current); + } + return highestAltitude; + } +} diff --git a/src/FindTheIntegerAddedToArrayI.java b/src/FindTheIntegerAddedToArrayI.java new file mode 100644 index 0000000..4b1898f --- /dev/null +++ b/src/FindTheIntegerAddedToArrayI.java @@ -0,0 +1,19 @@ +// https://leetcode.com/problems/find-the-integer-added-to-array-i +// T: O(N) +// S: O(1) + +public class FindTheIntegerAddedToArrayI { + public int addedInteger(int[] array1, int[] array2) { + final int min1 = smallestElement(array1); + final int min2 = smallestElement(array2); + return min2 - min1; + } + + private static int smallestElement(int[] array) { + int result = Integer.MAX_VALUE; + for (int element : array) { + result = Math.min(result, element); + } + return result; + } +} diff --git a/src/FindTheKBeautyOfANumber.java b/src/FindTheKBeautyOfANumber.java new file mode 100644 index 0000000..113653d --- /dev/null +++ b/src/FindTheKBeautyOfANumber.java @@ -0,0 +1,24 @@ +// https://leetcode.com/problems/find-the-k-beauty-of-a-number +// T: O(|num|) +// S: O(|num|) + +public class FindTheKBeautyOfANumber { + public int divisorSubstrings(int num, int k) { + int kBeauty = 0; + final String number = num + ""; + for (int index = 0 ; index < number.length() - k + 1 ; index++) { + final String substring = number.substring(index, index + k); + final int divisor = toNumber(substring); + if (divisor != 0 && num % divisor == 0) kBeauty++; + } + return kBeauty; + } + + private int toNumber(String string) { + int result = 0; + for (int i = 0; i < string.length() ; i++) { + result = 10 * result + (string.charAt(i) - '0'); + } + return result; + } +} diff --git a/src/FindTheKOrOfAnArray.java b/src/FindTheKOrOfAnArray.java new file mode 100644 index 0000000..5640479 --- /dev/null +++ b/src/FindTheKOrOfAnArray.java @@ -0,0 +1,27 @@ +// https://leetcode.com/problems/find-the-k-or-of-an-array +// T: O(N) +// S: O(1) + +public class FindTheKOrOfAnArray { + public int findKOr(int[] array, int k) { + int mask = 0; + + for (int i = 0 ; i < 32 ; i++) { + int count = 0; + for (int element : array) { + if ((element & (1 << i)) > 0) { + count++; + } + if (count == k) { + break; + } + } + + if(count == k) { + mask |= (1 << i); + } + } + + return mask; + } +} diff --git a/src/FindTheLongestBalancedSubstringOfABinaryString.java b/src/FindTheLongestBalancedSubstringOfABinaryString.java new file mode 100644 index 0000000..0a37b80 --- /dev/null +++ b/src/FindTheLongestBalancedSubstringOfABinaryString.java @@ -0,0 +1,26 @@ +// https://leetcode.com/problems/find-the-longest-balanced-substring-of-a-binary-string +// T: O(n) +// S: O(1) + +public class FindTheLongestBalancedSubstringOfABinaryString { + public int findTheLongestBalancedSubstring(String s) { + int result = 0; + for (int maxZeros = 0, maxOnes = 0, i = 0 ; i < s.length() ; i++) { + if (s.charAt(i) == '0') { + if (i - 1 >= 0 && s.charAt(i - 1) == '1') { + result = Math.max(result, 2 * Math.min(maxOnes, maxZeros)); + maxOnes = 0; + maxZeros = 1; + } else { + maxZeros++; + } + } else { + maxOnes++; + if (i == s.length() - 1) { + result = Math.max(result, 2 * Math.min(maxOnes, maxZeros)); + } + } + } + return result; + } +} diff --git a/src/FindTheLosersOfTheCircularGame.java b/src/FindTheLosersOfTheCircularGame.java new file mode 100644 index 0000000..ddd7af0 --- /dev/null +++ b/src/FindTheLosersOfTheCircularGame.java @@ -0,0 +1,26 @@ +// https://leetcode.com/problems/find-the-losers-of-the-circular-game +// T: O(N) +// S: O(N) + +import java.util.HashSet; +import java.util.Set; + +public class FindTheLosersOfTheCircularGame { + public int[] circularGameLosers(int n, int k) { + final Set players = new HashSet<>(); + for (int i = 0, turn = 1 ; ; i = (i + turn * k) % n, turn++) { + if (players.contains(i)) { + break; + } + players.add(i); + } + final int totalLosers = n - players.size(); + final int[] losers = new int[totalLosers]; + for (int i = 1, j = 0 ; i <= n ; i++) { + if (!players.contains(i - 1)) { + losers[j++] = i; + } + } + return losers; + } +} diff --git a/src/FindTheLuckyIntegerInAnArray.java b/src/FindTheLuckyIntegerInAnArray.java new file mode 100644 index 0000000..9ec28b1 --- /dev/null +++ b/src/FindTheLuckyIntegerInAnArray.java @@ -0,0 +1,32 @@ +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.PriorityQueue; +import java.util.Queue; + +public class FindTheLuckyIntegerInAnArray { + public int findLucky(int[] array) { + Map frequencies = getFrequencies(array); + Queue luckyIntegers = getLuckyIntegers(frequencies); + if (luckyIntegers.isEmpty()) return -1; + return luckyIntegers.poll(); + } + + private Map getFrequencies(int[] array) { + Map frequencies = new HashMap<>(); + for (int element : array) { + frequencies.put(element, frequencies.getOrDefault(element, 0) + 1); + } + return frequencies; + } + + private Queue getLuckyIntegers(Map frequencies){ + Queue luckyNumbers = new PriorityQueue<>(Comparator.reverseOrder()); + for (Map.Entry entry : frequencies.entrySet()) { + if (entry.getKey() == entry.getValue()) { + luckyNumbers.add(entry.getValue()); + } + } + return luckyNumbers; + } +} diff --git a/src/FindTheMaximumAchievableNumber.java b/src/FindTheMaximumAchievableNumber.java new file mode 100644 index 0000000..422271c --- /dev/null +++ b/src/FindTheMaximumAchievableNumber.java @@ -0,0 +1,9 @@ +// https://leetcode.com/problems/find-the-maximum-achievable-number +// T: O(1) +// S: O(1) + +public class FindTheMaximumAchievableNumber { + public int theMaximumAchievableX(int num, int t) { + return num + 2 * t; + } +} diff --git a/src/FindTheMaximumDivisibilityScore.java b/src/FindTheMaximumDivisibilityScore.java new file mode 100644 index 0000000..dfab7d6 --- /dev/null +++ b/src/FindTheMaximumDivisibilityScore.java @@ -0,0 +1,37 @@ +// https://leetcode.com/problems/find-the-maximum-divisibility-score +// m: length of divisors +// n: length of nums +// T: O(m * n) +// S: O(m) + +import java.util.HashSet; +import java.util.Set; + +public class FindTheMaximumDivisibilityScore { + public int maxDivScore(int[] nums, int[] divisors) { + final Set setDivisors = new HashSet<>(); + int maxDivisibilityScore = 0, minDivisor = Integer.MAX_VALUE; + for (int divisor : divisors) { + if (setDivisors.contains(divisor)) { + continue; + } + setDivisors.add(divisor); + final int divisorScore = getDivisorScore(nums, divisor); + if (divisorScore > maxDivisibilityScore) { + maxDivisibilityScore = divisorScore; + minDivisor = divisor; + } else if (divisorScore == maxDivisibilityScore) { + minDivisor = Math.min(minDivisor, divisor); + } + } + return minDivisor; + } + + private int getDivisorScore(int[] array, int divisor) { + int count = 0; + for (int element : array) { + if (element % divisor == 0) count++; + } + return count; + } +} diff --git a/src/FindTheMiddleIndexInArray.java b/src/FindTheMiddleIndexInArray.java new file mode 100644 index 0000000..a881510 --- /dev/null +++ b/src/FindTheMiddleIndexInArray.java @@ -0,0 +1,18 @@ +// https://leetcode.com/problems/find-the-middle-index-in-array +// T: O(N) +// S: O(1) + +import java.util.Arrays; + +public class FindTheMiddleIndexInArray { + public int findMiddleIndex(int[] nums) { + int leftSum = 0, rightSum = Arrays.stream(nums).sum() - nums[0]; + if (leftSum == rightSum) return 0; + for (int index = 1 ; index < nums.length ; index++) { + rightSum -= nums[index]; + leftSum += nums[index - 1]; + if (leftSum == rightSum) return index; + } + return -1; + } +} diff --git a/src/FindTheNumberOfGoodPairsI.java b/src/FindTheNumberOfGoodPairsI.java new file mode 100644 index 0000000..883f236 --- /dev/null +++ b/src/FindTheNumberOfGoodPairsI.java @@ -0,0 +1,50 @@ +// https://leetcode.com/problems/find-the-number-of-good-pairs-i +// x = largest possible integer +// T: O(n*sqrt(x) + m) +// S: O(n + m) + +import java.util.HashMap; +import java.util.Map; + +public class FindTheNumberOfGoodPairsI { + public int numberOfPairs(int[] array1, int[] array2, int k) { + final Map dividends = getDividendFrequencies(array1, k); + final Map divisors = getElementFrequencies(array2); + int pairs = 0; + + for (Map.Entry entry : dividends.entrySet()) { + final int dividend = entry.getKey(); + final int frequency = entry.getValue(); + + for (int i = 1 ; i * i <= dividend ; i++) { + if (dividend % i == 0) { + pairs += frequency * divisors.getOrDefault(i, 0); + if (i != dividend / i) { + pairs += frequency * divisors.getOrDefault(dividend / i, 0); + } + } + } + } + + return pairs; + } + + private static Map getElementFrequencies(int[] array) { + final Map frequencies = new HashMap<>(); + for (int element : array) { + frequencies.put(element, frequencies.getOrDefault(element, 0) + 1); + } + return frequencies; + } + + private static Map getDividendFrequencies(int[] array, int k) { + final Map frequencies = new HashMap<>(); + for (int element : array) { + if (element % k == 0) { + int quotient = element / k; + frequencies.put(quotient, frequencies.getOrDefault(quotient, 0) + 1); + } + } + return frequencies; + } +} diff --git a/src/FindThePeaks.java b/src/FindThePeaks.java new file mode 100644 index 0000000..cddbc34 --- /dev/null +++ b/src/FindThePeaks.java @@ -0,0 +1,20 @@ +// https://leetcode.com/problems/find-the-peaks +// T: O(n) +// S: O(1) + +import java.util.ArrayList; +import java.util.List; + +public class FindThePeaks { + public List findPeaks(int[] mountain) { + final List peaks = new ArrayList<>(); + + for (int i = 1 ; i < mountain.length - 1 ; i++) { + if (mountain[i] > mountain[i - 1] && mountain[i] > mountain[i + 1]) { + peaks.add(i); + } + } + + return peaks; + } +} diff --git a/src/FindThePivotInteger.java b/src/FindThePivotInteger.java new file mode 100644 index 0000000..75c8145 --- /dev/null +++ b/src/FindThePivotInteger.java @@ -0,0 +1,19 @@ +// https://leetcode.com/problems/find-the-pivot-integer +// T: O(N) +// S: O(1) + +public class FindThePivotInteger { + public int pivotInteger(int n) { + for (int pivot = 1, left = 1, right = summation(n) ; pivot <= n ; pivot++) { + if (left == right) return pivot; + if (left > right) break; + left += pivot + 1; + right -= pivot; + } + return -1; + } + + private int summation(int n) { + return (n * (n + 1)) / 2; + } +} diff --git a/src/FindTheSumOfEncryptedIntegers.java b/src/FindTheSumOfEncryptedIntegers.java new file mode 100644 index 0000000..aaae55d --- /dev/null +++ b/src/FindTheSumOfEncryptedIntegers.java @@ -0,0 +1,27 @@ +// https://leetcode.com/problems/find-the-sum-of-encrypted-integers +// T: O(N) +// S: O(1) + +public class FindTheSumOfEncryptedIntegers { + public int sumOfEncryptedInt(int[] array) { + int sum = 0; + for (int element : array) { + sum += encryptedInteger(element); + } + return sum; + } + + private static int encryptedInteger(int x) { + int maxDigit = 0, digits = 0; + while (x > 0) { + maxDigit = Math.max(maxDigit, x % 10); + digits++; + x /= 10; + } + int result = 0; + while (digits-- > 0) { + result = 10 * result + maxDigit; + } + return result; + } +} diff --git a/src/FindTheTownJudge.java b/src/FindTheTownJudge.java new file mode 100644 index 0000000..26d260c --- /dev/null +++ b/src/FindTheTownJudge.java @@ -0,0 +1,18 @@ +import java.util.HashMap; +import java.util.Map; + +public class FindTheTownJudge { + public int findJudge(int n, int[][] trust) { + Map inDegreeTrust = new HashMap<>(); + Map outDegreeTrust = new HashMap<>(); + for (int[] person : trust) { + inDegreeTrust.put(person[1], inDegreeTrust.getOrDefault(person[1], 0) + 1); + outDegreeTrust.put(person[0], inDegreeTrust.getOrDefault(person[0], 0) + 1); + } + for (int i = 1 ; i <= n ; i++) { + if (outDegreeTrust.getOrDefault(i, 0) == 0 && inDegreeTrust.getOrDefault(i, 0) == n - 1) + return i; + } + return -1; + } +} diff --git a/src/FindTheWidthOfColumnsOfAGrid.java b/src/FindTheWidthOfColumnsOfAGrid.java new file mode 100644 index 0000000..f1096aa --- /dev/null +++ b/src/FindTheWidthOfColumnsOfAGrid.java @@ -0,0 +1,20 @@ +// https://leetcode.com/problems/find-the-width-of-columns-of-a-grid +// m: rows in matrix +// n: columns in matrix +// T: O(m * n) +// S: O(n) + +public class FindTheWidthOfColumnsOfAGrid { + public int[] findColumnWidth(int[][] grid) { + final int columns = grid[0].length; + final int[] result = new int[columns]; + for (int column = 0 ; column < columns ; column++) { + int maxLen = 0; + for (int[] row : grid) { + maxLen = Math.max(maxLen, (String.valueOf(row[column])).length()); + } + result[column] = maxLen; + } + return result; + } +} diff --git a/src/FindTheWinningPlayerInCoinGame.java b/src/FindTheWinningPlayerInCoinGame.java new file mode 100644 index 0000000..78786a8 --- /dev/null +++ b/src/FindTheWinningPlayerInCoinGame.java @@ -0,0 +1,11 @@ +// https://leetcode.com/problems/find-the-winning-player-in-coin-game +// T: O(1) +// S: O(1) + +public class FindTheWinningPlayerInCoinGame { + public String losingPlayer(int x, int y) { + final int maxGames10CentCoins = y / 4; + final int maxGamesPossible = Math.min(x, maxGames10CentCoins); + return maxGamesPossible % 2 == 0 ? "Bob" : "Alice"; + } +} diff --git a/src/FindTheXOROfNumbersWhichAppearTwice.java b/src/FindTheXOROfNumbersWhichAppearTwice.java new file mode 100644 index 0000000..83cb97d --- /dev/null +++ b/src/FindTheXOROfNumbersWhichAppearTwice.java @@ -0,0 +1,20 @@ +// https://leetcode.com/problems/find-the-xor-of-numbers-which-appear-twice +// T: O(N) +// S: O(N) + +import java.util.HashSet; +import java.util.Set; + +public class FindTheXOROfNumbersWhichAppearTwice { + public int duplicateNumbersXOR(int[] array) { + final Set numbers = new HashSet<>(); + int result = 0; + for (int element : array) { + if (numbers.contains(element)) { + result ^= element; + } + numbers.add(element); + } + return result; + } +} diff --git a/src/FindWinnerOnATicTacToeGame.java b/src/FindWinnerOnATicTacToeGame.java new file mode 100644 index 0000000..c86b61a --- /dev/null +++ b/src/FindWinnerOnATicTacToeGame.java @@ -0,0 +1,34 @@ +public class FindWinnerOnATicTacToeGame { + public String tictactoe(int[][] moves) { + String winner = getWinnerInTicTacToe(moves); + if ("".equals(winner)) return moves.length == 9 ? "Draw" : "Pending"; + return winner; + } + + private String getWinnerInTicTacToe(int[][] moves) { + final int[] rows = new int[3], columns = new int[3]; + int d1 = 0, d2 = 0, k = 1; + for (int[] move : moves) { + rows[move[0]] += k; + columns[move[1]] += k; + if (move[0] == move[1]) d1 += k; + if (move[0] == 2 - move[1]) d2 += k; + k *= -1; + } + String result = winnerCheckInArray(rows); + if (!"".equals(result)) return result; + result = winnerCheckInArray(columns); + if (!"".equals(result)) return result; + if (d1 == 3 || d2 == 3) return "A"; + if (d1 == -3 || d2 == -3) return "B"; + return ""; + } + + private String winnerCheckInArray(int[] array) { + for (int element : array) { + if (element == 3) return "A"; + if (element == -3) return "B"; + } + return ""; + } +} diff --git a/src/FindWordsContainingCharacter.java b/src/FindWordsContainingCharacter.java new file mode 100644 index 0000000..9440972 --- /dev/null +++ b/src/FindWordsContainingCharacter.java @@ -0,0 +1,28 @@ +// https://leetcode.com/problems/find-words-containing-character +// T: O(|words| * |words[i].length|) +// S: O(1) + +import java.util.ArrayList; +import java.util.List; + +public class FindWordsContainingCharacter { + public List findWordsContaining(String[] words, char x) { + final List result = new ArrayList<>(); + for (int i = 0 ; i < words.length ; i++) { + if (containsCharacter(words[i], x)) { + result.add(i); + } + } + + return result; + } + + private static boolean containsCharacter(String s, char c) { + for (int i = 0 ; i < s.length() ; i++) { + if (s.charAt(i) == c) { + return true; + } + } + return false; + } +} diff --git a/src/FindWordsThatCanBeFormedByCharacters.java b/src/FindWordsThatCanBeFormedByCharacters.java new file mode 100644 index 0000000..1fc9867 --- /dev/null +++ b/src/FindWordsThatCanBeFormedByCharacters.java @@ -0,0 +1,32 @@ +import java.util.HashMap; +import java.util.Map; + +public class FindWordsThatCanBeFormedByCharacters { + public int countCharacters(String[] words, String chars) { + final Map characterFrequencies = getCharFrequencies(chars); + int result = 0; + for (String word : words) { + if (word.length() > chars.length()) continue; + Map wordCharFrequencies = getCharFrequencies(word); + if (canBeFormedBy(wordCharFrequencies, characterFrequencies)) { + result += word.length(); + } + } + return result; + } + + private Map getCharFrequencies(String string) { + Map frequencies = new HashMap<>(); + for (int index = 0 ; index < string.length() ; index++) { + frequencies.put(string.charAt(index), frequencies.getOrDefault(string.charAt(index), 0) + 1); + } + return frequencies; + } + + private boolean canBeFormedBy(Map frequencies1, Map frequencies2) { + for (Map.Entry entry : frequencies1.entrySet()) { + if (frequencies2.getOrDefault(entry.getKey(), 0) < entry.getValue()) return false; + } + return true; + } +} diff --git a/src/Finding3DigitEvenNumbers.java b/src/Finding3DigitEvenNumbers.java new file mode 100644 index 0000000..6bc09ef --- /dev/null +++ b/src/Finding3DigitEvenNumbers.java @@ -0,0 +1,57 @@ +// https://leetcode.com/problems/finding-3-digit-even-numbers +// T: O(N) +// S: O(N) + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Finding3DigitEvenNumbers { + public int[] findEvenNumbers(int[] digits) { + final Map frequencies = getFrequency(digits); + final List numbers = new ArrayList<>(); + for (int number = 100 ; number <= 999 ; number += 2) { + if (canBeFormed(number, frequencies)) { + numbers.add(number); + } + } + return toArray(numbers); + } + + private boolean canBeFormed(int number, Map digits) { + final Map numberDigits = getFrequency(number); + for (Map.Entry entry : numberDigits.entrySet()) { + if (digits.getOrDefault(entry.getKey(), 0) < entry.getValue()) { + return false; + } + } + return true; + } + + private int[] toArray(List list) { + final int[] array = new int[list.size()]; + for (int i = 0 ; i < list.size() ; i++) { + array[i] = list.get(i); + } + return array; + } + + private Map getFrequency(int[] array) { + final Map frequency = new HashMap<>(); + for (int element : array) { + frequency.put(element, frequency.getOrDefault(element, 0) + 1); + } + return frequency; + } + + private Map getFrequency(int number) { + final Map frequency = new HashMap<>(); + while (number > 0) { + int digit = number % 10; + frequency.put(digit, frequency.getOrDefault(digit, 0) + 1); + number /= 10; + } + return frequency; + } +} diff --git a/src/FirstLetterToAppearTwice.java b/src/FirstLetterToAppearTwice.java new file mode 100644 index 0000000..7843b26 --- /dev/null +++ b/src/FirstLetterToAppearTwice.java @@ -0,0 +1,19 @@ +// https://leetcode.com/problems/first-letter-to-appear-twice +// T: O(1) +// S: O(1) + +import java.util.HashSet; +import java.util.Set; + +public class FirstLetterToAppearTwice { + public char repeatedCharacter(String s) { + final Set characters = new HashSet<>(); + for (int index = 0 ; index < s.length() ; index++) { + if (characters.contains(s.charAt(index))) { + return s.charAt(index); + } + characters.add(s.charAt(index)); + } + return 'a'; + } +} diff --git a/src/FirstMissingPositive.java b/src/FirstMissingPositive.java new file mode 100644 index 0000000..1d063de --- /dev/null +++ b/src/FirstMissingPositive.java @@ -0,0 +1,35 @@ +// https://leetcode.com/problems/first-missing-positive +// T: O(N) +// S: O(1) + +public class FirstMissingPositive { + public int firstMissingPositive(int[] nums) { + int n = nums.length; + + // Use cycle sort to place positive elements smaller than n at the correct index + for (int i = 0 ; i < n ; ) { + if (nums[i] > 0 && nums[i] <= n && nums[i] != nums[nums[i] - 1]) { + swap(nums, i, nums[i] - 1); + } else { + i++; + } + } + + // Iterate through nums return smallest missing positive integer + for (int i = 0; i < n; i++) { + if (nums[i] != i + 1) { + return i + 1; + } + } + + // If all elements are at the correct index + // the smallest missing positive number is n + 1 + return n + 1; + } + + private static void swap(int[] nums, int i, int j) { + int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } +} diff --git a/src/FlattenAMultiLevelDoublyLinkedList.java b/src/FlattenAMultiLevelDoublyLinkedList.java new file mode 100644 index 0000000..ef0bea8 --- /dev/null +++ b/src/FlattenAMultiLevelDoublyLinkedList.java @@ -0,0 +1,49 @@ +// T: O(n) +// S: O(n) + +public class FlattenAMultiLevelDoublyLinkedList { + private static final class Node { + public int val; + public Node prev; + public Node next; + public Node child; + } + + public Node flatten(Node head) { + for (Node temp = head ; temp != null ; temp = temp.next) { + if (temp.child != null) { + Node lastNodeOfFlattenedChildren = flattenLinkedList(temp.child); + lastNodeOfFlattenedChildren.next = temp.next; + if (temp.next != null) { + temp.next.prev = lastNodeOfFlattenedChildren; + } + temp.next = temp.child; + temp.child.prev = temp; + temp.child = null; + } + } + return head; + } + + private Node flattenLinkedList(Node head) { + Node temp = head; + for (; temp.next != null ; temp = temp.next) { + if (temp.child != null) { + Node lastNodeOfFlattenedChildren = flattenLinkedList(temp.child); + lastNodeOfFlattenedChildren.next = temp.next; + temp.next.prev = lastNodeOfFlattenedChildren; + temp.next = temp.child; + temp.child.prev = temp; + temp.child = null; + } + } + if (temp.child != null) { + Node lastNodeOfFlattenedChildren = flattenLinkedList(temp.child); + temp.next = temp.child; + temp.child.prev = temp; + temp.child = null; + return lastNodeOfFlattenedChildren; + } + return temp; + } +} diff --git a/src/FlattenBinaryTreeToLinkedList.java b/src/FlattenBinaryTreeToLinkedList.java new file mode 100644 index 0000000..6e2643f --- /dev/null +++ b/src/FlattenBinaryTreeToLinkedList.java @@ -0,0 +1,26 @@ +// https://leetcode.com/problems/flatten-binary-tree-to-linked-list +// T: O(n) +// S: O(log(n)) + +public class FlattenBinaryTreeToLinkedList { + public static void flatten(TreeNode root) { + flattenAndGetLastNode(root); + } + + private static TreeNode flattenAndGetLastNode(TreeNode root) { + if (root == null) return null; + + TreeNode leftLast = flattenAndGetLastNode(root.left); + TreeNode rightLast = flattenAndGetLastNode(root.right); + + if (root.left != null) { + leftLast.right = root.right; + root.right = root.left; + root.left = null; + } + + return rightLast != null + ? rightLast + : (leftLast == null ? root : leftLast); + } +} diff --git a/src/FlipGame.java b/src/FlipGame.java new file mode 100644 index 0000000..f301fd1 --- /dev/null +++ b/src/FlipGame.java @@ -0,0 +1,23 @@ +// https://leetcode.com/problems/flip-game +// N = |currentState| +// T: O(N^2) +// S: O(N^2) + +import java.util.ArrayList; +import java.util.List; + +public class FlipGame { + public List generatePossibleNextMoves(String currentState) { + final List result = new ArrayList<>(); + for (int i = 0 ; i < currentState.length() - 1 ; i++) { + if (currentState.charAt(i) == '+' && currentState.charAt(i + 1) == '+') { + result.add(flip(currentState, i)); + } + } + return result; + } + + private static String flip(String state, int index) { + return state.substring(0, index) + "--" + state.substring(index + 2); + } +} diff --git a/src/FlippingAnImage.java b/src/FlippingAnImage.java new file mode 100644 index 0000000..8108fab --- /dev/null +++ b/src/FlippingAnImage.java @@ -0,0 +1,16 @@ +public class FlippingAnImage { + public int[][] flipAndInvertImage(int[][] image) { + final int rows = image.length, columns = image[0].length; + int temp; + + for (int row = 0 ; row < rows ; row++) { + for (int column = 0 ; column < (columns + 1) / 2 ; column++) { + temp = image[row][column] ^ 1; + image[row][column] = image[row][columns - column - 1] ^ 1; + image[row][columns - column - 1] = temp; + } + } + + return image; + } +} diff --git a/src/FloodFill.java b/src/FloodFill.java new file mode 100644 index 0000000..f3ef210 --- /dev/null +++ b/src/FloodFill.java @@ -0,0 +1,25 @@ +public class FloodFill { + private int[][] image; + private int height; + private int width; + + public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { + this.image = image; + height = image.length; + width = image[0].length; + if (image[sr][sc] != newColor) { + colorPixel(sr, sc, image[sr][sc], newColor); + } + return image; + } + + private void colorPixel(int row, int col, int oldColor, int newColor) { + if (image[row][col] != newColor) { + image[row][col] = newColor; + if (row - 1 >= 0 && image[row - 1][col] == oldColor) colorPixel(row - 1, col, oldColor, newColor); + if (col + 1 < width && image[row][col + 1] == oldColor) colorPixel(row, col + 1, oldColor, newColor); + if (row + 1 < height && image[row + 1][col] == oldColor) colorPixel(row + 1, col, oldColor, newColor); + if (col - 1 >= 0 && image[row][col - 1] == oldColor) colorPixel(row, col - 1, oldColor, newColor); + } + } +} diff --git a/src/FormSmallestNumberFromTwoDigitArrays.java b/src/FormSmallestNumberFromTwoDigitArrays.java new file mode 100644 index 0000000..7b098d1 --- /dev/null +++ b/src/FormSmallestNumberFromTwoDigitArrays.java @@ -0,0 +1,58 @@ +// https://leetcode.com/problems/form-smallest-number-from-two-digit-arrays +// T: O(N log(N) + M log(M)) +// S: O(log(N) + log(M)) + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +public class FormSmallestNumberFromTwoDigitArrays { + public int minNumber(int[] nums1, int[] nums2) { + final Set intersection = intersection(nums1, nums2); + + if (!intersection.isEmpty()) { + final int[] digits = toArray(intersection); + Arrays.sort(digits); + return digits[0]; + } + + Arrays.sort(nums1); + Arrays.sort(nums2); + final int smallerDigit = Math.min(nums1[0], nums2[0]); + final int largerDigit = Math.max(nums1[0], nums2[0]); + return smallerDigit * 10 + largerDigit; + } + + private Set intersection(int[] array1, int[] array2) { + final Set set1 = toSet(array1); + final Set set2 = toSet(array2); + return intersection(set1, set2); + } + + private Set toSet(int[] array) { + final Set set = new HashSet<>(); + for (int element : array) { + set.add(element); + } + return set; + } + + private Set intersection(Set set1, Set set2) { + final Set set = new HashSet<>(); + for (int element : set1) { + if (set2.contains(element)) { + set.add(element); + } + } + return set; + } + + private int[] toArray(Set set) { + final int[] array = new int[set.size()]; + int index = 0; + for (int element : set) { + array[index++] = element; + } + return array; + } +} diff --git a/src/FourSum.java b/src/FourSum.java new file mode 100644 index 0000000..b17a273 --- /dev/null +++ b/src/FourSum.java @@ -0,0 +1,25 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class FourSum { + public List> fourSum(int[] nums, int target) { + Arrays.sort(nums); + final Set> quadruplets = new HashSet<>(); + + for (int a = 0 ; a < nums.length - 3 ; a++) { + for (int b = a + 1 ; b < nums.length - 2 ; b++) { + for (int c = b + 1, d = nums.length - 1 ; c < d ; ) { + int sum = nums[a] + nums[b] + nums[c] + nums[d]; + if (sum == target) quadruplets.add(List.of(nums[a], nums[b], nums[c++], nums[d--])); + else if (sum < target) c++; + else d--; + } + } + } + + return new ArrayList<>(quadruplets); + } +} diff --git a/src/FractionToRecurringDecimal.java b/src/FractionToRecurringDecimal.java new file mode 100644 index 0000000..ed861cb --- /dev/null +++ b/src/FractionToRecurringDecimal.java @@ -0,0 +1,48 @@ +// https://leetcode.com/problems/fraction-to-recurring-decimal +// T: O(log(n / d)) but not sure, could use some mathematician's help +// S: O(log(n / d)) + +import java.util.HashMap; +import java.util.Map; + +public class FractionToRecurringDecimal { + private static final String ZERO = "0"; + + public String fractionToDecimal(long numerator, long denominator) { + if (numerator == 0) return ZERO; + + StringBuilder result = new StringBuilder(); + result.append(isNegative(numerator, denominator) ? "-" : ""); + + numerator = Math.abs(numerator); + denominator = Math.abs(denominator); + + // integral part + result.append(numerator / denominator); + numerator %= denominator; + if (numerator == 0) return result.toString(); + + // fractional part + result.append("."); + Map map = new HashMap<>(); + map.put(numerator, result.length()); + + while (numerator != 0) { + numerator *= 10; + result.append(numerator / denominator); + numerator %= denominator; + if (map.containsKey(numerator)) { + int index = map.get(numerator); + result.insert(index, "("); + result.append(")"); + break; + } else map.put(numerator, result.length()); + } + + return result.toString(); + } + + private boolean isNegative(long numerator, long denominator) { + return (numerator > 0) ^ (denominator > 0); + } +} diff --git a/src/FurthestPointFromOrigin.java b/src/FurthestPointFromOrigin.java new file mode 100644 index 0000000..5879bc0 --- /dev/null +++ b/src/FurthestPointFromOrigin.java @@ -0,0 +1,23 @@ +// https://leetcode.com/problems/furthest-point-from-origin +// T: O(N) +// S: O(1) + +public class FurthestPointFromOrigin { + public int furthestDistanceFromOrigin(String moves) { + final int numberOfLeftMoves = numberOf(moves, 'L'); + final int numberOfRightMoves = numberOf(moves, 'R'); + final int numberOfFreeMoves = numberOf(moves, '_'); + + return Math.abs(numberOfLeftMoves - numberOfRightMoves) + numberOfFreeMoves; + } + + private static int numberOf(final String moves, final char c) { + int count = 0; + for (int i = 0 ; i < moves.length() ; i++) { + if (moves.charAt(i) == c) { + count++; + } + } + return count; + } +} diff --git a/src/GameOfLife.java b/src/GameOfLife.java new file mode 100644 index 0000000..ebeb019 --- /dev/null +++ b/src/GameOfLife.java @@ -0,0 +1,55 @@ +// https://leetcode.com/problems/game-of-life + +import java.util.Arrays; + +public class GameOfLife { + private static int rows, columns; + + public static void gameOfLife(int[][] board) { + rows = board.length; + columns = board[0].length; + final int[][] adjacentLiveSquares = getAdjacentLiveSquares(board); + System.out.println(Arrays.deepToString(adjacentLiveSquares)); + + for (int row = 0 ; row < rows ; row++) { + for (int column = 0 ; column < columns ; column++) { + if (board[row][column] == 1) { + if (adjacentLiveSquares[row][column] < 2 || adjacentLiveSquares[row][column] > 3) { + board[row][column] = 0; + } + } else { + if (adjacentLiveSquares[row][column] == 3) { + board[row][column] = 1; + } + } + } + } + } + + private static int[][] getAdjacentLiveSquares(int[][] board) { + final int[][] result = new int[rows][columns]; + + for (int row = 0 ; row < rows ; row++) { + for (int column = 0 ; column < columns ; column++) { + result[row][column] = (row > 0 ? getRowSum(board, row - 1, column) : 0) + + (row + 1 < rows ? getRowSum(board, row + 1, column) : 0) + + (column > 0 ? board[row][column - 1] : 0) + + (column + 1 < columns ? board[row][column + 1] : 0); + } + } + + return result; + } + + private static int getRowSum(int[][] board, int row, int column) { + return board[row][column] + + (column - 1 >= 0 ? board[row][column - 1] : 0) + + (column + 1 < columns ? board[row][column + 1] : 0); + } + + public static void main(String[] args) { + int[][] result = new int[][] {{0,1,0},{0,0,1},{1,1,1},{0,0,0}}; + gameOfLife(result); + System.out.println(Arrays.deepToString(result)); + } +} diff --git a/src/GasStation.java b/src/GasStation.java new file mode 100644 index 0000000..29384b2 --- /dev/null +++ b/src/GasStation.java @@ -0,0 +1,27 @@ +// https://leetcode.com/problems/gas-station +// T: O(n) +// S: O(1) + +public class GasStation { + public int canCompleteCircuit(int[] gas, int[] cost) { + if (sum(gas) < sum(cost)) return -1; + + int startIndex = 0; + for (int i = 0, total = 0 ; i < gas.length ; i++) { + total += gas[i] - cost[i]; + if (total < 0) { + total = 0; + startIndex = i + 1; + } + } + return startIndex; + } + + private int sum(int[] array) { + int sum = 0; + for (int element : array) { + sum += element; + } + return sum; + } +} diff --git a/src/GenerateAStringWithCharactersThatHaveOddCounts.java b/src/GenerateAStringWithCharactersThatHaveOddCounts.java new file mode 100644 index 0000000..a7c91b5 --- /dev/null +++ b/src/GenerateAStringWithCharactersThatHaveOddCounts.java @@ -0,0 +1,7 @@ +public class GenerateAStringWithCharactersThatHaveOddCounts { + public String generateTheString(int n) { + if ((n & 1) == 0) { + return "a".repeat(n - 1) + "b"; + } return "a".repeat(n); + } +} diff --git a/src/GenerateParentheses.java b/src/GenerateParentheses.java new file mode 100644 index 0000000..3417e29 --- /dev/null +++ b/src/GenerateParentheses.java @@ -0,0 +1,40 @@ +// https://leetcode.com/problems/generate-parentheses +// T: O(Catalan-number(n)) or O(4^n/sqrt(n)) +// S: O(Catalan-number(n)) or O(4^n/sqrt(n)) + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class GenerateParentheses { + private static final Map> VALID_PARENTHESES = new HashMap<>(); + + static { + VALID_PARENTHESES.put(0, List.of("")); + VALID_PARENTHESES.put(1, List.of("()")); + for (int i = 2 ; i <= 8 ; i++) { + addValidParentheses(i); + } + } + + private static void addValidParentheses(int i) { + final List result = new ArrayList<>(); + addValidParentheses(i, result); + VALID_PARENTHESES.put(i, result); + } + + private static void addValidParentheses(int i, List result) { + for (int k = 0 ; k < i ; k++) { + for (String s1 : VALID_PARENTHESES.get(i - k - 1)) { + for (String s2 : VALID_PARENTHESES.get(k)) { + result.add("(" + s1 + ")" + s2); + } + } + } + } + + public List generateParenthesis(int n) { + return VALID_PARENTHESES.get(n); + } +} diff --git a/src/GetMaximumInGeneratedArray.java b/src/GetMaximumInGeneratedArray.java new file mode 100644 index 0000000..7ae1d14 --- /dev/null +++ b/src/GetMaximumInGeneratedArray.java @@ -0,0 +1,15 @@ +import java.util.Arrays; + +public class GetMaximumInGeneratedArray { + public int getMaximumGenerated(int n) { + if (n == 0) return 0; + final int[] array = new int[n + 1]; + array[0] = 0; + array[1] = 1; + for (int index = 2 ; index < array.length ; index++) { + if ((index & 1) == 0) array[index] = array[index / 2]; + else array[index] = array[index / 2] + array[index - index / 2]; + } + return Arrays.stream(array).max().getAsInt(); + } +} diff --git a/src/GoalParserInterpretation.java b/src/GoalParserInterpretation.java new file mode 100644 index 0000000..6797bbb --- /dev/null +++ b/src/GoalParserInterpretation.java @@ -0,0 +1,18 @@ +public class GoalParserInterpretation { + public String interpret(String command) { + final StringBuilder result = new StringBuilder(); + for (int index = 0 ; index < command.length() ; ) { + if (command.charAt(index) == 'G') { + result.append('G'); + index++; + } else if (command.charAt(index + 1) == ')') { + result.append('o'); + index += 2; + } else { + result.append("al"); + index += 4; + } + } + return result.toString(); + } +} diff --git a/src/GoatLatin.java b/src/GoatLatin.java new file mode 100644 index 0000000..f4b89ca --- /dev/null +++ b/src/GoatLatin.java @@ -0,0 +1,52 @@ +import java.util.Set; + +public class GoatLatin { + private static final Set VOWELS = Set.of('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'); + + public String toGoatLatin(String sentence) { + StringBuilder result = new StringBuilder(), word = new StringBuilder(); + char firstLetter = ' '; + int wordCount = 1; + boolean vowelWord = false, newWord = true; + for (int index = 0 ; index < sentence.length() ; index++) { + if (newWord) { + if (index == sentence.length() - 1) { + result.append(toGoatLatin(wordCount, new StringBuilder(), + false, sentence.charAt(index))); + break; + } + if (isVowel(sentence.charAt(index))) { + vowelWord = true; + word.append(sentence.charAt(index)); + } else { + vowelWord = false; + firstLetter = sentence.charAt(index); + } + + newWord = false; + } else if (sentence.charAt(index) == ' ' || index == sentence.length() - 1) { + newWord = true; + if (index == sentence.length() - 1) word.append(sentence.charAt(index)); + result.append(toGoatLatin(wordCount, word, vowelWord, firstLetter)); + word = new StringBuilder(); + wordCount++; + } else { + word.append(sentence.charAt(index)); + } + } + return result.toString(); + } + + private StringBuilder toGoatLatin(int wordCount, StringBuilder word, boolean vowelWord, char firstLetter) { + return new StringBuilder() + .append(wordCount == 1 ? "" : ' ') + .append(word) + .append(vowelWord ? "" : firstLetter) + .append("ma") + .append("a".repeat(wordCount)); + } + + private boolean isVowel(char character) { + return VOWELS.contains(character); + } +} diff --git a/src/GraphValidTree.java b/src/GraphValidTree.java new file mode 100644 index 0000000..da28c61 --- /dev/null +++ b/src/GraphValidTree.java @@ -0,0 +1,59 @@ +// https://leetcode.com/problems/graph-valid-tree +// T: O(N) +// S: O(N) + +public class GraphValidTree { + private static final class DisjointSet { + private final int[] root, rank; + + public DisjointSet(int size) { + root = new int[size]; + rank = new int[size]; + for (int i = 0 ; i < size ; i++) { + root[i] = i; + rank[i] = 1; + } + } + + public int find(int num) { + if (root[num] == num) { + return num; + } + return root[num] = find(root[num]); + } + + public boolean areConnected(int x, int y) { + return find(x) == find(y); + } + + public void union(int x, int y) { + final int rootX = find(x), rootY = find(y); + if (rootX == rootY) { + return; + } + if (rank[rootX] < rank[rootY]) { + root[rootX] = rootY; + } else if (rank[rootX] > rank[rootY]) { + root[rootY] = rootX; + } else { + root[rootY] = rootX; + rank[rootX]++; + } + } + } + + public boolean validTree(int n, int[][] edges) { + if (edges.length != n - 1) { + return false; + } + + final DisjointSet disjointSet = new DisjointSet(n); + for (int[] edge : edges) { + if (disjointSet.areConnected(edge[0], edge[1])) { + return false; + } + disjointSet.union(edge[0], edge[1]); + } + return true; + } +} diff --git a/src/GrayCode.java b/src/GrayCode.java new file mode 100644 index 0000000..40525cd --- /dev/null +++ b/src/GrayCode.java @@ -0,0 +1,19 @@ +// https://leetcode.com/problems/gray-code +// T: O(2 ^ n) +// S: O(2 ^ n) + +import java.util.ArrayList; +import java.util.List; + +public class GrayCode { + public List grayCode(int n) { + final List result = new ArrayList<>(1 << n); + result.add(0); + for (int i = 0, factor = 1 ; i < n ; i++, factor *= 2) { + for (int j = factor - 1 ; j >= 0 ; j--) { + result.add(result.get(j) + factor); + } + } + return result; + } +} diff --git a/src/GreatestCommonDivisorOfStrings.java b/src/GreatestCommonDivisorOfStrings.java new file mode 100644 index 0000000..bc73865 --- /dev/null +++ b/src/GreatestCommonDivisorOfStrings.java @@ -0,0 +1,17 @@ +public class GreatestCommonDivisorOfStrings { + public String gcdOfStrings(String str1, String str2) { + if (!patternExist(str1, str2)) return ""; + return str1.substring(0, gcd(str1.length(), str2.length())); + } + + private boolean patternExist(String str1, String str2) { + for (int i = 0, j = 0 ; i < str1.length() ; i++, j = (j + 1) % str2.length()) { + if (str1.charAt(i) != str2.charAt(j)) return false; + } + return true; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/src/GreatestEnglishLetterInUpperAndLowerCase.java b/src/GreatestEnglishLetterInUpperAndLowerCase.java new file mode 100644 index 0000000..b8c55ae --- /dev/null +++ b/src/GreatestEnglishLetterInUpperAndLowerCase.java @@ -0,0 +1,42 @@ +// https://leetcode.com/problems/greatest-english-letter-in-upper-and-lower-case +// T: O(|s|) +// S: O(1) + +import java.util.HashSet; +import java.util.Set; + +public class GreatestEnglishLetterInUpperAndLowerCase { + public String greatestLetter(String s) { + final Set lowercaseLetters = getLowercaseLetters(s); + final Set uppercaseLetters = getUppercaseLetters(s); + char maxLetter = 'a' - 1; + + for (char letter : lowercaseLetters) { + if (uppercaseLetters.contains(Character.toUpperCase(letter)) && letter > maxLetter) { + maxLetter = letter; + } + } + + return maxLetter >= 'a' ? (Character.toUpperCase(maxLetter) + "") : ""; + } + + private Set getUppercaseLetters(String string) { + final Set set = new HashSet<>(); + for (int i = 0 ; i < string.length() ; i++) { + if (Character.isUpperCase(string.charAt(i))) { + set.add(string.charAt(i)); + } + } + return set; + } + + private Set getLowercaseLetters(String string) { + final Set set = new HashSet<>(); + for (int i = 0 ; i < string.length() ; i++) { + if (Character.isLowerCase(string.charAt(i))) { + set.add(string.charAt(i)); + } + } + return set; + } +} diff --git a/src/GroupAnagrams.java b/src/GroupAnagrams.java new file mode 100644 index 0000000..3d0e000 --- /dev/null +++ b/src/GroupAnagrams.java @@ -0,0 +1,33 @@ +// https://leetcode.com/problems/group-anagrams +// T: O(|words| * |words[i]|) +// S: O(|words| * |words[i]|) + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class GroupAnagrams { + public List> groupAnagrams(String[] words) { + final Map> anagrams = new HashMap<>(); + for (String word : words) { + final String signature = getSignature(word); + if (anagrams.containsKey(signature)) { + anagrams.get(signature).add(word); + } else { + List list = new ArrayList<>(); + list.add(word); + anagrams.put(signature, list); + } + } + return new ArrayList<>(anagrams.values()); + } + + private String getSignature(String string) { + final char[] array = new char[26]; + for (int i = 0 ; i < string.length() ; i++) { + array[string.charAt(i) - 'a']++; + } + return String.valueOf(array); + } +} diff --git a/src/HIndex.java b/src/HIndex.java new file mode 100644 index 0000000..9c4d750 --- /dev/null +++ b/src/HIndex.java @@ -0,0 +1,34 @@ +// https://leetcode.com/problems/h-index +// T: O(N) +// S: O(N) + +import java.util.HashMap; +import java.util.Map; + +public class HIndex { + public int hIndex(int[] citations) { + final Map citationFrequencies = getFrequencies(citations); + final int maxCitation = max(citations); + for (int hIndex = maxCitation, papers = 0 ; hIndex >= 0 ; hIndex--) { + papers += citationFrequencies.getOrDefault(hIndex, 0); + if (papers >= hIndex) return hIndex; + } + return 0; + } + + private int max(int[] array) { + int result = 0; + for (int element : array) { + result = Math.max(result, element); + } + return result; + } + + private Map getFrequencies(int[] array) { + final Map frequencies = new HashMap<>(); + for (int element : array) { + frequencies.put(element, frequencies.getOrDefault(element, 0) + 1); + } + return frequencies; + } +} diff --git a/src/HIndexII.java b/src/HIndexII.java new file mode 100644 index 0000000..4a30b0d --- /dev/null +++ b/src/HIndexII.java @@ -0,0 +1,20 @@ +// https://leetcode.com/problems/h-index-ii +// T: O(log(N)) +// S: O(1) + +public class HIndexII { + public static void main(String[] args) { + System.out.println(hIndex(new int[] {0, 5, 5, 5, 5})); + } + + public static int hIndex(int[] citations) { + int left = 0, right = citations.length - 1, middle; + while (left <= right) { + middle = left + (right - left) / 2; + if (citations[middle] == citations.length - middle) return citations[middle]; + else if (citations[middle] > citations.length - middle) right = middle - 1; + else left = middle + 1; + } + return citations.length - left; + } +} diff --git a/src/HarshadNumber.java b/src/HarshadNumber.java new file mode 100644 index 0000000..a7ba4b8 --- /dev/null +++ b/src/HarshadNumber.java @@ -0,0 +1,22 @@ +// https://leetcode.com/problems/harshad-number +// T: O(log(N)) +// S: O(1) + +public class HarshadNumber { + public int sumOfTheDigitsOfHarshadNumber(int x) { + final int sumOfDigits = sumOfDigits(x); + if (x % sumOfDigits == 0) { + return sumOfDigits; + } + return -1; + } + + private static int sumOfDigits(int x) { + int sum = 0; + while (x > 0) { + sum += x % 10; + x /= 10; + } + return sum; + } +} diff --git a/src/Heaters.java b/src/Heaters.java new file mode 100644 index 0000000..451abcc --- /dev/null +++ b/src/Heaters.java @@ -0,0 +1,33 @@ +import java.util.Arrays; + +public class Heaters { + private static int binarySearch(int[] array, int element) { + int left = 0, right = array.length - 1, middle; + while (left <= right) { + middle = (left + right) / 2; + if (array[middle] == element) return middle; + else if (array[middle] < element) left = middle + 1; + else right = middle - 1; + } + return left; + } + + public static void main(String[] args) { + System.out.println(findRadius(new int[] {1, 2, 3, 4}, new int[] {1, 4})); + } + + public static int findRadius(int[] houses, int[] heaters) { + Arrays.sort(heaters); + int minRadius = 0, leftRadius, rightRadius; + for (int house : houses) { + int index = binarySearch(heaters, house); + if (index < heaters.length && house == heaters[index]) { + continue; + } + leftRadius = index > 0 ? house - heaters[index - 1] : Integer.MAX_VALUE; + rightRadius = (index == heaters.length ? Integer.MAX_VALUE : heaters[index] - house); + minRadius = Math.max(minRadius, Math.min(leftRadius, rightRadius)); + } + return minRadius; + } +} diff --git a/src/HelloWorld.java b/src/HelloWorld.java new file mode 100644 index 0000000..e483972 --- /dev/null +++ b/src/HelloWorld.java @@ -0,0 +1,96 @@ +import java.util.*; + +public class HelloWorld { + public static List> buyVolumes(List volumes) { + if (volumes.isEmpty()) { + return new ArrayList<>(); + } + + final List> result = new ArrayList<>(); + int max = 0, required = 1, elements = 0; + boolean found = false; + for (int volumeNumber : volumes) { + max = Math.max(max, volumeNumber); + elements++; + if (volumeNumber == required) { + found = true; + } + if (found) { + if (elements == max - required + 1) { + result.add(sorted(required, max)); + elements = 0; + required = max + 1; + found = false; + } else { + result.add(List.of(-1)); + } + } else { + result.add(List.of(-1)); + } + } + return result; + } + + private static List sorted(int start, int end) { + final List result = new ArrayList<>(); + for (int element = start ; element <= end ; element++) { + result.add(element); + } + return result; + } + + private static List hello(List prices, List start, List end, List querries) { + final Map orderPrices = getPricesFrequency(prices, start, end); + final long[][] pairs = createPairs(orderPrices); + final List result = new ArrayList<>(); + for (int query : querries) { + final int index = binarySearch(pairs, query - 1); + if (pairs[index][0] == query - 1) { + result.add(pairs[index][1]); + } else { + result.add(pairs[index - 1][1]); + } + } + return result; + } + + private static Map getPricesFrequency(List prices, List start, List end) { + final Map result = new HashMap<>(); + final int queries = start.size(); + for (int i = 0 ; i < queries ; i++) { + final int startIndex = start.get(i), endIndex = end.get(i); + addToFrequencies(result, prices, startIndex, endIndex); + } + return result; + } + + private static void addToFrequencies(Map frequencies, List prices, int start, int end) { + for (int i = start ; i <= end ; i++) { + frequencies.put(prices.get(i), frequencies.getOrDefault(prices.get(i), 0L) + 1); + } + } + + private static long[][] createPairs(Map frequencies) { + final long[][] result = new long[frequencies.size()][2]; + int k = 0; + for (Map.Entry entry : frequencies.entrySet()) { + result[k++] = new long[] {entry.getKey(), entry.getValue()}; + } + for (int i = 1 ; i < result.length ; i++) { + result[i][1] += result[i - 1][1]; + } + Arrays.sort(result, Comparator.comparingLong(a -> a[0])); + return result; + } + + private static int binarySearch(long[][] array, int x) { + int left = 0, right = array.length - 1, middle; + while (left <= right) { + middle = left + (right - left) / 2; + if (array[middle][0] == x) return middle; + else if (array[middle][0] < x) left = middle + 1; + else right = middle - 1; + } + return left; + } + } diff --git a/src/HouseRobberII.java b/src/HouseRobberII.java new file mode 100644 index 0000000..d00072a --- /dev/null +++ b/src/HouseRobberII.java @@ -0,0 +1,25 @@ +// https://leetcode.com/problems/house-robber-ii +// T: O(N) +// S: O(1) + +public class HouseRobberII { + public int rob(int[] array) { + if (array.length == 1) return array[0]; + if (array.length == 2) return Math.max(array[0], array[1]); + + return Math.max( + rob(array, 0, array.length - 2), + rob(array, 1, array.length - 1) + ); + } + + public int rob(int[] array, int start, int end) { + int a = array[start], b = Math.max(array[start], array[start + 1]), c = Math.max(a, b); + for (int i = start + 2 ; i <= end ; i++) { + c = Math.max(array[i] + a, b); + a = b; + b = c; + } + return c; + } +} diff --git a/src/HowManyNumbersAreSmallerThanCurrentNumber.java b/src/HowManyNumbersAreSmallerThanCurrentNumber.java new file mode 100644 index 0000000..ce51557 --- /dev/null +++ b/src/HowManyNumbersAreSmallerThanCurrentNumber.java @@ -0,0 +1,27 @@ +public class HowManyNumbersAreSmallerThanCurrentNumber { + public int[] smallerNumbersThanCurrent(int[] nums) { + final int[] elementsFrequency = getElementsFrequency(nums); + final int[] elementsSmallerThan = countSmallerThan(elementsFrequency); + final int[] result = new int[nums.length]; + for (int i = 0 ; i < nums.length ; i++) { + result[i] = elementsSmallerThan[nums[i]]; + } + return result; + } + + private int[] getElementsFrequency(int[] array) { + final int[] frequency = new int[101]; + for (int element : array) { + frequency[element]++; + } + return frequency; + } + + private int[] countSmallerThan(int[] frequency) { + final int[] smallerThan = new int[101]; + for (int i = 1 ; i < 101 ; i++) { + smallerThan[i] = smallerThan[i - 1] + frequency[i - 1]; + } + return smallerThan; + } +} diff --git a/src/ImageSmoother.java b/src/ImageSmoother.java new file mode 100644 index 0000000..e77308a --- /dev/null +++ b/src/ImageSmoother.java @@ -0,0 +1,18 @@ +public class ImageSmoother { + public int[][] imageSmoother(int[][] img) { + int[][] result = new int[img.length][img[0].length]; + int sum, count, rows = img.length, columns = img[0].length; + for (int row = 0 ; row < rows; row++) { + for (int column = 0 ; column < columns ; column++) { + sum = count = 0; + for (int k_row = row == 0 ? row : row - 1 ; k_row <= (row == rows - 1 ? row : row + 1) ; k_row++) { + for (int k_column = column == 0 ? column : column - 1 ; k_column <= (column == columns - 1 ? column : column + 1) ; k_column++, count++) { + sum += img[k_row][k_column]; + } + } + result[row][column] = sum / count; + } + } + return result; + } +} diff --git a/src/IncreasingDecreasingString.java b/src/IncreasingDecreasingString.java new file mode 100644 index 0000000..d3ee300 --- /dev/null +++ b/src/IncreasingDecreasingString.java @@ -0,0 +1,29 @@ +public class IncreasingDecreasingString { + public String sortString(String s) { + final int[] frequency = getFrequency(s); + final StringBuilder result = new StringBuilder(); + while (result.length() < s.length()) { + for (int i = 0 ; i < frequency.length ; i++) { + if (frequency[i] > 0) { + result.append((char) ('a' + i)); + frequency[i]--; + } + } + for (int i = frequency.length - 1 ; i >= 0 ; i--) { + if (frequency[i] > 0) { + result.append((char) ('a' + i)); + frequency[i]--; + } + } + } + return result.toString(); + } + + private int[] getFrequency(String string) { + final int[] frequencies = new int[26]; + for (int i = 0 ; i < string.length() ; i++) { + frequencies[string.charAt(i) - 'a']++; + } + return frequencies; + } +} diff --git a/src/IncreasingOrderSearchTree.java b/src/IncreasingOrderSearchTree.java new file mode 100644 index 0000000..1579739 --- /dev/null +++ b/src/IncreasingOrderSearchTree.java @@ -0,0 +1,19 @@ +public class IncreasingOrderSearchTree { + TreeNode current; + + public TreeNode increasingBST(TreeNode root) { + if (root == null) return null; + TreeNode result = new TreeNode(); + current = result; + inOrderTraversal(root); + return result.right; + } + + private void inOrderTraversal(TreeNode root) { + if (root == null) return; + inOrderTraversal(root.left); + current.right = new TreeNode(root.val); + current = current.right; + inOrderTraversal(root.right); + } +} diff --git a/src/InsertDeleteGetRandomO1.java b/src/InsertDeleteGetRandomO1.java new file mode 100644 index 0000000..a92e73b --- /dev/null +++ b/src/InsertDeleteGetRandomO1.java @@ -0,0 +1,45 @@ +// https://leetcode.com/problems/insert-delete-getrandom-o1 + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; + +public class InsertDeleteGetRandomO1 { + static class RandomizedSet { + private final Random random = new Random(); + private final List list = new ArrayList<>(); + private final Map indexMapping = new HashMap<>(); + + public boolean insert(int val) { + if (indexMapping.containsKey(val)) { + return false; + } + list.add(val); + indexMapping.put(val, list.size() - 1); + return true; + } + + private int last() { + return this.list.getLast(); + } + + public boolean remove(int val) { + if (!indexMapping.containsKey(val)) { + return false; + } + final int index = indexMapping.get(val); + indexMapping.put(last(), index); + indexMapping.remove(val); + list.set(index, last()); + list.removeLast(); + return true; + } + + public int getRandom() { + final int randomIndex = random.nextInt(list.size()); + return list.get(randomIndex); + } + } +} diff --git a/src/InsertInterval.java b/src/InsertInterval.java new file mode 100644 index 0000000..774275a --- /dev/null +++ b/src/InsertInterval.java @@ -0,0 +1,54 @@ +// https://leetcode.com/problems/insert-interval/submissions +// T: O(n) +// S: O(n) + +public class InsertInterval { + public int[][] insert(int[][] intervals, int[] newInterval) { + if (intervals.length == 0) return new int[][] {newInterval}; + final int startIndex = search(intervals, newInterval[0]); + final int endIndex = search(intervals, newInterval[1]); + final int newStart = startIndex >= intervals.length + ? newInterval[0] + : Math.min(intervals[startIndex][0], newInterval[0]); + final int newEnd = endIndex >= intervals.length + ? newInterval[1] + : newInterval[1] >= intervals[endIndex][0] ? intervals[endIndex][1] : newInterval[1]; + final boolean hasMerged = hasMerged(intervals, newInterval, startIndex, endIndex); + final int intervalMergedEnd = endIndex >= intervals.length + ? intervals.length - 1 + : newInterval[1] >= intervals[endIndex][0] ? endIndex : endIndex - 1; + final int intervalMergedStart = startIndex; + final int elements = intervals.length - (hasMerged ? intervalMergedEnd - intervalMergedStart : -1); + final int[][] result = new int[elements][2]; + int i = 0; + for ( ; i < intervalMergedStart ; i++) result[i] = intervals[i]; + result[i++] = new int[] {newStart, newEnd}; + if (hasMerged) { + for (i = intervalMergedEnd + 1 ; i < intervals.length ; i++) { + result[i - (intervalMergedEnd - intervalMergedStart)] = intervals[i]; + } + } else { + for ( ; i < intervals.length ; i++) { + result[i] = intervals[i - 1]; + } + } + return result; + } + + private boolean hasMerged(int[][] intervals, int[] interval, int start, int end) { + if (start >= intervals.length) return false; + return interval[0] <= intervals[start][1] || + (end < intervals.length && interval[1] >= intervals[end][0]); + } + + private int search(int[][] array, int x) { + int left = 0, right = array.length - 1, middle; + while (left <= right) { + middle = left + (right - left) / 2; + if (array[middle][1] == x) return middle; + else if (array[middle][1] > x) right = middle - 1; + else left = middle + 1; + } + return left; + } +} diff --git a/src/InsertionSortList.java b/src/InsertionSortList.java new file mode 100644 index 0000000..6b41236 --- /dev/null +++ b/src/InsertionSortList.java @@ -0,0 +1,29 @@ +// https://leetcode.com/problems/insertion-sort-list +// T: O(n^2) +// S: O(1) + +public class InsertionSortList { + public ListNode insertionSortList(ListNode head) { + if (head == null || head.next == null) return head; + + ListNode newHead = new ListNode(0); + ListNode pre = newHead; + ListNode next; + + for (ListNode cur = head ; cur != null ; ) { + next = cur.next; + + while (pre.next != null && pre.next.val < cur.val) { + pre = pre.next; + } + + //insert between pre and pre.next + cur.next = pre.next; + pre.next = cur; + pre = newHead; + cur = next; + } + + return newHead.next; + } +} diff --git a/src/IntegerToRoman.java b/src/IntegerToRoman.java new file mode 100644 index 0000000..dbc0e9c --- /dev/null +++ b/src/IntegerToRoman.java @@ -0,0 +1,36 @@ +// https://leetcode.com/problems/integer-to-roman +// T: O(log n) +// S: O(log n) + +public class IntegerToRoman { + private static final String[] ROMAN_VALUES = new String[] { "I", "V", "X", "L", "C", "D", "M" }; + + public String intToRoman(int num) { + final StringBuilder builder = new StringBuilder(); + final String number = num + ""; + for (int i = 0 ; i < number.length() ; i++) { + builder.append(getRomanString(number.charAt(i), number.length() - i - 1)); + } + return builder.toString(); + } + + private static String getRomanString(char digit, int power) { + if (digit == '4') { + return ROMAN_VALUES[2 * power] + ROMAN_VALUES[2 * power + 1]; + } + if (digit == '9') { + return ROMAN_VALUES[2 * power] + ROMAN_VALUES[2 * power + 2]; + } + + return switch (digit) { + case '1' -> ROMAN_VALUES[2 * power].repeat(1); + case '2' -> ROMAN_VALUES[2 * power].repeat(2); + case '3' -> ROMAN_VALUES[2 * power].repeat(3); + case '5' -> ROMAN_VALUES[2 * power + 1]; + case '6' -> ROMAN_VALUES[2 * power + 1] + ROMAN_VALUES[2 * power].repeat(1); + case '7' -> ROMAN_VALUES[2 * power + 1] + ROMAN_VALUES[2 * power].repeat(2); + case '8' -> ROMAN_VALUES[2 * power + 1] + ROMAN_VALUES[2 * power].repeat(3); + default -> ""; + }; + } +} diff --git a/src/InterleavingString.java b/src/InterleavingString.java new file mode 100644 index 0000000..4955ba7 --- /dev/null +++ b/src/InterleavingString.java @@ -0,0 +1,34 @@ +// https://leetcode.com/problems/interleaving-string +// T: O(n * m) +// S: O(min(m, n)) + +public class InterleavingString { + public boolean isInterleave(String s1, String s2, String s3) { + if (s1.length() + s2.length() != s3.length()) return false; + if (s1.length() < s2.length()) { + String temp = s1; + s1 = s2; + s2 = temp; + } + + final int rows = s1.length() + 1, columns = s2.length() + 1; + final boolean[] dp = new boolean[columns]; + + for (int row = 0 ; row < rows ; row++) { + for (int column = 0 ; column < columns ; column++) { + if (row == 0 && column == 0) { + dp[column] = true; + } else if (row == 0) { + dp[column] = dp[column - 1] && s2.charAt(column - 1) == s3.charAt(row + column - 1); + } else if (column == 0) { + dp[column] = dp[column] && s1.charAt(row - 1) == s3.charAt(row + column - 1); + } else { + dp[column] = (s1.charAt(row - 1) == s3.charAt(row + column - 1) && dp[column]) + || (s2.charAt(column - 1) == s3.charAt(row + column - 1) && dp[column - 1]); + } + } + } + + return dp[columns - 1]; + } +} diff --git a/src/IntersectionOf2LinkedLists.java b/src/IntersectionOf2LinkedLists.java index 27b6759..6fcf322 100644 --- a/src/IntersectionOf2LinkedLists.java +++ b/src/IntersectionOf2LinkedLists.java @@ -2,14 +2,6 @@ import java.util.Set; public class IntersectionOf2LinkedLists { - public static class ListNode { - int val; - ListNode next; - ListNode(int x) { - val = x; - next = null; - } - } public ListNode getIntersectionNode(ListNode headA, ListNode headB) { Set aNodes = new HashSet<>(); diff --git a/src/IntersectionOfMultipleArrays.java b/src/IntersectionOfMultipleArrays.java new file mode 100644 index 0000000..9efff3d --- /dev/null +++ b/src/IntersectionOfMultipleArrays.java @@ -0,0 +1,41 @@ +// https://leetcode.com/problems/intersection-of-multiple-arrays +// T: O() +// S: O() + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class IntersectionOfMultipleArrays { + public List intersection(int[][] nums) { + Set set = setFrom(nums[0]); + for (int index = 1 ; index < nums.length ; index++) { + final Set other = setFrom(nums[index]); + set = intersection(set, other); + } + final List list = toList(set); + list.sort(Integer::compareTo); + return list; + } + + private Set setFrom(int[] array) { + final Set set = new HashSet<>(); + for (int element : array) { + set.add(element); + } + return set; + } + + private List toList(final Set set) { + return new ArrayList<>(set); + } + + private Set intersection(Set set1, Set set2) { + final Set result = new HashSet<>(); + for (int element : set1) { + if (set2.contains(element)) result.add(element); + } + return result; + } +} diff --git a/src/InvertBinaryTree.java b/src/InvertBinaryTree.java index 5fb9e80..667c246 100644 --- a/src/InvertBinaryTree.java +++ b/src/InvertBinaryTree.java @@ -1,9 +1,4 @@ public class InvertBinaryTree { - private static class TreeNode { - int val; - TreeNode left; - TreeNode right; - } public static TreeNode invertTree(TreeNode root) { if (root == null) { diff --git a/src/JewelsAndStones.java b/src/JewelsAndStones.java new file mode 100644 index 0000000..045387c --- /dev/null +++ b/src/JewelsAndStones.java @@ -0,0 +1,23 @@ +import java.util.HashSet; +import java.util.Set; + +public class JewelsAndStones { + public int numJewelsInStones(String jewels, String stones) { + Set jewelTypes = toSet(jewels); + int totalJewels = 0; + for (char stone : stones.toCharArray()) { + if (jewelTypes.contains(stone)) { + totalJewels++; + } + } + return totalJewels; + } + + private Set toSet(String string) { + Set set = new HashSet<>(); + for (char character : string.toCharArray()) { + set.add(character); + } + return set; + } +} diff --git a/src/JumpGame.java b/src/JumpGame.java new file mode 100644 index 0000000..cd2824a --- /dev/null +++ b/src/JumpGame.java @@ -0,0 +1,13 @@ +// https://leetcode.com/problems/jump-game +// T: O(N) +// S: O(1) + +public class JumpGame { + public boolean canJump(int[] nums) { + int last = nums.length - 1; + for (int i = nums.length - 2 ; i >= 0 ; i--) { + if (i + nums[i] >= last) last = i; + } + return last == 0; + } +} diff --git a/src/JumpGameII.java b/src/JumpGameII.java new file mode 100644 index 0000000..0fefd43 --- /dev/null +++ b/src/JumpGameII.java @@ -0,0 +1,24 @@ +// https://leetcode.com/problems/jump-game-ii +// T: O(n) +// S: O(1) + +public class JumpGameII { + public int jump(int[] nums) { + if (nums.length == 1) return 0; + + int jumps = 0; + for (int current = 0 ; current < nums.length ; jumps++) { + int maxJumpIndex = current, maxJump = nums[current]; + for (int i = current ; i < current + nums[current] + 1 && i < nums.length ; i++) { + if (i == nums.length - 1) return jumps + 1; + int potential = i - current + nums[i]; + if (potential > maxJump) { + maxJump = potential; + maxJumpIndex = i; + } else if (potential == maxJump) maxJumpIndex = i; + } + current = maxJumpIndex; + } + return jumps; + } +} diff --git a/src/KDiffPairsInAnArray.java b/src/KDiffPairsInAnArray.java new file mode 100644 index 0000000..5d56213 --- /dev/null +++ b/src/KDiffPairsInAnArray.java @@ -0,0 +1,29 @@ +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class KDiffPairsInAnArray { + public int findPairs(int[] nums, int k) { + int pairs= 0; + if (k == 0) { + Map frequencies = new HashMap<>(); + for (int number : nums) { + frequencies.put(number, frequencies.getOrDefault(number, 0) + 1); + } + for (int frequency : frequencies.values()) { + pairs += frequency > 1 ? 1 : 0; + } + } else { + Set numbers = new HashSet<>(); + for (int number : nums) { + if (!numbers.contains(number)) { + pairs += numbers.contains(number - k) ? 1 : 0; + pairs += numbers.contains(number + k) ? 1 : 0; + numbers.add(number); + } + } + } + return pairs; + } +} diff --git a/src/KItemsWithTheMaximumSum.java b/src/KItemsWithTheMaximumSum.java new file mode 100644 index 0000000..ae7f8b0 --- /dev/null +++ b/src/KItemsWithTheMaximumSum.java @@ -0,0 +1,16 @@ +// https://leetcode.com/problems/k-items-with-the-maximum-sum +// T: O(1) +// S: O(1) + +public class KItemsWithTheMaximumSum { + public int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { + int maxSum = Math.min(numOnes, k); + k -= numOnes; + if (k <= 0) return maxSum; + + k -= numZeros; + if (k <= 0) return maxSum; + + return maxSum - k; + } +} diff --git a/src/KeepMultiplyingFoundValuesByTwo.java b/src/KeepMultiplyingFoundValuesByTwo.java new file mode 100644 index 0000000..7bfd19b --- /dev/null +++ b/src/KeepMultiplyingFoundValuesByTwo.java @@ -0,0 +1,24 @@ +// https://leetcode.com/problems/keep-multiplying-found-values-by-two +// T: O(N) +// S: O(N) + +import java.util.HashSet; +import java.util.Set; + +public class KeepMultiplyingFoundValuesByTwo { + public int findFinalValue(int[] nums, int original) { + final Set numbers = setFrom(nums); + while (numbers.contains(original)) { + original *= 2; + } + return original; + } + + private Set setFrom(int[] numbers) { + final Set set = new HashSet<>(); + for (int element : numbers) { + set.add(element); + } + return set; + } +} diff --git a/src/KidsWithTheGreatestNumberOfCandies.java b/src/KidsWithTheGreatestNumberOfCandies.java new file mode 100644 index 0000000..62f39c1 --- /dev/null +++ b/src/KidsWithTheGreatestNumberOfCandies.java @@ -0,0 +1,14 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class KidsWithTheGreatestNumberOfCandies { + public List kidsWithCandies(int[] candies, int extraCandies) { + final List result = new ArrayList<>(); + final int maxCandies = Arrays.stream(candies).max().getAsInt(); + for (int person : candies) { + result.add(person + extraCandies >= maxCandies); + } + return result; + } +} diff --git a/src/KnightProbabilityInChessboard.java b/src/KnightProbabilityInChessboard.java new file mode 100644 index 0000000..927fc8c --- /dev/null +++ b/src/KnightProbabilityInChessboard.java @@ -0,0 +1,154 @@ +// https://leetcode.com/problems/knight-probability-in-chessboard +// T: O(n^2 * k) +// S: O(n^2) + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class KnightProbabilityInChessboard { + static class Position { + private final int n; + private int row; + private int column; + + Position(int row, int column, int n) { + this.n = n; + this.row = row; + this.column = column; + } + + private void normalize() { + row = normalize(row); + column = normalize(column); + if (row > column) { + int temp = row; + row = column; + column = temp; + } + } + + private int normalize(int index) { + if (index >= (n + 1) / 2) { + return n - index - 1; + } + return index; + } + + private Position apply(Movement movement) { + return switch (movement) { + case TOP_LEFT -> new Position(row - 2, column - 1, n); + case TOP_RIGHT -> new Position(row - 2, column + 1, n); + case RIGHT_TOP -> new Position(row - 1, column + 2, n); + case RIGHT_BOTTOM -> new Position(row + 1, column + 2, n); + case BOTTOM_RIGHT -> new Position(row + 2, column + 1, n); + case BOTTOM_LEFT -> new Position(row + 2, column - 1, n); + case LEFT_BOTTOM -> new Position(row + 1, column - 2, n); + case LEFT_TOP -> new Position(row - 1, column - 2, n); + }; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + Position other = (Position) o; + if (row != other.row) return false; + return column == other.column; + } + + @Override + public int hashCode() { + return 31 * row + column; + } + } + + private record State(int n, int k, Position position) { } + + private enum Movement { + TOP_LEFT, + TOP_RIGHT, + RIGHT_TOP, + RIGHT_BOTTOM, + BOTTOM_RIGHT, + BOTTOM_LEFT, + LEFT_TOP, + LEFT_BOTTOM + } + + private static final Map> allowedMovements = new HashMap<>(); + private static final Map results = new HashMap<>(); + private static int[][] validMoves; + + public static double knightProbability(int n, int k, int row, int column) { + computeValidMovements(n); + return getKnightProbability(n, k, new Position(row, column, n)); + } + + private static double getKnightProbability(int n, int k, Position position) { + if (k == 0) return 1; + + position.normalize(); + State state = new State(n, k, position); + if (results.containsKey(state)) return results.get(state); + + if (k == 1) { + double answer = ((double) validMoves(position)) / 8; + results.put(state, answer); + return answer; + } + + double sumOfProbabilities = 0; + for (Movement movement : allowedMovements.get(position)) { + Position newPosition = position.apply(movement); + sumOfProbabilities += getKnightProbability(n, k - 1, newPosition); + } + double answer = sumOfProbabilities / 8; + results.put(state, answer); + return answer; + } + + private static void computeValidMovements(int n) { + for (int row = 0 ; row < (n + 1) / 2 ; row++) { + for (int column = row ; column < (n + 1) / 2 ; column++) { + Position position = new Position(row, column, n); + allowedMovements.put(position, knightMovementsAt(position)); + } + } + fillValidMovesTable(n); + } + + private static void fillValidMovesTable(int n) { + final int length = (n + 1) / 2; + validMoves = new int[length][length]; + for (int row = 0 ; row < length ; row++) { + for (int column = row ; column < length ; column++) { + validMoves[row][column] = allowedMovements.get(new Position(row, column, n)).size(); + } + } + } + + private static List knightMovementsAt(Position position) { + final List movements = new ArrayList<>(); + if (isValidIndices(position.row - 2, position.column - 1, position.n)) movements.add(Movement.TOP_LEFT); + if (isValidIndices(position.row - 2, position.column + 1, position.n)) movements.add(Movement.TOP_RIGHT); + if (isValidIndices(position.row - 1, position.column + 2, position.n)) movements.add(Movement.RIGHT_TOP); + if (isValidIndices(position.row + 1, position.column + 2, position.n)) movements.add(Movement.RIGHT_BOTTOM); + if (isValidIndices(position.row + 2, position.column + 1, position.n)) movements.add(Movement.BOTTOM_RIGHT); + if (isValidIndices(position.row + 2, position.column - 1, position.n)) movements.add(Movement.BOTTOM_LEFT); + if (isValidIndices(position.row + 1, position.column - 2, position.n)) movements.add(Movement.LEFT_BOTTOM); + if (isValidIndices(position.row - 1, position.column - 2, position.n)) movements.add(Movement.LEFT_TOP); + return movements; + } + + private static boolean isValidIndices(int row, int column, int n) { + return row >= 0 + && row < n + && column >= 0 + && column < n; + } + + private static int validMoves(Position position) { + return validMoves[position.row][position.column]; + } +} diff --git a/src/KthDistinctStringInAnArray.java b/src/KthDistinctStringInAnArray.java new file mode 100644 index 0000000..e3cab6d --- /dev/null +++ b/src/KthDistinctStringInAnArray.java @@ -0,0 +1,27 @@ +// https://leetcode.com/problems/kth-distinct-string-in-an-array +// T: O(|arr|) +// S: O(|arr|) + +import java.util.HashMap; +import java.util.Map; + +public class KthDistinctStringInAnArray { + public String kthDistinct(String[] arr, int k) { + final Map frequencies = getFrequency(arr); + for (String s : arr) { + if (frequencies.get(s) == 1) { + k--; + } + if (k == 0) return s; + } + return ""; + } + + private Map getFrequency(String[] array) { + final Map frequencies = new HashMap<>(); + for (String s : array) { + frequencies.put(s, frequencies.getOrDefault(s, 0) + 1); + } + return frequencies; + } +} diff --git a/src/KthLargestElementInAStream.java b/src/KthLargestElementInAStream.java new file mode 100644 index 0000000..dbe77bb --- /dev/null +++ b/src/KthLargestElementInAStream.java @@ -0,0 +1,28 @@ +import java.util.PriorityQueue; +import java.util.Queue; + +public class KthLargestElementInAStream { + class KthLargest { + + private final Queue heap = new PriorityQueue<>(); + private final int heapSize; + + public KthLargest(int k, int[] nums) { + heapSize = k; + for (int element : nums) { + heap.add(element); + } + while (heap.size() > heapSize) { + heap.poll(); + } + } + + public int add(int val) { + heap.add(val); + while (heap.size() > heapSize) { + heap.poll(); + } + return heap.peek(); + } + } +} diff --git a/src/KthLargestElementInAnArray.java b/src/KthLargestElementInAnArray.java new file mode 100644 index 0000000..02ac421 --- /dev/null +++ b/src/KthLargestElementInAnArray.java @@ -0,0 +1,34 @@ +// https://leetcode.com/problems/kth-largest-element-in-an-array +// T: O(n) +// S: O(1) + +public class KthLargestElementInAnArray { + public int findKthLargest(int[] nums, int k) { + int partitionIndex = nums.length - k; + for (int left = 0, right = nums.length - 1, j ; left < right ; ) { + j = partition(nums, left, right); + if (j == partitionIndex) return nums[partitionIndex]; + else if (j < partitionIndex) left = j + 1; + else right = j - 1; + } + return nums[partitionIndex]; + } + + private int partition(int[] array, int left, int right) { + int pivot = array[right], i = left - 1; + for (int j = left ; j < right ; j++) { + if (array[j] < pivot) { + i++; + swap(array, i, j); + } + } + swap(array, i + 1, right); + return i + 1; + } + + private void swap(int[] array, int i, int j) { + int temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } +} diff --git a/src/KthMissingPositiveNumber.java b/src/KthMissingPositiveNumber.java new file mode 100644 index 0000000..d7dad8e --- /dev/null +++ b/src/KthMissingPositiveNumber.java @@ -0,0 +1,19 @@ +// https://leetcode.com/problems/kth-missing-positive-number +// T: O(n) +// S: O(1) + +public class KthMissingPositiveNumber { + public int findKthPositive(int[] arr, int k) { + int pointer = 1, missing = 0; + for (int index = 0, current = arr[index]; missing < k ; ) { + if (pointer < current) { + missing++; + } else { + index++; + current = index == arr.length ? Integer.MAX_VALUE : arr[index]; + } + pointer++; + } + return pointer - 1; + } +} diff --git a/src/KthSmallestElementInABST.java b/src/KthSmallestElementInABST.java new file mode 100644 index 0000000..616f928 --- /dev/null +++ b/src/KthSmallestElementInABST.java @@ -0,0 +1,27 @@ +// https://leetcode.com/problems/kth-smallest-element-in-a-bst +// T: O(k + log(N)) +// S: O(log(N)) + +import java.util.Stack; + +public class KthSmallestElementInABST { + public int kthSmallest(TreeNode root, int k) { + final Stack stack = new Stack<>(); + addLeftPathToStack(root, stack); + + for (int count = 0 ; !stack.isEmpty() ; ) { + final TreeNode current = stack.pop(); + count++; + if (count == k) return current.val; + addLeftPathToStack(current.right, stack); + } + + return -1; + } + + private void addLeftPathToStack(TreeNode root, Stack stack) { + if (root == null) return; + stack.push(root); + addLeftPathToStack(root.left, stack); + } +} diff --git a/src/LRUCache.java b/src/LRUCache.java new file mode 100644 index 0000000..445b433 --- /dev/null +++ b/src/LRUCache.java @@ -0,0 +1,89 @@ +// T: O(n) +// S: O(n) + +import java.util.HashMap; +import java.util.Map; + +public class LRUCache { + private static class Node { + int key; + int value; + Node previous; + Node next; + + public Node(int key, int value) { + this.key = key; + this.value = value; + } + } + + private final Map cache = new HashMap<>(); + private final int capacity; + private Node head, tail; + + public LRUCache(int capacity) { + this.capacity = capacity; + } + + public int get(int key) { + if (!cache.containsKey(key)) { + return -1; + } + final Node node = cache.get(key); + moveNodeToTail(node); + return node.value; + } + + public void put(int key, int value) { + if (cache.containsKey(key)) { + Node node = cache.get(key); + node.value = value; + moveNodeToTail(node); + } else if (cache.size() == capacity) { + Node node = new Node(key, value); + cache.put(key, node); + cache.remove(head.key); + appendToTail(node); + popHead(); + } else { + Node node = new Node(key, value); + cache.put(key, node); + + if (cache.size() == 1) { + head = node; + tail = node; + } else { + appendToTail(node); + } + } + } + + private void moveNodeToTail(Node node) { + if (node == tail) { + return; + } + + if (node == head) { + appendToTail(node); + popHead(); + return; + } + + Node previous = node.previous, next = node.next; + previous.next = next; + next.previous = previous; + + appendToTail(node); + } + + private void appendToTail(Node node) { + tail.next = node; + node.previous = tail; + tail = node; + } + + private void popHead() { + head = head.next; + head.previous = null; + } +} \ No newline at end of file diff --git a/src/Largest3SameDigitNumberInString.java b/src/Largest3SameDigitNumberInString.java new file mode 100644 index 0000000..902ab77 --- /dev/null +++ b/src/Largest3SameDigitNumberInString.java @@ -0,0 +1,25 @@ +// https://leetcode.com/problems/largest-3-same-digit-number-in-string +// T: O(|s|) +// S: O(1) + +public class Largest3SameDigitNumberInString { + public String largestGoodInteger(String num) { + char current = num.charAt(0), result = '0' - 1; + for (int index = 1, count = 1 ; index < num.length() ; index++) { + if (num.charAt(index) == current) { + count++; + } else { + current = num.charAt(index); + count = 1; + } + + if (count >= 3 && current > result) { + result = current; + } + } + + if (result >= '0') { + return (result + "").repeat(3); + } else return ""; + } +} diff --git a/src/LargestComponentSizeByCommonFactor.java b/src/LargestComponentSizeByCommonFactor.java new file mode 100644 index 0000000..c2e0d19 --- /dev/null +++ b/src/LargestComponentSizeByCommonFactor.java @@ -0,0 +1,78 @@ +// https://leetcode.com/problems/largest-component-size-by-common-factor +// N = nums, M = max(N) +// T: O(M + N sqrt(M) al(M) + N al(N)) al = inverse Ackermann function +// S: O(M + N) + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public class LargestComponentSizeByCommonFactor { + private static final class DisjointSet { + private final int[] root, rank; + + public DisjointSet(int size) { + root = new int[size]; + rank = new int[size]; + for (int i = 0 ; i < size ; i++) { + root[i] = i; + rank[i] = 1; + } + } + + public int find(int num) { + if (num == root[num]) { + return num; + } + return root[num] = find(root[num]); + } + + public boolean areConnected(int x, int y) { + return find(x) == find(y); + } + + public void union(int x, int y) { + final int rootX = find(x), rootY = find(y); + if (rootX == rootY) { + return; + } + if (rank[rootX] > rank[rootY]) { + root[rootY] = rootX; + } else if (rank[rootX] < rank[rootY]) { + root[rootY] = rootX; + } else { + root[rootY] = rootX; + rank[rootX]++; + } + } + + public int size() { + return root.length; + } + } + + public int largestComponentSize(int[] nums) { + final int maxValue = Arrays.stream(nums).max().getAsInt(); + final DisjointSet disjointSet = new DisjointSet(maxValue + 1); + for (int number : nums) { + for (int i = 2 ; i * i <= number ; i++) { + if (number % i == 0) { + disjointSet.union(number, i); + disjointSet.union(number, number/ i); + } + } + } + return largestComponentSize(disjointSet, nums); + } + + private static int largestComponentSize(DisjointSet disjointSet, int[] numbers) { + final Map rootFrequencies = new HashMap<>(); + int maxSize = 1; + for (int number : numbers) { + final int root = disjointSet.find(number); + rootFrequencies.put(root, rootFrequencies.getOrDefault(root, 0) + 1); + maxSize = Math.max(maxSize, rootFrequencies.get(root)); + } + return maxSize; + } +} diff --git a/src/LargestLocalValuesInAMatrix.java b/src/LargestLocalValuesInAMatrix.java new file mode 100644 index 0000000..3fbc63e --- /dev/null +++ b/src/LargestLocalValuesInAMatrix.java @@ -0,0 +1,28 @@ +// https://leetcode.com/problems/largest-local-values-in-a-matrix +// T: O(n ^ 2) +// S: O(n ^ 2) + +public class LargestLocalValuesInAMatrix { + public int[][] largestLocal(int[][] grid) { + final int n = grid.length; + final int[][] result = new int[n - 2][n - 2]; + + for (int row = 1 ; row < n - 1 ; row++) { + for (int column = 1 ; column < n - 1 ; column++) { + result[row - 1][column - 1] = localMax(grid, row, column); + } + } + + return result; + } + + private int localMax(int[][] grid, int row, int column) { + int max = Integer.MIN_VALUE; + for (int i = row - 1 ; i <= row + 1 ; i++) { + for (int j = column - 1 ; j <= column + 1 ; j++) { + max = Math.max(max, grid[i][j]); + } + } + return max; + } +} diff --git a/src/LargestNumber.java b/src/LargestNumber.java new file mode 100644 index 0000000..39debbb --- /dev/null +++ b/src/LargestNumber.java @@ -0,0 +1,38 @@ +// https://leetcode.com/problems/largest-number +// T: O(Nlog(N)) +// S: O(N) + +import java.util.ArrayList; +import java.util.List; + +public class LargestNumber { + private static final String ZERO = "0"; + + public static String largestNumber(int[] nums) { + final List numbers = convertToStrings(nums); + numbers.sort((s1, s2) -> { + final String order1 = s1 + s2; + final String order2 = s2 + s1; + return order2.compareTo(order1); + }); + + if (numbers.get(0).equals(ZERO)) return ZERO; + return combineStrings(numbers); + } + + private static String combineStrings(List numbers) { + final StringBuilder result = new StringBuilder(); + for (String string : numbers) { + result.append(string); + } + return result.toString(); + } + + private static List convertToStrings(int[] array) { + final List numbers = new ArrayList<>(); + for (int number : array) { + numbers.add(String.valueOf(number)); + } + return numbers; + } +} diff --git a/src/LargestNumberAfterDigitSwapsByParity.java b/src/LargestNumberAfterDigitSwapsByParity.java new file mode 100644 index 0000000..0d898b9 --- /dev/null +++ b/src/LargestNumberAfterDigitSwapsByParity.java @@ -0,0 +1,49 @@ +// https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity +// T: O(log(n) log(log(n))) +// S: O(log(n)) + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +public class LargestNumberAfterDigitSwapsByParity { + public int largestInteger(int num) { + final String number = num + ""; + final List evenDigits = getEvenDigits(number); + final List oddDigits = getOddDigits(number); + + evenDigits.sort(Comparator.reverseOrder()); + oddDigits.sort(Comparator.reverseOrder()); + + final StringBuilder result = new StringBuilder(); + for (int i = 0, evenIndex = 0, oddIndex = 0; i < number.length() ; i++) { + if (isOddDigit(number, i)) { + result.append(oddDigits.get(oddIndex++)); + } else { + result.append(evenDigits.get(evenIndex++)); + } + } + + return Integer.parseInt(result.toString()); + } + + private boolean isOddDigit(String number, int index) { + return (number.charAt(index) - '0') % 2 == 1; + } + + private List getEvenDigits(String string) { + final List result = new ArrayList<>(); + for (int index = 0 ; index < string.length() ; index++) { + if (!isOddDigit(string, index)) result.add(string.charAt(index) - '0'); + } + return result; + } + + private List getOddDigits(String string) { + final List result = new ArrayList<>(); + for (int index = 0 ; index < string.length() ; index++) { + if (isOddDigit(string, index)) result.add(string.charAt(index) - '0'); + } + return result; + } +} diff --git a/src/LargestNumberAtLeastTwiceOfOthers.java b/src/LargestNumberAtLeastTwiceOfOthers.java new file mode 100644 index 0000000..c6279e6 --- /dev/null +++ b/src/LargestNumberAtLeastTwiceOfOthers.java @@ -0,0 +1,22 @@ +public class LargestNumberAtLeastTwiceOfOthers { + public int dominantIndex(int[] nums) { + int largestIndex = largestIndex(nums), largest = nums[largestIndex]; + for (int number : nums) { + if (number != largest && 2 * number > largest) { + return -1; + } + } + return largestIndex; + } + + private int largestIndex(int[] array) { + int largest = Integer.MIN_VALUE, largestIndex = -1; + for (int index = 0 ; index < array.length ; index++) { + if (array[index] > largest) { + largest = array[index]; + largestIndex = index; + } + } + return largestIndex; + } +} diff --git a/src/LargestOddNumberInString.java b/src/LargestOddNumberInString.java new file mode 100644 index 0000000..daab62c --- /dev/null +++ b/src/LargestOddNumberInString.java @@ -0,0 +1,18 @@ +// https://leetcode.com/problems/largest-odd-number-in-string +// T: O(|num|) +// S: O(num) + +public class LargestOddNumberInString { + public String largestOddNumber(String num) { + for (int i = num.length() - 1 ; i >= 0 ; i--) { + if (isOddDigit(num.charAt(i))) { + return num.substring(0, i + 1); + } + } + return ""; + } + + private boolean isOddDigit(char digit) { + return (digit - '0') % 2 == 1; + } +} diff --git a/src/LargestPerimeterTriangle.java b/src/LargestPerimeterTriangle.java new file mode 100644 index 0000000..b2e8602 --- /dev/null +++ b/src/LargestPerimeterTriangle.java @@ -0,0 +1,11 @@ +import java.util.Arrays; + +public class LargestPerimeterTriangle { + public int largestPerimeter(int[] nums) { + Arrays.sort(nums); + for (int i = nums.length - 1 ; i >= 2 ; i--) { + if (nums[i - 2] + nums[i - 1] > nums[i]) return nums[i - 2] + nums[i - 1] + nums[i]; + } + return 0; + } +} diff --git a/src/LargestPositiveIntegerThatExistsWithItsNegative.java b/src/LargestPositiveIntegerThatExistsWithItsNegative.java new file mode 100644 index 0000000..03f284e --- /dev/null +++ b/src/LargestPositiveIntegerThatExistsWithItsNegative.java @@ -0,0 +1,22 @@ +// https://leetcode.com/problems/largest-positive-integer-that-exists-with-its-negative +// T: O(N) +// S: O(N) + +import java.util.HashSet; +import java.util.Set; + +public class LargestPositiveIntegerThatExistsWithItsNegative { + public int findMaxK(int[] array) { + int largest = -1; + final Set numbers = new HashSet<>(); + + for (int element : array) { + if (Math.abs(element) > largest && numbers.contains(-element)) { + largest = Math.abs(element); + } + numbers.add(element); + } + + return largest; + } +} diff --git a/src/LargestSubStringBetweenTwoEqualCharacters.java b/src/LargestSubStringBetweenTwoEqualCharacters.java new file mode 100644 index 0000000..c9e2601 --- /dev/null +++ b/src/LargestSubStringBetweenTwoEqualCharacters.java @@ -0,0 +1,17 @@ +import java.util.HashMap; +import java.util.Map; + +public class LargestSubStringBetweenTwoEqualCharacters { + public int maxLengthBetweenEqualCharacters(String s) { + int maxLength = -1; + final Map lastIndex = new HashMap<>(); + for (int i = 0 ; i < s.length() ; i++) { + if (lastIndex.containsKey(s.charAt(i))) { + maxLength = Math.max(maxLength, i - lastIndex.get(s.charAt(i)) - 1); + } else { + lastIndex.put(s.charAt(i), i); + } + } + return maxLength; + } +} diff --git a/src/LargestTriangleArea.java b/src/LargestTriangleArea.java new file mode 100644 index 0000000..3711881 --- /dev/null +++ b/src/LargestTriangleArea.java @@ -0,0 +1,19 @@ +public class LargestTriangleArea { + public double largestTriangleArea(int[][] points) { + double result = 0; + for (int i = 0 ; i < points.length ; i++) { + for (int j = i + 1 ; j < points.length ; j++) { + for (int k = j + 1 ; k < points.length ; k++) { + result = Math.max(result, triangleArea(points[i], points[j], points[k])); + } + } + } + return result; + } + + private double triangleArea(int[] p1, int[] p2, int[] p3) { + return 0.5 * Math.abs( + p1[0] * p2[1] + p2[0] * p3[1] + p3[0] * p1[1]- p2[0] * p1[1] - p3[0] * p2[1] - p1[0] * p3[1] + ); + } +} diff --git a/src/LastStoneWeight.java b/src/LastStoneWeight.java new file mode 100644 index 0000000..b5eb6ba --- /dev/null +++ b/src/LastStoneWeight.java @@ -0,0 +1,19 @@ +import java.util.Comparator; +import java.util.PriorityQueue; +import java.util.Queue; + +public class LastStoneWeight { + public int lastStoneWeight(int[] stones) { + Queue maxHeap = new PriorityQueue<>(Comparator.reverseOrder()); + for (int stone : stones) maxHeap.add(stone); + int stone1, stone2; + while (maxHeap.size() > 1) { + stone1 = maxHeap.poll(); + stone2 = maxHeap.poll(); + if (stone1 != stone2) { + maxHeap.add(Math.abs(stone1 - stone2)); + } + } + return maxHeap.isEmpty() ? 0 : maxHeap.peek(); + } +} diff --git a/src/LastVisitedIntegers.java b/src/LastVisitedIntegers.java new file mode 100644 index 0000000..10ac349 --- /dev/null +++ b/src/LastVisitedIntegers.java @@ -0,0 +1,31 @@ +// https://leetcode.com/problems/last-visited-integers +// T: O(N) +// S: O(N) + +import java.util.ArrayList; +import java.util.List; + +public class LastVisitedIntegers { + public List lastVisitedIntegers(int[] array) { + final List seen = new ArrayList<>(); + final List ans = new ArrayList<>(); + + int k = 0; + + for (int element : array) { + if (element == -1) { + k++; + if (k > seen.size()) { + ans.add(-1); + } else { + ans.add(seen.get(seen.size() - k)); + } + } else { + k = 0; + seen.add(element); + } + } + + return ans; + } +} diff --git a/src/LatestTimeByReplacingHiddenDigits.java b/src/LatestTimeByReplacingHiddenDigits.java new file mode 100644 index 0000000..a93b8e1 --- /dev/null +++ b/src/LatestTimeByReplacingHiddenDigits.java @@ -0,0 +1,28 @@ +public class LatestTimeByReplacingHiddenDigits { + public String maximumTime(String time) { + String[] parts = time.split(":"); + String hour = parts[0], minutes = parts[1]; + return new StringBuilder(maxHours(hour)).append(':').append(maxMinutes(minutes)).toString(); + } + + private String maxHours(String string) { + if (string.charAt(0) == '?') { + if (string.charAt(1) == '?') return "23"; + if (string.charAt(1) > '3') return "1" + string.charAt(1); + return "2" + string.charAt(1); + } else if (string.charAt(1) == '?') { + return string.charAt(0) + (string.charAt(0) == '2' ? "3" : "9"); + } + return string; + } + + private String maxMinutes(String string) { + if (string.charAt(0) == '?') { + if (string.charAt(1) == '?') return "59"; + return "5" + string.charAt(1); + } else if (string.charAt(1) == '?') { + return string.charAt(0) + "9"; + } + return string; + } +} diff --git a/src/LatestTimeYouCanObtainAfterReplacingCharacters.java b/src/LatestTimeYouCanObtainAfterReplacingCharacters.java new file mode 100644 index 0000000..34d1ff7 --- /dev/null +++ b/src/LatestTimeYouCanObtainAfterReplacingCharacters.java @@ -0,0 +1,35 @@ +// https://leetcode.com/problems/latest-time-you-can-obtain-after-replacing-characters +// T: O(1) +// S: O(1) + +public class LatestTimeYouCanObtainAfterReplacingCharacters { + public String findLatestTime(String s) { + return maxHour(s.substring(0, 2)) + ":" + maxMinutes(s.substring(3)); + } + + private static String maxHour(String s) { + if (s.charAt(0) == '?' && s.charAt(1) == '?') { + return "11"; + } + if (s.charAt(0) == '?') { + return (s.charAt(1) <= '1' ? "1" : "0") + s.charAt(1); + } + if (s.charAt(1) == '?') { + return s.charAt(0) + (s.charAt(0) == '0' ? "9" : "1"); + } + return s; + } + + private static String maxMinutes(String s) { + if (s.charAt(0) == '?' && s.charAt(1) == '?') { + return "59"; + } + if (s.charAt(0) == '?') { + return "5" + s.charAt(1); + } + if (s.charAt(1) == '?') { + return s.charAt(0) + "9"; + } + return s; + } +} diff --git a/src/LeafSimilarTrees.java b/src/LeafSimilarTrees.java new file mode 100644 index 0000000..d91ee81 --- /dev/null +++ b/src/LeafSimilarTrees.java @@ -0,0 +1,26 @@ +import java.util.ArrayList; +import java.util.List; + +public class LeafSimilarTrees { + public boolean leafSimilar(TreeNode root1, TreeNode root2) { + List leafSequence1 = getLeafSequence(root1); + List leafSequence2 = getLeafSequence(root2); + return leafSequence1.equals(leafSequence2); + } + + private List getLeafSequence(TreeNode root) { + List result = new ArrayList<>(); + getLeafSequence(root, result); + return result; + } + + private void getLeafSequence(TreeNode root, List leafNodes) { + if (root == null) return; + if (root.left == null && root.right == null) { + leafNodes.add(root.val); + return; + } + getLeafSequence(root.left, leafNodes); + getLeafSequence(root.right, leafNodes); + } +} diff --git a/src/LeftAndRightSumDifferences.java b/src/LeftAndRightSumDifferences.java new file mode 100644 index 0000000..e86ff06 --- /dev/null +++ b/src/LeftAndRightSumDifferences.java @@ -0,0 +1,26 @@ +// https://leetcode.com/problems/left-and-right-sum-differences +// T: O(N) +// S: O(N) + +public class LeftAndRightSumDifferences { + public int[] leftRightDifference(int[] nums) { + final int[] result = new int[nums.length]; + int leftSum = 0, rightSum = sum(nums, 1, nums.length); + + for (int index = 0 ; index < nums.length ; index++) { + result[index] = Math.abs(leftSum - rightSum); + leftSum += nums[index]; + rightSum -= (index + 1 < nums.length ? nums[index + 1] : 0); + } + + return result; + } + + private int sum(int[] array, int startIndex, int endIndex) { + int sum = 0; + for (int i = startIndex ; i < endIndex ; i++) { + sum += array[i]; + } + return sum; + } +} diff --git a/src/LemonadeChange.java b/src/LemonadeChange.java new file mode 100644 index 0000000..d339997 --- /dev/null +++ b/src/LemonadeChange.java @@ -0,0 +1,20 @@ +public class LemonadeChange { + public boolean lemonadeChange(int[] bills) { + int fives = 0, tenners = 0, twenties = 0; + for (int i = 0 ; i < bills.length && fives >= 0 && tenners >= 0 && twenties >= 0 ; i++) { + if (bills[i] == 20) { + if (tenners > 0) { + tenners--; + fives--; + } else { + fives -= 3; + } + twenties++; + } else if (bills[i] == 10) { + fives--; + tenners++; + } else fives++; + } + return fives >=0 && tenners >= 0 && twenties >= 0; + } +} diff --git a/src/LengthOfLastWord.java b/src/LengthOfLastWord.java index 10d5c73..78f3c30 100644 --- a/src/LengthOfLastWord.java +++ b/src/LengthOfLastWord.java @@ -1,10 +1,23 @@ +// https://leetcode.com/problems/length-of-last-word +// T: O(N) +// S: O(1) + public class LengthOfLastWord { - public int lengthOfLastWord(String sentence) { - String[] words = sentence.split(" "); - if (words.length == 0) { - return 0; + public int lengthOfLastWord(String s) { + int i = s.length() - 1; + + // skip all spaces at the end of the word + while (i >= 0 && s.charAt(i) == ' ') { + i--; + } + + final int wordEndIndex = i; + + // arrive at the start of the word + while (i >= 0 && s.charAt(i) != ' ') { + i--; } - return words[words.length - 1].length(); + return wordEndIndex - i; } } diff --git a/src/LetterCombinationsOfAPhoneNumber.java b/src/LetterCombinationsOfAPhoneNumber.java new file mode 100644 index 0000000..31bfd39 --- /dev/null +++ b/src/LetterCombinationsOfAPhoneNumber.java @@ -0,0 +1,35 @@ +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class LetterCombinationsOfAPhoneNumber { + private static final Map> NUMBER_TO_CHARS = Map.ofEntries( + Map.entry('2', Set.of('a', 'b', 'c')), + Map.entry('3', Set.of('d', 'e', 'f')), + Map.entry('4', Set.of('g', 'h', 'i')), + Map.entry('5', Set.of('j', 'k', 'l')), + Map.entry('6', Set.of('m', 'n', 'o')), + Map.entry('7', Set.of('p', 'q', 'r', 's')), + Map.entry('8', Set.of('t', 'u', 'v')), + Map.entry('9', Set.of('w', 'x', 'y', 'z')) + ); + + public List letterCombinations(String digits) { + if (digits.isEmpty()) return Collections.emptyList(); + final List result = new ArrayList<>(); + addLetterCombinationsToResult(digits, 0, "", result); + return result; + } + + private void addLetterCombinationsToResult(String s, int i, String current, List result) { + if (i == s.length()) { + result.add(current); + return; + } + for (char character : NUMBER_TO_CHARS.get(s.charAt(i))) { + addLetterCombinationsToResult(s, i + 1, current + character, result); + } + } +} diff --git a/src/LexicographicallySmallestPalindrome.java b/src/LexicographicallySmallestPalindrome.java new file mode 100644 index 0000000..0963bdf --- /dev/null +++ b/src/LexicographicallySmallestPalindrome.java @@ -0,0 +1,27 @@ +// https://leetcode.com/problems/lexicographically-smallest-palindrome +// T: O(N) +// S: O(N) + +public class LexicographicallySmallestPalindrome { + public String makeSmallestPalindrome(String s) { + final StringBuilder firstPart = new StringBuilder(); + final StringBuilder lastPart = new StringBuilder(); + + for (int i = 0 ; i < s.length() / 2 ; i++) { + char first = s.charAt(i), last = s.charAt(s.length() - 1 - i); + if (first != last) { + char smaller = (char) Math.min(first, last); + firstPart.append(smaller); + lastPart.append(smaller); + } else { + firstPart.append(first); + lastPart.append(first); + } + } + + if (s.length() % 2 == 0) { + return firstPart.append(lastPart.reverse()).toString(); + } + return firstPart.append(s.charAt(s.length() / 2)).append(lastPart.reverse()).toString(); + } +} diff --git a/src/LexicographicallySmallestStringAfterASwap.java b/src/LexicographicallySmallestStringAfterASwap.java new file mode 100644 index 0000000..db13761 --- /dev/null +++ b/src/LexicographicallySmallestStringAfterASwap.java @@ -0,0 +1,24 @@ +// https://leetcode.com/problems/lexicographically-smallest-string-after-a-swap +// T: O(|s|) +// S: O(|s|) + +public class LexicographicallySmallestStringAfterASwap { + public String getSmallestString(String s) { + for (int i = 0 ; i < s.length() - 1 ; i++) { + if (sameParity(s, i) && s.charAt(i) > s.charAt(i + 1)) { + return swapCharWithNextChar(s, i); + } + } + return s; + } + + private static boolean sameParity(String s, int index) { + return Integer.parseInt(s.charAt(index) + "") % 2 == + Integer.parseInt(s.charAt(index + 1) + "") % 2; + } + + private static String swapCharWithNextChar(String s, int index) { + return s.substring(0, index) + s.charAt(index + 1) + + s.charAt(index) + s.substring(index + 2); + } +} diff --git a/src/LinkedListCycle.java b/src/LinkedListCycle.java index bf4265c..3c2adae 100644 --- a/src/LinkedListCycle.java +++ b/src/LinkedListCycle.java @@ -1,26 +1,16 @@ -import java.util.HashSet; -import java.util.Set; +// T: O(n) +// S: O(1) public class LinkedListCycle { - static class ListNode { - int val; - ListNode next; - ListNode(int x) { - val = x; - next = null; - } - } - public boolean hasCycle(ListNode head) { - Set nodes = new HashSet<>(); - while (head != null) { - if (nodes.contains(head)) { - return true; - } else { - nodes.add(head); - } - head = head.next; + if (head == null) return false; + + for (ListNode slow = head, fast = head.next; fast != null && fast.next != null ; ) { + if (slow == fast) return true; + slow = slow.next; + fast = fast.next.next; } + return false; } } diff --git a/src/LinkedListCycleII.java b/src/LinkedListCycleII.java new file mode 100644 index 0000000..cd27d62 --- /dev/null +++ b/src/LinkedListCycleII.java @@ -0,0 +1,24 @@ +// https://leetcode.com/problems/linked-list-cycle-ii +// T: O(n) +// S: O(1) + +public class LinkedListCycleII { + public ListNode detectCycle(ListNode head) { + if (head == null) return null; + + ListNode slow = head, fast = head, entry = head; + while (fast.next != null && fast.next.next != null) { + slow = slow.next; + fast = fast.next.next; + + if (slow == fast) { + while (entry != slow) { + entry = entry.next; + slow = slow.next; + } + return entry; + } + } + return null; + } +} diff --git a/src/ListNode.java b/src/ListNode.java new file mode 100644 index 0000000..8f00c5b --- /dev/null +++ b/src/ListNode.java @@ -0,0 +1,22 @@ +public class ListNode { + int val; + ListNode next; + + ListNode() { } + + ListNode(int val) { + this.val = val; + } + + ListNode(int val, ListNode next) { + this.val = val; + this.next = next; + } + + @Override + public String toString() { + return "ListNode{" + + "val=" + val + + '}'; + } +} diff --git a/src/LoggerRateLimiter.java b/src/LoggerRateLimiter.java new file mode 100644 index 0000000..e657c64 --- /dev/null +++ b/src/LoggerRateLimiter.java @@ -0,0 +1,28 @@ +// https://leetcode.com/problems/logger-rate-limiter +// N: number of requests made to shouldPrint(), M: total number of different messages +// T: O(N) +// S: O(M) + +import java.util.HashMap; +import java.util.Map; + +public class LoggerRateLimiter { +} + +class Logger { + final Map messageTimestamps = new HashMap<>(); + + public boolean shouldPrintMessage(int timestamp, String message) { + if (!messageTimestamps.containsKey(message)) { + messageTimestamps.put(message, timestamp); + return true; + } + + if (messageTimestamps.get(message) + 10 > timestamp) { + return false; + } + + messageTimestamps.put(message, timestamp); + return true; + } +} \ No newline at end of file diff --git a/src/LongPressedName.java b/src/LongPressedName.java new file mode 100644 index 0000000..82ccf53 --- /dev/null +++ b/src/LongPressedName.java @@ -0,0 +1,21 @@ +public class LongPressedName { + public boolean isLongPressedName(String name, String typed) { + char current = name.charAt(0); + for (int i = 0, j = 0, freq = 0, typedFreq = 0 ; i < name.length() && j < typed.length() ; ) { + while (i < name.length() && name.charAt(i) == current) { + i++; + freq++; + } + while (j < typed.length() && typed.charAt(j) == current) { + j++; + typedFreq++; + } + if (typedFreq < freq) return false; + if (i == name.length() && j < typed.length()) return false; + if (j == typed.length() && i < name.length()) return false; + current = i >= name.length() ? ' ' : name.charAt(i); + freq = typedFreq = 0; + } + return true; + } +} diff --git a/src/LongerContiguousSegmentOfOnesThanZeros.java b/src/LongerContiguousSegmentOfOnesThanZeros.java new file mode 100644 index 0000000..6feaec4 --- /dev/null +++ b/src/LongerContiguousSegmentOfOnesThanZeros.java @@ -0,0 +1,19 @@ +// https://leetcode.com/problems/longer-contiguous-segments-of-ones-than-zeros +// T: O(N) +// S: O(1) + +public class LongerContiguousSegmentOfOnesThanZeros { + public boolean checkZeroOnes(String s) { + return lengthContiguousSegment(s, '1') > lengthContiguousSegment(s, '0'); + } + + private int lengthContiguousSegment(String s, char c) { + int maxLen = 0; + for (int i = 0, current = 0 ; i < s.length() ; i++) { + if (s.charAt(i) == c) current++; + else current = 0; + maxLen = Math.max(maxLen, current); + } + return maxLen; + } +} diff --git a/src/LongestAlternatingSubarray.java b/src/LongestAlternatingSubarray.java new file mode 100644 index 0000000..c77ada3 --- /dev/null +++ b/src/LongestAlternatingSubarray.java @@ -0,0 +1,15 @@ +// https://leetcode.com/problems/longest-alternating-subarray +// T: O(N) +// S: O(1) + +public class LongestAlternatingSubarray { + public int alternatingSubarray(int[] array) { + int maxLength = 0, j = 0; + for (int i = 0 ; i < array.length ; i = Math.max(i + 1, j - 1)) { + for (j = i + 1 ; j < array.length && array[j] == array[i] + (j - i) % 2 ; j++) { + maxLength = Math.max(maxLength, j - i + 1); + } + } + return maxLength > 1 ? maxLength : -1; + } +} diff --git a/src/LongestCommonPrefix.java b/src/LongestCommonPrefix.java index 6f289c4..33e9033 100644 --- a/src/LongestCommonPrefix.java +++ b/src/LongestCommonPrefix.java @@ -1,4 +1,6 @@ -// https://leetcode.com/problems/longest-common-prefix/ +// https://leetcode.com/problems/longest-common-prefix +// T: O(|array| * |array[i]|) +// S: O(|array[i]|) public class LongestCommonPrefix { public String longestCommonPrefix(String[] array) { diff --git a/src/LongestCommonSubsequence.java b/src/LongestCommonSubsequence.java new file mode 100644 index 0000000..1091a53 --- /dev/null +++ b/src/LongestCommonSubsequence.java @@ -0,0 +1,39 @@ +public class LongestCommonSubsequence { + public int longestCommonSubsequence(String text1, String text2) { + final int[][] memory = new int[2][text2.length()]; + final int rows = text1.length(), columns = text2.length(); + + // first row, first column + memory[0][0] = text1.charAt(0) == text2.charAt(0) ? 1 : 0; + + // first row + for (int column = 1 ; column < columns ; column++) { + memory[0][column] = text2.charAt(column) == text1.charAt(0) ? 1 : memory[0][column - 1]; + } + + int i = 1; + // rest of table + for (int row = 1 ; row < rows ; row++, i ^= 1) { + for (int column = 0 ; column < text2.length() ; column++) { + if (column == 0) { + memory[i][column] = text1.charAt(row) == text2.charAt(0) ? 1 : memory[i ^ 1][column]; + } else { + memory[i][column] = max( + memory[i][column - 1], + memory[i ^ 1][column], + text1.charAt(row) == text2.charAt(column) ? 1 + memory[i ^ 1][column - 1] : 0 + ); + } + } + } + return memory[i ^ 1][columns - 1]; + } + + private int max(int... values) { + int result = 0; + for (int value : values) { + result = Math.max(result, value); + } + return result; + } +} diff --git a/src/LongestConsecutiveSequence.java b/src/LongestConsecutiveSequence.java new file mode 100644 index 0000000..228903f --- /dev/null +++ b/src/LongestConsecutiveSequence.java @@ -0,0 +1,33 @@ +// https://leetcode.com/problems/longest-consecutive-sequence +// T: O(n) +// S: O(n) + +import java.util.HashSet; +import java.util.Set; + +public class LongestConsecutiveSequence { + public int longestConsecutive(int[] nums) { + final Set numbers = setFrom(nums); + int maxLength = 0; + + for (int number : numbers) { + if (!numbers.contains(number - 1)) { + int length = 1; + for (int i = number + 1 ; numbers.contains(i) ; i++) { + length++; + } + maxLength = Math.max(maxLength, length); + } + } + + return maxLength; + } + + private Set setFrom(int[] array) { + final Set set = new HashSet<>(); + for (int element : array) { + set.add(element); + } + return set; + } +} diff --git a/src/LongestContinuousIncreasingSubsequence.java b/src/LongestContinuousIncreasingSubsequence.java new file mode 100644 index 0000000..ce79c46 --- /dev/null +++ b/src/LongestContinuousIncreasingSubsequence.java @@ -0,0 +1,14 @@ +public class LongestContinuousIncreasingSubsequence { + public int findLengthOfLCIS(int[] nums) { + int result = 1, current = 1; + for (int index = 1 ; index < nums.length ; index++) { + if (nums[index] > nums[index - 1]) { + current++; + result = Math.max(result, current); + } else { + current = 1; + } + } + return result; + } +} diff --git a/src/LongestEvenOddSubarrayWithThreshold.java b/src/LongestEvenOddSubarrayWithThreshold.java new file mode 100644 index 0000000..3e3b10e --- /dev/null +++ b/src/LongestEvenOddSubarrayWithThreshold.java @@ -0,0 +1,18 @@ +// https://leetcode.com/problems/longest-even-odd-subarray-with-threshold +// T: O(N) +// S: O(N) + +public class LongestEvenOddSubarrayWithThreshold { + public int longestAlternatingSubarray(int[] array, int threshold) { + final int[] dp = new int[array.length]; + dp[0] = array[0] % 2 == 0 && array[0] <= threshold ? 1 : 0; + int maxLength = dp[0]; + for (int i = 1 ; i < dp.length ; i++) { + if (array[i] <= threshold && array[i] % 2 != array[i - 1] % 2 && dp[i - 1] > 0) dp[i] = dp[i - 1] + 1; + else if (array[i] % 2 == 0 && array[i] <= threshold) dp[i] = 1; + else dp[i] = 0; + maxLength = Math.max(maxLength, dp[i]); + } + return maxLength; + } +} diff --git a/src/LongestHarmoniousSubsequence.java b/src/LongestHarmoniousSubsequence.java new file mode 100644 index 0000000..5dfa15b --- /dev/null +++ b/src/LongestHarmoniousSubsequence.java @@ -0,0 +1,26 @@ +import java.util.HashMap; +import java.util.Map; + +public class LongestHarmoniousSubsequence { + public int findLHS(int[] array) { + Map frequencies = getFrequencies(array); + int value, frequency, result = 0; + for (Map.Entry entry : frequencies.entrySet()) { + value = entry.getKey(); + frequency = entry.getValue(); + result = Math.max(result, Math.max( + frequencies.containsKey(value - 1) ? frequency + frequencies.get(value - 1) : 0, + frequencies.containsKey(value + 1) ? frequency + frequencies.get(value + 1) : 0 + )); + } + return result; + } + + private Map getFrequencies(int[] array) { + Map frequencies = new HashMap<>(); + for (int element : array) { + frequencies.put(element, frequencies.getOrDefault(element, 0) + 1); + } + return frequencies; + } +} diff --git a/src/LongestIncreasingSubsequence.java b/src/LongestIncreasingSubsequence.java new file mode 100644 index 0000000..ce15838 --- /dev/null +++ b/src/LongestIncreasingSubsequence.java @@ -0,0 +1,43 @@ +// https://leetcode.com/problems/longest-increasing-subsequence +// T: O(NlogN) +// S: O(N) + +import java.util.ArrayList; +import java.util.List; + +public class LongestIncreasingSubsequence { + public static int lengthOfLIS(int[] nums) { + final List tail = new ArrayList<>(); + int maxLength = 1; + tail.add(nums[0]); + + for (int i = 1 ; i < nums.length ; i++) { + if (nums[i] > tail.get(maxLength - 1)) { + tail.add(nums[i]); + maxLength++; + } else if (nums[i] < tail.get(0)) { + tail.set(0, nums[i]); + } else { + int insertionIndex = binarySearch(tail, nums[i]); + tail.set(insertionIndex, nums[i]); + } + } + + return maxLength; + } + + private static int binarySearch(List array, int x) { + int left = 0, right = array.size(), middle; + while (left <= right) { + middle = left + (right - left) / 2; + if (array.get(middle) == x) return middle; + else if (array.get(middle) < x) left = middle + 1; + else right = middle - 1; + } + return left; + } + + public static void main(String[] args) { + System.out.println(lengthOfLIS(new int[] {1,3,6,7,9,4,10,5,6})); + } +} diff --git a/src/LongestNiceSubstring.java b/src/LongestNiceSubstring.java new file mode 100644 index 0000000..bc124dd --- /dev/null +++ b/src/LongestNiceSubstring.java @@ -0,0 +1,40 @@ +import java.util.HashSet; +import java.util.Set; + +public class LongestNiceSubstring { + public String longestNiceSubstring(String s) { + String longestNiceSubString = ""; + Set alphabets = new HashSet<>(); + for (int i = 0 ; i < s.length() ; i++) { + for (int j = i ; j < s.length() ; j++) { + alphabets.add(s.charAt(j)); + if (containsBotLowerAndUpperCase(alphabets) && j - i + 1 > longestNiceSubString.length()) { + longestNiceSubString = s.substring(i, j + 1); + } + } + alphabets.clear(); + } + return longestNiceSubString; + } + + private boolean containsBotLowerAndUpperCase(Set alphabets) { + for (char alphabet : alphabets) { + if (!alphabets.contains(inverse(alphabet))) { + return false; + } + } + return true; + } + + private char inverse(char c) { + return Character.isLowerCase(c) ? Character.toUpperCase(c) : Character.toLowerCase(c); + } + + private Set getCharacters(String s, int start, int end) { + final Set set = new HashSet<>(); + for (int index = start ; index <= end ; index++) { + set.add(s.charAt(index)); + } + return set; + } +} diff --git a/src/LongestPalindromicSubstring.java b/src/LongestPalindromicSubstring.java new file mode 100644 index 0000000..661021d --- /dev/null +++ b/src/LongestPalindromicSubstring.java @@ -0,0 +1,29 @@ +// https://leetcode.com/problems/longest-palindromic-substring +// T: O(n^2) +// S: O(1) + +public class LongestPalindromicSubstring { + public String longestPalindrome(String s) { + if (s.length() < 2) return s; + int maxLen = 0, startIndex = -1; + for (int i = 0, len ; i < s.length() - 1 ; i++) { + len = palindromeLengthFromCenter(s, i, i); + if (s.charAt(i) == s.charAt(i + 1)) { + len = Math.max(len, palindromeLengthFromCenter(s, i, i + 1)); + } + if (len > maxLen) { + maxLen = len; + startIndex = i - (maxLen - 1) / 2; + } + } + return s.substring(startIndex, startIndex + maxLen); + } + + private int palindromeLengthFromCenter(String s, int left, int right) { + while (left - 1 >= 0 && right + 1 < s.length() && s.charAt(left - 1) == s.charAt(right + 1)) { + left--; + right++; + } + return right - left + 1; + } +} diff --git a/src/LongestStrictlyIncreasingOrStrictlyDecreasingSubarray.java b/src/LongestStrictlyIncreasingOrStrictlyDecreasingSubarray.java new file mode 100644 index 0000000..dd161f5 --- /dev/null +++ b/src/LongestStrictlyIncreasingOrStrictlyDecreasingSubarray.java @@ -0,0 +1,38 @@ +// https://leetcode.com/problems/longest-strictly-increasing-or-strictly-decreasing-subarray +// T: O(N) +// S: O(1) + +public class LongestStrictlyIncreasingOrStrictlyDecreasingSubarray { + public int longestMonotonicSubarray(int[] array) { + return Math.max( + lengthLongestIncreasingSubarray(array), + lengthLongestDecreasingSubarray(array) + ); + } + + private static int lengthLongestIncreasingSubarray(int[] array) { + int length = 1; + for (int i = 1, current = 1 ; i < array.length ; i++) { + if (array[i] > array[i - 1]) { + current++; + } else { + current = 1; + } + length = Math.max(length, current); + } + return length; + } + + private static int lengthLongestDecreasingSubarray(int[] array) { + int length = 1; + for (int i = 1, current = 1 ; i < array.length ; i++) { + if (array[i] < array[i - 1]) { + current++; + } else { + current = 1; + } + length = Math.max(length, current); + } + return length; + } +} diff --git a/src/LongestSubsequenceWithLimitedSum.java b/src/LongestSubsequenceWithLimitedSum.java new file mode 100644 index 0000000..b4412d1 --- /dev/null +++ b/src/LongestSubsequenceWithLimitedSum.java @@ -0,0 +1,46 @@ +// https://leetcode.com/problems/longest-subsequence-with-limited-sum +// T: O((n + m) log(n)) +// S: O(n) + +import java.util.PriorityQueue; +import java.util.Queue; + +public class LongestSubsequenceWithLimitedSum { + public int[] answerQueries(int[] nums, int[] queries) { + final int[] result = new int[queries.length]; + final int[] prefixSumArray = getMinSumArray(nums); + + for (int index = 0 ; index < queries.length ; index++) { + int maxLen = binarySearch(prefixSumArray, queries[index]); + if (maxLen < prefixSumArray.length && prefixSumArray[maxLen] == queries[index]) { + result[index] = maxLen + 1; + } else result[index] = maxLen; + } + + return result; + } + + private int binarySearch(int[] array, int x) { + int left = 0, right = array.length - 1, index = 0; + while (left <= right) { + index = left + (right - left) / 2; + if (array[index] == x) return index; + else if (array[index] > x) right = index - 1; + else left = index + 1; + } + return left; + } + + private int[] getMinSumArray(int[] array) { + final Queue minHeap = new PriorityQueue<>(); + final int[] result = new int[array.length]; + for (int element : array) { + minHeap.add(element); + } + result[0] = minHeap.poll(); + for (int index = 1 ; index < result.length ; index++) { + result[index] = result[index - 1] + minHeap.poll(); + } + return result; + } +} diff --git a/src/LongestSubstringWithoutRepeatingCharacters.java b/src/LongestSubstringWithoutRepeatingCharacters.java new file mode 100644 index 0000000..e70f68b --- /dev/null +++ b/src/LongestSubstringWithoutRepeatingCharacters.java @@ -0,0 +1,23 @@ +// https://leetcode.com/problems/longest-substring-without-repeating-characters +// T: O(|s|) +// S: O(1) + +import java.util.HashSet; +import java.util.Set; + +public class LongestSubstringWithoutRepeatingCharacters { + public int lengthOfLongestSubstring(String s) { + final Set letters = new HashSet<>(); + int maxLength = 1; + for (int i = 0, j = 0 ; i < s.length() ; i++) { + if (letters.contains(s.charAt(i))) { + while (letters.contains(s.charAt(i))) { + letters.remove(s.charAt(j++)); + } + } + letters.add(s.charAt(i)); + maxLength = Math.max(maxLength, i - j + 1); + } + return maxLength; + } +} diff --git a/src/LongestUncommonSubsequenceI.java b/src/LongestUncommonSubsequenceI.java new file mode 100644 index 0000000..6d04e51 --- /dev/null +++ b/src/LongestUncommonSubsequenceI.java @@ -0,0 +1,6 @@ +public class LongestUncommonSubsequenceI { + public int findLUSlength(String a, String b) { + if (a.equals(b)) return -1; + return Math.max(a.length(), b.length()); + } +} diff --git a/src/LongestUnequalAdjacentGroupsSubsequenceI.java b/src/LongestUnequalAdjacentGroupsSubsequenceI.java new file mode 100644 index 0000000..14c0143 --- /dev/null +++ b/src/LongestUnequalAdjacentGroupsSubsequenceI.java @@ -0,0 +1,21 @@ +// https://leetcode.com/problems/longest-unequal-adjacent-groups-subsequence-i +// T: O(|groups|) +// S: O(1) + +import java.util.ArrayList; +import java.util.List; + +public class LongestUnequalAdjacentGroupsSubsequenceI { + public List getLongestSubsequence(String[] words, int[] groups) { + final List result = new ArrayList<>(); + + for (int i = 0, previous = -1 ; i < groups.length ; i++) { + if (groups[i] != previous) { + result.add(words[i]); + } + previous = groups[i]; + } + + return result; + } +} diff --git a/src/LowestCommonAncestorOfBinarySearchTree.java b/src/LowestCommonAncestorOfBinarySearchTree.java index 9b54a35..4b488d6 100644 --- a/src/LowestCommonAncestorOfBinarySearchTree.java +++ b/src/LowestCommonAncestorOfBinarySearchTree.java @@ -2,11 +2,6 @@ import java.util.List; public class LowestCommonAncestorOfBinarySearchTree { - private static class TreeNode { - int val; - TreeNode left; - TreeNode right; - } public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { List pathToP = pathTo(root, p); diff --git a/src/LowestCommonAncestorOfBinaryTree.java b/src/LowestCommonAncestorOfBinaryTree.java new file mode 100644 index 0000000..3bfd075 --- /dev/null +++ b/src/LowestCommonAncestorOfBinaryTree.java @@ -0,0 +1,13 @@ +// https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree +// T: O(N) +// S: O(log(N)) + +public class LowestCommonAncestorOfBinaryTree { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + if (root == null || root == p || root == q) return root; + TreeNode left = lowestCommonAncestor(root.left, p, q); + TreeNode right = lowestCommonAncestor(root.right, p, q); + if (left != null && right != null) return root; + return left == null ? right : left; + } +} diff --git a/src/LuckyNumbersInAMatrix.java b/src/LuckyNumbersInAMatrix.java new file mode 100644 index 0000000..e26e5a7 --- /dev/null +++ b/src/LuckyNumbersInAMatrix.java @@ -0,0 +1,49 @@ +import java.util.ArrayList; +import java.util.List; + +public class LuckyNumbersInAMatrix { + public List luckyNumbers (int[][] matrix) { + final int rows = matrix.length, columns = matrix[0].length; + final List luckyNumbers = new ArrayList<>(); + int[] columnMax = getMaxOfColumns(matrix); + for (int row = 0 ; row < rows ; row++) { + RowMin rowMin = RowMin.from(matrix[row]); + if (rowMin.min == columnMax[rowMin.index]) { + luckyNumbers.add(rowMin.min); + } + } + return luckyNumbers; + } + + private static final class RowMin { + private final int index; + private final int min; + + private RowMin(int index, int min) { + this.index = index; + this.min = min; + } + + private static RowMin from(int[] row) { + int minIndex = 0, min = row[0]; + for (int i = 1; i < row.length; i++) { + if (row[i] < min) { + minIndex = i; + min = row[i]; + } + } + return new RowMin(minIndex, min); + } + } + + private int[] getMaxOfColumns(int[][] grid) { + final int rows = grid.length, columns = grid[0].length; + final int[] columnsMax = new int[columns]; + for (int[] row : grid) { + for (int column = 0 ; column < columns ; column++) { + columnsMax[column] = Math.max(columnsMax[column], row[column]); + } + } + return columnsMax; + } +} diff --git a/src/MajorityElement.java b/src/MajorityElement.java index ee47435..ee63039 100644 --- a/src/MajorityElement.java +++ b/src/MajorityElement.java @@ -1,24 +1,20 @@ -import java.util.HashMap; -import java.util.Map; +// https://leetcode.com/problems/majority-element +// T: O(N) +// S: O(1) public class MajorityElement { - public int majorityElement(int[] array) { - Map frequencies = getFrequencies(array); - int maxFrequency = frequencies.values().stream().max(Integer::compareTo).get(); - for (Map.Entry entry : frequencies.entrySet()) { - if (entry.getValue() == maxFrequency) { - return entry.getKey(); - } - } + public int majorityElement(int[] nums) { + int candidate = nums[0], frequency = 0; - return -1; - } + for (int element : nums) { + frequency += element == candidate ? 1 : -1; - private static Map getFrequencies(int[] array) { - Map result = new HashMap<>(); - for (int element : array) { - result.put(element, result.getOrDefault(element, 0) + 1); + if (frequency == 0) { + candidate = element; + frequency = 1; + } } - return result; + + return candidate; } } diff --git a/src/MajorityElementII.java b/src/MajorityElementII.java new file mode 100644 index 0000000..26664fb --- /dev/null +++ b/src/MajorityElementII.java @@ -0,0 +1,42 @@ +// https://leetcode.com/problems/majority-element-ii +// T: O(N) +// S: O(1) + +import java.util.ArrayList; +import java.util.List; + +public class MajorityElementII { + public List majorityElement(int[] nums) { + int candidate1 = 0, candidate2 = 0, frequency1 = 0, frequency2 = 0; + for (int element : nums) { + if (element == candidate1) frequency1++; + else if (element == candidate2) frequency2++; + else if (frequency1 == 0) { + candidate1 = element; + frequency1 = 1; + } else if (frequency2 == 0) { + candidate2 = element; + frequency2 = 1; + } else { + frequency1--; + frequency2--; + } + } + return confirmCandidates(nums, candidate1, candidate2); + } + + private List confirmCandidates(int[] array, int candidate1, int candidate2) { + final List result = new ArrayList<>(); + if (frequency(array, candidate1) > array.length / 3) result.add(candidate1); + if (candidate2 != candidate1 && frequency(array, candidate2) > array.length / 3) result.add(candidate2); + return result; + } + + private int frequency(int[] array, int val) { + int count = 0; + for (int element : array) { + if (element == val) count++; + } + return count; + } +} diff --git a/src/MakeASquareWithTheSameColor.java b/src/MakeASquareWithTheSameColor.java new file mode 100644 index 0000000..9d04700 --- /dev/null +++ b/src/MakeASquareWithTheSameColor.java @@ -0,0 +1,33 @@ +// https://leetcode.com/problems/make-a-square-with-the-same-color +// T: O(1) +// S: O(1) + +public class MakeASquareWithTheSameColor { + public boolean canMakeSquare(char[][] grid) { + for (int i = 0 ; i < 2 ; i++) { + for (int j = 0 ; j < 2 ; j++) { + if (isPossibleToMakeSquare(grid, i, j)) { + return true; + } + } + } + return false; + } + + private static boolean isPossibleToMakeSquare(char[][] grid, int i, int j) { + int numberOfBlacks = 0; + int numberOfWhites = 0; + + for (int row = i ; row < i + 2 ; row++) { + for (int column = j ; column < j + 2 ; column++) { + if (grid[row][column] == 'W') { + numberOfWhites++; + } else { + numberOfBlacks++; + } + } + } + + return numberOfBlacks == 4 || numberOfWhites == 4 || numberOfBlacks == 3 || numberOfWhites == 3; + } +} diff --git a/src/MakeArrayZeroBySubtractingEqualAmounts.java b/src/MakeArrayZeroBySubtractingEqualAmounts.java new file mode 100644 index 0000000..65ff7c8 --- /dev/null +++ b/src/MakeArrayZeroBySubtractingEqualAmounts.java @@ -0,0 +1,18 @@ +// https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts +// T: O(|nums|) +// S: O(|nums|) + +import java.util.HashSet; +import java.util.Set; + +public class MakeArrayZeroBySubtractingEqualAmounts { + public int minimumOperations(int[] nums) { + final Set set = new HashSet<>(); + for (int element : nums) { + if (element != 0) { + set.add(element); + } + } + return set.size(); + } +} diff --git a/src/MakeTheStringGreat.java b/src/MakeTheStringGreat.java new file mode 100644 index 0000000..c64272c --- /dev/null +++ b/src/MakeTheStringGreat.java @@ -0,0 +1,28 @@ +// https://leetcode.com/problems/make-the-string-great +// T: O(N) +// S: O(N) + +import java.util.Stack; + +public class MakeTheStringGreat { + public String makeGood(String s) { + final Stack characters = new Stack<>(); + for (int index = 0 ; index < s.length() ; index++) { + char c = s.charAt(index); + if (!characters.isEmpty() && c == inverse(characters.peek())) { + characters.pop(); + } else characters.push(c); + } + return toStringBuilder(characters).reverse().toString(); + } + + private StringBuilder toStringBuilder(Stack stack) { + StringBuilder result = new StringBuilder(); + while (!stack.isEmpty()) result.append(stack.pop()); + return result; + } + + private char inverse(char c) { + return Character.isUpperCase(c) ? Character.toLowerCase(c) : Character.toUpperCase(c); + } +} diff --git a/src/MakeThreeStringsEqual.java b/src/MakeThreeStringsEqual.java new file mode 100644 index 0000000..6bc4c44 --- /dev/null +++ b/src/MakeThreeStringsEqual.java @@ -0,0 +1,21 @@ +// https://leetcode.com/problems/make-three-strings-equal +// T: O(min(|s1|, |s2|, |s3|)) +// S: O(1) + +public class MakeThreeStringsEqual { + public int findMinimumOperations(String s1, String s2, String s3) { + int maxPrefixLength = 0; + for (int i = 0, j = 0, k = 0 ; i < s1.length() && j < s2.length() && k < s3.length() ; i++, j++, k++) { + if (s1.charAt(i) != s2.charAt(j) || s2.charAt(j) != s3.charAt(k)) { + break; + } + maxPrefixLength++; + } + + if (maxPrefixLength == 0) { + return -1; + } + + return s1.length() + s2.length() + s3.length() - 3 * maxPrefixLength; + } +} diff --git a/src/MakeTwoArraysEqualByReversingSubArrays.java b/src/MakeTwoArraysEqualByReversingSubArrays.java new file mode 100644 index 0000000..cc3d377 --- /dev/null +++ b/src/MakeTwoArraysEqualByReversingSubArrays.java @@ -0,0 +1,18 @@ +import java.util.HashMap; +import java.util.Map; + +public class MakeTwoArraysEqualByReversingSubArrays { + public boolean canBeEqual(int[] target, int[] array) { + Map targetFrequencies = getFrequencies(target); + Map arrayFrequencies = getFrequencies(array); + return targetFrequencies.equals(arrayFrequencies); + } + + private Map getFrequencies(int[] array) { + Map frequencies = new HashMap<>(); + for (int element : array) { + frequencies.put(element, frequencies.getOrDefault(element, 0) + 1); + } + return frequencies; + } +} diff --git a/src/MatrixCellsInDistanceOrder.java b/src/MatrixCellsInDistanceOrder.java new file mode 100644 index 0000000..536c583 --- /dev/null +++ b/src/MatrixCellsInDistanceOrder.java @@ -0,0 +1,26 @@ +import java.util.LinkedList; +import java.util.Queue; + +public class MatrixCellsInDistanceOrder { + public int[][] allCellsDistOrder(final int rows, final int columns, int rCenter, int cCenter) { + int[][] result = new int[rows * columns][2]; + final Queue positions = new LinkedList<>(); + final boolean[][] visited = new boolean[rows][columns]; + positions.add(new int[] {rCenter, cCenter}); + int k = 0, row, column; + while (!positions.isEmpty()) { + int[] position = positions.poll(); + row = position[0]; + column = position[1]; + if (row < 0 || row >= rows || column < 0 || column >= columns) continue; + if (visited[row][column]) continue; + visited[row][column] = true; + result[k++] = position; + positions.add(new int[] {row - 1, column}); + positions.add(new int[] {row, column + 1}); + positions.add(new int[] {row + 1, column}); + positions.add(new int[] {row, column - 1}); + } + return result; + } +} diff --git a/src/MatrixDiagonalSum.java b/src/MatrixDiagonalSum.java new file mode 100644 index 0000000..e9c65da --- /dev/null +++ b/src/MatrixDiagonalSum.java @@ -0,0 +1,26 @@ +// https://leetcode.com/problems/matrix-diagonal-sum +// T: O(N) +// S: O(1) + +public class MatrixDiagonalSum { + public int diagonalSum(int[][] matrix) { + return sumPrimaryDiagonal(matrix) + sumSecondaryDiagonal(matrix) - + ((matrix.length & 1) == 1 ? matrix[matrix.length / 2][matrix.length / 2] : 0); + } + + private int sumPrimaryDiagonal(int[][] matrix) { + int sum = 0; + for (int i = 0 ; i < matrix.length ; i++) { + sum += matrix[i][i]; + } + return sum; + } + + private int sumSecondaryDiagonal(int[][] matrix) { + int sum = 0; + for (int i = 0 ; i < matrix.length ; i++) { + sum += matrix[i][matrix.length - 1 - i]; + } + return sum; + } +} diff --git a/src/MatrixSimilarityAfterCyclicShifts.java b/src/MatrixSimilarityAfterCyclicShifts.java new file mode 100644 index 0000000..227b442 --- /dev/null +++ b/src/MatrixSimilarityAfterCyclicShifts.java @@ -0,0 +1,48 @@ +// https://leetcode.com/problems/matrix-similarity-after-cyclic-shifts +// m = rows(mat), n = columns(mat) +// T: O(m * n) +// S: O(1) + +public class MatrixSimilarityAfterCyclicShifts { + public boolean areSimilar(int[][] matrix, int k) { + final int rows = matrix.length, columns = matrix[0].length; + + if (k % columns == 0) { + return true; + } + + for (int i = 0 ; i < rows ; i += 2) { + if (!isValidLeftShift(matrix[i], k)) { + return false; + } + } + + for (int i = 1 ; i < rows ; i += 2) { + if (!isValidRightShift(matrix[i], k)) { + return false; + } + } + + return true; + } + + private static boolean isValidRightShift(int[] row, int shift) { + int shiftLength = shift % row.length; + for (int i = 0, k = 0 ; k < row.length ; i = (i + 1) % row.length, k++) { + if (row[i] != row[(i + shiftLength) % row.length]) { + return false; + } + } + return true; + } + + private static boolean isValidLeftShift(int[] row, int shift) { + final int shiftLength = shift % row.length; + for (int i = 0, k = 0 ; k < row.length ; i = (i + 1) % row.length, k++) { + if (row[i] != row[(i - shiftLength + row.length) % row.length]) { + return false; + } + } + return true; + } +} diff --git a/src/MaxPairSumInAnArray.java b/src/MaxPairSumInAnArray.java new file mode 100644 index 0000000..0b9499f --- /dev/null +++ b/src/MaxPairSumInAnArray.java @@ -0,0 +1,27 @@ +// https://leetcode.com/problems/max-pair-sum-in-an-array +// T: O(N) +// S: O(1) + +public class MaxPairSumInAnArray { + public int maxSum(int[] nums) { + final int[] digitMaxSum = new int[9]; + int maxPairSum = 0; + for (int element : nums) { + final int maxDigit = getMaxDigit(element); + if (digitMaxSum[maxDigit - 1] != 0) { + maxPairSum = Math.max(maxPairSum, digitMaxSum[maxDigit - 1] + element); + } + digitMaxSum[maxDigit - 1] = Math.max(digitMaxSum[maxDigit - 1], element); + } + return maxPairSum == 0 ? -1 : maxPairSum; + } + + private int getMaxDigit(int number) { + final String string = number + ""; + int maxDigit = 0; + for (int i = 0 ; i < string.length() ; i++) { + maxDigit = Math.max(maxDigit, string.charAt(i) - '0'); + } + return maxDigit; + } +} diff --git a/src/MaximalSquare.java b/src/MaximalSquare.java new file mode 100644 index 0000000..df44fe3 --- /dev/null +++ b/src/MaximalSquare.java @@ -0,0 +1,32 @@ +// https://leetcode.com/problems/maximal-square +// T: O(m * n) +// S: O(n) + +public class MaximalSquare { + public int maximalSquare(char[][] matrix) { + final int columns = matrix[0].length; + final int[] dp = new int[columns + 1]; + int maxSideLength = 0, prev = 0, temp; + + for (char[] row : matrix) { + for (int column = 0; column < columns; column++) { + temp = dp[column + 1]; + if (isOne(row[column])) { + dp[column + 1] = min(dp[column + 1], dp[column], prev) + 1; + } else dp[column + 1] = 0; + maxSideLength = Math.max(maxSideLength, dp[column + 1]); + prev = temp; + } + } + + return maxSideLength * maxSideLength; + } + + private int min(int a, int b, int c) { + return Math.min(a, Math.min(b, c)); + } + + private boolean isOne(char c) { + return c == '1'; + } +} diff --git a/src/MaximizeSumOfArrayAfterKNegations.java b/src/MaximizeSumOfArrayAfterKNegations.java new file mode 100644 index 0000000..d0b2850 --- /dev/null +++ b/src/MaximizeSumOfArrayAfterKNegations.java @@ -0,0 +1,26 @@ +import java.util.Arrays; + +public class MaximizeSumOfArrayAfterKNegations { + public int largestSumAfterKNegations(int[] nums, int k) { + Arrays.sort(nums); + int sum = 0, index = 0; + for ( ; index < nums.length && k > 0 ; index++) { + if (nums[index] < 0) { + sum -= nums[index]; + k--; + } else break; + } + if ((k & 1) == 1) { + if (index < nums.length) { + if (index == 0) sum -= nums[index]; + else if (-nums[index - 1] < nums[index]) sum += 2 * nums[index - 1] + nums[index]; + else sum -= nums[index]; + index++; + } else return sum + 2 * nums[nums.length - 1]; + } + for ( ; index < nums.length ; index++) { + sum += nums[index]; + } + return sum; + } +} diff --git a/src/Maximum69Number.java b/src/Maximum69Number.java new file mode 100644 index 0000000..c28749f --- /dev/null +++ b/src/Maximum69Number.java @@ -0,0 +1,19 @@ +public class Maximum69Number { + public int maximum69Number (int num) { + int result = 0; + int divisor = 10_000; + boolean changed = false; + while (num > 0) { + result *= 10; + if (!changed && num / divisor == 6) { + result += 9; + changed = true; + } else { + result += num / divisor; + } + num -= (num / divisor) * divisor; + divisor /= 10; + } + return result; + } +} diff --git a/src/MaximumAreaOfLongestDiagonalRectangle.java b/src/MaximumAreaOfLongestDiagonalRectangle.java new file mode 100644 index 0000000..07b4423 --- /dev/null +++ b/src/MaximumAreaOfLongestDiagonalRectangle.java @@ -0,0 +1,31 @@ +// https://leetcode.com/problems/maximum-area-of-longest-diagonal-rectangle +// T: O(N) +// S: O(1) + +public class MaximumAreaOfLongestDiagonalRectangle { + public int areaOfMaxDiagonal(int[][] dimensions) { + int maxArea = 0, maxDiagonal = 0; + + for (final int[] rectangle : dimensions) { + final int diagonal = getDiagonal(rectangle); + final int area = getArea(rectangle); + + if (diagonal > maxDiagonal) { + maxDiagonal = diagonal; + maxArea = area; + } else if (diagonal == maxDiagonal) { + maxArea = Math.max(maxArea, area); + } + } + + return maxArea; + } + + private static int getArea(int[] rectangle) { + return rectangle[0] * rectangle[1]; + } + + private static int getDiagonal(int[] rectangle) { + return rectangle[0] * rectangle[0] + rectangle[1] * rectangle[1]; + } +} diff --git a/src/MaximumAscendingSubArraySum.java b/src/MaximumAscendingSubArraySum.java new file mode 100644 index 0000000..faf908f --- /dev/null +++ b/src/MaximumAscendingSubArraySum.java @@ -0,0 +1,12 @@ +public class MaximumAscendingSubArraySum { + public int maxAscendingSum(int[] nums) { + int maxSum = nums[0]; + for (int index = 1, current = nums[0] ; index < nums.length ; index++) { + if (nums[index] > nums[index - 1]) { + current += nums[index]; + } else current = nums[index]; + maxSum = Math.max(maxSum, current); + } + return maxSum; + } +} diff --git a/src/MaximumAverageSubArrayI.java b/src/MaximumAverageSubArrayI.java new file mode 100644 index 0000000..5804dd2 --- /dev/null +++ b/src/MaximumAverageSubArrayI.java @@ -0,0 +1,14 @@ +public class MaximumAverageSubArrayI { + public double findMaxAverage(int[] numbers, int k) { + long sum = 0; + for (int i = 0 ; i < k ; i++) { + sum += numbers[i]; + } + double maxSum = sum; + for (int index = 0 ; index < numbers.length - k ; index++) { + sum += numbers[index + k] - numbers[index]; + maxSum = Math.max(maxSum, sum); + } + return maxSum / k; + } +} diff --git a/src/MaximumCountOfPositiveIntegerAndNegativeInteger.java b/src/MaximumCountOfPositiveIntegerAndNegativeInteger.java new file mode 100644 index 0000000..70da0bf --- /dev/null +++ b/src/MaximumCountOfPositiveIntegerAndNegativeInteger.java @@ -0,0 +1,39 @@ +// https://leetcode.com/problems/maximum-count-of-positive-integer-and-negative-integer +// T: O(log(N)) +// S: O(1) + +public class MaximumCountOfPositiveIntegerAndNegativeInteger { + public int maximumCount(int[] nums) { + int firstIndex = binarySearchFirstIndex(nums, 0); + int lastIndex = binarySearchLastIndex(nums, 0); + return Math.max(firstIndex, nums.length - lastIndex - (lastIndex < nums.length && nums[lastIndex] == 0 ? 1 : 0)); + } + + // left leaning binary search with insertion point + private int binarySearchFirstIndex(int[] array, int x) { + int left = 0, right = array.length - 1, middle, index = -1; + while (left <= right) { + middle = left + (right - left) / 2; + if (array[middle] == x) { + index = middle; + right = middle - 1; + } else if (array[middle] > x) right = middle - 1; + else left = middle + 1; + } + return index == -1 ? left : index; + } + + // right leaning binary search with insertion point + private int binarySearchLastIndex(int[] array, int x) { + int left = 0, right = array.length - 1, middle, index = -1; + while (left <= right) { + middle = left + (right - left) / 2; + if (array[middle] == x) { + index = middle; + left = middle + 1; + } else if (array[middle] > x) right = middle - 1; + else left = middle + 1; + } + return index == -1 ? left : index; + } +} diff --git a/src/MaximumDepthOfBinaryTree.java b/src/MaximumDepthOfBinaryTree.java index 4a716f8..050eb47 100644 --- a/src/MaximumDepthOfBinaryTree.java +++ b/src/MaximumDepthOfBinaryTree.java @@ -1,10 +1,4 @@ public class MaximumDepthOfBinaryTree { - private static class TreeNode { - int val; - TreeNode left; - TreeNode right; - } - public int maxDepth(TreeNode root) { if (root == null) { return 0; diff --git a/src/MaximumDepthOfNAryTree.java b/src/MaximumDepthOfNAryTree.java new file mode 100644 index 0000000..3cd2fd0 --- /dev/null +++ b/src/MaximumDepthOfNAryTree.java @@ -0,0 +1,32 @@ +// https://leetcode.com/problems/maximum-depth-of-n-ary-tree +// T: O(N) +// S: O(logN) + +import java.util.List; + +public class MaximumDepthOfNAryTree { + public static class Node { + public int val; + public List children; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, List _children) { + val = _val; + children = _children; + } + } + + public int maxDepth(Node root) { + if (root == null) return 0; + int maxDepth = 0; + for (Node child : root.children) { + maxDepth = Math.max(maxDepth, maxDepth(child)); + } + return 1 + maxDepth; + } +} diff --git a/src/MaximumDifferenceBetweenIncreasingElements.java b/src/MaximumDifferenceBetweenIncreasingElements.java new file mode 100644 index 0000000..1453ca4 --- /dev/null +++ b/src/MaximumDifferenceBetweenIncreasingElements.java @@ -0,0 +1,16 @@ +// https://leetcode.com/problems/maximum-difference-between-increasing-elements +// T: O(N) +// S: O(1) + +public class MaximumDifferenceBetweenIncreasingElements { + public int maximumDifference(int[] nums) { + int maxDifference = -1; + for (int index = nums.length - 2, currentMax = nums[nums.length - 1] ; index >= 0 ; index--) { + if (currentMax > nums[index]) { + maxDifference = Math.max(maxDifference, currentMax - nums[index]); + } + currentMax = Math.max(currentMax, nums[index]); + } + return maxDifference; + } +} diff --git a/src/MaximumDifferenceByRemappingADigit.java b/src/MaximumDifferenceByRemappingADigit.java new file mode 100644 index 0000000..a5f4443 --- /dev/null +++ b/src/MaximumDifferenceByRemappingADigit.java @@ -0,0 +1,37 @@ +// https://leetcode.com/problems/maximum-difference-by-remapping-a-digit +// T: O(log(N)) +// S: O(1) + +public class MaximumDifferenceByRemappingADigit { + public int minMaxDifference(int num) { + final String number = num + ""; + final int maxDigit = maxDigit(number); + final int minDigit = minDigit(number); + return maxDigit - minDigit; + } + + private int maxDigit(String x) { + for (int i = 0 ; i < x.length() ; i++) { + int digit = x.charAt(i) - '0'; + if (digit < 9) { + return changeOccurrence(x, digit, 9); + } + } + return Integer.parseInt(x); + } + + private int minDigit(String x) { + for (int i = 0 ; i < x.length() ; i++) { + int digit = x.charAt(i) - '0'; + if (digit != 0) { + return changeOccurrence(x, digit, 0); + } + } + return Integer.parseInt(x); + } + + private int changeOccurrence(String x, int digit, int to) { + final String result = x.replace((char) (digit + '0'), (char) (to + '0')); + return Integer.parseInt(result); + } +} diff --git a/src/MaximumEnemyFortsThatCanBeCaptured.java b/src/MaximumEnemyFortsThatCanBeCaptured.java new file mode 100644 index 0000000..f6dcccd --- /dev/null +++ b/src/MaximumEnemyFortsThatCanBeCaptured.java @@ -0,0 +1,25 @@ +// https://leetcode.com/problems/maximum-enemy-forts-that-can-be-captured +// T: O(N) +// S: O(1) + +public class MaximumEnemyFortsThatCanBeCaptured { + public int captureForts(int[] forts) { + int last1 = Integer.MAX_VALUE, last_1 = Integer.MAX_VALUE, maxCapture = 0, previous = 0; + for (int index = 0 ; index < forts.length ; index++) { + if (forts[index] == 1) { + if (last_1 != Integer.MAX_VALUE && previous == -1) { + maxCapture = Math.max(maxCapture, index - last_1 - 1); + } + previous = 1; + last1 = index; + } else if (forts[index] == -1) { + if (last1 != Integer.MAX_VALUE && previous == 1) { + maxCapture = Math.max(maxCapture, index - last1 - 1); + } + previous = -1; + last_1 = index; + } + } + return maxCapture; + } +} diff --git a/src/MaximumHeightOfATriangle.java b/src/MaximumHeightOfATriangle.java new file mode 100644 index 0000000..b84ff88 --- /dev/null +++ b/src/MaximumHeightOfATriangle.java @@ -0,0 +1,31 @@ +// https://leetcode.com/problems/maximum-height-of-a-triangle +// T: O(log(n) + log(m)) +// S: O(1) + +public class MaximumHeightOfATriangle { + public static int maxHeightOfTriangle(int red, int blue) { + return Math.max(possibleRows(red, blue), possibleRows(blue, red)); + } + + private static int possibleRows(int oddRowBalls, int evenRowBalls) { + final int evenRows = possibleEvenRows(evenRowBalls); + final int oddRows = possibleOddRows(oddRowBalls); + return Math.min(oddRows, evenRows + 1) + Math.min(oddRows, evenRows); + } + + private static int possibleOddRows(int balls) { + return (int) Math.sqrt(balls); + } + + /* + k - (-1 + sqrt(1 + 4b)) / 2 = 0 + k = (-1 + sqrt(1 + 4b)) / 2 + */ + private static int possibleEvenRows(int balls) { + return (int) ((Math.sqrt(1 + 4 * balls) - 1) / 2); + } + + public static void main(String[] args) { + System.out.println(maxHeightOfTriangle(10, 1)); + } +} diff --git a/src/MaximumLengthOfRepeatedSubArray.java b/src/MaximumLengthOfRepeatedSubArray.java new file mode 100644 index 0000000..ffc00c5 --- /dev/null +++ b/src/MaximumLengthOfRepeatedSubArray.java @@ -0,0 +1,21 @@ +// longest common subarray / longest common substring length +// https://leetcode.com/problems/maximum-length-of-repeated-subarray +// T: O(|nums1| * |nums2|) +// S: O(min(|nums1|, |nums2|)) + +public class MaximumLengthOfRepeatedSubArray { + public int findLength(int[] nums1, int[] nums2) { + final int rows = nums1.length + 1, columns = nums2.length + 1; + final int[][] memory = new int[2][columns]; + int maxValue = 0; + + for (int row = 1, i = 1 ; row < rows ; row++, i ^= 1) { + for (int column = 1 ; column < columns ; column++) { + memory[i][column] = nums1[row - 1] == nums2[column - 1] ? 1 + memory[i ^ 1][column - 1] : 0; + maxValue = Math.max(maxValue, memory[i][column]); + } + } + + return maxValue; + } +} diff --git a/src/MaximumLengthSubstringWithTwoOccurrences.java b/src/MaximumLengthSubstringWithTwoOccurrences.java new file mode 100644 index 0000000..37b0abe --- /dev/null +++ b/src/MaximumLengthSubstringWithTwoOccurrences.java @@ -0,0 +1,26 @@ +// https://leetcode.com/problems/maximum-length-substring-with-two-occurrences +// T: O(N) +// S: O(1) + +import java.util.HashMap; +import java.util.Map; + +public class MaximumLengthSubstringWithTwoOccurrences { + public int maximumLengthSubstring(String s) { + final Map frequencies = new HashMap<>(); + int maxLength = 1; + + for (int left = 0, right = 0 ; left < s.length() && right < s.length() ; ) { + if (frequencies.getOrDefault(s.charAt(right), 0) == 2) { + frequencies.put(s.charAt(left), frequencies.get(s.charAt(left)) - 1); + left++; + } else { + frequencies.put(s.charAt(right), frequencies.getOrDefault(s.charAt(right), 0) + 1); + right++; + maxLength = Math.max(maxLength, right - left); + } + } + + return maxLength; + } +} diff --git a/src/MaximumNestingDepthOfTheParentheses.java b/src/MaximumNestingDepthOfTheParentheses.java new file mode 100644 index 0000000..98178ac --- /dev/null +++ b/src/MaximumNestingDepthOfTheParentheses.java @@ -0,0 +1,11 @@ +public class MaximumNestingDepthOfTheParentheses { + public int maxDepth(String s) { + int nestingDepth = 0, maximumNestingDepth = 0; + for (int index = 0 ; index < s.length() ; index++) { + if (s.charAt(index) == '(') nestingDepth++; + else if (s.charAt(index) == ')') nestingDepth--; + maximumNestingDepth = Math.max(nestingDepth, maximumNestingDepth); + } + return maximumNestingDepth; + } +} diff --git a/src/MaximumNumberOfBalloons.java b/src/MaximumNumberOfBalloons.java new file mode 100644 index 0000000..3aab7db --- /dev/null +++ b/src/MaximumNumberOfBalloons.java @@ -0,0 +1,32 @@ +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +public class MaximumNumberOfBalloons { + private static final Set BALLOON_CHARACTERS = Set.of('b', 'a', 'l', 'o', 'n'); + private static final Set BALLOON_DOUBLE_LETTERS = Set.of('l', 'o'); + + public int maxNumberOfBalloons(String text) { + Map frequencies = getCharacterFrequencies(text); + int result = Integer.MAX_VALUE; + for (char character : BALLOON_CHARACTERS) { + result = Math.min(result, frequencies.getOrDefault(character, 0)); + } + return result; + } + + private Map getCharacterFrequencies(String string) { + final Map frequencies = new HashMap<>(); + char character; + for (int i = 0 ; i < string.length() ; i++) { + character = string.charAt(i); + if (BALLOON_CHARACTERS.contains(character)) { + frequencies.put(character, frequencies.getOrDefault(character, 0) + 1); + } + } + for (char letter : BALLOON_DOUBLE_LETTERS) { + frequencies.put(letter, frequencies.getOrDefault(letter, 0) / 2); + } + return frequencies; + } +} diff --git a/src/MaximumNumberOfBallsInABox.java b/src/MaximumNumberOfBallsInABox.java new file mode 100644 index 0000000..abb1bd3 --- /dev/null +++ b/src/MaximumNumberOfBallsInABox.java @@ -0,0 +1,22 @@ +import java.util.HashMap; +import java.util.Map; + +public class MaximumNumberOfBallsInABox { + public int countBalls(int lowLimit, int highLimit) { + final Map boxes = new HashMap<>(); + for (int ball = lowLimit ; ball <= highLimit ; ball++) { + int boxNumber = sumOfDigits(ball); + boxes.put(boxNumber, boxes.getOrDefault(boxNumber, 0) + 1); + } + return boxes.values().stream().max(Integer::compareTo).get(); + } + + private int sumOfDigits(int n) { + int sum = 0; + while (n > 0) { + sum += n % 10; + n /= 10; + } + return sum; + } +} diff --git a/src/MaximumNumberOfOperationsWithTheSameScoreI.java b/src/MaximumNumberOfOperationsWithTheSameScoreI.java new file mode 100644 index 0000000..7314091 --- /dev/null +++ b/src/MaximumNumberOfOperationsWithTheSameScoreI.java @@ -0,0 +1,17 @@ +// https://leetcode.com/problems/maximum-number-of-operations-with-the-same-score-i +// T: O(N) +// S: O(1) + +public class MaximumNumberOfOperationsWithTheSameScoreI { + public int maxOperations(int[] array) { + int maxOperations = 1; + for (int i = 2 ; i < array.length - 1 ; i += 2) { + if ((array[i] + array[i + 1]) == (array[0] + array[1])) { + maxOperations++; + } else { + break; + } + } + return maxOperations; + } +} diff --git a/src/MaximumNumberOfPairsInArray.java b/src/MaximumNumberOfPairsInArray.java new file mode 100644 index 0000000..aa96fe1 --- /dev/null +++ b/src/MaximumNumberOfPairsInArray.java @@ -0,0 +1,30 @@ +// https://leetcode.com/problems/maximum-number-of-pairs-in-array +// T: O(N) +// S: O(N) + +import java.util.HashMap; +import java.util.Map; + +public class MaximumNumberOfPairsInArray { + public int[] numberOfPairs(int[] nums) { + final Map digitFrequencies = getFrequencies(nums); + final int numberOfPairs = getNumberOfPairs(digitFrequencies); + return new int[] { numberOfPairs, nums.length - 2 * numberOfPairs }; + } + + private int getNumberOfPairs(Map frequencies) { + int result = 0; + for (int frequency : frequencies.values()) { + result += frequency / 2; + } + return result; + } + + private Map getFrequencies(int[] array) { + final Map result = new HashMap<>(); + for (int element : array) { + result.put(element, result.getOrDefault(element, 0) + 1); + } + return result; + } +} diff --git a/src/MaximumNumberOfWordsFoundInSentences.java b/src/MaximumNumberOfWordsFoundInSentences.java new file mode 100644 index 0000000..20af616 --- /dev/null +++ b/src/MaximumNumberOfWordsFoundInSentences.java @@ -0,0 +1,22 @@ +// https://leetcode.com/problems/maximum-number-of-words-found-in-sentences +// T: O(s * |s|) +// S: O(1) +// s = no. of sentences and |s| length of sentence + +public class MaximumNumberOfWordsFoundInSentences { + public int mostWordsFound(String[] sentences) { + int maxWords = 0; + for (String sentence : sentences) { + maxWords = Math.max(maxWords, totalWords(sentence)); + } + return maxWords; + } + + private int totalWords(String string) { + int count = 0; + for (int i = 0 ; i < string.length() ; i++) { + if (string.charAt(i) == ' ') count++; + } + return count + 1; + } +} diff --git a/src/MaximumNumberOfWordsYouCanType.java b/src/MaximumNumberOfWordsYouCanType.java new file mode 100644 index 0000000..5beef69 --- /dev/null +++ b/src/MaximumNumberOfWordsYouCanType.java @@ -0,0 +1,31 @@ +// https://leetcode.com/problems/maximum-number-of-words-you-can-type +// T: O(|brokenLetters| + |text|) +// S: O(1) + +import java.util.HashSet; +import java.util.Set; + +public class MaximumNumberOfWordsYouCanType { + public int canBeTypedWords(String text, String brokenLetters) { + final Set brokenCharacters = getCharacters(brokenLetters); + int words = 0; + boolean canType = true; + for (int i = 0 ; i < text.length() ; i++) { + if (text.charAt(i) == ' ') { + if (canType) words++; + canType = true; + } else if (brokenCharacters.contains(text.charAt(i))) { + canType = false; + } + } + return words + (canType ? 1 : 0); + } + + private Set getCharacters(String s) { + final Set set = new HashSet<>(); + for (int i = 0 ; i < s.length() ; i++) { + set.add(s.charAt(i)); + } + return set; + } +} diff --git a/src/MaximumOddBinaryNumber.java b/src/MaximumOddBinaryNumber.java new file mode 100644 index 0000000..1ba7415 --- /dev/null +++ b/src/MaximumOddBinaryNumber.java @@ -0,0 +1,20 @@ +// https://leetcode.com/problems/maximum-odd-binary-number +// T: O(S) +// S: O(1) + +public class MaximumOddBinaryNumber { + public String maximumOddBinaryNumber(String s) { + final int numberOfOnes = getNumberOfOnes(s); + return "1".repeat(numberOfOnes - 1) + "0".repeat(s.length() - numberOfOnes) + "1"; + } + + private static int getNumberOfOnes(String s) { + int count = 0; + for (int i = 0 ; i < s.length() ; i++) { + if (s.charAt(i) == '1') { + count++; + } + } + return count; + } +} diff --git a/src/MaximumPopulationYear.java b/src/MaximumPopulationYear.java new file mode 100644 index 0000000..977d1b0 --- /dev/null +++ b/src/MaximumPopulationYear.java @@ -0,0 +1,26 @@ +// https://leetcode.com/problems/maximum-population-year +// T: O(N) +// S: O(1) + +public class MaximumPopulationYear { + public int maximumPopulation(int[][] logs) { + final int[] population = new int[101]; + for (int[] log : logs) { + population[log[0] - 1950]++; + population[log[1] - 1950]--; + } + return maxIndexOfRunningSum(population) + 1950; + } + + private int maxIndexOfRunningSum(int[] array) { + int maxIndex = 0; + for (int index = 1, current = array[0], maxVal = current ; index < array.length ; index++) { + current += array[index]; + if (current > maxVal) { + maxVal = current; + maxIndex = index; + } + } + return maxIndex; + } +} diff --git a/src/MaximumProductDifferenceBetweenTwoPairs.java b/src/MaximumProductDifferenceBetweenTwoPairs.java new file mode 100644 index 0000000..1637159 --- /dev/null +++ b/src/MaximumProductDifferenceBetweenTwoPairs.java @@ -0,0 +1,49 @@ +// https://leetcode.com/problems/maximum-product-difference-between-two-pairs +// T: O(N) +// S: O(1) + +public class MaximumProductDifferenceBetweenTwoPairs { + public int maxProductDifference(int[] nums) { + Pair largest = getLargestAndSecondLargest(nums); + Pair smallest = getSmallestAndSecondSmallest(nums); + return largest.a * largest.b - smallest.a * smallest.b; + } + + private Pair getLargestAndSecondLargest(int[] array) { + int largest = Integer.MIN_VALUE, secondLargest = Integer.MIN_VALUE; + for (int element : array) { + if (element > largest) { + int temp = largest; + largest = element; + secondLargest = temp; + } else if (element > secondLargest) { + secondLargest= element; + } + } + return new Pair(largest, secondLargest); + } + + private Pair getSmallestAndSecondSmallest(int[] array) { + int smallest = Integer.MAX_VALUE, secondSmallest = Integer.MAX_VALUE; + for (int element : array) { + if (element < smallest) { + int temp = smallest; + smallest = element; + secondSmallest = temp; + } else if (element < secondSmallest) { + secondSmallest = element; + } + } + return new Pair(smallest, secondSmallest); + } + + private static final class Pair { + private final int a; + private final int b; + + private Pair(int a, int b) { + this.a = a; + this.b = b; + } + } +} diff --git a/src/MaximumProductOfThreeNumbers.java b/src/MaximumProductOfThreeNumbers.java new file mode 100644 index 0000000..8ff75b8 --- /dev/null +++ b/src/MaximumProductOfThreeNumbers.java @@ -0,0 +1,28 @@ +public class MaximumProductOfThreeNumbers { + public int maximumProduct(int[] numbers) { + int positive1 = Integer.MIN_VALUE, positive2 = Integer.MIN_VALUE, positive3 = Integer.MIN_VALUE, + negative1 = Integer.MAX_VALUE, + negative2 = Integer.MAX_VALUE; + + for (int number : numbers) { + if (number > positive1) { + positive3 = positive2; + positive2 = positive1; + positive1= number; + } else if (number > positive2) { + positive3 = positive2; + positive2 = number; + } else if (number> positive3) { + positive3 = number; + } + if (number < negative2) { + negative1 = negative2; + negative2 = number; + } else if (number < negative1) { + negative1 = number; + } + } + + return Math.max(positive1 * positive2 * positive3, negative1 * negative2 * positive1); + } +} diff --git a/src/MaximumProductOfTwoElementsInArray.java b/src/MaximumProductOfTwoElementsInArray.java new file mode 100644 index 0000000..01c15a8 --- /dev/null +++ b/src/MaximumProductOfTwoElementsInArray.java @@ -0,0 +1,14 @@ +public class MaximumProductOfTwoElementsInArray { + public int maxProduct(int[] array) { + int max = array[0], secondMax = Integer.MIN_VALUE; + for (int index = 1 ; index < array.length ; index++) { + if (array[index] > max) { + secondMax = max; + max = array[index]; + } else if (array[index] > secondMax) { + secondMax = array[index]; + } + } + return (max - 1) * (secondMax - 1) ; + } +} diff --git a/src/MaximumProductSubarray.java b/src/MaximumProductSubarray.java new file mode 100644 index 0000000..2eb334d --- /dev/null +++ b/src/MaximumProductSubarray.java @@ -0,0 +1,25 @@ +// https://leetcode.com/problems/maximum-product-subarray +// T: O(N) +// S: O(1) + +public class MaximumProductSubarray { + public static int maxProduct(int[] nums) { + int max = nums[0], min = nums[0], maxSoFar = max, temp; + for (int i = 1 ; i < nums.length ; i++) { + int number = nums[i]; + temp = max(max * number, min * number, number); + min = min(max * number, min * number, number); + max = temp; + maxSoFar = Math.max(maxSoFar, max); + } + return maxSoFar; + } + + private static int max(int a, int b, int c) { + return Math.max(a, Math.max(b, c)); + } + + private static int min(int a, int b, int c) { + return Math.min(a, Math.min(b, c)); + } +} diff --git a/src/MaximumRepeatingSubString.java b/src/MaximumRepeatingSubString.java new file mode 100644 index 0000000..71a7592 --- /dev/null +++ b/src/MaximumRepeatingSubString.java @@ -0,0 +1,24 @@ +public class MaximumRepeatingSubString { + public int maxRepeating(String sequence, String word) { + int result = 0, index = 0; + while (index < sequence.length()) { + int matchIndex = sequence.indexOf(word, index); + if (matchIndex == -1) break; + int k = 0; + for (int i = matchIndex + word.length() ; i < sequence.length() ; i += word.length(), k++) { + if (!areEqual(sequence, word, i)) break; + } + result = Math.max(result, 1 + k); + index = matchIndex + 1; + } + return result; + } + + private boolean areEqual(String text, String pattern, int startIndex) { + if (pattern.length() > text.length() - startIndex) return false; + for (int i = startIndex ; i < text.length() && i - startIndex < pattern.length() ; i++) { + if (text.charAt(i) != pattern.charAt(i - startIndex)) return false; + } + return true; + } +} diff --git a/src/MaximumScoreAfterSplittingAString.java b/src/MaximumScoreAfterSplittingAString.java new file mode 100644 index 0000000..86bc4a1 --- /dev/null +++ b/src/MaximumScoreAfterSplittingAString.java @@ -0,0 +1,20 @@ +public class MaximumScoreAfterSplittingAString { + public int maxScore(String s) { + final int ones = getFrequency(s, '1'); + int score = 0; + for (int index = 0, left = 0, right = ones ; index < s.length() - 1 ; index++) { + left += s.charAt(index) == '0' ? 1 : 0; + right -= s.charAt(index) == '0' ? 0 : 1; + score = Math.max(score, left + right); + } + return score; + } + + private int getFrequency(String s, char character) { + int frequency = 0; + for (int index = 0 ; index < s.length() ; index++) { + if (s.charAt(index) == character) frequency++; + } + return frequency; + } +} diff --git a/src/MaximumStrongPairXORI.java b/src/MaximumStrongPairXORI.java new file mode 100644 index 0000000..d35349e --- /dev/null +++ b/src/MaximumStrongPairXORI.java @@ -0,0 +1,21 @@ +// https://leetcode.com/problems/maximum-strong-pair-xor-i +// T: O(N^2) +// S: O(1) + +import java.util.Arrays; + +public class MaximumStrongPairXORI { + public int maximumStrongPairXor(int[] array) { + int result = 0; + + for (int i = 0 ; i < array.length ; i++) { + for (int j = i ; j < array.length ; j++) { + if (Math.abs(array[i] - array[j]) <= Math.min(array[i], array[j])) { + result = Math.max(result, array[i] ^ array[j]); + } + } + } + + return result; + } +} diff --git a/src/MaximumSumWithExactlyKElements.java b/src/MaximumSumWithExactlyKElements.java new file mode 100644 index 0000000..c31662d --- /dev/null +++ b/src/MaximumSumWithExactlyKElements.java @@ -0,0 +1,16 @@ +// https://leetcode.com/problems/maximum-sum-with-exactly-k-elements +// T: O(n) +// S: O(1) + +import java.util.Arrays; + +public class MaximumSumWithExactlyKElements { + public int maximizeSum(int[] nums, int k) { + final int maxElement = Arrays.stream(nums).max().getAsInt(); + return maxElement * k + summation(k - 1); + } + + private int summation(int x) { + return (x * (x + 1)) / 2; + } +} diff --git a/src/MaximumUnitsOnATruck.java b/src/MaximumUnitsOnATruck.java new file mode 100644 index 0000000..b53dd78 --- /dev/null +++ b/src/MaximumUnitsOnATruck.java @@ -0,0 +1,43 @@ +import java.util.ArrayList; +import java.util.List; + +public class MaximumUnitsOnATruck { + public int maximumUnits(int[][] boxTypes, int truckSize) { + final List boxes = getBoxTypesFrom(boxTypes); + boxes.sort(BoxType::compareTo); + int units = 0; + for (BoxType box : boxes) { + if (box.number <= truckSize) { + units += box.units * box.number; + truckSize -= box.number; + } else { + units += box.units * truckSize; + break; + } + } + return units; + } + + private List getBoxTypesFrom(int[][] boxes) { + final List boxTypes = new ArrayList<>(); + for (int[] box : boxes) { + boxTypes.add(new BoxType(box[0], box[1])); + } + return boxTypes; + } + + private static final class BoxType implements Comparable { + private final int number; + private final int units; + + private BoxType(int number, int units) { + this.number = number; + this.units = units; + } + + @Override + public int compareTo(BoxType o) { + return Integer.compare(o.units, this.units); + } + } +} diff --git a/src/MaximumValueOfAStringInAnArray.java b/src/MaximumValueOfAStringInAnArray.java new file mode 100644 index 0000000..a0d352f --- /dev/null +++ b/src/MaximumValueOfAStringInAnArray.java @@ -0,0 +1,21 @@ +// https://leetcode.com/problems/maximum-value-of-a-string-in-an-array +// T: O(|strings| * |strings[i]|) +// S: O(1) + +public class MaximumValueOfAStringInAnArray { + public int maximumValue(String[] strings) { + int max = -1; + for (String string : strings) { + max = Math.max(max, value(string)); + } + return max; + } + + private int value(String string) { + try { + return Integer.parseInt(string); + } catch (Exception e) { + return string.length(); + } + } +} diff --git a/src/MaximumValueOfAnOrderedTripletI.java b/src/MaximumValueOfAnOrderedTripletI.java new file mode 100644 index 0000000..9a6e10c --- /dev/null +++ b/src/MaximumValueOfAnOrderedTripletI.java @@ -0,0 +1,18 @@ +// https://leetcode.com/problems/maximum-value-of-an-ordered-triplet-i +// T: O(N^3) +// S: O(1) + +public class MaximumValueOfAnOrderedTripletI { + public long maximumTripletValue(int[] array) { + long result = 0; + for (int i = 0 ; i < array.length ; i++) { + for (int j = i + 1 ; j < array.length ; j++) { + for (int k = j + 1 ; k < array.length ; k++) { + result = Math.max(result, (long) (array[i] - array[j]) * array[k]); + } + } + } + + return result; + } +} diff --git a/src/MeanOfArrayAfterRemovingSomeElements.java b/src/MeanOfArrayAfterRemovingSomeElements.java new file mode 100644 index 0000000..3277a7f --- /dev/null +++ b/src/MeanOfArrayAfterRemovingSomeElements.java @@ -0,0 +1,18 @@ +// https://leetcode.com/problems/mean-of-array-after-removing-some-elements +// T: O(nlog(n)) +// S: O(1) + +import java.util.Arrays; + +public class MeanOfArrayAfterRemovingSomeElements { + public double trimMean(int[] arr) { + Arrays.sort(arr); + int sum = 0; + final int startIndex = arr.length / 20; + final int endIndex = arr.length - startIndex; + for (int index = startIndex ; index < endIndex; index++) { + sum += arr[index]; + } + return (double) sum / (endIndex - startIndex); + } +} diff --git a/src/MedianOfTwoSortedArrays.java b/src/MedianOfTwoSortedArrays.java new file mode 100644 index 0000000..0622582 --- /dev/null +++ b/src/MedianOfTwoSortedArrays.java @@ -0,0 +1,36 @@ +// https://leetcode.com/problems/median-of-two-sorted-arrays +// T: O(m + n) +// S: O(m + n) + +public class MedianOfTwoSortedArrays { + static public double findMedianSortedArrays(int[] nums1, int[] nums2) { + final int[] array = merge(nums1, nums2); + if (array.length % 2 == 1) { + return array[array.length / 2]; + } + return ((double) array[array.length / 2 - 1] + array[array.length / 2]) / 2; + } + + private static int[] merge(int[] array1, int[] array2) { + final int[] result = new int[array1.length + array2.length]; + int i = 0, j = 0, k = 0; + + while (i < array1.length && j < array2.length) { + if (array1[i] <= array2[j]) { + result[k++] = array1[i++]; + } else { + result[k++] = array2[j++]; + } + } + + while (i < array1.length) { + result[k++] = array1[i++]; + } + + while (j < array2.length) { + result[k++] = array2[j++]; + } + + return result; + } +} diff --git a/src/MeetingRooms.java b/src/MeetingRooms.java new file mode 100644 index 0000000..a608cb2 --- /dev/null +++ b/src/MeetingRooms.java @@ -0,0 +1,18 @@ +// https://leetcode.com/problems/meeting-rooms +// T: O(N logN) +// S: O(logN) + +import java.util.Arrays; +import java.util.Comparator; + +public class MeetingRooms { + public boolean canAttendMeetings(int[][] intervals) { + Arrays.sort(intervals, Comparator.comparingInt(a -> a[0])); + for (int i = 0 ; i < intervals.length - 1 ; i++) { + if (intervals[i][1] > intervals[i + 1][0]) { + return false; + } + } + return true; + } +} diff --git a/src/Merge2SortedLists.java b/src/Merge2SortedLists.java index 2c47ced..577a5ac 100644 --- a/src/Merge2SortedLists.java +++ b/src/Merge2SortedLists.java @@ -1,4 +1,4 @@ -// https://leetcode.com/problems/merge-two-sorted-lists/ +// https://leetcode.com/problems/merge-two-sorted-lists public class Merge2SortedLists { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { @@ -19,12 +19,4 @@ public ListNode mergeTwoLists(ListNode l1, ListNode l2) { previous.next = l1 == null ? l2 : l1; return result.next; } - - public static class ListNode { - int val; - ListNode next; - ListNode() {} - ListNode(int val) { this.val = val; } - ListNode(int val, ListNode next) { this.val = val; this.next = next; } - } } diff --git a/src/MergeIntervals.java b/src/MergeIntervals.java new file mode 100644 index 0000000..732cb5b --- /dev/null +++ b/src/MergeIntervals.java @@ -0,0 +1,35 @@ +// https://leetcode.com/problems/merge-intervals/submissions +// T: O(n log(n)) +// S: O(n) + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; + +public class MergeIntervals { + public int[][] merge(int[][] intervals) { + Arrays.sort(intervals, Comparator.comparingInt(interval -> interval[0])); + final List mergedIntervals = new ArrayList<>(); + int start = intervals[0][0], stop = intervals[0][1]; + for (int i = 1 ; i < intervals.length ; i++) { + if (intervals[i][0] <= stop) stop = Math.max(stop, intervals[i][1]); + else { + mergedIntervals.add(new int[] {start, stop}); + start = intervals[i][0]; + stop = intervals[i][1]; + } + } + mergedIntervals.add(new int[] {start, stop}); + return toArray(mergedIntervals); + } + + private int[][] toArray(List list) { + int[][] result = new int[list.size()][2]; + int i = 0; + for (int[] interval : list) { + result[i++] = interval; + } + return result; + } +} diff --git a/src/MergeSimilarItems.java b/src/MergeSimilarItems.java new file mode 100644 index 0000000..d899e34 --- /dev/null +++ b/src/MergeSimilarItems.java @@ -0,0 +1,42 @@ +// https://leetcode.com/problems/merge-similar-items +// T: O(Nlog(N)) +// S: O(N) + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class MergeSimilarItems { + public List> mergeSimilarItems(int[][] items1, int[][] items2) { + final Map valueToWeight = getValueToWeightMapping(items1); + for (int[] row : items2) { + if (valueToWeight.containsKey(row[0])) { + valueToWeight.put(row[0], valueToWeight.get(row[0]) + row[1]); + } else { + valueToWeight.put(row[0], row[1]); + } + } + + final List> list = toList(valueToWeight); + list.sort(Comparator.comparingInt(a -> a.get(0))); + return list; + } + + private List> toList(Map mapping) { + final List> result = new ArrayList<>(); + for (Map.Entry entry : mapping.entrySet()) { + result.add(List.of(entry.getKey(), entry.getValue())); + } + return result; + } + + private Map getValueToWeightMapping(int[][] array) { + final Map result = new HashMap<>(); + for (int[] row : array) { + result.put(row[0], row[1]); + } + return result; + } +} diff --git a/src/MergeStringsAlternately.java b/src/MergeStringsAlternately.java new file mode 100644 index 0000000..c421137 --- /dev/null +++ b/src/MergeStringsAlternately.java @@ -0,0 +1,17 @@ +public class MergeStringsAlternately { + public String mergeAlternately(String word1, String word2) { + final StringBuilder result = new StringBuilder(); + final String[] words = {word1, word2}; + int i = 0, maxLen = Math.max(word1.length(), word2.length()); + for (int[] indexes = {0, 0} ; indexes[0] < maxLen || indexes[1] < maxLen ; i ^= 1) { + result.append(get(words[i], indexes[i])); + indexes[i]++; + } + return result.toString(); + } + + private String get(String s, int index) { + if (index < s.length()) return s.charAt(index) + ""; + return ""; + } +} diff --git a/src/MergeTwo2DArraysBySummingValues.java b/src/MergeTwo2DArraysBySummingValues.java new file mode 100644 index 0000000..eef8c6d --- /dev/null +++ b/src/MergeTwo2DArraysBySummingValues.java @@ -0,0 +1,43 @@ +// https://leetcode.com/problems/merge-two-2d-arrays-by-summing-values +// T: O(N + M) +// S: O(N + M) + +import java.util.ArrayList; +import java.util.List; + +public class MergeTwo2DArraysBySummingValues { + public int[][] mergeArrays(int[][] array1, int[][] array2) { + final List result = new ArrayList<>(); + int i = 0, j = 0; + while (i < array1.length && j < array2.length) { + if (array1[i][0] == array2[j][0]) { + result.add(new int[] {array1[i][0], array1[i][1] + array2[j][1]}); + i++; + j++; + } else if (array1[i][0] < array2[j][0]) { + result.add(array1[i++]); + } else { + result.add(array2[j++]); + } + } + + while (i < array1.length) { + result.add(array1[i++]); + } + + while (j < array2.length) { + result.add(array2[j++]); + } + + return toArray(result); + } + + private int[][] toArray(List list) { + final int[][] array = new int[list.size()][2]; + int k = 0; + for (int[] slice : list) { + array[k++] = slice; + } + return array; + } +} diff --git a/src/MergeTwoBinaryTrees.java b/src/MergeTwoBinaryTrees.java new file mode 100644 index 0000000..8e26b21 --- /dev/null +++ b/src/MergeTwoBinaryTrees.java @@ -0,0 +1,25 @@ +public class MergeTwoBinaryTrees { + public TreeNode mergeTrees(TreeNode root1, TreeNode root2) { + if (root1 == null) return root2; + if (root2 == null) return root1; + root1.val += root2.val; + root1.left = mergeTrees(root1.left, root2.left); + root1.right = mergeTrees(root1.right, root2.right); + return root1; + } + + private void mergeTrees(TreeNode result, TreeNode root1, TreeNode root2) { + if (root1 == null && root2 == null) return; + if (root1 == null) result.val = root2.val; + else if (root2 == null) result.val = root1.val; + else result.val = root1.val + root2.val; + if ((root1 != null && root1.left != null) || (root2 != null && root2.left != null)) { + result.left = new TreeNode(); + mergeTrees(result.left, root1 == null ? null : root1.left, root2 == null ? null : root2.left); + } + if ((root1 != null && root1.right != null) || (root2 != null && root2.right != null)) { + result.right = new TreeNode(); + mergeTrees(result.right, root1 == null ? null : root1.right, root2 == null ? null : root2.right); + } + } +} diff --git a/src/MiddleOfTheLinkedList.java b/src/MiddleOfTheLinkedList.java new file mode 100644 index 0000000..afc6b30 --- /dev/null +++ b/src/MiddleOfTheLinkedList.java @@ -0,0 +1,10 @@ +public class MiddleOfTheLinkedList { + public ListNode middleNode(ListNode head) { + ListNode slow = head, fast = head; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + return slow; + } +} diff --git a/src/MinCostClimbingStairs.java b/src/MinCostClimbingStairs.java new file mode 100644 index 0000000..b1f6137 --- /dev/null +++ b/src/MinCostClimbingStairs.java @@ -0,0 +1,15 @@ +// https://leetcode.com/problems/min-cost-climbing-stairs +// T: O(n) +// S: O(1) + +public class MinCostClimbingStairs { + public int minCostClimbingStairs(int[] cost) { + int currentCost = cost[1], previousCost = cost[0], temp; + for (int index = 2 ; index < cost.length ; index++) { + temp = currentCost; + currentCost = Math.min(currentCost, previousCost) + cost[index]; + previousCost = temp; + } + return Math.min(previousCost, currentCost); + } +} diff --git a/src/MinCostToConnectAllPoints.java b/src/MinCostToConnectAllPoints.java new file mode 100644 index 0000000..443bb1b --- /dev/null +++ b/src/MinCostToConnectAllPoints.java @@ -0,0 +1,82 @@ +// https://leetcode.com/problems/min-cost-to-connect-all-points +// P = |points|, E = P^2 +// T: O(E logE + E al(P)) al = inverse Ackerman function +// S: O(P + E) = S(E) + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +public class MinCostToConnectAllPoints { + private static class DisjointSet { + private final int[] roots, rank; + + DisjointSet(int size) { + roots = new int[size]; + rank = new int[size]; + for (int i = 0 ; i < size ; i++) { + roots[i] = i; + rank[i] = i; + } + } + + public int find(int num) { + if (num == roots[num]) { + return num; + } + return roots[num] = find(roots[num]); + } + + public boolean areConnected(int x, int y) { + return find(x) == find(y); + } + + public void union(int x, int y) { + final int rootX = find(x), rootY = find(y); + if (rootX == rootY) { + return; + } + if (rank[rootX] > rank[rootY]) { + roots[rootY] = rootX; + } else if (rank[rootX] < rank[rootY]) { + roots[rootX] = rootY; + } else { + roots[rootY] = rootX; + rank[rootX]++; + } + } + } + + // Kruskal's algorithm + public int minCostConnectPoints(int[][] points) { + final List edges = createEdges(points); + final DisjointSet disjointSet = new DisjointSet(points.length); + edges.sort(Comparator.comparingInt(a -> a[2])); + + int minCost = 0; + + for (int[] edge : edges) { + final int from = edge[0], to = edge[1], weight = edge[2]; + if (!disjointSet.areConnected(from, to)) { + disjointSet.union(from, to); + minCost += weight; + } + } + + return minCost; + } + + private static List createEdges(int[][] points) { + final List edges = new ArrayList<>(); + for (int i = 0 ; i < points.length ; i++) { + for (int j = i + 1 ; j < points.length ; j++) { + edges.add(new int[] { i, j, manhattanDistance(points[i], points[j]) }); + } + } + return edges; + } + + private static int manhattanDistance(int[] p1, int[] p2) { + return Math.abs(p1[0] - p2[0]) + Math.abs(p1[1] - p2[1]); + } +} diff --git a/src/MinMaxGame.java b/src/MinMaxGame.java new file mode 100644 index 0000000..526d7c1 --- /dev/null +++ b/src/MinMaxGame.java @@ -0,0 +1,14 @@ +// https://leetcode.com/problems/min-max-game +// T: O(N) +// S: O(1) + +public class MinMaxGame { + public int minMaxGame(int[] array) { + for (int len = array.length / 2 ; len > 1 ; len /= 2) { + for (int i = 0 ; i < len ; i++) { + array[i] = i % 2 == 0 ? Math.min(array[2 * i], array[2 * i + 1]) : Math.max(array[2 * i], array[2 * i + 1]); + } + } + return array[0]; + } +} diff --git a/src/MinimizeStringLength.java b/src/MinimizeStringLength.java new file mode 100644 index 0000000..e88b12b --- /dev/null +++ b/src/MinimizeStringLength.java @@ -0,0 +1,16 @@ +// https://leetcode.com/problems/minimize-string-length +// T: O(N) +// S: O(1) + +import java.util.HashSet; +import java.util.Set; + +public class MinimizeStringLength { + public int minimizedStringLength(String s) { + final Set letters = new HashSet<>(); + for (int i = 0 ; i < s.length() ; i++) { + letters.add(s.charAt(i)); + } + return letters.size(); + } +} diff --git a/src/MinimumAbsoluteDifference.java b/src/MinimumAbsoluteDifference.java new file mode 100644 index 0000000..4c871d5 --- /dev/null +++ b/src/MinimumAbsoluteDifference.java @@ -0,0 +1,21 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class MinimumAbsoluteDifference { + public List> minimumAbsDifference(int[] array) { + List> result = new ArrayList<>(); + Arrays.sort(array); + long minAbsDifference = Long.MAX_VALUE; + for (int i = 0 ; i < array.length - 1 ; i++) { + if (array[i + 1] - array[i] < minAbsDifference) { + minAbsDifference = array[i + 1] - array[i]; + result = new ArrayList<>(); + result.add(List.of(array[i], array[i + 1])); + } else if (array[i + 1] - array[i] == minAbsDifference) { + result.add(List.of(array[i], array[i + 1])); + } + } + return result; + } +} diff --git a/src/MinimumAbsoluteDifferenceInBST.java b/src/MinimumAbsoluteDifferenceInBST.java new file mode 100644 index 0000000..5f59331 --- /dev/null +++ b/src/MinimumAbsoluteDifferenceInBST.java @@ -0,0 +1,15 @@ +public class MinimumAbsoluteDifferenceInBST { + long result = Integer.MAX_VALUE; + + public int getMinimumDifference(TreeNode root) { + computeMinAbsoluteDifference(root, Integer.MIN_VALUE, Integer.MAX_VALUE); + return (int) result; + } + + public void computeMinAbsoluteDifference(TreeNode root, long left, long right) { + if (root == null) return; + result = Math.min(result, Math.min(root.val - left, right - root.val)); + computeMinAbsoluteDifference(root.left, left, root.val); + computeMinAbsoluteDifference(root.right, root.val, right); + } +} diff --git a/src/MinimumAmountOfTimeToFillCups.java b/src/MinimumAmountOfTimeToFillCups.java new file mode 100644 index 0000000..3d94c30 --- /dev/null +++ b/src/MinimumAmountOfTimeToFillCups.java @@ -0,0 +1,14 @@ +// https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups +// T: O(1) +// S: O(1) + +import java.util.Arrays; + +public class MinimumAmountOfTimeToFillCups { + public int fillCups(int[] amount) { + return Math.max( + Arrays.stream(amount).max().getAsInt(), + (Arrays.stream(amount).sum() + 1) / 2 + ); + } +} diff --git a/src/MinimumAverageOfSmallestAndLargestElements.java b/src/MinimumAverageOfSmallestAndLargestElements.java new file mode 100644 index 0000000..8c86527 --- /dev/null +++ b/src/MinimumAverageOfSmallestAndLargestElements.java @@ -0,0 +1,18 @@ +// https://leetcode.com/problems/minimum-average-of-smallest-and-largest-elements +// T: O(N log(N)) +// S: O(log(N)) + +import java.util.Arrays; + +public class MinimumAverageOfSmallestAndLargestElements { + public double minimumAverage(int[] array) { + Arrays.sort(array); + double minAverage = Double.MAX_VALUE; + + for (int i = 0 ; i < array.length / 2 ; i++) { + minAverage = Math.min(minAverage, ((double) array[i] + array[array.length - i - 1]) / 2); + } + + return minAverage; + } +} diff --git a/src/MinimumBitFlipsToConvertNumber.java b/src/MinimumBitFlipsToConvertNumber.java new file mode 100644 index 0000000..2d89594 --- /dev/null +++ b/src/MinimumBitFlipsToConvertNumber.java @@ -0,0 +1,18 @@ +// https://leetcode.com/problems/minimum-bit-flips-to-convert-number +// T: O(log(n)) +// S: O(1) + +public class MinimumBitFlipsToConvertNumber { + public int minBitFlips(int start, int goal) { + return hammingWeight(start ^ goal); + } + + private int hammingWeight(int x) { + int result = 0; + while (x > 0) { + x = x & (x - 1); + result++; + } + return result; + } +} diff --git a/src/MinimumChangesToMakeAlternatingBinaryString.java b/src/MinimumChangesToMakeAlternatingBinaryString.java new file mode 100644 index 0000000..0f87666 --- /dev/null +++ b/src/MinimumChangesToMakeAlternatingBinaryString.java @@ -0,0 +1,16 @@ +public class MinimumChangesToMakeAlternatingBinaryString { + public int minOperations(String s) { + return Math.min( + operationsToChangeIntoAlternatingString(s, '1'), + operationsToChangeIntoAlternatingString(s, '0') + ); + } + + private int operationsToChangeIntoAlternatingString(String s, char start) { + int changes = 0, current = start - '0'; + for (int index = 0 ; index < s.length() ; index++, current ^= 1) { + if (s.charAt(index) != current + '0') changes++; + } + return changes; + } +} diff --git a/src/MinimumCommonValue.java b/src/MinimumCommonValue.java new file mode 100644 index 0000000..783133c --- /dev/null +++ b/src/MinimumCommonValue.java @@ -0,0 +1,18 @@ +// https://leetcode.com/problems/minimum-common-value +// T: O(m + n) +// S: O(1) + +public class MinimumCommonValue { + public int getCommon(int[] array1, int[] array2) { + for (int i = 0, j = 0 ; i < array1.length && j < array2.length ; ) { + if (array1[i] == array2[j]) return array1[i]; + + if (array1[i] < array2[j]) { + i++; + } else { + j++; + } + } + return -1; + } +} diff --git a/src/MinimumCostOfBuyingCandiesWithDiscount.java b/src/MinimumCostOfBuyingCandiesWithDiscount.java new file mode 100644 index 0000000..61036ca --- /dev/null +++ b/src/MinimumCostOfBuyingCandiesWithDiscount.java @@ -0,0 +1,16 @@ +// https://leetcode.com/problems/minimum-cost-of-buying-candies-with-discount +// T: O(n log(n)) +// S: O(log(n)) + +import java.util.Arrays; + +public class MinimumCostOfBuyingCandiesWithDiscount { + public int minimumCost(int[] cost) { + Arrays.sort(cost); + int totalCost = 0; + for (int index = cost.length - 1 ; index >= 0 ; index -= 3) { + totalCost += cost[index] + (index - 1 >= 0 ? cost[index - 1] : 0); + } + return totalCost; + } +} diff --git a/src/MinimumCostToMoveChipsToTheSamePosition.java b/src/MinimumCostToMoveChipsToTheSamePosition.java new file mode 100644 index 0000000..45dba0e --- /dev/null +++ b/src/MinimumCostToMoveChipsToTheSamePosition.java @@ -0,0 +1,9 @@ +public class MinimumCostToMoveChipsToTheSamePosition { + public int minCostToMoveChips(int[] positions) { + int evenPositionChips = 0; + for (int position : positions) { + if (position % 2 == 0) evenPositionChips++; + } + return Math.min(evenPositionChips, positions.length - evenPositionChips); + } +} diff --git a/src/MinimumCostToReachCityWithDiscounts.java b/src/MinimumCostToReachCityWithDiscounts.java new file mode 100644 index 0000000..d4aa0cb --- /dev/null +++ b/src/MinimumCostToReachCityWithDiscounts.java @@ -0,0 +1,78 @@ +// https://leetcode.com/problems/minimum-cost-to-reach-city-with-discounts +// T: O((N * K + E) log(N * K)) +// S: O(N * K + E) + +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.PriorityQueue; +import java.util.Queue; + +public class MinimumCostToReachCityWithDiscounts { + private record Info(int vertex, int cost, int discounts) {} + + public static int minimumCost(int n, int[][] highways, int discounts) { + final Map> graph = createGraph(highways); + final int[][] minCosts = dijkstra(n, graph, discounts); + return minCost(minCosts[n -1]); + } + + // N = n, K = |discounts|, E + // T: O(N * K + E log(N * K)) = O((N * K + E) log(N * K)) + // S: O(N * K + E) + private static int[][] dijkstra(int n, Map> graph, int discount) { + final int[][] dp = initializeDp(n, discount); + final Queue queue = new PriorityQueue<>(Comparator.comparingInt(a -> a.cost)); + queue.add(new Info(0, 0, discount)); + + while (!queue.isEmpty()) { + final Info info = queue.poll(); + if (dp[info.vertex][info.discounts] <= info.cost) { + continue; + } + + dp[info.vertex][info.discounts] = info.cost; + + for (Map.Entry entry : graph.getOrDefault(info.vertex, new HashMap<>()).entrySet()) { + final int vertex = entry.getKey(), cost = entry.getValue(); + queue.add(new Info(vertex, info.cost + cost, info.discounts)); + if (info.discounts > 0) { + queue.add(new Info(vertex, info.cost + cost / 2, info.discounts - 1)); + } + } + } + + return dp; + } + + private static int[][] initializeDp(int n, int discounts) { + final int[][] dp = new int[n][discounts + 1]; + for (int[] row : dp) { + Arrays.fill(row, Integer.MAX_VALUE); + } + return dp; + } + + private static int minCost(int[] array) { + final int result = Arrays.stream(array).min().getAsInt(); + if (result == Integer.MAX_VALUE) { + return -1; + } + return result; + } + + private static Map> createGraph(int[][] edges) { + final Map> graph = new HashMap<>(); + for (int[] edge : edges) { + final int from = edge[0], to = edge[1], cost = edge[2]; + final Map fromNeighbours = graph.getOrDefault(from, new HashMap<>()); + final Map toNeighbours = graph.getOrDefault(to, new HashMap<>()); + fromNeighbours.put(to, cost); + toNeighbours.put(from, cost); + graph.putIfAbsent(from, fromNeighbours); + graph.putIfAbsent(to, toNeighbours); + } + return graph; + } +} diff --git a/src/MinimumCutsToDivideACircle.java b/src/MinimumCutsToDivideACircle.java new file mode 100644 index 0000000..82fb626 --- /dev/null +++ b/src/MinimumCutsToDivideACircle.java @@ -0,0 +1,10 @@ +// https://leetcode.com/problems/minimum-cuts-to-divide-a-circle +// T: O(1) +// S: O(1) + +public class MinimumCutsToDivideACircle { + public int numberOfCuts(int n) { + if (n == 1) return 0; + return n % 2 == 0 ? n / 2 : n; + } +} diff --git a/src/MinimumDepthOfBinaryTree.java b/src/MinimumDepthOfBinaryTree.java index fc2b722..5f83724 100644 --- a/src/MinimumDepthOfBinaryTree.java +++ b/src/MinimumDepthOfBinaryTree.java @@ -1,9 +1,4 @@ public class MinimumDepthOfBinaryTree { - private static class TreeNode { - int val; - TreeNode left; - TreeNode right; - } public static int minDepth(TreeNode root) { if (root == null) { diff --git a/src/MinimumDifferenceBetweenHighestAndLowestOfKScores.java b/src/MinimumDifferenceBetweenHighestAndLowestOfKScores.java new file mode 100644 index 0000000..b645ace --- /dev/null +++ b/src/MinimumDifferenceBetweenHighestAndLowestOfKScores.java @@ -0,0 +1,16 @@ +// https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores +// T: O(Nlog(N)) +// S: O(1) + +import java.util.Arrays; + +public class MinimumDifferenceBetweenHighestAndLowestOfKScores { + public int minimumDifference(int[] nums, int k) { + Arrays.sort(nums); + int minDifference = Integer.MAX_VALUE; + for (int i = 0 ; i < nums.length - k + 1 ; i++) { + minDifference = Math.min(minDifference, nums[i + k - 1] - nums[i]); + } + return minDifference; + } +} diff --git a/src/MinimumDistanceBetweenBSTNodes.java b/src/MinimumDistanceBetweenBSTNodes.java new file mode 100644 index 0000000..654c796 --- /dev/null +++ b/src/MinimumDistanceBetweenBSTNodes.java @@ -0,0 +1,15 @@ +public class MinimumDistanceBetweenBSTNodes { + long result = Integer.MAX_VALUE; + + public int minDiffInBST(TreeNode root) { + computeMinAbsoluteDifference(root, Integer.MIN_VALUE, Integer.MAX_VALUE); + return (int) result; + } + + public void computeMinAbsoluteDifference(TreeNode root, long left, long right) { + if (root == null) return; + result = Math.min(result, Math.min(root.val - left, right - root.val)); + computeMinAbsoluteDifference(root.left, left, root.val); + computeMinAbsoluteDifference(root.right, root.val, right); + } +} diff --git a/src/MinimumDistanceToTheTargetElement.java b/src/MinimumDistanceToTheTargetElement.java new file mode 100644 index 0000000..7d58d16 --- /dev/null +++ b/src/MinimumDistanceToTheTargetElement.java @@ -0,0 +1,34 @@ +import java.util.ArrayList; +import java.util.List; + +public class MinimumDistanceToTheTargetElement { + public int getMinDistance(int[] nums, int target, int start) { + final List indexes = getIndexes(nums, target); + final int position = search(indexes, start); + if (position >= indexes.size()) return start - indexes.get(position - 1); + if (indexes.get(position) == start) return 0; + if (position == 0) return indexes.get(position) - start; + return Math.min(indexes.get(position) - start, start - indexes.get(position - 1)); + } + + private List getIndexes(int[] array, int target){ + final List indexes = new ArrayList<>(); + for (int index = 0 ; index < array.length ; index++) { + if (array[index] == target) { + indexes.add(index); + } + } + return indexes; + } + + private int search(List array, int x) { + int left = 0, right = array.size() - 1, middle; + while (left <= right) { + middle = left + (right - left) / 2; + if (array.get(middle) == x) return middle; + else if (array.get(middle) > x) right = middle - 1; + else left = middle + 1; + } + return left; + } +} diff --git a/src/MinimumGeneticMutation.java b/src/MinimumGeneticMutation.java new file mode 100644 index 0000000..2d7c0ad --- /dev/null +++ b/src/MinimumGeneticMutation.java @@ -0,0 +1,70 @@ +// https://leetcode.com/problems/minimum-genetic-mutation +// T: O(B) +// S: O(1) + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Queue; +import java.util.Set; + +public class MinimumGeneticMutation { + private record Info(String mutation, int steps) {} + + private static final char[] GENES = new char[] {'A', 'G', 'C', 'T'}; + + // n = length of string (8), m = possible number of characters + // BFS, T: O(V + E) = O(nB + n^m * mn) S: O(n^m) + public static int minMutation(String startGene, String endGene, String[] bank) { + final Set genePool = toSet(bank); + if (!genePool.contains(endGene)) { + return -1; + } + + final Queue queue = new LinkedList<>() {{ add(new Info(startGene, 0)); }}; + final Set visited = new HashSet<>(); + + while (!queue.isEmpty()) { + final Info info = queue.poll(); + if (visited.contains(info.mutation)) { + continue; + } + visited.add(info.mutation); + + if (endGene.equals(info.mutation)) { + return info.steps; + } + + for (String neighbour : validMutations(genePool, info.mutation)) { + queue.add(new Info(neighbour, info.steps + 1)); + } + } + + return -1; + } + + // T: O(|s|), S: O(|s|) + private static List validMutations(Set genePool, String s) { + final List result = new ArrayList<>(); + for (int i = 0 ; i < s.length() ; i++) { + for (char c : GENES) { + final String mutation = s.substring(0, i) + c + s.substring(i + 1); + if (genePool.contains(mutation)) { + result.add(mutation); + } + } + } + return result; + } + + // T: O(nB) S: O(nB) + private static Set toSet(String[] bank) { + final Set set = new HashSet<>(); + Collections.addAll(set, bank); + return set; + } +} diff --git a/src/MinimumHeightTrees.java b/src/MinimumHeightTrees.java new file mode 100644 index 0000000..b244d1e --- /dev/null +++ b/src/MinimumHeightTrees.java @@ -0,0 +1,78 @@ +// https://leetcode.com/problems/minimum-height-trees +// T: O(N) +// S: O(N) + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class MinimumHeightTrees { + public List findMinHeightTrees(int n, int[][] edges) { + if (n == 0) return new ArrayList<>(); + if (n == 1) return new ArrayList<>() {{ add(0); }}; + + final Map> graph = createGraph(edges); + return minHeightTreeRoots(graph); + } + + // T: O(N), S: O(N) + private static List minHeightTreeRoots(Map> graph) { + final int[] degree = computeDegree(graph); + Set leafNodes = addLeafNodes(degree); + + while (graph.size() > 2) { + final Set newLeafNodes = new HashSet<>(); + for (int leafNode : leafNodes) { + degree[leafNode]--; + for (int neighbour : graph.get(leafNode)) { + degree[neighbour]--; + if (degree[neighbour] == 1) { + newLeafNodes.add(neighbour); + } + } + graph.remove(leafNode); + } + leafNodes = newLeafNodes; + } + + return new ArrayList<>(graph.keySet()); + } + + // T: O(N), S: O(N) + private static Set addLeafNodes(int[] degree) { + final Set leafNodes = new HashSet<>(); + for (int i = 0 ; i < degree.length ; i++) { + if (degree[i] == 1) { + leafNodes.add(i); + } + } + return leafNodes; + } + + // T: O(N), S: O(N) + private static int[] computeDegree(Map> graph) { + final int[] degree = new int[graph.size()]; + for (Map.Entry> entry : graph.entrySet()) { + degree[entry.getKey()] = entry.getValue().size(); + } + return degree; + } + + // T: O(N), S: O(N) + private static Map> createGraph(int[][] edges) { + final Map> graph = new HashMap<>(); + for (int[] edge : edges) { + final int from = edge[0], to = edge[1]; + final Set fromSet = graph.getOrDefault(from, new HashSet<>()); + final Set toSet = graph.getOrDefault(to, new HashSet<>()); + fromSet.add(to); + toSet.add(from); + graph.putIfAbsent(from, fromSet); + graph.putIfAbsent(to, toSet); + } + return graph; + } +} diff --git a/src/MinimumHoursOfTrainingToWinACompetition.java b/src/MinimumHoursOfTrainingToWinACompetition.java new file mode 100644 index 0000000..248e75b --- /dev/null +++ b/src/MinimumHoursOfTrainingToWinACompetition.java @@ -0,0 +1,24 @@ +// https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition +// T: O(N) +// S: O(1) + +public class MinimumHoursOfTrainingToWinACompetition { + public static int minNumberOfHours(int initialEnergy, int initialExperience, int[] energy, int[] experience) { + int trainingRequired = 0; + + for (int index = 0 ; index < energy.length ; index++) { + if (energy[index] >= initialEnergy) { + trainingRequired += energy[index] - initialEnergy + 1; + initialEnergy += energy[index] - initialEnergy + 1; + } + if (experience[index] >= initialExperience) { + trainingRequired += experience[index] - initialExperience + 1; + initialExperience += experience[index] - initialExperience + 1; + } + initialEnergy -= energy[index]; + initialExperience += experience[index]; + } + + return trainingRequired; + } +} diff --git a/src/MinimumIndexSumOfTwoLists.java b/src/MinimumIndexSumOfTwoLists.java new file mode 100644 index 0000000..169f756 --- /dev/null +++ b/src/MinimumIndexSumOfTwoLists.java @@ -0,0 +1,40 @@ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class MinimumIndexSumOfTwoLists { + public String[] findRestaurant(String[] list1, String[] list2) { + int indexSum = Integer.MAX_VALUE; + List result = new ArrayList<>(); + Map restaurantIndices = getValueToIndexMap(list1); + for (int index = 0 ; index < list2.length ; index++) { + if (restaurantIndices.containsKey(list2[index])) { + if (index + restaurantIndices.get(list2[index]) < indexSum) { + result.clear(); + result.add(list2[index]); + indexSum = index + restaurantIndices.get(list2[index]); + } else if(index + restaurantIndices.get(list2[index]) == indexSum) { + result.add(list2[index]); + } + } + } + return toArray(result); + } + + private String[] toArray(List strings) { + String[] result = new String[strings.size()]; + for (int index = 0 ; index < result.length ; index++) { + result[index] = strings.get(index); + } + return result; + } + + private Map getValueToIndexMap(String[] array) { + Map result = new HashMap<>(); + for (int index = 0 ; index < array.length ; index++) { + result.put(array[index], index); + } + return result; + } +} diff --git a/src/MinimumMovesToConvertString.java b/src/MinimumMovesToConvertString.java new file mode 100644 index 0000000..c5e751e --- /dev/null +++ b/src/MinimumMovesToConvertString.java @@ -0,0 +1,16 @@ +// https://leetcode.com/problems/minimum-moves-to-convert-string +// T: O(|s|) +// S: O(1) + +public class MinimumMovesToConvertString { + public int minimumMoves(String s) { + int conversions = 0; + for (int i = 0 ; i < s.length() ; i++) { + if (s.charAt(i) == 'X') { + conversions++; + i += 2; + } + } + return conversions; + } +} diff --git a/src/MinimumNumberGame.java b/src/MinimumNumberGame.java new file mode 100644 index 0000000..d7d56a2 --- /dev/null +++ b/src/MinimumNumberGame.java @@ -0,0 +1,19 @@ +// https://leetcode.com/problems/minimum-number-game +// T: O(N*log(N)) +// S: O(log(N)) + +import java.util.Arrays; + +public class MinimumNumberGame { + public int[] numberGame(int[] array) { + Arrays.sort(array); + final int[] result = new int[array.length]; + + for (int i = 0 ; i < array.length ; i += 2) { + result[i] = array[i + 1]; + result[i + 1] = array[i]; + } + + return result; + } +} diff --git a/src/MinimumNumberOfArrowsToBurstBalloons.java b/src/MinimumNumberOfArrowsToBurstBalloons.java new file mode 100644 index 0000000..41410b1 --- /dev/null +++ b/src/MinimumNumberOfArrowsToBurstBalloons.java @@ -0,0 +1,26 @@ +// https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons +// T: O(NlogN) +// S: O(logN) + +import java.util.Arrays; +import java.util.Comparator; + +public class MinimumNumberOfArrowsToBurstBalloons { + public int findMinArrowShots(int[][] points) { + if (points.length == 0) { + return 0; + } + + Arrays.sort(points, Comparator.comparingInt(o -> o[1])); + + int arrows = 1, endPoint = points[0][1]; + for (int[] p: points) { + if (endPoint < p[0]) { + arrows++; + endPoint = p[1]; + } + } + + return arrows; + } +} diff --git a/src/MinimumNumberOfChairsInAWaitingRoom.java b/src/MinimumNumberOfChairsInAWaitingRoom.java new file mode 100644 index 0000000..b6e94b0 --- /dev/null +++ b/src/MinimumNumberOfChairsInAWaitingRoom.java @@ -0,0 +1,18 @@ +// https://leetcode.com/problems/minimum-number-of-chairs-in-a-waiting-room +// T: O(N) +// S: O(1) + +public class MinimumNumberOfChairsInAWaitingRoom { + public int minimumChairs(String s) { + int minChairs = 0; + for (int i = 0, sum = 0 ; i < s.length() ; i++) { + if (s.charAt(i) == 'E') { + sum++; + } else { + sum--; + } + minChairs = Math.max(minChairs, sum); + } + return minChairs; + } +} diff --git a/src/MinimumNumberOfMovesToSeatEveryone.java b/src/MinimumNumberOfMovesToSeatEveryone.java new file mode 100644 index 0000000..e547ffb --- /dev/null +++ b/src/MinimumNumberOfMovesToSeatEveryone.java @@ -0,0 +1,17 @@ +// https://leetcode.com/problems/minimum-number-of-moves-to-seat-everyone +// T: O(n log(n)) +// S: O(1) + +import java.util.Arrays; + +public class MinimumNumberOfMovesToSeatEveryone { + public int minMovesToSeat(int[] seats, int[] students) { + Arrays.sort(seats); + Arrays.sort(students); + int minMoves = 0; + for (int i = 0 ; i < students.length ; i++) { + minMoves += Math.abs(seats[i] - students[i]); + } + return minMoves; + } +} diff --git a/src/MinimumNumberOfOperationsToConvertTime.java b/src/MinimumNumberOfOperationsToConvertTime.java new file mode 100644 index 0000000..24878b4 --- /dev/null +++ b/src/MinimumNumberOfOperationsToConvertTime.java @@ -0,0 +1,23 @@ +// https://leetcode.com/problems/minimum-number-of-operations-to-convert-time +// T: O(1) +// S: O(1) + +public class MinimumNumberOfOperationsToConvertTime { + private final static int[] MINUTE_INCREMENTS = {60, 15, 5, 1}; + + public int convertTime(String current, String correct) { + final int hour1 = Integer.parseInt(current.substring(0, 2)), hour2 = Integer.parseInt(correct.substring(0, 2)); + final int minutes1 = Integer.parseInt(current.substring(3)), minutes2 = Integer.parseInt(correct.substring(3)); + final int totalMinutes1 = hour1 * 60 + minutes1, totalMinutes2 = hour2 * 60 + minutes2; + + int operations = 0; + int difference = totalMinutes2 - totalMinutes1; + + for (int i = 0 ; i < MINUTE_INCREMENTS.length && difference > 0; i++) { + operations += difference / MINUTE_INCREMENTS[i]; + difference -= (difference / MINUTE_INCREMENTS[i]) * MINUTE_INCREMENTS[i]; + } + + return operations; + } +} diff --git a/src/MinimumNumberOfPushesToTypeWordI.java b/src/MinimumNumberOfPushesToTypeWordI.java new file mode 100644 index 0000000..2231bb3 --- /dev/null +++ b/src/MinimumNumberOfPushesToTypeWordI.java @@ -0,0 +1,28 @@ +// https://leetcode.com/problems/minimum-number-of-pushes-to-type-word-i +// T: O(|word|) +// S: O(|word|) + +import java.util.HashMap; +import java.util.Map; + +public class MinimumNumberOfPushesToTypeWordI { + public static int minimumPushes(String word) { + final Map letterFrequency = getLetterFrequencies(word); + final var entries = letterFrequency.entrySet().stream().sorted((a, b) -> Integer.compare(b.getValue(), a.getValue())).toList(); + + int pushes = 0; + for (int i = 0 ; i < entries.size() ; i++) { + pushes += entries.get(i).getValue() * ((i + 8) / 8); + } + + return pushes; + } + + private static Map getLetterFrequencies(String s) { + final Map frequencies = new HashMap<>(); + for (int i = 0 ; i < s.length() ; i++) { + frequencies.put(s.charAt(i), frequencies.getOrDefault(s.charAt(i), 0) + 1); + } + return frequencies; + } +} diff --git a/src/MinimumOperationsToCollectElements.java b/src/MinimumOperationsToCollectElements.java new file mode 100644 index 0000000..3ebd0e3 --- /dev/null +++ b/src/MinimumOperationsToCollectElements.java @@ -0,0 +1,22 @@ +// https://leetcode.com/problems/minimum-operations-to-collect-elements +// T: O(|array|) +// S: O(k) + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class MinimumOperationsToCollectElements { + public int minOperations(List array, int k) { + final Set collection = new HashSet<>(); + for (int i = array.size() - 1 ; i >= 0 ; i--) { + if (array.get(i) <= k) { + collection.add(array.get(i)); + } + if (collection.size() == k) { + return array.size() - i; + } + } + return -1; + } +} diff --git a/src/MinimumOperationsToExceedThresholdValueI.java b/src/MinimumOperationsToExceedThresholdValueI.java new file mode 100644 index 0000000..c864ae3 --- /dev/null +++ b/src/MinimumOperationsToExceedThresholdValueI.java @@ -0,0 +1,24 @@ +// https://leetcode.com/problems/minimum-operations-to-exceed-threshold-value-i +// T: O(N log(N)) +// S: O(log(N)) + +import java.util.Arrays; + +public class MinimumOperationsToExceedThresholdValueI { + public int minOperations(int[] array, int k) { + Arrays.sort(array); + return binarySearch(array, k); + } + + // binary search with left drag + private static int binarySearch(int[] array, int element) { + int left = 0, right = array.length - 1, middle; + while (left <= right) { + middle = left + (right - left) / 2; + if (array[middle] == element) right = middle - 1; + else if (array[middle] <= element) left = middle + 1; + else right = middle - 1; + } + return left; + } +} diff --git a/src/MinimumOperationsToMakeTheArrayIncreasing.java b/src/MinimumOperationsToMakeTheArrayIncreasing.java new file mode 100644 index 0000000..6ead1a6 --- /dev/null +++ b/src/MinimumOperationsToMakeTheArrayIncreasing.java @@ -0,0 +1,14 @@ +// https://leetcode.com/problems/minimum-operations-to-make-the-array-increasing +// T: O(N) +// S: O(1) + +public class MinimumOperationsToMakeTheArrayIncreasing { + public int minOperations(int[] nums) { + int operations = 0; + for (int index = 1, current = nums[0] ; index < nums.length ; index++) { + operations += Math.max(0, current - nums[index] + 1); + current = Math.max(current + 1, nums[index]); + } + return operations; + } +} diff --git a/src/MinimumPathSum.java b/src/MinimumPathSum.java new file mode 100644 index 0000000..a1a4130 --- /dev/null +++ b/src/MinimumPathSum.java @@ -0,0 +1,27 @@ +// https://leetcode.com/problems/minimum-path-sum +// T: O(m * n) +// S: O(1) + +public class MinimumPathSum { + public int minPathSum(int[][] grid) { + final int rows = grid.length, columns = grid[0].length; + + // last row + for (int column = columns - 2 ; column >= 0 ; column--) { + grid[rows - 1][column] += grid[rows - 1][column + 1]; + } + + // last column + for (int row = rows - 2 ; row >= 0 ; row--) { + grid[row][columns - 1] += grid[row + 1][columns - 1]; + } + + for (int row = rows - 2 ; row >= 0 ; row--) { + for (int column = columns - 2 ; column >= 0 ; column--) { + grid[row][column] += Math.min(grid[row + 1][column], grid[row][column + 1]); + } + } + + return grid[0][0]; + } +} diff --git a/src/MinimumRecolorsToGetKConsecutiveBlackBlocks.java b/src/MinimumRecolorsToGetKConsecutiveBlackBlocks.java new file mode 100644 index 0000000..0ddab6f --- /dev/null +++ b/src/MinimumRecolorsToGetKConsecutiveBlackBlocks.java @@ -0,0 +1,26 @@ +// https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks +// T: O(N) +// S: O(1) + +public class MinimumRecolorsToGetKConsecutiveBlackBlocks { + public int minimumRecolors(String blocks, int k) { + int numberOfWhites = numberOfWhitesInFirst(blocks, k); + int minRecolors = numberOfWhites; + + for (int index = k ; index < blocks.length() ; index++) { + if (blocks.charAt(index - k)== 'W') numberOfWhites--; + if (blocks.charAt(index) == 'W') numberOfWhites++; + minRecolors = Math.min(minRecolors, numberOfWhites); + } + + return minRecolors; + } + + private int numberOfWhitesInFirst(String blocks, int k) { + int result = 0; + for (int index = 0 ; index < k ; index++) { + if (blocks.charAt(index) == 'W') result++; + } + return result; + } +} diff --git a/src/MinimumRemoveToMakeValidParentheses.java b/src/MinimumRemoveToMakeValidParentheses.java new file mode 100644 index 0000000..f7a5e96 --- /dev/null +++ b/src/MinimumRemoveToMakeValidParentheses.java @@ -0,0 +1,44 @@ +// https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses +// T: O(n) +// S: O(n) + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.Stack; + +public class MinimumRemoveToMakeValidParentheses { + private static final record OpeningBrace(int index) { } + + public String minRemoveToMakeValid(String s) { + final Stack stack = new Stack<>(); + final List extraClosingBraceIndices = new ArrayList<>(); + char c; + for (int i = 0 ; i < s.length() ; i++) { + c = s.charAt(i); + if (c == ')') { + if (!stack.isEmpty()) { + stack.pop(); + } else extraClosingBraceIndices.add(i); + } else if (c == '(') stack.push(new OpeningBrace(i)); + } + final Set errorIndices = compileErrorIndicesFrom(extraClosingBraceIndices, stack); + StringBuilder result = new StringBuilder(); + for (int i = 0; i < s.length() ; i++) { + if (!errorIndices.contains(i)) { + result.append(s.charAt(i)); + } + } + return result.toString(); + } + + private Set compileErrorIndicesFrom(List wrongClosingBraces, Stack openingBraces) { + Set result = new HashSet<>(); + while (!openingBraces.isEmpty()) { + result.add(openingBraces.pop().index); + } + result.addAll(wrongClosingBraces); + return result; + } +} diff --git a/src/MinimumRightShiftsToSortTheArray.java b/src/MinimumRightShiftsToSortTheArray.java new file mode 100644 index 0000000..e82d265 --- /dev/null +++ b/src/MinimumRightShiftsToSortTheArray.java @@ -0,0 +1,36 @@ +// https://leetcode.com/problems/minimum-right-shifts-to-sort-the-array +// T: O(N) +// S: O(1) + +import java.util.List; + +public class MinimumRightShiftsToSortTheArray { + public int minimumRightShifts(List array) { + final int minElementIndex = getMinElementIndex(array); + if (!canSort(array, minElementIndex)) { + return -1; + } + + return (array.size() - minElementIndex) % array.size(); + } + + private static boolean canSort(List array, int minElementIndex) { + for (int i = (minElementIndex + 1) % array.size(), k = 0 ; k < array.size() - 1; k++, i = (i + 1) % array.size()) { + if (array.get(i) <= array.get((i - 1 + array.size()) % array.size())) { + return false; + } + } + return true; + } + + private static int getMinElementIndex(List array) { + int minElement = Integer.MAX_VALUE, index = -1; + for (int i = 0 ; i < array.size() ; i++) { + if (array.get(i) < minElement) { + minElement = array.get(i); + index = i; + } + } + return index; + } +} diff --git a/src/MinimumSizeSubarraySum.java b/src/MinimumSizeSubarraySum.java new file mode 100644 index 0000000..8a79679 --- /dev/null +++ b/src/MinimumSizeSubarraySum.java @@ -0,0 +1,17 @@ +// https://leetcode.com/problems/minimum-size-subarray-sum +// T: O(N) +// S: O(1) + +public class MinimumSizeSubarraySum { + public int minSubArrayLen(int target, int[] array) { + int minSize = Integer.MAX_VALUE; + for (int left = 0, right = 0, sum = 0 ; right < array.length ; right++) { + sum += array[right]; + while (sum >= target) { + minSize = Math.min(minSize, right - left + 1); + sum -= array[left++]; + } + } + return minSize == Integer.MAX_VALUE ? 0 : minSize; + } +} diff --git a/src/MinimumStringLengthAfterRemovingSubstrings.java b/src/MinimumStringLengthAfterRemovingSubstrings.java new file mode 100644 index 0000000..5ffbdb2 --- /dev/null +++ b/src/MinimumStringLengthAfterRemovingSubstrings.java @@ -0,0 +1,31 @@ +// https://leetcode.com/problems/minimum-string-length-after-removing-substrings +// T: O(N) +// S: O(N) + +import java.util.Set; +import java.util.Stack; + +public class MinimumStringLengthAfterRemovingSubstrings { + final static Set REMOVAL_TERMINATING_CHARS = Set.of('B', 'D'); + + public int minLength(String s) { + final Stack stack = new Stack<>(); + for (int i = 0 ; i < s.length() ; i++) { + final char letter = s.charAt(i); + if (!stack.isEmpty() && REMOVAL_TERMINATING_CHARS.contains(letter) && stack.peek() == inverse(letter)) { + stack.pop(); + } else { + stack.push(letter); + } + } + return stack.size(); + } + + private char inverse(char letter) { + return switch (letter) { + case 'B' -> 'A'; + case 'D' -> 'C'; + default -> ' '; + }; + } +} diff --git a/src/MinimumSubSequenceInNonIncreasingOrder.java b/src/MinimumSubSequenceInNonIncreasingOrder.java new file mode 100644 index 0000000..f277f8c --- /dev/null +++ b/src/MinimumSubSequenceInNonIncreasingOrder.java @@ -0,0 +1,18 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class MinimumSubSequenceInNonIncreasingOrder { + public List minSubsequence(int[] array) { + Arrays.sort(array); + final int sum = Arrays.stream(array).sum(); + final List result = new ArrayList<>(); + result.add(array[array.length - 1]); + for (int index = array.length - 2, current = array[array.length - 1] ; index >= 0 ; index--) { + if (current > sum - current) break; + current += array[index]; + result.add(array[index]); + } + return result; + } +} diff --git a/src/MinimumSumOfFourDigitNumberAfterSplittingDigits.java b/src/MinimumSumOfFourDigitNumberAfterSplittingDigits.java new file mode 100644 index 0000000..faaef89 --- /dev/null +++ b/src/MinimumSumOfFourDigitNumberAfterSplittingDigits.java @@ -0,0 +1,23 @@ +// https://leetcode.com/problems/minimum-sum-of-four-digit-number-after-splitting-digits +// T: O(1) +// S: O(1) + +import java.util.Arrays; + +public class MinimumSumOfFourDigitNumberAfterSplittingDigits { + public int minimumSum(int num) { + final int digit1 = num / 1000; + final int digit2 = (num / 100) % 10; + final int digit3 = (num / 10) % 10; + final int digit4 = num % 10; + + final int[] digits = { digit1, digit2, digit3, digit4 }; + Arrays.sort(digits); + + return toNumber(digits[0], digits[2]) + toNumber(digits[1], digits[3]); + } + + private int toNumber(int a, int b) { + return 10 * a + b; + } +} diff --git a/src/MinimumSumOfMountainTripletsI.java b/src/MinimumSumOfMountainTripletsI.java new file mode 100644 index 0000000..e005a61 --- /dev/null +++ b/src/MinimumSumOfMountainTripletsI.java @@ -0,0 +1,40 @@ +// https://leetcode.com/problems/minimum-sum-of-mountain-triplets-i +// T: O(N^2) +// T: O(1) + +public class MinimumSumOfMountainTripletsI { + public int minimumSum(int[] array) { + int minSum = Integer.MAX_VALUE; + + for (int i = 1 ; i < array.length - 1 ; i++) { + final int minLeft = getSmallestOnLeft(array, i); + if (minLeft >= array[i]) { + continue; + } + final int minRight = getSmallestOnRight(array, i); + if (minRight >= array[i]) { + continue; + } + + minSum = Math.min(minSum, minLeft + minRight + array[i]); + } + + return minSum == Integer.MAX_VALUE ? -1 : minSum; + } + + private static int getSmallestOnLeft(int[] array, int index) { + int min = Integer.MAX_VALUE; + for (int i = 0 ; i < index ; i++) { + min = Math.min(min, array[i]); + } + return min; + } + + private static int getSmallestOnRight(int[] array, int index) { + int min = Integer.MAX_VALUE; + for (int i = index + 1 ; i < array.length ; i++) { + min = Math.min(min, array[i]); + } + return min; + } +} diff --git a/src/MinimumTimeToTypeWordUsingSpecialTypewriter.java b/src/MinimumTimeToTypeWordUsingSpecialTypewriter.java new file mode 100644 index 0000000..734e5fd --- /dev/null +++ b/src/MinimumTimeToTypeWordUsingSpecialTypewriter.java @@ -0,0 +1,19 @@ +// https://leetcode.com/problems/minimum-time-to-type-word-using-special-typewriter +// T: O(|word|) +// S: O(1) + +public class MinimumTimeToTypeWordUsingSpecialTypewriter { + public int minTimeToType(String word) { + return movingTime(word) + word.length(); + } + + private int movingTime(String s) { + int movingTime = 0, distance; + for (int i = 1 ; i < s.length() ; i++) { + distance = Math.abs(s.charAt(i) - s.charAt(i - 1)); + movingTime += Math.min(distance, 26 - distance); + } + distance = Math.abs(s.charAt(0) - 'a'); + return movingTime + Math.min(distance, 26 - distance); + } +} diff --git a/src/MinimumTimeVisitingAllPoints.java b/src/MinimumTimeVisitingAllPoints.java new file mode 100644 index 0000000..ae1e8ba --- /dev/null +++ b/src/MinimumTimeVisitingAllPoints.java @@ -0,0 +1,12 @@ +public class MinimumTimeVisitingAllPoints { + public int minTimeToVisitAllPoints(int[][] points) { + int minTime = 0; + for (int index = 0 ; index < points.length - 1 ; index++) { + minTime += Math.max( + Math.abs(points[index + 1][1] - points[index][1]), + Math.abs(points[index + 1][0] - points[index][0]) + ); + } + return minTime; + } +} diff --git a/src/MinimumValueToGetPositiveStepByStepSum.java b/src/MinimumValueToGetPositiveStepByStepSum.java new file mode 100644 index 0000000..63e882c --- /dev/null +++ b/src/MinimumValueToGetPositiveStepByStepSum.java @@ -0,0 +1,15 @@ +public class MinimumValueToGetPositiveStepByStepSum { + public int minStartValue(int[] array) { + int lowestPoint =getLowestPoint(array); + return 1 - Math.min(0, lowestPoint); + } + + private int getLowestPoint(int[] array) { + int lowestPoint = 0, sum = 0; + for (int element : array) { + sum += element; + if (sum < lowestPoint) lowestPoint = sum; + } + return lowestPoint; + } +} diff --git a/src/MissingRanges.java b/src/MissingRanges.java new file mode 100644 index 0000000..7a41bd3 --- /dev/null +++ b/src/MissingRanges.java @@ -0,0 +1,28 @@ +// https://leetcode.com/problems/missing-ranges +// T: O(N) +// S: O(N) + +import java.util.ArrayList; +import java.util.List; + +public class MissingRanges { + public List> findMissingRanges(int[] nums, int lower, int upper) { + if (nums.length == 0) { + return List.of(List.of(lower, upper)); + } + + final List> result = new ArrayList<>(); + if (lower != nums[0]) { + result.add(List.of(lower, nums[0] - 1)); + } + for (int i = 0 ; i < nums.length - 1 ; i++) { + if (nums[i + 1] - nums[i] > 1) { + result.add(List.of(nums[i] + 1, nums[i + 1] - 1)); + } + } + if (nums[nums.length - 1] != upper) { + result.add(List.of(nums[nums.length - 1] + 1, upper)); + } + return result; + } +} diff --git a/src/ModifyTheMatrix.java b/src/ModifyTheMatrix.java new file mode 100644 index 0000000..12db3fb --- /dev/null +++ b/src/ModifyTheMatrix.java @@ -0,0 +1,32 @@ +// https://leetcode.com/problems/modify-the-matrix +// T: O(m * n) +// S: O(1) + +public class ModifyTheMatrix { + public int[][] modifiedMatrix(int[][] matrix) { + final int rows = matrix.length, columns = matrix[0].length; + + for (int column = 0 ; column < columns ; column++) { + final int maxValueColumn = getMaxInColumn(matrix, column); + replaceAllNegative1With(matrix, column, maxValueColumn); + } + + return matrix; + } + + private static int getMaxInColumn(int[][] matrix, int column) { + int maxValue = Integer.MIN_VALUE; + for (int[] row : matrix) { + maxValue = Math.max(maxValue, row[column]); + } + return maxValue; + } + + private static void replaceAllNegative1With(int[][] matrix, int column, int value) { + for (int row = 0 ; row < matrix.length ; row++) { + if (matrix[row][column] == -1) { + matrix[row][column] = value; + } + } + } +} diff --git a/src/MonotonicArray.java b/src/MonotonicArray.java new file mode 100644 index 0000000..3d20cc2 --- /dev/null +++ b/src/MonotonicArray.java @@ -0,0 +1,19 @@ +public class MonotonicArray { + public boolean isMonotonic(int[] nums) { + return isMonotonicIncreasing(nums) || isMonotonicDecreasing(nums); + } + + private boolean isMonotonicIncreasing(int[] array) { + for (int i = 1 ; i < array.length ; i++) { + if (array[i] < array[i - 1]) return false; + } + return true; + } + + private boolean isMonotonicDecreasing(int[] array) { + for (int i = 1 ; i < array.length ; i++) { + if (array[i] > array[i - 1]) return false; + } + return true; + } +} diff --git a/src/MostCommonWord.java b/src/MostCommonWord.java new file mode 100644 index 0000000..1d312f2 --- /dev/null +++ b/src/MostCommonWord.java @@ -0,0 +1,22 @@ +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class MostCommonWord { + public String mostCommonWord(String paragraph, String[] banned) { + String text = paragraph.replaceAll("[^a-zA-Z0-9 ]", " ").toLowerCase(); + Set bannedWords = new HashSet<>(Arrays.asList(banned)); + Map wordFrequencies = new HashMap<>(); + + for (String word : text.split("\\s+")) { + if (!bannedWords.contains(word)) { + wordFrequencies.put(word, wordFrequencies.getOrDefault(word, 0) + 1); + } + } + + return Collections.max(wordFrequencies.entrySet(), Map.Entry.comparingByValue()).getKey(); + } +} diff --git a/src/MostFrequentEvenElement.java b/src/MostFrequentEvenElement.java new file mode 100644 index 0000000..3a81c9b --- /dev/null +++ b/src/MostFrequentEvenElement.java @@ -0,0 +1,29 @@ +// https://leetcode.com/problems/most-frequent-even-element +// T: O(N) +// S: O(N) + +import java.util.HashMap; +import java.util.Map; + +public class MostFrequentEvenElement { + public int mostFrequentEven(int[] nums) { + final Map evenFrequencies = new HashMap<>(); + int maxFrequency = 0, smallestEvenNumber = -1; + + for (int element : nums) { + if (element % 2 == 1) { + continue; + } + + evenFrequencies.put(element, evenFrequencies.getOrDefault(element, 0) + 1); + if (evenFrequencies.get(element) > maxFrequency) { + maxFrequency = evenFrequencies.get(element); + smallestEvenNumber = element; + } else if (evenFrequencies.get(element) == maxFrequency) { + smallestEvenNumber = Math.min(smallestEvenNumber, element); + } + } + + return smallestEvenNumber; + } +} diff --git a/src/MostFrequentNumberFollowingKeyInAnArray.java b/src/MostFrequentNumberFollowingKeyInAnArray.java new file mode 100644 index 0000000..040dbfd --- /dev/null +++ b/src/MostFrequentNumberFollowingKeyInAnArray.java @@ -0,0 +1,35 @@ +// https://leetcode.com/problems/most-frequent-number-following-key-in-an-array +// T: O(N) +// S: O(N) + +import java.util.HashMap; +import java.util.Map; + +public class MostFrequentNumberFollowingKeyInAnArray { + public int mostFrequent(int[] nums, int key) { + final Map targetToFrequency = getTargetFrequencies(nums, key); + return mostFrequentTarget(targetToFrequency); + } + + private Map getTargetFrequencies(int[] array, int key) { + final Map result = new HashMap<>(); + for (int index = 0 ; index < array.length - 1 ; index++) { + if (array[index] == key) { + int target = array[index + 1]; + result.put(target, result.getOrDefault(target, 0) + 1); + } + } + return result; + } + + private int mostFrequentTarget(final Map frequencies) { + int target = -1, maxFrequency = -1; + for (Map.Entry entry : frequencies.entrySet()) { + if (entry.getValue() > maxFrequency) { + maxFrequency = entry.getValue(); + target = entry.getKey(); + } + } + return target; + } +} diff --git a/src/MostVisitedSectorInACircularTrack.java b/src/MostVisitedSectorInACircularTrack.java new file mode 100644 index 0000000..d644af2 --- /dev/null +++ b/src/MostVisitedSectorInACircularTrack.java @@ -0,0 +1,18 @@ +import java.util.ArrayList; +import java.util.List; + +public class MostVisitedSectorInACircularTrack { + public List mostVisited(int n, int[] rounds) { + final int start = rounds[0], end = rounds[rounds.length - 1]; + final List result = new ArrayList<>(); + if (start <= end) { + for (int i = start ; i <= end ; i++) { + result.add(i); + } + return result; + } + for (int i = 1; i <= end ; i++) result.add(i); + for (int i = start ; i <= n ; i++) result.add(i); + return result; + } +} diff --git a/src/MovingAverageFromDataStream.java b/src/MovingAverageFromDataStream.java new file mode 100644 index 0000000..f7a11d5 --- /dev/null +++ b/src/MovingAverageFromDataStream.java @@ -0,0 +1,31 @@ +// https://leetcode.com/problems/moving-average-from-data-stream +// N: number of calls to next(), M: max window size +// T: O(N) +// S: O(M) + +import java.util.LinkedList; +import java.util.Queue; + +public class MovingAverageFromDataStream { +} + + +class MovingAverage { + final int windowSize; + final Queue queue = new LinkedList<>(); + double windowSum = 0; + + // T: O(1) + public MovingAverage(int size) { + windowSize = size; + } + + // T: O(1) + // S: O(1) + public double next(int val) { + queue.add(val); + final int toRemove = (queue.size() > windowSize && !queue.isEmpty()) ? queue.poll() : 0; + windowSum += val - toRemove; + return windowSum / queue.size(); + } +} \ No newline at end of file diff --git a/src/MultiplyStrings.java b/src/MultiplyStrings.java new file mode 100644 index 0000000..03cd382 --- /dev/null +++ b/src/MultiplyStrings.java @@ -0,0 +1,49 @@ +// https://leetcode.com/problems/multiply-strings +// T: O(|num1| * |num2|) +// S: O(|num1| + |num2|) + +public class MultiplyStrings { + private static final String ZERO = "0"; + private static final String ONE = "1"; + + public String multiply(String num1, String num2) { + if (ZERO.equals(num1) || ZERO.equals(num2)) return ZERO; + if (ONE.equals(num1)) return num2; + if (ONE.equals(num2)) return num1; + + StringBuilder result = new StringBuilder(ZERO); + for (int i = num2.length() - 1 ; i >= 0 ; i--) { + result = add(result, multiply(num1, num2.charAt(i) - '0', num2.length() - i - 1)); + } + return result.toString(); + } + + private StringBuilder multiply(String number, int digit, int factor) { + final StringBuilder result = new StringBuilder(); + int carry = 0; + for (int i = number.length() - 1 ; i >= 0 ; i--) { + int val = (number.charAt(i) - '0') * digit + carry; + result.append(val % 10); + carry = val / 10; + } + if (carry > 0) result.append(carry); + return result.reverse().append(ZERO.repeat(factor)); + } + + private StringBuilder add(StringBuilder a, StringBuilder b) { + final StringBuilder result = new StringBuilder(); + int carry = 0; + for (int i = a.length() - 1, j = b.length() - 1 ; i >= 0 || j >= 0 ; i--, j--) { + int val = getDigit(a, i) + getDigit(b, j) + carry; + result.append(val % 10); + carry = val / 10; + } + if (carry > 0) result.append(carry); + return result.reverse(); + } + + private int getDigit(StringBuilder string, int index) { + if (index < 0) return 0; + return string.charAt(index) - '0'; + } +} diff --git a/src/NArayTreePreOrderTraversal.java b/src/NArayTreePreOrderTraversal.java new file mode 100644 index 0000000..12d54a4 --- /dev/null +++ b/src/NArayTreePreOrderTraversal.java @@ -0,0 +1,35 @@ +import java.util.ArrayList; +import java.util.List; + +public class NArayTreePreOrderTraversal { + private static class Node { + public int val; + public List children; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, List _children) { + val = _val; + children = _children; + } + } + + List result = new ArrayList<>(); + + public List preorder(Node root) { + preorderTraversal(root); + return result; + } + + private void preorderTraversal(Node root) { + if (root == null) return; + result.add(root.val); + for (Node child :root.children) { + preorderTraversal(child); + } + } +} diff --git a/src/NAryTreeLevelOrderTraversal.java b/src/NAryTreeLevelOrderTraversal.java new file mode 100644 index 0000000..5627945 --- /dev/null +++ b/src/NAryTreeLevelOrderTraversal.java @@ -0,0 +1,56 @@ +// https://leetcode.com/problems/n-ary-tree-level-order-traversal +// T: O(N) +// S: O(N) + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + +public class NAryTreeLevelOrderTraversal { + public static class Node { + public int val; + public List children; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, List _children) { + val = _val; + children = _children; + } + } + + public List> levelOrder(Node root) { + if (root == null) { + return new ArrayList<>(); + } + + final List> result = new ArrayList<>(); + final Queue queue = new LinkedList<>(); + List current = new ArrayList<>(); + + queue.add(root); + queue.add(null); + + while (!queue.isEmpty()) { + final Node node = queue.poll(); + if (node == null) { + result.add(current); + current = new ArrayList<>(); + if (!queue.isEmpty()) { + queue.add(null); + } + continue; + } + + current.add(node.val); + queue.addAll(node.children); + } + + return result; + } +} diff --git a/src/NAryTreePostorderTraversal.java b/src/NAryTreePostorderTraversal.java new file mode 100644 index 0000000..a33c4ee --- /dev/null +++ b/src/NAryTreePostorderTraversal.java @@ -0,0 +1,35 @@ +import java.util.ArrayList; +import java.util.List; + +public class NAryTreePostorderTraversal { + private static class Node { + public int val; + public List children; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, List _children) { + val = _val; + children = _children; + } + } + + List result = new ArrayList<>(); + + public List postorder(Node root) { + postorderTraversal(root); + return result; + } + + private void postorderTraversal(Node root) { + if (root == null) return; + for (Node child : root.children) { + postorderTraversal(child); + } + result.add(root.val); + } +} diff --git a/src/NQueens.java b/src/NQueens.java new file mode 100644 index 0000000..61a3c20 --- /dev/null +++ b/src/NQueens.java @@ -0,0 +1,96 @@ +// https://leetcode.com/problems/n-queens +// T: O(N!) +// S: O(N^2) + +import java.util.ArrayList; +import java.util.List; + +public class NQueens { + private static boolean[] rows, columns; + + public static List> solveNQueens(int n) { + final List> result = new ArrayList<>(); + final List board = getEmptyBoard(n); + rows = new boolean[n]; + columns = new boolean[n]; + nQueens(0, n, result, board, 0); + return result; + } + + private static void nQueens(int row, int n, List> result, List board, int queens) { + if (row == n) { + if (queens == n) { + result.add(new ArrayList<>(board)); + } + return; + } + + for (int column = 0 ; column < n ; column++) { + if (canPlace(board, row, column)) { + placeQueen(board, row, column); + nQueens(row + 1, n, result, board, queens + 1); + removeQueen(board, row, column); + } + } + } + + private static void placeQueen(List board, int row, int column) { + board.set( + row, + board.get(row).substring(0, column) + 'Q' + board.get(row).substring(column + 1) + ); + rows[row] = true; + columns[column] = true; + } + + private static void removeQueen(List board, int row, int column) { + board.set( + row, + board.get(row).substring(0, column) + '.' + board.get(row).substring(column + 1) + ); + rows[row] = false; + columns[column] = false; + } + + private static boolean canPlace(List board, int row, int column) { + return !rows[row] && !columns[column] && !queenInLeftDiagonal(board, row, column) + && !queenInRightDiagonal(board, row, column); + } + + private static boolean queenInLeftDiagonal(List board, int row, int column) { + for (int i = row - 1, j = column - 1 ; i >= 0 && j >= 0 ; i--, j--) { + if (board.get(i).charAt(j) == 'Q') { + return true; + } + } + for (int i = row + 1, j = column + 1 ; i < board.size() && j < board.size() ; i++, j++) { + if (board.get(i).charAt(j) == 'Q') { + return true; + } + } + return false; + } + + private static boolean queenInRightDiagonal(List board, int row, int column) { + for (int i = row - 1, j = column + 1 ; i >= 0 && j < board.size() ; i--, j++) { + if (board.get(i).charAt(j) == 'Q') { + return true; + } + } + for (int i = row + 1, j = column - 1 ; i < board.size() && j >= 0 ; i++, j--) { + if (board.get(i).charAt(j) == 'Q') { + return true; + } + } + return false; + } + + private static List getEmptyBoard(int n) { + final List board = new ArrayList<>(); + final String line = ".".repeat(n); + for (int i = 0 ; i < n ; i++) { + board.add(line); + } + return board; + } +} diff --git a/src/NQueensII.java b/src/NQueensII.java new file mode 100644 index 0000000..2cc8e68 --- /dev/null +++ b/src/NQueensII.java @@ -0,0 +1,97 @@ +// https://leetcode.com/problems/n-queens-ii +// T: O(N!) +// S: O(N^2) + +import java.util.ArrayList; +import java.util.List; + +public class NQueensII { + private static boolean[] rows, columns; + private static int result = 0; + + public int totalNQueens(int n) { + result = 0; + final List board = getEmptyBoard(n); + rows = new boolean[n]; + columns = new boolean[n]; + nQueens(0, n, board, 0); + return result; + } + + private static void nQueens(int row, int n, List board, int queens) { + if (row == n) { + if (queens == n) { + result++; + } + return; + } + + for (int column = 0 ; column < n ; column++) { + if (canPlace(board, row, column)) { + placeQueen(board, row, column); + nQueens(row + 1, n, board, queens + 1); + removeQueen(board, row, column); + } + } + } + + private static void placeQueen(List board, int row, int column) { + board.set( + row, + board.get(row).substring(0, column) + 'Q' + board.get(row).substring(column + 1) + ); + rows[row] = true; + columns[column] = true; + } + + private static void removeQueen(List board, int row, int column) { + board.set( + row, + board.get(row).substring(0, column) + '.' + board.get(row).substring(column + 1) + ); + rows[row] = false; + columns[column] = false; + } + + private static boolean canPlace(List board, int row, int column) { + return !rows[row] && !columns[column] && !queenInLeftDiagonal(board, row, column) + && !queenInRightDiagonal(board, row, column); + } + + private static boolean queenInLeftDiagonal(List board, int row, int column) { + for (int i = row - 1, j = column - 1 ; i >= 0 && j >= 0 ; i--, j--) { + if (board.get(i).charAt(j) == 'Q') { + return true; + } + } + for (int i = row + 1, j = column + 1 ; i < board.size() && j < board.size() ; i++, j++) { + if (board.get(i).charAt(j) == 'Q') { + return true; + } + } + return false; + } + + private static boolean queenInRightDiagonal(List board, int row, int column) { + for (int i = row - 1, j = column + 1 ; i >= 0 && j < board.size() ; i--, j++) { + if (board.get(i).charAt(j) == 'Q') { + return true; + } + } + for (int i = row + 1, j = column - 1 ; i < board.size() && j >= 0 ; i++, j--) { + if (board.get(i).charAt(j) == 'Q') { + return true; + } + } + return false; + } + + private static List getEmptyBoard(int n) { + final List board = new ArrayList<>(); + final String line = ".".repeat(n); + for (int i = 0 ; i < n ; i++) { + board.add(line); + } + return board; + } +} diff --git a/src/NRepeatedElementInSizeNArray.java b/src/NRepeatedElementInSizeNArray.java new file mode 100644 index 0000000..44f2764 --- /dev/null +++ b/src/NRepeatedElementInSizeNArray.java @@ -0,0 +1,10 @@ +public class NRepeatedElementInSizeNArray { + public int repeatedNTimes(int[] nums) { + for (int k = 1 ; k < 4 ; k++) { + for (int i = 0 ; i < nums.length - k ; i++) { + if (nums[i] == nums[i + k]) return nums[i]; + } + } + return -1; + } +} diff --git a/src/NeitherMinimumNorMaximum.java b/src/NeitherMinimumNorMaximum.java new file mode 100644 index 0000000..56fec25 --- /dev/null +++ b/src/NeitherMinimumNorMaximum.java @@ -0,0 +1,15 @@ +// https://leetcode.com/problems/neither-minimum-nor-maximum +// T: O(1) +// S: O(1) + +public class NeitherMinimumNorMaximum { + public int findNonMinOrMax(int[] nums) { + if (nums.length < 3) return -1; + final int max = Math.max(nums[0], nums[1]); + final int min = Math.min(nums[0], nums[1]); + + if (nums[2] < min) return min; + else if (nums[2] < max) return nums[2]; + return max; + } +} diff --git a/src/NetworkDelayTime.java b/src/NetworkDelayTime.java new file mode 100644 index 0000000..157ae1f --- /dev/null +++ b/src/NetworkDelayTime.java @@ -0,0 +1,65 @@ +// https://leetcode.com/problems/network-delay-time +// Single source shortest path algorithm (Dijkstra's Algorithm) +// T: O(E log(N) for dijkstra + N for searching max val) +// S: O(E + N) + +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.PriorityQueue; +import java.util.Queue; + +public class NetworkDelayTime { + private record Node(int value, long time) { } + + public int networkDelayTime(int[][] times, int n, int k) { + final Map> graph = createDirectedGraphFrom(times); + final long[] minTimeTaken = getMinTimeTakenArray(n, k); + final Queue queue = new PriorityQueue(Comparator.comparing(Node::time)); + queue.add(new Node(k, 0)); + + while (!queue.isEmpty()) { + Node node = queue.poll(); + if (!graph.containsKey(node.value)) continue; + Map vertexNode = graph.get(node.value); + for (int adjacent : vertexNode.keySet()) { + if (minTimeTaken[node.value - 1] + vertexNode.get(adjacent) < minTimeTaken[adjacent - 1]) { + minTimeTaken[adjacent - 1] = minTimeTaken[node.value - 1] + vertexNode.get(adjacent); + queue.add(new Node(adjacent, minTimeTaken[adjacent - 1])); + } + } + } + + return allAreReached(minTimeTaken) ? (int) Arrays.stream(minTimeTaken).max().getAsLong() : -1; + } + + private Map> createDirectedGraphFrom(int[][] times) { + final Map> graph = new HashMap<>(); + for (int[] time : times) { + int start = time[0]; + int destination = time[1]; + int delay = time[2]; + + graph.putIfAbsent(start, new HashMap<>()); + graph.get(start).put(destination, delay); + } + return graph; + } + + private long[] getMinTimeTakenArray(int length, int start) { + long[] array = new long[length]; + for (int i = 0 ; i < length ; i++) { + array[i] = Integer.MAX_VALUE; + } + array[start - 1] = 0; + return array; + } + + private boolean allAreReached(long[] array) { + for (long val : array) { + if (val == Integer.MAX_VALUE) return false; + } + return true; + } +} diff --git a/src/NextPermutation.java b/src/NextPermutation.java new file mode 100644 index 0000000..2b85462 --- /dev/null +++ b/src/NextPermutation.java @@ -0,0 +1,42 @@ +// https://leetcode.com/problems/next-permutation +// T: O(|nums|) +// S: O(1) + +public class NextPermutation { + public void nextPermutation(int[] nums) { + for (int i = nums.length - 2 ; i >= 0 ; i--) { + if (nums[i] < nums[i + 1]) { + int index = indexOfNextLargest(nums, i + 1, nums[i]); + swap(nums, i, index); + reverse(nums, i + 1, nums.length); + return; + } + } + reverse(nums); + } + + private void swap(int[] array, int i, int j) { + int temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + + private int indexOfNextLargest(int[] array, int start, int x) { + for (int i = start ; i < array.length ; i++) { + if (array[i] <= x) { + return i - 1; + } + } + return array.length - 1; + } + + private void reverse(int[] array) { + reverse(array, 0, array.length); + } + + private void reverse(int[] array, int start, int end) { + for (int i = start ; i < start + (end - start) / 2 ; i++) { + swap(array, i, end - i + start - 1); + } + } +} diff --git a/src/NonDecreasingArray.java b/src/NonDecreasingArray.java new file mode 100644 index 0000000..ec20cbd --- /dev/null +++ b/src/NonDecreasingArray.java @@ -0,0 +1,15 @@ +public class NonDecreasingArray { + public boolean checkPossibility(int[] array) { + boolean handledDecreasing = false; + for (int index = 0 ; index < array.length - 1 ; index++) { + if (array[index] > array[index + 1]) { + if (handledDecreasing) return false; + handledDecreasing = true; + if ((index - 1 >= 0 && array[index - 1] > array[index + 1]) && (index + 2 < array.length && array[index] > array[index + 2])) { + return false; + } + } + } + return true; + } +} diff --git a/src/NthTribonacciNumber.java b/src/NthTribonacciNumber.java new file mode 100644 index 0000000..c3b781d --- /dev/null +++ b/src/NthTribonacciNumber.java @@ -0,0 +1,15 @@ +public class NthTribonacciNumber { + public int tribonacci(int n) { + if (n == 0) return 0; + if (n <= 2) return 1; + int a = 0, b = 1, c = 1, temp; + while (n - 2 > 0) { + temp = c; + c = a + b + c; + a = b; + b = temp; + n--; + } + return c; + } +} diff --git a/src/NumberComplement.java b/src/NumberComplement.java index ba81197..212dc51 100644 --- a/src/NumberComplement.java +++ b/src/NumberComplement.java @@ -1,6 +1,5 @@ public class NumberComplement { - public static int findComplement(int n) { - int numberOfBits = (int) (Math.floor(Math.log(n) / Math.log(2))) + 1; - return ((1 << numberOfBits) - 1) ^ n; + public static int findComplement(int number) { + return ~number & (Integer.highestOneBit(number) - 1); } } diff --git a/src/NumberOfArithmeticTriplets.java b/src/NumberOfArithmeticTriplets.java new file mode 100644 index 0000000..08db058 --- /dev/null +++ b/src/NumberOfArithmeticTriplets.java @@ -0,0 +1,22 @@ +// https://leetcode.com/problems/number-of-arithmetic-triplets +// T: O(N) +// S: O(N) + +import java.util.HashSet; +import java.util.Set; + +public class NumberOfArithmeticTriplets { + public int arithmeticTriplets(int[] array, int diff) { + final Set elements = new HashSet<>(); + int triplets = 0; + + for (int number : array) { + if (elements.contains(number - diff) && elements.contains(number - 2 * diff)) { + triplets++; + } + elements.add(number); + } + + return triplets; + } +} diff --git a/src/NumberOfBeautifulPairs.java b/src/NumberOfBeautifulPairs.java new file mode 100644 index 0000000..d04b286 --- /dev/null +++ b/src/NumberOfBeautifulPairs.java @@ -0,0 +1,41 @@ +// https://leetcode.com/problems/number-of-beautiful-pairs/description +// N: length of number array +// m: size of average number +// T: O(N * log(m)) +// S: O(N) + +import java.util.HashMap; +import java.util.Map; + +public class NumberOfBeautifulPairs { + public int countBeautifulPairs(int[] array) { + final Map firstDigitFrequencies = new HashMap<>(); + int pairs = 0; + for (int element : array) { + final int firstDigit = getFirstDigit(element); + final int lastDigit = getLastDigit(element); + for (Map.Entry entry : firstDigitFrequencies.entrySet()) { + if (gcd(lastDigit, entry.getKey()) == 1) { + pairs += entry.getValue(); + } + } + firstDigitFrequencies.put(firstDigit, firstDigitFrequencies.getOrDefault(firstDigit, 0) + 1); + } + return pairs; + } + + private int getFirstDigit(int number) { + return (number + "").charAt(0) - '0'; + } + + private int getLastDigit(int number) { + return number % 10; + } + + // T: O(log(max(a, b))) + // S: O(log(max(a, b))) + private int gcd(int a, int b) { + if (b == 0) return a; + return gcd(b, a % b); + } +} diff --git a/src/NumberOfBitChangesToMakeTwoIntegersEqual.java b/src/NumberOfBitChangesToMakeTwoIntegersEqual.java new file mode 100644 index 0000000..cd24c4a --- /dev/null +++ b/src/NumberOfBitChangesToMakeTwoIntegersEqual.java @@ -0,0 +1,25 @@ +// https://leetcode.com/problems/number-of-bit-changes-to-make-two-integers-equal +// T: O(max(log(N), log(K))) +// S: O(1) + +public class NumberOfBitChangesToMakeTwoIntegersEqual { + public int minChanges(int n, int k) { + if (n == k) { + return 0; + } + + int changes = 0; + while (n > 0 || k > 0) { + final int nLastBit = n & 1; + final int kLastBit = k & 1; + if (kLastBit == 1 && nLastBit == 0) { + return -1; + } else if (kLastBit == 0 && nLastBit == 1) { + changes++; + } + n >>= 1; + k >>= 1; + } + return changes; + } +} diff --git a/src/NumberOfChangingKeys.java b/src/NumberOfChangingKeys.java new file mode 100644 index 0000000..6bef959 --- /dev/null +++ b/src/NumberOfChangingKeys.java @@ -0,0 +1,19 @@ +// https://leetcode.com/problems/number-of-changing-keys +// T: O(|s|) +// S: O(1) + +public class NumberOfChangingKeys { + public int countKeyChanges(String s) { + int changes = 0; + for (int i = 1 ; i < s.length() ; i++) { + if (isDifferent(s.charAt(i - 1), s.charAt(i))) { + changes++; + } + } + return changes; + } + + private static boolean isDifferent(char a, char b) { + return Character.toLowerCase(a) != Character.toLowerCase(b); + } +} diff --git a/src/NumberOfCommonFactors.java b/src/NumberOfCommonFactors.java new file mode 100644 index 0000000..f3409ed --- /dev/null +++ b/src/NumberOfCommonFactors.java @@ -0,0 +1,17 @@ +// https://leetcode.com/problems/number-of-common-factors +// T: O(min(a, b)) +// S: O(1) + +public class NumberOfCommonFactors { + public int commonFactors(int a, int b) { + final int min = Math.min(a, b); + int commonFactors = 1; + + for (int factor = 2 ; factor <= min ; factor++) { + if (a % factor == 0 & b % factor == 0) { + commonFactors++; + } + } + return commonFactors; + } +} diff --git a/src/NumberOfConnectedComponentsInAnUndirectedGraph.java b/src/NumberOfConnectedComponentsInAnUndirectedGraph.java new file mode 100644 index 0000000..1d49eda --- /dev/null +++ b/src/NumberOfConnectedComponentsInAnUndirectedGraph.java @@ -0,0 +1,55 @@ +// https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph +// T: O(V + E * alpha(V)) alpha = inverse ackerman function +// S: O(V) + +public class NumberOfConnectedComponentsInAnUndirectedGraph { + private static final class DisjointSet { + private final int[] root, rank; + + public DisjointSet(int size) { + root = new int[size]; + rank = new int[size]; + for (int i = 0 ; i < size ; i++) { + root[i] = i; + rank[i] = 1; + } + } + + public int find(int num) { + if (num == root[num]) { + return num; + } + return root[num] = find(root[num]); + } + + public boolean areConnected(int x, int y) { + return find(x) == find(y); + } + + public void union(int x, int y) { + final int rootX = find(x), rootY = find(y); + if (rootX == rootY) { + return; + } + if (rank[rootX] < rank[rootY]) { + root[rootX] = rootY; + } else if (rank[rootX] > rank[rootY]) { + root[rootY] = rootX; + } else { + root[rootY] = rootX; + rank[rootX]++; + } + } + } + + public int countComponents(int n, int[][] edges) { + final DisjointSet disjointSet = new DisjointSet(n); + for (int[] edge : edges) { + if (!disjointSet.areConnected(edge[0], edge[1])) { + disjointSet.union(edge[0], edge[1]); + n--; + } + } + return n; + } +} diff --git a/src/NumberOfDaysBetweenTwoDates.java b/src/NumberOfDaysBetweenTwoDates.java new file mode 100644 index 0000000..d36f229 --- /dev/null +++ b/src/NumberOfDaysBetweenTwoDates.java @@ -0,0 +1,21 @@ +import java.time.LocalDate; + +import static java.time.temporal.ChronoUnit.DAYS; + +public class NumberOfDaysBetweenTwoDates { + public int daysBetweenDates(String date1, String date2) { + final String[] dateParts1 = date1.split("-"); + final String[] dateParts2 = date2.split("-"); + final LocalDate d1 = LocalDate.of( + Integer.parseInt(dateParts1[0]), + Integer.parseInt(dateParts1[1]), + Integer.parseInt(dateParts1[2]) + ); + final LocalDate d2 = LocalDate.of( + Integer.parseInt(dateParts2[0]), + Integer.parseInt(dateParts2[1]), + Integer.parseInt(dateParts2[2]) + ); + return (int) Math.abs(DAYS.between(d1, d2)); + } +} diff --git a/src/NumberOfDifferentIntegersInString.java b/src/NumberOfDifferentIntegersInString.java new file mode 100644 index 0000000..62da2c1 --- /dev/null +++ b/src/NumberOfDifferentIntegersInString.java @@ -0,0 +1,27 @@ +import java.util.HashSet; +import java.util.Set; + +public class NumberOfDifferentIntegersInString { + public int numDifferentIntegers(String word) { + final Set uniqueIntegers = integersInString(word); + return uniqueIntegers.size(); + } + + private Set integersInString(String s) { + final Set integers = new HashSet<>(); + boolean inNumber = false; + StringBuilder current = new StringBuilder(); + for (int index = 0 ; index < s.length() ; index++) { + if (Character.isDigit(s.charAt(index))) { + if (!inNumber) inNumber = true; + current.append(s.charAt(index) == '0' && current.length() == 0 ? "" : s.charAt(index)); + if (index == s.length() - 1) integers.add(current.toString()); + } else if (inNumber) { + inNumber = false; + integers.add(current.toString()); + current = new StringBuilder(); + } + } + return integers; + } +} diff --git a/src/NumberOfDistinctAverages.java b/src/NumberOfDistinctAverages.java new file mode 100644 index 0000000..26e4e04 --- /dev/null +++ b/src/NumberOfDistinctAverages.java @@ -0,0 +1,21 @@ +// https://leetcode.com/problems/number-of-distinct-averages +// T: O(Nlog(N)) +// S: O(N) + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +public class NumberOfDistinctAverages { + public int distinctAverages(int[] nums) { + final Set set = new HashSet<>(); + Arrays.sort(nums); + + for (int i = 0 ; i < nums.length / 2 ; i++) { + int sum = nums[i] + nums[nums.length - 1 - i]; + set.add(sum); + } + + return set.size(); + } +} diff --git a/src/NumberOfEmployeesWhoMetTheTarget.java b/src/NumberOfEmployeesWhoMetTheTarget.java new file mode 100644 index 0000000..225ae91 --- /dev/null +++ b/src/NumberOfEmployeesWhoMetTheTarget.java @@ -0,0 +1,15 @@ +// https://leetcode.com/problems/number-of-employees-who-met-the-target +// T: O(N) +// S: O(1) + +public class NumberOfEmployeesWhoMetTheTarget { + public int numberOfEmployeesWhoMetTarget(int[] hours, int target) { + int employeesWhoMetTarget = 0; + for (int hour : hours) { + if (hour >= target) { + employeesWhoMetTarget++; + } + } + return employeesWhoMetTarget; + } +} diff --git a/src/NumberOfEquivalentDominoPairs.java b/src/NumberOfEquivalentDominoPairs.java new file mode 100644 index 0000000..a999005 --- /dev/null +++ b/src/NumberOfEquivalentDominoPairs.java @@ -0,0 +1,37 @@ +import java.util.HashMap; +import java.util.Map; + +public class NumberOfEquivalentDominoPairs { + private static class Domino { + private final int number; + + Domino(int[] array) { + number = Math.min(array[0], array[1]) * 10 + Math.max(array[0], array[1]); + } + + @Override + public boolean equals(Object o) { + Domino domino = (Domino) o; + return number == domino.number; + } + + @Override + public int hashCode() { + return number; + } + } + + public int numEquivDominoPairs(int[][] dominoes) { + final Map dominoesFrequencies = new HashMap<>(); + Domino d; + for (int[] domino : dominoes) { + d = new Domino(domino); + dominoesFrequencies.put(d, dominoesFrequencies.getOrDefault(d, 0) + 1); + } + int equivalentPairs = 0; + for (int frequency : dominoesFrequencies.values()) { + equivalentPairs += (frequency * (frequency - 1)) / 2; + } + return equivalentPairs; + } +} diff --git a/src/NumberOfEvenAndOddBits.java b/src/NumberOfEvenAndOddBits.java new file mode 100644 index 0000000..fafa92e --- /dev/null +++ b/src/NumberOfEvenAndOddBits.java @@ -0,0 +1,27 @@ +// https://leetcode.com/problems/number-of-even-and-odd-bits +// T: O(log(N)) +// S: O(1) + +public class NumberOfEvenAndOddBits { + public int[] evenOddBit(int n) { + return new int[] { evenBits(n), oddBits(n)}; + } + + private int evenBits(int x) { + int bits = 0, num = 1; + while (num <= x) { + bits += (x & num) > 0 ? 1 : 0; + num <<= 2; + } + return bits; + } + + private int oddBits(int x) { + int bits = 0, num = 2; + while (num <= x) { + bits += (x & num) > 0 ? 1 : 0; + num <<= 2; + } + return bits; + } +} diff --git a/src/NumberOfGoodPairs.java b/src/NumberOfGoodPairs.java new file mode 100644 index 0000000..e4d4f96 --- /dev/null +++ b/src/NumberOfGoodPairs.java @@ -0,0 +1,29 @@ +// https://leetcode.com/problems/number-of-good-pairs +// T: O(n) +// S: O(n) + +import java.util.HashMap; +import java.util.Map; + +public class NumberOfGoodPairs { + public int numIdenticalPairs(int[] nums) { + Map frequencies = getFrequencies(nums); + int goodPairs = 0; + for (int frequency : frequencies.values()) { + goodPairs += nC2(frequency); + } + return goodPairs; + } + + private int nC2(int x) { + return (x * (x - 1)) / 2; + } + + private Map getFrequencies(int[] array) { + final Map frequencies = new HashMap<>(); + for (int element : array) { + frequencies.put(element, frequencies.getOrDefault(element, 0) + 1); + } + return frequencies; + } +} diff --git a/src/NumberOfIslands.java b/src/NumberOfIslands.java new file mode 100644 index 0000000..e820177 --- /dev/null +++ b/src/NumberOfIslands.java @@ -0,0 +1,52 @@ +// https://leetcode.com/problems/number-of-islands +// T: O(m * n) +// T: O(m * n) + +public class NumberOfIslands { + private static final char VISITED = '0'; + private static final char ISLAND = '1'; + + public int numIslands(char[][] grid) { + final int rows = grid.length, columns = grid[0].length; + int islands = 0; + + for (int row = 0 ; row < rows ; row++) { + for (int column = 0 ; column < columns ; column++) { + if (isIsland(grid[row][column])) { + islands++; + markIslandAsSeen(grid, row, column); + } + } + } + + return islands; + } + + private boolean isIsland(char c) { + return c == ISLAND; + } + + private void markIslandAsSeen(char[][] grid, int row, int column) { + if (!isValidPosition(grid, row, column) || !isIsland(grid[row][column])) return; + markVisited(grid, row, column); + markIslandAsSeen(grid, row - 1, column); + markIslandAsSeen(grid, row, column + 1); + markIslandAsSeen(grid, row + 1, column); + markIslandAsSeen(grid, row, column - 1); + } + + private boolean isValidPosition(char[][] grid, int row, int column) { + return row >= 0 + && row < grid.length + && column >= 0 + && column < grid[0].length; + } + + private boolean alreadyVisited(char c) { + return c == VISITED; + } + + private void markVisited(char[][] grid, int row, int column) { + grid[row][column] = VISITED; + } +} diff --git a/src/NumberOfLinesToWriteInString.java b/src/NumberOfLinesToWriteInString.java new file mode 100644 index 0000000..9d00849 --- /dev/null +++ b/src/NumberOfLinesToWriteInString.java @@ -0,0 +1,14 @@ +public class NumberOfLinesToWriteInString { + public int[] numberOfLines(int[] widths, String string) { + int lines = 1, width = 0; + for (char character : string.toCharArray()) { + if (width + widths[character - 'a'] <= 100) { + width += widths[character - 'a']; + } else { + lines++; + width = widths[character - 'a']; + } + } + return new int[] {lines, width}; + } +} diff --git a/src/NumberOfProvinces.java b/src/NumberOfProvinces.java new file mode 100644 index 0000000..728d922 --- /dev/null +++ b/src/NumberOfProvinces.java @@ -0,0 +1,71 @@ +// https://leetcode.com/problems/number-of-provinces +// T: O(N^2) +// S: O(N) + +public class NumberOfProvinces { + private static final class DisjointSet { + private final int[] array, rank; + + public DisjointSet(int size) { + this.array = new int[size]; + this.rank = new int[size]; + for (int i = 0 ; i < size ; i++) { + array[i] = i; + rank[i] = 1; + } + } + + // T: O(1) + public int find(int x) { + if (x == array[x]) { + return x; + } + final int rank = find(array[x]); + array[x] = rank; + return rank; + } + + // T: O(1) + public boolean areConnected(int x, int y) { + return find(x) == find(y); + } + + // T: O(1) + public void union(int x, int y) { + final int rootX = find(x), rootY = find(y); + if (rootX == rootY) { + return; + } + if (array[rootX] > array[rootY]) { + array[rootY] = rootX; + } else if (array[rootX] < array[rootY]) { + array[rootX] = rootY; + } else { + array[rootY] = rootX; + rank[rootX]++; + } + } + + private int size() { + return array.length; + } + } + + // T: O(n^2) + public int findCircleNum(int[][] isConnected) { + final int cities = isConnected.length; + final DisjointSet disjointSet = new DisjointSet(cities); + int provinces = cities; + + for (int i = 0 ; i < cities ; i++) { + for (int j = i + 1 ; j < cities ; j++) { + if (isConnected[i][j] == 1 && disjointSet.find(i) != disjointSet.find(j)) { + disjointSet.union(i, j); + provinces--; + } + } + } + + return provinces; + } +} diff --git a/src/NumberOfRecentCalls.java b/src/NumberOfRecentCalls.java new file mode 100644 index 0000000..6ef8da0 --- /dev/null +++ b/src/NumberOfRecentCalls.java @@ -0,0 +1,32 @@ +public class NumberOfRecentCalls { + class RecentCounter { + private Node head; + private Node tail; + private int size = 0; + + public int ping(int t) { + size++; + if (head == null) { + head = new Node(t); + tail = head; + } else { + tail.next = new Node(t); + tail = tail.next; + } + while (head.val < t - 3000) { + head = head.next; + size--; + } + return size; + } + + private class Node { + int val; + Node next; + + Node(final int val) { + this.val = val; + } + } + } +} diff --git a/src/NumberOfRectanglesThatCanFormTheLargestSquare.java b/src/NumberOfRectanglesThatCanFormTheLargestSquare.java new file mode 100644 index 0000000..04b1694 --- /dev/null +++ b/src/NumberOfRectanglesThatCanFormTheLargestSquare.java @@ -0,0 +1,15 @@ +public class NumberOfRectanglesThatCanFormTheLargestSquare { + public int countGoodRectangles(int[][] rectangles) { + int maxLength = 0, frequency = 0, length; + for (int[] rectangle : rectangles) { + length = Math.min(rectangle[0], rectangle[1]); + if (length > maxLength) { + maxLength = length; + frequency = 1; + } else if (length == maxLength) { + frequency++; + } + } + return frequency; + } +} diff --git a/src/NumberOfSeniorCitizens.java b/src/NumberOfSeniorCitizens.java new file mode 100644 index 0000000..edf10fe --- /dev/null +++ b/src/NumberOfSeniorCitizens.java @@ -0,0 +1,18 @@ +// https://leetcode.com/problems/number-of-senior-citizens +// T: O(N) +// S: O(1) + +public class NumberOfSeniorCitizens { + public int countSeniors(String[] details) { + int seniors = 0; + for (String detail : details) { + int age = getAge(detail); + if (age > 60) seniors++; + } + return seniors; + } + + private int getAge(String detail) { + return Integer.parseInt(detail.substring(11, 13)); + } +} diff --git a/src/NumberOfStepsToReduceANumberToZero.java b/src/NumberOfStepsToReduceANumberToZero.java new file mode 100644 index 0000000..3402b00 --- /dev/null +++ b/src/NumberOfStepsToReduceANumberToZero.java @@ -0,0 +1,11 @@ +public class NumberOfStepsToReduceANumberToZero { + public int numberOfSteps(int num) { + int steps = 0; + while (num > 0) { + steps++; + if ((num & 1) == 0) num >>= 1; + else num -= 1; + } + return steps; + } +} diff --git a/src/NumberOfStringsThatAppearAsSubstringsInWord.java b/src/NumberOfStringsThatAppearAsSubstringsInWord.java new file mode 100644 index 0000000..93ff8e2 --- /dev/null +++ b/src/NumberOfStringsThatAppearAsSubstringsInWord.java @@ -0,0 +1,11 @@ +public class NumberOfStringsThatAppearAsSubstringsInWord { + public int numOfStrings(String[] patterns, String word) { + int substrings = 0; + for (String pattern : patterns) { + if (word.contains(pattern)) { + substrings++; + } + } + return substrings; + } +} diff --git a/src/NumberOfStudentsDoingHomeworkAtGivenTime.java b/src/NumberOfStudentsDoingHomeworkAtGivenTime.java new file mode 100644 index 0000000..0cb000a --- /dev/null +++ b/src/NumberOfStudentsDoingHomeworkAtGivenTime.java @@ -0,0 +1,11 @@ +public class NumberOfStudentsDoingHomeworkAtGivenTime { + public int busyStudent(int[] startTime, int[] endTime, int queryTime) { + int students = 0; + for (int index = 0 ; index < startTime.length ; index++) { + if (startTime[index] <= queryTime && queryTime <= endTime[index]) { + students++; + } + } + return students; + } +} diff --git a/src/NumberOfStudentsUnableToEatLunch.java b/src/NumberOfStudentsUnableToEatLunch.java new file mode 100644 index 0000000..675f3dd --- /dev/null +++ b/src/NumberOfStudentsUnableToEatLunch.java @@ -0,0 +1,28 @@ +import java.util.LinkedList; +import java.util.Queue; + +public class NumberOfStudentsUnableToEatLunch { + public int countStudents(int[] students, int[] sandwiches) { + final Queue studentQueue = queueFrom(students); + int replacementStudents = 0, stack = 0; + while (!studentQueue.isEmpty() && replacementStudents < studentQueue.size()) { + if (studentQueue.peek() == sandwiches[stack]) { + stack++; + studentQueue.poll(); + replacementStudents = 0; + } else { + studentQueue.add(studentQueue.poll()); + replacementStudents++; + } + } + return studentQueue.size(); + } + + private Queue queueFrom(int[] array) { + final Queue queue = new LinkedList<>(); + for (int element : array) { + queue.add(element); + } + return queue; + } +} diff --git a/src/NumberOfUnequalTripletsInArray.java b/src/NumberOfUnequalTripletsInArray.java new file mode 100644 index 0000000..5a0cbc7 --- /dev/null +++ b/src/NumberOfUnequalTripletsInArray.java @@ -0,0 +1,21 @@ +// https://leetcode.com/problems/number-of-unequal-triplets-in-array +// T: O(N) +// S: O(N) + +import java.util.HashMap; +import java.util.Map; + +public class NumberOfUnequalTripletsInArray { + public int unequalTriplets(int[] array) { + final Map frequency = new HashMap<>(); + int pairs = 0, triplets = 0; + for (int index = 0 ; index < array.length ; index++) { + frequency.put(array[index], frequency.getOrDefault(array[index], 0) + 1); + final int pairsWithElement = index + 1 - frequency.getOrDefault(array[index], 0); + pairs += pairsWithElement; + final int pairsWithoutElement = pairs - pairsWithElement * frequency.getOrDefault(array[index], 0); + triplets += pairsWithoutElement; + } + return triplets; + } +} diff --git a/src/NumberOfValidClockTimes.java b/src/NumberOfValidClockTimes.java new file mode 100644 index 0000000..a4114b5 --- /dev/null +++ b/src/NumberOfValidClockTimes.java @@ -0,0 +1,35 @@ +// https://leetcode.com/problems/number-of-valid-clock-times +// T: O(1) +// S: O(1) + +public class NumberOfValidClockTimes { + private static final char QUESTION = '?'; + + public int countTime(String time) { + return numberOfValidHourStrings(time.substring(0, 2)) * numberOfValidMinuteStrings(time.substring(3)); + } + + private int numberOfValidMinuteStrings(String mm) { + final char first = mm.charAt(0), second = mm.charAt(1); + + if (first == QUESTION && second == QUESTION) return 60; + if (first != QUESTION && second != QUESTION) return 1; + if (first != QUESTION) return 10; + return 6; + } + + private int numberOfValidHourStrings(String hh) { + final char first = hh.charAt(0), second = hh.charAt(1); + + if (first == QUESTION && second == QUESTION) return 24; + if (first != QUESTION && second != QUESTION) return 1; + + if (first != QUESTION) { + if (first == '2') return 4; + return 10; + } + + if (second > '3') return 2; + return 3; + } +} diff --git a/src/NumberOfValidWordsInASentence.java b/src/NumberOfValidWordsInASentence.java new file mode 100644 index 0000000..c3f1195 --- /dev/null +++ b/src/NumberOfValidWordsInASentence.java @@ -0,0 +1,50 @@ +// https://leetcode.com/problems/number-of-valid-words-in-a-sentence +// T: O(|sentence|) +// S: O(|sentence|) + +import java.util.Set; + +public class NumberOfValidWordsInASentence { + private static final Set PUNCTUATIONS = Set.of('!', '.', ','); + + public int countValidWords(String sentence) { + StringBuilder word = new StringBuilder(); + int validWords= 0; + for (int i = 0 ; i < sentence.length() ; i++) { + if (sentence.charAt(i) == ' ') { + validWords += isValidWord(word) ? 1 : 0; + word = new StringBuilder(); + } else word.append(sentence.charAt(i)); + } + return validWords + (isValidWord(word) ? 1 : 0); + } + + private boolean isValidWord(StringBuilder s) { + if (s.length() == 0) return false; + for (int i = 0, hyphens = 0 ; i < s.length() ; i++) { + if (isDigit(s.charAt(i))) return false; + else if (isHyphen(s.charAt(i))) { + if (hyphens > 0) return false; + hyphens++; + if (i == 0 || i == s.length() - 1 || !isAlphabet(s.charAt(i + 1))) return false; + } else if (isPunctuationMark(s.charAt(i)) && i < s.length() - 1) return false; + } + return true; + } + + private boolean isDigit(char c) { + return Character.isDigit(c); + } + + private boolean isHyphen(char c) { + return c == '-'; + } + + private boolean isAlphabet(char c) { + return Character.isAlphabetic(c); + } + + private boolean isPunctuationMark(char c) { + return PUNCTUATIONS.contains(c); + } +} diff --git a/src/OccurrencesAfterBigram.java b/src/OccurrencesAfterBigram.java new file mode 100644 index 0000000..d089210 --- /dev/null +++ b/src/OccurrencesAfterBigram.java @@ -0,0 +1,33 @@ +import java.util.ArrayList; +import java.util.List; + +public class OccurrencesAfterBigram { + public String[] findOcurrences(String text, String first, String second) { + List result = new ArrayList<>(); + for (int fromIndex = 0 ; fromIndex < text.length() ; fromIndex += first.length() + 1) { + fromIndex = text.indexOf(first, fromIndex); + if (fromIndex == -1) break; + if (areEqual(text, fromIndex + first.length() + 1, second) + && fromIndex + first.length() + second.length() + 2 < text.length()) { + result.add(nextWord(text, fromIndex + first.length() + second.length() + 2)); + } + } + return result.toArray(new String[0]); + } + + private boolean areEqual(String text, int fromIndex, String pattern) { + if (pattern.length() > text.length() - fromIndex) return false; + for (int index = fromIndex ; index < text.length() && index - fromIndex < pattern.length() ; index++) { + if (text.charAt(index) != pattern.charAt(index - fromIndex)) return false; + } + return true; + } + + private String nextWord(String text, int startIndex) { + StringBuilder result = new StringBuilder(); + for (int index = startIndex ; index < text.length() && text.charAt(index) != ' ' ; index++) { + result.append(text.charAt(index)); + } + return result.toString(); + } +} diff --git a/src/OddStringDifference.java b/src/OddStringDifference.java new file mode 100644 index 0000000..af3219c --- /dev/null +++ b/src/OddStringDifference.java @@ -0,0 +1,33 @@ +// https://leetcode.com/problems/odd-string-difference +// T: O(|words| * |words[i]|) +// S: O(|words[i]|) + +import java.util.Arrays; + +public class OddStringDifference { + public String oddString(String[] words) { + final int[] diff1 = stringDiffArray(words[0]); + final int[] diff2 = stringDiffArray(words[1]); + + if (Arrays.equals(diff1, diff2)) { + for (int index = 2 ; index < words.length ; index++) { + final int[] diff = stringDiffArray(words[index]); + if (!Arrays.equals(diff1, diff)) return words[index]; + } + } else { + final int[] diff3 = stringDiffArray(words[2]); + if (Arrays.equals(diff1, diff3)) return words[1]; + return words[0]; + } + + return words[0]; + } + + private int[] stringDiffArray(String word) { + final int[] array = new int[word.length() - 1]; + for (int index = 0 ; index < word.length() - 1 ; index++) { + array[index] = word.charAt(index) - word.charAt(index + 1); + } + return array; + } +} diff --git a/src/OneBitAndTwoBitCharacters.java b/src/OneBitAndTwoBitCharacters.java new file mode 100644 index 0000000..d512f34 --- /dev/null +++ b/src/OneBitAndTwoBitCharacters.java @@ -0,0 +1,12 @@ +public class OneBitAndTwoBitCharacters { + public boolean isOneBitCharacter(int[] bits) { + for (int index = 0 ; index < bits.length ; index++) { + if (bits[index] == 1) { + index++; + } else if (bits[index] == 0 && index == bits.length - 1) { + return true; + } + } + return false; + } +} diff --git a/src/OptimizeWaterDistributionInAVillage.java b/src/OptimizeWaterDistributionInAVillage.java new file mode 100644 index 0000000..86fa90f --- /dev/null +++ b/src/OptimizeWaterDistributionInAVillage.java @@ -0,0 +1,81 @@ +// https://leetcode.com/problems/optimize-water-distribution-in-a-village +// N = n, E = |pipes| +// T: O(N + (N + E) log(N + E) + E al(N)) = O((N + E) log(N + E)) al = inverse Ackermann function +// S: O(N + E) + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; + +public class OptimizeWaterDistributionInAVillage { + private static final class DisjointSet { + private final int[] roots, rank; + + public DisjointSet(int size) { + roots = new int[size]; + rank = new int[size]; + for (int i = 0 ; i < size ; i++) { + roots[i] = i; + rank[i] = 1; + } + } + + public int find(int num) { + if (num == roots[num]) { + return num; + } + return roots[num] = find(roots[num]); + } + + public boolean isConnected(int x, int y) { + return find(x) == find(y); + } + + public void union(int x, int y) { + final int rootX = find(x), rootY = find(y); + if (rootX == rootY) { + return; + } + if (rank[rootX] > rank[rootY]) { + roots[rootY] = rootX; + } else if (rank[rootX] < rank[rootY]) { + roots[rootX] = rootY; + } else { + roots[rootY] = rootX; + rank[rootX]++; + } + } + } + + // Kruskal's algorithm to find MST in unordered weighted graph + public int minCostToSupplyWater(int n, int[] wells, int[][] pipes) { + final List edges = new ArrayList<>(pipes.length + n + 1); + final DisjointSet disjointSet = new DisjointSet(n + 1); + + // add extra vertex and extra edges + for (int i = 0 ; i < n ; i++) { + edges.add(new int[] {0, i + 1, wells[i]}); + } + + // add preexisting edges + edges.addAll(Arrays.asList(pipes)); + + // sort edges according to weight + edges.sort(Comparator.comparingInt(a -> a[2])); + + int totalCost = 0; + for (int[] edge : edges) { + final int house1 = edge[0], house2 = edge[1], cost = edge[2]; + if (!disjointSet.isConnected(house1, house2)) { + disjointSet.union(house1, house2); + totalCost += cost; + n--; + if (n == 0) { + break; + } + } + } + return totalCost; + } +} diff --git a/src/PalindromeLinkedList.java b/src/PalindromeLinkedList.java index 9fd1978..3abba8b 100644 --- a/src/PalindromeLinkedList.java +++ b/src/PalindromeLinkedList.java @@ -2,10 +2,6 @@ import java.util.List; public class PalindromeLinkedList { - private static class ListNode { - int val; - ListNode next; - } public static boolean isPalindrome(ListNode head) { List list = listFrom(head); diff --git a/src/PalindromeNumber.java b/src/PalindromeNumber.java index 6b34ce2..038431d 100644 --- a/src/PalindromeNumber.java +++ b/src/PalindromeNumber.java @@ -3,19 +3,16 @@ import java.util.Scanner; public class PalindromeNumber { - public static void main(String[] args) { - Scanner scanner = new Scanner(System.in); - int number = scanner.nextInt(); - System.out.println(isPalindrome(number)); - } - private static boolean isPalindrome(int number) { - String representation = number + ""; - for (int index = 0 ; index < representation.length() / 2 ; index++) { - if (representation.charAt(index) != representation.charAt(representation.length() - 1 - index)) { - return false; - } + public boolean isPalindrome(int number) { + if (number < 0 || (number % 10 == 0 && number != 0)) { + return false; + } + int reverse = 0; + while (number > reverse) { + reverse = 10 * reverse + number % 10; + number /= 10; } - return true; + return number == reverse || number == reverse / 10; } } diff --git a/src/PalindromePartitioning.java b/src/PalindromePartitioning.java new file mode 100644 index 0000000..ed20a1d --- /dev/null +++ b/src/PalindromePartitioning.java @@ -0,0 +1,30 @@ +// https://leetcode.com/problems/palindrome-partitioning +// T: O(n * 2^n) +// S: O(n) for recursion call stack + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +public class PalindromePartitioning { + public List> partition(String s) { + final int length = s.length(); + final boolean[][] dp = new boolean[length][length]; + final List> result = new ArrayList<>(); + addValidPartitions(s, 0, dp, result, new LinkedList<>()); + return result; + } + + private void addValidPartitions(String s, int start, boolean[][] dp, List> result, LinkedList current) { + if (start == s.length()) result.add(new ArrayList<>(current)); + + for (int end = start ; end < s.length() ; end++) { + if (s.charAt(start) == s.charAt(end) && (end - start <= 2 || dp[start + 1][end - 1])) { + dp[start][end] = true; + current.addLast(s.substring(start, end + 1)); + addValidPartitions(s, end + 1, dp, result, current); + current.pollLast(); + } + } + } +} diff --git a/src/PalindromePermutation.java b/src/PalindromePermutation.java new file mode 100644 index 0000000..91d8f6e --- /dev/null +++ b/src/PalindromePermutation.java @@ -0,0 +1,32 @@ +// https://leetcode.com/problems/palindrome-permutation +// T: O(|s|) +// S: O(|s|) + +import java.util.HashMap; +import java.util.Map; + +public class PalindromePermutation { + public boolean canPermutePalindrome(String s) { + final Map frequencies = getCharacterFrequencies(s); + return getNumberOfOddChars(frequencies) <= 1; + } + + private static Map getCharacterFrequencies(String string) { + final Map result = new HashMap<>(); + for (int i = 0 ; i < string.length() ; i++) { + final char c = string.charAt(i); + result.put(c, result.getOrDefault(c, 0) + 1); + } + return result; + } + + private static int getNumberOfOddChars(Map frequencies) { + int result = 0; + for (int freq : frequencies.values()) { + if (freq % 2 == 1) { + result++; + } + } + return result; + } +} diff --git a/src/ParallelCourses.java b/src/ParallelCourses.java new file mode 100644 index 0000000..0756749 --- /dev/null +++ b/src/ParallelCourses.java @@ -0,0 +1,73 @@ +// https://leetcode.com/problems/parallel-courses +// T: O(N + E) +// S: O(N + E) + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class ParallelCourses { + public int minimumSemesters(int n, int[][] relations) { + final Map> graph = createGraph(relations); + final int[] inDegree = computeInDegree(relations, n); + return minimumSemesters(graph, inDegree); + } + + // Kahn's algorithm T: O(N + E), S: O(N) + private static int minimumSemesters(Map> graph, int[] inDegree) { + Set noPrerequisites = coursesWithoutPrerequisites(inDegree); + int minSemesters = 0; + + while (!noPrerequisites.isEmpty()) { + final Set newCourses = new HashSet<>(); + for (int course : noPrerequisites) { + inDegree[course]--; + for (int neighbour : graph.getOrDefault(course, new HashSet<>())) { + inDegree[neighbour]--; + if (inDegree[neighbour] == 0) { + newCourses.add(neighbour); + } + } + graph.remove(course); + } + noPrerequisites = newCourses; + minSemesters++; + } + + return graph.isEmpty() ? minSemesters : -1; + } + + // T: O(E), S: O(N) + private static int[] computeInDegree(int[][] edges, int n) { + final int[] inDegree = new int[n]; + for (int[] edge : edges) { + final int to = edge[1] - 1; + inDegree[to]++; + } + return inDegree; + } + + // T: O(N), S: O(N) + private static Set coursesWithoutPrerequisites(int[] inDegree) { + final Set set = new HashSet<>(); + for (int i = 0 ; i < inDegree.length ; i++) { + if (inDegree[i] == 0) { + set.add(i); + } + } + return set; + } + + // T: O(E), S: O(E) + private static Map> createGraph(int[][] edges) { + final Map> graph = new HashMap<>(); + for (int[] edge : edges) { + final int from = edge[0] - 1, to = edge[1] - 1; + final Set fromNeighbours = graph.getOrDefault(from, new HashSet<>()); + fromNeighbours.add(to); + graph.putIfAbsent(from, fromNeighbours); + } + return graph; + } +} diff --git a/src/PartitionArrayIntoThreePartsWithEqualSum.java b/src/PartitionArrayIntoThreePartsWithEqualSum.java new file mode 100644 index 0000000..7bdba86 --- /dev/null +++ b/src/PartitionArrayIntoThreePartsWithEqualSum.java @@ -0,0 +1,17 @@ +import java.util.Arrays; + +public class PartitionArrayIntoThreePartsWithEqualSum { + public boolean canThreePartsEqualSum(int[] array) { + final int totalSum = Arrays.stream(array).sum(); + if (totalSum % 3 != 0) return false; + int count = 0; + for (int index = 0, sum = 0; index < array.length - 1 ; index++) { + sum += array[index]; + if (sum == totalSum / 3) { + count++; + sum = 0; + } + } + return count >= 2; + } +} diff --git a/src/PartitionList.java b/src/PartitionList.java new file mode 100644 index 0000000..04b718d --- /dev/null +++ b/src/PartitionList.java @@ -0,0 +1,24 @@ +// https://leetcode.com/problems/partition-list +// T: O(N) +// S: O(1) + +public class PartitionList { + + public ListNode partition(ListNode head, int x) { + ListNode beforeHead = new ListNode(), beforeTemp = beforeHead; + ListNode afterHead = new ListNode(), afterTemp = afterHead; + while (head != null) { + if (head.val < x) { + beforeTemp.next = head; + beforeTemp = beforeTemp.next; + } else { + afterTemp.next = head; + afterTemp = afterTemp.next; + } + head = head.next; + } + afterTemp.next = null; + beforeTemp.next = afterHead.next; + return beforeHead.next; + } +} diff --git a/src/PassThePillow.java b/src/PassThePillow.java new file mode 100644 index 0000000..d4cf152 --- /dev/null +++ b/src/PassThePillow.java @@ -0,0 +1,15 @@ +// https://leetcode.com/problems/pass-the-pillow +// T: O(1) +// S: O(1) + +public class PassThePillow { + public int passThePillow(int n, int time) { + final int direction = (int) Math.ceil((double) time / (n - 1)); + final int multiplier = direction % 2 == 0 ? -1 : 1; + final int steps = time - (direction - 1) * (n - 1); + if (multiplier == 1) { + return steps + 1; + } + return n - steps; + } +} diff --git a/src/PathCrossing.java b/src/PathCrossing.java new file mode 100644 index 0000000..af5a161 --- /dev/null +++ b/src/PathCrossing.java @@ -0,0 +1,46 @@ +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; + +public class PathCrossing { + public boolean isPathCrossing(String path) { + Set visitedPoints = new HashSet<>(); + visitedPoints.add(new Point(0, 0)); + for (int index = 0, x = 0, y = 0 ; index < path.length() ; index++) { + switch (path.charAt(index)) { + case 'N' -> y++; + case 'E' -> x++; + case 'S' -> y--; + case 'W' -> x--; + } + Point newPosition = new Point(x, y); + if (visitedPoints.contains(newPosition)) return true; + visitedPoints.add(newPosition); + } + return false; + } + + private static final class Point { + private final int x; + private final int y; + + private Point(int x, int y) { + this.x = x; + this.y = y; + } + + @Override + public boolean equals(Object obj) { + if (obj == this) return true; + if (obj == null || obj.getClass() != this.getClass()) return false; + var that = (Point) obj; + return this.x == that.x && + this.y == that.y; + } + + @Override + public int hashCode() { + return Objects.hash(x, y); + } + } +} diff --git a/src/PathSum.java b/src/PathSum.java index 8bf006a..94e9ed4 100644 --- a/src/PathSum.java +++ b/src/PathSum.java @@ -1,9 +1,4 @@ public class PathSum { - private static class TreeNode { - int val; - TreeNode left; - TreeNode right; - } public static boolean hasPathSum(TreeNode root, int sum) { return root != null && hasPathSum(root, sum, root.val); diff --git a/src/PathSumII.java b/src/PathSumII.java new file mode 100644 index 0000000..cb6b805 --- /dev/null +++ b/src/PathSumII.java @@ -0,0 +1,43 @@ +// https://leetcode.com/problems/path-sum-ii +// T: O(n * log(n)) +// S: O(n * log(n)) + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +public class PathSumII { + public List> pathSum(TreeNode root, int targetSum) { + final List> result = new ArrayList<>(); + if (root == null) return result; + pathSum(root, targetSum, result); + return result; + } + + private void pathSum(TreeNode root, int targetSum, final List> result) { + pathSum(root, targetSum, result, 0, new LinkedList<>()); + } + + private void pathSum(TreeNode root, int targetSum, final List> result, int sum, LinkedList path) { + path.addLast(root.val); + sum += root.val; + + if (isLeafNode(root)) { + if (sum == targetSum) result.add(new ArrayList<>(path)); + return; + } + + if (root.left != null) { + pathSum(root.left, targetSum, result, sum, path); + path.removeLast(); + } + if (root.right != null) { + pathSum(root.right, targetSum, result, sum, path); + path.removeLast(); + } + } + + private boolean isLeafNode(TreeNode root) { + return root.left == null && root.right == null; + } +} diff --git a/src/PathWithMaximumProbability.java b/src/PathWithMaximumProbability.java new file mode 100644 index 0000000..df05fd4 --- /dev/null +++ b/src/PathWithMaximumProbability.java @@ -0,0 +1,66 @@ +// https://leetcode.com/problems/path-with-maximum-probability +// T: O(E + N + E logN) +// S: O(E + N) + +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.PriorityQueue; +import java.util.Queue; + +public class PathWithMaximumProbability { + private record Pair(int vertex, double probability) {} + + public static double maxProbability(int n, int[][] edges, double[] probabilities, int start, int end) { + final Map> graph = createGraph(edges, probabilities); + final Map distances = dijkstra(graph, start, end); + return distances.getOrDefault(end, 0.0); + } + + private static Map> createGraph(int[][] edges, double[] probabilities) { + final Map> graph = new HashMap<>(); + int k = 0; + for (int[] edge : edges) { + final int from = edge[0], to = edge[1]; + final double weight = probabilities[k++]; + final Map fromNeighbours = graph.getOrDefault(from, new HashMap<>()); + final Map toNeighbours = graph.getOrDefault(to, new HashMap<>()); + fromNeighbours.put(to, weight); + toNeighbours.put(from, weight); + graph.putIfAbsent(from, fromNeighbours); + graph.putIfAbsent(to, toNeighbours); + } + return graph; + } + + private static Map dijkstra(Map> graph, int start, int end) { + final Map distances = new HashMap<>(); + final Queue minHeap = new PriorityQueue<>(Comparator.comparingDouble(a -> a.probability)); + minHeap.add(new Pair(start, 1)); + distances.put(start, 1.0); + + while (!minHeap.isEmpty()) { + final Pair pair = minHeap.poll(); + + if (pair.vertex == end) { + break; + } + + for (Map.Entry neighbour : graph.getOrDefault(pair.vertex, new HashMap<>()).entrySet()) { + final int edgeVertex = neighbour.getKey(); + final double edgeWeight = neighbour.getValue(); + final double currentProbability = distances.getOrDefault(edgeVertex, 0.0); + final double edgeProbability = Math.max( + currentProbability, + pair.probability * edgeWeight + ); + if (edgeProbability > currentProbability) { + distances.put(edgeVertex, edgeProbability); + minHeap.add(new Pair(edgeVertex, edgeProbability)); + } + } + } + + return distances; + } +} diff --git a/src/PathWithMinimumEffort.java b/src/PathWithMinimumEffort.java new file mode 100644 index 0000000..58c27e5 --- /dev/null +++ b/src/PathWithMinimumEffort.java @@ -0,0 +1,65 @@ +// https://leetcode.com/problems/path-with-minimum-effort +// T: O(m * n * log(m * n)) +// S: O(m * n) + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.PriorityQueue; +import java.util.Queue; + +public class PathWithMinimumEffort { + private record Position(int x, int y) {} + + private record Info(Position position, int effort) {} + + private static final int[][] Directions = new int[][] {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; + + // T: O(m * n * log(m * n)) S: O(m * n) + public int minimumEffortPath(int[][] heights) { + final int[][] minEffort = initialiseMinEfforts(heights.length, heights[0].length); + final Queue queue = new PriorityQueue<>(Comparator.comparingInt(a -> a.effort)); + queue.add(new Info(new Position(0, 0), 0)); + + while (!queue.isEmpty()) { + final Info info = queue.poll(); + if (info.effort >= minEffort[info.position.x][info.position.y]) { + continue; + } + minEffort[info.position.x][info.position.y] = info.effort; + + for (Position position : validPositions(heights, info.position)) { + queue.add(new Info(position, Math.max(info.effort, absDiff(info.position, position, heights)))); + } + } + + return minEffort[heights.length - 1][heights[0].length - 1]; + } + + // T: O(m * n), S: O(m * n) + private static int[][] initialiseMinEfforts(int rows, int columns) { + final int[][] result = new int[rows][columns]; + for (int[] row : result) { + Arrays.fill(row, Integer.MAX_VALUE); + } + return result; + } + + // T: O(1), S: O(1) + private static int absDiff(Position p1, Position p2, int[][] heights) { + return Math.abs(heights[p1.x][p1.y] - heights[p2.x][p2.y]); + } + + // T: O(1), S: O(1) + private static List validPositions(int[][] heights, Position position) { + final List result = new ArrayList<>(); + for (int[] direction : Directions) { + final int row = position.x + direction[0], column = position.y + direction[1]; + if (row >= 0 && row < heights.length && column >= 0 && column < heights[0].length) { + result.add(new Position(row, column)); + } + } + return result; + } +} diff --git a/src/PathsInMatrixWhoseSumIsDivisibleByK.java b/src/PathsInMatrixWhoseSumIsDivisibleByK.java new file mode 100644 index 0000000..a053638 --- /dev/null +++ b/src/PathsInMatrixWhoseSumIsDivisibleByK.java @@ -0,0 +1,39 @@ +// https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k +// T: O() +// S: O() + +import java.util.LinkedList; +import java.util.Queue; + +public class PathsInMatrixWhoseSumIsDivisibleByK { + private static final int MODULO = (int) (10e9 + 7); + + public int numberOfPaths(int[][] grid, int k) { + final int rows = grid.length, columns = grid[0].length; + // row, column, currentSum + final Queue queue = new LinkedList<>(); + queue.add(new int[] {0, 0, grid[0][0]}); + + int paths = 0; + + while (!queue.isEmpty()) { + final int[] position = queue.poll(); + final int row = position[0], column = position[1], currentSum = position[2]; + if (row == rows - 1 && column == columns - 1) { + if (currentSum % k == 0) { + paths = (paths + 1) % MODULO; + } + continue; + } + + if (column + 1 < columns) { + queue.add(new int[] { row, column + 1, currentSum + grid[row][column + 1]}); + } + if (row + 1 < rows) { + queue.add(new int[] { row + 1, column, currentSum + grid[row + 1][column]}); + } + } + + return paths; + } +} diff --git a/src/PeakIndexInMountainArray.java b/src/PeakIndexInMountainArray.java new file mode 100644 index 0000000..ef629c4 --- /dev/null +++ b/src/PeakIndexInMountainArray.java @@ -0,0 +1,8 @@ +public class PeakIndexInMountainArray { + public int peakIndexInMountainArray(int[] arr) { + for (int index = 1 ; index < arr.length ; index++) { + if (arr[index] < arr[index - 1]) return index - 1; + } + return -1; + } +} diff --git a/src/PeekingIterator.java b/src/PeekingIterator.java new file mode 100644 index 0000000..8709886 --- /dev/null +++ b/src/PeekingIterator.java @@ -0,0 +1,37 @@ +// https://leetcode.com/problems/peeking-iterator +// T: O(N) +// S: O(N) + +import java.util.Iterator; + +public class PeekingIterator implements Iterator { + final private Iterator iterator; + int next; + boolean hasNext; + + public PeekingIterator(Iterator iterator) { + this.iterator = iterator; + hasNext = iterator.hasNext(); + next = iterator.hasNext() ? iterator.next() : 0; + } + + // Returns the next element in the iteration without advancing the iterator. + public Integer peek() { + return next; + } + + // hasNext() and next() should behave the same as in the Iterator interface. + // Override them if needed. + @Override + public Integer next() { + int result = next; + hasNext = iterator.hasNext(); + next = iterator.hasNext() ? iterator.next() : 0; + return result; + } + + @Override + public boolean hasNext() { + return hasNext; + } +} \ No newline at end of file diff --git a/src/PercentageOfLetterInString.java b/src/PercentageOfLetterInString.java new file mode 100644 index 0000000..d474b65 --- /dev/null +++ b/src/PercentageOfLetterInString.java @@ -0,0 +1,15 @@ +// https://leetcode.com/problems/percentage-of-letter-in-string +// T: O(|s|) +// S: O(1) + +public class PercentageOfLetterInString { + public int percentageLetter(String s, char letter) { + int count = 0; + for (int index = 0 ; index < s.length() ; index++) { + if (letter == s.charAt(index)) { + count++; + } + } + return (int) (((double) count / s.length()) * 100); + } +} diff --git a/src/PerfectSquares.java b/src/PerfectSquares.java new file mode 100644 index 0000000..bdbd698 --- /dev/null +++ b/src/PerfectSquares.java @@ -0,0 +1,44 @@ +// https://leetcode.com/problems/perfect-squares +// T: O(k + sqrt(n)) k = size of perfect squares set which is constant +// S: O(k) + +import java.util.Set; + +public class PerfectSquares { + private static final Set PERFECT_SQUARES = Set.of( + 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, + 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, + 1936, 2025, 2116, 2209, 2304, 2401, 2500, 2601, 2704, 2809, 2916, 3025, 3136, 3249, 3364, 3481, 3600, 3721, + 3844, 3969, 4096, 4225, 4356, 4489, 4624, 4761, 4900, 5041, 5184, 5329, 5476, 5625, 5776, 5929, 6084, 6241, + 6400, 6561, 6724, 6889, 7056, 7225, 7396, 7569, 7744, 7921, 8100, 8281, 8464, 8649, 8836, 9025, 9216, 9409, + 9604, 9801, 10_000, 10_201 + ); + + private boolean isSquare(int n) { + return PERFECT_SQUARES.contains(n); + } + + // Based on Lagrange's Four Square theorem, there + // are only 4 possible results: 1, 2, 3, 4. + int numSquares(int n) { + // If n is a perfect square, return 1. + if (isSquare(n)) return 1; + + // The result is 4 if and only if n can be written in the + // form of 4^k*(8*m + 7). Please refer to + // Legendre's three-square theorem. + while (n % 4 == 0) { + n >>= 2; + } + if (n % 8 == 7) return 4; + + // Check whether 2 is the result. if number can be composed as a^2 + b^2 + for(int i = 1; i * i <= n; i++) { + if (isSquare(n - i * i)) { + return 2; + } + } + + return 3; + } +} diff --git a/src/PermutationDifferenceBetweenTwoStrings.java b/src/PermutationDifferenceBetweenTwoStrings.java new file mode 100644 index 0000000..dd9a6ac --- /dev/null +++ b/src/PermutationDifferenceBetweenTwoStrings.java @@ -0,0 +1,27 @@ +// https://leetcode.com/problems/permutation-difference-between-two-strings +// T: O(N) +// S: O(1) + +import java.util.HashMap; +import java.util.Map; + +public class PermutationDifferenceBetweenTwoStrings { + public int findPermutationDifference(String s, String t) { + final Map letterIndexes = getCharacterIndexMapping(s); + int sum = 0; + + for (int i = 0 ; i < t.length() ; i++) { + sum += Math.abs(i - letterIndexes.get(t.charAt(i))); + } + + return sum; + } + + private static Map getCharacterIndexMapping(String s) { + final Map map = new HashMap<>(); + for (int i = 0 ; i < s.length() ; i++) { + map.put(s.charAt(i), i); + } + return map; + } +} diff --git a/src/Permutations.java b/src/Permutations.java new file mode 100644 index 0000000..b6d23d6 --- /dev/null +++ b/src/Permutations.java @@ -0,0 +1,76 @@ +// https://leetcode.com/problems/permutations +// T: O(n * n!) +// S: O(n * n!) + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Permutations { + private static final Map>> PERMUTATION_MASKS = new HashMap<>(); + + static { + PERMUTATION_MASKS.put(1, List.of(List.of(0))); + PERMUTATION_MASKS.put(2, List.of( + List.of(0, 1), + List.of(1, 0) + )); + PERMUTATION_MASKS.put(3, List.of( + List.of(0, 1, 2), + List.of(0, 2, 1), + List.of(1, 0, 2), + List.of(1, 2, 0), + List.of(2, 0, 1), + List.of(2, 1, 0) + )); + + for (int i = 4 ; i <= 6 ; i++) { + PERMUTATION_MASKS.put(i, getPermutationMask(i)); + } + } + + private static List> getPermutationMask(int size) { + final List> result = new ArrayList<>(); + final List> previousPermutations = PERMUTATION_MASKS.get(size - 1); + for (List mask : previousPermutations) { + for (int insertionPosition = 0 ; insertionPosition < size ; insertionPosition++) { + result.add(newPermutation(mask, insertionPosition)); + } + } + return result; + } + + private static List newPermutation(List mask, int index) { + final List result = new ArrayList<>(); + for (int i = 0 ; i < index ; i++) result.add(mask.get(i)); + result.add(mask.size()); + for (int i = index ; i < mask.size() ; i++) result.add(mask.get(i)); + return result; + } + + public List> permute(int[] nums) { + final List> results = new ArrayList<>(); + final List> permutationMasks = PERMUTATION_MASKS.get(nums.length); + for (List mask : permutationMasks) { + results.add(permute(nums, mask)); + } + return results; + } + + private List permute(int[] array, List mask) { + final int[] result = new int[array.length]; + for (int i = 0 ; i < array.length ; i++) { + result[mask.get(i)] = array[i]; + } + return toList(result); + } + + private List toList(int[] array) { + final List result = new ArrayList<>(array.length); + for (int element : array) { + result.add(element); + } + return result; + } +} diff --git a/src/PermutationsII.java b/src/PermutationsII.java new file mode 100644 index 0000000..36eb08c --- /dev/null +++ b/src/PermutationsII.java @@ -0,0 +1,42 @@ +// https://leetcode.com/problems/permutations-ii +// T: O(n * n!) +// S: O(n * n!) + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +public class PermutationsII { + public List> permuteUnique(int[] nums) { + final Map frequencies = getFrequencies(nums); + final List> result = new ArrayList<>(); + permuteUnique(nums, result, frequencies, new LinkedList<>()); + return result; + } + + private void permuteUnique(int[] array, List> result, Map frequencies, LinkedList current) { + if (current.size() == array.length) { + result.add(new ArrayList<>(current)); + return; + } + for (Map.Entry entry : frequencies.entrySet()) { + if (entry.getValue() > 0) { + entry.setValue(entry.getValue() - 1); + current.add(entry.getKey()); + permuteUnique(array, result, frequencies, current); + current.removeLast(); + entry.setValue(entry.getValue() + 1); + } + } + } + + private Map getFrequencies(int[] array) { + final Map frequencies = new HashMap<>(); + for (int element : array) { + frequencies.put(element, frequencies.getOrDefault(element, 0) + 1); + } + return frequencies; + } +} diff --git a/src/PointsThatIntersectWithCars.java b/src/PointsThatIntersectWithCars.java new file mode 100644 index 0000000..63b86ce --- /dev/null +++ b/src/PointsThatIntersectWithCars.java @@ -0,0 +1,25 @@ +// https://leetcode.com/problems/points-that-intersect-with-cars +// T: O(|nums| + |cars|) +// S: O(|cars|) + +import java.util.List; + +public class PointsThatIntersectWithCars { + public int numberOfPoints(List> nums) { + final int[] points = new int[101]; + int count = 0; + + for (final List car : nums) { + points[car.get(0) - 1]++; + points[car.get(1)]--; + } + + for (int i = 0, overlap = 0 ; i < points.length ; i++) { + overlap += points[i]; + if (overlap > 0) { + count++; + } + } + return count; + } +} diff --git a/src/PopulatingNextRightPointersInEachNode.java b/src/PopulatingNextRightPointersInEachNode.java new file mode 100644 index 0000000..0a4e0d1 --- /dev/null +++ b/src/PopulatingNextRightPointersInEachNode.java @@ -0,0 +1,63 @@ +// https://leetcode.com/problems/populating-next-right-pointers-in-each-node +// T: O(n) +// S: O(n) + +import java.util.LinkedList; +import java.util.Queue; + +public class PopulatingNextRightPointersInEachNode { + public static Node connect(Node root) { + if (root == null) return null; + + final Queue queue = new LinkedList<>(); + queue.add(root); + queue.add(null); + Node previous = null; + + while (!queue.isEmpty()) { + final Node current = queue.poll(); + if (current == null) { + previous = null; + if (!queue.isEmpty()) queue.add(null); + continue; + } + + if (previous != null) previous.next = current; + previous = current; + addChildrenToQueue(queue, current); + } + + return root; + } + + private static void addChildrenToQueue(Queue queue, Node root) { + if (root.left != null) queue.add(root.left); + if (root.right != null) queue.add(root.right); + } + + private static class Node implements TreePrinter.PrintableNode { + public int val; + public Node left; + public Node right; + public Node next; + + public Node(int val) { + this.val = val; + } + + @Override + public TreePrinter.PrintableNode getLeft() { + return left; + } + + @Override + public TreePrinter.PrintableNode getRight() { + return right; + } + + @Override + public String getText() { + return val + ""; + } + } +} diff --git a/src/PopulatingNextRightPointersInEachNodeII.java b/src/PopulatingNextRightPointersInEachNodeII.java new file mode 100644 index 0000000..0767b08 --- /dev/null +++ b/src/PopulatingNextRightPointersInEachNodeII.java @@ -0,0 +1,63 @@ +// https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii +// T: O(n) +// S: O(n) + +import java.util.LinkedList; +import java.util.Queue; + +public class PopulatingNextRightPointersInEachNodeII { + public static Node connect(Node root) { + if (root == null) return null; + + final Queue queue = new LinkedList<>(); + queue.add(root); + queue.add(null); + Node previous = null; + + while (!queue.isEmpty()) { + final Node current = queue.poll(); + if (current == null) { + previous = null; + if (!queue.isEmpty()) queue.add(null); + continue; + } + + if (previous != null) previous.next = current; + previous = current; + addChildrenToQueue(queue, current); + } + + return root; + } + + private static void addChildrenToQueue(Queue queue, Node root) { + if (root.left != null) queue.add(root.left); + if (root.right != null) queue.add(root.right); + } + + private static class Node implements TreePrinter.PrintableNode { + public int val; + public Node left; + public Node right; + public Node next; + + public Node(int val) { + this.val = val; + } + + @Override + public TreePrinter.PrintableNode getLeft() { + return left; + } + + @Override + public TreePrinter.PrintableNode getRight() { + return right; + } + + @Override + public String getText() { + return val + ""; + } + } +} diff --git a/src/PositionsOfLargeGroups.java b/src/PositionsOfLargeGroups.java new file mode 100644 index 0000000..a22c65f --- /dev/null +++ b/src/PositionsOfLargeGroups.java @@ -0,0 +1,19 @@ +import java.util.ArrayList; +import java.util.List; + +public class PositionsOfLargeGroups { + public List> largeGroupPositions(String s) { + List> result = new ArrayList<>(); + char current = s.charAt(0); + int start = 0; + for (int index = 1 ; index < s.length() ; index++) { + if (s.charAt(index) != current) { + if (index - start >= 3) result.add(List.of(start, index - 1)); + start = index; + current = s.charAt(index); + } + } + if (s.length() - start >= 3) result.add(List.of(start, s.length() - 1)); + return result; + } +} diff --git a/src/Powxn.java b/src/Powxn.java new file mode 100644 index 0000000..5f3f4fb --- /dev/null +++ b/src/Powxn.java @@ -0,0 +1,17 @@ +// https://leetcode.com/problems/powx-n +// T: O(log(n)) +// S: O(1) + +public class Powxn { + public double myPow(double x, int n) { + if (n >= 0) return power(x, n); + return 1 / power(x, -n); + } + + private double power(double x, int n) { + if (n == 0) return 1; + if (n == 1) return x; + double half = power(x, n / 2); + return half * half * (n % 2 == 0 ? 1 : x); + } +} diff --git a/src/PrimeArrangements.java b/src/PrimeArrangements.java new file mode 100644 index 0000000..c6c0d3b --- /dev/null +++ b/src/PrimeArrangements.java @@ -0,0 +1,36 @@ +public class PrimeArrangements { + private static final int[] PRIME_DENSITY = { + 0, 1, 2, 2, 3, 3, 4, 4, 4, 4, + 5, 5, 6, 6, 6, 6, 7, 7, 8, 8, + 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, + 11, 11, 11, 11, 11, 11, 12, 12, + 12, 12, 13, 13, 14, 14, 14, 14, + 15, 15, 15, 15, 15, 15, 16, 16, + 16, 16, 16, 16, 17, 17, 18, 18, + 18, 18, 18, 18, 19, 19, 19, 19, + 20, 20, 21, 21, 21, 21, 21, 21, + 22, 22, 22, 22, 23, 23, 23, 23, + 23, 23, 24, 24, 24, 24, 24, 24, + 24, 24, 25, 25, 25, 25 + }; + + private static final int MOD = 1000_000_007; + + public int numPrimeArrangements(int n) { + final int primeNumbers = PRIME_DENSITY[n - 1]; + return factorialMod(primeNumbers, factorialMod(n - primeNumbers)) % MOD; + } + + private int factorialMod(long number, final long start) { + long result = start; + while (number > 1) { + result = (result * number) % MOD; + number--; + } + return (int) result; + } + + private int factorialMod(int number) { + return factorialMod(number, 1); + } +} diff --git a/src/PrimeInDiagonal.java b/src/PrimeInDiagonal.java new file mode 100644 index 0000000..2498225 --- /dev/null +++ b/src/PrimeInDiagonal.java @@ -0,0 +1,37 @@ +// https://leetcode.com/problems/prime-in-diagonal +// m: number of rows in matrix +// n: size of numbers in matrix +// T: O(m * sqrt(n)) +// S: O(1) + +public class PrimeInDiagonal { + public int diagonalPrime(int[][] nums) { + final int rows = nums.length; + int maxPrime = 0; + // left to right diagonal + for (int row = 0 ; row < rows ; row++) { + if (row % 2 == 1 && row == rows / 2) { + continue; + } + if (isPrime(nums[row][row])) { + maxPrime = Math.max(maxPrime, nums[row][row]); + } + } + + // top right to bottom left diagonal + for (int row = 0 ; row < rows ; row++) { + if (isPrime(nums[row][rows - row - 1])) { + maxPrime = Math.max(maxPrime, nums[row][rows - row - 1]); + } + } + return maxPrime; + } + + private boolean isPrime(int x) { + if (x <= 1) return false; + for (int i = 2 ; i * i <= x ; i++) { + if (x % i == 0) return false; + } + return true; + } +} diff --git a/src/PrimeNumberOfSetBitsInBinaryRepresentation.java b/src/PrimeNumberOfSetBitsInBinaryRepresentation.java new file mode 100644 index 0000000..086b112 --- /dev/null +++ b/src/PrimeNumberOfSetBitsInBinaryRepresentation.java @@ -0,0 +1,24 @@ +public class PrimeNumberOfSetBitsInBinaryRepresentation { + private final byte[] isPrime = new byte[] {0, 0, 1, 1, 0, 1, 0, + 1, 0, 0, 0, 1, 0, + 1, 0, 0, 0, 1, 0, + 1, 0, 0, 0, 1, 0 + }; + + public int countPrimeSetBits(int left, int right) { + int primeSetBits = 0; + for (int number = left ; number <= right ; number++) { + if (isPrime[setBits(number)] == 1) primeSetBits++; + } + return primeSetBits; + } + + private int setBits(int number) { + int setBits = 0; + while (number > 0) { + setBits += number & 1; + number >>= 1; + } + return setBits; + } +} diff --git a/src/ProductOfArrayExceptItself.java b/src/ProductOfArrayExceptItself.java new file mode 100644 index 0000000..6baadff --- /dev/null +++ b/src/ProductOfArrayExceptItself.java @@ -0,0 +1,28 @@ +// https://leetcode.com/problems/product-of-array-except-self +// T: O(N) +// S: O(1) + +public class ProductOfArrayExceptItself { + + public int[] productExceptSelf(int[] nums) { + final int[] result = new int[nums.length]; + multipleWithLeftPrefix(nums, result); + multiplyWithRightPostfix(nums, result); + return result; + } + + private void multipleWithLeftPrefix(int[] numbers, int[] result) { + result[0] = 1; + for(int i = 1 ; i < numbers.length ; i++) { + result[i] = result[i - 1] * numbers[i - 1]; + } + } + + private void multiplyWithRightPostfix(int[] numbers, int[] result) { + int right = 1; + for(int i = result.length - 1 ; i >= 0 ; i--) { + result[i] *= right; + right *= numbers[i]; + } + } +} diff --git a/src/ProjectionAreaOf3DShapes.java b/src/ProjectionAreaOf3DShapes.java new file mode 100644 index 0000000..9060059 --- /dev/null +++ b/src/ProjectionAreaOf3DShapes.java @@ -0,0 +1,29 @@ +import java.util.Arrays; + +public class ProjectionAreaOf3DShapes { + public int projectionArea(int[][] grid) { + int area = 0; + final int n = grid.length; + + // z axis + for (int row = 0 ; row < n ; row++) { + for(int column = 0 ; column < n ; column++) { + area += grid[row][column] > 0 ? 1 : 0; + } + } + + // x axis + for (int[] row : grid) { + area += Arrays.stream(row).max().getAsInt(); + } + + // y axis + for (int column = 0 ; column < n ; column++) { + int columnMax = 0; + for (int row = 0 ; row < n ; row++) columnMax = Math.max(columnMax, grid[row][column]); + area += columnMax; + } + + return area; + } +} diff --git a/src/RangeAdditionII.java b/src/RangeAdditionII.java new file mode 100644 index 0000000..745e201 --- /dev/null +++ b/src/RangeAdditionII.java @@ -0,0 +1,9 @@ +public class RangeAdditionII { + public int maxCount(int m, int n, int[][] operations) { + for (int[] operation : operations) { + m = Math.min(m, operation[0]); + n = Math.min(n, operation[1]); + } + return m * n; + } +} diff --git a/src/RangeSumOfBST.java b/src/RangeSumOfBST.java new file mode 100644 index 0000000..b4fdd42 --- /dev/null +++ b/src/RangeSumOfBST.java @@ -0,0 +1,10 @@ +public class RangeSumOfBST { + public int rangeSumBST(TreeNode root, int low, int high) { + if (root == null) return 0; + if (low <= root.val && root.val <= high) { + return root.val + rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high); + } + if (root.val < low) return rangeSumBST(root.right, low, high); + return rangeSumBST(root.left, low, high); + } +} diff --git a/src/RangeSumQuery2DImmutable.java b/src/RangeSumQuery2DImmutable.java new file mode 100644 index 0000000..e35715b --- /dev/null +++ b/src/RangeSumQuery2DImmutable.java @@ -0,0 +1,58 @@ +// https://leetcode.com/problems/range-sum-query-2d-immutable +// n: matrix.length +// m: matrix[0].length + + +class NumMatrix { + + final int rows; + final int columns; + final int[][] dp; + + // T: O(n * m) + // S: O(n * m) + public NumMatrix(int[][] matrix) { + this.rows = matrix.length; + this.columns = matrix[0].length; + this.dp = new int[rows][columns]; + + // first row + dp[0][0] = matrix[0][0]; + for (int column = 1 ; column < columns ; column++) { + dp[0][column] = dp[0][column - 1] + matrix[0][column]; + } + + // first column + for (int row = 1 ; row < rows ; row++) { + dp[row][0] = dp[row - 1][0] + matrix[row][0]; + } + + // rest of the matrix + for (int row = 1 ; row < rows ; row++) { + for (int column = 1 ; column < columns ; column++) { + dp[row][column] = dp[row - 1][column] + dp[row][column - 1] - dp[row - 1][column - 1] + + matrix[row][column]; + } + } + } + + // T: O(1) + // S: O(1) + public int sumRegion(int row1, int col1, int row2, int col2) { + int result = this.dp[row2][col2]; + if (row1 > 0) { + result -= this.dp[row1 - 1][col2]; + } + if (col1 > 0) { + result -= this.dp[row2][col1 - 1]; + } + if (row1 > 0 && col1 > 0) { + result += this.dp[row1 - 1][col1 - 1]; + } + return result; + } +} + +public class RangeSumQuery2DImmutable { + +} diff --git a/src/RankTransformOfArray.java b/src/RankTransformOfArray.java new file mode 100644 index 0000000..02f502a --- /dev/null +++ b/src/RankTransformOfArray.java @@ -0,0 +1,26 @@ +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public class RankTransformOfArray { + public int[] arrayRankTransform(int[] array) { + final Map elementRank = getElementRanks(array); + final int[] result = new int[array.length]; + for (int index = 0 ; index < array.length ; index++) { + result[index] = elementRank.get(array[index]); + } + return result; + } + + private Map getElementRanks(int[] array) { + final int[] sorted = array.clone(); + Arrays.sort(sorted); + final Map result = new HashMap<>(); + for (int i = 0, rank = 1 ; i < sorted.length ; i++) { + if (!result.containsKey(sorted[i])) { + result.put(sorted[i], rank++); + } + } + return result; + } +} diff --git a/src/ReadNCharactersGivenRead4.java b/src/ReadNCharactersGivenRead4.java new file mode 100644 index 0000000..bbcbca0 --- /dev/null +++ b/src/ReadNCharactersGivenRead4.java @@ -0,0 +1,29 @@ +// https://leetcode.com/problems/read-n-characters-given-read4 +// T: O(N) +// S: O(1) + +public class ReadNCharactersGivenRead4 { + static class Reader4 { + public int read4(char[] buffer) { + return 0; + } + } + + static class Solution extends Reader4 { + public int read(char[] buf, int n) { + int copiedChars = 0, readChars = 4; + char[] buf4 = new char[4]; + + while (copiedChars < n && readChars == 4) { + readChars = read4(buf4); + + for (int i = 0; i < readChars; ++i) { + if (copiedChars == n) return copiedChars; + buf[copiedChars] = buf4[i]; + ++copiedChars; + } + } + return copiedChars; + } + } +} diff --git a/src/RearrangeCharactersToMakeTargetString.java b/src/RearrangeCharactersToMakeTargetString.java new file mode 100644 index 0000000..5479f4a --- /dev/null +++ b/src/RearrangeCharactersToMakeTargetString.java @@ -0,0 +1,27 @@ +// https://leetcode.com/problems/rearrange-characters-to-make-target-string +// T: O(|s| + |target|) +// S: O(1) + +import java.util.HashMap; +import java.util.Map; + +public class RearrangeCharactersToMakeTargetString { + public int rearrangeCharacters(String s, String target) { + final Map sCharFrequencies = getCharFrequencies(s); + final Map targetCharFrequencies = getCharFrequencies(target); + + int maxCopies = Integer.MAX_VALUE; + for (char targetChar : targetCharFrequencies.keySet()) { + maxCopies = Math.min(maxCopies, sCharFrequencies.getOrDefault(targetChar, 0) / targetCharFrequencies.get(targetChar)); + } + return maxCopies; + } + + private Map getCharFrequencies(String string) { + final Map result = new HashMap<>(); + for (int i = 0 ; i < string.length() ; i++) { + result.put(string.charAt(i), result.getOrDefault(string.charAt(i), 0) + 1); + } + return result; + } +} diff --git a/src/RearrangeSpacesBetweenWords.java b/src/RearrangeSpacesBetweenWords.java new file mode 100644 index 0000000..ed4e482 --- /dev/null +++ b/src/RearrangeSpacesBetweenWords.java @@ -0,0 +1,40 @@ +import java.util.ArrayList; +import java.util.List; + +public class RearrangeSpacesBetweenWords { + public String reorderSpaces(String text) { + final int totalSpaces = countSpaces(text); + final List words = getWords(text); + final int spaces = words.size() > 1 ? totalSpaces / (words.size() - 1) : 0; + final int extraSpaces = words.size() > 1 ? totalSpaces % (words.size() - 1) : totalSpaces; + final StringBuilder result = new StringBuilder(); + final String spacesAfterWord = " ".repeat(spaces); + for (int i = 0 ; i < words.size() ; i++) { + result.append(words.get(i)).append(i != words.size() -1 ? spacesAfterWord : ""); + } + return result.append(" ".repeat(extraSpaces)).toString(); + } + + private int countSpaces(String s) { + int spaces = 0; + for (int i = 0 ; i < s.length() ; i++) { + if (s.charAt(i) == ' ') spaces++; + } + return spaces; + } + + private List getWords(String string) { + final List words = new ArrayList<>(); + StringBuilder word = new StringBuilder(); + for (int i = 0 ; i < string.length() ; i++) { + if (string.charAt(i) == ' ') { + if (word.length() > 0) words.add(word); + word = new StringBuilder(); + } else { + word.append(string.charAt(i)); + } + } + if (word.length() > 0) words.add(word); + return words; + } +} diff --git a/src/ReconstructItinerary.java b/src/ReconstructItinerary.java new file mode 100644 index 0000000..114a03c --- /dev/null +++ b/src/ReconstructItinerary.java @@ -0,0 +1,40 @@ +// https://leetcode.com/problems/reconstruct-itinerary +// E = |flights|, V = |airports| N = E / V +// T: O(V * NlogN) = O(E log(E / V)) +// S: O(V + E) + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.PriorityQueue; +import java.util.Queue; + +public class ReconstructItinerary { + public List findItinerary(List> tickets) { + final Map> graph = createGraph(tickets); + final List result = new ArrayList<>(); + dfs(graph, "JFK", result); + return result.reversed(); + } + + private static void dfs(Map> graph, String current, List result) { + final Queue queue = graph.getOrDefault(current, new PriorityQueue<>()); + while (!queue.isEmpty()) { + final String to = queue.poll(); + dfs(graph, to, result); + } + result.add(current); + } + + private static Map> createGraph(List> tickets) { + final Map> graph = new HashMap<>(); + for (List ticket : tickets) { + final String from = ticket.get(0), to = ticket.get(1); + final Queue queue = graph.getOrDefault(from, new PriorityQueue<>()); + queue.add(to); + graph.putIfAbsent(from, queue); + } + return graph; + } +} diff --git a/src/RecoverBinarySearchTree.java b/src/RecoverBinarySearchTree.java new file mode 100644 index 0000000..922858d --- /dev/null +++ b/src/RecoverBinarySearchTree.java @@ -0,0 +1,33 @@ +// https://leetcode.com/problems/recover-binary-search-tree +// T: O(n) +// S: O(log(n)) + +public class RecoverBinarySearchTree { + TreeNode first, second, previous = new TreeNode(Integer.MIN_VALUE); + + public void recoverTree(TreeNode root) { + inorder(root); + swapValues(first, second); + } + + private void inorder(TreeNode root) { + if (root == null) return; + inorder(root.left); + + if (first == null && root.val < previous.val) { + first = previous; + } + if (first != null && root.val < previous.val) { + second = root; + } + previous = root; + + inorder(root.right); + } + + private void swapValues(TreeNode a, TreeNode b) { + int temp = a.val; + a.val = b.val; + b.val = temp; + } +} diff --git a/src/RectangleArea.java b/src/RectangleArea.java new file mode 100644 index 0000000..d9fb13a --- /dev/null +++ b/src/RectangleArea.java @@ -0,0 +1,49 @@ +// https://leetcode.com/problems/rectangle-area +// T: O(1) +// S: O(1) + +public class RectangleArea { + private record Point(int x, int y) {} + + private static class Rectangle { + public final int xl; + public final int xr; + public final int yb; + public final int yt; + public final int area; + + Rectangle(Point lowerLeft, Point upperRight) { + xl = lowerLeft.x; + xr = upperRight.x; + yb = lowerLeft.y; + yt = upperRight.y; + area = (upperRight.x - lowerLeft.x) * (upperRight.y - lowerLeft.y); + } + + public static Rectangle from(int x1, int y1, int x2, int y2) { + final Point a1 = new Point(x1, y1); + final Point a2 = new Point(x2, y2); + return new Rectangle(a1, a2); + } + + public Rectangle intersection(Rectangle other) { + final int intersectionXl = Math.max(xl, other.xl); + final int intersectionXr = Math.max(intersectionXl, Math.min(xr, other.xr)); + final int intersectionYb = Math.max(yb, other.yb); + final int intersectionYt = Math.max(intersectionYb, Math.min(yt, other.yt)); + + if (intersectionXl > intersectionXr || intersectionYb > intersectionYt) { + return null; + } + + return Rectangle.from(intersectionXl, intersectionYb, intersectionXr, intersectionYt); + } + } + + public static int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { + final Rectangle rectangle1 = Rectangle.from(ax1, ay1, ax2, ay2); + final Rectangle rectangle2 = Rectangle.from(bx1, by1, bx2, by2); + final Rectangle intersection = rectangle1.intersection(rectangle2); + return rectangle1.area + rectangle2.area - (intersection == null ? 0 : intersection.area); + } +} diff --git a/src/RectangleOverlap.java b/src/RectangleOverlap.java new file mode 100644 index 0000000..2dc3770 --- /dev/null +++ b/src/RectangleOverlap.java @@ -0,0 +1,27 @@ +public class RectangleOverlap { + public boolean isRectangleOverlap(int[] rec1, int[] rec2) { + Rectangle rectangle1 = new Rectangle(rec1); + Rectangle rectangle2 = new Rectangle(rec2); + return hasXIntersection(rectangle1, rectangle2) && hasYIntersection(rectangle1, rectangle2); + } + + private boolean hasXIntersection(Rectangle rec1, Rectangle rec2) { + return (rec1.x1 <= rec2.x1 && rec2.x1 < rec1.x2) + || (rec2.x1 < rec1.x1 && rec1.x1 < rec2.x2); + } + + private boolean hasYIntersection(Rectangle rec1, Rectangle rec2) { + return (rec1.y1 <= rec2.y1 && rec2.y1 < rec1.y2) + || (rec2.y1 < rec1.y1 && rec1.y1 < rec2.y2); + } + + private static class Rectangle { + private final int x1, x2, y1, y2; + Rectangle(int[] points) { + this.x1 = points[0]; + this.y1 = points[1]; + this.x2 = points[2]; + this.y2 = points[3]; + } + } +} diff --git a/src/RedistributeCharactersToMakeAllStringsEqual.java b/src/RedistributeCharactersToMakeAllStringsEqual.java new file mode 100644 index 0000000..be79b02 --- /dev/null +++ b/src/RedistributeCharactersToMakeAllStringsEqual.java @@ -0,0 +1,27 @@ +// https://leetcode.com/problems/redistribute-characters-to-make-all-strings-equal +// T: O(|words| * |word|) +// S: O(1) + +import java.util.HashMap; +import java.util.Map; + +public class RedistributeCharactersToMakeAllStringsEqual { + public boolean makeEqual(String[] words) { + if (words.length == 1) return true; + final Map frequencies = getCharacterFrequencies(words); + for (int frequency : frequencies.values()) { + if (frequency % words.length != 0) return false; + } + return true; + } + + private Map getCharacterFrequencies(String[] words) { + final Map frequencies = new HashMap<>(); + for (String word : words) { + for (int i = 0 ; i < word.length() ; i++) { + frequencies.put(word.charAt(i), frequencies.getOrDefault(word.charAt(i), 0) + 1); + } + } + return frequencies; + } +} diff --git a/src/RedundantConnection.java b/src/RedundantConnection.java new file mode 100644 index 0000000..925eea7 --- /dev/null +++ b/src/RedundantConnection.java @@ -0,0 +1,55 @@ +// https://leetcode.com/problems/redundant-connection +// T: O(N) +// S: O(N) + +public class RedundantConnection { + private static final class DisjointSet { + private final int[] root, rank; + + public DisjointSet(int size) { + this.root = new int[size]; + this.rank = new int[size]; + for (int i = 0 ; i < size ; i++) { + root[i] = i; + rank[i] = 1; + } + } + + public int find(int num) { + if (num == root[num]) { + return num; + } + return root[num] = find(root[num]); + } + + public boolean areConnected(int x, int y) { + return find(x) == find(y); + } + + public void union(int x, int y) { + final int rootX = find(x), rootY = find(y); + if (rootX == rootY) { + return; + } + if (rank[rootX] < rank[rootY]) { + root[rootY] = rootX; + } else if (rank[rootX] > rank[rootY]) { + root[rootY] = rootX; + } else { + root[rootY] = rootX; + rank[rootX]++; + } + } + } + + public int[] findRedundantConnection(int[][] edges) { + final DisjointSet disjointSet = new DisjointSet(edges.length); + for (int[] edge : edges) { + if (disjointSet.areConnected(edge[0] - 1, edge[1] - 1)) { + return edge; + } + disjointSet.union(edge[0] - 1, edge[1] - 1); + } + return new int[] {}; + } +} diff --git a/src/ReformatDate.java b/src/ReformatDate.java new file mode 100644 index 0000000..aaa59b9 --- /dev/null +++ b/src/ReformatDate.java @@ -0,0 +1,35 @@ +public class ReformatDate { + public String reformatDate(String date) { + final String[] parts = date.split(" "); + return new StringBuilder(parts[2]) + .append('-') + .append(getMonth(parts[1])) + .append('-') + .append(getDay(parts[0])) + .toString(); + } + + private String getMonth(String month) { + return switch (month) { + case "Jan" -> "01"; + case "Feb" -> "02"; + case "Mar" -> "03"; + case "Apr" -> "04"; + case "May" -> "05"; + case "Jun" -> "06"; + case "Jul" -> "07"; + case "Aug" -> "08"; + case "Sep" -> "09"; + case "Oct" -> "10"; + case "Nov" -> "11"; + case "Dec" -> "12"; + default -> ""; + }; + } + + private String getDay(String string) { + if (string.length() == 3) { + return '0' + string.substring(0, 1); + } return string.substring(0, 2); + } +} diff --git a/src/ReformatPhoneNumber.java b/src/ReformatPhoneNumber.java new file mode 100644 index 0000000..62c6067 --- /dev/null +++ b/src/ReformatPhoneNumber.java @@ -0,0 +1,30 @@ +import java.util.LinkedList; +import java.util.Queue; + +public class ReformatPhoneNumber { + public String reformatNumber(String number) { + final Queue digits = getDigits(number); + final StringBuilder result = new StringBuilder(); + int count = 3; + while (!digits.isEmpty()) { + if (digits.size() == 4 && count % 3 == 0) { + result.append(count == 3 ? "" : '-').append(digits.poll()).append(digits.poll()) + .append('-').append(digits.poll()).append(digits.poll()); + break; + } + result.append(count == 0 ? '-' : "").append(digits.poll()); + count = (count + 1) % 3; + } + return result.toString(); + } + + private Queue getDigits(String number) { + final Queue digits = new LinkedList<>(); + for (int index = 0 ; index < number.length() ; index++) { + if (Character.isDigit(number.charAt(index))) { + digits.add(number.charAt(index)); + } + } + return digits; + } +} diff --git a/src/ReformatTheString.java b/src/ReformatTheString.java new file mode 100644 index 0000000..d0a7d6d --- /dev/null +++ b/src/ReformatTheString.java @@ -0,0 +1,22 @@ +import java.util.LinkedList; +import java.util.Queue; + +public class ReformatTheString { + public String reformat(String s) { + Queue digits = new LinkedList<>(); + Queue alphabets = new LinkedList<>(); + for (int index = 0 ; index < s.length() ; index++) { + if (Character.isAlphabetic(s.charAt(index))) { + alphabets.add(s.charAt(index)); + } else digits.add(s.charAt(index)); + } + if (Math.abs(digits.size() - alphabets.size()) > 1) return ""; + StringBuilder result = new StringBuilder(); + result.append(alphabets.size() > digits.size() ? alphabets.poll() : ""); + while (!digits.isEmpty() && !alphabets.isEmpty()) { + result.append(digits.poll()).append(alphabets.poll()); + } + result.append(!digits.isEmpty() ? digits.poll() : ""); + return result.toString(); + } +} diff --git a/src/RelativeRanks.java b/src/RelativeRanks.java new file mode 100644 index 0000000..d1ee1ce --- /dev/null +++ b/src/RelativeRanks.java @@ -0,0 +1,66 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class RelativeRanks { + static class Pair { + private final int index; + private final int value; + + Pair(int index, int value) { + this.index = index; + this.value = value; + } + + @Override + public String toString() { + return "Pair{" + + "index=" + index + + ", value=" + value + + '}'; + } + } + + private static List getValuesWithIndex(int[] array) { + List result = new ArrayList<>(); + for (int index = 0 ; index < array.length ; index++) { + result.add(new Pair(index, array[index])); + } + return result; + } + + private static Map getValueToIndexMap(List array) { + Map result = new HashMap<>(); + for (int index = 0 ; index < array.size() ; index++) { + result.put(array.get(index).value, index); + } + return result; + } + + private static String getRank(int position) { + switch (position) { + case 1: return "Gold Medal"; + case 2: return "Silver Medal"; + case 3: return "Bronze Medal"; + default: return position + ""; + } + } + + public static String[] findRelativeRanks(int[] score) { + List sortedScores = getValuesWithIndex(score); + sortedScores.sort(((o1, o2) -> Integer.compare(o2.value, o1.value))); + System.out.println(sortedScores); + Map value2index = getValueToIndexMap(sortedScores); + String[] result = new String[score.length]; + for (int index = 0 ; index < score.length ; index++) { + result[index] = getRank(value2index.get(score[index]) + 1); + } + return result; + } + + public static void main(String[] args) { + System.out.println(Arrays.toString(findRelativeRanks(new int[]{10, 3, 8, 9, 4}))); + } +} diff --git a/src/RelativeSortArray.java b/src/RelativeSortArray.java new file mode 100644 index 0000000..fd81a9d --- /dev/null +++ b/src/RelativeSortArray.java @@ -0,0 +1,40 @@ +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public class RelativeSortArray { + public int[] relativeSortArray(int[] arr1, int[] arr2) { + final Map elementWeight = new HashMap<>(); + for (int i = 0 ; i < arr2.length ; i++) elementWeight.put(arr2[i], i); + Integer[] array = arrayFrom(arr1); + Arrays.sort(array, (o1, o2) -> { + if (elementWeight.containsKey(o1) && elementWeight.containsKey(o2)) { + return elementWeight.get(o1) - elementWeight.get(o2); + } + if (elementWeight.containsKey(o1)) { + return -1; + } + if (elementWeight.containsKey(o2)) { + return 1; + } + return Integer.compare(o1, o2); + }); + return toIntArray(array); + } + + private Integer[] arrayFrom(int[] array) { + Integer[] result = new Integer[array.length]; + for (int index = 0 ; index < array.length ; index++) { + result[index] = array[index]; + } + return result; + } + + private int[] toIntArray(Integer[] array) { + int[] result = new int[array.length]; + for (int index = 0 ; index < array.length ; index++) { + result[index] = array[index]; + } + return result; + } +} diff --git a/src/RemoveAllAdjacentDuplicatesInAString.java b/src/RemoveAllAdjacentDuplicatesInAString.java new file mode 100644 index 0000000..6b44e50 --- /dev/null +++ b/src/RemoveAllAdjacentDuplicatesInAString.java @@ -0,0 +1,29 @@ +import java.util.Stack; + +public class RemoveAllAdjacentDuplicatesInAString { + + public String removeDuplicates(String s) { + final Stack stack = new Stack<>(); + int k, count = 0; + stack.push(s.charAt(0)); + for (int index = 1 ; index < s.length() ; index = k + 1, count = 0) { + for (k = index ; k + 1 < s.length() && s.charAt(k + 1) == s.charAt(k) ; k++); + if (!stack.isEmpty() && stack.peek() == s.charAt(k)) { + for (count = 0 ; !stack.isEmpty() && stack.peek() == s.charAt(k) ; count++) { + stack.pop(); + } + } + if (((k - index + 1 + count) & 1) == 1) stack.push(s.charAt(k)); + } + StringBuilder result = getCharactersFrom(stack); + return result.reverse().toString(); + } + + private StringBuilder getCharactersFrom(Stack stack) { + StringBuilder result = new StringBuilder(); + while (!stack.isEmpty()) { + result.append(stack.pop()); + } + return result; + } +} diff --git a/src/RemoveDigitFromNumberToMaximizeResult.java b/src/RemoveDigitFromNumberToMaximizeResult.java new file mode 100644 index 0000000..e04feab --- /dev/null +++ b/src/RemoveDigitFromNumberToMaximizeResult.java @@ -0,0 +1,29 @@ +// https://leetcode.com/problems/remove-digit-from-number-to-maximize-result +// T: O(|number|) +// S: O(|number|) + +import java.util.ArrayList; +import java.util.List; + +public class RemoveDigitFromNumberToMaximizeResult { + public String removeDigit(String number, char digit) { + final List digitIndices = getIndices(number, digit); + for (int index : digitIndices) { + if (index + 1 < number.length() && number.charAt(index) < number.charAt(index + 1)) { + return number.substring(0, index) + number.substring(index + 1); + } + } + int lastIndex = digitIndices.get(digitIndices.size() - 1); + return number.substring(0, lastIndex) + number.substring(lastIndex + 1); + } + + private List getIndices(String number, char digit) { + final List result = new ArrayList<>(); + for (int index = 0 ; index < number.length() ; index++) { + if (number.charAt(index) == digit) { + result.add(index); + } + } + return result; + } +} diff --git a/src/RemoveDuplicatesFromSortedArrayII.java b/src/RemoveDuplicatesFromSortedArrayII.java new file mode 100644 index 0000000..57d3528 --- /dev/null +++ b/src/RemoveDuplicatesFromSortedArrayII.java @@ -0,0 +1,20 @@ +// https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii +// T: O(N) +// S: O(1) + +public class RemoveDuplicatesFromSortedArrayII { + public int removeDuplicates(int[] nums) { + int insertionIndex = 1; + for (int i = 1, count = 1 ; i < nums.length ; i++) { + if (nums[i] == nums[insertionIndex - 1]) { + if (count == 2) continue; + nums[insertionIndex++] = nums[i]; + count++; + } else { + nums[insertionIndex++] = nums[i]; + count = 1; + } + } + return insertionIndex; + } +} diff --git a/src/RemoveDuplicatesFromSortedList.java b/src/RemoveDuplicatesFromSortedList.java index f12c0c9..fde4aed 100644 --- a/src/RemoveDuplicatesFromSortedList.java +++ b/src/RemoveDuplicatesFromSortedList.java @@ -1,20 +1,4 @@ public class RemoveDuplicatesFromSortedList { - public static class ListNode { - int val; - ListNode next; - - ListNode() { - } - - ListNode(int val) { - this.val = val; - } - - ListNode(int val, ListNode next) { - this.val = val; - this.next = next; - } - } public ListNode deleteDuplicates(ListNode head) { ListNode current = head; diff --git a/src/RemoveDuplicatesFromSortedListII.java b/src/RemoveDuplicatesFromSortedListII.java new file mode 100644 index 0000000..0b09be2 --- /dev/null +++ b/src/RemoveDuplicatesFromSortedListII.java @@ -0,0 +1,27 @@ +// https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii +// T: O(N) +// S: O(1) + +public class RemoveDuplicatesFromSortedListII { + + public ListNode deleteDuplicates(ListNode head) { + if (head == null) return null; + ListNode tempHead = new ListNode(); + tempHead.next = head; + int val; + for (ListNode current = head, previous = tempHead ; current != null && current.next != null ; ) { + if (current.val == current.next.val) { + val = current.val; + while (current.next != null && current.next.val == val) { + current = current.next; + } + current = current.next; + previous.next = current; + } else { + previous = current; + current = current.next; + } + } + return tempHead.next; + } +} diff --git a/src/RemoveLetterToEqualizeFrequency.java b/src/RemoveLetterToEqualizeFrequency.java new file mode 100644 index 0000000..9936398 --- /dev/null +++ b/src/RemoveLetterToEqualizeFrequency.java @@ -0,0 +1,52 @@ +// https://leetcode.com/problems/remove-letter-to-equalize-frequency +// T: O(|word|) +// S: O(1) + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +public class RemoveLetterToEqualizeFrequency { + public boolean equalFrequency(String word) { + final Map letterFrequency = getFrequencies(word); + final Map numberFrequency = getFrequencies(letterFrequency.values()); + + if (letterFrequency.size() == 1) { + return true; + } + + if (numberFrequency.size() == 1 && numberFrequency.keySet().iterator().next() == 1) { + return true; + } + + if (numberFrequency.size() == 1 || numberFrequency.size() > 2) { + return false; + } + + final Iterator iterator = numberFrequency.keySet().iterator(); + final int first = iterator.next(), second = iterator.next(); + final int smallerNum = Math.min(first, second); + final int largerNum = Math.max(first, second); + final int smallerNumFreq = numberFrequency.get(smallerNum); + final int largerNumFreq = numberFrequency.get(largerNum); + + return ((largerNum - smallerNum == 1) && largerNumFreq == 1) || (smallerNum == 1 && smallerNumFreq == 1); + } + + private Map getFrequencies(String string) { + final Map result = new HashMap<>(); + for (int index = 0 ; index < string.length() ; index++) { + char letter = string.charAt(index); + result.put(letter, result.getOrDefault(letter, 0) + 1); + } + return result; + } + + private Map getFrequencies(Iterable iterable) { + final Map result = new HashMap<>(); + for (int value : iterable) { + result.put(value, result.getOrDefault(value, 0) + 1); + } + return result; + } +} diff --git a/src/RemoveLinkedListElements.java b/src/RemoveLinkedListElements.java index f74adb1..e7651f9 100644 --- a/src/RemoveLinkedListElements.java +++ b/src/RemoveLinkedListElements.java @@ -1,13 +1,4 @@ public class RemoveLinkedListElements { - private static class ListNode { - int val; - ListNode next; - - ListNode(int val, ListNode next) { - this.val = val; - this.next = next; - } - } public static ListNode removeElements(ListNode head, int target) { ListNode result = new ListNode(-1, head), current = result; diff --git a/src/RemoveNthNodeFromEndOfList.java b/src/RemoveNthNodeFromEndOfList.java new file mode 100644 index 0000000..ba96f05 --- /dev/null +++ b/src/RemoveNthNodeFromEndOfList.java @@ -0,0 +1,24 @@ +public class RemoveNthNodeFromEndOfList { + + public ListNode removeNthFromEnd(ListNode head, int n) { + final int length = length(head); + final int removalIndex = length - n; + if (removalIndex == 0) return head.next; + ListNode current = head; + for (int i = 0 ; i < removalIndex - 1 ; i++) { + current = current.next; + } + current.next = current.next.next; + return head; + } + + private int length(ListNode head) { + int count = 0; + ListNode current = head; + while (current != null) { + count++; + current = current.next; + } + return count; + } +} diff --git a/src/RemoveOneElementToMakeTheArrayStrictlyIncreasing.java b/src/RemoveOneElementToMakeTheArrayStrictlyIncreasing.java new file mode 100644 index 0000000..167bc01 --- /dev/null +++ b/src/RemoveOneElementToMakeTheArrayStrictlyIncreasing.java @@ -0,0 +1,27 @@ +public class RemoveOneElementToMakeTheArrayStrictlyIncreasing { + public boolean canBeIncreasing(int[] array) { + if (array[0] >= array[1]) { + if (array.length == 2) return true; + return array[2] > array[1] && isStrictlyIncreasing(array, 3); + } + boolean firstAnomaly = true; + for (int index = 2 ; index < array.length ; index++) { + if (array[index] <= array[index - 1]) { + if (!firstAnomaly) return false; + firstAnomaly = false; + if (index == array.length - 1) return true; + if (array[index + 1] > array[index - 1]) continue; + if (array[index + 1] > array[index] && array[index] > array[index - 2]) continue; + return false; + } + } + return true; + } + + private boolean isStrictlyIncreasing(int[] array, int start) { + for (int i = start ; i < array.length ; i++) { + if (array[i] <= array[i - 1]) return false; + } + return true; + } +} diff --git a/src/RemoveOutermostParentheses.java b/src/RemoveOutermostParentheses.java new file mode 100644 index 0000000..569c221 --- /dev/null +++ b/src/RemoveOutermostParentheses.java @@ -0,0 +1,13 @@ +public class RemoveOutermostParentheses { + public String removeOuterParentheses(String s) { + StringBuilder result = new StringBuilder(); + for (int index = 0, level = 0 ; index < s.length() ; index++) { + if (level != 0 && (level != -1 || s.charAt(index) != ')')) { + result.append(s.charAt(index)); + } + if (s.charAt(index) == '(') level--; + else level++; + } + return result.toString(); + } +} diff --git a/src/RemovePalindromicSubSequences.java b/src/RemovePalindromicSubSequences.java new file mode 100644 index 0000000..7ce5a40 --- /dev/null +++ b/src/RemovePalindromicSubSequences.java @@ -0,0 +1,12 @@ +public class RemovePalindromicSubSequences { + public int removePalindromeSub(String s) { + return isPalindrome(s) ? 1 : 2; + } + + private boolean isPalindrome(String s) { + for (int i = 0 ; i < s.length() / 2 ; i++) { + if (s.charAt(i) != s.charAt(s.length() - 1 - i)) return false; + } + return true; + } +} diff --git a/src/RemoveTrailingZerosFromAString.java b/src/RemoveTrailingZerosFromAString.java new file mode 100644 index 0000000..ea86a44 --- /dev/null +++ b/src/RemoveTrailingZerosFromAString.java @@ -0,0 +1,14 @@ +// https://leetcode.com/problems/remove-trailing-zeros-from-a-string +// T: O(|s|) +// S: O(|s|) + +public class RemoveTrailingZerosFromAString { + public String removeTrailingZeros(String num) { + for (int i = num.length() - 1; i >= 0 ; i--) { + if (num.charAt(i) != '0') { + return num.substring(0, i + 1); + } + } + return ""; + } +} diff --git a/src/ReorderDataInLogFiles.java b/src/ReorderDataInLogFiles.java new file mode 100644 index 0000000..079b47d --- /dev/null +++ b/src/ReorderDataInLogFiles.java @@ -0,0 +1,33 @@ +import java.util.Arrays; + +public class ReorderDataInLogFiles { + public String[] reorderLogFiles(String[] logs) { + Arrays.sort(logs, (log1, log2) -> { + String[] split1 = log1.split(" ", 2); + String[] split2 = log2.split(" ", 2); + + boolean isDigit1 = Character.isDigit(split1[1].charAt(0)); + boolean isDigit2 = Character.isDigit(split2[1].charAt(0)); + + // case 1). both logs are letter-logs + if (!isDigit1 && !isDigit2) { + // first compare the content + int cmp = split1[1].compareTo(split2[1]); + if (cmp != 0) return cmp; + // logs of same content, compare the identifiers + return split1[0].compareTo(split2[0]); + } + + // case 2). one of logs is digit-log + if (!isDigit1) + // the letter-log comes before digit-logs + return -1; + else if (!isDigit2) + return 1; + else + // case 3). both logs are digit-log + return 0; + }); + return logs; + } +} diff --git a/src/ReorderList.java b/src/ReorderList.java new file mode 100644 index 0000000..23f8d9f --- /dev/null +++ b/src/ReorderList.java @@ -0,0 +1,47 @@ +// https://leetcode.com/problems/reorder-list +// T: O(N) +// S: O(1) + +public class ReorderList { + public void reorderList(ListNode head) { + if (head == null || head.next == null) return; + + ListNode middle = getMiddleOfLinkedList(head); + ListNode preMiddle = reverseLinkedList(middle); + interleaveNodes(head, preMiddle); + } + + private ListNode getMiddleOfLinkedList(ListNode head) { + ListNode p1 = head; + ListNode p2 = head; + while(p2.next!=null&&p2.next.next!=null){ + p1 = p1.next; + p2 = p2.next.next; + } + return p1; + } + + private ListNode reverseLinkedList(ListNode head) { + ListNode preCurrent = head.next; + while(preCurrent.next != null){ + ListNode current = preCurrent.next; + preCurrent.next = current.next; + current.next = head.next; + head.next = current; + } + return head; + } + + // 1->2->3->6->5->4 to 1->6->2->5->3->4 + private void interleaveNodes(ListNode head, ListNode preMiddle) { + ListNode p1 = head; + ListNode p2 = preMiddle.next; + while(p1 != preMiddle){ + preMiddle.next = p2.next; + p2.next = p1.next; + p1.next = p2; + p1 = p2.next; + p2 = preMiddle.next; + } + } +} diff --git a/src/RepeatedDNASequences.java b/src/RepeatedDNASequences.java new file mode 100644 index 0000000..05d55f6 --- /dev/null +++ b/src/RepeatedDNASequences.java @@ -0,0 +1,42 @@ +// https://leetcode.com/problems/repeated-dna-sequences +// T: O(N) +// S: O(N) + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class RepeatedDNASequences { + private static final Map NUCLEOTIDES_TO_INT = Map.ofEntries( + Map.entry('A', 0), + Map.entry('C', 1), + Map.entry('G', 2), + Map.entry('T', 3) + ); + + public List findRepeatedDnaSequences(String s) { + final List dnaSequences = new ArrayList<>(); + final Set encodings = new HashSet<>(); + final Set repeatedEncodings = new HashSet<>(); + + for (int i = 0 ; i < s.length() - 9 ; i++) { + final int encoding = getSequenceEncoding(s, i); + if (!encodings.add(encoding) && repeatedEncodings.add(encoding)) { + dnaSequences.add(s.substring(i, i + 10)); + } + } + + return dnaSequences; + } + + private int getSequenceEncoding(String s, int index) { + int encoding = 0; + for (int i = index ; i < index + 10 ; i++) { + encoding <<= 2; + encoding |= NUCLEOTIDES_TO_INT.get(s.charAt(i)); + } + return encoding; + } +} diff --git a/src/RepeatedStringMatch.java b/src/RepeatedStringMatch.java new file mode 100644 index 0000000..53b7dc5 --- /dev/null +++ b/src/RepeatedStringMatch.java @@ -0,0 +1,36 @@ +public class RepeatedStringMatch { + public int repeatedStringMatch(String a, String b) { + Pair result = canBeRepeatedForSubstring(a, b); + if (!result.canBeRepeated) return -1; + return (int) Math.ceil(1 + (double) (a.length() + result.startIndex - b.length()) / b.length()); + } + + private Pair canBeRepeatedForSubstring(String a, String b) { + boolean checking = false; + char firstChar = a.charAt(0); + int startIndex; + for (int j = 0 ; j < b.length() ; j++) { + if (firstChar == b.charAt(j)) { + int i = 0; + startIndex = j; + for ( ; i < a.length() ; i++, j = (j + 1) % b.length()) { + if (a.charAt(i) != b.charAt(j)) { + break; + } + } + if (i == a.length()) return new Pair(startIndex, true); + } + } + return new Pair(0, false); + } + + private static class Pair { + private final int startIndex; + private final boolean canBeRepeated; + + Pair(final int startIndex, final boolean canBeRepeated) { + this.startIndex = startIndex; + this.canBeRepeated = canBeRepeated; + } + } +} diff --git a/src/ReplaceAllDigitsWithCharacters.java b/src/ReplaceAllDigitsWithCharacters.java new file mode 100644 index 0000000..f62239b --- /dev/null +++ b/src/ReplaceAllDigitsWithCharacters.java @@ -0,0 +1,16 @@ +public class ReplaceAllDigitsWithCharacters { + public String replaceDigits(String s) { + final StringBuilder result = new StringBuilder(); + for (int i = 1 ; i < s.length() ; i += 2) { + result.append(s.charAt(i - 1)).append(shift(s.charAt(i - 1), s.charAt(i) - '0')); + } + if (s.length() % 2 == 1) { + result.append(s.charAt(s.length() - 1)); + } + return result.toString(); + } + + private char shift(char c, int shiftAmount) { + return (char) (c + shiftAmount); + } +} diff --git a/src/ReplaceAllToAvoidConsecutiveRepeatingCharacters.java b/src/ReplaceAllToAvoidConsecutiveRepeatingCharacters.java new file mode 100644 index 0000000..e494fdf --- /dev/null +++ b/src/ReplaceAllToAvoidConsecutiveRepeatingCharacters.java @@ -0,0 +1,30 @@ +// https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/submissions +// T:(n) +// S: O(n) + +public class ReplaceAllToAvoidConsecutiveRepeatingCharacters { + private static final Character QUESTION_MARK = '?'; + + public String modifyString(String s) { + final StringBuilder result = new StringBuilder(); + char last = QUESTION_MARK; + for (int index = 0 ; index < s.length() ; index++) { + char c = s.charAt(index); + if (c == QUESTION_MARK) { + char left = get(s, index - 1); + if (left == QUESTION_MARK) left = last; + final char right = get(s, index + 1); + c = 'a'; + while (c == left || c == right) c++; + last = c; + } + result.append(c); + } + return result.toString(); + } + + private char get(String string, int index) { + if (index < 0 || index >= string.length()) return QUESTION_MARK; + return string.charAt(index); + } +} diff --git a/src/ReplaceElementWithGreatestElementOnRightSide.java b/src/ReplaceElementWithGreatestElementOnRightSide.java new file mode 100644 index 0000000..f81a86e --- /dev/null +++ b/src/ReplaceElementWithGreatestElementOnRightSide.java @@ -0,0 +1,11 @@ +public class ReplaceElementWithGreatestElementOnRightSide { + public int[] replaceElements(int[] array) { + int[] result = new int[array.length]; + result[result.length - 1] = -1; + for (int index = array.length - 2, max = array[array.length - 1]; index >= 0 ; index--) { + result[index] = max; + max = Math.max(max, array[index]); + } + return result; + } +} diff --git a/src/ReshapeTheMatrix.java b/src/ReshapeTheMatrix.java new file mode 100644 index 0000000..3f07791 --- /dev/null +++ b/src/ReshapeTheMatrix.java @@ -0,0 +1,13 @@ +public class ReshapeTheMatrix { + public int[][] matrixReshape(int[][] mat, int r, int c) { + if (r * c != mat.length * mat[0].length || (mat.length == r && mat[0].length == c)) return mat; + + int[][] result = new int[r][c]; + for (int i = 0, k = 0 ; i < mat.length ; i++) { + for (int j = 0 ; j < mat[0].length ; j++, k++) { + result[k / c][k % c] = mat[i][j]; + } + } + return result; + } +} diff --git a/src/RestoreIPAddresses.java b/src/RestoreIPAddresses.java new file mode 100644 index 0000000..5ad1ef1 --- /dev/null +++ b/src/RestoreIPAddresses.java @@ -0,0 +1,57 @@ +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +public class RestoreIPAddresses { + public List restoreIpAddresses(final String s) { + final List result = new ArrayList<>(); + restoreIpAddresses(s, result, new LinkedList<>(), 0); + return result; + } + + private void restoreIpAddresses(final String s, final List result, LinkedList numbers, int index) { + if (numbers.size() == 4 && index == s.length()) { + result.add(ipAddressFrom(numbers)); + return; + } + if (numbers.size() >= 4 || index == s.length()) { + return; + } + for (int i = index + 1 ; i <= s.length() ; i++) { + if (isValidIpAddressInteger(s, index, i)) { + numbers.add(toNumber(s, index, i)); + restoreIpAddresses(s, result, numbers, i); + numbers.removeLast(); + } else { + break; + } + } + } + + private String ipAddressFrom(LinkedList numbers) { + StringBuilder result = new StringBuilder(); + for (int number : numbers) { + result.append(number).append('.'); + } + result.deleteCharAt(result.length() - 1); + return result.toString(); + } + + private boolean isValidIpAddressInteger(String s, int start, int end) { + if (hasLeadingZeros(s, start, end)) return false; + return toNumber(s, start, end) < 256; + } + + private boolean hasLeadingZeros(String s, int start, int end) { + return end - start > 1 && s.charAt(start) == '0'; + } + + private int toNumber(String s, int start, int end) { + int val = 0; + for (int index = start ; index < end ; index++) { + val *= 10; + val += s.charAt(index) - '0'; + } + return val; + } +} diff --git a/src/ReverseInteger.java b/src/ReverseInteger.java index 7cf85cc..db4ef00 100644 --- a/src/ReverseInteger.java +++ b/src/ReverseInteger.java @@ -1,24 +1,18 @@ // https://leetcode.com/problems/reverse-integer/ -import java.util.Scanner; - public class ReverseInteger { - public static void main(String[] args) { - Scanner scanner = new Scanner(System.in); - int number = scanner.nextInt(); - System.out.println(reverse(number)); - } - - private static int reverse(int number) { - boolean isPositive = number >= 0; - StringBuilder accumulator = new StringBuilder(number + ""); - if (!isPositive) { - accumulator.replace(0, 1, ""); - } - try { - return Integer.parseInt(accumulator.reverse().insert(0, isPositive ? "" : "-").toString()); - } catch (NumberFormatException exception) { - return 0; + public int reverse(int x) { + int result = 0, next; + boolean isPositive = x >= 0; + x = isPositive ? x : -x; + while (x > 0) { + next = 10 * result + x % 10; + if (next / 10 != result) { + return 0; + } + result = next; + x /= 10; } + return isPositive ? result : -result; } } diff --git a/src/ReverseLinkedList.java b/src/ReverseLinkedList.java index b73820c..8039cda 100644 --- a/src/ReverseLinkedList.java +++ b/src/ReverseLinkedList.java @@ -1,8 +1,7 @@ +// T: O(n) +// S: O(1) + public class ReverseLinkedList { - private static class ListNode { - int val; - ListNode next; - } public static ListNode reverseList(ListNode head) { if (head == null || head.next == null) { diff --git a/src/ReverseLinkedListII.java b/src/ReverseLinkedListII.java new file mode 100644 index 0000000..bb0711d --- /dev/null +++ b/src/ReverseLinkedListII.java @@ -0,0 +1,39 @@ +// T: O(n) +// S: O(1) + +public class ReverseLinkedListII { + + public ListNode reverseBetween(ListNode head, int left, int right) { + if (left == right) return head; + + ListNode start = new ListNode(); + start.next = head; + + ListNode temp = start; + int i = 1; + for ( ; i < left ; i++) { + temp = temp.next; + } + + ListNode a = temp.next, b = temp.next.next, c = temp.next.next.next; + a.next = null; + + for ( ; i < right && c != null; i++) { + b.next = a; + a = b; + b = c; + c = c.next; + } + if (i < right) { + b.next = a; + if (left != 1) { + temp.next = b; + return start.next; + } + return b; + } + temp.next.next = b; + temp.next = a; + return start.next; + } +} diff --git a/src/ReverseNodesInKGroup.java b/src/ReverseNodesInKGroup.java new file mode 100644 index 0000000..25c6825 --- /dev/null +++ b/src/ReverseNodesInKGroup.java @@ -0,0 +1,44 @@ +// https://leetcode.com/problems/reverse-nodes-in-k-group +// T: O(N) +// S: O(1) + +public class ReverseNodesInKGroup { + public static ListNode reverseKGroup(ListNode head, int k) { + if (head == null || head.next == null || k == 1) { + return head; + } + + final ListNode result = new ListNode(0); + result.next = head; + + for (ListNode i = result ; i != null ; ) { + ListNode start = i; + + // go forward k steps + int count = 0; + for ( ; count < k && i != null ; count++) { + i = i.next; + } + + if (count == k && i != null) { + i = reverse(start, i); + } + } + + return result.next; + } + + private static ListNode reverse(ListNode start, ListNode end) { + ListNode a = start.next, b = start.next.next, terminal = end.next; + a.next = end.next; + while (b != terminal) { + ListNode c = b.next; + b.next = a; + a = b; + b = c; + } + ListNode newStart = start.next; + start.next = a; + return newStart; + } +} diff --git a/src/ReverseOnlyLetters.java b/src/ReverseOnlyLetters.java new file mode 100644 index 0000000..f594b38 --- /dev/null +++ b/src/ReverseOnlyLetters.java @@ -0,0 +1,16 @@ +public class ReverseOnlyLetters { + public static String reverseOnlyLetters(String s) { + StringBuilder result = new StringBuilder(); + int tail = s.length() - 1; + while (tail >= 0 && !Character.isAlphabetic(s.charAt(tail))) tail--; + + for (int head = 0 ; head < s.length() ; head++) { + if (Character.isAlphabetic(s.charAt(head))) { + result.append(s.charAt(tail--)); + while (tail >=0 && !Character.isAlphabetic(s.charAt(tail))) tail--; + } else result.append(s.charAt(head)); + } + + return result.toString(); + } +} diff --git a/src/ReversePrefixOfWord.java b/src/ReversePrefixOfWord.java new file mode 100644 index 0000000..1ea3564 --- /dev/null +++ b/src/ReversePrefixOfWord.java @@ -0,0 +1,19 @@ +// https://leetcode.com/problems/reverse-prefix-of-word +// T: O(|word|) +// S: O(|word|) + +public class ReversePrefixOfWord { + public String reversePrefix(String word, char ch) { + final StringBuilder result = new StringBuilder(); + boolean encounteredChar = false; + for (int i = 0 ; i < word.length() ; i++) { + if (!encounteredChar && word.charAt(i) == ch) { + result.append(word.charAt(i)).reverse(); + encounteredChar = true; + } else { + result.append(word.charAt(i)); + } + } + return result.toString(); + } +} diff --git a/src/ReverseStringII.java b/src/ReverseStringII.java new file mode 100644 index 0000000..8c597cf --- /dev/null +++ b/src/ReverseStringII.java @@ -0,0 +1,16 @@ +public class ReverseStringII { + public String reverseStr(String s, int k) { + StringBuilder result = new StringBuilder(); + for (int index = 0 ; index < s.length() ; ) { + for (int j = 0, reverseLength = Math.min(k, s.length() - index); j < reverseLength ; j++) { + result.append(s.charAt(index + reverseLength - j - 1)); + } + index += k; + for (int j = 0 ; j < k && index + j < s.length() ; j++) { + result.append(s.charAt(index + j)); + } + index += k; + } + return result.toString(); + } +} diff --git a/src/ReverseWordsInAString.java b/src/ReverseWordsInAString.java new file mode 100644 index 0000000..e30488c --- /dev/null +++ b/src/ReverseWordsInAString.java @@ -0,0 +1,19 @@ +// https://leetcode.com/problems/reverse-words-in-a-string +// T: O(s) +// S: O(s) + +public class ReverseWordsInAString { + private static final char SPACE = ' '; + + public static String reverseWords(String s) { + final String[] words = s.split(" "); + final StringBuilder result = new StringBuilder(); + for (int i = words.length - 1 ; i >= 0 ; i--) { + String word = words[i]; + if (word.isEmpty()) continue; + result.append(word).append(SPACE); + } + result.deleteCharAt(result.length() - 1); + return result.toString(); + } +} diff --git a/src/ReverseWordsInStringIII.java b/src/ReverseWordsInStringIII.java new file mode 100644 index 0000000..dff133e --- /dev/null +++ b/src/ReverseWordsInStringIII.java @@ -0,0 +1,15 @@ +public class ReverseWordsInStringIII { + public String reverseWords(String s) { + StringBuilder result = new StringBuilder(), buffer = new StringBuilder(); + for (int index = 0 ; index < s.length() ; index++) { + if (s.charAt(index) == ' ') { + result.append(result.length() == 0 ? "" : ' ').append(buffer.reverse()); + buffer = new StringBuilder(); + } else { + buffer.append(s.charAt(index)); + } + } + result.append(result.length() == 0 ? "" : ' ').append(buffer.reverse()); + return result.toString(); + } +} diff --git a/src/RichestCustomerWealth.java b/src/RichestCustomerWealth.java new file mode 100644 index 0000000..dacf5c5 --- /dev/null +++ b/src/RichestCustomerWealth.java @@ -0,0 +1,11 @@ +import java.util.Arrays; + +public class RichestCustomerWealth { + public int maximumWealth(int[][] accounts) { + int maxWealth = 0; + for (int[] customer : accounts) { + maxWealth = Math.max(maxWealth, Arrays.stream(customer).sum()); + } + return maxWealth; + } +} diff --git a/src/RingsAndRods.java b/src/RingsAndRods.java new file mode 100644 index 0000000..49f45fa --- /dev/null +++ b/src/RingsAndRods.java @@ -0,0 +1,32 @@ +// https://leetcode.com/problems/rings-and-rods +// T: O(|rings|) +// S: O(1) + +public class RingsAndRods { + public int countPoints(String rings) { + final boolean[][] rods = new boolean[10][3]; + for (int i = 0 ; i < rings.length() ; i += 2) { + rods[rings.charAt(i + 1) - '0'][toColorIndex(rings.charAt(i))] = true; + } + int points = 0; + for (boolean[] rod : rods) { + if (containsAllColors(rod)) { + points++; + } + } + return points; + } + + private int toColorIndex(char color) { + return switch (color) { + case 'R' -> 0; + case 'G' -> 1; + case 'B' -> 2; + default -> -1; + }; + } + + private boolean containsAllColors(boolean[] rod) { + return rod[0] && rod[1] && rod[2]; + } +} diff --git a/src/RobotReturnToOrigin.java b/src/RobotReturnToOrigin.java new file mode 100644 index 0000000..5c8aecf --- /dev/null +++ b/src/RobotReturnToOrigin.java @@ -0,0 +1,14 @@ +public class RobotReturnToOrigin { + public boolean judgeCircle(String moves) { + int vertical = 0, horizontal = 0; + for (int index = 0 ; index < moves.length() ; index++) { + switch (moves.charAt(index)) { + case 'U': vertical++; break; + case 'R': horizontal++; break; + case 'D': vertical--; break; + case 'L': horizontal--; break; + } + } + return vertical == 0 && horizontal == 0; + } +} diff --git a/src/RomanToInteger.java b/src/RomanToInteger.java index 0522fcd..b40d94f 100644 --- a/src/RomanToInteger.java +++ b/src/RomanToInteger.java @@ -1,35 +1,41 @@ -// https://leetcode.com/problems/roman-to-integer/ +// https://leetcode.com/problems/roman-to-integer +// T: O(|S|) +// S: O(1) -import java.util.HashMap; import java.util.Map; -import java.util.Scanner; +import java.util.Set; public class RomanToInteger { - private static final Map romanNumerals = new HashMap<>(); + private static final Map ROMAN_NUMERALS = Map.of( + 'I', 1, + 'V', 5, + 'X', 10, + 'L', 50, + 'C', 100, + 'D', 500, + 'M', 1000 + ); - static { - romanNumerals.put('I', 1); - romanNumerals.put('V', 5); - romanNumerals.put('X', 10); - romanNumerals.put('L', 50); - romanNumerals.put('C', 100); - romanNumerals.put('D', 500); - romanNumerals.put('M', 1000); - } + private static final Map> DECREMENT_ROMAN_NUMERALS = Map.of( + 'I', Set.of('V', 'X'), + 'X', Set.of('L', 'C'), + 'C', Set.of('D', 'M') + ); - private static int romanToInt(String string) { - int value = 0; - for (int index = 0 ; index < string.length() ; index++) { - if (index < string.length() - 1 && value(string.charAt(index)) < value(string.charAt(index + 1))) { - value -= value(string.charAt(index)); + public int romanToInt(String s) { + int number = 0; + for (int i = 0 ; i < s.length() ; ) { + final char c = s.charAt(i); + if (DECREMENT_ROMAN_NUMERALS.containsKey(c) + && i + 1 < s.length() + && DECREMENT_ROMAN_NUMERALS.get(c).contains(s.charAt(i + 1))) { + number += ROMAN_NUMERALS.get(s.charAt(i + 1)) - ROMAN_NUMERALS.get(c); + i += 2; } else { - value += value(string.charAt(index)); + number += ROMAN_NUMERALS.get(c); + i++; } } - return value; - } - - private static int value(char character) { - return romanNumerals.get(character); + return number; } } diff --git a/src/RootEqualsSumOfChildren.java b/src/RootEqualsSumOfChildren.java new file mode 100644 index 0000000..52ee7c3 --- /dev/null +++ b/src/RootEqualsSumOfChildren.java @@ -0,0 +1,9 @@ +// https://leetcode.com/problems/root-equals-sum-of-children +// T: O(1) +// S: O(1) + +public class RootEqualsSumOfChildren { + public boolean checkTree(TreeNode root) { + return root.val == root.left.val + root.right.val; + } +} diff --git a/src/RotateImage.java b/src/RotateImage.java new file mode 100644 index 0000000..c56b02d --- /dev/null +++ b/src/RotateImage.java @@ -0,0 +1,53 @@ +// https://leetcode.com/problems/rotate-image +// T: O(n ^ 2) +// S: O(1) + +public class RotateImage { + private static final class Point { + private final int row; + private final int column; + + private Point(int row, int column) { + this.row = row; + this.column = column; + } + } + + public void rotate(int[][] matrix) { + final int frames = (matrix.length + 1) / 2; + for (int frame = 0 ; frame < frames ; frame++) { + rotate90Degrees(matrix, frame); + } + } + + private void rotate90Degrees(int[][] matrix, int frame) { + for (int i = 0 ; i < matrix.length - 2 * frame - 1 ; i++) { + Point p1 = getCoordinates(frame, 0, matrix.length, i); + int temp1 = get(matrix, p1), temp2; + for (int k = 0 ; k < 4 ; k++) { + Point p2 = getCoordinates(frame, (k + 1) % 4, matrix.length, i); + temp2 = get(matrix, p2); + set(matrix, p2, temp1); + temp1 = temp2; + } + } + } + + private int get(int[][] matrix, Point point) { + return matrix[point.row][point.column]; + } + + private void set(int[][] matrix, Point point, int value) { + matrix[point.row][point.column] = value; + } + + private Point getCoordinates(int frame, int k, int size, int shift) { + return switch (k) { + case 0 -> new Point(frame, frame + shift); + case 1 -> new Point(frame + shift, size - 1 - frame); + case 2 -> new Point(size - 1 - frame, size - 1 - frame - shift); + case 3 -> new Point(size - 1 - frame - shift, frame); + default -> null; + }; + } +} diff --git a/src/RotateList.java b/src/RotateList.java new file mode 100644 index 0000000..52fef21 --- /dev/null +++ b/src/RotateList.java @@ -0,0 +1,45 @@ +// https://leetcode.com/problems/rotate-list +// T: O(N) +// S: O(1) + +public class RotateList { + + public ListNode rotateRight(ListNode head, int k) { + final int length = getLength(head); + if (length == 0) return head; + final int rotations = k % length; + if (rotations == 0) return head; + final ListNode last = getLastNode(head); + final ListNode cutoffNode = getCutoffNode(head, rotations, length); + final ListNode newHead = cutoffNode.next; + last.next = head; + cutoffNode.next = null; + return newHead; + } + + private int getLength(ListNode head) { + int length = 0; + ListNode current = head; + while (current != null) { + current = current.next; + length++; + } + return length; + } + + private ListNode getLastNode(ListNode head) { + ListNode current = head; + while (current.next != null) { + current = current.next; + } + return current; + } + + private ListNode getCutoffNode(ListNode head, int rotations, int length) { + ListNode current = head; + for (int i = 0 ; i < length - rotations - 1 ; i++) { + current = current.next; + } + return current; + } +} diff --git a/src/RotateString.java b/src/RotateString.java new file mode 100644 index 0000000..44e9634 --- /dev/null +++ b/src/RotateString.java @@ -0,0 +1,41 @@ +public class RotateString { + public boolean rotateString(String s, String goal) { + if (s.length() != goal.length()) return false; + if (s.equals(goal) || s.length() == 0) return true; + return patternExists(s + s, goal); + } + + private boolean patternExists(String string, String pattern) { + return kmpIndex(string, pattern) != -1; + } + + private int kmpIndex(String string, String pattern) { + int[] patternPrefix = patternPrefixArray(pattern); + for (int t = 0, p = 0 ; t < string.length() && p < pattern.length() ; ) { + if (string.charAt(t) == pattern.charAt(p)) { + if (p == pattern.length() - 1) return t - p; + p++; + t++; + } else if (p != 0) { + p = patternPrefix[p - 1]; + } else { + t++; + } + } + return -1; + } + + private int[] patternPrefixArray(String pattern) { + int[] patternPrefix = new int[pattern.length()]; + for (int j = 0, i = 1 ; i < pattern.length() && j < pattern.length() ; ) { + if (pattern.charAt(j) == pattern.charAt(i)) { + patternPrefix[i++] = j++ + 1; + } else if (j == 0) { + patternPrefix[i++] = 0; + } else { + j = patternPrefix[j - 1]; + } + } + return patternPrefix; + } +} diff --git a/src/RottingOranges.java b/src/RottingOranges.java new file mode 100644 index 0000000..015528e --- /dev/null +++ b/src/RottingOranges.java @@ -0,0 +1,101 @@ +// https://leetcode.com/problems/rotting-oranges +// T: O(m * n) +// S: O(m * n) + +import java.util.LinkedList; +import java.util.Queue; + +public class RottingOranges { + private record RottenOrange(int row, int column, int time) {} + + private static final int FRESH_ORANGE = 1; + private static final int ROTTEN_ORANGE = 2; + + public int orangesRotting(int[][] grid) { + final Queue queue = new LinkedList<>(); + addAllRottenOrangesToQueue(grid, queue); + int elapsedTime = 0; + + while (!queue.isEmpty()) { + RottenOrange orange = queue.poll(); + addAdjacentOrangesInQueue(orange, queue, grid); + elapsedTime = Math.max(elapsedTime, orange.time); + } + + if (containsFreshOranges(grid)) return -1; + return elapsedTime; + } + + private void addAllRottenOrangesToQueue(int[][] grid, final Queue queue) { + for (int row = 0 ; row < grid.length ; row++) { + for (int column = 0 ; column < grid[0].length ; column++) { + if (isRottenOrange(grid[row][column])) { + queue.add(new RottenOrange(row, column, 0)); + } + } + } + } + + private boolean isRottenOrange(int orange) { + return orange == ROTTEN_ORANGE; + } + + private boolean isFreshOrange(int orange) { + return orange == FRESH_ORANGE; + } + + private boolean containsFreshOranges(int[][] grid) { + for (int[] row : grid) { + for (int orange : row) { + if (isFreshOrange(orange)) return true; + } + } + return false; + } + + private void addAdjacentOrangesInQueue(RottenOrange orange, Queue queue, int[][] grid) { + addOrangeOnTop(orange, queue, grid); + addOrangeOnRight(orange, queue, grid); + addOrangeOnBottom(orange, queue, grid); + addOrangeOnLeft(orange, queue, grid); + } + + private void addOrangeOnTop(RottenOrange orange, Queue queue, int[][] grid) { + if (isValidPosition(grid, orange.row - 1, orange.column) && isFreshOrange(grid[orange.row - 1][orange.column])) { + markRotten(grid, orange.row - 1, orange.column); + queue.add(new RottenOrange(orange.row - 1, orange.column, orange.time + 1)); + } + } + + private void addOrangeOnRight(RottenOrange orange, Queue queue, int[][] grid) { + if (isValidPosition(grid, orange.row, orange.column + 1) && isFreshOrange(grid[orange.row][orange.column + 1])) { + markRotten(grid, orange.row, orange.column + 1); + queue.add(new RottenOrange(orange.row, orange.column + 1, orange.time + 1)); + } + } + + private void addOrangeOnBottom(RottenOrange orange, Queue queue, int[][] grid) { + if (isValidPosition(grid, orange.row + 1, orange.column) && isFreshOrange(grid[orange.row + 1][orange.column])) { + markRotten(grid, orange.row + 1, orange.column); + queue.add(new RottenOrange(orange.row + 1, orange.column, orange.time + 1)); + } + } + + private void addOrangeOnLeft(RottenOrange orange, Queue queue, int[][] grid) { + if (isValidPosition(grid, orange.row, orange.column - 1) && isFreshOrange(grid[orange.row][orange.column - 1])) { + markRotten(grid, orange.row, orange.column - 1); + queue.add(new RottenOrange(orange.row, orange.column - 1, orange.time + 1)); + } + } + + private boolean isValidPosition(int[][] grid, int row, int column) { + return row >= 0 + && row < grid.length + && column >= 0 + && column < grid[0].length; + } + + private void markRotten(int[][] grid, int row, int column) { + grid[row][column] = ROTTEN_ORANGE; + } +} diff --git a/src/RowWithMaximumOnes.java b/src/RowWithMaximumOnes.java new file mode 100644 index 0000000..9330490 --- /dev/null +++ b/src/RowWithMaximumOnes.java @@ -0,0 +1,28 @@ +// https://leetcode.com/problems/row-with-maximum-ones +// m: number of rows in matrix +// n: number of columns in matrix +// T: O(m * n) +// S: O(m * n) + +public class RowWithMaximumOnes { + public int[] rowAndMaximumOnes(int[][] matrix) { + final int rows = matrix.length, columns = matrix[0].length; + int maxOnes = 0, maxRow = 0; + for (int row = 0 ; row < rows ; row++) { + final int onesCount = getOnesCount(matrix[row]); + if (onesCount > maxOnes) { + maxOnes = onesCount; + maxRow = row; + } + } + return new int[] { maxRow, maxOnes }; + } + + private int getOnesCount(int[] array) { + int count = 0; + for (int element : array) { + if (element == 1) count++; + } + return count; + } +} diff --git a/src/RunningSumOf1DArray.java b/src/RunningSumOf1DArray.java new file mode 100644 index 0000000..92ee285 --- /dev/null +++ b/src/RunningSumOf1DArray.java @@ -0,0 +1,10 @@ +public class RunningSumOf1DArray { + public int[] runningSum(int[] nums) { + final int[] sum = new int[nums.length]; + sum[0] = nums[0]; + for (int index = 1 ; index < nums.length ; index++) { + sum[index] = nums[index] + sum[index - 1]; + } + return sum; + } +} diff --git a/src/SameTree.java b/src/SameTree.java index 9dc840f..4f8fda6 100644 --- a/src/SameTree.java +++ b/src/SameTree.java @@ -1,9 +1,4 @@ public class SameTree { - private static class TreeNode { - int val; - TreeNode left; - TreeNode right; - } public boolean isSameTree(TreeNode p, TreeNode q) { if (p == null && q == null) { diff --git a/src/ScoreOfAString.java b/src/ScoreOfAString.java new file mode 100644 index 0000000..eedb041 --- /dev/null +++ b/src/ScoreOfAString.java @@ -0,0 +1,13 @@ +// https://leetcode.com/problems/score-of-a-string +// T: O(N) +// S: O(1) + +public class ScoreOfAString { + public int scoreOfString(String s) { + int sum = 0; + for (int i = 0 ; i < s.length() - 1 ; i++) { + sum += Math.abs(s.charAt(i) - s.charAt(i + 1)); + } + return sum; + } +} diff --git a/src/SearchA2DMatrix.java b/src/SearchA2DMatrix.java new file mode 100644 index 0000000..91ecaa1 --- /dev/null +++ b/src/SearchA2DMatrix.java @@ -0,0 +1,17 @@ +// https://leetcode.com/problems/search-a-2d-matrix +// T: O(log(m*n)) +// S: O(1) + +public class SearchA2DMatrix { + public boolean searchMatrix(int[][] matrix, int target) { + final int rows = matrix.length, columns = matrix[0].length; + int left = 0, right = rows * columns - 1, middle; + while (left <= right) { + middle = left + (right - left) / 2; + if (matrix[middle / columns][middle % columns] == target) return true; + else if (matrix[middle / columns][middle % columns] > target) right = middle - 1; + else left = middle + 1; + } + return false; + } +} diff --git a/src/SearchA2DMatrixII.java b/src/SearchA2DMatrixII.java new file mode 100644 index 0000000..787e00e --- /dev/null +++ b/src/SearchA2DMatrixII.java @@ -0,0 +1,15 @@ +// https://leetcode.com/problems/search-a-2d-matrix-ii +// T: O(m + n) +// S: O(1) + +public class SearchA2DMatrixII { + public boolean searchMatrix(int[][] matrix, int target) { + final int rows = matrix.length, columns = matrix[0].length; + for (int column = columns - 1, row = 0 ; row < rows && column >= 0 ; ) { + if (matrix[row][column] == target) return true; + else if (matrix[row][column] < target) row++; + else column--; + } + return false; + } +} diff --git a/src/SearchInBinarySearchTree.java b/src/SearchInBinarySearchTree.java new file mode 100644 index 0000000..c36517a --- /dev/null +++ b/src/SearchInBinarySearchTree.java @@ -0,0 +1,6 @@ +public class SearchInBinarySearchTree { + public TreeNode searchBST(TreeNode root, int val) { + if (root == null || root.val == val) return root; + return root.val < val ? searchBST(root.right, val) : searchBST(root.left, val); + } +} diff --git a/src/SearchInRotatedSortedArray.java b/src/SearchInRotatedSortedArray.java new file mode 100644 index 0000000..971e701 --- /dev/null +++ b/src/SearchInRotatedSortedArray.java @@ -0,0 +1,35 @@ +// https://leetcode.com/problems/search-in-rotated-sorted-array +// T: O(logN) +// S: O(1) + +public class SearchInRotatedSortedArray { + public int search(int[] nums, int target) { + final int pivotIndex = binarySearchPivotIndex(nums); + final int answer = binarySearch(nums, 0, pivotIndex - 1, target); + if (answer != -1) { + return answer; + } + return binarySearch(nums, pivotIndex, nums.length - 1, target); + } + + private static int binarySearchPivotIndex(int[] array) { + int left = 0, right = array.length - 1, middle; + while (left <= right) { + middle = left + (right - left) / 2; + if (array[middle] > array[array.length - 1]) left = middle + 1; + else right = middle - 1; + } + return left; + } + + private static int binarySearch(int[] array, int start, int end, int x) { + int left = start, right = end, middle; + while (left <= right) { + middle = left + (right - left) / 2; + if (array[middle] == x) return middle; + else if (array[middle] < x) left = middle + 1; + else right = middle - 1; + } + return -1; + } +} diff --git a/src/SearchInRotatedSortedArrayII.java b/src/SearchInRotatedSortedArrayII.java new file mode 100644 index 0000000..6291ce0 --- /dev/null +++ b/src/SearchInRotatedSortedArrayII.java @@ -0,0 +1,12 @@ +// https://leetcode.com/problems/search-in-rotated-sorted-array-ii +// T: O(N) +// S: O(1) + +public class SearchInRotatedSortedArrayII { + public boolean search(int[] nums, int target) { + for (int element : nums) { + if (element == target) return true; + } + return false; + } +} diff --git a/src/SearchInSortedArrayOfUnknownSize.java b/src/SearchInSortedArrayOfUnknownSize.java new file mode 100644 index 0000000..f6d3389 --- /dev/null +++ b/src/SearchInSortedArrayOfUnknownSize.java @@ -0,0 +1,26 @@ +// https://leetcode.com/problems/search-in-a-sorted-array-of-unknown-size +// T: O(logN) +// S: O(1) + +public class SearchInSortedArrayOfUnknownSize { + public interface ArrayReader { + int get(int index); + } + + public int search(ArrayReader reader, int target) { + int left = 0, right = 1, middle; + + while (reader.get(right) < target) { + left = right; + right *= 2; + } + + while (left <= right) { + middle = left + (right - left) / 2; + if (reader.get(middle) == target) return middle; + else if (reader.get(middle) < target) left = middle + 1; + else right = middle - 1; + } + return -1; + } +} diff --git a/src/SecondLargestDigitInAString.java b/src/SecondLargestDigitInAString.java new file mode 100644 index 0000000..6b61a2c --- /dev/null +++ b/src/SecondLargestDigitInAString.java @@ -0,0 +1,18 @@ +public class SecondLargestDigitInAString { + public int secondHighest(String s) { + int largestDigit = -1, secondLargestDigit = -1; + for (int index = 0 ; index < s.length() ; index++) { + if (Character.isDigit(s.charAt(index))) { + int digit = s.charAt(index) - '0'; + if (digit > largestDigit) { + int temp = largestDigit; + largestDigit = digit; + secondLargestDigit = temp; + } else if (digit < largestDigit && digit > secondLargestDigit) { + secondLargestDigit = digit; + } + } + } + return secondLargestDigit; + } +} diff --git a/src/SecondMinimumNodeInBinaryTree.java b/src/SecondMinimumNodeInBinaryTree.java new file mode 100644 index 0000000..6aa57bf --- /dev/null +++ b/src/SecondMinimumNodeInBinaryTree.java @@ -0,0 +1,27 @@ +import java.util.HashSet; +import java.util.PriorityQueue; +import java.util.Queue; +import java.util.Set; + +public class SecondMinimumNodeInBinaryTree { + public int findSecondMinimumValue(TreeNode root) { + Set elements = treeToSet(root); + if (elements.size() < 2) return -1; + Queue queue = new PriorityQueue<>(elements); + queue.poll(); + return queue.peek(); + } + + private static Set treeToSet(TreeNode root) { + Set result = new HashSet<>(); + addTreeNodesToSet(root, result); + return result; + } + + private static void addTreeNodesToSet(TreeNode root, Set set) { + if (root == null) return; + set.add(root.val); + addTreeNodesToSet(root.left, set); + addTreeNodesToSet(root.right, set); + } +} diff --git a/src/SelfDividingNumbers.java b/src/SelfDividingNumbers.java new file mode 100644 index 0000000..4c05b36 --- /dev/null +++ b/src/SelfDividingNumbers.java @@ -0,0 +1,24 @@ +import java.util.ArrayList; +import java.util.List; + +public class SelfDividingNumbers { + public List selfDividingNumbers(int left, int right) { + List result = new ArrayList<>(); + for(int number = left ; number <= right ; number++) { + if (isSefDividing(number)) { + result.add(number); + } + } + return result; + } + + private boolean isSefDividing(int number) { + int original = number, digit; + while (number > 0) { + digit = number % 10; + if (digit == 0 || original % digit != 0) return false; + number /= 10; + } + return true; + } +} diff --git a/src/SemiOrderedPermutation.java b/src/SemiOrderedPermutation.java new file mode 100644 index 0000000..47bb5a9 --- /dev/null +++ b/src/SemiOrderedPermutation.java @@ -0,0 +1,25 @@ +// https://leetcode.com/problems/semi-ordered-permutation +// T: O(N) +// S: O(1) + +import java.util.Arrays; + +public class SemiOrderedPermutation { + public int semiOrderedPermutation(int[] nums) { + final int startIndex = findIndexOf(nums, 1); + final int endIndex = findIndexOf(nums, nums.length); + final int endDrift = nums.length - endIndex - 1; + + if (endIndex < startIndex) { + return startIndex + endDrift - 1; + } + return startIndex + endDrift; + } + + private int findIndexOf(int[] array, int element) { + for (int i = 0 ; i < array.length ; i++) { + if (array[i] == element) return i; + } + return -1; + } +} diff --git a/src/SeparateTheDigitsInAnArray.java b/src/SeparateTheDigitsInAnArray.java new file mode 100644 index 0000000..b9b94a6 --- /dev/null +++ b/src/SeparateTheDigitsInAnArray.java @@ -0,0 +1,31 @@ +// https://leetcode.com/problems/separate-the-digits-in-an-array +// T: O(N) +// S: O(N) + +import java.util.ArrayList; +import java.util.List; + +public class SeparateTheDigitsInAnArray { + public int[] separateDigits(int[] nums) { + final List digits = new ArrayList<>(); + for (int number : nums) { + addDigitsToList(digits, number); + } + return toArray(digits); + } + + private int[] toArray(List list) { + final int[] array = new int[list.size()]; + for (int index = 0 ; index < list.size() ; index++) { + array[index] = list.get(index); + } + return array; + } + + private void addDigitsToList(List digits, int number) { + final String num = number + ""; + for (int index = 0 ; index < num.length() ; index++) { + digits.add(num.charAt(index) - '0'); + } + } +} diff --git a/src/SetMatrixZeroes.java b/src/SetMatrixZeroes.java new file mode 100644 index 0000000..fd1cb92 --- /dev/null +++ b/src/SetMatrixZeroes.java @@ -0,0 +1,46 @@ +// https://leetcode.com/problems/set-matrix-zeroes/ +// T: O(m * n) +// S: O(1) + +public class SetMatrixZeroes { + public void setZeroes(int[][] matrix) { + final int rows = matrix.length, columns = matrix[0].length; + boolean firstColumnIsZero = false; + + for (int row = 0 ; row < rows ; row++) { + if (matrix[row][0] == 0) firstColumnIsZero = true; + for (int column = 1 ; column < columns ; column++) { + if (matrix[row][column] == 0) { + matrix[row][0] = 0; + matrix[0][column] = 0; + } + } + } + + for (int column = columns - 1 ; column >= 1 ; column--) { + if (matrix[0][column] == 0) { + markColumn0(matrix, column); + } + } + + for (int row = rows - 1 ; row >= 0 ; row--) { + if (matrix[row][0] == 0) { + markRow0(matrix, row); + } + } + + if (firstColumnIsZero) markColumn0(matrix, 0); + } + + private void markRow0(int[][] matrix, int row) { + for (int column = 0 ; column < matrix[0].length ; column++) { + matrix[row][column] = 0; + } + } + + private void markColumn0(int[][] matrix, int column) { + for (int row = 0 ; row < matrix.length ; row++) { + matrix[row][column] = 0; + } + } +} diff --git a/src/SetMismatch.java b/src/SetMismatch.java new file mode 100644 index 0000000..d378ef5 --- /dev/null +++ b/src/SetMismatch.java @@ -0,0 +1,16 @@ +public class SetMismatch { + public int[] findErrorNums(int[] array) { + int repeated = 0, missing = 0; + for (int number : array) { + if (array[Math.abs(number) - 1] < 0) repeated = number; + else array[Math.abs(number) - 1] *= -1; + } + for (int index = 0 ; index < array.length ; index++) { + if (array[index] > 0) { + missing = index + 1; + break; + } + } + return new int[] {Math.abs(repeated), missing}; + } +} diff --git a/src/Shift2DGrid.java b/src/Shift2DGrid.java new file mode 100644 index 0000000..c5bf06e --- /dev/null +++ b/src/Shift2DGrid.java @@ -0,0 +1,34 @@ +import java.util.ArrayList; +import java.util.List; + +public class Shift2DGrid { + public static List> shiftGrid(int[][] grid, int k) { + final int rows = grid.length, columns = grid[0].length; + final List> result = getGrid(rows, columns); + final int rowOperations = k / columns; + for (int column = 0 ; column < columns ; column++) { + int rowShifts = (rowOperations + (k - columns * rowOperations - 1 >= column ? 1 : 0)) % rows; + int columnIndex = (columns + column - (k % columns)) % columns; + for (int row = 0 ; row < rows ; row++) { + result.get(row).set(column, grid[(rows + row - rowShifts) % rows][columnIndex]); + } + } + return result; + } + + private static List> getGrid(int rows, int columns) { + List> result = new ArrayList<>(rows); + for (int row = 0 ; row < rows ; row++) { + result.add(getList(columns)); + } + return result; + } + + private static List getList(int size) { + List result = new ArrayList<>(); + for (int i = 0 ; i < size ; i++) { + result.add(0); + } + return result; + } +} diff --git a/src/ShortestCompletingWord.java b/src/ShortestCompletingWord.java new file mode 100644 index 0000000..3d8349e --- /dev/null +++ b/src/ShortestCompletingWord.java @@ -0,0 +1,37 @@ +public class ShortestCompletingWord { + private final int[] primes = { + 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, + 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101 + }; + + public String shortestCompletingWord(String licensePlate, String[] words) { + long licenseHash = getHash(licensePlate); + int shortestCompletingWordLen = Integer.MAX_VALUE; + int shortestWordIndex = -1; + for (int index = 0 ; index < words.length ; index++) { + if (words[index].length() < shortestCompletingWordLen && containsAllChars(words[index], licenseHash)) { + shortestCompletingWordLen = words[index].length(); + shortestWordIndex = index; + } + } + return words[shortestWordIndex]; + } + + private long getHash(String string) { + long result = 1; + for (char character : string.toLowerCase().toCharArray()) { + if (Character.isAlphabetic(character)) { + result *= primes[character - 'a']; + } + } + return result; + } + + private boolean containsAllChars(String word, long hash) { + long result = 1; + for (char character : word.toCharArray()){ + result = (result * primes[character - 'a']) % hash; + } + return result == 0; + } +} diff --git a/src/ShortestDistanceToACharacter.java b/src/ShortestDistanceToACharacter.java new file mode 100644 index 0000000..4f7b682 --- /dev/null +++ b/src/ShortestDistanceToACharacter.java @@ -0,0 +1,16 @@ +public class ShortestDistanceToACharacter { + public int[] shortestToChar(String string, char c) { + int[] answer = new int[string.length()]; + for (int i = 0, l = Integer.MIN_VALUE ; i < string.length() ; i++) { + if (string.charAt(i) == c) l = i; + answer[i] = l == Integer.MIN_VALUE ? Integer.MAX_VALUE : i - l; + } + + for (int i = string.length() - 1, r = Integer.MAX_VALUE ; i >= 0 ; i--) { + if (string.charAt(i) == c) r = i; + answer[i] = Math.min(answer[i], r - i); + } + + return answer; + } +} diff --git a/src/ShortestDistanceToTargetStringInACircularArray.java b/src/ShortestDistanceToTargetStringInACircularArray.java new file mode 100644 index 0000000..bfc4b96 --- /dev/null +++ b/src/ShortestDistanceToTargetStringInACircularArray.java @@ -0,0 +1,17 @@ +// https://leetcode.com/problems/shortest-distance-to-target-string-in-a-circular-array +// T: O(N) +// S: O(1) + +public class ShortestDistanceToTargetStringInACircularArray { + public int closetTarget(String[] words, String target, int startIndex) { + if (words[startIndex].equals(target)) return 0; + + for (int left = (startIndex - 1 + words.length) % words.length, right = (startIndex + 1) % words.length, count = 1; + count <= words.length / 2; + left = (left - 1 + words.length) % words.length, right = (right + 1) % words.length, count++ + ) { + if (words[left].equals(target) || words[right].equals(target)) return count; + } + return -1; + } +} diff --git a/src/ShortestPathInBinaryMatrix.java b/src/ShortestPathInBinaryMatrix.java new file mode 100644 index 0000000..0a21dd3 --- /dev/null +++ b/src/ShortestPathInBinaryMatrix.java @@ -0,0 +1,64 @@ +// https://leetcode.com/problems/shortest-path-in-binary-matrix +// N = total number of vertices +// T: O(N) +// S: O(N) + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + +public class ShortestPathInBinaryMatrix { + private static final List> directions = List.of( + List.of(-1, -1), + List.of(-1, 0), + List.of(-1, 1), + List.of(1, -1), + List.of(1, 0), + List.of(1, 1), + List.of(0, -1), + List.of(0, 1) + ); + + public int shortestPathBinaryMatrix(int[][] grid) { + final int n = grid.length; + if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1) { + return -1; + } + + final Queue queue = new LinkedList<>(); + queue.add(new int[] {0, 0}); + grid[0][0] = 1; + + while (!queue.isEmpty()) { + final int[] position = queue.poll(); + if (position[0] == n - 1 && position[1] == n - 1) { + return grid[n - 1][n - 1]; + } + + for (int[] neighbour : getNeighbours(position, grid)) { + queue.add(neighbour); + grid[neighbour[0]][neighbour[1]] = grid[position[0]][position[1]] + 1; + } + } + + return -1; + } + + private static List getNeighbours(int[] position, int[][] grid) { + final List result = new ArrayList<>(); + for (List direction : directions) { + final int row = position[0] + direction.get(0); + final int column = position[1] + direction.get(1); + if (isValid(grid, row, column) && grid[row][column] == 0) { + result.add(new int[] { row, column }); + } + } + return result; + } + + private static boolean isValid(int[][] grid, int row, int column) { + final int n = grid.length; + return row >= 0 && row < n && column >= 0 && column < n; + } +} diff --git a/src/ShortestSubarrayWithORAtLeastKI.java b/src/ShortestSubarrayWithORAtLeastKI.java new file mode 100644 index 0000000..4a3ed45 --- /dev/null +++ b/src/ShortestSubarrayWithORAtLeastKI.java @@ -0,0 +1,19 @@ +// https://leetcode.com/problems/shortest-subarray-with-or-at-least-k-i +// T: O(N^2) +// S: O(1) + +public class ShortestSubarrayWithORAtLeastKI { + public int minimumSubarrayLength(int[] array, int k) { + int minLength = Integer.MAX_VALUE; + for (int i = 0 ; i < array.length ; i++) { + int current = array[i]; + for (int j = i ; j < array.length ; j++) { + current |= array[j]; + if (current >= k) { + minLength = Math.min(minLength, j - i + 1); + } + } + } + return minLength == Integer.MAX_VALUE ? -1 : minLength; + } +} diff --git a/src/ShortestUnsortedContinuousSubarray.java b/src/ShortestUnsortedContinuousSubarray.java new file mode 100644 index 0000000..0ca2675 --- /dev/null +++ b/src/ShortestUnsortedContinuousSubarray.java @@ -0,0 +1,12 @@ +public class ShortestUnsortedContinuousSubarray { + public int findUnsortedSubarray(int[] nums) { + int n = nums.length, l = n, r = 0, max = nums[0], min = nums[n - 1]; + for (int i = 1; i < n; i++) { + if (nums[i] < max) r = i + 1; + else max = nums[i]; + if (nums[n - 1 - i] > min) l = n - 1 - i - 1; + else min = nums[n - 1 - i]; + } + return Math.max(0, r - l - 1); + } +} diff --git a/src/ShortestWordDistance.java b/src/ShortestWordDistance.java new file mode 100644 index 0000000..bca102e --- /dev/null +++ b/src/ShortestWordDistance.java @@ -0,0 +1,22 @@ +// https://leetcode.com/problems/shortest-word-distance +// N: number of words, M: average word length +// T: O(N * M) +// S: O(1) + +public class ShortestWordDistance { + public int shortestDistance(String[] wordsDict, String word1, String word2) { + int result = wordsDict.length, i = -1, j = -1; + for (int index = 0 ; index < wordsDict.length ; index++) { + if (wordsDict[index].equals(word1)) { + i = index; + } else if (wordsDict[index].equals(word2)) { + j = index; + } + + if (i != -1 && j != -1) { + result = Math.min(result, Math.abs(j - i)); + } + } + return result; + } +} diff --git a/src/ShuffleString.java b/src/ShuffleString.java new file mode 100644 index 0000000..4c3a13e --- /dev/null +++ b/src/ShuffleString.java @@ -0,0 +1,9 @@ +public class ShuffleString { + public String restoreString(String s, int[] indices) { + final char[] result = new char[indices.length]; + for (int i = 0 ; i < s.length() ; i++) { + result[indices[i]] = s.charAt(i); + } + return String.valueOf(result); + } +} diff --git a/src/ShuffleTheArray.java b/src/ShuffleTheArray.java new file mode 100644 index 0000000..1c78df6 --- /dev/null +++ b/src/ShuffleTheArray.java @@ -0,0 +1,10 @@ +public class ShuffleTheArray { + public int[] shuffle(int[] nums, int n) { + final int[] result = new int[nums.length]; + for (int i = 0 ; i < nums.length / 2 ; i++) { + result[2 * i] = nums[i]; + result[2 * i + 1] = nums[nums.length / 2 + i]; + } + return result; + } +} diff --git a/src/SignOfTheProductOfAnArray.java b/src/SignOfTheProductOfAnArray.java new file mode 100644 index 0000000..5702861 --- /dev/null +++ b/src/SignOfTheProductOfAnArray.java @@ -0,0 +1,18 @@ +// https://leetcode.com/problems/sign-of-the-product-of-an-array +// T: O(N) +// S: O(1) + +public class SignOfTheProductOfAnArray { + public int arraySign(int[] nums) { + int sign = 1; + for (int element : nums) { + sign *= signum(element); + } + return sign; + } + + private int signum(int x) { + if (x == 0) return 0; + return x > 0 ? 1 : -1; + } +} diff --git a/src/SimplifyPath.java b/src/SimplifyPath.java new file mode 100644 index 0000000..1c9f21f --- /dev/null +++ b/src/SimplifyPath.java @@ -0,0 +1,55 @@ +// https://leetcode.com/problems/simplify-path +// T: O(|path|) +// S: O(|path|) + +import java.util.LinkedList; + +public class SimplifyPath { + private static final char SLASH = '/'; + private static final String ROOT = "/"; + private static final String GO_ONE_LEVEL_UP = ".."; + private static final String STAY_WHERE_YOU_ARE = "."; + + public String simplifyPath(String path) { + final LinkedList fragments = new LinkedList<>(); + StringBuilder current = new StringBuilder(); + for (int i = 0 ; i < path.length() ; i++) { + if (path.charAt(i) == SLASH) { + if (!isEmpty(current)) { + addToFragments(current, fragments); + current = new StringBuilder(); + } + } else current.append(path.charAt(i)); + } + if (!isEmpty(current)) addToFragments(current, fragments); + return toPath(fragments); + } + + private String toPath(LinkedList fragments) { + if (fragments.isEmpty()) return ROOT; + StringBuilder result = new StringBuilder(); + for (StringBuilder fragment : fragments) { + result.append(SLASH).append(fragment); + } + return result.toString(); + } + + private void removeLast(LinkedList fragments) { + if (!fragments.isEmpty()) { + fragments.removeLast(); + } + } + + private void addToFragments(StringBuilder current, LinkedList fragments) { + String currentString = current.toString(); + if (GO_ONE_LEVEL_UP.equals(currentString)) { + removeLast(fragments); + } else if (!STAY_WHERE_YOU_ARE.equals(currentString)) { + fragments.add(current); + } + } + + private boolean isEmpty(StringBuilder stringBuilder) { + return stringBuilder.length() == 0; + } +} diff --git a/src/SingleNumberII.java b/src/SingleNumberII.java new file mode 100644 index 0000000..d28288e --- /dev/null +++ b/src/SingleNumberII.java @@ -0,0 +1,17 @@ +// https://leetcode.com/problems/single-number-ii +// T: O(n) +// S: O(1) + +public class SingleNumberII { + public int singleNumber(int[] nums) { + int x1 = 0, x2 = 0, mask = 0; + for (int element : nums) { + x2 ^= (x1 & element); + x1 ^= element; + mask = ~(x1 & x2); + x1 &= mask; + x2 &= mask; + } + return x1; + } +} diff --git a/src/SingleNumberIII.java b/src/SingleNumberIII.java new file mode 100644 index 0000000..6a261b5 --- /dev/null +++ b/src/SingleNumberIII.java @@ -0,0 +1,34 @@ +// https://leetcode.com/problems/single-number-iii +// T: O(N) +// S: O(1) + +public class SingleNumberIII { + public int[] singleNumber(int[] nums) { + // get xor of 2 unique numbers a ^ b + int diff = getXor(nums); + + diff = getLastSetBit(diff); + + final int[] result = {0, 0}; + for (int element : nums) { + // different set bit + if ((element & diff) == 0) { + result[0] ^= element; + } else result[1] ^= element; + } + + return result; + } + + private int getXor(int[] array) { + int diff = 0; + for (int element : array) { + diff ^= element; + } + return diff; + } + + private int getLastSetBit(int x) { + return x & -x; + } +} diff --git a/src/SlowestKey.java b/src/SlowestKey.java new file mode 100644 index 0000000..8aac92d --- /dev/null +++ b/src/SlowestKey.java @@ -0,0 +1,15 @@ +public class SlowestKey { + public char slowestKey(int[] releaseTimes, String keysPressed) { + char slowestKey = keysPressed.charAt(0); + int longestDuration = releaseTimes[0]; + for (int index = 1 ; index < keysPressed.length() ; index++) { + if (releaseTimes[index] - releaseTimes[index - 1] > longestDuration) { + longestDuration = releaseTimes[index] - releaseTimes[index - 1]; + slowestKey = keysPressed.charAt(index); + } else if (releaseTimes[index] - releaseTimes[index - 1] == longestDuration) { + slowestKey = (char) Math.max(slowestKey, keysPressed.charAt(index)); + } + } + return slowestKey; + } +} diff --git a/src/SmallestEvenMultiple.java b/src/SmallestEvenMultiple.java new file mode 100644 index 0000000..e1964f4 --- /dev/null +++ b/src/SmallestEvenMultiple.java @@ -0,0 +1,10 @@ +// https://leetcode.com/problems/smallest-even-multiple +// T: O(1) +// S: O(1) + +public class SmallestEvenMultiple { + public int smallestEvenMultiple(int n) { + if (n % 2 == 0) return n; + return n * 2; + } +} diff --git a/src/SmallestIndexWithEqualValue.java b/src/SmallestIndexWithEqualValue.java new file mode 100644 index 0000000..a9689a6 --- /dev/null +++ b/src/SmallestIndexWithEqualValue.java @@ -0,0 +1,12 @@ +// https://leetcode.com/problems/smallest-index-with-equal-value +// T: O(N) +// S: O(1) + +public class SmallestIndexWithEqualValue { + public int smallestEqual(int[] nums) { + for (int i = 0 ; i < nums.length ; i++) { + if (i % 10 == nums[i]) return i; + } + return -1; + } +} diff --git a/src/SmallestMissingIntegerGreaterThanSequentialPrefixSum.java b/src/SmallestMissingIntegerGreaterThanSequentialPrefixSum.java new file mode 100644 index 0000000..9147482 --- /dev/null +++ b/src/SmallestMissingIntegerGreaterThanSequentialPrefixSum.java @@ -0,0 +1,38 @@ +// https://leetcode.com/problems/smallest-missing-integer-greater-than-sequential-prefix-sum +// T: O(N) +// S: O(N) + +import java.util.HashSet; +import java.util.Set; + +public class SmallestMissingIntegerGreaterThanSequentialPrefixSum { + public int missingInteger(int[] array) { + final int sequentialSum = getLongestSequentialSum(array); + final Set numbers = toSet(array); + for (int start = sequentialSum ; ; start++) { + if (!numbers.contains(start)) { + return start; + } + } + } + + private static Set toSet(int[] array) { + final Set set = new HashSet<>(); + for (int element : array) { + set.add(element); + } + return set; + } + + private static int getLongestSequentialSum(int[] array) { + int sum = array[0]; + for (int i = 1 ; i < array.length ; i++) { + if (array[i] == array[i - 1] + 1) { + sum += array[i]; + } else { + break; + } + } + return sum; + } +} diff --git a/src/SmallestRangeI.java b/src/SmallestRangeI.java new file mode 100644 index 0000000..7bce761 --- /dev/null +++ b/src/SmallestRangeI.java @@ -0,0 +1,10 @@ +import java.util.Arrays; + +public class SmallestRangeI { + public int smallestRangeI(int[] nums, int k) { + return Math.max( + 0, + Arrays.stream(nums).max().getAsInt() - Arrays.stream(nums).min().getAsInt() - 2 * k + ); + } +} diff --git a/src/SmallestStringWithSwaps.java b/src/SmallestStringWithSwaps.java new file mode 100644 index 0000000..7835ef1 --- /dev/null +++ b/src/SmallestStringWithSwaps.java @@ -0,0 +1,71 @@ +// https://leetcode.com/problems/smallest-string-with-swaps +// s = |s|, p = |pairs| +// T: O(s + p * al(s) + s log(s)) al = inverse Ackermann function +// S: O(s + log(s)) + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.PriorityQueue; +import java.util.Queue; + +public class SmallestStringWithSwaps { + private static final class DisjointSet { + private final int[] root, rank; + + public DisjointSet(int size) { + root = new int[size]; + rank = new int[size]; + for (int i = 0 ; i < size ; i++) { + root[i] = i; + rank[i] = 1; + } + } + + public int find(int num) { + if (num == root[num]) { + return num; + } + return root[num] = find(root[num]); + } + + public boolean areConnected(int x, int y) { + return find(x) == find(y); + } + + public void union(int x, int y) { + final int rootX = find(x), rootY = find(y); + if (rootX == rootY) { + return; + } + if (rank[rootX] > rank[rootY]) { + root[rootY] = rootX; + } else if (rank[rootX] < rank[rootY]) { + root[rootX] = rootY; + } else { + root[rootY] = rootX; + rank[rootX]++; + } + } + } + + public String smallestStringWithSwaps(String s, List> pairs) { + final DisjointSet disjointSet = new DisjointSet(s.length()); + for (List pair : pairs) { + disjointSet.union(pair.get(0), pair.get(1)); + } + final Map> charMinHeaps = new HashMap<>(); + for (int i = 0 ; i < s.length() ; i++) { + final int root = disjointSet.find(i); + final Queue minHeap = charMinHeaps.getOrDefault(root, new PriorityQueue<>()); + minHeap.add(s.charAt(i)); + charMinHeaps.putIfAbsent(root, minHeap); + } + final StringBuilder builder = new StringBuilder(); + for (int i = 0 ; i < s.length() ; i++) { + final int root = disjointSet.find(i); + builder.append(charMinHeaps.get(root).poll()); + } + return builder.toString(); + } +} diff --git a/src/SnakesAndLadders.java b/src/SnakesAndLadders.java new file mode 100644 index 0000000..324c29e --- /dev/null +++ b/src/SnakesAndLadders.java @@ -0,0 +1,77 @@ +// https://leetcode.com/problems/snakes-and-ladders +// T: O(n^2) +// S: O(n^2) + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Queue; + +public class SnakesAndLadders { + private record Position(int row, int column) {} + + private record Info(int square, int cost) {} + + // BFS: T: O(V + E), V = n^2, E = 6n^2 T: O(n^2), S: O(V) = O(n^2) + public int snakesAndLadders(int[][] board) { + final int n = board.length; + final Map squareToPosition = createSquaresToPositions(n); + final Queue queue = new LinkedList<>() {{ add(new Info(1, 0)); }}; + final int[] distances = initializeDistances(n); + + while (!queue.isEmpty()) { + final Info info = queue.poll(); + if (distances[info.square] <= info.cost) { + continue; + } + + distances[info.square] = info.cost; + + for (int nextSquare : validPositions(board, info.square, squareToPosition)) { + queue.add(new Info(nextSquare, info.cost + 1)); + } + } + + return distances[n * n] == Integer.MAX_VALUE ? -1 : distances[n * n]; + } + + // T: O(1), S: O(1) + private static List validPositions(int[][] grid, int square, Map positions) { + final int n = grid.length; + final List result = new ArrayList<>(); + for (int i = 1 ; i <= 6 ; i++) { + final int nextSquare = square + i; + if (nextSquare > n * n) { + break; + } + final Position position = positions.get(nextSquare); + if (grid[position.row][position.column] == -1) { + result.add(nextSquare); + } else { + result.add(grid[position.row][position.column]); + } + } + return result; + } + + // T: O(n^2), S: O(n^2) + private static int[] initializeDistances(int n) { + final int[] distances = new int[n * n + 1]; + Arrays.fill(distances, Integer.MAX_VALUE); + return distances; + } + + // T: O(n^2), S: O(n^2) + private static Map createSquaresToPositions(int n) { + final Map result = new HashMap<>(); + for (int i = 1 ; i <= n * n ; i++) { + final int row = n - ((i - 1) / n) - 1; + final int column = (n - 1 - row) % 2 == 0 ? (i - 1) % n : n - 1 - ((i - 1) % n); + result.put(i, new Position(row, column)); + } + return result; + } +} diff --git a/src/SortArrayByIncreasingFrequency.java b/src/SortArrayByIncreasingFrequency.java new file mode 100644 index 0000000..c35aa26 --- /dev/null +++ b/src/SortArrayByIncreasingFrequency.java @@ -0,0 +1,32 @@ +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class SortArrayByIncreasingFrequency { + public int[] frequencySort(int[] array) { + Map frequencies = getFrequencies(array); + + return toArray(Arrays.stream(array).boxed().sorted((a, b) -> { + if (frequencies.get(a).equals(frequencies.get(b))) return b - a; + return frequencies.get(a) - frequencies.get(b); + }).collect(Collectors.toList())); + } + + private Map getFrequencies(int[] array) { + final Map frequencies = new HashMap<>(); + for (int element : array) { + frequencies.put(element, frequencies.getOrDefault(element, 0) + 1); + } + return frequencies; + } + + private int[] toArray(List list) { + final int[] array = new int[list.size()]; + for (int index = 0 ; index < list.size() ; index++) { + array[index] = list.get(index); + } + return array; + } +} diff --git a/src/SortArrayByParityII.java b/src/SortArrayByParityII.java new file mode 100644 index 0000000..2cc41b5 --- /dev/null +++ b/src/SortArrayByParityII.java @@ -0,0 +1,17 @@ +public class SortArrayByParityII { + public static int[] sortArrayByParityII(int[] array) { + for (int i = 0, j = 1; i < array.length ; i += 2) { + if ((array[i] & 1) == 1) { + while (j < array.length && ((array[j] & 1) == 1)) j += 2; + swap(array, i, j); + } + } + return array; + } + + private static void swap(int[] array, int i, int j) { + int temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } +} diff --git a/src/SortColors.java b/src/SortColors.java new file mode 100644 index 0000000..90ea3f0 --- /dev/null +++ b/src/SortColors.java @@ -0,0 +1,21 @@ +// https://leetcode.com/problems/sort-colors +// T: O(n) single pass solution +// S: O(1) + +public class SortColors { + public void sortColors(int[] nums) { + int zerosIndex = 0; + int onesIndex = 0; + + for (int i = 0 ; i < nums.length ; i++) { + int temp = nums[i]; + nums[i] = 2; + if (temp == 0) { + nums[onesIndex++] = 1; + nums[zerosIndex++] = 0; + } else if (temp == 1) { + nums[onesIndex++] = 1; + } + } + } +} diff --git a/src/SortEvenAndOddIndicesIndependently.java b/src/SortEvenAndOddIndicesIndependently.java new file mode 100644 index 0000000..a0a695a --- /dev/null +++ b/src/SortEvenAndOddIndicesIndependently.java @@ -0,0 +1,28 @@ +// https://leetcode.com/problems/sort-even-and-odd-indices-independently +// T: O(n log(n)) +// S: O(n) + +import java.util.Arrays; +import java.util.Comparator; + +public class SortEvenAndOddIndicesIndependently { + public int[] sortEvenOdd(int[] nums) { + final int[] even = new int[(nums.length + 1) / 2]; + final Integer[] odd = new Integer[nums.length / 2]; + + for (int i = 0 ; i < nums.length ; i++) { + if (i % 2 == 0) even[i / 2] = nums[i]; + else odd[i / 2] = nums[i]; + } + + Arrays.sort(even); + Arrays.sort(odd, Comparator.reverseOrder()); + + for (int i = 0 ; i < nums.length ; i++) { + if (i % 2 == 0) nums[i] = even[i / 2]; + else nums[i] = odd[i / 2]; + } + + return nums; + } +} diff --git a/src/SortIntegersByTheNumberOf1Bits.java b/src/SortIntegersByTheNumberOf1Bits.java new file mode 100644 index 0000000..3485fc5 --- /dev/null +++ b/src/SortIntegersByTheNumberOf1Bits.java @@ -0,0 +1,31 @@ +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class SortIntegersByTheNumberOf1Bits { + public int[] sortByBits(int[] array) { + List sorted = Arrays.stream(array).boxed().sorted((a, b) -> { + final int setBits1 = setBits(a), setBits2 = setBits(b); + if (setBits1 == setBits2) return Integer.compare(a, b); + return Integer.compare(setBits1, setBits2); + }).collect(Collectors.toList()); + return toArray(sorted); + } + + private int[] toArray(List array) { + final int[] result = new int[array.size()]; + for (int index = 0 ; index < result.length ; index++) { + result[index] = array.get(index); + } + return result; + } + + private int setBits(int number) { + int setBits = 0; + while (number > 0) { + setBits += number & 1; + number >>= 1; + } + return setBits; + } +} diff --git a/src/SortList.java b/src/SortList.java new file mode 100644 index 0000000..9c838e3 --- /dev/null +++ b/src/SortList.java @@ -0,0 +1,41 @@ +// https://leetcode.com/problems/sort-list +// T: O(N log(N)) +// S: O(log(N)) + +public class SortList { + public ListNode sortList(ListNode head) { + if (head == null || head.next == null) return head; + ListNode mid = getMid(head); + ListNode left = sortList(head); + ListNode right = sortList(mid); + return merge(left, right); + } + + ListNode merge(ListNode list1, ListNode list2) { + ListNode dummyHead = new ListNode(); + ListNode tail = dummyHead; + while (list1 != null && list2 != null) { + if (list1.val < list2.val) { + tail.next = list1; + list1 = list1.next; + } else { + tail.next = list2; + list2 = list2.next; + } + tail = tail.next; + } + tail.next = (list1 != null ? list1 : list2); + return dummyHead.next; + } + + ListNode getMid(ListNode head) { + ListNode midPrev = null; + while (head != null && head.next != null) { + midPrev = (midPrev == null ? head : midPrev.next); + head = head.next.next; + } + ListNode mid = midPrev.next; + midPrev.next = null; + return mid; + } +} diff --git a/src/SortThePeople.java b/src/SortThePeople.java new file mode 100644 index 0000000..9d04187 --- /dev/null +++ b/src/SortThePeople.java @@ -0,0 +1,33 @@ +// https://leetcode.com/problems/sort-the-people +// T: O(n + nlogn) +// S: O(n) + +import java.util.ArrayList; +import java.util.List; + +public class SortThePeople { + private record Person(String name, int height) {} + + public String[] sortPeople(String[] names, int[] heights) { + final List people = getPeople(names, heights); + people.sort((a, b) -> Integer.compare(b.height, a.height)); + return toNameArray(people); + } + + private String[] toNameArray(List people) { + final String[] names = new String[people.size()]; + int k = 0; + for (Person person : people) { + names[k++] = person.name; + } + return names; + } + + private List getPeople(String[] names, int[] heights) { + final List people = new ArrayList<>(); + for (int i = 0 ; i < names.length ; i++) { + people.add(new Person(names[i], heights[i])); + } + return people; + } +} diff --git a/src/SortingTheSentence.java b/src/SortingTheSentence.java new file mode 100644 index 0000000..672e715 --- /dev/null +++ b/src/SortingTheSentence.java @@ -0,0 +1,43 @@ +import java.util.ArrayList; +import java.util.List; + +public class SortingTheSentence { + public String sortSentence(String s) { + final List words = getWords(s); + words.sort(Word::compareTo); + final StringBuilder result = new StringBuilder(); + for (Word word : words) { + result.append(word.val).append(' '); + } + return result.deleteCharAt(result.length() - 1).toString(); + } + + private List getWords(String s) { + StringBuilder word = new StringBuilder(); + final List words = new ArrayList<>(); + for (int index = 0 ; index < s.length() ; index++) { + if (Character.isDigit(s.charAt(index))){ + words.add(new Word(word.toString(), s.charAt(index) - '0')); + word = new StringBuilder(); + } else if (s.charAt(index) != ' '){ + word.append(s.charAt(index)); + } + } + return words; + } + + private static final class Word implements Comparable { + private final String val; + private final int position; + + private Word(String val, int position) { + this.val = val; + this.position = position; + } + + @Override + public int compareTo(Word o) { + return Integer.compare(this.position, o.position); + } + } +} diff --git a/src/SpecialArrayI.java b/src/SpecialArrayI.java new file mode 100644 index 0000000..4c2b537 --- /dev/null +++ b/src/SpecialArrayI.java @@ -0,0 +1,14 @@ +// https://leetcode.com/problems/special-array-i +// T: O(N) +// S: O(1) + +public class SpecialArrayI { + public boolean isArraySpecial(int[] array) { + for (int i = 0 ; i < array.length - 1 ; i++) { + if (array[i] % 2 == array[i + 1] % 2) { + return false; + } + } + return true; + } +} diff --git a/src/SpecialArrayWithXElementsGreaterThanEqualToX.java b/src/SpecialArrayWithXElementsGreaterThanEqualToX.java new file mode 100644 index 0000000..14e113a --- /dev/null +++ b/src/SpecialArrayWithXElementsGreaterThanEqualToX.java @@ -0,0 +1,20 @@ +import java.util.Arrays; + +public class SpecialArrayWithXElementsGreaterThanEqualToX { + public int specialArray(int[] array) { + Arrays.sort(array); + int index = lastUniqueElementIndex(array); + for (int pointer = array[index] ; array.length - index <= pointer ; ) { + if (pointer == array.length - index) return pointer; + pointer--; + while (index > 0 && array[index - 1] >= pointer) index--; + } + return -1; + } + + private int lastUniqueElementIndex(int[] array) { + int index = array.length - 1; + while (index - 1 >= 0 && array[index - 1] == array[index]) index--; + return index; + } +} diff --git a/src/SpecialPositionInABinaryMatrix.java b/src/SpecialPositionInABinaryMatrix.java new file mode 100644 index 0000000..223e1bf --- /dev/null +++ b/src/SpecialPositionInABinaryMatrix.java @@ -0,0 +1,51 @@ +// https://leetcode.com/problems/special-positions-in-a-binary-matrix +// T: O(n * m) +// S: O(n + m) + +import java.util.Arrays; + +public class SpecialPositionInABinaryMatrix { + public int numSpecial(int[][] matrix) { + final int[] rowSum = getRowSum(matrix); + final ColumnSumData columnSumData = getColumnSum(matrix); + final int[] columnSumOneRowIndex = columnSumData.oneIndex; + final int[] columnSum = columnSumData.sum; + int specialPositions = 0; + for (int i = 0 ; i < columnSum.length ; i++) { + if (columnSum[i] == 1 && rowSum[columnSumOneRowIndex[i]] == 1) { + specialPositions++; + } + } + return specialPositions; + } + + private int[] getRowSum(int[][] matrix) { + final int[] sum = new int[matrix.length]; + for (int i = 0 ; i < sum.length ; i++) { + sum[i] = Arrays.stream(matrix[i]).sum(); + } + return sum; + } + + private ColumnSumData getColumnSum(int[][] matrix) { + final int[] sum = new int[matrix[0].length]; + final int[] indexes = new int[sum.length]; + for (int i = 0 ; i < sum.length ; i++) { + for (int row = 0 , index = 0 ; row < matrix.length ; row++) { + sum[i] += matrix[row][i]; + if (matrix[row][i] == 1) indexes[i] = row; + } + } + return new ColumnSumData(sum, indexes); + } + + private static final class ColumnSumData { + private final int[] sum; + private final int[] oneIndex; + + private ColumnSumData(int[] sum, int[] oneIndex) { + this.sum = sum; + this.oneIndex = oneIndex; + } + } +} diff --git a/src/SpiralMatrix.java b/src/SpiralMatrix.java new file mode 100644 index 0000000..92a243d --- /dev/null +++ b/src/SpiralMatrix.java @@ -0,0 +1,32 @@ +import java.util.ArrayList; +import java.util.List; + +public class SpiralMatrix { + public List spiralOrder(int[][] matrix) { + final List result = new ArrayList<>(); + final int rows = matrix.length, columns = matrix[0].length, elements = rows * columns; + for (int i = 0, top = 0, bottom = rows, left = 0, right = columns ; ; ) { + for (int row = top, column = left ; column < right ; column++, i++) { + result.add(matrix[row][column]); + } + top++; + if (i == elements) break; + for (int row = top, column = right - 1 ; row < bottom ; row++, i++) { + result.add(matrix[row][column]); + } + right--; + if (i == elements) break; + for (int row = bottom - 1, column = right - 1 ; column >= left ; column--, i++) { + result.add(matrix[row][column]); + } + bottom--; + if (i == elements) break; + for (int row = bottom - 1, column = left ; row >= top ; row--, i++) { + result.add(matrix[row][column]); + } + left++; + if (i == elements) break; + } + return result; + } +} diff --git a/src/SpiralMatrixII.java b/src/SpiralMatrixII.java new file mode 100644 index 0000000..0ec7c88 --- /dev/null +++ b/src/SpiralMatrixII.java @@ -0,0 +1,34 @@ +// https://leetcode.com/problems/spiral-matrix-ii +// T: O(n^2) +// S: O(n^2) + +public class SpiralMatrixII { + public int[][] generateMatrix(int n) { + final int[][] matrix = new int[n][n]; + final int rows = matrix.length, columns = matrix[0].length, elements = rows * columns; + + for (int i = 0, top = 0, bottom = rows, left = 0, right = columns, k = 1 ; ; ) { + for (int row = top, column = left ; column < right ; column++, i++) { + matrix[row][column] = k++; + } + top++; + if (i == elements) break; + for (int row = top, column = right - 1 ; row < bottom ; row++, i++) { + matrix[row][column] = k++; + } + right--; + if (i == elements) break; + for (int row = bottom - 1, column = right - 1 ; column >= left ; column--, i++) { + matrix[row][column] = k++; + } + bottom--; + if (i == elements) break; + for (int row = bottom - 1, column = left ; row >= top ; row--, i++) { + matrix[row][column] = k++; + } + left++; + if (i == elements) break; + } + return matrix; + } +} diff --git a/src/SplitAStringInBalancedStrings.java b/src/SplitAStringInBalancedStrings.java new file mode 100644 index 0000000..5361cf5 --- /dev/null +++ b/src/SplitAStringInBalancedStrings.java @@ -0,0 +1,10 @@ +public class SplitAStringInBalancedStrings { + public int balancedStringSplit(String s) { + int balancedSubStrings = 0; + for (int i = 0, current = 0 ; i < s.length() ; i++) { + current += s.charAt(i) == 'L' ? -1 : 1; + if (current == 0) balancedSubStrings++; + } + return balancedSubStrings; + } +} diff --git a/src/SplitStringsBySeparator.java b/src/SplitStringsBySeparator.java new file mode 100644 index 0000000..5531ff7 --- /dev/null +++ b/src/SplitStringsBySeparator.java @@ -0,0 +1,40 @@ +// https://leetcode.com/problems/split-strings-by-separator +// W: number of words +// s: string in words +// T: O(W * |s|) +// S: O(W * |s|) + +import java.util.ArrayList; +import java.util.List; + +public class SplitStringsBySeparator { + public List splitWordsBySeparator(List words, char separator) { + final List result = new ArrayList<>(); + for (String word : words) { + final List splitStrings = split(word, separator); + for (String split : splitStrings) { + if (!split.isEmpty()) { + result.add(split); + } + } + } + return result; + } + + private List split(String string, char separator) { + final List result = new ArrayList<>(); + StringBuilder builder = new StringBuilder(); + for (int i = 0 ; i < string.length() ; i++) { + if (string.charAt(i) == separator) { + result.add(builder.toString()); + builder = new StringBuilder(); + } else { + builder.append(string.charAt(i)); + } + } + if (!builder.isEmpty()) { + result.add(builder.toString()); + } + return result; + } +} diff --git a/src/SplitTheArray.java b/src/SplitTheArray.java new file mode 100644 index 0000000..c86c43a --- /dev/null +++ b/src/SplitTheArray.java @@ -0,0 +1,19 @@ +// https://leetcode.com/problems/split-the-array +// T: O(N) +// S: O(N) + +import java.util.HashMap; +import java.util.Map; + +public class SplitTheArray { + public boolean isPossibleToSplit(int[] array) { + final Map frequencies = new HashMap<>(); + for (int element : array) { + if (frequencies.getOrDefault(element, 0) == 2) { + return false; + } + frequencies.put(element, frequencies.getOrDefault(element, 0) + 1); + } + return true; + } +} diff --git a/src/SplitWithMinimumSum.java b/src/SplitWithMinimumSum.java new file mode 100644 index 0000000..228107b --- /dev/null +++ b/src/SplitWithMinimumSum.java @@ -0,0 +1,32 @@ +// https://leetcode.com/problems/split-with-minimum-sum +// T: O(log(N)log(log(N))) +// S: O(log(log(N))) + +import java.util.ArrayList; +import java.util.List; + +public class SplitWithMinimumSum { + public int splitNum(int num) { + final List digits = getDigits(num); + digits.sort(Integer::compareTo); + int a = 0, b = 0, k = 0; + for (int digit : digits) { + if (k == 0) { + a = 10 * a + digit; + } else { + b = 10 * b + digit; + } + k ^= 1; + } + return a + b; + } + + private List getDigits(int x) { + final List digits = new ArrayList<>(); + final String number = x + ""; + for (int index = 0 ; index < number.length() ; index++) { + digits.add(number.charAt(index) - '0'); + } + return digits; + } +} diff --git a/src/StringMatchingInAnArray.java b/src/StringMatchingInAnArray.java new file mode 100644 index 0000000..a59d43d --- /dev/null +++ b/src/StringMatchingInAnArray.java @@ -0,0 +1,24 @@ +import java.util.ArrayList; +import java.util.List; + +public class StringMatchingInAnArray { + public List stringMatching(String[] words) { + final List result = new ArrayList<>(); + for (int i = 0 ; i < words.length ; i++) { + for (int j = 0 ; j < words.length ; j++) { + if(i == j) continue; + if (isSubString(words[i], words[j])) { + result.add(words[i]); + break; + } + } + } + return result; + } + + private boolean isSubString(String pattern, String text) { + if (pattern.length() > text.length()) return false; + if (pattern.length() == text.length()) return pattern.equals(text); + return text.contains(pattern); + } +} diff --git a/src/StringToIntegerAtoi.java b/src/StringToIntegerAtoi.java new file mode 100644 index 0000000..bd8d8f5 --- /dev/null +++ b/src/StringToIntegerAtoi.java @@ -0,0 +1,45 @@ +// https://leetcode.com/problems/string-to-integer-atoi +// T:O(|input|) +// S:O(1) + +public class StringToIntegerAtoi { + public int myAtoi(String input) { + int sign = 1; + int result = 0; + int index = 0; + int n = input.length(); + + // Discard all spaces from the beginning of the input string. + while (index < n && input.charAt(index) == ' ') { + index++; + } + + // sign = +1, if it's positive number, otherwise sign = -1. + if (index < n && input.charAt(index) == '+') { + index++; + } else if (index < n && input.charAt(index) == '-') { + sign = -1; + index++; + } + + // Traverse next digits of input and stop if it is not a digit + while (index < n && Character.isDigit(input.charAt(index))) { + int digit = input.charAt(index) - '0'; + + // Check overflow and underflow conditions. + if ((result > Integer.MAX_VALUE / 10) || + (result == Integer.MAX_VALUE / 10 && digit > Integer.MAX_VALUE % 10)) { + // If integer overflowed return 2^31-1, otherwise if underflowed return -2^31. + return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; + } + + // Append current digit to the result. + result = 10 * result + digit; + index++; + } + + // We have formed a valid number without any overflow/underflow. + // Return it after multiplying it with its sign. + return sign * result; + } +} diff --git a/src/StrobogrammaticNumber.java b/src/StrobogrammaticNumber.java new file mode 100644 index 0000000..1292ba0 --- /dev/null +++ b/src/StrobogrammaticNumber.java @@ -0,0 +1,30 @@ +// https://leetcode.com/problems/strobogrammatic-number +// T: O(N) +// S: O(1) + +import java.util.HashMap; +import java.util.Map; + +// Strobogrammatic digits: 0, 1, 8 +// Strobogrammatic interchangeable digits: 6 --> 9, 9 --> 6 +public class StrobogrammaticNumber { + private static final Map STROBOGRAMMATIC_MIRROR = new HashMap<>() {{ + put('0', '0'); + put('1', '1'); + put('6', '9'); + put('8', '8'); + put('9', '6'); + }}; + + public boolean isStrobogrammatic(String number) { + for (int i = 0 ; i < number.length() ; i++) { + final char digit = number.charAt(i); + if (!STROBOGRAMMATIC_MIRROR.containsKey(digit) + || STROBOGRAMMATIC_MIRROR.get(digit) != number.charAt(number.length() - 1 - i) + ) { + return false; + } + } + return true; + } +} diff --git a/src/StrongPasswordCheckerII.java b/src/StrongPasswordCheckerII.java new file mode 100644 index 0000000..81de45f --- /dev/null +++ b/src/StrongPasswordCheckerII.java @@ -0,0 +1,77 @@ +// https://leetcode.com/problems/strong-password-checker-ii +// T: O(|password|) +// S: O(1) + +import java.util.HashSet; +import java.util.Set; + +public class StrongPasswordCheckerII { + private static final String SPECIAL_CHARACTERS = "!@#$%^&*()-+"; + + public boolean strongPasswordCheckerII(String password) { + return atLeastLen8(password) + && atLeast1LowercaseLetter(password) + && atLeast1UppercaseLetter(password) + && atLeast1Digit(password) + && atLeast1SpecialCharacter(password) + && noAdjacentSameCharacters(password); + } + + private boolean noAdjacentSameCharacters(String password) { + for (int i = 1 ; i < password.length() ; i++) { + if (password.charAt(i - 1) == password.charAt(i)) { + return false; + } + } + return true; + } + + private boolean atLeast1SpecialCharacter(String password) { + final Set characters = charactersOf(password); + for (int i = 0 ; i < SPECIAL_CHARACTERS.length() ; i++) { + if (characters.contains(SPECIAL_CHARACTERS.charAt(i))) { + return true; + } + } + return false; + } + + private Set charactersOf(String password) { + final Set set = new HashSet<>(); + for (int i = 0 ; i < password.length() ; i++) { + set.add(password.charAt(i)); + } + return set; + } + + private boolean atLeast1Digit(String password) { + for (int i = 0 ; i < password.length() ; i++) { + if (password.charAt(i) >= '0' && password.charAt(i) <= '9') { + return true; + } + } + return false; + } + + private boolean atLeast1UppercaseLetter(String password) { + for (int i = 0 ; i < password.length() ; i++) { + if (password.charAt(i) >= 'A' && password.charAt(i) <= 'Z') { + return true; + } + } + return false; + } + + private boolean atLeast1LowercaseLetter(String password) { + for (int i = 0 ; i < password.length() ; i++) { + if (password.charAt(i) >= 'a' && password.charAt(i) <= 'z') { + return true; + } + } + return false; + } + + private boolean atLeastLen8(String password) { + return password.length() >= 8; + } +} diff --git a/src/StudentAttendanceRecordI.java b/src/StudentAttendanceRecordI.java new file mode 100644 index 0000000..5d0cd97 --- /dev/null +++ b/src/StudentAttendanceRecordI.java @@ -0,0 +1,17 @@ +public class StudentAttendanceRecordI { + public boolean checkRecord(String s) { + int consecutiveLate = 0, absentees = 0; + for (int index = 0 ; index < s.length() ; index++) { + if (s.charAt(index) == 'L') { + consecutiveLate++; + } else { + if (s.charAt(index) == 'A') absentees++; + consecutiveLate = 0; + } + if (absentees >= 2 || consecutiveLate >= 3) { + return false; + } + } + return true; + } +} diff --git a/src/SubarraysDistinctElementSumOfSquaresI.java b/src/SubarraysDistinctElementSumOfSquaresI.java new file mode 100644 index 0000000..49b6d8f --- /dev/null +++ b/src/SubarraysDistinctElementSumOfSquaresI.java @@ -0,0 +1,23 @@ +// https://leetcode.com/problems/subarrays-distinct-element-sum-of-squares-i +// T: O(N^2) +// S: O(N) + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class SubarraysDistinctElementSumOfSquaresI { + public int sumCounts(List array) { + int sum = 0; + + for (int i = 0 ; i < array.size() ; i++) { + final Set subArray = new HashSet<>(); + for (int j = i ; j < array.size() ; j++) { + subArray.add(array.get(j)); + sum += subArray.size() * subArray.size(); + } + } + + return sum; + } +} diff --git a/src/Subsets.java b/src/Subsets.java new file mode 100644 index 0000000..5465ca6 --- /dev/null +++ b/src/Subsets.java @@ -0,0 +1,27 @@ +// https://leetcode.com/problems/subsets +// T: O(n * 2^n) +// S: O(n) + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +public class Subsets { + public List> subsets(int[] nums) { + final List> result = new ArrayList<>(); + addSubsets(nums, 0, result, new LinkedList<>()); + return result; + } + + private void addSubsets(int[] array, int index, List> result, LinkedList current) { + if (index == array.length) { + result.add(new ArrayList<>(current)); + return; + } + + current.add(array[index]); + addSubsets(array, index + 1, result, current); + current.removeLast(); + addSubsets(array, index + 1, result, current); + } +} diff --git a/src/SubsetsII.java b/src/SubsetsII.java new file mode 100644 index 0000000..2522c5a --- /dev/null +++ b/src/SubsetsII.java @@ -0,0 +1,27 @@ +// https://leetcode.com/problems/subsets-ii +// T: O(2^n) +// S: O(n * 2^n) + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +public class SubsetsII { + public List> subsetsWithDup(int[] nums) { + Arrays.sort(nums); + final List> result = new ArrayList<>(); + helper(result, new LinkedList<>(), nums, 0); + return result; + } + + public void helper(List> result, LinkedList current, int[] numbers, int index) { + result.add(new ArrayList<>(current)); + for(int i = index ; i < numbers.length ; i++) { + if(i > index && numbers[i] == numbers[i-1]) continue; + current.add(numbers[i]); + helper(result, current, numbers, i + 1); + current.removeLast(); + } + } +} diff --git a/src/SubstringWithConcatenationOfAllWords.java b/src/SubstringWithConcatenationOfAllWords.java new file mode 100644 index 0000000..8c6bf39 --- /dev/null +++ b/src/SubstringWithConcatenationOfAllWords.java @@ -0,0 +1,88 @@ +// https://leetcode.com/problems/substring-with-concatenation-of-all-words +// T: O(|words| + |s| * |words[i]|) +// S: O(|words| + |words[i]|) + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +class SubstringWithConcatenationOfAllWords { + private final Map wordCount = new HashMap<>(); + private int n; + private int wordLength; + private int substringSize; + private int k; + + private void slidingWindow(int left, String s, List answer) { + HashMap wordsFound = new HashMap<>(); + int wordsUsed = 0; + boolean excessWord = false; + + // Do the same iteration pattern as the previous approach - iterate + // word_length at a time, and at each iteration we focus on one word + for (int right = left; right <= n - wordLength; right += wordLength) { + String sub = s.substring(right, right + wordLength); + if (!wordCount.containsKey(sub)) { + // Mismatched word - reset the window + wordsFound.clear(); + wordsUsed = 0; + excessWord = false; + left = right + wordLength; + } else { + // If we reached max window size or have an excess word + while (right - left == substringSize || excessWord) { + String leftmostWord = s.substring(left, left + wordLength); + left += wordLength; + wordsFound.put( + leftmostWord, + wordsFound.get(leftmostWord) - 1 + ); + + if ( + wordsFound.get(leftmostWord) >= + wordCount.get(leftmostWord) + ) { + // This word was an excess word + excessWord = false; + } else { + // Otherwise we actually needed it + wordsUsed--; + } + } + + // Keep track of how many times this word occurs in the window + wordsFound.put(sub, wordsFound.getOrDefault(sub, 0) + 1); + if (wordsFound.get(sub) <= wordCount.get(sub)) { + wordsUsed++; + } else { + // Found too many instances already + excessWord = true; + } + + if (wordsUsed == k && !excessWord) { + // Found a valid substring + answer.add(left); + } + } + } + } + + public List findSubstring(String s, String[] words) { + n = s.length(); + k = words.length; + wordLength = words[0].length(); + substringSize = wordLength * k; + + for (String word : words) { + wordCount.put(word, wordCount.getOrDefault(word, 0) + 1); + } + + List answer = new ArrayList<>(); + for (int i = 0; i < wordLength; i++) { + slidingWindow(i, s, answer); + } + + return answer; + } +} \ No newline at end of file diff --git a/src/SubstringsOfSizeThreeWithDistinctCharacters.java b/src/SubstringsOfSizeThreeWithDistinctCharacters.java new file mode 100644 index 0000000..30e2da5 --- /dev/null +++ b/src/SubstringsOfSizeThreeWithDistinctCharacters.java @@ -0,0 +1,34 @@ +// https://leetcode.com/problems/substrings-of-size-three-with-distinct-characters +// T: O(N) +// S: O(1) + +import java.util.HashMap; +import java.util.Map; + +public class SubstringsOfSizeThreeWithDistinctCharacters { + public int countGoodSubstrings(String s) { + if (s.length() < 3) return 0; + final Map frequency = getFrequency(s, 3); + int goodSubStrings = 0; + if (frequency.size() == 3) goodSubStrings++; + for (int index = 3 ; index < s.length() ; index++) { + remove(frequency, s.charAt(index - 3)); + frequency.put(s.charAt(index), frequency.getOrDefault(s.charAt(index), 0) + 1); + if (frequency.size() == 3) goodSubStrings++; + } + return goodSubStrings; + } + + private Map getFrequency(String s, int upto) { + final Map frequencies = new HashMap<>(); + for (int i = 0 ; i < upto ; i++) { + frequencies.put(s.charAt(i), frequencies.getOrDefault(s.charAt(i), 0) + 1); + } + return frequencies; + } + + private void remove(Map frequencies, char c) { + if (frequencies.get(c) == 1) frequencies.remove(c); + else frequencies.put(c, frequencies.get(c) - 1); + } +} diff --git a/src/SubtractTheProductAndSumOfDigitsOfAnInteger.java b/src/SubtractTheProductAndSumOfDigitsOfAnInteger.java new file mode 100644 index 0000000..87d2b31 --- /dev/null +++ b/src/SubtractTheProductAndSumOfDigitsOfAnInteger.java @@ -0,0 +1,12 @@ +public class SubtractTheProductAndSumOfDigitsOfAnInteger { + public int subtractProductAndSum(int n) { + int product= 1, sum = 0, digit; + while (n > 0) { + digit = n % 10; + product *= digit; + sum += digit; + n /= 10; + } + return product - sum; + } +} diff --git a/src/SubtreeOfAnotherTree.java b/src/SubtreeOfAnotherTree.java new file mode 100644 index 0000000..84ad7b5 --- /dev/null +++ b/src/SubtreeOfAnotherTree.java @@ -0,0 +1,15 @@ +public class SubtreeOfAnotherTree { + public boolean isSubtree(TreeNode root, TreeNode subRoot) { + if (root == null) return false; + if (root.val == subRoot.val && areSame(root, subRoot)) { + return true; + } + return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot); + } + + private boolean areSame(TreeNode root, TreeNode subTree) { + if (subTree == null && root == null) return true; + if (root == null || subTree == null) return false; + return root.val == subTree.val && areSame(root.left, subTree.left) && areSame(root.right, subTree.right); + } +} diff --git a/src/SudokuSolver.java b/src/SudokuSolver.java new file mode 100644 index 0000000..c8b48be --- /dev/null +++ b/src/SudokuSolver.java @@ -0,0 +1,140 @@ +// https://leetcode.com/problems/sudoku-solver +// T: O(n^2 * k) but n = 9 and k = 9 so just O(1) +// S: O(n^2) but n = 9 so just O(1) + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class SudokuSolver { + private record Position(int row, int column) { + private static final Position start = new Position(0, 0); + + private boolean isValid() { + return row >= 0 + && row < 9 + && column >= 0 + && column < 9; + } + + private Position next() { + if (column == 8) return new Position(row + 1, 0); + return new Position(row, column + 1); + } + } + + private static final Map> rows = new HashMap<>(); + private static final Map> columns = new HashMap<>(); + private static final Map> subGrids = new HashMap<>(); + + public static void solveSudoku(char[][] board) { + computeDigitsInRows(board); + computeDigitsInColumns(board); + computeDigitsInSubGrids(board); + solveSudoku(board, Position.start); + } + + private static boolean solveSudoku(char[][] board, Position position) { + if (!position.isValid()) return true; + if (isAlreadyFilled(board, position)) return solveSudoku(board, position.next()); + + for (int i = 1 ; i <= 9 ; i++) { + if (isInRow(i, position) || isInColumn(i, position) || isInSubGrid(i, position)) continue; + insertInGrid(i, position, board); + boolean solved = solveSudoku(board, position.next()); + if (solved) return true; + removeFromGrid(i, position, board); + } + return false; + } + + private static boolean isAlreadyFilled(char[][] board, Position position) { + return board[position.row][position.column] != '.'; + } + + private static boolean isInRow(int digit, Position position) { + return rows.get(position.row).contains(digit); + } + + private static boolean isInColumn(int digit, Position position) { + return columns.get(position.column).contains(digit); + } + + private static boolean isInSubGrid(int digit, Position position) { + return subGrids.get(getSubGridId(position)).contains(digit); + } + + private static void insertInGrid(int digit, Position position, char[][] board) { + rows.get(position.row).add(digit); + columns.get(position.column).add(digit); + subGrids.get(getSubGridId(position)).add(digit); + board[position.row][position.column] = toChar(digit); + } + + private static void removeFromGrid(int digit, Position position, char[][] board) { + rows.get(position.row).remove(digit); + columns.get(position.column).remove(digit); + subGrids.get(getSubGridId(position)).remove(digit); + board[position.row][position.column] = '.'; + } + + private static void computeDigitsInRows(char[][] board) { + for (int row = 0 ; row < 9 ; row++) { + final Set digits = new HashSet<>(); + for (char element : board[row]) { + if (Character.isDigit(element)) { + digits.add(toInt(element)); + } + } + rows.put(row, digits); + } + } + + private static void computeDigitsInColumns(char[][] board) { + for (int column = 0 ; column < 9 ; column++) { + final Set digits = new HashSet<>(); + for (int row = 0 ; row < 9 ; row++) { + if (Character.isDigit(board[row][column])) { + digits.add(toInt(board[row][column])); + } + } + columns.put(column, digits); + } + } + + private static void computeDigitsInSubGrids(char[][] board) { + for (int i = 0 ; i < 3 ; i++) { + for (int j = 0 ; j < 3 ; j++) { + final int subGridId = getSubGridId(i, j); + final Set digits = new HashSet<>(); + for (int row = 3 * i ; row < 3 * i + 3 ; row++) { + for (int column = 3 * j ; column < 3 * j + 3 ; column++) { + if (Character.isDigit(board[row][column])) { + digits.add(toInt(board[row][column])); + } + } + } + subGrids.put(subGridId, digits); + } + } + } + + private static int toInt(char c) { + return c - '0'; + } + + private static char toChar(int digit) { + return (char) ('0' + digit); + } + + private static int getSubGridId(int i, int j) { + return 10 * i + j; + } + + private static int getSubGridId(Position position) { + int i = position.row / 3; + int j = position.column / 3; + return getSubGridId(i, j); + } +} diff --git a/src/SumMultiples.java b/src/SumMultiples.java new file mode 100644 index 0000000..1c1bd3c --- /dev/null +++ b/src/SumMultiples.java @@ -0,0 +1,19 @@ +// https://leetcode.com/problems/sum-multiples +// T: O(1) +// S: O(1) + +public class SumMultiples { + public int sumOfMultiples(int n) { + return 3 * summation(n / 3) + + 5 * summation(n / 5) + + 7 * summation(n / 7) + - 15 * summation(n / 15) + - 21 * summation(n / 21) + - 35 * summation(n / 35) + + 105 * summation(n / 105); + } + + private int summation(int x) { + return (x * (x + 1)) / 2; + } +} diff --git a/src/SumOfAllOddLengthSubArrays.java b/src/SumOfAllOddLengthSubArrays.java new file mode 100644 index 0000000..acb44dc --- /dev/null +++ b/src/SumOfAllOddLengthSubArrays.java @@ -0,0 +1,9 @@ +public class SumOfAllOddLengthSubArrays { + public int sumOddLengthSubarrays(int[] array) { + int sum = 0; + for (int index = 0 ; index < array.length ; index++) { + sum += (((array.length - index) * (index + 1) + 1) / 2) * array[index]; + } + return sum; + } +} diff --git a/src/SumOfAllSubsetXORTotals.java b/src/SumOfAllSubsetXORTotals.java new file mode 100644 index 0000000..2043d75 --- /dev/null +++ b/src/SumOfAllSubsetXORTotals.java @@ -0,0 +1,13 @@ +// https://leetcode.com/problems/sum-of-all-subset-xor-totals +// T: O(N) +// S: O(1) + +public class SumOfAllSubsetXORTotals { + public int subsetXORSum(int[] nums) { + int or = 0; + for (int element : nums) { + or |= element; + } + return or * (1 << nums.length - 1); + } +} diff --git a/src/SumOfDigitsInBaseK.java b/src/SumOfDigitsInBaseK.java new file mode 100644 index 0000000..eefa9d0 --- /dev/null +++ b/src/SumOfDigitsInBaseK.java @@ -0,0 +1,23 @@ +public class SumOfDigitsInBaseK { + public int sumBase(int n, int k) { + return sumOfDigits(toBaseK(n, k)); + } + + private int sumOfDigits(StringBuilder number) { + int sum = 0; + for (int index = 0 ; index < number.length() ; index++) { + sum += number.charAt(index) - '0'; + } + return sum; + } + + private StringBuilder toBaseK(int n, int k) { + if (n == 0) return new StringBuilder("0"); + final StringBuilder result = new StringBuilder(); + while (n > 0) { + result.append(n % k); + n /= k; + } + return result.reverse(); + } +} diff --git a/src/SumOfDigitsOfStringAfterConvert.java b/src/SumOfDigitsOfStringAfterConvert.java new file mode 100644 index 0000000..62b55a4 --- /dev/null +++ b/src/SumOfDigitsOfStringAfterConvert.java @@ -0,0 +1,39 @@ +// https://leetcode.com/problems/sum-of-digits-of-string-after-convert +// T: O(|s|* k) +// S: O(|s|) + +public class SumOfDigitsOfStringAfterConvert { + public int getLucky(String s, int k) { + final String convertedString = convert(s); + int num = sumOfDigits(convertedString); + for (int i = 0 ; i < k - 1 ; i++) { + num = sumOfDigits(num); + } + return num; + } + + private String convert(String s) { + final StringBuilder result = new StringBuilder(); + for (int i = 0 ; i < s.length() ; i++) { + result.append(s.charAt(i) - 'a' + 1); + } + return result.toString(); + } + + private int sumOfDigits(int number) { + int sum = 0; + while (number > 0) { + sum += number % 10; + number /= 10; + } + return sum; + } + + private int sumOfDigits(String number) { + int sum = 0; + for (int i = 0 ; i < number.length() ; i++) { + sum += number.charAt(i) - '0'; + } + return sum; + } +} diff --git a/src/SumOfRootToLeafBinaryNumbers.java b/src/SumOfRootToLeafBinaryNumbers.java new file mode 100644 index 0000000..5abc300 --- /dev/null +++ b/src/SumOfRootToLeafBinaryNumbers.java @@ -0,0 +1,11 @@ +public class SumOfRootToLeafBinaryNumbers { + public int sumRootToLeaf(TreeNode root) { + return sumRootToLeaf(root, 0); + } + + private int sumRootToLeaf(TreeNode root, int sum) { + if (root == null) return 0; + if (root.left == null && root.right == null) return sum + root.val; + return sumRootToLeaf(root.left, (sum + root.val) << 1) + sumRootToLeaf(root.right, (sum + root.val) << 1); + } +} diff --git a/src/SumOfSquareNumbers.java b/src/SumOfSquareNumbers.java new file mode 100644 index 0000000..a663337 --- /dev/null +++ b/src/SumOfSquareNumbers.java @@ -0,0 +1,16 @@ +public class SumOfSquareNumbers { + public boolean judgeSquareSum(int c) { + int count; + for (int i = 2 ; i * i <= c ; i++) { + if (c % i == 0) { + count = 0; + while (c % i == 0) { + c /= i; + count++; + } + if (i % 4 == 3 && count % 2 == 1) return false; + } + } + return true; + } +} diff --git a/src/SumOfSquaresOfSpecialElements.java b/src/SumOfSquaresOfSpecialElements.java new file mode 100644 index 0000000..b8059c6 --- /dev/null +++ b/src/SumOfSquaresOfSpecialElements.java @@ -0,0 +1,15 @@ +// https://leetcode.com/problems/sum-of-squares-of-special-elements +// T: O(N) +// S: O(1) + +public class SumOfSquaresOfSpecialElements { + public int sumOfSquares(int[] nums) { + int result = 0; + for (int i = 0 ; i < nums.length ; i++) { + if (nums.length % (i + 1) == 0) { + result += nums[i] * nums[i]; + } + } + return result; + } +} diff --git a/src/SumOfUniqueElements.java b/src/SumOfUniqueElements.java new file mode 100644 index 0000000..b1e7fe3 --- /dev/null +++ b/src/SumOfUniqueElements.java @@ -0,0 +1,37 @@ +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class SumOfUniqueElements { + public int sumOfUnique(int[] nums) { + final Set uniqueElements = uniqueElements(nums); + return sum(uniqueElements); + } + + private Set uniqueElements(int[] array) { + final Map frequencies = getFrequencies(array); + final Set set = new HashSet<>(); + for (Map.Entry entry : frequencies.entrySet()) { + if (entry.getValue() == 1) set.add(entry.getKey()); + } + return set; + } + + private Map getFrequencies(int[] array) { + final Map frequencies = new HashMap<>(); + for (int element : array) { + frequencies.put(element, frequencies.getOrDefault(element, 0) + 1); + } + return frequencies; + } + + private int sum(Collection collection) { + int sum = 0; + for (int element : collection) { + sum += element; + } + return sum; + } +} diff --git a/src/SumOfValuesAtIndicesWithKSetBits.java b/src/SumOfValuesAtIndicesWithKSetBits.java new file mode 100644 index 0000000..536c9aa --- /dev/null +++ b/src/SumOfValuesAtIndicesWithKSetBits.java @@ -0,0 +1,26 @@ +// https://leetcode.com/problems/sum-of-values-at-indices-with-k-set-bits +// T: O(N) +// S: O(1) + +import java.util.List; + +public class SumOfValuesAtIndicesWithKSetBits { + public int sumIndicesWithKSetBits(List array, int k) { + int sum = 0; + for (int i = 0 ; i < array.size() ; i++) { + if (numberOfSetBits(i) == k) { + sum += array.get(i); + } + } + return sum; + } + + private static int numberOfSetBits(int number) { + int setBits = 0; + while (number > 0) { + setBits += number % 2; + number /= 2; + } + return setBits; + } +} diff --git a/src/SumRootToLeafNumbers.java b/src/SumRootToLeafNumbers.java new file mode 100644 index 0000000..769cd45 --- /dev/null +++ b/src/SumRootToLeafNumbers.java @@ -0,0 +1,20 @@ +// https://leetcode.com/problems/sum-root-to-leaf-numbers +// T: O(n) +// S: O(log(n)) + +public class SumRootToLeafNumbers { + public int sumNumbers(TreeNode root) { + return sumNumbers(root, 0); + } + + private int sumNumbers(TreeNode root, int currentSum) { + if (root == null) return 0; + if (isLeafNode(root)) return 10 * currentSum + root.val; + return sumNumbers(root.left, 10 * currentSum + root.val) + + sumNumbers(root.right, 10 * currentSum + root.val); + } + + private boolean isLeafNode(TreeNode root) { + return root.left == null && root.right == null; + } +} diff --git a/src/SummaryRanges.java b/src/SummaryRanges.java new file mode 100644 index 0000000..b643e4c --- /dev/null +++ b/src/SummaryRanges.java @@ -0,0 +1,23 @@ +import java.util.ArrayList; +import java.util.List; + +public class SummaryRanges { + + private String getRangeString(int start, int end) { + return end == start ? start + "" : start + "->" + end; + } + + public List summaryRanges(int[] array) { + if (array.length == 0) return new ArrayList<>(); + List result = new ArrayList<>(); + int startIndex = 0; + for (int index = 1 ; index < array.length ; index++) { + if (array[index] > array[startIndex] + (index - startIndex)) { + result.add(getRangeString(array[startIndex], array[index - 1])); + startIndex = index; + } + } + result.add(getRangeString(array[startIndex], array[array.length - 1])); + return result; + } +} diff --git a/src/SurfaceAreaOf3DShapes.java b/src/SurfaceAreaOf3DShapes.java new file mode 100644 index 0000000..d68b1c6 --- /dev/null +++ b/src/SurfaceAreaOf3DShapes.java @@ -0,0 +1,16 @@ +public class SurfaceAreaOf3DShapes { + public int surfaceArea(int[][] grid) { + final int rows = grid.length, columns = grid[0].length; + int surfaceArea = 0; + for (int row = 0 ; row < rows ; row++) { + for (int column = 0 ; column < columns ; column++) { + surfaceArea += (grid[row][column] > 0 ? 2 : 0) + + (column + 1 < columns ? Math.abs(grid[row][column] - grid[row][column + 1]) : grid[row][column]) + + (row + 1 < rows ? Math.abs(grid[row][column] - grid[row + 1][column]) : grid[row][column]) + + (row == 0 ? grid[row][column] : 0) + + (column == 0 ? grid[row][column] : 0); + } + } + return surfaceArea; + } +} diff --git a/src/SurroundedRegions.java b/src/SurroundedRegions.java new file mode 100644 index 0000000..9442e5e --- /dev/null +++ b/src/SurroundedRegions.java @@ -0,0 +1,92 @@ +// https://leetcode.com/problems/surrounded-regions +// T: O(m * n) +// S: O(m * n) + +import java.util.HashSet; +import java.util.Set; + +public class SurroundedRegions { + private record Position(int row, int column) { + @Override + public boolean equals(Object o) { + if (this == o) return true; + Position position = (Position) o; + if (row != position.row) return false; + return column == position.column; + } + + @Override + public int hashCode() { + return 31 * row + column; + } + + public Position top() { + return new Position(row - 1, column); + } + + public Position right() { + return new Position(row, column + 1); + } + + public Position bottom() { + return new Position(row + 1, column); + } + + public Position left() { + return new Position(row, column - 1); + } + } + + public void solve(char[][] board) { + final Set visited = new HashSet<>(); + final Set current = new HashSet<>(); + final int rows = board.length, columns = board[0].length; + + for (int row = 1 ; row < rows - 1 ; row++) { + for (int column = 1 ; column < columns - 1 ; column++) { + if (board[row][column] == 'O') { + final boolean isBorderRegion = markRegion(board, new Position(row, column), visited, current); + if (!isBorderRegion) { + captureRegion(board, current); + } + current.clear(); + } + } + } + } + + private boolean markRegion(char[][] board, Position position, Set visited, Set region) { + if (isInvalidPosition(board, position) || visited.contains(position) || isX(board, position)) return false; + visited.add(position); + region.add(position); + boolean top = markRegion(board, position.top(), visited, region); + boolean right = markRegion(board, position.right(), visited, region); + boolean bottom = markRegion(board, position.bottom(), visited, region); + boolean left = markRegion(board, position.left(), visited, region); + return top || right || bottom || left || isBorderPosition(board, position); + } + + private boolean isX(char[][] board, Position position) { + return board[position.row][position.column] == 'X'; + } + + private boolean isBorderPosition(char[][] board, Position position) { + return position.row == 0 + || position.row == board.length - 1 + || position.column == 0 + || position.column == board[0].length - 1; + } + + private boolean isInvalidPosition(char[][] board, Position position) { + return position.row < 0 + || position.row >= board.length + || position.column < 0 + || position.column >= board[0].length; + } + + private void captureRegion(char[][] board, Set positions) { + for (Position position : positions) { + board[position.row][position.column] = 'X'; + } + } +} diff --git a/src/SwapNodesInPairs.java b/src/SwapNodesInPairs.java new file mode 100644 index 0000000..7154694 --- /dev/null +++ b/src/SwapNodesInPairs.java @@ -0,0 +1,20 @@ +// https://leetcode.com/problems/swap-nodes-in-pairs +// T: O(n) +// S: O(1) + +public class SwapNodesInPairs { + + public ListNode swapPairs(ListNode head) { + if (head == null || head.next == null) return head; + ListNode newHead = head.next, a = head, b = head.next.next, temp; + head.next.next = head; + while (a != null) { + a.next = (b == null || b.next == null ? b : b.next); + temp = (b == null || b.next == null ? null : b.next.next); + if (b != null && b.next != null) b.next.next = b; + a = b; + b = temp; + } + return newHead; + } +} diff --git a/src/SymmetricTree.java b/src/SymmetricTree.java index ac48e1d..cf6a86c 100644 --- a/src/SymmetricTree.java +++ b/src/SymmetricTree.java @@ -1,33 +1,13 @@ public class SymmetricTree { - private static class TreeNode { - int val; - TreeNode left; - TreeNode right; - } public boolean isSymmetric(TreeNode root) { return root == null || isSymmetric(root.left, root.right); } public boolean isSymmetric(TreeNode p, TreeNode q) { - if (p == null && q == null) { - return true; - } - - if (p == null || q == null || p.val != q.val) { - return false; - } - - boolean left = (p.left == null && q.right == null) || (p.left != null && q.right != null); - if (p.left != null && q.right != null) { - left = isSymmetric(p.left, q.right); - } - - boolean right = (p.right == null && q.left == null) || (p.right != null && q.left != null); - if (p.right != null && q.left != null) { - right = isSymmetric(p.right, q.left); + if (p != null && q != null) { + return p.val == q.val && isSymmetric(p.left, q.right) && isSymmetric(p.right, q.left); } - - return left && right; + return p == q; } } diff --git a/src/TakeGiftsFromTheRichestPile.java b/src/TakeGiftsFromTheRichestPile.java new file mode 100644 index 0000000..aea8a64 --- /dev/null +++ b/src/TakeGiftsFromTheRichestPile.java @@ -0,0 +1,37 @@ +// https://leetcode.com/problems/take-gifts-from-the-richest-pile +// T: O(k * log(N)) +// S: O(N) + +import java.util.Comparator; +import java.util.PriorityQueue; +import java.util.Queue; + +public class TakeGiftsFromTheRichestPile { + public long pickGifts(int[] gifts, int k) { + final Queue maxHeap = maHeapFrom(gifts); + + for (int i = 0 ; i < k ; i++) { + final int maxPile = maxHeap.poll(); + final int giftsToLeaveBehind = (int) Math.max(Math.sqrt(maxPile), 0); + maxHeap.add(giftsToLeaveBehind); + } + + return sum(maxHeap); + } + + private long sum(Queue heap) { + long sum = 0; + while (!heap.isEmpty()) { + sum += heap.poll(); + } + return sum; + } + + private Queue maHeapFrom(int[] array) { + final Queue maxHeap = new PriorityQueue<>(Comparator.reverseOrder()); + for (int element : array) { + maxHeap.add(element); + } + return maxHeap; + } +} diff --git a/src/TeemoAttacking.java b/src/TeemoAttacking.java new file mode 100644 index 0000000..90d6a7e --- /dev/null +++ b/src/TeemoAttacking.java @@ -0,0 +1,10 @@ +public class TeemoAttacking { + public int findPoisonedDuration(int[] timeSeries, int duration) { + int poisonDuration = 0; + for (int i = 0, current = timeSeries[0] - 1 ; i < timeSeries.length; i++) { + poisonDuration += duration - Math.max(0, Math.max(current, timeSeries[i] - 1) - timeSeries[i] + 1); + current = timeSeries[i] + duration - 1; + } + return poisonDuration; + } +} diff --git a/src/TextJustification.java b/src/TextJustification.java new file mode 100644 index 0000000..cd1e156 --- /dev/null +++ b/src/TextJustification.java @@ -0,0 +1,66 @@ +// https://leetcode.com/problems/text-justification +// T: O(|words|) +// S: O(|words|) + +import java.util.ArrayList; +import java.util.List; + +public class TextJustification { + public List fullJustify(String[] words, int maxWidth) { + List ans = new ArrayList<>(); + int i = 0; + + while (i < words.length) { + List currentLine = getWords(i, words, maxWidth); + i += currentLine.size(); + ans.add(createLine(currentLine, i, words, maxWidth)); + } + + return ans; + } + + private List getWords(int i, String[] words, int maxWidth) { + List currentLine = new ArrayList<>(); + int currLength = 0; + + while (i < words.length && currLength + words[i].length() <= maxWidth) { + currentLine.add(words[i]); + currLength += words[i].length() + 1; + i++; + } + + return currentLine; + } + + private String createLine( + List line, + int i, + String[] words, + int maxWidth + ) { + int baseLength = -1; + for (String word : line) { + baseLength += word.length() + 1; + } + + int extraSpaces = maxWidth - baseLength; + + if (line.size() == 1 || i == words.length) { + return String.join(" ", line) + " ".repeat(extraSpaces); + } + + int wordCount = line.size() - 1; + int spacesPerWord = extraSpaces / wordCount; + int needsExtraSpace = extraSpaces % wordCount; + + for (int j = 0; j < needsExtraSpace; j++) { + line.set(j, line.get(j) + " "); + } + + for (int j = 0; j < wordCount; j++) { + line.set(j, line.get(j) + " ".repeat(spacesPerWord)); + } + + return String.join(" ", line); + } +} \ No newline at end of file diff --git a/src/TheEarliestMomentWhenEveryoneBecomeFriends.java b/src/TheEarliestMomentWhenEveryoneBecomeFriends.java new file mode 100644 index 0000000..3962b3c --- /dev/null +++ b/src/TheEarliestMomentWhenEveryoneBecomeFriends.java @@ -0,0 +1,63 @@ +// https://leetcode.com/problems/the-earliest-moment-when-everyone-become-friends +// M = |logs| +// T: O(N + M logM + M al(N)) al = inverse Ackermann function +// S: O(N + logM) + +import java.util.Arrays; +import java.util.Comparator; + +public class TheEarliestMomentWhenEveryoneBecomeFriends { + private static final class DisjointSet { + private final int[] root, rank; + + public DisjointSet(int size) { + root = new int[size]; + rank = new int[size]; + for (int i = 0 ; i < size ; i++) { + root[i] = i; + rank[i] = 1; + } + } + + public int find(int num) { + if (num == root[num]) { + return num; + } + return root[num] = find(root[num]); + } + + public boolean areConnected(int x, int y) { + return find(x) == find(y); + } + + public void union(int x, int y) { + final int rootX = find(x), rootY = find(y); + if (rootX == rootY) { + return; + } + if (rank[rootX] > rank[rootY]) { + root[rootY] = rootX; + } else if (rank[rootX] < rank[rootY]) { + root[rootX] = rootY; + } else { + root[rootY] = rootX; + rank[rootX]++; + } + } + } + + public int earliestAcq(int[][] logs, int n) { + final DisjointSet disjointSet = new DisjointSet(n); + Arrays.sort(logs, Comparator.comparingInt(a -> a[0])); + for (int[] log : logs) { + if (!disjointSet.areConnected(log[1], log[2])) { + disjointSet.union(log[1], log[2]); + n--; + if (n == 1) { + return log[0]; + } + } + } + return -1; + } +} diff --git a/src/TheEmployeeThatWorkedOnTheLongestTask.java b/src/TheEmployeeThatWorkedOnTheLongestTask.java new file mode 100644 index 0000000..a8d673f --- /dev/null +++ b/src/TheEmployeeThatWorkedOnTheLongestTask.java @@ -0,0 +1,20 @@ +// https://leetcode.com/problems/the-employee-that-worked-on-the-longest-task +// T: O(|logs|) +// S: O(1) + +public class TheEmployeeThatWorkedOnTheLongestTask { + public int hardestWorker(int n, int[][] logs) { + int longestTime = -1, employeeId = -1, previousTime = 0; + for (int[] log : logs) { + int time = log[1] - previousTime; + previousTime = log[1]; + if (time > longestTime) { + longestTime = time; + employeeId = log[0]; + } else if (time == longestTime && log[0] < employeeId) { + employeeId = log[0]; + } + } + return employeeId; + } +} diff --git a/src/TheKWeakestRowsInAMatrix.java b/src/TheKWeakestRowsInAMatrix.java new file mode 100644 index 0000000..da67da4 --- /dev/null +++ b/src/TheKWeakestRowsInAMatrix.java @@ -0,0 +1,42 @@ +import java.util.PriorityQueue; +import java.util.Queue; + +public class TheKWeakestRowsInAMatrix { + public int[] kWeakestRows(int[][] mat, int k) { + final Queue minHeap = new PriorityQueue<>(); + for (int index = 0 ; index < mat.length ; index++) { + minHeap.add(Row.from(mat[index], index)); + } + final int[] result = new int[k]; + for (int i = 0 ; i < result.length ; i++) { + result[i] = minHeap.poll().index; + } + return result; + } + + private static final class Row implements Comparable { + private final int index; + private final int soldiers; + + private Row(int index, int soldiers) { + this.index = index; + this.soldiers = soldiers; + } + + @Override + public int compareTo(Row other) { + if (this.soldiers == other.soldiers) { + return Integer.compare(this.index, other.index); + } + return Integer.compare(this.soldiers, other.soldiers); + } + + private static Row from(int[] row, int index) { + int soldiers = 0; + for (int i = 0; i < row.length && row[i] == 1; i++) { + soldiers++; + } + return new Row(index, soldiers); + } + } +} diff --git a/src/TheMazeII.java b/src/TheMazeII.java new file mode 100644 index 0000000..c42110f --- /dev/null +++ b/src/TheMazeII.java @@ -0,0 +1,78 @@ +// https://leetcode.com/problems/the-maze-ii +// T: O(m * n * log(m * n)) +// S: O(m * n) + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.PriorityQueue; +import java.util.Queue; + +public class TheMazeII { + private static final int[][] DIRECTIONS = new int[][] {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; + + public int shortestDistance(int[][] maze, int[] start, int[] destination) { + final int rows = maze.length, columns = maze[0].length; + final int[][] distance = dijkstra(maze, start); + return distance[destination[0]][destination[1]] == Integer.MAX_VALUE ? -1 : distance[destination[0]][destination[1]]; + } + + // T: O(m * n * log(mn)) + // S: O(m * n) + public int[][] dijkstra(int[][] maze, int[] start) { + final int[][] distance = getDistances(maze.length, maze[0].length); + final Queue queue = new PriorityQueue<>(Comparator.comparingInt(a -> a[2])); + + queue.add(new int[] { start[0], start[1], 0 }); + + while (!queue.isEmpty()) { + final int[] s = queue.poll(); + final int row = s[0], column = s[1], d = s[2]; + + if (distance[row][column] <= d) { + continue; + } + + distance[row][column] = d; + + for (int[] position: validPositions(maze, s[0], s[1])) { + final int newDistance = distance[row][column] + manhattanDistance(s[0], s[1], position); + queue.add(new int[] { position[0], position[1], newDistance}); + } + } + + return distance; + } + + // T: O(m + n) + // S: O(1) + private static List validPositions(int[][] grid, int row, int column) { + final List result = new ArrayList<>(); + for (int[] direction : DIRECTIONS) { + int i = row, j = column; + while (i >= 0 && j >= 0 && i < grid.length && j < grid[0].length && grid[i][j] == 0) { + i += direction[0]; + j += direction[1]; + } + result.add(new int[] { i - direction[0], j - direction[1] }); + } + return result; + } + + // T: O(m * n) + // S: O(m * n) + private static int[][] getDistances(int rows, int columns) { + final int[][] result = new int[rows][columns]; + for (int i = 0 ; i < rows ; i++) { + for (int j = 0 ; j < columns ; j++) { + result[i][j] = Integer.MAX_VALUE; + } + } + return result; + } + + // T: O(1), S: O(1) + private static int manhattanDistance(int row, int column, int[] position) { + return Math.abs(row - position[0]) + Math.abs(column - position[1]); + } +} diff --git a/src/TheMazeIII.java b/src/TheMazeIII.java new file mode 100644 index 0000000..edc13fc --- /dev/null +++ b/src/TheMazeIII.java @@ -0,0 +1,98 @@ +// https://leetcode.com/problems/the-maze-iii +// T: O(m * n log(m * n)) +// S: O(m * n) + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.PriorityQueue; +import java.util.Queue; + +public class TheMazeIII { + private record Info(int[] position, int distance, String path) {} + + private record Position(int[] position, String direction) {} + + private static final Position[] DIRECTIONS = new Position[] { + new Position(new int[] { 1, 0 }, "d"), + new Position(new int[] { 0, -1 }, "l"), + new Position(new int[] { 0, 1 }, "r"), + new Position(new int[] { -1, 0 }, "u") + }; + + // T: O(m * n * log(m * n)), S: O(m * n) + public String findShortestWay(int[][] maze, int[] ball, int[] hole) { + final int[][] distances = getDistances(maze.length, maze[0].length); + final Queue queue = new PriorityQueue<>((a, b) -> { + if (a.distance == b.distance) { + return a.path.compareTo(b.path); + } + return Integer.compare(a.distance, b.distance); + }); + queue.add(new Info(ball, 0, "")); + String path = null; + + while (!queue.isEmpty()) { + final Info info = queue.poll(); + + if (distances[info.position[0]][info.position[1]] <= info.distance) { + continue; + } + + distances[info.position[0]][info.position[1]] = info.distance; + + if (info.position[0] == hole[0] && info.position[1] == hole[1]) { + if (path == null) { + path = info.path; + } else { + path = path.compareTo(info.path) > 0 ? info.path : path; + } + } + + for (Position position : validPositions(maze, info.position, hole)) { + queue.add(new Info( + position.position, + info.distance + manhattanDistance(position.position, info.position), + info.path + position.direction + )); + } + } + + final int minDistance = distances[hole[0]][hole[1]]; + return minDistance == Integer.MAX_VALUE ? "impossible" : path; + } + + // T: O(1), S:O(1) + private static int manhattanDistance(int[] p1, int[] p2) { + return Math.abs(p1[0] - p2[0]) + Math.abs(p1[1] - p2[1]); + } + + // T: O(m + n), S: O(1) + private static List validPositions(int[][] grid, int[] position, int[] target) { + final List result = new ArrayList<>(); + for (Position p : DIRECTIONS) { + int row = position[0], column = position[1]; + while (row >= 0 && row < grid.length + && column >= 0 && column < grid[0].length && grid[row][column] == 0 && + (row != target[0] || column != target[1])) { + row += p.position[0]; + column += p.position[1]; + } + if (row == target[0] && column == target[1]) { + result.add(new Position(new int[] { row, column}, p.direction)); + } else { + result.add(new Position(new int[]{row - p.position[0], column - p.position[1]}, p.direction)); + } + } + return result; + } + + // T: O(m * n), S: O(m * n) + private static int[][] getDistances(int rows, int columns) { + final int[][] distances = new int[rows][columns]; + for (int[] row : distances) { + Arrays.fill(row, Integer.MAX_VALUE); + } + return distances; + } +} diff --git a/src/ThousandSeparator.java b/src/ThousandSeparator.java new file mode 100644 index 0000000..adabd18 --- /dev/null +++ b/src/ThousandSeparator.java @@ -0,0 +1,25 @@ +import java.util.LinkedList; + +public class ThousandSeparator { + public String thousandSeparator(int n) { + final LinkedList list = getDigits(n); + final StringBuilder result = new StringBuilder(); + for (int i = 3 ; !list.isEmpty() ; i = (i + 1) % 3) { + if (i == 0) result.append('.'); + result.append(list.pop()); + } + return result.reverse().toString(); + } + + private LinkedList getDigits(int number) { + final LinkedList result = new LinkedList<>(); + if (number == 0) { + result.add(0); + } + while (number > 0) { + result.add(number % 10); + number /= 10; + } + return result; + } +} diff --git a/src/ThreeConsecutiveOdds.java b/src/ThreeConsecutiveOdds.java new file mode 100644 index 0000000..8ba79e7 --- /dev/null +++ b/src/ThreeConsecutiveOdds.java @@ -0,0 +1,14 @@ +public class ThreeConsecutiveOdds { + public boolean threeConsecutiveOdds(int[] array) { + for (int i = 0 ; i < array.length - 2 ; i++) { + if (isOdd(array[i]) && isOdd(array[i + 1]) && isOdd(array[i + 2])) { + return true; + } + } + return false; + } + + private boolean isOdd(int x) { + return (x & 1) == 1; + } +} diff --git a/src/ThreeDivisors.java b/src/ThreeDivisors.java new file mode 100644 index 0000000..1a66a91 --- /dev/null +++ b/src/ThreeDivisors.java @@ -0,0 +1,49 @@ +// https://leetcode.com/problems/three-divisors +// T: O(1) +// S: O(1) + +public class ThreeDivisors { + private static final PrimeSieve PRIME_SIEVE = PrimeSieve.ofSize(101); + + public boolean isThree(int n) { + return isPerfectSquare(n); + } + + private boolean isPerfectSquare(int x) { + int sqrt = (int) Math.sqrt(x); + return sqrt * sqrt == x && PRIME_SIEVE.isPrime(sqrt); + } + + private static class PrimeSieve { + final byte[] sieve; + + private static PrimeSieve ofSize(int size) { + return new PrimeSieve(size); + } + + PrimeSieve(int size) { + this.sieve = new byte[size + 1]; + initializeSieve(); + } + + public boolean isPrime(int number) { + return sieve[number] == 0; + } + + private void initializeSieve() { + sieve[0] = 1; + sieve[1] = 1; + for (int i = 2 ; i < sieve.length ; i++) { + if (sieve[i] == 0) { + markFactors(i); + } + } + } + + private void markFactors(int prime) { + for (int i = prime * prime ; i < sieve.length ; i += prime) { + sieve[i] = 1; + } + } + } +} diff --git a/src/ThreeSum.java b/src/ThreeSum.java new file mode 100644 index 0000000..46ac050 --- /dev/null +++ b/src/ThreeSum.java @@ -0,0 +1,25 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class ThreeSum { + public List> threeSum(int[] nums) { + if (nums.length < 3) return Collections.emptyList(); + final Set> triplets = new HashSet<>(); + Arrays.sort(nums); + + for (int i = 0; i < nums.length - 2; i++) { + for (int j = i + 1, k = nums.length - 1 ; j < k ; ) { + int sum = nums[i] + nums[j] + nums[k]; + if (sum == 0) triplets.add(List.of(nums[i], nums[j++], nums[k--])); + else if (sum > 0) k--; + else j++; + } + } + + return new ArrayList<>(triplets); + } +} diff --git a/src/ThreeSumClosest.java b/src/ThreeSumClosest.java new file mode 100644 index 0000000..67fcea4 --- /dev/null +++ b/src/ThreeSumClosest.java @@ -0,0 +1,28 @@ +// https://leetcode.com/problems/3sum-closest +// T: O(n^2) +// S: O(1) + +import java.util.Arrays; + +public class ThreeSumClosest { + public static void main(String[] args) { + System.out.println(threeSumClosest(new int[] {0, 2, 1, -3}, 1)); + } + + public static int threeSumClosest(int[] nums, int target) { + Arrays.sort(nums); + int closestSum = nums[0] + nums[1] + nums[2]; + for (int i = 0 ; i < nums.length - 2 ; i++) { + for (int j = i + 1, k = nums.length - 1 ; j < k ; ) { + int sum = nums[i] + nums[j] + nums[k]; + if (sum == target) return sum; + if (Math.abs(sum - target) < Math.abs(closestSum - target)) { + closestSum = sum; + } + else if (sum > target) k--; + else j++; + } + } + return closestSum; + } +} diff --git a/src/ThroneInheritance.java b/src/ThroneInheritance.java new file mode 100644 index 0000000..f8ab812 --- /dev/null +++ b/src/ThroneInheritance.java @@ -0,0 +1,63 @@ +// https://leetcode.com/problems/throne-inheritance +// N = people in royal family +// birth() T: O(1) +// death() T: O(1) +// getInheritanceOrder T: O(N) +// S: O(N) + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ThroneInheritance { + private static final class Person { + private final String name; + private boolean isAlive = true; + private final List children = new ArrayList<>(); + + Person(String name) { + this.name = name; + } + + void markDead() { + this.isAlive = false; + } + + void addChild(Person child) { + this.children.add(child); + } + } + + private final Map royalFamily = new HashMap<>(); + private final Person king; + + public ThroneInheritance(String kingName) { + king = new Person(kingName); + royalFamily.put(kingName, king); + } + + public void birth(String parentName, String childName) { + Person child = new Person(childName); + royalFamily.put(childName, child); + royalFamily.get(parentName).addChild(child); + } + + public void death(String name) { + royalFamily.get(name).markDead(); + } + + public List getInheritanceOrder() { + final List names = new ArrayList<>(); + getInheritanceOrder(king, names); + return names; + } + + public void getInheritanceOrder(Person person, List names) { + if (person == null) return; + if (person.isAlive) names.add(person.name); + for (Person child : person.children) { + getInheritanceOrder(child, names); + } + } +} diff --git a/src/TimeNeededToBuyTickets.java b/src/TimeNeededToBuyTickets.java new file mode 100644 index 0000000..7ea3a8b --- /dev/null +++ b/src/TimeNeededToBuyTickets.java @@ -0,0 +1,12 @@ +// https://leetcode.com/problems/time-needed-to-buy-tickets +// T: O(|tickets|) +// S: O(1) + +public class TimeNeededToBuyTickets { + public int timeRequiredToBuy(int[] tickets, int k) { + int time = 0; + for (int i = 0 ; i < k ; i++) time += Math.min(tickets[i], tickets[k]); + for (int i = k + 1 ; i < tickets.length ; i++) time += Math.min(tickets[i], tickets[k] - 1); + return time + tickets[k]; + } +} diff --git a/src/TimeNeededToInformAllEmployees.java b/src/TimeNeededToInformAllEmployees.java new file mode 100644 index 0000000..9aec965 --- /dev/null +++ b/src/TimeNeededToInformAllEmployees.java @@ -0,0 +1,57 @@ +// https://leetcode.com/problems/time-needed-to-inform-all-employees +// T: O(n) +// S: O(n) + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class TimeNeededToInformAllEmployees { + private static final class TreeNode { + int val; + List subordinates = new ArrayList<>(); + + TreeNode(int val) { + this.val = val; + } + + private boolean hasSubordinates() { + return subordinates.size() > 0; + } + + private void addSubordinate(TreeNode subordinate) { + this.subordinates.add(subordinate); + } + } + + public int numOfMinutes(int n, int headID, int[] manager, int[] informTime) { + TreeNode company = createEmployeeGraph(headID, manager); + return timeNeededForInformationDispersal(company, informTime); + } + + private int timeNeededForInformationDispersal(TreeNode root, int[] informTime) { + if (root == null || !root.hasSubordinates()) return 0; + int timeTaken = 0; + for (TreeNode subordinate : root.subordinates) { + timeTaken = Math.max(timeTaken, timeNeededForInformationDispersal(subordinate, informTime)); + } + return timeTaken + informTime[root.val]; + } + + private TreeNode createEmployeeGraph(int headIndex, int[] managers) { + final TreeNode root = new TreeNode(headIndex); + final Map employees = new HashMap<>(); + employees.put(headIndex, root); + for (int i = 0 ; i < managers.length ; i++) { + int managerId = managers[i]; + if (managerId == -1) continue; + TreeNode manager = employees.getOrDefault(managerId, new TreeNode(managerId)); + TreeNode subordinate = employees.getOrDefault(i, new TreeNode(i)); + manager.addSubordinate(subordinate); + if (!employees.containsKey(managerId)) employees.put(managerId, manager); + if (!employees.containsKey(i)) employees.put(i, subordinate); + } + return root; + } +} diff --git a/src/ToLowerCase.java b/src/ToLowerCase.java new file mode 100644 index 0000000..362a083 --- /dev/null +++ b/src/ToLowerCase.java @@ -0,0 +1,25 @@ +public class ToLowerCase { + public String toLowerCase(String s) { + StringBuilder result = new StringBuilder(); + for (int index = 0 ; index < s.length() ; index++) { + result.append(toLowerCase(s.charAt(index))); + } + return result.toString(); + } + + private char toLowerCase(char character) { + return isUpperCase(character) && isAlphabet(character) ? (char) (character + 32) : character; + } + + private boolean isAlphabet(char character) { + return isUpperCase(character) || isLowerCase(character); + } + + private boolean isLowerCase(char character) { + return 97 <= character && character <= 122; + } + + private boolean isUpperCase(char character) { + return 65 <= character && character <= 90; + } +} diff --git a/src/ToeplitzMatrix.java b/src/ToeplitzMatrix.java new file mode 100644 index 0000000..5b5b523 --- /dev/null +++ b/src/ToeplitzMatrix.java @@ -0,0 +1,19 @@ +public class ToeplitzMatrix { + public boolean isToeplitzMatrix(int[][] matrix) { + final int rows = matrix.length, columns = matrix[0].length; + int current; + for (int column = 0 ; column < columns ; column++) { + current = matrix[0][column]; + for (int row = 1 ; row < rows && column + row < columns ; row++) { + if (matrix[row][column + row] != current) return false; + } + } + for (int row = 1 ; row < rows - 1 ; row++) { + current = matrix[row][0]; + for (int column = 1 ; column < columns && row + column < rows ; column++) { + if (matrix[row + column][column] != current) return false; + } + } + return true; + } +} diff --git a/src/TotalDistanceTraveled.java b/src/TotalDistanceTraveled.java new file mode 100644 index 0000000..11d6490 --- /dev/null +++ b/src/TotalDistanceTraveled.java @@ -0,0 +1,25 @@ +// https://leetcode.com/problems/total-distance-traveled +// M = mainTank +// T: O(M) +// S: O(1) + +public class TotalDistanceTraveled { + public int distanceTraveled(int mainTank, int additionalTank) { + int totalDistance = 0; + while (mainTank > 0) { + if (mainTank >= 5) { + mainTank -= 5; + totalDistance += 50; + if (additionalTank > 0) { + mainTank++; + additionalTank--; + } + } else { + totalDistance += mainTank * 10; + mainTank = 0; + } + } + + return totalDistance; + } +} diff --git a/src/TransposeMatrix.java b/src/TransposeMatrix.java new file mode 100644 index 0000000..96a84d8 --- /dev/null +++ b/src/TransposeMatrix.java @@ -0,0 +1,14 @@ +public class TransposeMatrix { + public int[][] transpose(int[][] matrix) { + final int rows = matrix.length, columns = matrix[0].length; + final int[][] result = new int[columns][rows]; + + for (int row = 0 ; row < rows ; row++) { + for (int column = 0 ; column < columns ; column++) { + result[column][row] = matrix[row][column]; + } + } + + return result; + } +} diff --git a/src/TrappingRainwater.java b/src/TrappingRainwater.java new file mode 100644 index 0000000..f06fc83 --- /dev/null +++ b/src/TrappingRainwater.java @@ -0,0 +1,20 @@ +// T: O(n) +// S: O(1) + +public class TrappingRainwater { + public static int trap(int[] height) { + int result = 0; + for (int left = 0, right = height.length - 1, leftMax = 0, rightMax = 0 ; left < right ; ) { + if (height[left] < height[right]) { + if (leftMax < height[left]) leftMax = height[left]; + else result += leftMax - height[left]; + left++; + } else { + if (rightMax < height[right]) rightMax = height[right]; + else result += rightMax - height[right]; + right--; + } + } + return result; + } +} diff --git a/src/TreeNode.java b/src/TreeNode.java new file mode 100644 index 0000000..d8a3798 --- /dev/null +++ b/src/TreeNode.java @@ -0,0 +1,48 @@ +public class TreeNode implements TreePrinter.PrintableNode { + int val; + TreeNode left; + TreeNode right; + TreeNode() {} + + public static final TreeNode EXAMPLE_1; + + static { + EXAMPLE_1 = new TreeNode(7); + EXAMPLE_1.left = new TreeNode(3); + EXAMPLE_1.right = new TreeNode(15); + EXAMPLE_1.right.left = new TreeNode(9); + EXAMPLE_1.right.right = new TreeNode(20); + } + + TreeNode(int val) { + this.val = val; + } + + TreeNode(int val, TreeNode left, TreeNode right) { + this.val = val; + this.left = left; + this.right = right; + } + + @Override + public String toString() { + return "TreeNode{" + + "val=" + val + + '}'; + } + + @Override + public TreePrinter.PrintableNode getLeft() { + return this.left; + } + + @Override + public TreePrinter.PrintableNode getRight() { + return this.right; + } + + @Override + public String getText() { + return this.val + ""; + } +} diff --git a/src/TreePrinter.java b/src/TreePrinter.java new file mode 100644 index 0000000..9586652 --- /dev/null +++ b/src/TreePrinter.java @@ -0,0 +1,134 @@ +import java.util.ArrayList; +import java.util.List; + + +/** + * Binary tree printer + * + * @author saiteja + */ +public class TreePrinter { + /** Node that can be printed */ + public interface PrintableNode { + /** Get left child */ + PrintableNode getLeft(); + + /** Get right child */ + PrintableNode getRight(); + + /** Get text to be printed */ + String getText(); + } + + + /** + * Print a tree + * + * @param root + * tree root node + */ + public static void print(PrintableNode root) { + List> lines = new ArrayList<>(); + + List level = new ArrayList<>(); + List next = new ArrayList<>(); + + level.add(root); + int nn = 1; + + int widest = 0; + + while (nn != 0) { + List line = new ArrayList(); + + nn = 0; + + for (PrintableNode n : level) { + if (n == null) { + line.add(null); + + next.add(null); + next.add(null); + } else { + String aa = n.getText(); + line.add(aa); + if (aa.length() > widest) widest = aa.length(); + + next.add(n.getLeft()); + next.add(n.getRight()); + + if (n.getLeft() != null) nn++; + if (n.getRight() != null) nn++; + } + } + + if (widest % 2 == 1) widest++; + + lines.add(line); + + List tmp = level; + level = next; + next = tmp; + next.clear(); + } + + int perpiece = lines.get(lines.size() - 1).size() * (widest + 4); + for (int i = 0; i < lines.size(); i++) { + List line = lines.get(i); + int hpw = (int) Math.floor(perpiece / 2f) - 1; + + if (i > 0) { + for (int j = 0; j < line.size(); j++) { + + // split node + char c = ' '; + if (j % 2 == 1) { + if (line.get(j - 1) != null) { + c = (line.get(j) != null) ? '┴' : '┘'; + } else { + if (line.get(j) != null) c = '└'; + } + } + System.out.print(c); + + // lines and spaces + if (line.get(j) == null) { + for (int k = 0; k < perpiece - 1; k++) { + System.out.print(" "); + } + } else { + + for (int k = 0; k < hpw; k++) { + System.out.print(j % 2 == 0 ? " " : "─"); + } + System.out.print(j % 2 == 0 ? "┌" : "┐"); + for (int k = 0; k < hpw; k++) { + System.out.print(j % 2 == 0 ? "─" : " "); + } + } + } + System.out.println(); + } + + // print line of numbers + for (String f : line) { + + if (f == null) f = ""; + int gap1 = (int) Math.ceil(perpiece / 2f - f.length() / 2f); + int gap2 = (int) Math.floor(perpiece / 2f - f.length() / 2f); + + // a number + for (int k = 0; k < gap1; k++) { + System.out.print(" "); + } + System.out.print(f); + for (int k = 0; k < gap2; k++) { + System.out.print(" "); + } + } + System.out.println(); + + perpiece /= 2; + } + } +} diff --git a/src/Triangle.java b/src/Triangle.java new file mode 100644 index 0000000..7a1192d --- /dev/null +++ b/src/Triangle.java @@ -0,0 +1,35 @@ +// https://leetcode.com/problems/triangle +// T: O(n) where n elements in triangle +// S: O(1) + +import java.util.List; + +public class Triangle { + public int minimumTotal(List> triangle) { + final int rows = triangle.size(); + List previousRow = triangle.get(0); + + for (int row = 1 ; row < rows ; row++) { + final List currentRow = triangle.get(row); + for (int column = 0 ; column < row + 1 ; column++) { + if (column == 0) currentRow.set(column, currentRow.get(column) + previousRow.get(0)); + else if (column == row) currentRow.set(column, currentRow.get(column) + previousRow.get(row - 1)); + else currentRow.set( + column, + currentRow.get(column) + Math.min(previousRow.get(column - 1), previousRow.get(column)) + ); + } + previousRow = currentRow; + } + + return minOfLastRow(triangle); + } + + private int minOfLastRow(List> triangle) { + return min(triangle.get(triangle.size() - 1)); + } + + private int min(List array) { + return array.stream().min(Integer::compareTo).get(); + } +} diff --git a/src/Trie.java b/src/Trie.java new file mode 100644 index 0000000..7e847eb --- /dev/null +++ b/src/Trie.java @@ -0,0 +1,59 @@ +// https://leetcode.com/problems/implement-trie-prefix-tree +// insertion +// T: O(n) +// S: O(n) +// search +// T: O(n) +// S: O(n) +// starts with +// T: O(n) +// S: O(n) + +public class Trie { + private final Trie[] alphabet = new Trie[26]; + private boolean isWordEnd = false; + + public Trie() { } + + public void insert(String word) { + insert(word, 0); + } + + private void insert(String word, int index) { + if (index == word.length()) { + this.isWordEnd = true; + return; + } + int charIndex = toIndex(word.charAt(index)); + if (alphabet[charIndex] == null) { + alphabet[charIndex] = new Trie(); + } + alphabet[charIndex].insert(word, index + 1); + } + + public boolean search(String word) { + return search(word, 0); + } + + public boolean search(String word, int index) { + if (index == word.length()) return isWordEnd; + int charIndex = toIndex(word.charAt(index)); + if (alphabet[charIndex] == null) return false; + return alphabet[charIndex].search(word, index + 1); + } + + public boolean startsWith(String prefix) { + return startsWith(prefix, 0); + } + + public boolean startsWith(String prefix, int index) { + if (index == prefix.length()) return true; + int charIndex = toIndex(prefix.charAt(index)); + if (alphabet[charIndex] == null) return false; + return alphabet[charIndex].startsWith(prefix, index + 1); + } + + private int toIndex(char c) { + return c - 'a'; + } +} diff --git a/src/TrimABinarySearchTree.java b/src/TrimABinarySearchTree.java new file mode 100644 index 0000000..7dd264a --- /dev/null +++ b/src/TrimABinarySearchTree.java @@ -0,0 +1,10 @@ +public class TrimABinarySearchTree { + public TreeNode trimBST(TreeNode root, int low, int high) { + if (root == null) return null; + if (root.val < low) return trimBST(root.right, low, high); + if (root.val > high) return trimBST(root.left, low, high); + root.left = trimBST(root.left, low, high); + root.right = trimBST(root.right, low, high); + return root; + } +} diff --git a/src/TruncateSentences.java b/src/TruncateSentences.java new file mode 100644 index 0000000..1929cac --- /dev/null +++ b/src/TruncateSentences.java @@ -0,0 +1,14 @@ +public class TruncateSentences { + public String truncateSentence(String s, int k) { + final StringBuilder result = new StringBuilder(); + for (int index = 0, words = 0 ; index < s.length() && words < k ; index++) { + if (s.charAt(index) != ' ') { + result.append(s.charAt(index)); + } else { + words++; + result.append(words < k ? ' ' : ""); + } + } + return result.toString(); + } +} diff --git a/src/TwoFurthestHousesWithDifferentColors.java b/src/TwoFurthestHousesWithDifferentColors.java new file mode 100644 index 0000000..e0e0084 --- /dev/null +++ b/src/TwoFurthestHousesWithDifferentColors.java @@ -0,0 +1,9 @@ +public class TwoFurthestHousesWithDifferentColors { + public int maxDistance(int[] colors) { + int i = colors.length - 1; + for ( ; i >= 0 && colors[i] == colors[0] ; i--); + int distance = i; + for (i = 0 ; i < colors.length && colors[i] == colors[colors.length - 1] ; i++); + return Math.max(distance, colors.length - 1 - i); + } +} diff --git a/src/TwoOutOfThree.java b/src/TwoOutOfThree.java new file mode 100644 index 0000000..c512a07 --- /dev/null +++ b/src/TwoOutOfThree.java @@ -0,0 +1,35 @@ +// https://leetcode.com/problems/two-out-of-three +// T: O(|nums1| + |nums2| + |nums3|) +// S: O(|nums1| + |nums2| + |nums3|) + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class TwoOutOfThree { + public List twoOutOfThree(int[] nums1, int[] nums2, int[] nums3) { + final Set set1 = getElements(nums1); + final Set set2 = getElements(nums2); + final Set set3 = getElements(nums3); + final Set resultElements = new HashSet<>(); + for (int element : set1) { + if (set2.contains(element) || set3.contains(element)) { + resultElements.add(element); + } + } + for (int element : set2) { + if (set3.contains(element)) resultElements.add(element); + } +// return resultElements.stream().toList(); // cant be used because LeetCode is still on a previous version of Java + return new ArrayList<>(resultElements); + } + + private Set getElements(int[] array) { + final Set set = new HashSet<>(); + for (int element : array) { + set.add(element); + } + return set; + } +} diff --git a/src/TwoSum.java b/src/TwoSum.java index ef5470e..f072b69 100644 --- a/src/TwoSum.java +++ b/src/TwoSum.java @@ -1,4 +1,6 @@ // https://leetcode.com/problems/two-sum/ +// T: O(N) +// S: O(N) import java.util.Arrays; import java.util.HashMap; diff --git a/src/TwoSumIIIDataStructureDesign.java b/src/TwoSumIIIDataStructureDesign.java new file mode 100644 index 0000000..637824d --- /dev/null +++ b/src/TwoSumIIIDataStructureDesign.java @@ -0,0 +1,34 @@ +import java.util.HashMap; +import java.util.Map; + +public class TwoSumIIIDataStructureDesign { + static class TwoSum { + private final Map map = new HashMap<>(); + + // T: O(1) + public void add(int number) { + map.put(number, map.getOrDefault(number, 0) + 1); + } + + // N: number of unique elements we have seen so far + // T: O(N) + public boolean find(int sum) { + for (int current : map.keySet()) { + final int required = sum - current; + if (required == current) { + if (map.get(required) >= 2) { + return true; + } else { + continue; + } + } + + if (map.containsKey(required)) { + return true; + } + } + + return false; + } + } +} diff --git a/src/TwoSumIVInputIsABST.java b/src/TwoSumIVInputIsABST.java new file mode 100644 index 0000000..c3c7875 --- /dev/null +++ b/src/TwoSumIVInputIsABST.java @@ -0,0 +1,14 @@ +import java.util.HashSet; +import java.util.Set; + + +public class TwoSumIVInputIsABST { + Set elements = new HashSet<>(); + + public boolean findTarget(TreeNode root, int k) { + if (root == null) return false; + if (elements.contains(k - root.val)) return true; + elements.add(root.val); + return findTarget(root.left, k) || findTarget(root.right, k); + } +} diff --git a/src/TypeOfTriangle.java b/src/TypeOfTriangle.java new file mode 100644 index 0000000..9b39e0f --- /dev/null +++ b/src/TypeOfTriangle.java @@ -0,0 +1,22 @@ +// https://leetcode.com/problems/type-of-triangle +// T: O(1) +// S: O(1) + +public class TypeOfTriangle { + public String triangleType(int[] sides) { + if (!isValidTriangle(sides)) { + return "none"; + } + if (sides[0] == sides[1] && sides[1] == sides[2]) { + return "equilateral"; + } + if (sides[0] == sides[1] || sides[0] == sides[2] || sides[1] == sides[2]) { + return "isosceles"; + } + return "scalene"; + } + + private static boolean isValidTriangle(int[] sides) { + return sides[0] + sides[1] > sides[2] && sides[0] + sides[2] > sides[1] && sides[1] + sides[2] > sides[0]; + } +} diff --git a/src/UglyNumber.java b/src/UglyNumber.java index 92cd96f..d6ef212 100644 --- a/src/UglyNumber.java +++ b/src/UglyNumber.java @@ -1,3 +1,7 @@ +// https://leetcode.com/problems/ugly-number +// T: O(log(N)) +// S: O(1) + public class UglyNumber { public static boolean isUgly(int number) { if (number <= 0) { diff --git a/src/UglyNumberII.java b/src/UglyNumberII.java new file mode 100644 index 0000000..c4c5dd1 --- /dev/null +++ b/src/UglyNumberII.java @@ -0,0 +1,26 @@ +// https://leetcode.com/problems/ugly-number-ii +// T: O(N) +// S: O(N) + +public class UglyNumberII { + public int nthUglyNumber(int n) { + final int[] dp = new int[n]; + dp[0] = 1; + int factor2 = 2, factor3 = 3, factor5 = 5; + int index2 = 0, index3 = 0, index5 = 0; + + for(int i = 1 ; i < n ; i++) { + final int uglyNumber = min(factor2, factor3, factor5); + dp[i] = uglyNumber; + if (uglyNumber == factor2) factor2 = 2 * dp[++index2]; + if (uglyNumber == factor3) factor3 = 3 * dp[++index3]; + if (uglyNumber == factor5) factor5 = 5 * dp[++index5]; + } + + return dp[dp.length - 1]; + } + + private int min(int a, int b, int c) { + return Math.min(a, Math.min(b, c)); + } +} diff --git a/src/UglyNumberIII.java b/src/UglyNumberIII.java new file mode 100644 index 0000000..dbea550 --- /dev/null +++ b/src/UglyNumberIII.java @@ -0,0 +1,59 @@ +// https://leetcode.com/problems/ugly-number-iii +// T: O(log(MAX_VAL)) MAX_VAL = Integer.MAX_VAL here +// S: O(1) + +public class UglyNumberIII { + private long a; + private long b; + private long c; + private long lcm_a_b; + private long lcm_a_c; + private long lcm_b_c; + private long lcm_a_b_c; + + public int nthUglyNumber(int n, int a, int b, int c) { + setValues(a, b, c); + int left = 1, right = Integer.MAX_VALUE, middle; + long factors; + while (left <= right) { + middle = left + (right - left) / 2; + factors = numberOfFactors(middle); + if (factors >= n) right = middle - 1; + else left = middle + 1; + } + return left; + } + + private void setValues(long a, long b, long c) { + this.a = a; + this.b = b; + this.c = c; + this.lcm_a_b = lcm(a, b); + this.lcm_a_c = lcm(a, c); + this.lcm_b_c = lcm(b, c); + this.lcm_a_b_c = lcm(lcm_a_b, c); + } + + /* + * @param n number + * @return will tell how many factors are there of a, b and c between 1 and n + * e.g. if n=10 and a=2 b=3 so there are 7 factors {2, 3, 4, 6, 8, 9, 10} + */ + private long numberOfFactors(int n) { + return n / a + + n / b + + n / c + - n / lcm_a_b + - n / lcm_a_c + - n / lcm_b_c + + n / lcm_a_b_c; + } + + private long gcd(long a, long b) { + return b == 0 ? a : gcd(b, a % b); + } + + private long lcm(long a, long b) { + return (a * b) / gcd(a, b); + } +} diff --git a/src/UncommonWordsFromTwoSentences.java b/src/UncommonWordsFromTwoSentences.java new file mode 100644 index 0000000..4879157 --- /dev/null +++ b/src/UncommonWordsFromTwoSentences.java @@ -0,0 +1,35 @@ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class UncommonWordsFromTwoSentences { + public String[] uncommonFromSentences(String s1, String s2) { + final Map sentence1Words = getWordFrequencies(s1); + final Map sentence2Words = getWordFrequencies(s2); + final List result = new ArrayList<>(); + for (Map.Entry entry : sentence1Words.entrySet()) { + if (entry.getValue() == 1 && !sentence2Words.containsKey(entry.getKey())) result.add(entry.getKey()); + } + for (Map.Entry entry : sentence2Words.entrySet()) { + if (entry.getValue() == 1 && !sentence1Words.containsKey(entry.getKey())) result.add(entry.getKey()); + } + return result.toArray(new String[] {}); + } + + private Map getWordFrequencies(String string) { + final Map map = new HashMap<>(); + StringBuilder word =new StringBuilder(); + String s; + for (int index = 0 ; index < string.length() ; index++) { + if (string.charAt(index) == ' ') { + s = word.toString(); + map.put(s, map.getOrDefault(s, 0) + 1); + word = new StringBuilder(); + } else word.append(string.charAt(index)); + } + s = word.toString(); + map.put(s, map.getOrDefault(s, 0) + 1); + return map; + } +} diff --git a/src/UniqueBinarySearchTrees.java b/src/UniqueBinarySearchTrees.java new file mode 100644 index 0000000..78c5c23 --- /dev/null +++ b/src/UniqueBinarySearchTrees.java @@ -0,0 +1,17 @@ +// T: O(n) +// S: O(1) + +public class UniqueBinarySearchTrees { + public int numTrees(int n) { + return catalanNumber(n); + } + + private int catalanNumber(int n) { + long result = 1; + for (int i = 2 ; i <= n ; i++) { + result *= (4L * i - 2); + result /= i + 1; + } + return (int) result; + } +} diff --git a/src/UniqueBinarySearchTreesII.java b/src/UniqueBinarySearchTreesII.java new file mode 100644 index 0000000..9958e8d --- /dev/null +++ b/src/UniqueBinarySearchTreesII.java @@ -0,0 +1,38 @@ +import java.util.ArrayList; +import java.util.List; + +public class UniqueBinarySearchTreesII { + public static List generateTrees(int n) { + List[] result = new List[n + 1]; + result[0] = new ArrayList<>(); + if (n == 0) { + return result[0]; + } + + result[0].add(null); + for (int len = 1; len <= n; len++) { + result[len] = new ArrayList<>(); + for (int j = 0; j < len; j++) { + for (TreeNode nodeL : result[j]) { + for (TreeNode nodeR : result[len - j - 1]) { + TreeNode node = new TreeNode(j + 1); + node.left = nodeL; + node.right = clone(nodeR, j + 1); + result[len].add(node); + } + } + } + } + return result[n]; + } + + private static TreeNode clone(TreeNode n, int offset) { + if (n == null) { + return null; + } + TreeNode node = new TreeNode(n.val + offset); + node.left = clone(n.left, offset); + node.right = clone(n.right, offset); + return node; + } +} diff --git a/src/UniqueEmailAddresses.java b/src/UniqueEmailAddresses.java new file mode 100644 index 0000000..91ecbf2 --- /dev/null +++ b/src/UniqueEmailAddresses.java @@ -0,0 +1,27 @@ +import java.util.HashSet; +import java.util.Set; + +public class UniqueEmailAddresses { + public int numUniqueEmails(String[] emails) { + Set uniqueEmails = new HashSet<>(); + for (String emailAddress : emails) { + uniqueEmails.add(getActualEmailAddress(emailAddress)); + } + return uniqueEmails.size(); + } + + private static String getActualEmailAddress(String email) { + StringBuilder result = new StringBuilder(); + for (int index = 0 ; index < email.length() ; index++) { + if (email.charAt(index) == '+') { + while (email.charAt(index) != '@') index++; + result.append(email.substring(index)); + break; + } else if (email.charAt(index) == '@') { + result.append(email.substring(index)); + break; + } else if (email.charAt(index) != '.') result.append(email.charAt(index)); + } + return result.toString(); + } +} diff --git a/src/UniqueMorseCodeWords.java b/src/UniqueMorseCodeWords.java new file mode 100644 index 0000000..c10557d --- /dev/null +++ b/src/UniqueMorseCodeWords.java @@ -0,0 +1,32 @@ +import java.util.HashSet; +import java.util.Set; + +public class UniqueMorseCodeWords { + private final String[] morseCodeMapping = new String[] { + ".-","-...","-.-.","-..",".","..-.", + "--.","....","..",".---","-.-",".-..", + "--","-.","---",".--.","--.-",".-.", + "...","-","..-","...-",".--","-..-", + "-.--","--.." + }; + + public int uniqueMorseRepresentations(String[] words) { + Set transformations = new HashSet<>(); + for (String word : words) { + transformations.add(morseValue(word)); + } + return transformations.size(); + } + + private String morseValue(String word) { + StringBuilder result = new StringBuilder(); + for (char character : word.toCharArray()) { + result.append(morseValue(character)); + } + return result.toString(); + } + + private String morseValue(char character) { + return morseCodeMapping[character - 'a']; + } +} diff --git a/src/UniqueNumberOfOccurrences.java b/src/UniqueNumberOfOccurrences.java new file mode 100644 index 0000000..9051d19 --- /dev/null +++ b/src/UniqueNumberOfOccurrences.java @@ -0,0 +1,29 @@ +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class UniqueNumberOfOccurrences { + public boolean uniqueOccurrences(int[] array) { + Map frequencies = getFrequencies(array); + return areUnique(frequencies.values()); + } + + private Map getFrequencies(int[] array) { + Map frequencies = new HashMap<>(); + for (int element : array) { + frequencies.put(element, frequencies.getOrDefault(element, 0) + 1); + } + return frequencies; + } + + private boolean areUnique(Collection numbers) { + Set values = new HashSet<>(); + for (int number : numbers) { + if (values.contains(number)) return false; + values.add(number); + } + return true; + } +} diff --git a/src/UniquePathII.java b/src/UniquePathII.java new file mode 100644 index 0000000..d86a9bb --- /dev/null +++ b/src/UniquePathII.java @@ -0,0 +1,35 @@ +// https://leetcode.com/problems/unique-paths-ii +// T: O(m * n) +// S: O(n) + +public class UniquePathII { + public int uniquePathsWithObstacles(int[][] obstacleGrid) { + final int rows = obstacleGrid.length, columns = obstacleGrid[0].length; + if (obstacleGrid[rows - 1][columns - 1] == 1) return 0; + final int[][] memory = getMemoryTable(obstacleGrid); + + int i = 0; + for (int row = rows - 2 ; row >= 0; row--, i ^= 1) { + memory[i][columns - 1] = memory[i ^ 1][columns - 1] & (obstacleGrid[row][columns - 1] ^ 1); + for (int column = columns - 2 ; column >= 0 ; column--) { + if (obstacleGrid[row][column] == 1) { + memory[i][column] = 0; + } else { + memory[i][column] = memory[i ^ 1][column] + memory[i][column + 1]; + } + } + } + + return memory[i ^ 1][0]; + } + + private int[][] getMemoryTable(int[][] obstacles) { + final int rows = obstacles.length, columns = obstacles[0].length; + final int[][] memory = new int[2][columns]; + memory[1][columns - 1] = 1; + for (int column = columns - 2 ; column >= 0 ; column--) { + memory[1][column] = memory[1][column + 1] & (obstacles[rows - 1][column] ^ 1); + } + return memory; + } +} diff --git a/src/UniquePaths.java b/src/UniquePaths.java new file mode 100644 index 0000000..c7ac26b --- /dev/null +++ b/src/UniquePaths.java @@ -0,0 +1,15 @@ +// https://leetcode.com/problems/unique-paths +// T: O(min(m, n)) +// S: O(1) + +public class UniquePaths { + public int uniquePaths(int m, int n) { + final int M = Math.max(m, n) - 1, N = Math.min(m, n) - 1; + long result = 1; + for (int i = M + 1, j = 1 ; i <= M + N ; i++, j++) { + result *= i; + result /= j; + } + return (int) result; + } +} diff --git a/src/UnivaluedBinaryTree.java b/src/UnivaluedBinaryTree.java new file mode 100644 index 0000000..c120c0d --- /dev/null +++ b/src/UnivaluedBinaryTree.java @@ -0,0 +1,14 @@ +public class UnivaluedBinaryTree { + private int val; + + public boolean isUnivalTree(TreeNode root) { + val = root.val; + return isUnival(root); + } + + private boolean isUnival(TreeNode root) { + if (root == null) return true; + if (root.val != val) return false; + return isUnival(root.left) && isUnival(root.right); + } +} diff --git a/src/ValidAnagram.java b/src/ValidAnagram.java index a2c93ad..cf4aab5 100644 --- a/src/ValidAnagram.java +++ b/src/ValidAnagram.java @@ -1,3 +1,8 @@ +// https://leetcode.com/problems/valid-anagram +// T: O(|s| + |t|) +// S: O(1) + + import java.util.HashMap; import java.util.Map; diff --git a/src/ValidBoomerang.java b/src/ValidBoomerang.java new file mode 100644 index 0000000..3a0a00f --- /dev/null +++ b/src/ValidBoomerang.java @@ -0,0 +1,40 @@ +import java.util.Objects; + +public class ValidBoomerang { + public boolean isBoomerang(int[][] points) { + Position p1 = Position.from(points[0]); + Position p2 = Position.from(points[1]); + Position p3 = Position.from(points[2]); + if (p1.equals(p2) || p2.equals(p3) || p3.equals(p1)) return false; + if (p1.x == p2.x) return p3.x != p2.x; + if (p2.x == p3.x) return true; + return (p2.y - p1.y) * (p3.x - p2.x) != (p3.y - p2.y) * (p2.x - p1.x); + } + + private final static class Position { + private final int x; + private final int y; + + private static Position from(int[] array){ + return new Position(array[0], array[1]); + } + + Position(int x, int y) { + this.x = x; + this.y = y; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Position position = (Position) o; + return x == position.x && y == position.y; + } + + @Override + public int hashCode() { + return Objects.hash(x, y); + } + } +} diff --git a/src/ValidMountainArray.java b/src/ValidMountainArray.java new file mode 100644 index 0000000..1cffcc6 --- /dev/null +++ b/src/ValidMountainArray.java @@ -0,0 +1,15 @@ +public class ValidMountainArray { + public boolean validMountainArray(int[] arr) { + boolean isIncreasing = true; + for (int index = 1 ; index < arr.length ; index++) { + if (arr[index] == arr[index - 1]) return false; + if (arr[index] < arr[index - 1] && isIncreasing) { + if (index == 1) return false; + isIncreasing = false; + } else if (arr[index] > arr[index - 1] && !isIncreasing) { + return false; + } + } + return !isIncreasing; + } +} diff --git a/src/ValidPalindromeII.java b/src/ValidPalindromeII.java new file mode 100644 index 0000000..0d31d3c --- /dev/null +++ b/src/ValidPalindromeII.java @@ -0,0 +1,19 @@ +public class ValidPalindromeII { + public boolean validPalindrome(String s) { + for (int left = 0, right = s.length() - 1; left < right ; left++, right--) { + if (s.charAt(left) != s.charAt(right)) { + if (isValidPalindrome(s, left + 1, right)) return true; + return isValidPalindrome(s, left, right + 1); + } + } + return true; + } + + private boolean isValidPalindrome(String string, int left, int right) { + if (left >= string.length() || right <= 0) return false; + for ( ; left < right ; left++, right--) { + if (string.charAt(left) != string.charAt(right)) return false; + } + return true; + } +} diff --git a/src/ValidParentheses.java b/src/ValidParentheses.java index 5d95593..ea31056 100644 --- a/src/ValidParentheses.java +++ b/src/ValidParentheses.java @@ -1,48 +1,37 @@ // https://leetcode.com/problems/valid-parentheses/ +// T: O(n) +// S: O(n) -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; import java.util.Set; import java.util.Stack; public class ValidParentheses { - private static final Set openBrackets = new HashSet<>(); - private static final Map inverse = new HashMap<>(); - - static { - openBrackets.add('('); - openBrackets.add('{'); - openBrackets.add('['); - - inverse.put(')', '('); - inverse.put('}', '{'); - inverse.put(']', '['); - } - - public boolean isValid(String string) { - Stack brackets = new Stack<>(); - for(int index = 0 ; index < string.length() ; index++) { - char character = string.charAt(index); - if (isOpenBracket(character)) { - brackets.push(character); - } else { - if (!brackets.isEmpty() && brackets.peek() == inverse(character)) { - brackets.pop(); - } else { - return false; - } - } + private static final Set CLOSING_BRACES = Set.of(')', ']', '}'); + + public boolean isValid(String s) { + final Stack stack = new Stack<>(); + char bracket; + for (int i = 0 ; i < s.length() ; i++) { + bracket = s.charAt(i); + if (isClosingBracket(bracket)) { + if (!stack.isEmpty() && areOpposites(stack.peek(), bracket)) { + stack.pop(); + } else return false; + } else stack.push(bracket); } - - return brackets.isEmpty(); + return stack.isEmpty(); } - private char inverse(char bracket) { - return inverse.get(bracket); + private boolean isClosingBracket(char c) { + return CLOSING_BRACES.contains(c); } - private boolean isOpenBracket(char bracket) { - return openBrackets.contains(bracket); + private boolean areOpposites(char left, char right) { + return switch(left) { + case '(' -> right == ')'; + case '[' -> right == ']'; + case '{' -> right == '}'; + default -> false; + }; } } diff --git a/src/IsPerfectSquare.java b/src/ValidPerfectSquare.java similarity index 91% rename from src/IsPerfectSquare.java rename to src/ValidPerfectSquare.java index 2ce8973..ef42b4d 100644 --- a/src/IsPerfectSquare.java +++ b/src/ValidPerfectSquare.java @@ -1,4 +1,4 @@ -public class IsPerfectSquare { +public class ValidPerfectSquare { public static boolean isPerfectSquare(long number) { long left = 0, right = number, mid; while (left <= right) { diff --git a/src/ValidSudoku.java b/src/ValidSudoku.java new file mode 100644 index 0000000..977b5de --- /dev/null +++ b/src/ValidSudoku.java @@ -0,0 +1,72 @@ +// https://leetcode.com/problems/valid-sudoku +// T: O(1) +// S: O(1) + +import java.util.HashSet; +import java.util.Set; + +public class ValidSudoku { + private static final int SUDOKU_SIZE = 9; + + public boolean isValidSudoku(char[][] board) { + if (repetitionInRows(board)) return false; + if (repetitionInColumns(board)) return false; + return !repetitionInBlocks(board); + } + + private boolean repetitionInRows(char[][] board) { + for (char[] row : board) { + if (repetitionInRow(row)) return true; + } + return false; + } + + private boolean repetitionInRow(char[] row) { + final Set digits = new HashSet<>(); + for (char character : row) { + if (Character.isDigit(character)) { + if (digits.contains(character)) return true; + digits.add(character); + } + } + return false; + } + + private boolean repetitionInColumns(char[][] board) { + final Set digits = new HashSet<>(); + for (int column = 0 ; column < SUDOKU_SIZE ; column++) { + digits.clear(); + for (int row = 0 ; row < SUDOKU_SIZE ; row++) { + char c = board[row][column]; + if (Character.isDigit(c)) { + if (digits.contains(c)) return true; + digits.add(c); + } + } + } + return false; + } + + private boolean repetitionInBlocks(char[][] board) { + for (int i = 0 ; i < SUDOKU_SIZE / 3 ; i++) { + for (int j = 0 ; j < SUDOKU_SIZE / 3 ; j++) { + if (repetitionInBlock(board, i, j)) return true; + } + } + return false; + } + + private boolean repetitionInBlock(final char[][] board, final int i, final int j) { + final Set digits = new HashSet<>(); + for (int row = 3 * i ; row < 3 * i + 3 ; row++) { + for (int column = 3 * j ; column < 3 * j + 3 ; column++) { + char c = board[row][column]; + if (Character.isDigit(c)) { + if (digits.contains(c)) return true; + digits.add(c); + } + } + } + return false; + } +} diff --git a/src/ValidWord.java b/src/ValidWord.java new file mode 100644 index 0000000..3bb2733 --- /dev/null +++ b/src/ValidWord.java @@ -0,0 +1,40 @@ +// https://leetcode.com/problems/valid-word +// T: O(N) +// S: O(1) + +import java.util.Set; + +public class ValidWord { + private static final Set VOWELS = Set.of('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'); + + public boolean isValid(String word) { + return word.length() >= 3 && isAlphaNum(word) && hasOneVowel(word) && hasOneConsonant(word); + } + + private static boolean isAlphaNum(String s) { + for (int i = 0 ; i < s.length() ; i++) { + if (!Character.isAlphabetic(s.charAt(i)) && !Character.isDigit(s.charAt(i))) { + return false; + } + } + return true; + } + + private static boolean hasOneVowel(String s) { + for (int i = 0 ; i < s.length() ; i++) { + if (VOWELS.contains(s.charAt(i))) { + return true; + } + } + return false; + } + + private static boolean hasOneConsonant(String s) { + for (int i = 0 ; i < s.length() ; i++) { + if (Character.isAlphabetic(s.charAt(i)) && !VOWELS.contains(s.charAt(i))) { + return true; + } + } + return false; + } +} diff --git a/src/ValidWordAbbreviation.java b/src/ValidWordAbbreviation.java new file mode 100644 index 0000000..a2b826a --- /dev/null +++ b/src/ValidWordAbbreviation.java @@ -0,0 +1,35 @@ +// https://leetcode.com/problems/valid-word-abbreviation +// T: O(|word|) +// S: O(1) + +public class ValidWordAbbreviation { + public boolean validWordAbbreviation(String word, String abbr) { + if(abbr.length() > word.length()) { + return false; + } + + int i = 0, j = 0; + while(i < word.length() && j < abbr.length()) { + final char wc = word.charAt(i), ac = abbr.charAt(j); + // if both characters are different, return false + if(Character.isLetter(ac) && wc != ac) return false; + else{ + // encountering a digit + if(Character.isDigit(ac)){ + int a = ac - '0'; + if(a == 0) return false; + // while we get digits, we create bigger number + while(j + 1 < abbr.length() && Character.isDigit(abbr.charAt(j + 1))){ + a = a * 10 + abbr.charAt(j + 1) - '0'; + j++; + } + // jump i end of digits position + i += a - 1; + } + } + j++; + i++; + } + return i == word.length() && j == abbr.length(); + } +} diff --git a/src/ValidateBinarySearchTree.java b/src/ValidateBinarySearchTree.java new file mode 100644 index 0000000..8aa408a --- /dev/null +++ b/src/ValidateBinarySearchTree.java @@ -0,0 +1,17 @@ +// https://leetcode.com/problems/validate-binary-search-tree +// T: O(n) +// S: O(log(n)) + +public class ValidateBinarySearchTree { + public boolean isValidBST(TreeNode root) { + return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE); + } + + private boolean isValidBST(TreeNode root, long minLeftVal, long maxRightVal) { + if (root == null) return true; + return minLeftVal < root.val + && root.val < maxRightVal + && isValidBST(root.left, minLeftVal, root.val) + && isValidBST(root.right, root.val, maxRightVal); + } +} diff --git a/src/VerifyAnAlienDictionary.java b/src/VerifyAnAlienDictionary.java new file mode 100644 index 0000000..4690407 --- /dev/null +++ b/src/VerifyAnAlienDictionary.java @@ -0,0 +1,33 @@ +import java.util.Comparator; + +public class VerifyAnAlienDictionary { + public boolean isAlienSorted(String[] words, String order) { + AlienLanguageComparator alienLanguageComparator = new AlienLanguageComparator(order); + for (int i = 1 ; i < words.length ; i++) { + if (alienLanguageComparator.compare(words[i - 1], words[i]) > 0) { + return false; + } + } + return true; + } + + private static class AlienLanguageComparator implements Comparator { + final int[] characterOrder = new int[26]; + + AlienLanguageComparator(String order) { + for (int index = 0 ; index < 26 ; index++) { + characterOrder[order.charAt(index) - 'a'] = index; + } + } + + @Override + public int compare(String s1, String s2) { + if (s1.length() == s2.length() && s1.equals(s2)) return 0; + for (int i = 0, j = 0 ; i < s1.length() && j < s2.length() ; i++, j++) { + if (characterOrder[s1.charAt(i) - 'a'] < characterOrder[s2.charAt(j) - 'a']) return -1; + else if (characterOrder[s1.charAt(i) - 'a'] > characterOrder[s2.charAt(j) - 'a']) return 1; + } + return s1.length() - s2.length(); + } + } +} diff --git a/src/WaterBottles.java b/src/WaterBottles.java new file mode 100644 index 0000000..1534cd5 --- /dev/null +++ b/src/WaterBottles.java @@ -0,0 +1,10 @@ +public class WaterBottles { + public int numWaterBottles(int numBottles, int numExchange) { + int drink = numBottles; + while (numBottles >= numExchange) { + drink += numBottles / numExchange; + numBottles = numBottles % numExchange + numBottles / numExchange; + } + return drink; + } +} diff --git a/src/WidestVerticalAreaBetweenTwoPointsContainingNoPoints.java b/src/WidestVerticalAreaBetweenTwoPointsContainingNoPoints.java new file mode 100644 index 0000000..c536711 --- /dev/null +++ b/src/WidestVerticalAreaBetweenTwoPointsContainingNoPoints.java @@ -0,0 +1,17 @@ +// https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points +// T: O(N log(N)) +// S: O(log(N)) + +import java.util.Arrays; +import java.util.Comparator; + +public class WidestVerticalAreaBetweenTwoPointsContainingNoPoints { + public int maxWidthOfVerticalArea(int[][] points) { + Arrays.sort(points, Comparator.comparingInt(a -> a[0])); + int maxVerticalArea = 0; + for (int i = 0 ; i < points.length - 1; i++) { + maxVerticalArea = Math.max(maxVerticalArea, points[i + 1][0] - points[i][0]); + } + return maxVerticalArea; + } +} diff --git a/src/WordBreak.java b/src/WordBreak.java new file mode 100644 index 0000000..a48b315 --- /dev/null +++ b/src/WordBreak.java @@ -0,0 +1,26 @@ +// https://leetcode.com/problems/word-break +// T: O(s^3 + w) +// S: O(s + w) + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class WordBreak { + public boolean wordBreak(String s, List wordDict) { + final Set words = new HashSet<>(wordDict); + final boolean[] dp = new boolean[s.length() + 1]; + dp[0] = true; + + for (int i = 1 ; i <= s.length() ; i++) { + for (int j = 0 ; j < i ; j++) { + if (dp[j] && words.contains(s.substring(j, i))) { + dp[i] = true; + break; + } + } + } + + return dp[dp.length - 1]; + } +} diff --git a/src/WordLadder.java b/src/WordLadder.java new file mode 100644 index 0000000..11eedde --- /dev/null +++ b/src/WordLadder.java @@ -0,0 +1,58 @@ +// https://leetcode.com/problems/word-ladder +// T: O(nB + n^m * nm) +// S: O(nB + n^m) + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; +import java.util.Set; + +public class WordLadder { + private record Info(String string, int steps) {} + + // n = possible chars, m = |s| + // V = n^m + // BFS, T: O(V + E) = O(nB + n^m * nm), S: O(n^m) + public int ladderLength(String beginWord, String endWord, List wordList) { + final Set words = new HashSet<>(wordList); + if (!words.contains(endWord)) { + return 0; + } + + final Queue queue = new LinkedList<>() {{ add(new Info(beginWord, 0)); }}; + final Set visited = new HashSet<>(); + + while (!queue.isEmpty()) { + final Info info = queue.poll(); + if (visited.contains(info.string)) { + continue; + } + visited.add(info.string); + if (endWord.equals(info.string)) { + return info.steps + 1; + } + + for (String neighbour : validMutations(words, info.string)) { + queue.add(new Info(neighbour, info.steps + 1)); + } + } + + return -1; + } + + // T: O(n * m), S: O(n * m) + private static List validMutations(Set words, String string) { + final List list = new ArrayList<>(); + for (int i = 0 ; i < string.length() ; i++) { + for (char c = 'a' ; c <= 'z' ; c++) { + final String word = string.substring(0, i) + c + string.substring(i + 1); + if (words.contains(word)) { + list.add(word); + } + } + } + return list; + } +} diff --git a/src/WordSearch.java b/src/WordSearch.java new file mode 100644 index 0000000..8833249 --- /dev/null +++ b/src/WordSearch.java @@ -0,0 +1,35 @@ +// https://leetcode.com/problems/word-search +// T: O(4^{m * n}) +// S: O(m * n) + +public class WordSearch { + + public boolean exist(char[][] board, String word) { + final int rows = board.length, columns = board[0].length; + + for (int row = 0; row < rows ; row++) { + for (int column = 0; column < columns ; column++) { + if (exist(board, row, column, word, 0)) { + return true; + } + } + } + + return false; + } + + private boolean exist(char[][] board, int row, int column, String word, int i) { + if (i == word.length()) return true; + if (row < 0 || column < 0 || row == board.length || column == board[row].length) return false; + if (board[row][column] != word.charAt(i)) return false; + + board[row][column] ^= 256; + boolean exist = exist(board, row, column+1, word, i + 1) + || exist(board, row, column - 1, word, i + 1) + || exist(board, row + 1, column, word, i + 1) + || exist(board, row - 1, column, word, i + 1); + + board[row][column] ^= 256; + return exist; + } +} diff --git a/src/XOROperationInAnArray.java b/src/XOROperationInAnArray.java new file mode 100644 index 0000000..a7ab98a --- /dev/null +++ b/src/XOROperationInAnArray.java @@ -0,0 +1,9 @@ +public class XOROperationInAnArray { + public int xorOperation(int n, int start) { + int result = 0; + for (int i = 0 ; i < n ; i++) { + result ^= start + 2 * i; + } + return result; + } +} diff --git a/src/XOfAKindInADeckOfCards.java b/src/XOfAKindInADeckOfCards.java new file mode 100644 index 0000000..cf7c23b --- /dev/null +++ b/src/XOfAKindInADeckOfCards.java @@ -0,0 +1,37 @@ +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class XOfAKindInADeckOfCards { + public boolean hasGroupsSizeX(int[] deck) { + if (deck.length == 1) return false; + Map cards = getFrequencies(deck); + Set frequencies = new HashSet<>(cards.values()); + if (frequencies.size() == 1 && cards.get(deck[0]) >= 2) return true; + return gcd(frequencies) > 1; + } + + private int gcd(Collection collection) { + int gcd = 0; + boolean firstTime = true; + for (int value : collection) { + gcd = firstTime ? value : gcd(gcd, value); + firstTime = false; + } + return gcd; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } + + private Map getFrequencies(int[] array) { + Map result = new HashMap<>(); + for (int val : array) { + result.put(val, result.getOrDefault(val, 0) + 1); + } + return result; + } +} diff --git a/src/ZigZagConversion.java b/src/ZigZagConversion.java new file mode 100644 index 0000000..e70cd2b --- /dev/null +++ b/src/ZigZagConversion.java @@ -0,0 +1,31 @@ +// https://leetcode.com/problems/zigzag-conversion +// T: O(|s|) +// S: O(|s|) + +public class ZigZagConversion { + public static String convert(String s, int numRows) { + if (numRows == 1) return s; + final StringBuilder result = new StringBuilder(); + final int jumpSize = (numRows - 1) * 2; + + // first row + for (int i = 0 ; i < s.length() ; i += jumpSize) { + result.append(s.charAt(i)); + } + + for (int row = 1 ; row < numRows - 1 ; row++) { + int[] jumps = {jumpSize - 2 * row, 2 * row}; + for (int i = row, k = 0 ; i < s.length() ; k ^= 1) { + result.append(s.charAt(i)); + i += jumps[k]; + } + } + + // last row + for (int i = numRows - 1 ; i < s.length() ; i += jumpSize) { + result.append(s.charAt(i)); + } + + return result.toString(); + } +}