├── .ruby-version ├── .gitignore ├── .github └── pull_request_template.md ├── shell ├── 0195-tenth-line.sh ├── 0193-valid-phone-numbers.sh ├── 0192-word-frequency.sh └── 0194-transpose-file.sh ├── database ├── 0182-duplicate-emails.sql ├── 0584-find-customer-referee.sql ├── 0175-combine-two-tables.sql ├── 0183-customers-who-never-order.sql ├── 0197-rising-temperature.sql ├── 0181-employees-earning-more-than-their-managers.sql ├── 0196-delete-duplicate-emails.sql └── 1683-invalid-tweets.sql └── algorithms ├── ruby ├── 3133-minimum-array-end.rb ├── 2413-smallest-even-multiple.rb ├── 0104-maximum-depth-of-binary-tree.rb ├── 0070-climbing-stairs.rb ├── 0226-invert-binary-tree.rb ├── 0509-fibonacci-number.rb ├── 0344-reverse-string.rb ├── 0009-palindrome-number.rb ├── 0557-reverse-words-in-a-string-iii.rb ├── 1523-count-odd-numbers-in-an-interval-range.rb ├── 0058-length-of-last-word.rb ├── 0069-sqrtx.rb ├── 0121-best-time-to-buy-and-sell-stock.rb ├── 0990-satisfiability-of-equality-equations.rb ├── 0004-median-of-two-sorted-arrays.rb ├── 0091-decode-ways.rb ├── 2187-minimum-time-to-complete-trips.rb ├── 0045-jump-game-ii.rb ├── 0387-first-unique-character-in-a-string.rb ├── 0001-two-sum.rb ├── 1470-shuffle-the-array.rb ├── 0002-add-two-numbers.rb ├── 0148-sort-list.rb ├── 0072-edit-distance.rb ├── 0953-verifying-an-alien-dictionary.rb ├── 1680-concatenation-of-consecutive-binary-numbers.rb ├── 0021-merge-two-sorted-lists.rb ├── 0028-find-the-index-of-the-first-occurrence-in-a-string.rb ├── 0382-linked-list-random-node.rb ├── 0035-search-insert-position.rb ├── 0014-longest-common-prefix.rb ├── 0416-partition-equal-subset-sum.rb ├── 0283-move-zeroes.rb ├── 0113-path-sum-ii.rb ├── 0783-minimum-distance-between-bst-nodes.rb ├── 0258-add-digits.rb ├── 0003-longest-substring-without-repeating-characters.rb ├── 0020-valid-parentheses.rb ├── 0652-find-duplicate-subtrees.rb ├── 0013-roman-to-integer.rb ├── 1071-greatest-common-divisor-of-strings.rb ├── 0343-integer-break.rb ├── 0234-palindrome-linked-list.rb ├── 0904-fruit-into-baskets.rb ├── 0206-reverse-linked-list.rb ├── 0502-ipo.rb ├── 0567-permutation-in-string.rb ├── 0006-zigzag-conversion.rb ├── 0152-maximum-product-subarray.rb ├── 0189-rotate-array.rb ├── 0010-regular-expression-matching.rb ├── 0101-symmetric-tree.rb ├── 2595-number-of-even-and-odd-bits.rb ├── 0172-factorial-trailing-zeroes.rb ├── 0345-reverse-vowels-of-a-string.rb ├── 0342-power-of-four.rb ├── 0443-string-compression.rb ├── 0958-check-completeness-of-a-binary-tree.rb ├── 1137-n-th-tribonacci-number.rb ├── 2477-minimum-fuel-cost-to-report-to-the-capital.rb ├── 0338-counting-bits.rb ├── 0103-binary-tree-zigzag-level-order-traversal.rb ├── 0905-sort-array-by-parity.rb ├── 1675-minimize-deviation-in-array.rb ├── 0347-top-k-frequent-elements.rb ├── 0989-add-to-array-form-of-integer.rb ├── 0389-find-the-difference.rb ├── 0100-same-tree.rb ├── 1155-number-of-dice-rolls-with-target-sum.rb ├── 0054-spiral-matrix.rb ├── 2348-number-of-zero-filled-subarrays.rb ├── 1162-as-far-from-land-as-possible.rb ├── 0867-transpose-matrix.rb ├── 0136-single-number.rb ├── 0796-rotate-string.rb ├── 0024-swap-nodes-in-pairs.rb ├── 1351-count-negative-numbers-in-a-sorted-matrix.rb ├── 0022-generate-parentheses.rb ├── 0048-rotate-image.rb ├── 0230-kth-smallest-element-in-a-bst.rb ├── 0119-pascals-triangle-ii.rb ├── 0201-bitwise-and-of-numbers-range.rb ├── 2409-count-days-spent-together.rb ├── 0912-sort-an-array.rb ├── 0111-minimum-depth-of-binary-tree.rb ├── 0118-pascals-triangle.rb ├── 0023-merge-k-sorted-lists.rb ├── 0073-set-matrix-zeroes.rb ├── 0046-permutations.rb ├── 0050-powx-n.rb ├── 0876-middle-of-the-linked-list.rb ├── 1207-unique-number-of-occurrences.rb ├── 0094-binary-tree-inorder-traversal.rb ├── 0110-balanced-binary-tree.rb ├── 0129-sum-root-to-leaf-numbers.rb ├── 2444-count-subarrays-with-fixed-bounds.rb ├── 0459-repeated-substring-pattern.rb ├── 0137-single-number-ii.rb ├── 0019-remove-nth-node-from-end-of-list.rb ├── 0242-valid-anagram.rb ├── 0539-minimum-time-difference.rb ├── 0168-excel-sheet-column-title.rb ├── 0108-convert-sorted-array-to-binary-search-tree.rb ├── 0700-search-in-a-binary-search-tree.rb ├── 0409-longest-palindrome.rb ├── 0128-longest-consecutive-sequence.rb ├── 0149-max-points-on-a-line.rb ├── 0142-linked-list-cycle-ii.rb ├── 0109-convert-sorted-list-to-binary-search-tree.rb ├── 0670-maximum-swap.rb ├── 0322-coin-change.rb ├── 0066-plus-one.rb ├── 0383-ransom-note.rb ├── 1287-element-appearing-more-than-25-in-sorted-array.rb ├── 0199-binary-tree-right-side-view.rb ├── 1721-swapping-nodes-in-a-linked-list.rb ├── 0169-majority-element.rb ├── 0427-construct-quad-tree.rb ├── 0704-binary-search.rb ├── 0049-group-anagrams.rb ├── 0053-maximum-subarray.rb ├── 1480-running-sum-of-1d-array.rb ├── 0589-n-ary-tree-preorder-traversal.rb ├── 0077-combinations.rb ├── 0219-contains-duplicate-ii.rb ├── 2433-find-the-original-array-of-prefix-xor.rb ├── 0102-binary-tree-level-order-traversal.rb ├── 0515-find-largest-value-in-each-tree-row.rb ├── 0530-minimum-absolute-difference-in-bst.rb ├── 0064-minimum-path-sum.rb ├── 1424-diagonal-traverse-ii.rb ├── 0215-kth-largest-element-in-an-array.rb ├── 0055-jump-game.rb ├── 0319-bulb-switcher.rb ├── 0274-h-index.rb ├── 0278-first-bad-version.rb ├── 0896-monotonic-array.rb ├── 0082-remove-duplicates-from-sorted-list-ii.rb ├── 0202-happy-number.rb ├── 0092-reverse-linked-list-ii.rb ├── 0637-average-of-levels-in-binary-tree.rb ├── 1456-maximum-number-of-vowels-in-a-substring-of-given-length.rb ├── 1732-find-the-highest-altitude.rb ├── 0095-unique-binary-search-trees-ii.rb ├── 0238-product-of-array-except-self.rb ├── 0779-k-th-symbol-in-grammar.rb ├── 0287-find-the-duplicate-number.rb ├── 1232-check-if-it-is-a-straight-line.rb ├── 0377-combination-sum-iv.rb ├── 0875-koko-eating-bananas.rb ├── 1359-count-all-valid-pickup-and-delivery-options.rb ├── 1822-sign-of-the-product-of-an-array.rb ├── 0300-longest-increasing-subsequence.rb ├── 1464-maximum-product-of-two-elements-in-an-array.rb ├── 0643-maximum-average-subarray-i.rb ├── 0790-domino-and-tromino-tiling.rb ├── 0017-letter-combinations-of-a-phone-number.rb ├── 0056-merge-intervals.rb ├── 0098-validate-binary-search-tree.rb └── 0392-is-subsequence.rb └── python3 ├── 0104-maximum-depth-of-binary-tree.py ├── 0299-bulls-and-cows.py ├── 0783-minimum-distance-between-bst-nodes.py ├── 0067-add-binary.py ├── 0502-ipo.py ├── 2187-minimum-time-to-complete-trips.py ├── 0808-soup-servings.py ├── 0443-string-compression.py ├── 2462-total-cost-to-hire-k-workers.py └── 1444-number-of-ways-of-cutting-a-pizza.py /.ruby-version: -------------------------------------------------------------------------------- 1 | 3.3.4 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | ### Solutions 2 | - [ ] Ruby 3 | - [ ] Python3 -------------------------------------------------------------------------------- /shell/0195-tenth-line.sh: -------------------------------------------------------------------------------- 1 | # 195. Tenth Line 2 | # https://leetcode.com/problems/tenth-line/ 3 | 4 | # Read from the file file.txt and output the tenth line to stdout. 5 | awk 'NR==10{print $0}' file.txt 6 | -------------------------------------------------------------------------------- /shell/0193-valid-phone-numbers.sh: -------------------------------------------------------------------------------- 1 | # 193. Valid Phone Numbers 2 | # https://leetcode.com/problems/valid-phone-numbers 3 | 4 | # Read from the file file.txt and output all valid phone numbers to stdout. 5 | grep -P '^(\d{3}-|\(\d{3}\) )\d{3}-\d{4}$' file.txt 6 | -------------------------------------------------------------------------------- /database/0182-duplicate-emails.sql: -------------------------------------------------------------------------------- 1 | -- 182. Duplicate Emails 2 | -- https://leetcode.com/problems/duplicate-emails 3 | 4 | -- Write your MySQL query statement below 5 | SELECT 6 | email 7 | FROM 8 | Person 9 | group by 10 | email 11 | having count(email) > 1 12 | ; 13 | -------------------------------------------------------------------------------- /database/0584-find-customer-referee.sql: -------------------------------------------------------------------------------- 1 | -- 584. Find Customer Referee 2 | -- https://leetcode.com/problems/find-customer-referee 3 | 4 | -- Write your MySQL query statement below 5 | SELECT 6 | name 7 | FROM 8 | Customer 9 | WHERE 10 | referee_id is NULL OR referee_id <> 2 11 | ; 12 | -------------------------------------------------------------------------------- /shell/0192-word-frequency.sh: -------------------------------------------------------------------------------- 1 | # 192. Word Frequency 2 | # https://leetcode.com/problems/word-frequency 3 | 4 | # Read from the file words.txt and output the word frequency list to stdout. 5 | cat words.txt | tr [:space:] "\n" | sed '/^$/d' | tr '[:upper:]' '[:lower:]'|sort|uniq -c|sort -nr | awk '{ print $2,$1}' 6 | -------------------------------------------------------------------------------- /database/0175-combine-two-tables.sql: -------------------------------------------------------------------------------- 1 | -- 175. Combine Two Tables 2 | -- https://leetcode.com/problems/combine-two-tables 3 | 4 | -- Write your MySQL query statement below 5 | SELECT 6 | firstName, 7 | lastName, 8 | city, 9 | state 10 | FROM 11 | Person 12 | LEFT JOIN Address on Person.personId = Address.personId 13 | ; 14 | -------------------------------------------------------------------------------- /database/0183-customers-who-never-order.sql: -------------------------------------------------------------------------------- 1 | -- 183. Customers Who Never Order 2 | -- https://leetcode.com/problems/customers-who-never-order 3 | 4 | -- Write your MySQL query statement below 5 | SELECT 6 | name as 'Customers' 7 | FROM 8 | customers 9 | WHERE 10 | id NOT IN 11 | ( 12 | SELECT customerid FROM Orders 13 | ) 14 | ; 15 | -------------------------------------------------------------------------------- /database/0197-rising-temperature.sql: -------------------------------------------------------------------------------- 1 | -- 197. Rising Temperature 2 | -- https://leetcode.com/problems/rising-temperature 3 | 4 | -- Write your MySQL query statement below 5 | SELECT 6 | weather.id AS 'Id' 7 | FROM 8 | weather 9 | JOIN 10 | weather w ON DATEDIFF(weather.recordDate, w.recordDate) = 1 11 | AND weather.temperature > w.temperature 12 | ; 13 | -------------------------------------------------------------------------------- /database/0181-employees-earning-more-than-their-managers.sql: -------------------------------------------------------------------------------- 1 | -- 181. Employees Earning More Than Their Managers 2 | -- https://leetcode.com/problems/employees-earning-more-than-their-managers 3 | 4 | -- Write your MySQL query statement below 5 | SELECT 6 | a.name AS Employee 7 | FROM 8 | Employee AS a 9 | JOIN Employee AS b ON a.managerId = b.id AND a.salary > b.salary 10 | ; 11 | -------------------------------------------------------------------------------- /database/0196-delete-duplicate-emails.sql: -------------------------------------------------------------------------------- 1 | -- 196. Delete Duplicate Emails 2 | -- https://leetcode.com/problems/delete-duplicate-emails 3 | 4 | -- Please write a DELETE statement and DO NOT write a SELECT statement. 5 | -- Write your MySQL query statement below 6 | DELETE 7 | p1 8 | FROM 9 | Person p1, Person p2 10 | WHERE 11 | p1.email = p2.email and p1.id > p2.id 12 | ; 13 | -------------------------------------------------------------------------------- /shell/0194-transpose-file.sh: -------------------------------------------------------------------------------- 1 | # 194. Transpose File 2 | # https://leetcode.com/problems/transpose-file 3 | 4 | # Read from the file file.txt and print its transposed content to stdout. 5 | awk ' 6 | { 7 | for (i = 1; i <= NF; i++) { 8 | if (NR == 1){ 9 | s[i] = $i; 10 | } else{ 11 | s[i] = s[i] " " $i; 12 | } 13 | } 14 | } 15 | END { 16 | for (i = 1; s[i] != ""; i++) { 17 | print s[i]; 18 | } 19 | }' file.txt 20 | -------------------------------------------------------------------------------- /algorithms/ruby/3133-minimum-array-end.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 3133. Minimum Array End 4 | # Medium 5 | # https://leetcode.com/problems/minimum-array-end 6 | 7 | def min_end(n, x) 8 | result = x 9 | remaining = n - 1 10 | position = 1 11 | 12 | while remaining != 0 13 | if (x & position) == 0 14 | result |= (remaining & 1) * position 15 | remaining >>= 1 16 | end 17 | position <<= 1 18 | end 19 | 20 | result.to_i 21 | end 22 | -------------------------------------------------------------------------------- /algorithms/python3/0104-maximum-depth-of-binary-tree.py: -------------------------------------------------------------------------------- 1 | # 104. Maximum Depth of Binary Tree 2 | # https://leetcode.com/problems/maximum-depth-of-binary-tree 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, val=0, left=None, right=None): 7 | # self.val = val 8 | # self.left = left 9 | # self.right = right 10 | class Solution: 11 | def maxDepth(self, root: Optional[TreeNode]) -> int: 12 | return 1 + max(map(self.maxDepth, (root.left, root.right))) if root else 0 -------------------------------------------------------------------------------- /algorithms/ruby/2413-smallest-even-multiple.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 2413. Smallest Even Multiple 4 | # https://leetcode.com/problems/smallest-even-multiple 5 | 6 | # @param {Integer} n 7 | # @return {Integer} 8 | def smallest_even_multiple(n) 9 | n.even? ? n : 2 * n 10 | end 11 | 12 | # ********************# 13 | # TEST # 14 | # ********************# 15 | 16 | require "test/unit" 17 | class Test_smallest_even_multiple < Test::Unit::TestCase 18 | def test_ 19 | assert_equal 10, smallest_even_multiple(5) 20 | assert_equal 6, smallest_even_multiple(6) 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /algorithms/ruby/0104-maximum-depth-of-binary-tree.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 104. Maximum Depth of Binary Tree 4 | # https://leetcode.com/problems/maximum-depth-of-binary-tree 5 | 6 | # Definition for a binary tree node. 7 | # class TreeNode 8 | # attr_accessor :val, :left, :right 9 | # def initialize(val = 0, left = nil, right = nil) 10 | # @val = val 11 | # @left = left 12 | # @right = right 13 | # end 14 | # end 15 | # @param {TreeNode} root 16 | # @return {Integer} 17 | def max_depth(root) 18 | root ? 1 + [max_depth(root.left), max_depth(root.right)].max : 0 19 | end 20 | -------------------------------------------------------------------------------- /algorithms/ruby/0070-climbing-stairs.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 70. Climbing Stairs 4 | # https://leetcode.com/problems/climbing-stairs 5 | 6 | # @param {Integer} n 7 | # @return {Integer} 8 | def climb_stairs(n) 9 | fib = { 0 => 0, 1 => 1, 2 => 2 } 10 | fib.default_proc = ->(f, n) { f[n] = f[n - 1] + f[n - 2] } 11 | fib[n] 12 | end 13 | 14 | # ********************# 15 | # TEST # 16 | # ********************# 17 | 18 | require "test/unit" 19 | class Test_climb_stairs < Test::Unit::TestCase 20 | def test_ 21 | assert_equal 2, climb_stairs(2) 22 | assert_equal 3, climb_stairs(3) 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /algorithms/ruby/0226-invert-binary-tree.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 226. Invert Binary Tree 4 | # https://leetcode.com/problems/invert-binary-tree 5 | 6 | # Definition for a binary tree node. 7 | # class TreeNode 8 | # attr_accessor :val, :left, :right 9 | # def initialize(val = 0, left = nil, right = nil) 10 | # @val = val 11 | # @left = left 12 | # @right = right 13 | # end 14 | # end 15 | # @param {TreeNode} root 16 | # @return {TreeNode} 17 | def invert_tree(root) 18 | return if root.nil? 19 | root.left, root.right = invert_tree(root.right), invert_tree(root.left) 20 | root 21 | end 22 | -------------------------------------------------------------------------------- /algorithms/ruby/0509-fibonacci-number.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 509. Fibonacci Number 4 | # https://leetcode.com/problems/fibonacci-number 5 | 6 | # @param {Integer} n 7 | # @return {Integer} 8 | def fib(n) 9 | case n 10 | when 0 11 | return 0 12 | when 1 13 | return 1 14 | end 15 | 16 | fib(n - 1) + fib(n - 2) 17 | end 18 | 19 | # ********************# 20 | # TEST # 21 | # ********************# 22 | 23 | require "test/unit" 24 | class Test_fib < Test::Unit::TestCase 25 | def test_ 26 | assert_equal 1, fib(2) 27 | assert_equal 2, fib(3) 28 | assert_equal 3, fib(4) 29 | end 30 | end 31 | -------------------------------------------------------------------------------- /algorithms/ruby/0344-reverse-string.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 344. Reverse String 4 | # https://leetcode.com/problems/reverse-string 5 | 6 | # @param {Character[]} s 7 | # @return {Void} Do not return anything, modify s in-place instead. 8 | def reverse_string(s) 9 | s.reverse! 10 | end 11 | 12 | # ********************# 13 | # TEST # 14 | # ********************# 15 | 16 | require "test/unit" 17 | class Test_reverse_string < Test::Unit::TestCase 18 | def test_ 19 | assert_equal %w[o l l e h], reverse_string(%w[h e l l o]) 20 | assert_equal %w[h a n n a H], reverse_string(%w[H a n n a h]) 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /algorithms/ruby/0009-palindrome-number.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 9. Palindrome Number 4 | # https://leetcode.com/problems/palindrome-number 5 | 6 | # @param {Integer} x 7 | # @return {Boolean} 8 | def is_palindrome(x) 9 | return false if x.negative? 10 | 11 | x.digits.join.to_i == x 12 | end 13 | 14 | # ********************# 15 | # TEST # 16 | # ********************# 17 | 18 | require "test/unit" 19 | class Test_is_palindrome < Test::Unit::TestCase 20 | def test_ 21 | assert_equal true, is_palindrome(121) 22 | assert_equal false, is_palindrome(-121) 23 | assert_equal false, is_palindrome(10) 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /algorithms/ruby/0557-reverse-words-in-a-string-iii.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 557. Reverse Words in a String III 4 | # https://leetcode.com/problems/reverse-words-in-a-string-iii 5 | 6 | # @param {String} s 7 | # @return {String} 8 | def reverse_words(s) 9 | s.split.map(&:reverse).join(" ") 10 | end 11 | 12 | # ********************# 13 | # TEST # 14 | # ********************# 15 | 16 | require "test/unit" 17 | class Test_reverse_words < Test::Unit::TestCase 18 | def test_ 19 | assert_equal "s'teL ekat edoCteeL tsetnoc", reverse_words("Let's take LeetCode contest") 20 | assert_equal "doG gniD", reverse_words("God Ding") 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /algorithms/ruby/1523-count-odd-numbers-in-an-interval-range.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 1523. Count Odd Numbers in an Interval Range 4 | # https://leetcode.com/problems/count-odd-numbers-in-an-interval-range 5 | 6 | # @param {Integer} low 7 | # @param {Integer} high 8 | # @return {Integer} 9 | def count_odds(low, high) 10 | low += 1 if low % 2 == 0 11 | 12 | low > high ? 0 : ((high - low) / 2) + 1 13 | end 14 | 15 | # ********************# 16 | # TEST # 17 | # ********************# 18 | 19 | require "test/unit" 20 | class Test_count_odds < Test::Unit::TestCase 21 | def test_ 22 | assert_equal 3, count_odds(3, 7) 23 | assert_equal 1, count_odds(8, 10) 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /algorithms/ruby/0058-length-of-last-word.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 58. Length of Last Word 4 | # https://leetcode.com/problems/length-of-last-word 5 | 6 | # @param {String} s 7 | # @return {Integer} 8 | def length_of_last_word(s) 9 | words = s.strip.split(" ") 10 | words.last.length 11 | end 12 | 13 | # ********************# 14 | # TEST # 15 | # ********************# 16 | 17 | require "test/unit" 18 | class Test_length_of_last_word < Test::Unit::TestCase 19 | def test_ 20 | assert_equal 5, length_of_last_word("Hello World") 21 | assert_equal 4, length_of_last_word(" fly me to the moon ") 22 | assert_equal 6, length_of_last_word("luffy is still joyboy") 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /algorithms/ruby/0069-sqrtx.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 69. Sqrt(x) 4 | # https://leetcode.com/problems/sqrtx 5 | 6 | # @param {Integer} x 7 | # @return {Integer} 8 | def my_sqrt(x) 9 | return 0 if x.zero? 10 | return 1 if x < 4 11 | 12 | prev = 2 13 | cur = x / 2 14 | while (prev - cur).abs > 1 15 | return cur if cur * cur == x 16 | 17 | prev = cur 18 | cur = (cur + x / cur) / 2 19 | end 20 | cur * cur > x ? (cur - 1) : cur 21 | end 22 | 23 | # ********************# 24 | # TEST # 25 | # ********************# 26 | 27 | require "test/unit" 28 | class Test_my_sqrt < Test::Unit::TestCase 29 | def test_ 30 | assert_equal 2, my_sqrt(4) 31 | assert_equal 2, my_sqrt(8) 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /algorithms/ruby/0121-best-time-to-buy-and-sell-stock.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 121. Best Time to Buy and Sell Stock 4 | # https://leetcode.com/problems/best-time-to-buy-and-sell-stock 5 | 6 | # @param {Integer[]} prices 7 | # @return {Integer} 8 | def max_profit(prices) 9 | min, max_prof = prices[0], 0 10 | prices.each.each do |p| 11 | min = [min, p].min 12 | max_prof = [max_prof, p - min].max 13 | end 14 | 15 | max_prof 16 | end 17 | 18 | # **************** # 19 | # TEST # 20 | # **************** # 21 | 22 | require "test/unit" 23 | class Test_max_profit < Test::Unit::TestCase 24 | def test_ 25 | assert_equal 5, max_profit([7, 1, 5, 3, 6, 4]) 26 | assert_equal 0, max_profit([7, 6, 4, 3, 1]) 27 | end 28 | end 29 | -------------------------------------------------------------------------------- /algorithms/ruby/0990-satisfiability-of-equality-equations.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 990. Satisfiability of Equality Equations 4 | # https://leetcode.com/problems/satisfiability-of-equality-equations 5 | 6 | # @param {String[]} equations 7 | # @return {Boolean} 8 | def equations_possible(equations) 9 | equations.join.tap { _1.tr! Regexp.last_match(1), Regexp.last_match(2) while _1 =~ /(.)==(?!\1)(.)/ } !~ /(.)!=\1/ 10 | end 11 | 12 | # ********************# 13 | # TEST # 14 | # ********************# 15 | 16 | require "test/unit" 17 | class Test_equations_possible < Test::Unit::TestCase 18 | def test_ 19 | assert_equal false, equations_possible(["a==b", "b!=a"]) 20 | assert_equal true, equations_possible(["b==a", "a==b"]) 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /algorithms/ruby/0004-median-of-two-sorted-arrays.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 4. Median of Two Sorted Arrays 4 | # https://leetcode.com/problems/median-of-two-sorted-arrays 5 | 6 | # @param {Integer[]} nums1 7 | # @param {Integer[]} nums2 8 | # @return {Float} 9 | def find_median_sorted_arrays(nums1, nums2) 10 | sorted = (nums1 + nums2).sort 11 | len = sorted.length 12 | (sorted[(len - 1) / 2] + sorted[len / 2]) / 2.0 13 | end 14 | 15 | # **************** # 16 | # TEST # 17 | # **************** # 18 | 19 | require "test/unit" 20 | class Test_find_median_sorted_arrays < Test::Unit::TestCase 21 | def test_ 22 | assert_equal 2.0, find_median_sorted_arrays([1, 3], [2]) 23 | assert_equal 2.5, find_median_sorted_arrays([1, 2], [3, 4]) 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /algorithms/ruby/0091-decode-ways.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 91. Decode Ways 4 | # https://leetcode.com/problems/decode-ways 5 | 6 | # @param {String} s 7 | # @return {Integer} 8 | def num_decodings(s) 9 | i1, i2 = 1, 1 10 | for i in 1..s.length do 11 | count = s[i - 1, 1] != "0" ? i1 : 0 12 | count += i2 if s[i - 2, 2].between?("10", "26") && i > 1 13 | i2 = i1 14 | i1 = count 15 | end 16 | count 17 | end 18 | 19 | # ********************# 20 | # TEST # 21 | # ********************# 22 | 23 | require "test/unit" 24 | class Test_num_decodings < Test::Unit::TestCase 25 | def test_ 26 | assert_equal 2, num_decodings("12") 27 | assert_equal 3, num_decodings("226") 28 | assert_equal 0, num_decodings("06") 29 | end 30 | end 31 | -------------------------------------------------------------------------------- /algorithms/ruby/2187-minimum-time-to-complete-trips.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 2187. Minimum Time to Complete Trips 4 | # https://leetcode.com/problems/minimum-time-to-complete-trips 5 | 6 | # @param {Integer[]} time 7 | # @param {Integer} total_trips 8 | # @return {Integer} 9 | def minimum_time(time, total_trips) 10 | (1..time.min * total_trips).bsearch do |x| 11 | time.sum { x / _1 } >= total_trips 12 | end 13 | end 14 | 15 | # **************** # 16 | # TEST # 17 | # **************** # 18 | 19 | require "test/unit" 20 | class Test_minimum_time < Test::Unit::TestCase 21 | def test_ 22 | assert_equal 3, minimum_time([1, 2, 3], 5) 23 | assert_equal 2, minimum_time([2], 1) 24 | assert_equal 4, minimum_time([1, 2, 3, 1], 10) 25 | end 26 | end 27 | -------------------------------------------------------------------------------- /algorithms/python3/0299-bulls-and-cows.py: -------------------------------------------------------------------------------- 1 | # 299. Bulls and Cows 2 | # https://leetcode.com/problems/bulls-and-cows 3 | 4 | import operator; 5 | 6 | class Solution: 7 | def getHint(self, secret: str, guess: str) -> str: 8 | bulls = sum(map(operator.eq, secret, guess)) 9 | both = sum(min(secret.count(x), guess.count(x)) for x in set(guess)) 10 | return '%dA%dB' % (bulls, both - bulls) 11 | 12 | # ********************# 13 | # TEST # 14 | # ********************# 15 | 16 | import unittest 17 | 18 | class TestStringMethods(unittest.TestCase): 19 | def test_addBinary(self): 20 | self.assertEqual(Solution.getHint(self, "1807", "7810"), "1A3B") 21 | self.assertEqual(Solution.getHint(self, "1123", "0111"), "1A1B") 22 | 23 | if __name__ == '__main__': 24 | unittest.main() -------------------------------------------------------------------------------- /algorithms/ruby/0045-jump-game-ii.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 45. Jump Game II 4 | # https://leetcode.com/problems/jump-game-ii 5 | 6 | # @param {Integer[]} nums 7 | # @return {Integer} 8 | def jump(nums) 9 | current_jump = 0 10 | last_jump = 0 11 | step = 0 12 | 13 | (nums.size - 1).times do |i| 14 | current_jump = [current_jump, i + nums[i]].max 15 | if i == last_jump 16 | step += 1 17 | last_jump = current_jump 18 | end 19 | end 20 | 21 | step 22 | end 23 | 24 | # ********************# 25 | # TEST # 26 | # ********************# 27 | 28 | require "test/unit" 29 | class Test_jump < Test::Unit::TestCase 30 | def test_ 31 | assert_equal 2, jump([2, 3, 1, 1, 4]) 32 | assert_equal 2, jump([2, 3, 0, 1, 4]) 33 | end 34 | end 35 | -------------------------------------------------------------------------------- /algorithms/ruby/0387-first-unique-character-in-a-string.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 387. First Unique Character in a String 4 | # https://leetcode.com/problems/first-unique-character-in-a-string 5 | 6 | # @param {String} s 7 | # @return {Integer} 8 | def first_uniq_char(s) 9 | a = s.chars 10 | hash = a.each_with_object(Hash.new(0)) do |e, h| 11 | h[e] += 1 12 | end 13 | hash.key(1) ? a.index(hash.key(1)) : -1 14 | end 15 | 16 | # ********************# 17 | # TEST # 18 | # ********************# 19 | 20 | require "test/unit" 21 | class Test_first_uniq_char < Test::Unit::TestCase 22 | def test_ 23 | assert_equal 0, first_uniq_char("leetcode") 24 | assert_equal 2, first_uniq_char("loveleetcode") 25 | assert_equal(-1, first_uniq_char("aabb")) 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /algorithms/ruby/0001-two-sum.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 1. Two Sum 4 | # https://leetcode.com/problems/two-sum 5 | 6 | # @param {Integer[]} nums 7 | # @param {Integer} target 8 | # @return {Integer[]} 9 | def two_sum(nums, target) 10 | h = {} 11 | (0..nums.size - 1).each do |i| 12 | complement = target - nums[i] 13 | 14 | return [i, h[complement]] if h.key?(complement) 15 | 16 | h[nums[i]] = i 17 | end 18 | end 19 | 20 | # **************** # 21 | # TEST # 22 | # **************** # 23 | 24 | require "test/unit" 25 | class Test_two_sum < Test::Unit::TestCase 26 | def test_ 27 | assert_equal [0, 1].sort, two_sum([2, 7, 11, 15], 9).sort 28 | assert_equal [1, 2].sort, two_sum([3, 2, 4], 6).sort 29 | assert_equal [0, 1].sort, two_sum([3, 3], 6).sort 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /algorithms/ruby/1470-shuffle-the-array.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 1470. Shuffle the Array 4 | # https://leetcode.com/problems/shuffle-the-array 5 | 6 | # @param {Integer[]} nums 7 | # @param {Integer} n 8 | # @return {Integer[]} 9 | def shuffle(nums, n) 10 | result = [] 11 | 12 | n.times do |i| 13 | result << nums[i] 14 | result << nums[i + n] 15 | end 16 | 17 | result 18 | end 19 | 20 | # ********************# 21 | # TEST # 22 | # ********************# 23 | 24 | require "test/unit" 25 | class Test_shuffle < Test::Unit::TestCase 26 | def test_ 27 | assert_equal [2, 3, 5, 4, 1, 7], shuffle([2, 5, 1, 3, 4, 7], 3) 28 | assert_equal [1, 4, 2, 3, 3, 2, 4, 1], shuffle([1, 2, 3, 4, 4, 3, 2, 1], 4) 29 | assert_equal [1, 2, 1, 2], shuffle([1, 1, 2, 2], 2) 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /algorithms/ruby/0002-add-two-numbers.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 2. Add Two Numbers 4 | # https://leetcode.com/problems/add-two-numbers 5 | 6 | # Definition for singly-linked list. 7 | # class ListNode 8 | # attr_accessor :val, :next 9 | 10 | # def initialize(val = 0, _next = nil) 11 | # @val = val 12 | # @next = _next 13 | # end 14 | # end 15 | # @param {ListNode} l1 16 | # @param {ListNode} l2 17 | # @return {ListNode} 18 | def add_two_numbers(l1, l2, carry = 0) 19 | return nil if l1.nil? && l2.nil? && carry.zero? 20 | 21 | sum = (l1&.val || 0) + (l2&.val || 0) + carry 22 | ListNode.new(sum % 10).tap do |l3| 23 | l3.next = add_two_numbers(l1&.next, l2&.next, sum / 10) 24 | end 25 | end 26 | 27 | # **************** # 28 | # TEST # 29 | # **************** # 30 | 31 | # TODO: Write tests 32 | -------------------------------------------------------------------------------- /algorithms/ruby/0148-sort-list.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 148. Sort List 4 | # https://leetcode.com/problems/sort-list 5 | # Medium 6 | 7 | # Definition for singly-linked list. 8 | # class ListNode 9 | # attr_accessor :val, :next 10 | # def initialize(val = 0, _next = nil) 11 | # @val = val 12 | # @next = _next 13 | # end 14 | # end 15 | # @param {ListNode} head 16 | # @return {ListNode} 17 | def sort_list(head) 18 | return nil if head.nil? 19 | array = [] 20 | tmp = head 21 | while tmp 22 | array.push(tmp) 23 | tmp = tmp.next 24 | end 25 | # As a rule against bugs. 26 | # Take list node - nil pointers. 27 | array.each { |x| x.next = nil } 28 | array.sort! { |a, b| a.val <=> b.val } 29 | (0...(array.size - 1)).each do |i| 30 | array[i].next = array[i + 1] 31 | end 32 | array[0] 33 | end 34 | -------------------------------------------------------------------------------- /algorithms/python3/0783-minimum-distance-between-bst-nodes.py: -------------------------------------------------------------------------------- 1 | # 783. Minimum Distance Between BST Nodes 2 | # https://leetcode.com/problems/minimum-distance-between-bst-nodes 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, val=0, left=None, right=None): 7 | # self.val = val 8 | # self.left = left 9 | # self.right = right 10 | class Solution: 11 | def minDiffInBST(self, root: Optional[TreeNode]) -> int: 12 | self.min = float('inf') 13 | self.prev = None 14 | self.inorder(root) 15 | return self.min 16 | 17 | def inorder(self, root: TreeNode) -> None: 18 | if root is None: 19 | return 20 | 21 | self.inorder(root.left) 22 | if self.prev is not None: 23 | self.min = min(self.min, root.val - self.prev) 24 | self.prev = root.val 25 | self.inorder(root.right) -------------------------------------------------------------------------------- /algorithms/ruby/0072-edit-distance.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 72. Edit Distance 4 | # https://leetcode.com/problems/edit-distance 5 | # Hard 6 | 7 | # @param {String} word1 8 | # @param {String} word2 9 | # @return {Integer} 10 | def min_distance(word1, word2) 11 | n = word2.length 12 | curr = (0..n).to_a 13 | 14 | word1.length.times do |i| 15 | prev, curr = curr, [i + 1] + [0] * n 16 | 17 | n.times do |j| 18 | curr[j + 1] = word1[i] == word2[j] ? prev[j] : [curr[j], prev[j], prev[j + 1]].min + 1 19 | end 20 | end 21 | 22 | curr[n] 23 | end 24 | 25 | # **************** # 26 | # TEST # 27 | # **************** # 28 | 29 | require "test/unit" 30 | class Test_min_distance < Test::Unit::TestCase 31 | def test_ 32 | assert_equal 3, min_distance("horse", "ros") 33 | assert_equal 5, min_distance("intention", "execution") 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /algorithms/ruby/0953-verifying-an-alien-dictionary.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 953. Verifying an Alien Dictionary 4 | # https://leetcode.com/problems/verifying-an-alien-dictionary 5 | 6 | # @param {String[]} words 7 | # @param {String} order 8 | # @return {Boolean} 9 | def is_alien_sorted(words, order) 10 | words.sort_by { |w| w.chars.map { |c| order.include?(c) ? order.index(c) : c.ord } } == words 11 | end 12 | 13 | # ********************# 14 | # TEST # 15 | # ********************# 16 | 17 | require "test/unit" 18 | class Test_is_alien_sorted < Test::Unit::TestCase 19 | def test_ 20 | assert_equal true, is_alien_sorted(%w[hello leetcode], "hlabcdefgijkmnopqrstuvwxyz") 21 | assert_equal false, is_alien_sorted(%w[word world row], "worldabcefghijkmnpqstuvxyz") 22 | assert_equal false, is_alien_sorted(%w[apple app], "abcdefghijklmnopqrstuvwxyz") 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /algorithms/ruby/1680-concatenation-of-consecutive-binary-numbers.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 1680. Concatenation of Consecutive Binary Numbers 4 | # https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers 5 | 6 | # @param {Integer} n 7 | # @return {Integer} 8 | MOD = 10**9 + 7 9 | def concatenated_binary(n) 10 | t = r = 1 11 | (1..n).reduce(0) do |s, k| 12 | s = ((s << r) + k) % MOD 13 | t -= 1 14 | if t.zero? 15 | t = 1 << r 16 | r += 1 17 | end 18 | s 19 | end 20 | end 21 | 22 | # ********************# 23 | # TEST # 24 | # ********************# 25 | 26 | require "test/unit" 27 | class Test_concatenated_binary < Test::Unit::TestCase 28 | def test_ 29 | assert_equal 1, concatenated_binary(1) 30 | assert_equal 27, concatenated_binary(3) 31 | assert_equal 505_379_714, concatenated_binary(12) 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /algorithms/ruby/0021-merge-two-sorted-lists.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 21. Merge Two Sorted Lists 4 | # https://leetcode.com/problems/merge-two-sorted-lists 5 | 6 | # Definition for singly-linked list. 7 | # class ListNode 8 | # attr_accessor :val, :next 9 | # def initialize(val = 0, _next = nil) 10 | # @val = val 11 | # @next = _next 12 | # end 13 | # end 14 | # @param {ListNode} list1 15 | # @param {ListNode} list2 16 | # @return {ListNode} 17 | def merge_two_lists(list1, list2) 18 | return list1 unless list2 19 | return list2 unless list1 20 | 21 | if list1.val < list2.val 22 | list1.next = merge_two_lists(list1.next, list2) 23 | list1 24 | else 25 | list2.next = merge_two_lists(list1, list2.next) 26 | list2 27 | end 28 | end 29 | 30 | # **************** # 31 | # TEST # 32 | # **************** # 33 | 34 | # TODO: Write tests 35 | -------------------------------------------------------------------------------- /algorithms/ruby/0028-find-the-index-of-the-first-occurrence-in-a-string.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 28. Find the Index of the First Occurrence in a String 4 | # https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string 5 | 6 | # @param {String} haystack 7 | # @param {String} needle 8 | # @return {Integer} 9 | def str_str(haystack, needle) 10 | return 0 if needle.empty? 11 | return -1 if needle.size > haystack.size 12 | 13 | (haystack.size - needle.size + 1).times do |i| 14 | return i if haystack[i..i + needle.size - 1] == needle 15 | end 16 | 17 | -1 18 | end 19 | 20 | # **************** # 21 | # TEST # 22 | # **************** # 23 | 24 | require "test/unit" 25 | class Test_str_str < Test::Unit::TestCase 26 | def test_ 27 | assert_equal 0, str_str("sadbutsad", "sad") 28 | assert_equal(-1, str_str("leetcode", "leeto")) 29 | end 30 | end 31 | -------------------------------------------------------------------------------- /algorithms/ruby/0382-linked-list-random-node.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 382. Linked List Random Node 4 | # https://leetcode.com/problems/linked-list-random-node 5 | 6 | # Definition for singly-linked list. 7 | # class ListNode 8 | # attr_accessor :val, :next 9 | # def initialize(val = 0, _next = nil) 10 | # @val = val 11 | # @next = _next 12 | # end 13 | # end 14 | class Solution 15 | =begin 16 | :type head: ListNode 17 | =end 18 | def initialize(head) 19 | @array = [] 20 | tmp = head 21 | while tmp 22 | @array.push(tmp) 23 | tmp = tmp.next 24 | end 25 | end 26 | 27 | 28 | =begin 29 | :rtype: Integer 30 | =end 31 | def get_random 32 | @array[rand(@array.size)].val 33 | end 34 | end 35 | 36 | # Your Solution object will be instantiated and called as such: 37 | # obj = Solution.new(head) 38 | # param_1 = obj.get_random() 39 | -------------------------------------------------------------------------------- /algorithms/ruby/0035-search-insert-position.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 35. Search Insert Position 4 | # https://leetcode.com/problems/search-insert-position 5 | 6 | # @param {Integer[]} nums 7 | # @param {Integer} target 8 | # @return {Integer} 9 | def search_insert(nums, target) 10 | return 0 if nums.empty? 11 | 12 | l = 0 13 | r = nums.length - 1 14 | while l <= r 15 | m = (l + r) / 2 16 | if nums[m] == target 17 | return m 18 | elsif nums[m] > target 19 | r = m - 1 20 | else 21 | l = m + 1 22 | end 23 | end 24 | 25 | l 26 | end 27 | 28 | # ********************# 29 | # TEST # 30 | # ********************# 31 | 32 | require "test/unit" 33 | class Test_search_insert < Test::Unit::TestCase 34 | def test_ 35 | assert_equal 1, search_insert([1, 3, 5, 6], 2) 36 | assert_equal 4, search_insert([1, 3, 5, 6], 7) 37 | end 38 | end 39 | -------------------------------------------------------------------------------- /algorithms/ruby/0014-longest-common-prefix.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 14. Longest Common Prefix 4 | # https://leetcode.com/problems/longest-common-prefix 5 | # Easy 6 | 7 | # @param {String[]} strs 8 | # @return {String} 9 | def longest_common_prefix(strs) 10 | return "" if strs.empty? 11 | 12 | prefix = strs[0] 13 | strs[1..].each do |str| 14 | loop do 15 | break if str.start_with?(prefix) 16 | 17 | prefix = prefix[0...prefix.length - 1] 18 | return "" if prefix.empty? 19 | end 20 | end 21 | 22 | prefix 23 | end 24 | 25 | # ********************# 26 | # TEST # 27 | # ********************# 28 | 29 | require "test/unit" 30 | class Test_longest_common_prefix < Test::Unit::TestCase 31 | def test_ 32 | assert_equal "fl", longest_common_prefix(%w[flower flow flight]) 33 | assert_equal "", longest_common_prefix(%w[dog racecar car]) 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /algorithms/ruby/0416-partition-equal-subset-sum.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 416. Partition Equal Subset Sum 4 | # https://leetcode.com/problems/partition-equal-subset-sum/ 5 | # Medium 6 | 7 | =begin 8 | Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise. 9 | 10 | Example 1: 11 | Input: nums = [1,5,11,5] 12 | Output: true 13 | Explanation: The array can be partitioned as [1, 5, 5] and [11]. 14 | 15 | Example 2: 16 | Input: nums = [1,2,3,5] 17 | Output: false 18 | Explanation: The array cannot be partitioned into equal sum subsets. 19 | 20 | Constraints: 21 | 1 <= nums.length <= 200 22 | 1 <= nums[i] <= 100 23 | =end 24 | 25 | # @param {Integer[]} nums 26 | # @return {Boolean} 27 | def can_partition(nums) 28 | (s = nums.sum).even? && 29 | (nums.reduce(1) { _1 | (_1 << _2) } >> s / 2).odd? 30 | end 31 | -------------------------------------------------------------------------------- /algorithms/ruby/0283-move-zeroes.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 283. Move Zeroes 4 | # https://leetcode.com/problems/move-zeroes 5 | # Easy 6 | 7 | =begin 8 | Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. 9 | 10 | Note that you must do this in-place without making a copy of the array. 11 | 12 | Example 1: 13 | Input: nums = [0,1,0,3,12] 14 | Output: [1,3,12,0,0] 15 | 16 | Example 2: 17 | Input: nums = [0] 18 | Output: [0] 19 | 20 | Constraints: 21 | * 1 <= nums.length <= 104 22 | * -231 <= nums[i] <= 231 - 1 23 | =end 24 | 25 | # @param {Integer[]} nums 26 | # @return {Void} Do not return anything, modify nums in-place instead. 27 | def move_zeroes(nums) 28 | k = 0 29 | nums.length.times do |i| 30 | next if nums[i].zero? 31 | 32 | nums[k] = nums[i] 33 | k += 1 34 | end 35 | 36 | k.upto(nums.length - 1).each { |i| nums[i] = 0 } 37 | end 38 | -------------------------------------------------------------------------------- /algorithms/ruby/0113-path-sum-ii.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 113. Path Sum II 4 | # https://leetcode.com/problems/path-sum-ii 5 | 6 | # Definition for a binary tree node. 7 | # class TreeNode 8 | # attr_accessor :val, :left, :right 9 | # def initialize(val = 0, left = nil, right = nil) 10 | # @val = val 11 | # @left = left 12 | # @right = right 13 | # end 14 | # end 15 | # @param {TreeNode} root 16 | # @param {Integer} target_sum 17 | # @return {Integer[][]} 18 | def path_sum(root, target_sum, path = []) 19 | return [] if root.nil? 20 | 21 | target_sum -= root.val 22 | return [path + [root.val]] if root.left.nil? && root.right.nil? && target_sum.zero? 23 | 24 | path_sum(root.left, target_sum, path + [root.val]) + 25 | path_sum(root.right, target_sum, path + [root.val]) 26 | end 27 | 28 | # **************** # 29 | # TEST # 30 | # **************** # 31 | 32 | # TODO: Write tests 33 | -------------------------------------------------------------------------------- /algorithms/ruby/0783-minimum-distance-between-bst-nodes.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 783. Minimum Distance Between BST Nodes 4 | # https://leetcode.com/problems/minimum-distance-between-bst-nodes 5 | # Easy 6 | # TODO: Write Tests 7 | 8 | # Definition for a binary tree node. 9 | # class TreeNode 10 | # attr_accessor :val, :left, :right 11 | # def initialize(val = 0, left = nil, right = nil) 12 | # @val = val 13 | # @left = left 14 | # @right = right 15 | # end 16 | # end 17 | # @param {TreeNode} root 18 | # @return {Integer} 19 | def min_diff_in_bst(root) 20 | @prev = nil 21 | @min = nil 22 | inorder_traversal(root) 23 | @min 24 | end 25 | 26 | def inorder_traversal(root) 27 | return if root.nil? 28 | inorder_traversal(root.left) 29 | if @prev 30 | val = root.val - @prev 31 | @min = @min ? [@min, val].min : val 32 | end 33 | @prev = root.val 34 | inorder_traversal(root.right) 35 | end 36 | -------------------------------------------------------------------------------- /algorithms/ruby/0258-add-digits.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 258. Add Digits 4 | # https://leetcode.com/problems/add-digits 5 | # Easy 6 | 7 | =begin 8 | Given an integer num, repeatedly add all its digits until the result has only one digit, and return it. 9 | 10 | Example 1: 11 | Input: num = 38 12 | Output: 2 13 | Explanation: The process is 14 | 38 --> 3 + 8 --> 11 15 | 11 --> 1 + 1 --> 2 16 | Since 2 has only one digit, return it. 17 | 18 | Example 2: 19 | Input: num = 0 20 | Output: 0 21 | 22 | Constraints: 23 | 0 <= num <= 231 - 1 24 | =end 25 | 26 | # @param {Integer} num 27 | # @return {Integer} 28 | def add_digits(num) 29 | num == 0 ? 0 : (num - 1) % 9 + 1 30 | end 31 | 32 | # **************** # 33 | # TEST # 34 | # **************** # 35 | 36 | require "test/unit" 37 | class Test_add_digits < Test::Unit::TestCase 38 | def test_ 39 | assert_equal 2, add_digits(38) 40 | assert_equal 0, add_digits(0) 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /algorithms/python3/0067-add-binary.py: -------------------------------------------------------------------------------- 1 | # 67. Add Binary 2 | # https://leetcode.com/problems/add-binary 3 | 4 | class Solution: 5 | def addBinary(self, a: str, b: str) -> str: 6 | a_len, b_len = -len(a), -len(b) 7 | i, carry,res = -1, 0, "" 8 | 9 | while i >= a_len or i >= b_len: 10 | a_bit = int(a[i]) if i >= a_len else 0 11 | b_bit = int(b[i]) if i >= b_len else 0 12 | 13 | sum = a_bit + b_bit + carry 14 | res = str(sum % 2) + res 15 | carry = sum // 2 16 | 17 | i -= 1 18 | 19 | return "1" + res if carry else res 20 | 21 | # ********************# 22 | # TEST # 23 | # ********************# 24 | 25 | import unittest 26 | 27 | class TestStringMethods(unittest.TestCase): 28 | def test_addBinary(self): 29 | self.assertEqual(Solution.addBinary(self, "11", "1"), "100") 30 | self.assertEqual(Solution.addBinary(self, "1010", "1011"), "10101") 31 | 32 | 33 | if __name__ == '__main__': 34 | unittest.main() -------------------------------------------------------------------------------- /algorithms/ruby/0003-longest-substring-without-repeating-characters.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 3. Longest Substring Without Repeating Characters 4 | # https://leetcode.com/problems/longest-substring-without-repeating-characters 5 | 6 | # @param {String} s 7 | # @return {Integer} 8 | def length_of_longest_substring(s) 9 | max_len = 0 10 | i = 0 11 | h = {} 12 | 13 | (0...s.length).each do |j| 14 | i = [h[s[j]], i].max if h[s[j]].to_i.positive? 15 | max_len = [max_len, j - i + 1].max 16 | h[s[j]] = j + 1 17 | end 18 | 19 | max_len 20 | end 21 | 22 | # **************** # 23 | # TEST # 24 | # **************** # 25 | 26 | require "test/unit" 27 | class Test_length_of_longest_substring < Test::Unit::TestCase 28 | def test_ 29 | assert_equal 3, length_of_longest_substring("abcabcbb") 30 | assert_equal 1, length_of_longest_substring("bbbbb") 31 | assert_equal 3, length_of_longest_substring("pwwkew") 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /algorithms/ruby/0020-valid-parentheses.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 20. Valid Parentheses 4 | # https://leetcode.com/problems/valid-parentheses 5 | 6 | # @param {String} s 7 | # @return {Boolean} 8 | def is_valid(s) 9 | arr = [] 10 | 11 | s.chars.each do |c| 12 | if ["(", "{", "["].include?(c) 13 | arr.push(c) 14 | else 15 | return false if arr.empty? 16 | if c == ")" && arr.last != "(" || 17 | c == "}" && arr.last != "{" || 18 | c == "]" && arr.last != "[" 19 | 20 | return false 21 | end 22 | 23 | arr.pop 24 | end 25 | end 26 | 27 | arr.empty? 28 | end 29 | 30 | # ********************# 31 | # TEST # 32 | # ********************# 33 | 34 | require "test/unit" 35 | class Test_is_valid < Test::Unit::TestCase 36 | def test_ 37 | assert_equal true, is_valid("()") 38 | assert_equal true, is_valid("()[]{}") 39 | assert_equal false, is_valid("(]") 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /algorithms/ruby/0652-find-duplicate-subtrees.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 652. Find Duplicate Subtrees 4 | # https://leetcode.com/problems/find-duplicate-subtrees 5 | 6 | # Definition for a binary tree node. 7 | # class TreeNode 8 | # attr_accessor :val, :left, :right 9 | # def initialize(val = 0, left = nil, right = nil) 10 | # @val = val 11 | # @left = left 12 | # @right = right 13 | # end 14 | # end 15 | # @param {TreeNode} root 16 | # @return {TreeNode[]} 17 | def find_duplicate_subtrees(root) 18 | @path = {} 19 | @duplicates = [] 20 | 21 | find_duplicates(root) 22 | 23 | @duplicates 24 | end 25 | 26 | def find_duplicates(root) 27 | return "" if root.nil? 28 | 29 | path = [root.val, find_duplicates(root.left), find_duplicates(root.right)].join(",") 30 | 31 | if @path[path] 32 | @duplicates << root if @path[path] == 1 33 | @path[path] += 1 34 | else 35 | @path[path] = 1 36 | end 37 | 38 | path 39 | end 40 | -------------------------------------------------------------------------------- /algorithms/ruby/0013-roman-to-integer.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 13. Roman to Integer 4 | # https://leetcode.com/problems/roman-to-integer 5 | 6 | ROMAN_VALUES = { 7 | "I" => 1, 8 | "V" => 5, 9 | "X" => 10, 10 | "L" => 50, 11 | "C" => 100, 12 | "D" => 500, 13 | "M" => 1000 14 | }.freeze 15 | 16 | # @param {String} s 17 | # @return {Integer} 18 | def roman_to_int(s) 19 | sum = 0 20 | v = 0 21 | s.chars.each_with_index do |c, i| 22 | if s[i + 1] && ROMAN_VALUES[c] < ROMAN_VALUES[s[i + 1]] 23 | v = ROMAN_VALUES[c] 24 | else 25 | sum += ROMAN_VALUES[c] - v 26 | v = 0 27 | end 28 | end 29 | 30 | sum 31 | end 32 | 33 | # ********************# 34 | # TEST # 35 | # ********************# 36 | 37 | require "test/unit" 38 | class Test_roman_to_int < Test::Unit::TestCase 39 | def test_ 40 | assert_equal 3, roman_to_int("III") 41 | assert_equal 58, roman_to_int("LVIII") 42 | assert_equal 1994, roman_to_int("MCMXCIV") 43 | end 44 | end 45 | -------------------------------------------------------------------------------- /algorithms/ruby/1071-greatest-common-divisor-of-strings.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 1071. Greatest Common Divisor of Strings 4 | # https://leetcode.com/problems/greatest-common-divisor-of-strings 5 | # Easy 6 | 7 | # @param {String} str1 8 | # @param {String} str2 9 | # @return {String} 10 | def gcd_of_strings(str1, str2) 11 | return str1 if str1 == str2 12 | 13 | if str1.size >= str2.size 14 | long = str1 15 | short = str2 16 | else 17 | long = str2 18 | short = str1 19 | end 20 | len = short.size 21 | return "" unless short == long[0...len] 22 | 23 | gcd_of_strings(short, long[len..]) 24 | end 25 | 26 | # ********************# 27 | # TEST # 28 | # ********************# 29 | 30 | require "test/unit" 31 | class Test_gcd_of_strings < Test::Unit::TestCase 32 | def test_ 33 | assert_equal "ABC", gcd_of_strings("ABCABC", "ABC") 34 | assert_equal "AB", gcd_of_strings("ABABAB", "ABAB") 35 | assert_equal "", gcd_of_strings("LEET", "CODE") 36 | end 37 | end 38 | -------------------------------------------------------------------------------- /algorithms/ruby/0343-integer-break.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 343. Integer Break 4 | # Medium 5 | # https://leetcode.com/problems/integer-break 6 | 7 | =begin 8 | Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers. 9 | Return the maximum product you can get. 10 | 11 | Example 1: 12 | Input: n = 2 13 | Output: 1 14 | Explanation: 2 = 1 + 1, 1 × 1 = 1. 15 | 16 | Example 2: 17 | Input: n = 10 18 | Output: 36 19 | Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36. 20 | 21 | Constraints: 22 | 2 <= n <= 58 23 | =end 24 | 25 | # @param {Integer} n 26 | # @return {Integer} 27 | def integer_break(n) 28 | n < 4 ? n - 1 : 3**((n - 2) / 3) * ((n - 2) % 3 + 2) 29 | end 30 | 31 | # **************** # 32 | # TEST # 33 | # **************** # 34 | 35 | require "test/unit" 36 | class Test_integer_break < Test::Unit::TestCase 37 | def test_ 38 | assert_equal 1, integer_break(2) 39 | assert_equal 36, integer_break(10) 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /algorithms/ruby/0234-palindrome-linked-list.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 234. Palindrome Linked List 4 | # https://leetcode.com/problems/palindrome-linked-list 5 | 6 | =begin 7 | 8 | Given the head of a singly linked list, return true if it is a 9 | 10 | ### Example 1: 11 | Input: head = [1,2,2,1] 12 | Output: true 13 | 14 | ### Example 2: 15 | Input: head = [1,2] 16 | Output: false 17 | 18 | ### Constraints: 19 | The number of nodes in the list is in the range [1, 105]. 20 | 0 <= Node.val <= 9 21 | 22 | =end 23 | 24 | # Definition for singly-linked list. 25 | # class ListNode 26 | # attr_accessor :val, :next 27 | # def initialize(val = 0, _next = nil) 28 | # @val = val 29 | # @next = _next 30 | # end 31 | # end 32 | # @param {ListNode} head 33 | # @return {Boolean} 34 | def is_palindrome(head) 35 | data = [] 36 | current_node = head 37 | while !current_node.nil? 38 | data << current_node.val 39 | current_node = current_node.next 40 | end 41 | data == data.reverse 42 | end 43 | -------------------------------------------------------------------------------- /algorithms/ruby/0904-fruit-into-baskets.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 904. Fruit Into Baskets 4 | # https://leetcode.com/problems/fruit-into-baskets 5 | 6 | # @param {Integer[]} fruits 7 | # @return {Integer} 8 | def total_fruit(fruits) 9 | left = 0 10 | max_fruit = 0 11 | hash = {} 12 | hash.default = 0 13 | 14 | fruits.each_with_index do |fruit, right| 15 | hash[fruit] += 1 16 | 17 | while hash.length > 2 18 | hash[fruits[left]] -= 1 19 | 20 | hash.delete(fruits[left]) if hash[fruits[left]].zero? 21 | 22 | left += 1 23 | end 24 | 25 | max_fruit = [max_fruit, right - left + 1].max 26 | end 27 | 28 | max_fruit 29 | end 30 | 31 | # ********************# 32 | # TEST # 33 | # ********************# 34 | 35 | require "test/unit" 36 | class Test_total_fruit < Test::Unit::TestCase 37 | def test_ 38 | assert_equal 3, total_fruit([1, 2, 1]) 39 | assert_equal 3, total_fruit([0, 1, 2, 2]) 40 | assert_equal 4, total_fruit([1, 2, 3, 2, 2]) 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /algorithms/python3/0502-ipo.py: -------------------------------------------------------------------------------- 1 | # 502. IPO 2 | # https://leetcode.com/problems/ipo 3 | 4 | import heapq 5 | 6 | class Solution: 7 | def findMaximizedCapital(self, k: int, w: int, profits: list[int], capital: list[int]) -> int: 8 | n = len(profits) 9 | projects = list(zip(capital, profits)) 10 | projects.sort() 11 | 12 | q = [] 13 | ptr = 0 14 | for i in range(k): 15 | while ptr < n and projects[ptr][0] <= w: 16 | heapq.heappush(q, -projects[ptr][1]) 17 | ptr += 1 18 | if not q: 19 | break 20 | w += -heapq.heappop(q) 21 | return w 22 | 23 | # ********************# 24 | # TEST # 25 | # ********************# 26 | 27 | import unittest 28 | 29 | class TestStringMethods(unittest.TestCase): 30 | def test_addBinary(self): 31 | self.assertEqual(Solution.findMaximizedCapital(self, 2, 0, [1, 2, 3], [0, 1, 1]), 4) 32 | self.assertEqual(Solution.findMaximizedCapital(self, 3, 0, [1, 2, 3], [0, 1, 2]), 6) 33 | 34 | if __name__ == '__main__': 35 | unittest.main() 36 | -------------------------------------------------------------------------------- /algorithms/ruby/0206-reverse-linked-list.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 206. Reverse Linked List 4 | # https://leetcode.com/problems/reverse-linked-list 5 | 6 | =begin 7 | 8 | Given the head of a singly linked list, reverse the list, and return the reversed list. 9 | 10 | ### Example 1: 11 | Input: head = [1,2,3,4,5] 12 | Output: [5,4,3,2,1] 13 | 14 | ### Example 2: 15 | Input: head = [1,2] 16 | Output: [2,1] 17 | 18 | ### Example 3: 19 | Input: head = [] 20 | Output: [] 21 | 22 | ### Constraints: 23 | * The number of nodes in the list is the range [0, 5000]. 24 | * -5000 <= Node.val <= 5000 25 | 26 | =end 27 | 28 | # Definition for singly-linked list. 29 | # class ListNode 30 | # attr_accessor :val, :next 31 | # def initialize(val = 0, _next = nil) 32 | # @val = val 33 | # @next = _next 34 | # end 35 | # end 36 | # @param {ListNode} head 37 | # @return {ListNode} 38 | def reverse_list(head, prev = nil) 39 | while head 40 | head, head.next, prev = head.next, prev, head 41 | end 42 | prev 43 | end 44 | -------------------------------------------------------------------------------- /algorithms/ruby/0502-ipo.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 502. IPO 4 | # https://leetcode.com/problems/ipo 5 | 6 | # @param {Integer} k 7 | # @param {Integer} w 8 | # @param {Integer[]} profits 9 | # @param {Integer[]} capital 10 | # @return {Integer} 11 | def bs_insert(a, item) 12 | a.insert(a.bsearch_index { item <= _1 } || a.size, item) 13 | end 14 | 15 | def find_maximized_capital(k, w, profits, costs) 16 | tasks = costs.zip(profits).sort 17 | sorted_profits = [] 18 | 19 | k.times.reduce(w) do |capital, _| 20 | while tasks[0] && capital >= tasks[0][0] 21 | bs_insert(sorted_profits, tasks.shift[1]) 22 | end 23 | 24 | capital + (sorted_profits.pop || 0) 25 | end 26 | end 27 | 28 | # ********************# 29 | # TEST # 30 | # ********************# 31 | 32 | require "test/unit" 33 | class Test_find_maximized_capital < Test::Unit::TestCase 34 | def test_ 35 | assert_equal 4, find_maximized_capital(2, 0, [1, 2, 3], [0, 1, 1]) 36 | assert_equal 6, find_maximized_capital(3, 0, [1, 2, 3], [0, 1, 2]) 37 | end 38 | end 39 | -------------------------------------------------------------------------------- /algorithms/ruby/0567-permutation-in-string.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 567. Permutation in String 4 | # https://leetcode.com/problems/permutation-in-string 5 | 6 | # @param {String} s1 7 | # @param {String} s2 8 | # @return {Boolean} 9 | def check_inclusion(s1, s2) 10 | return false if s1.size > s2.size 11 | 12 | s1_h = Hash.new(0) 13 | s1.each_char { |c| s1_h[c] += 1 } 14 | 15 | i = 0 16 | j = 0 17 | 18 | while j < s2.size 19 | if s1_h[s2[j]] != 0 20 | s1_h[s2[j]] -= 1 21 | return true if j - i == s1.size - 1 22 | 23 | j += 1 24 | elsif i == j 25 | i += 1 26 | j += 1 27 | else 28 | s1_h[s2[i]] += 1 29 | i += 1 30 | end 31 | end 32 | 33 | false 34 | end 35 | 36 | # ********************# 37 | # TEST # 38 | # ********************# 39 | 40 | require "test/unit" 41 | class Test_check_inclusion < Test::Unit::TestCase 42 | def test_ 43 | assert_equal true, check_inclusion("ab", "eidbaooo") 44 | assert_equal false, check_inclusion("ab", "eidboaoo") 45 | end 46 | end 47 | -------------------------------------------------------------------------------- /algorithms/ruby/0006-zigzag-conversion.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 6. Verifying an Alien Dictionary 4 | # https://leetcode.com/problems/zigzag-conversion 5 | 6 | # @param {String} s 7 | # @param {Integer} num_rows 8 | # @return {String} 9 | def convert(s, num_rows) 10 | return s if s.size == 1 || num_rows == 1 11 | 12 | str = s.chars 13 | res = Array.new(num_rows) { [] } 14 | 15 | j = 0 16 | while str.any? 17 | if num_rows == 1 || (j % (num_rows - 1)).zero? 18 | num_rows.times { |i| res[i][j] = str.shift } 19 | else 20 | res[num_rows - (j % (num_rows - 1)) - 1][j] = str.shift 21 | end 22 | 23 | j += 1 24 | end 25 | 26 | res.flatten.compact.join 27 | end 28 | 29 | # **************** # 30 | # TEST # 31 | # **************** # 32 | 33 | require "test/unit" 34 | class Test_convert < Test::Unit::TestCase 35 | def test_ 36 | assert_equal "PAHNAPLSIIGYIR", convert("PAYPALISHIRING", 3) 37 | assert_equal "PINALSIGYAHRPI", convert("PAYPALISHIRING", 4) 38 | assert_equal "A", convert("A", 1) 39 | end 40 | end 41 | -------------------------------------------------------------------------------- /algorithms/ruby/0152-maximum-product-subarray.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 152. Maximum Product Subarray 4 | # https://leetcode.com/problems/maximum-product-subarray/ 5 | # Medium 6 | 7 | =begin 8 | Given an integer array nums, find a subarray that has the largest product, and return the product. 9 | 10 | The test cases are generated so that the answer will fit in a 32-bit integer. 11 | 12 | Example 1: 13 | Input: nums = [2,3,-2,4] 14 | Output: 6 15 | Explanation: [2,3] has the largest product 6. 16 | 17 | Example 2: 18 | Input: nums = [-2,0,-1] 19 | Output: 0 20 | Explanation: The result cannot be 2, because [-2,-1] is not a subarray. 21 | 22 | Constraints: 23 | 1 <= nums.length <= 2 * 104 24 | -10 <= nums[i] <= 10 25 | The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. 26 | =end 27 | 28 | # @param {Integer[]} nums 29 | # @return {Integer} 30 | def max_product(nums) 31 | min = max = 1 32 | res = nums[0] 33 | nums.each do |n| 34 | min, max = [n, min * n, max * n].minmax 35 | res = [res, max].max 36 | end 37 | res 38 | end 39 | -------------------------------------------------------------------------------- /algorithms/ruby/0189-rotate-array.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 189. Rotate Array 4 | # https://leetcode.com/problems/rotate-array 5 | # Medium 6 | 7 | =begin 8 | Given an integer array nums, rotate the array to the right by k steps, where k is non-negative. 9 | 10 | Example 1: 11 | Input: nums = [1,2,3,4,5,6,7], k = 3 12 | Output: [5,6,7,1,2,3,4] 13 | Explanation: 14 | rotate 1 steps to the right: [7,1,2,3,4,5,6] 15 | rotate 2 steps to the right: [6,7,1,2,3,4,5] 16 | rotate 3 steps to the right: [5,6,7,1,2,3,4] 17 | 18 | Example 2: 19 | Input: nums = [-1,-100,3,99], k = 2 20 | Output: [3,99,-1,-100] 21 | Explanation: 22 | rotate 1 steps to the right: [99,-1,-100,3] 23 | rotate 2 steps to the right: [3,99,-1,-100] 24 | 25 | Constraints: 26 | 1 <= nums.length <= 105 27 | -231 <= nums[i] <= 231 - 1 28 | 0 <= k <= 105 29 | =end 30 | 31 | # @param {Integer[]} nums 32 | # @param {Integer} k 33 | # @return {Void} Do not return anything, modify nums in-place instead. 34 | def rotate(nums, k) 35 | k %= nums.size 36 | nums[0...k], nums[k..-1] = nums[-k..-1], nums[0...nums.size - k] 37 | end 38 | -------------------------------------------------------------------------------- /algorithms/ruby/0010-regular-expression-matching.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 10. Regular Expression Matching 4 | # https://leetcode.com/problems/regular-expression-matching 5 | 6 | # @param {String} s 7 | # @param {String} p 8 | # @return {Boolean} 9 | def is_match(s, p) 10 | s = s.bytes 11 | p = p.bytes 12 | dp = Array.new(s.length + 1) { Array.new(p.length + 1, false) } 13 | m = s.length 14 | n = p.length 15 | dp[m][n] = true 16 | m.downto(0) do |i| 17 | (n - 1).downto(0) do |j| 18 | first = i < m && (s[i] == p[j] || p[j] == 46) 19 | dp[i][j] = if p[j + 1] == 42 20 | dp[i][j + 2] || (first && dp[i + 1][j]) 21 | else 22 | first && dp[i + 1][j + 1] 23 | end 24 | end 25 | end 26 | dp[0][0] 27 | end 28 | 29 | # **************** # 30 | # TEST # 31 | # **************** # 32 | 33 | require "test/unit" 34 | class Test_is_match < Test::Unit::TestCase 35 | def test_ 36 | assert_equal false, is_match("aa", "a") 37 | assert_equal true, is_match("aa", "a*") 38 | assert_equal true, is_match("ab", ".*") 39 | end 40 | end 41 | -------------------------------------------------------------------------------- /algorithms/ruby/0101-symmetric-tree.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 101. Symmetric Tree 4 | # https://leetcode.com/problems/symmetric-tree 5 | 6 | =begin 7 | 8 | Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). 9 | 10 | ### Constraints: 11 | 12 | * The number of nodes in the tree is in the range [1, 1000]. 13 | * -100 <= Node.val <= 100 14 | 15 | =end 16 | 17 | # Definition for a binary tree node. 18 | # class TreeNode 19 | # attr_accessor :val, :left, :right 20 | # def initialize(val = 0, left = nil, right = nil) 21 | # @val = val 22 | # @left = left 23 | # @right = right 24 | # end 25 | # end 26 | # @param {TreeNode} root 27 | # @return {Boolean} 28 | def is_symmetric(root) 29 | return true unless root 30 | 31 | symmetric_trees?(root.left, root.right) 32 | end 33 | 34 | def symmetric_trees?(node1, node2) 35 | return true if node1.nil? && node2.nil? 36 | return false if node1&.val != node2&.val 37 | 38 | symmetric_trees?(node1.left, node2.right) && symmetric_trees?(node1.right, node2.left) 39 | end 40 | -------------------------------------------------------------------------------- /algorithms/ruby/2595-number-of-even-and-odd-bits.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 2595. Number of Even and Odd Bits 4 | # https://leetcode.com/problems/number-of-even-and-odd-bits 5 | 6 | =begin 7 | 8 | You are given a positive integer n. 9 | 10 | Let even denote the number of even indices in the binary representation of n (0-indexed) with value 1. 11 | 12 | Let odd denote the number of odd indices in the binary representation of n (0-indexed) with value 1. 13 | 14 | Return an integer array answer where answer = [even, odd]. 15 | 16 | ### Constraints: 17 | 18 | * 1 <= n <= 1000 19 | 20 | =end 21 | 22 | # Runtime 89 ms, Beats 100% 23 | # Memory 210.9 MB, Beats 100% 24 | # @param {Integer} n 25 | # @return {Integer[]} 26 | def even_odd_bit(n) 27 | [(n & 341).digits(2).count(1), (n & 682).digits(2).count(1)] 28 | end 29 | 30 | # **************** # 31 | # TEST # 32 | # **************** # 33 | 34 | require "test/unit" 35 | class Test_even_odd_bit < Test::Unit::TestCase 36 | def test_ 37 | assert_equal [2, 0], even_odd_bit(17) 38 | assert_equal [0, 1], even_odd_bit(2) 39 | end 40 | end 41 | -------------------------------------------------------------------------------- /algorithms/ruby/0172-factorial-trailing-zeroes.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 172. Factorial Trailing Zeroes 4 | # https://leetcode.com/problems/factorial-trailing-zeroes 5 | # Medium 6 | 7 | =begin 8 | Given an integer n, return the number of trailing zeroes in n!. 9 | 10 | Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1. 11 | 12 | Example 1: 13 | Input: n = 3 14 | Output: 0 15 | Explanation: 3! = 6, no trailing zero. 16 | 17 | Example 2: 18 | Input: n = 5 19 | Output: 1 20 | Explanation: 5! = 120, one trailing zero. 21 | 22 | Example 3: 23 | Input: n = 0 24 | Output: 0 25 | 26 | Constraints: 27 | 0 <= n <= 104 28 | =end 29 | 30 | # @param {Integer} n 31 | # @return {Integer} 32 | def trailing_zeroes(n) 33 | (n / 5).zero? ? 0 : n / 5 + trailing_zeroes(n / 5) 34 | end 35 | 36 | # ********************# 37 | # TEST # 38 | # ********************# 39 | 40 | require "test/unit" 41 | class Test_trailing_zeroes < Test::Unit::TestCase 42 | def test_ 43 | assert_equal 0, trailing_zeroes(3) 44 | assert_equal 1, trailing_zeroes(5) 45 | assert_equal 0, trailing_zeroes(0) 46 | end 47 | end 48 | -------------------------------------------------------------------------------- /algorithms/ruby/0345-reverse-vowels-of-a-string.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 345. Reverse Vowels of a String 4 | # https://leetcode.com/problems/reverse-vowels-of-a-string 5 | # Easy 6 | 7 | =begin 8 | Given a string s, reverse only all the vowels in the string and return it. 9 | 10 | The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once. 11 | 12 | Example 1: 13 | Input: s = "hello" 14 | Output: "holle" 15 | 16 | Example 2: 17 | Input: s = "leetcode" 18 | Output: "leotcede" 19 | 20 | Constraints: 21 | * 1 <= s.length <= 3 * 105 22 | * s consist of printable ASCII characters. 23 | =end 24 | 25 | # @param {String} s 26 | # @return {String} 27 | def reverse_vowels(s) 28 | vowels = s.scan(/[aeiou]/i) 29 | s.gsub(/[aeiou]/i) { vowels.pop } 30 | end 31 | 32 | # **************** # 33 | # TEST # 34 | # **************** # 35 | 36 | require "test/unit" 37 | class Test_reverse_vowels < Test::Unit::TestCase 38 | def test_ 39 | assert_equal "holle", reverse_vowels("hello") 40 | assert_equal "leotcede", reverse_vowels("leetcode") 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /algorithms/ruby/0342-power-of-four.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 342. Power of Four 4 | # Easy 5 | # https://leetcode.com/problems/power-of-four 6 | 7 | =begin 8 | Given an integer n, return true if it is a power of four. Otherwise, return false. 9 | An integer n is a power of four, if there exists an integer x such that n == 4^x. 10 | 11 | Example 1: 12 | Input: n = 16 13 | Output: true 14 | 15 | Example 2: 16 | Input: n = 5 17 | Output: false 18 | 19 | Example 3: 20 | Input: n = 1 21 | Output: true 22 | 23 | Constraints: 24 | -231 <= n <= 231 - 1 25 | =end 26 | 27 | # @param {Integer} n 28 | # @return {Boolean} 29 | def is_power_of_four(n) 30 | return true if n == 1 31 | four = 1 32 | while four < n 33 | four *= 4 34 | end 35 | four == n ? true : false 36 | end 37 | 38 | # **************** # 39 | # TEST # 40 | # **************** # 41 | 42 | require "test/unit" 43 | class Test_is_power_of_four < Test::Unit::TestCase 44 | def test_ 45 | assert_equal true, is_power_of_four(16) 46 | assert_equal false, is_power_of_four(5) 47 | assert_equal true, is_power_of_four(1) 48 | end 49 | end 50 | -------------------------------------------------------------------------------- /algorithms/ruby/0443-string-compression.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 443. String Compression 4 | # https://leetcode.com/problems/string-compression 5 | 6 | # @param {Character[]} chars 7 | # @return {Integer} 8 | def compress(chars) 9 | n = chars.length 10 | 11 | return 1 if n == 1 12 | 13 | i = 0 14 | j = 0 15 | count = 0 16 | 17 | while i < n do 18 | count += 1 19 | 20 | if chars[i + 1] != chars[i] 21 | chars[j] = chars[i] 22 | j += 1 23 | 24 | if count > 1 25 | count.to_s.each_char do |char| 26 | chars[j] = char 27 | j += 1 28 | end 29 | end 30 | 31 | count = 0 32 | end 33 | 34 | i += 1 35 | end 36 | 37 | j 38 | end 39 | 40 | # **************** # 41 | # TEST # 42 | # **************** # 43 | 44 | require "test/unit" 45 | class Test_compress < Test::Unit::TestCase 46 | def test_ 47 | assert_equal 6, compress(["a", "a", "b", "b", "c", "c", "c"]) 48 | assert_equal 1, compress(["a"]) 49 | assert_equal 4, compress(["a", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b"]) 50 | end 51 | end 52 | -------------------------------------------------------------------------------- /algorithms/ruby/0958-check-completeness-of-a-binary-tree.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 958. Check Completeness of a Binary Tree 4 | # https://leetcode.com/problems/check-completeness-of-a-binary-tree 5 | 6 | =begin 7 | 8 | Given the root of a binary tree, determine if it is a complete binary tree. 9 | 10 | In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. 11 | 12 | ### Constraints: 13 | 14 | * The number of nodes in the tree is in the range [1, 100]. 15 | * 1 <= Node.val <= 1000 16 | 17 | =end 18 | 19 | # Definition for a binary tree node. 20 | # class TreeNode 21 | # attr_accessor :val, :left, :right 22 | # def initialize(val = 0, left = nil, right = nil) 23 | # @val = val 24 | # @left = left 25 | # @right = right 26 | # end 27 | # end 28 | # @param {TreeNode} root 29 | # @return {Boolean} 30 | def is_complete_tree(root) 31 | q = [root] 32 | q.push root.left, root.right while root = q.shift 33 | q.count(nil) == q.size 34 | end 35 | -------------------------------------------------------------------------------- /algorithms/python3/2187-minimum-time-to-complete-trips.py: -------------------------------------------------------------------------------- 1 | # 2187. Minimum Time to Complete Trips 2 | # https://leetcode.com/problems/minimum-time-to-complete-trips 3 | 4 | class Solution: 5 | def minimumTime(self, time: list[int], totalTrips: int) -> int: 6 | # Initialize the left and right boundaries. 7 | left, right = 1, min(time) * totalTrips 8 | 9 | # Can these buses finish 'totalTrips' of trips in 'given_time'? 10 | def timeEnough(given_time): 11 | return sum(given_time // t for t in time) >= totalTrips 12 | 13 | # Binary search to find the minimum time to finish the task. 14 | while left < right: 15 | mid = (left + right) // 2 16 | if timeEnough(mid): 17 | right = mid 18 | else: 19 | left = mid + 1 20 | return left 21 | 22 | # ********************# 23 | # TEST # 24 | # ********************# 25 | 26 | import unittest 27 | 28 | class TestMinimumTime(unittest.TestCase): 29 | def test_minimumTime(self): 30 | self.assertEqual(Solution.minimumTime(self, [1, 2, 3, 5], 5), 3) 31 | self.assertEqual(Solution.minimumTime(self, [2], 1),2) 32 | 33 | if __name__ == '__main__': 34 | unittest.main() 35 | -------------------------------------------------------------------------------- /algorithms/ruby/1137-n-th-tribonacci-number.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 1137. N-th Tribonacci Number 4 | # https://leetcode.com/problems/n-th-tribonacci-number 5 | # Easy 6 | 7 | =begin 8 | The Tribonacci sequence Tn is defined as follows: 9 | 10 | T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0. 11 | 12 | Given n, return the value of Tn. 13 | 14 | Example 1: 15 | Input: n = 4 16 | Output: 4 17 | Explanation: 18 | T_3 = 0 + 1 + 1 = 2 19 | T_4 = 1 + 1 + 2 = 4 20 | 21 | Example 2: 22 | Input: n = 25 23 | Output: 1389537 24 | 25 | Constraints: 26 | 0 <= n <= 37 27 | The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1. 28 | =end 29 | 30 | # @param {Integer} n 31 | # @return {Integer} 32 | def tribonacci(n) 33 | arr = [0, 1, 1] 34 | 35 | arr.size.upto(n) { arr << arr.last(3).sum } 36 | 37 | arr[n] 38 | end 39 | 40 | # **************** # 41 | # TEST # 42 | # **************** # 43 | 44 | require "test/unit" 45 | class Test_tribonacci < Test::Unit::TestCase 46 | def test_ 47 | assert_equal 4, tribonacci(4) 48 | assert_equal 1389537, tribonacci(25) 49 | end 50 | end 51 | -------------------------------------------------------------------------------- /algorithms/ruby/2477-minimum-fuel-cost-to-report-to-the-capital.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 2477. Minimum Fuel Cost to Report to the Capital 4 | # https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital 5 | 6 | # @param {Integer[][]} roads 7 | # @param {Integer} seats 8 | # @return {Integer} 9 | def minimum_fuel_cost(roads, seats) 10 | hsh = Array.new roads.size + 1 do [] end 11 | roads.each do | (x, y) | 12 | hsh[x] << y 13 | hsh[y] << x 14 | end 15 | 16 | cost = 0 17 | l = -> n, p do 18 | c = hsh[n].reduce(1) { _2 == p ? (next _1) : _1 + l.(_2, n) } 19 | cost += (c + seats - 1) / seats 20 | c 21 | end 22 | 23 | hsh[0].each { l.(_1, 0) } 24 | 25 | cost 26 | end 27 | 28 | # ********************# 29 | # TEST # 30 | # ********************# 31 | 32 | require "test/unit" 33 | class Test_minimum_fuel_cost < Test::Unit::TestCase 34 | def test_ 35 | assert_equal 3, minimum_fuel_cost([[0, 1], [0, 2], [0, 3]], 5) 36 | assert_equal 7, minimum_fuel_cost([[3, 1], [3, 2], [1, 0], [0, 4], [0, 5], [4, 6]], 2) 37 | assert_equal 0, minimum_fuel_cost([], 1) 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /algorithms/ruby/0338-counting-bits.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 338. Counting Bits 4 | # https://leetcode.com/problems/counting-bits 5 | # Easy 6 | 7 | =begin 8 | Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i. 9 | 10 | Example 1: 11 | Input: n = 2 12 | Output: [0,1,1] 13 | Explanation: 14 | 0 --> 0 15 | 1 --> 1 16 | 2 --> 10 17 | 18 | Example 2: 19 | Input: n = 5 20 | Output: [0,1,1,2,1,2] 21 | Explanation: 22 | 0 --> 0 23 | 1 --> 1 24 | 2 --> 10 25 | 3 --> 11 26 | 4 --> 100 27 | 5 --> 101 28 | 29 | Constraints: 30 | 0 <= n <= 105 31 | =end 32 | 33 | # @param {Integer} n 34 | # @return {Integer[]} 35 | def count_bits(n) 36 | result = [0] 37 | (0..n).each { |i| 38 | result[i] = result[i / 2] + (i % 2) 39 | } 40 | result 41 | end 42 | 43 | # **************** # 44 | # TEST # 45 | # **************** # 46 | 47 | require "test/unit" 48 | class Test_count_bits < Test::Unit::TestCase 49 | def test_ 50 | assert_equal [0, 1, 1], count_bits(2) 51 | assert_equal [0, 1, 1, 2, 1, 2], count_bits(5) 52 | end 53 | end 54 | -------------------------------------------------------------------------------- /algorithms/ruby/0103-binary-tree-zigzag-level-order-traversal.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 103. Binary Tree Zigzag Level Order Traversal 4 | # https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal 5 | 6 | # Definition for a binary tree node. 7 | # class TreeNode 8 | # attr_accessor :val, :left, :right 9 | # def initialize(val = 0, left = nil, right = nil) 10 | # @val = val 11 | # @left = left 12 | # @right = right 13 | # end 14 | # end 15 | # @param {TreeNode} root 16 | # @return {Integer[][]} 17 | def zigzag_level_order(root) 18 | return [] if root.nil? 19 | 20 | res = [] 21 | stack = [root] 22 | count = 1 23 | until stack.empty? 24 | res << stack.map(&:val) 25 | count += 1 26 | arr = [] 27 | stack.size.times do 28 | current = stack.pop 29 | if count.even? 30 | arr.push(current.right) if current.right 31 | arr.push(current.left) if current.left 32 | else 33 | arr.push(current.left) if current.left 34 | arr.push(current.right) if current.right 35 | end 36 | end 37 | stack = arr 38 | end 39 | 40 | res 41 | end 42 | -------------------------------------------------------------------------------- /algorithms/ruby/0905-sort-array-by-parity.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 905. Sort Array By Parity 4 | # Easy 5 | # https://leetcode.com/problems/sort-array-by-parity 6 | 7 | =begin 8 | Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers. 9 | Return any array that satisfies this condition. 10 | 11 | Example 1: 12 | Input: nums = [3,1,2,4] 13 | Output: [2,4,3,1] 14 | Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. 15 | 16 | Example 2: 17 | Input: nums = [0] 18 | Output: [0] 19 | 20 | Constraints: 21 | 1 <= nums.length <= 5000 22 | 0 <= nums[i] <= 5000 23 | =end 24 | 25 | # @param {Integer[]} nums 26 | # @return {Integer[]} 27 | def sort_array_by_parity(nums) 28 | nums.partition(&:even?).sum([]) 29 | end 30 | 31 | # **************** # 32 | # TEST # 33 | # **************** # 34 | 35 | require "test/unit" 36 | class Test_length_of_longest_substring < Test::Unit::TestCase 37 | def test_ 38 | assert_equal [2, 4, 3, 1].sort, sort_array_by_parity([3, 1, 2, 4]).sort 39 | assert_equal [0].sort, sort_array_by_parity([0]) 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /algorithms/ruby/1675-minimize-deviation-in-array.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 1675. Minimize Deviation in Array 4 | # https://leetcode.com/problems/minimize-deviation-in-array 5 | 6 | # @param {Integer[]} nums 7 | # @return {Integer} 8 | def minimum_deviation(nums) 9 | nums.uniq! 10 | nums.map! { |x| x.odd? ? x * 2 : x }.sort! 11 | diff = nums.last - nums.first 12 | stack = [] 13 | 14 | loop do 15 | if stack.empty? || nums.last.to_i > stack.first 16 | max = nums.pop 17 | else 18 | max = stack.shift 19 | end 20 | 21 | break if max.odd? 22 | 23 | stack.push max / 2 24 | max = [stack.first, nums.last].compact.max 25 | min = [stack.last, nums.first].compact.min 26 | diff = [diff, max - min].min 27 | end 28 | 29 | diff 30 | end 31 | 32 | # ********************# 33 | # TEST # 34 | # ********************# 35 | 36 | require "test/unit" 37 | class Test_minimum_deviation < Test::Unit::TestCase 38 | def test_ 39 | assert_equal 1, minimum_deviation([1, 2, 3, 4]) 40 | assert_equal 3, minimum_deviation([4, 1, 5, 20, 3]) 41 | assert_equal 3, minimum_deviation([2, 10, 8]) 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /algorithms/ruby/0347-top-k-frequent-elements.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 347. Top K Frequent Elements 4 | # https://leetcode.com/problems/top-k-frequent-elements 5 | # Medium 6 | 7 | =begin 8 | Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. 9 | 10 | Example 1: 11 | Input: nums = [1,1,1,2,2,3], k = 2 12 | Output: [1,2] 13 | 14 | Example 2: 15 | Input: nums = [1], k = 1 16 | Output: [1] 17 | 18 | Constraints: 19 | 1 <= nums.length <= 105 20 | -104 <= nums[i] <= 104 21 | k is in the range [1, the number of unique elements in the array]. 22 | It is guaranteed that the answer is unique. 23 | =end 24 | 25 | # @param {Integer[]} nums 26 | # @param {Integer} k 27 | # @return {Integer[]} 28 | def top_k_frequent(nums, k) 29 | nums.tally.sort_by { |_, v| -v }.first(k).to_h.keys 30 | end 31 | 32 | # **************** # 33 | # TEST # 34 | # **************** # 35 | 36 | require "test/unit" 37 | class Test_top_k_frequent < Test::Unit::TestCase 38 | def test_ 39 | assert_equal [1, 2], top_k_frequent([1, 1, 1, 2, 2, 3], 2) 40 | assert_equal [1], top_k_frequent([1], 1) 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /algorithms/python3/0808-soup-servings.py: -------------------------------------------------------------------------------- 1 | # 808. Soup Servings 2 | # Medium 3 | # https://leetcode.com/problems/soup-servings 4 | 5 | import math; 6 | 7 | class Solution: 8 | def soupServings(self, n: int) -> float: 9 | m = math.ceil(n / 25) 10 | dp = {} 11 | 12 | def calculate_dp(i, j): 13 | return (dp[max(0, i - 4)][j] + dp[max(0, i - 3)][j - 1] + 14 | dp[max(0, i - 2)][max(0, j - 2)] 15 | + dp[i - 1][max(0, j - 3)]) / 4 16 | 17 | dp[0] = {0: 0.5} 18 | for k in range(1, m + 1): 19 | dp[0][k] = 1 20 | dp[k] = {0: 0} 21 | for j in range(1, k + 1): 22 | dp[j][k] = calculate_dp(j, k) 23 | dp[k][j] = calculate_dp(k, j) 24 | if dp[k][k] > 1 - 1e-5: 25 | return 1 26 | return dp[m][m] 27 | 28 | # ********************# 29 | # TEST # 30 | # ********************# 31 | 32 | import unittest 33 | 34 | class TestStringMethods(unittest.TestCase): 35 | def test_addBinary(self): 36 | self.assertEqual(Solution.soupServings(self, 50), 0.62500) 37 | self.assertEqual(Solution.soupServings(self, 100), 0.71875) 38 | 39 | 40 | if __name__ == '__main__': 41 | unittest.main() 42 | -------------------------------------------------------------------------------- /algorithms/ruby/0989-add-to-array-form-of-integer.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 989. Add to Array-Form of Integer 4 | # https://leetcode.com/problems/add-to-array-form-of-integer 5 | 6 | # TODO: IMPROVE 7 | 8 | # @param {Integer[]} num 9 | # @param {Integer} k 10 | # @return {Integer[]} 11 | def add_to_array_form1(num, k) 12 | (num.join.to_i + k).digits.reverse 13 | end 14 | 15 | # ********************# 16 | # TEST # 17 | # ********************# 18 | 19 | require "test/unit" 20 | class Test_add_to_array_form < Test::Unit::TestCase 21 | def test_ 22 | assert_equal [1, 2, 3, 4], add_to_array_form1([1, 2, 0, 0], 34) 23 | assert_equal [4, 5, 5], add_to_array_form1([2, 7, 4], 181) 24 | assert_equal [1, 0, 2, 1], add_to_array_form1([2, 1, 5], 806) 25 | end 26 | end 27 | 28 | require "benchmark" 29 | 30 | num = [1, 0, 2, 9, 5, 8, 7, 3, 6, 7, 9, 1, 3, 4, 6, 7, 8, 9, 5, 4, 3, 4, 6, 7, 7, 6, 5, 4, 3, 0, 1] 31 | k = 458971347 32 | Benchmark.bm do |x| 33 | x.report("add_to_array_form1: ") { add_to_array_form1(num, k) } 34 | end 35 | 36 | # user system total real 37 | # add_to_array_form1: 0.000033 0.000025 0.000058 ( 0.000054) 38 | -------------------------------------------------------------------------------- /algorithms/ruby/0389-find-the-difference.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 389. Find the Difference 4 | # Easy 5 | # https://leetcode.com/problems/find-the-difference 6 | 7 | =begin 8 | You are given two strings s and t. 9 | 10 | String t is generated by random shuffling string s and then add one more letter at a random position. 11 | Return the letter that was added to t. 12 | 13 | Example 1: 14 | Input: s = "abcd", t = "abcde" 15 | Output: "e" 16 | Explanation: 'e' is the letter that was added. 17 | 18 | Example 2: 19 | Input: s = "", t = "y" 20 | Output: "y" 21 | 22 | Constraints: 23 | 0 <= s.length <= 1000 24 | t.length == s.length + 1 25 | s and t consist of lowercase English letters. 26 | =end 27 | 28 | # @param {String} s 29 | # @param {String} t 30 | # @return {Character} 31 | def find_the_difference(s, t) 32 | (s + t).bytes.reduce(:^).chr 33 | end 34 | 35 | # **************** # 36 | # TEST # 37 | # **************** # 38 | 39 | require "test/unit" 40 | class Test_find_the_difference < Test::Unit::TestCase 41 | def test_ 42 | assert_equal "e", find_the_difference("abcd", "abcde") 43 | assert_equal "y", find_the_difference("", "y") 44 | end 45 | end 46 | -------------------------------------------------------------------------------- /algorithms/python3/0443-string-compression.py: -------------------------------------------------------------------------------- 1 | # 443. String Compression 2 | # https://leetcode.com/problems/string-compression 3 | 4 | class Solution: 5 | def compress(self, chars: list[str]) -> int: 6 | n = len(chars) 7 | 8 | if n == 1: 9 | return 1 10 | 11 | i = 0 12 | j = 0 13 | count = 0 14 | 15 | while i < n: 16 | count += 1 17 | 18 | if i == n - 1 or chars[i + 1] != chars[i]: 19 | chars[j] = chars[i] 20 | j += 1 21 | 22 | if count > 1: 23 | for char in str(count): 24 | chars[j] = char 25 | j += 1 26 | 27 | count = 0 28 | 29 | i += 1 30 | 31 | return j 32 | 33 | # ********************# 34 | # TEST # 35 | # ********************# 36 | 37 | import unittest 38 | 39 | class TestStringMethods(unittest.TestCase): 40 | def test_addBinary(self): 41 | self.assertEqual(Solution.compress(self, ["a", "a", "b", "b", "c", "c", "c"]), 6) 42 | self.assertEqual(Solution.compress(self, ["a"]), 1) 43 | self.assertEqual(Solution.compress(self, ["a", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b"]), 4) 44 | 45 | if __name__ == '__main__': 46 | unittest.main() -------------------------------------------------------------------------------- /algorithms/ruby/0100-same-tree.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 100. Same Tree 4 | # https://leetcode.com/problems/same-tree/ 5 | # Easy 6 | 7 | =begin 8 | Given the roots of two binary trees p and q, write a function to check if they are the same or not. 9 | 10 | Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. 11 | 12 | Example 1: 13 | Input: p = [1,2,3], q = [1,2,3] 14 | Output: true 15 | 16 | Example 2: 17 | Input: p = [1,2], q = [1,null,2] 18 | Output: false 19 | 20 | Example 3: 21 | Input: p = [1,2,1], q = [1,1,2] 22 | Output: false 23 | =end 24 | 25 | # Definition for a binary tree node. 26 | # class TreeNode 27 | # attr_accessor :val, :left, :right 28 | # def initialize(val = 0, left = nil, right = nil) 29 | # @val = val 30 | # @left = left 31 | # @right = right 32 | # end 33 | # end 34 | # @param {TreeNode} p 35 | # @param {TreeNode} q 36 | # @return {Boolean} 37 | def is_same_tree(p, q) 38 | return true if p.nil? && q.nil? 39 | return false if p.nil? || q.nil? || p.val != q.val 40 | 41 | p.val == q.val && is_same_tree(p.left, q.left) && is_same_tree(p.right, q.right) 42 | end 43 | -------------------------------------------------------------------------------- /algorithms/ruby/1155-number-of-dice-rolls-with-target-sum.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 1155. Number of Dice Rolls With Target Sum 4 | # https://leetcode.com/problems/number-of-dice-rolls-with-target-sum 5 | 6 | # @param {Integer} n 7 | # @param {Integer} k 8 | # @param {Integer} target 9 | # @return {Integer} 10 | def num_rolls_to_target(n, k, target) 11 | dp = Array.new(n).map { |x| Array.new(target + 1, 0) } 12 | 13 | # fill first row 14 | (1..target).each do |cell| 15 | dp[0][cell] = 1 if k >= cell 16 | end 17 | 18 | # fill the rest rows 19 | 20 | (1...n).each do |row| 21 | (1..target).each do |cell| 22 | (1..k).each do |i| 23 | dp[row][cell] += dp[row - 1][cell - i] if cell - i >= 0 24 | end 25 | end 26 | end 27 | 28 | dp[n - 1][target] % (10**9 + 7) 29 | end 30 | 31 | # **************** # 32 | # TEST # 33 | # **************** # 34 | 35 | require "test/unit" 36 | class Test_num_rolls_to_target < Test::Unit::TestCase 37 | def test_ 38 | assert_equal 1, num_rolls_to_target(1, 6, 3) 39 | assert_equal 6, num_rolls_to_target(2, 6, 7) 40 | assert_equal 222616187, num_rolls_to_target(30, 30, 500) 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /algorithms/ruby/0054-spiral-matrix.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 54. Spiral Matrix 4 | # https://leetcode.com/problems/spiral-matrix 5 | 6 | =begin 7 | 8 | Given an m x n matrix, return all elements of the matrix in spiral order. 9 | 10 | ### Example 1: 11 | Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] 12 | Output: [1,2,3,6,9,8,7,4,5] 13 | 14 | ### Example 2: 15 | Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] 16 | Output: [1,2,3,4,8,12,11,10,9,5,6,7] 17 | 18 | ### Constraints: 19 | * m == matrix.length 20 | * n == matrix[i].length 21 | * 1 <= m, n <= 10 22 | * -100 <= matrix[i][j] <= 100 23 | 24 | =end 25 | 26 | # @param {Integer[][]} matrix 27 | # @return {Integer[]} 28 | def spiral_order(matrix) 29 | (row = matrix.shift) ? row + spiral_order(matrix.transpose.reverse) : [] 30 | end 31 | 32 | # **************** # 33 | # TEST # 34 | # **************** # 35 | 36 | require "test/unit" 37 | class Test_spiral_order < Test::Unit::TestCase 38 | def test_ 39 | assert_equal [1, 2, 3, 6, 9, 8, 7, 4, 5], spiral_order([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) 40 | assert_equal [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7], spiral_order([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /algorithms/ruby/2348-number-of-zero-filled-subarrays.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 2348. Number of Zero-Filled Subarrays 4 | # https://leetcode.com/problems/number-of-zero-filled-subarrays 5 | 6 | =begin 7 | 8 | Given an integer array nums, return the number of subarrays filled with 0. 9 | 10 | A subarray is a contiguous non-empty sequence of elements within an array. 11 | 12 | ### Constraints: 13 | 14 | * 1 <= nums.length <= 105 15 | * -109 <= nums[i] <= 109 16 | 17 | =end 18 | 19 | # Runtime 202 ms, Beats 100% 20 | # Memory 223 MB, Beats 100% 21 | # @param {Integer[]} nums 22 | # @return {Integer} 23 | def zero_filled_subarray(nums) 24 | res = i = j = 0 25 | 26 | while i < nums.size 27 | j = i + 1 if nums[i] != 0 28 | res += i - j + 1 29 | i += 1 30 | end 31 | 32 | res 33 | end 34 | 35 | # **************** # 36 | # TEST # 37 | # **************** # 38 | 39 | require "test/unit" 40 | class Test_zero_filled_subarray < Test::Unit::TestCase 41 | def test_ 42 | assert_equal 6, zero_filled_subarray([1, 3, 0, 0, 2, 0, 0, 4]) 43 | assert_equal 9, zero_filled_subarray([0, 0, 0, 2, 0, 0]) 44 | assert_equal 0, zero_filled_subarray([2, 10, 2019]) 45 | end 46 | end 47 | -------------------------------------------------------------------------------- /algorithms/ruby/1162-as-far-from-land-as-possible.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 1162. As Far from Land as Possible 4 | # https://leetcode.com/problems/as-far-from-land-as-possible 5 | 6 | # @param {Integer[][]} grid 7 | # @return {Integer} 8 | def max_distance(grid) 9 | queue = [] 10 | grid.each_with_index { |row, i| 11 | row.each_with_index { |cell, j| 12 | queue << [i, j] if cell == 1 13 | } 14 | } 15 | n = grid.size 16 | hop_count = -1 17 | until queue.empty? 18 | queue.size.times { 19 | i, j = queue.shift 20 | [[i + 1, j], [i - 1, j], [i, j + 1], [i, j - 1]].each { |ii, jj| 21 | next if !ii.between?(0, n - 1) || !jj.between?(0, n - 1) || !grid[ii][jj].zero? 22 | queue << [ii, jj] 23 | grid[ii][jj] = 2 24 | } 25 | } 26 | hop_count += 1 27 | end 28 | hop_count.zero? ? -1 : hop_count 29 | end 30 | 31 | # **************** # 32 | # TEST # 33 | # **************** # 34 | 35 | require "test/unit" 36 | class Test_max_distance < Test::Unit::TestCase 37 | def test_ 38 | assert_equal 2, max_distance([[1, 0, 1], [0, 0, 0], [1, 0, 1]]) 39 | assert_equal 4, max_distance([[1, 0, 0], [0, 0, 0], [0, 0, 0]]) 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /algorithms/ruby/0867-transpose-matrix.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 867. Transpose Matrix 4 | # Easy 5 | # https://leetcode.com/problems/transpose-matrix 6 | 7 | =begin 8 | Given a 2D integer array matrix, return the transpose of matrix. 9 | The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. 10 | 11 | Example 1: 12 | Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] 13 | Output: [[1,4,7],[2,5,8],[3,6,9]] 14 | 15 | Example 2: 16 | Input: matrix = [[1,2,3],[4,5,6]] 17 | Output: [[1,4],[2,5],[3,6]] 18 | 19 | Constraints: 20 | m == matrix.length 21 | n == matrix[i].length 22 | 1 <= m, n <= 1000 23 | 1 <= m * n <= 105 24 | -109 <= matrix[i][j] <= 109 25 | =end 26 | 27 | # @param {Integer[][]} matrix 28 | # @return {Integer[][]} 29 | def transpose(matrix) 30 | matrix.transpose 31 | end 32 | 33 | # **************** # 34 | # TEST # 35 | # **************** # 36 | 37 | require "test/unit" 38 | class Test_transpose < Test::Unit::TestCase 39 | def test_ 40 | assert_equal [[1, 4, 7], [2, 5, 8], [3, 6, 9]], transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) 41 | assert_equal [[1, 4], [2, 5], [3, 6]], transpose([[1, 2, 3], [4, 5, 6]]) 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /algorithms/ruby/0136-single-number.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 136. Single Number 4 | # https://leetcode.com/problems/single-number 5 | # Easy 6 | 7 | =begin 8 | Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. 9 | 10 | You must implement a solution with a linear runtime complexity and use only constant extra space. 11 | 12 | Example 1: 13 | Input: nums = [2,2,1] 14 | Output: 1 15 | 16 | Example 2: 17 | Input: nums = [4,1,2,1,2] 18 | Output: 4 19 | 20 | Example 3: 21 | Input: nums = [1] 22 | Output: 1 23 | 24 | Constraints: 25 | 1 <= nums.length <= 3 * 104 26 | -3 * 104 <= nums[i] <= 3 * 104 27 | Each element in the array appears twice except for one element which appears only once. 28 | =end 29 | 30 | # @param {Integer[]} nums 31 | # @return {Integer} 32 | def single_number(nums) 33 | nums.reduce(&:^) 34 | end 35 | 36 | # ********************# 37 | # TEST # 38 | # ********************# 39 | 40 | require "test/unit" 41 | class Test_single_number < Test::Unit::TestCase 42 | def test_ 43 | assert_equal 1, single_number([2, 2, 1]) 44 | assert_equal 4, single_number([4, 1, 2, 1, 2]) 45 | assert_equal 1, single_number([1]) 46 | end 47 | end 48 | -------------------------------------------------------------------------------- /algorithms/ruby/0796-rotate-string.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 796. Rotate String 4 | # Easy 5 | # https://leetcode.com/problems/rotate-string 6 | 7 | =begin 8 | Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s. 9 | A shift on s consists of moving the leftmost character of s to the rightmost position. 10 | * For example, if s = "abcde", then it will be "bcdea" after one shift. 11 | 12 | Example 1: 13 | Input: s = "abcde", goal = "cdeab" 14 | Output: true 15 | Example 2: 16 | Input: s = "abcde", goal = "abced" 17 | Output: false 18 | 19 | Constraints: 20 | * 1 <= s.length, goal.length <= 100 21 | * s and goal consist of lowercase English letters. 22 | =end 23 | 24 | # @param {String} s 25 | # @param {String} goal 26 | # @return {Boolean} 27 | def rotate_string(s, goal) 28 | return false if s.length != goal.length 29 | (s + s).include?(goal) 30 | end 31 | 32 | # **************** # 33 | # TEST # 34 | # **************** # 35 | 36 | require "test/unit" 37 | class Test_rotate_string < Test::Unit::TestCase 38 | def test_ 39 | assert_equal true, rotate_string("abcde", "cdeab") 40 | assert_equal false, rotate_string("abcde", "abced") 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /algorithms/ruby/0024-swap-nodes-in-pairs.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 24. Swap Nodes in Pairs 4 | # https://leetcode.com/problems/swap-nodes-in-pairs 5 | # Medium 6 | 7 | =begin 8 | Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.) 9 | 10 | Example 1: 11 | Input: head = [1,2,3,4] 12 | Output: [2,1,4,3] 13 | 14 | Example 2: 15 | Input: head = [] 16 | Output: [] 17 | 18 | Example 3: 19 | Input: head = [1] 20 | Output: [1] 21 | 22 | Constraints: 23 | The number of nodes in the list is in the range [0, 100]. 24 | 0 <= Node.val <= 100 25 | =end 26 | 27 | # Definition for singly-linked list. 28 | # class ListNode 29 | # attr_accessor :val, :next 30 | # def initialize(val = 0, _next = nil) 31 | # @val = val 32 | # @next = _next 33 | # end 34 | # end 35 | # @param {ListNode} head 36 | # @return {ListNode} 37 | 38 | def swap_pairs(head) 39 | return head if !head || !head.next 40 | 41 | next_node, next_segment = head.next, head.next.next 42 | next_node.next = head 43 | head_next = swap_pairs(next_segment) 44 | head.next = head_next 45 | 46 | next_node 47 | end 48 | -------------------------------------------------------------------------------- /algorithms/ruby/1351-count-negative-numbers-in-a-sorted-matrix.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix 4 | # 1351. Count Negative Numbers in a Sorted Matrix 5 | # Easy 6 | 7 | =begin 8 | Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid. 9 | 10 | Example 1: 11 | Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]] 12 | Output: 8 13 | Explanation: There are 8 negatives number in the matrix. 14 | 15 | Example 2: 16 | Input: grid = [[3,2],[1,0]] 17 | Output: 0 18 | =end 19 | 20 | # @param {Integer[][]} grid 21 | # @return {Integer} 22 | def count_negatives(grid) 23 | grid.reduce(0) do |sum, row| 24 | row.each do |column| 25 | sum += 1 if column < 0 26 | end 27 | sum 28 | end 29 | end 30 | 31 | # **************** # 32 | # TEST # 33 | # **************** # 34 | 35 | require "test/unit" 36 | class Test_count_negatives < Test::Unit::TestCase 37 | def test_ 38 | assert_equal 8, count_negatives([[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]]) 39 | assert_equal 0, count_negatives([[3, 2], [1, 0]]) 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /algorithms/ruby/0022-generate-parentheses.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 22. Generate Parentheses 4 | # https://leetcode.com/problems/generate-parentheses 5 | # Medium 6 | 7 | =begin 8 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 9 | 10 | Example 1: 11 | Input: n = 3 12 | Output: ["((()))","(()())","(())()","()(())","()()()"] 13 | 14 | Example 2: 15 | Input: n = 1 16 | Output: ["()"] 17 | 18 | Constraints: 19 | * 1 <= n <= 8 20 | =end 21 | 22 | # @param {Integer} n 23 | # @return {String[]} 24 | def generate_parenthesis(n) 25 | @res = [] 26 | backtrack("", 0, 0, n) 27 | @res 28 | end 29 | 30 | def backtrack(curr, open, close, n) 31 | @res << curr and return if curr.length == n * 2 32 | backtrack(curr + "(", open + 1, close, n) if open < n 33 | backtrack(curr + ")", open, close + 1, n) if close < open 34 | end 35 | 36 | # ********************# 37 | # TEST # 38 | # ********************# 39 | 40 | require "test/unit" 41 | class Test_generate_parenthesis < Test::Unit::TestCase 42 | def test_ 43 | assert_equal ["((()))", "(()())", "(())()", "()(())", "()()()"], generate_parenthesis(3) 44 | assert_equal ["()"], generate_parenthesis(1) 45 | end 46 | end 47 | -------------------------------------------------------------------------------- /algorithms/ruby/0048-rotate-image.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 48. Rotate Image 4 | # https://leetcode.com/problems/rotate-image 5 | # Medium 6 | 7 | =begin 8 | You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). 9 | 10 | You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. 11 | 12 | Example 1: 13 | Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] 14 | Output: [[7,4,1],[8,5,2],[9,6,3]] 15 | 16 | Example 2: 17 | Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] 18 | Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] 19 | 20 | Constraints: 21 | n == matrix.length == matrix[i].length 22 | 1 <= n <= 20 23 | -1000 <= matrix[i][j] <= 1000 24 | =end 25 | 26 | # @param {Integer[][]} matrix 27 | # @return {Void} Do not return anything, modify matrix in-place instead. 28 | def rotate(matrix, z = matrix.size - 1) 29 | for i in 0...(matrix.size / 2) 30 | for j in i..(z - i - 1) 31 | matrix[ i][j], matrix[j][z - i], matrix[z - i][z - j], matrix[z - j][ i] = 32 | matrix[z - j][i], matrix[i][ j], matrix[ j][z - i], matrix[z - i][z - j] 33 | end 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /algorithms/ruby/0230-kth-smallest-element-in-a-bst.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 230. Kth Smallest Element in a BST 4 | # https://leetcode.com/problems/kth-smallest-element-in-a-bst 5 | # Medium 6 | 7 | =begin 8 | 9 | Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree. 10 | 11 | ### Example 1: 12 | Input: root = [3,1,4,null,2], k = 1 13 | Output: 1 14 | 15 | ### Example 2: 16 | Input: root = [5,3,6,2,4,null,null,1], k = 3 17 | Output: 3 18 | 19 | ### Constraints: 20 | * The number of nodes in the tree is n. 21 | * 1 <= k <= n <= 104 22 | * 0 <= Node.val <= 104 23 | 24 | =end 25 | 26 | # Definition for a binary tree node. 27 | # class TreeNode 28 | # attr_accessor :val, :left, :right 29 | # def initialize(val = 0, left = nil, right = nil) 30 | # @val = val 31 | # @left = left 32 | # @right = right 33 | # end 34 | # end 35 | # @param {TreeNode} root 36 | # @param {Integer} k 37 | # @return {Integer} 38 | def kth_smallest(root, k) 39 | find = -> root { root && (find[root.left] or 40 | (k -= 1) == 0 ? root.val : 41 | find[root.right]) } 42 | find[root] 43 | end 44 | -------------------------------------------------------------------------------- /algorithms/ruby/0119-pascals-triangle-ii.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 119. Pascal's Triangle II 4 | # Easy 5 | # https://leetcode.com/problems/pascals-triangle-ii 6 | 7 | =begin 8 | Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. 9 | In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: 10 | 11 | Example 1: 12 | Input: rowIndex = 3 13 | Output: [1,3,3,1] 14 | 15 | Example 2: 16 | Input: rowIndex = 0 17 | Output: [1] 18 | 19 | Example 3: 20 | Input: rowIndex = 1 21 | Output: [1,1] 22 | 23 | Constraints: 24 | 0 <= rowIndex <= 33 25 | =end 26 | 27 | # @param {Integer} row_index 28 | # @return {Integer[]} 29 | def get_row(row_index) 30 | return [1] if row_index == 0 31 | 32 | ans = [1] 33 | temp = 1 34 | for i in 1...row_index do 35 | temp = temp * (row_index - i + 1) / i 36 | ans << temp 37 | end 38 | ans << 1 39 | ans 40 | end 41 | 42 | # **************** # 43 | # TEST # 44 | # **************** # 45 | 46 | require "test/unit" 47 | class Test_get_row < Test::Unit::TestCase 48 | def test_ 49 | assert_equal [1, 3, 3, 1], get_row(3) 50 | assert_equal [1], get_row(0) 51 | assert_equal [1, 1], get_row(1) 52 | end 53 | end 54 | -------------------------------------------------------------------------------- /algorithms/ruby/0201-bitwise-and-of-numbers-range.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 201. Bitwise AND of Numbers Range 4 | # https://leetcode.com/problems/bitwise-and-of-numbers-range 5 | # Medium 6 | 7 | =begin 8 | Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive. 9 | 10 | Example 1: 11 | Input: left = 5, right = 7 12 | Output: 4 13 | 14 | Example 2: 15 | Input: left = 0, right = 0 16 | Output: 0 17 | 18 | Example 3: 19 | Input: left = 1, right = 2147483647 20 | Output: 0 21 | 22 | Constraints: 23 | 0 <= left <= right <= 231 - 1 24 | =end 25 | 26 | # @param {Integer} left 27 | # @param {Integer} right 28 | # @return {Integer} 29 | def range_bitwise_and(left, right) 30 | shift = 0 31 | while left != right 32 | left >>= 1 33 | right >>= 1 34 | shift += 1 35 | end 36 | left << shift 37 | end 38 | 39 | # **************** # 40 | # TEST # 41 | # **************** # 42 | 43 | require "test/unit" 44 | class Test_range_bitwise_and < Test::Unit::TestCase 45 | def test_ 46 | assert_equal 4, range_bitwise_and(5, 7) 47 | assert_equal 0, range_bitwise_and(0, 0) 48 | assert_equal 0, range_bitwise_and(1, 2147483647) 49 | end 50 | end 51 | -------------------------------------------------------------------------------- /algorithms/ruby/2409-count-days-spent-together.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 2409. Count Days Spent Together 4 | # https://leetcode.com/problems/count-days-spent-together 5 | 6 | # @param {String} arrive_alice 7 | # @param {String} leave_alice 8 | # @param {String} arrive_bob 9 | # @param {String} leave_bob 10 | # @return {Integer} 11 | def count_days_together(arrive_alice, leave_alice, arrive_bob, leave_bob) 12 | return 0 if arrive_alice > leave_bob || arrive_bob > leave_alice 13 | 14 | start_date = [arrive_alice, arrive_bob].max 15 | end_date = [leave_alice, leave_bob].min 16 | days(end_date) - days(start_date) + 1 17 | end 18 | 19 | def days(date) 20 | days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] 21 | month, day = date.split("-").map(&:to_i) 22 | (0..(month - 2)).reduce(day) do |total, i| 23 | total + days_per_month[i] 24 | end 25 | end 26 | 27 | # ********************# 28 | # TEST # 29 | # ********************# 30 | 31 | require "test/unit" 32 | class Test_count_days_together < Test::Unit::TestCase 33 | def test_ 34 | assert_equal 3, count_days_together("08-15", "08-18", "08-16", "08-19") 35 | assert_equal 0, count_days_together("10-01", "10-31", "11-01", "12-31") 36 | end 37 | end 38 | -------------------------------------------------------------------------------- /algorithms/python3/2462-total-cost-to-hire-k-workers.py: -------------------------------------------------------------------------------- 1 | # 2462. Total Cost to Hire K Workers 2 | # https://leetcode.com/problems/total-cost-to-hire-k-workers 3 | # Medium 4 | 5 | from heapq import heapify, heappush, heappop 6 | 7 | class Solution: 8 | def totalCost(self, costs: list[int], k: int, candidates: int) -> int: 9 | q = costs[:candidates] 10 | qq = costs[max(candidates, len(costs)-candidates):] 11 | heapify(q) 12 | heapify(qq) 13 | ans = 0 14 | i, ii = candidates, len(costs)-candidates-1 15 | for _ in range(k): 16 | if not qq or q and q[0] <= qq[0]: 17 | ans += heappop(q) 18 | if i <= ii: 19 | heappush(q, costs[i]) 20 | i += 1 21 | else: 22 | ans += heappop(qq) 23 | if i <= ii: 24 | heappush(qq, costs[ii]) 25 | ii -= 1 26 | return ans 27 | 28 | # ********************# 29 | # TEST # 30 | # ********************# 31 | 32 | import unittest 33 | 34 | class TestMinimumTime(unittest.TestCase): 35 | def test_minimumTime(self): 36 | self.assertEqual(Solution.totalCost(self, [17,12,10,2,7,2,11,20,8], 3, 4), 11) 37 | self.assertEqual(Solution.totalCost(self, [1,2,4,1], 3, 3), 4) 38 | 39 | if __name__ == '__main__': 40 | unittest.main() -------------------------------------------------------------------------------- /algorithms/ruby/0912-sort-an-array.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 912. Sort an Array 4 | # https://leetcode.com/problems/sort-an-array 5 | 6 | # @param {Integer[]} nums 7 | # @return {Integer[]} 8 | def sort_array(nums) 9 | in_place_quick_sort(nums, 0, nums.length - 1) 10 | nums 11 | end 12 | 13 | def in_place_quick_sort(nums, l, r) 14 | return if l >= r 15 | 16 | pivot = nums[rand(l..r)] 17 | pl, pr = partition(nums, l, r, pivot) 18 | in_place_quick_sort(nums, l, pl - 1) 19 | in_place_quick_sort(nums, pr + 1, r) 20 | end 21 | 22 | def partition(nums, l, r, pivot) 23 | p0, p1, p2 = l, l, r 24 | while p1 <= p2 25 | if nums[p1] < pivot 26 | nums[p0], nums[p1] = nums[p1], nums[p0] 27 | p0 += 1 28 | p1 += 1 29 | elsif nums[p1] == pivot 30 | p1 += 1 31 | else 32 | nums[p1], nums[p2] = nums[p2], nums[p1] 33 | p2 -= 1 34 | end 35 | end 36 | 37 | [p0, p2] 38 | end 39 | 40 | # ********************# 41 | # TEST # 42 | # ********************# 43 | 44 | require "test/unit" 45 | class Test_sort_array < Test::Unit::TestCase 46 | def test_ 47 | assert_equal [1, 2, 3, 5], sort_array([5, 2, 3, 1]) 48 | assert_equal [0, 0, 1, 1, 2, 5], sort_array([5, 1, 1, 2, 0, 0]) 49 | end 50 | end 51 | -------------------------------------------------------------------------------- /algorithms/ruby/0111-minimum-depth-of-binary-tree.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 111. Minimum Depth of Binary Tree 4 | # Easy 5 | # https://leetcode.com/problems/minimum-depth-of-binary-tree 6 | 7 | =begin 8 | Given a binary tree, find its minimum depth. 9 | The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 10 | Note: A leaf is a node with no children. 11 | 12 | Example 1: 13 | Input: root = [3,9,20,null,null,15,7] 14 | Output: 2 15 | 16 | Example 2: 17 | Input: root = [2,null,3,null,4,null,5,null,6] 18 | Output: 5 19 | 20 | Constraints: 21 | * The number of nodes in the tree is in the range [0, 105]. 22 | * -1000 <= Node.val <= 1000 23 | =end 24 | 25 | # Definition for a binary tree node. 26 | # class TreeNode 27 | # attr_accessor :val, :left, :right 28 | # def initialize(val = 0, left = nil, right = nil) 29 | # @val = val 30 | # @left = left 31 | # @right = right 32 | # end 33 | # end 34 | # @param {TreeNode} root 35 | # @return {Integer} 36 | def min_depth(root) 37 | return 0 if root.nil? 38 | return 1 + min_depth(root.right) if root.left.nil? 39 | return 1 + min_depth(root.left) if root.right.nil? 40 | 1 + [min_depth(root.left), min_depth(root.right)].min 41 | end 42 | -------------------------------------------------------------------------------- /algorithms/ruby/0118-pascals-triangle.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 118. Pascal's Triangle 4 | # Easy 5 | # https://leetcode.com/problems/pascals-triangle 6 | 7 | =begin 8 | Given an integer numRows, return the first numRows of Pascal's triangle. 9 | In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: 10 | 11 | Example 1: 12 | Input: numRows = 5 13 | Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] 14 | 15 | Example 2: 16 | Input: numRows = 1 17 | Output: [[1]] 18 | 19 | Constraints: 20 | * 1 <= numRows <= 30 21 | =end 22 | 23 | # @param {Integer} num_rows 24 | # @return {Integer[][]} 25 | def generate(num_rows) 26 | result = [[1]] 27 | 28 | (num_rows - 1).times do 29 | prev_row = result.last 30 | row = [1] 31 | 32 | 0.upto(prev_row.size - 2) do |i| 33 | row << prev_row[i] + prev_row[i + 1] 34 | end 35 | 36 | row << 1 37 | result << row 38 | end 39 | 40 | result 41 | end 42 | 43 | # **************** # 44 | # TEST # 45 | # **************** # 46 | 47 | require "test/unit" 48 | class Test_generate < Test::Unit::TestCase 49 | def test_ 50 | assert_equal [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]], generate(5) 51 | assert_equal [[1]], generate(1) 52 | end 53 | end 54 | -------------------------------------------------------------------------------- /algorithms/ruby/0023-merge-k-sorted-lists.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 23. Merge k Sorted Lists 4 | # https://leetcode.com/problems/merge-k-sorted-lists 5 | 6 | =begin 7 | 8 | You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. 9 | Merge all the linked-lists into one sorted linked-list and return it. 10 | 11 | # Constraints: 12 | 13 | * k == lists.length 14 | * 0 <= k <= 104 15 | * 0 <= lists[i].length <= 500 16 | * -104 <= lists[i][j] <= 104 17 | * lists[i] is sorted in ascending order. 18 | * The sum of lists[i].length will not exceed 104. 19 | 20 | =end 21 | 22 | # Definition for singly-linked list. 23 | # class ListNode 24 | # attr_accessor :val, :next 25 | # def initialize(val = 0, _next = nil) 26 | # @val = val 27 | # @next = _next 28 | # end 29 | # end 30 | # @param {ListNode[]} lists 31 | # @return {ListNode} 32 | def merge_k_lists(lists) 33 | values = [] 34 | 35 | lists.each do |list| 36 | while list 37 | values << list.val 38 | list = list.next 39 | end 40 | end 41 | 42 | values.sort! 43 | head = dumphead = ListNode.new(nil) 44 | 45 | values.each do |value| 46 | head.next = ListNode.new(value) 47 | head = head.next 48 | end 49 | 50 | dumphead.next 51 | end 52 | -------------------------------------------------------------------------------- /algorithms/ruby/0073-set-matrix-zeroes.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 73. Set Matrix Zeroes 4 | # https://leetcode.com/problems/set-matrix-zeroes 5 | # Medium 6 | 7 | =begin 8 | Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's. 9 | 10 | You must do it in place. 11 | 12 | Example 1: 13 | Input: matrix = [[1,1,1],[1,0,1],[1,1,1]] 14 | Output: [[1,0,1],[0,0,0],[1,0,1]] 15 | 16 | Example 2: 17 | Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]] 18 | Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]] 19 | 20 | Constraints: 21 | m == matrix.length 22 | n == matrix[0].length 23 | 1 <= m, n <= 200 24 | -231 <= matrix[i][j] <= 231 - 1 25 | =end 26 | 27 | # @param {Integer[][]} matrix 28 | # @return {Void} Do not return anything, modify matrix in-place instead. 29 | def set_zeroes(matrix) 30 | rows = Array.new(matrix.size, false) 31 | columns = Array.new(matrix[0].size, false) 32 | 33 | (0...matrix.size).each do |i| 34 | (0...matrix[0].size).each do |j| 35 | if matrix[i][j].zero? 36 | rows[i] = true 37 | columns[j] = true 38 | end 39 | end 40 | end 41 | 42 | (0...matrix.size).each do |i| 43 | (0...matrix[0].size).each do |j| 44 | matrix[i][j] = 0 if rows[i] || columns[j] 45 | end 46 | end 47 | end 48 | -------------------------------------------------------------------------------- /algorithms/ruby/0046-permutations.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 46. Permutations 4 | # https://leetcode.com/problems/permutations 5 | # Medium 6 | 7 | =begin 8 | Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order. 9 | 10 | Example 1: 11 | Input: nums = [1,2,3] 12 | Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] 13 | 14 | Example 2: 15 | Input: nums = [0,1] 16 | Output: [[0,1],[1,0]] 17 | 18 | Example 3: 19 | Input: nums = [1] 20 | Output: [[1]] 21 | 22 | Constraints: 23 | 1 <= nums.length <= 6 24 | -10 <= nums[i] <= 10 25 | All the integers of nums are unique. 26 | =end 27 | 28 | # @param {Integer[]} nums 29 | # @return {Integer[][]} 30 | def permute(nums, temp = [], res = []) 31 | nums.empty? ? res << temp : nums.each { |num| permute(nums - [num], temp + [num], res) } 32 | res 33 | end 34 | 35 | # ********************# 36 | # TEST # 37 | # ********************# 38 | 39 | require "test/unit" 40 | class Test_combination_sumpermute < Test::Unit::TestCase 41 | def test_ 42 | assert_equal [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]], permute([1, 2, 3]) 43 | assert_equal [[0, 1], [1, 0]], permute([0, 1]) 44 | assert_equal [[1]], permute([1]) 45 | end 46 | end 47 | -------------------------------------------------------------------------------- /algorithms/ruby/0050-powx-n.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 50. Pow(x, n) 4 | # https://leetcode.com/problems/powx-n 5 | # Medium 6 | 7 | =begin 8 | Implement pow(x, n), which calculates x raised to the power n (i.e., x**n). 9 | 10 | Example 1: 11 | Input: x = 2.00000, n = 10 12 | Output: 1024.00000 13 | 14 | Example 2: 15 | Input: x = 2.10000, n = 3 16 | Output: 9.26100 17 | 18 | Example 3: 19 | Input: x = 2.00000, n = -2 20 | Output: 0.25000 21 | Explanation: 2-2 = 1/22 = 1/4 = 0.25 22 | 23 | Constraints: 24 | -100.0 < x < 100.0 25 | -231 <= n <= 231-1 26 | n is an integer. 27 | Either x is not zero or n > 0. 28 | -104 <= xn <= 104 29 | =end 30 | 31 | # @param {Float} x 32 | # @param {Integer} n 33 | # @return {Float} 34 | def pow(x, n) 35 | return 1 if n.zero? 36 | return (1 / pow(x, -n)) if n.negative? 37 | return x * pow(x, n - 1) if n.odd? 38 | pow(x * x, n / 2) 39 | end 40 | 41 | def my_pow(x, n) 42 | pow(x, n).round(5) 43 | end 44 | 45 | # **************** # 46 | # TEST # 47 | # **************** # 48 | 49 | require "test/unit" 50 | class Test_my_pow < Test::Unit::TestCase 51 | def test_ 52 | assert_equal 1024.00000, my_pow(2.00000, 10) 53 | assert_equal 9.26100, my_pow(2.10000, 3) 54 | assert_equal 0.25000, my_pow(2.00000, -2) 55 | end 56 | end 57 | -------------------------------------------------------------------------------- /algorithms/ruby/0876-middle-of-the-linked-list.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 876. Middle of the Linked List 4 | # https://leetcode.com/problems/middle-of-the-linked-list 5 | # Easy 6 | # TODO: Write Tests 7 | 8 | =begin 9 | 10 | Given the head of a singly linked list, return the middle node of the linked list. 11 | 12 | If there are two middle nodes, return the second middle node. 13 | 14 | ### Example 1: 15 | Input: head = [1,2,3,4,5] 16 | Output: [3,4,5] 17 | Explanation: The middle node of the list is node 3. 18 | 19 | ### Example 2: 20 | Input: head = [1,2,3,4,5,6] 21 | Output: [4,5,6] 22 | Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one. 23 | 24 | ### Constraints: 25 | * The number of nodes in the list is in the range [1, 100]. 26 | * 1 <= Node.val <= 100 27 | 28 | =end 29 | 30 | # Definition for singly-linked list. 31 | # class ListNode 32 | # attr_accessor :val, :next 33 | # def initialize(val = 0, _next = nil) 34 | # @val = val 35 | # @next = _next 36 | # end 37 | # end 38 | # @param {ListNode} head 39 | # @return {ListNode} 40 | def middle_node(head) 41 | slow = fast = head 42 | while fast != nil && fast.next != nil 43 | slow = slow.next 44 | fast = fast.next.next 45 | end 46 | slow 47 | end 48 | -------------------------------------------------------------------------------- /algorithms/ruby/1207-unique-number-of-occurrences.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 1207. Unique Number of Occurrences 4 | # https://leetcode.com/problems/unique-number-of-occurrences 5 | # Easy 6 | 7 | =begin 8 | Given an array of integers arr, return true if the number of occurrences of each value in the array is unique or false otherwise. 9 | 10 | Example 1: 11 | Input: arr = [1,2,2,1,1,3] 12 | Output: true 13 | Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. 14 | 15 | Example 2: 16 | Input: arr = [1,2] 17 | Output: false 18 | 19 | Example 3: 20 | Input: arr = [-3,0,1,-3,1,1,1,-3,10,0] 21 | Output: true 22 | 23 | Constraints: 24 | 1 <= arr.length <= 1000 25 | -1000 <= arr[i] <= 1000 26 | =end 27 | 28 | # @param {Integer[]} arr 29 | # @return {Boolean} 30 | def unique_occurrences(arr) 31 | !arr.tally.values.uniq! 32 | end 33 | 34 | # **************** # 35 | # TEST # 36 | # **************** # 37 | 38 | require "test/unit" 39 | class Test_unique_occurrences < Test::Unit::TestCase 40 | def test_ 41 | assert_equal true, unique_occurrences([1, 2, 2, 1, 1, 3]) 42 | assert_equal false, unique_occurrences([1, 2]) 43 | assert_equal true, unique_occurrences([-3, 0, 1, -3, 1, 1, 1, -3, 10, 0]) 44 | end 45 | end 46 | -------------------------------------------------------------------------------- /algorithms/ruby/0094-binary-tree-inorder-traversal.rb: -------------------------------------------------------------------------------- 1 | # 94. Binary Tree Inorder Traversal 2 | # Easy 3 | # https://leetcode.com/problems/binary-tree-inorder-traversal 4 | 5 | =begin 6 | Given the root of a binary tree, return the inorder traversal of its nodes' values. 7 | 8 | Example 1: 9 | Input: root = [1,null,2,3] 10 | Output: [1,3,2] 11 | 12 | Example 2: 13 | Input: root = [] 14 | Output: [] 15 | 16 | Example 3: 17 | Input: root = [1] 18 | Output: [1] 19 | 20 | Constraints: 21 | The number of nodes in the tree is in the range [0, 100]. 22 | -100 <= Node.val <= 100 23 | =end 24 | 25 | # frozen_string_literal: true 26 | 27 | # Definition for a binary tree node. 28 | # class TreeNode 29 | # attr_accessor :val, :left, :right 30 | # def initialize(val = 0, left = nil, right = nil) 31 | # @val = val 32 | # @left = left 33 | # @right = right 34 | # end 35 | # end 36 | # @param {TreeNode} root 37 | # @return {Integer[]} 38 | def inorder_traversal(root) 39 | ret = [] 40 | stack = [root] 41 | while true 42 | top = stack[-1] 43 | if !top&.left.nil? 44 | stack << top.left 45 | else 46 | t = stack.pop 47 | t = stack.pop if t.nil? 48 | break if t.nil? 49 | ret << t.val 50 | stack << t.right 51 | end 52 | end 53 | ret 54 | end 55 | -------------------------------------------------------------------------------- /algorithms/ruby/0110-balanced-binary-tree.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 110. Balanced Binary Tree 4 | # https://leetcode.com/problems/balanced-binary-tree/ 5 | # Easy 6 | 7 | =begin 8 | 9 | Given a binary tree, determine if it is height-balanced. 10 | 11 | ### Example 1: 12 | Input: root = [3,9,20,null,null,15,7] 13 | Output: true 14 | 15 | ### Example 2: 16 | Input: root = [1,2,2,3,3,null,null,4,4] 17 | Output: false 18 | 19 | ### Example 3: 20 | Input: root = [] 21 | Output: true 22 | 23 | ### Constraints: 24 | * The number of nodes in the tree is in the range [0, 5000]. 25 | * -104 <= Node.val <= 104 26 | 27 | =end 28 | 29 | # Definition for a binary tree node. 30 | # class TreeNode 31 | # attr_accessor :val, :left, :right 32 | # def initialize(val = 0, left = nil, right = nil) 33 | # @val = val 34 | # @left = left 35 | # @right = right 36 | # end 37 | # end 38 | # @param {TreeNode} root 39 | # @return {Boolean} 40 | def is_balanced(root) 41 | balanced_height(root, 0) >= 0 42 | end 43 | 44 | def balanced_height(root, height) 45 | return height unless root 46 | 47 | l = balanced_height(root.left, height + 1) 48 | r = balanced_height(root.right, height + 1) 49 | 50 | return -1 if l == -1 || r == -1 || (l - r).abs > 1 51 | 52 | [l, r].max 53 | end 54 | -------------------------------------------------------------------------------- /algorithms/ruby/0129-sum-root-to-leaf-numbers.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 129. Sum Root to Leaf Numbers 4 | # https://leetcode.com/problems/sum-root-to-leaf-numbers 5 | 6 | =begin 7 | 8 | You are given the root of a binary tree containing digits from 0 to 9 only. 9 | 10 | Each root-to-leaf path in the tree represents a number. 11 | 12 | * For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123. 13 | Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer. 14 | 15 | A leaf node is a node with no children. 16 | 17 | ### Constraints: 18 | 19 | * The number of nodes in the tree is in the range [1, 1000]. 20 | * 0 <= Node.val <= 9 21 | * The depth of the tree will not exceed 10. 22 | 23 | =end 24 | 25 | # Definition for a binary tree node. 26 | # class TreeNode 27 | # attr_accessor :val, :left, :right 28 | # def initialize(val = 0, left = nil, right = nil) 29 | # @val = val 30 | # @left = left 31 | # @right = right 32 | # end 33 | # end 34 | # @param {TreeNode} root 35 | # @return {Integer} 36 | def sum_numbers(root, n = 0) 37 | n, l, r = n * 10 + root.val, root.left, root.right 38 | !l && !r ? n : 39 | (l ? sum_numbers(l, n) : 0) + 40 | (r ? sum_numbers(r, n) : 0) 41 | end 42 | -------------------------------------------------------------------------------- /algorithms/ruby/2444-count-subarrays-with-fixed-bounds.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 2444. Count Subarrays With Fixed Bounds 4 | # https://leetcode.com/problems/count-subarrays-with-fixed-bounds 5 | # Hard 6 | 7 | # @param {Integer[]} nums 8 | # @param {Integer} min_k 9 | # @param {Integer} max_k 10 | # @return {Integer} 11 | def count_subarrays(nums, min_k, max_k) 12 | max_found = min_found = false 13 | start = 0 14 | res = 0 15 | min_index = max_index = 0 16 | nums.each_with_index do |num, i| 17 | unless num.between?(min_k, max_k) 18 | start = i + 1 19 | min_found = max_found = false 20 | else 21 | if num == min_k 22 | min_found = true 23 | min_index = i 24 | end 25 | if num == max_k 26 | max_found = true 27 | max_index = i 28 | end 29 | if min_found && max_found 30 | res += ([min_index, max_index].min - start + 1) 31 | end 32 | end 33 | end 34 | res 35 | end 36 | 37 | # ********************# 38 | # TEST # 39 | # ********************# 40 | 41 | require "test/unit" 42 | class Test_count_subarrays < Test::Unit::TestCase 43 | def test_ 44 | assert_equal 2, count_subarrays([1, 3, 5, 2, 7, 5], 1, 5) 45 | assert_equal 10, count_subarrays([1, 1, 1, 1], 1, 1) 46 | end 47 | end 48 | -------------------------------------------------------------------------------- /algorithms/ruby/0459-repeated-substring-pattern.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 459. Repeated Substring Pattern 4 | # Easy 5 | # https://leetcode.com/problems/repeated-substring-pattern 6 | 7 | =begin 8 | Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. 9 | 10 | Example 1: 11 | Input: s = "abab" 12 | Output: true 13 | Explanation: It is the substring "ab" twice. 14 | 15 | Example 2: 16 | Input: s = "aba" 17 | Output: false 18 | 19 | Example 3: 20 | Input: s = "abcabcabcabc" 21 | Output: true 22 | Explanation: It is the substring "abc" four times or the substring "abcabc" twice. 23 | 24 | Constraints: 25 | 1 <= s.length <= 104 26 | s consists of lowercase English letters. 27 | =end 28 | 29 | # @param {String} s 30 | # @return {Boolean} 31 | def repeated_substring_pattern(s) 32 | str = s + s 33 | str[1...-1].include? s 34 | end 35 | 36 | # **************** # 37 | # TEST # 38 | # **************** # 39 | 40 | require "test/unit" 41 | class Test_repeated_substring_pattern < Test::Unit::TestCase 42 | def test_ 43 | assert_equal true, repeated_substring_pattern("abab") 44 | assert_equal false, repeated_substring_pattern("aba") 45 | assert_equal true, repeated_substring_pattern("abcabcabcabc") 46 | end 47 | end 48 | -------------------------------------------------------------------------------- /algorithms/ruby/0137-single-number-ii.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 137. Single Number II 4 | # https://leetcode.com/problems/single-number-ii 5 | # Medium 6 | 7 | =begin 8 | Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it. 9 | 10 | You must implement a solution with a linear runtime complexity and use only constant extra space. 11 | 12 | Example 1: 13 | Input: nums = [2,2,3,2] 14 | Output: 3 15 | 16 | Example 2: 17 | Input: nums = [0,1,0,1,0,1,99] 18 | Output: 99 19 | 20 | Constraints: 21 | 1 <= nums.length <= 3 * 104 22 | -231 <= nums[i] <= 231 - 1 23 | Each element in nums appears exactly three times except for one element which appears once. 24 | =end 25 | 26 | # @param {Integer[]} nums 27 | # @return {Integer} 28 | def single_number(nums) 29 | one = 0 30 | two = 0 31 | 32 | nums.each do |num| 33 | one = (one ^ num) & ~two 34 | two = (two ^ num) & ~one 35 | end 36 | 37 | one 38 | end 39 | 40 | # **************** # 41 | # TEST # 42 | # **************** # 43 | 44 | require "test/unit" 45 | class Test_single_number < Test::Unit::TestCase 46 | def test_ 47 | assert_equal 3, single_number([2, 2, 3, 2]) 48 | assert_equal 99, single_number([0, 1, 0, 1, 0, 1, 99]) 49 | end 50 | end 51 | -------------------------------------------------------------------------------- /algorithms/ruby/0019-remove-nth-node-from-end-of-list.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 19. Remove Nth Node From End of List 4 | # https://leetcode.com/problems/remove-nth-node-from-end-of-list 5 | 6 | =begin 7 | 8 | Given the head of a linked list, remove the nth node from the end of the list and return its head. 9 | 10 | ### Example 1: 11 | Input: head = [1,2,3,4,5], n = 2 12 | Output: [1,2,3,5] 13 | 14 | ### Example 2: 15 | Input: head = [1], n = 1 16 | Output: [] 17 | 18 | ### Example 3: 19 | Input: head = [1,2], n = 1 20 | Output: [1] 21 | 22 | ### Constraints: 23 | The number of nodes in the list is sz. 24 | 1 <= sz <= 30 25 | 0 <= Node.val <= 100 26 | 1 <= n <= sz 27 | 28 | =end 29 | 30 | # Definition for singly-linked list. 31 | # class ListNode 32 | # attr_accessor :val, :next 33 | # def initialize(val = 0, _next = nil) 34 | # @val = val 35 | # @next = _next 36 | # end 37 | # end 38 | # @param {ListNode} head 39 | # @param {Integer} n 40 | # @return {ListNode} 41 | def remove_nth_from_end(head, n) 42 | dummy = ListNode.new(0) 43 | dummy.next = head 44 | slow = dummy 45 | fast = dummy 46 | (n + 1).times do 47 | fast = fast.next 48 | end 49 | while fast 50 | slow = slow.next 51 | fast = fast.next 52 | end 53 | slow.next = slow.next.next 54 | dummy.next 55 | end 56 | -------------------------------------------------------------------------------- /algorithms/ruby/0242-valid-anagram.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 242. Valid Anagram 4 | # https://leetcode.com/problems/valid-anagram 5 | # Easy 6 | 7 | =begin 8 | Given two strings s and t, return true if t is an anagram of s, and false otherwise. 9 | 10 | An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 11 | 12 | Example 1: 13 | Input: s = "anagram", t = "nagaram" 14 | Output: true 15 | 16 | Example 2: 17 | Input: s = "rat", t = "car" 18 | Output: false 19 | 20 | Constraints: 21 | 1 <= s.length, t.length <= 5 * 104 22 | s and t consist of lowercase English letters. 23 | =end 24 | 25 | # @param {String} s 26 | # @param {String} t 27 | # @return {Boolean} 28 | def is_anagram(s, t) 29 | counter = s.chars.reduce(Hash.new(0)) { |ha, ch| ha[ch] += 1; ha } 30 | 31 | t.chars.each do |ch| 32 | counter[ch] -= 1 33 | return false if counter[ch] < 0 34 | end 35 | 36 | counter.values.all?(&:zero?) 37 | end 38 | 39 | # **************** # 40 | # TEST # 41 | # **************** # 42 | 43 | require "test/unit" 44 | class Test_is_anagram < Test::Unit::TestCase 45 | def test_ 46 | assert_equal true, is_anagram("anagram", "nagaram") 47 | assert_equal false, is_anagram("rat", "car") 48 | end 49 | end 50 | -------------------------------------------------------------------------------- /algorithms/ruby/0539-minimum-time-difference.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 539. Minimum Time Difference 4 | # https://leetcode.com/problems/minimum-time-difference 5 | # Medium 6 | 7 | =begin 8 | Given a list of 24-hour clock time points in "HH:MM" format, return the minimum minutes difference between any two time-points in the list. 9 | 10 | Example 1: 11 | Input: timePoints = ["23:59","00:00"] 12 | Output: 1 13 | 14 | Example 2: 15 | Input: timePoints = ["00:00","23:59","00:00"] 16 | Output: 0 17 | 18 | 19 | Constraints: 20 | * 2 <= timePoints.length <= 2 * 104 21 | * timePoints[i] is in the format "HH:MM". 22 | =end 23 | 24 | 25 | # @param {String[]} time_points 26 | # @return {Integer} 27 | def find_min_difference(time_points) 28 | return 0 if time_points.size > 1440 29 | 30 | time_points.map! { |time| time.split(":").map(&:to_i).reduce(0) { |h, m| h * 60 + m } }.sort! 31 | time_points << time_points[0] + 1440 32 | time_points.each_cons(2).map { |a, b| b - a }.min 33 | end 34 | 35 | # ********************# 36 | # TEST # 37 | # ********************# 38 | 39 | require "test/unit" 40 | class Test_find_min_difference < Test::Unit::TestCase 41 | def test_ 42 | assert_equal 1, find_min_difference(["23:59", "00:00"]) 43 | assert_equal 0, find_min_difference(["00:00", "23:59", "00:00"]) 44 | end 45 | end 46 | -------------------------------------------------------------------------------- /algorithms/ruby/0168-excel-sheet-column-title.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 168. Excel Sheet Column Title 4 | # Easy 5 | # https://leetcode.com/problems/excel-sheet-column-title 6 | 7 | =begin 8 | Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet. 9 | 10 | For example: 11 | A -> 1 12 | B -> 2 13 | C -> 3 14 | ... 15 | Z -> 26 16 | AA -> 27 17 | AB -> 28 18 | ... 19 | 20 | Example 1: 21 | Input: columnNumber = 1 22 | Output: "A" 23 | 24 | Example 2: 25 | Input: columnNumber = 28 26 | Output: "AB" 27 | 28 | Example 3: 29 | Input: columnNumber = 701 30 | Output: "ZY" 31 | 32 | Constraints: 33 | * 1 <= columnNumber <= 231 - 1 34 | =end 35 | 36 | # @param {Integer} column_number 37 | # @return {String} 38 | def convert_to_title(column_number) 39 | result = "" 40 | 41 | while column_number > 0 42 | column_number -= 1 43 | result = (column_number % 26 + 65).chr + result 44 | column_number /= 26 45 | end 46 | 47 | result 48 | end 49 | 50 | # **************** # 51 | # TEST # 52 | # **************** # 53 | 54 | require "test/unit" 55 | class Test_convert_to_title < Test::Unit::TestCase 56 | def test_ 57 | assert_equal "A", convert_to_title(1) 58 | assert_equal "AB", convert_to_title(28) 59 | assert_equal "ZY", convert_to_title(701) 60 | end 61 | end 62 | -------------------------------------------------------------------------------- /algorithms/ruby/0108-convert-sorted-array-to-binary-search-tree.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 108. Convert Sorted Array to Binary Search Tree 4 | # https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree 5 | # Easy 6 | 7 | =begin 8 | 9 | Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree. 10 | 11 | ### Example 1: 12 | Input: nums = [-10,-3,0,5,9] 13 | Output: [0,-3,9,-10,null,5] 14 | Explanation: [0,-10,5,null,-3,null,9] is also accepted: 15 | 16 | ### Example 2: 17 | Input: nums = [1,3] 18 | Output: [3,1] 19 | Explanation: [1,null,3] and [3,1] are both height-balanced BSTs. 20 | 21 | ### Constraints: 22 | * 1 <= nums.length <= 104 23 | * -104 <= nums[i] <= 104 24 | * nums is sorted in a strictly increasing order. 25 | 26 | =end 27 | 28 | # Definition for a binary tree node. 29 | # class TreeNode 30 | # attr_accessor :val, :left, :right 31 | # def initialize(val = 0, left = nil, right = nil) 32 | # @val = val 33 | # @left = left 34 | # @right = right 35 | # end 36 | # end 37 | # @param {Integer[]} nums 38 | # @return {TreeNode} 39 | def sorted_array_to_bst(nums, l = 0, r = nums.size, m = (l + r) / 2) 40 | TreeNode.new(nums[m], sorted_array_to_bst(nums, l, m), sorted_array_to_bst(nums, m + 1, r)) if l < r 41 | end 42 | -------------------------------------------------------------------------------- /algorithms/ruby/0700-search-in-a-binary-search-tree.rb: -------------------------------------------------------------------------------- 1 | # 700. Search in a Binary Search Tree 2 | # https://leetcode.com/problems/search-in-a-binary-search-tree 3 | # Easy 4 | 5 | =begin 6 | You are given the root of a binary search tree (BST) and an integer val. 7 | 8 | Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null. 9 | 10 | Example 1: 11 | Input: root = [4,2,7,1,3], val = 2 12 | Output: [2,1,3] 13 | 14 | Example 2: 15 | Input: root = [4,2,7,1,3], val = 5 16 | Output: [] 17 | 18 | Constraints: 19 | The number of nodes in the tree is in the range [1, 5000]. 20 | 1 <= Node.val <= 107 21 | root is a binary search tree. 22 | 1 <= val <= 107 23 | =end 24 | 25 | # frozen_string_literal: true 26 | 27 | # Definition for a binary tree node. 28 | # class TreeNode 29 | # attr_accessor :val, :left, :right 30 | # def initialize(val = 0, left = nil, right = nil) 31 | # @val = val 32 | # @left = left 33 | # @right = right 34 | # end 35 | # end 36 | # @param {TreeNode} root 37 | # @param {Integer} val 38 | # @return {TreeNode} 39 | def search_bst(root, val) 40 | return nil if root.nil? 41 | 42 | return root if root.val == val 43 | return search_bst(root.right, val) if root.val < val 44 | 45 | search_bst(root.left, val) 46 | end 47 | -------------------------------------------------------------------------------- /algorithms/ruby/0409-longest-palindrome.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 409. Longest Palindrome 4 | # https://leetcode.com/problems/longest-palindrome 5 | 6 | =begin 7 | 8 | Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. 9 | 10 | Letters are case sensitive, for example, "Aa" is not considered a palindrome here. 11 | 12 | ### Example 1: 13 | Input: s = "abccccdd" 14 | Output: 7 15 | Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7. 16 | 17 | ### Example 2: 18 | Input: s = "a" 19 | Output: 1 20 | Explanation: The longest palindrome that can be built is "a", whose length is 1. 21 | 22 | ### Constraints: 23 | * 1 <= s.length <= 2000 24 | * s consists of lowercase and/or uppercase English letters only. 25 | 26 | =end 27 | 28 | # Runtime 92 ms 29 | # Memory 210.9 MB 30 | # @param {String} s 31 | # @return {Integer} 32 | def longest_palindrome(s) 33 | [s.size, s.each_char.tally.sum { _2 & ~1 } + 1].min 34 | end 35 | 36 | # **************** # 37 | # TEST # 38 | # **************** # 39 | 40 | require "test/unit" 41 | class Test_longest_palindrome < Test::Unit::TestCase 42 | def test_ 43 | assert_equal 7, longest_palindrome("abccccdd") 44 | assert_equal 1, longest_palindrome("a") 45 | end 46 | end 47 | -------------------------------------------------------------------------------- /algorithms/ruby/0128-longest-consecutive-sequence.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 128. Longest Consecutive Sequence 4 | # https://leetcode.com/problems/longest-consecutive-sequence 5 | # Medium 6 | 7 | =begin 8 | Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. 9 | 10 | You must write an algorithm that runs in O(n) time. 11 | 12 | Example 1: 13 | Input: nums = [100,4,200,1,3,2] 14 | Output: 4 15 | Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. 16 | 17 | Example 2: 18 | Input: nums = [0,3,7,2,5,8,4,6,0,1] 19 | Output: 9 20 | 21 | Constraints: 22 | 0 <= nums.length <= 105 23 | -109 <= nums[i] <= 109 24 | =end 25 | 26 | # @param {Integer[]} nums 27 | # @return {Integer} 28 | def longest_consecutive(nums) 29 | return 0 if nums.empty? 30 | nums.sort.uniq.each_cons(2).inject([1, 1]) { |(maxl, curl), (v1, v2)| 31 | (v1 + 1 == v2) ? [[maxl, curl + 1].max, curl + 1] : [maxl, 1] 32 | }.first 33 | end 34 | 35 | # **************** # 36 | # TEST # 37 | # **************** # 38 | 39 | require "test/unit" 40 | class Test_longest_consecutive < Test::Unit::TestCase 41 | def test_ 42 | assert_equal 4, longest_consecutive([100, 4, 200, 1, 3, 2]) 43 | assert_equal 9, longest_consecutive([0, 3, 7, 2, 5, 8, 4, 6, 0, 1]) 44 | end 45 | end 46 | -------------------------------------------------------------------------------- /algorithms/ruby/0149-max-points-on-a-line.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 149. Max Points on a Line 4 | # https://leetcode.com/problems/max-points-on-a-line 5 | # Hard 6 | 7 | =begin 8 | Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line. 9 | 10 | Example 1: 11 | Input: points = [[1,1],[2,2],[3,3]] 12 | Output: 3 13 | 14 | Example 2: 15 | Input: points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]] 16 | Output: 4 17 | 18 | Constraints: 19 | 1 <= points.length <= 300 20 | points[i].length == 2 21 | -104 <= xi, yi <= 104 22 | All the points are unique. 23 | =end 24 | 25 | # @param {Integer[][]} points 26 | # @return {Integer} 27 | def max_points(points) 28 | (points[0...-1].each_with_index.collect { |p, idx| 29 | points[idx + 1..-1].collect { |p1| 30 | dx = p.first - p1.first 31 | dx.zero? ? Float::INFINITY : Rational(p.last - p1.last, dx) 32 | }.tally.values.max 33 | }.max || 0) + 1 34 | end 35 | 36 | # **************** # 37 | # TEST # 38 | # **************** # 39 | 40 | require "test/unit" 41 | class Test_max_points < Test::Unit::TestCase 42 | def test_ 43 | assert_equal 3, max_points([[1, 1], [2, 2], [3, 3]]) 44 | assert_equal 4, max_points([[1, 1], [3, 2], [5, 3], [4, 1], [2, 3], [1, 4]]) 45 | end 46 | end 47 | -------------------------------------------------------------------------------- /algorithms/ruby/0142-linked-list-cycle-ii.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 142. Linked List Cycle II 4 | # https://leetcode.com/problems/linked-list-cycle-ii 5 | 6 | =begin 7 | 8 | Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null. 9 | There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter. 10 | Do not modify the linked list. 11 | 12 | Constraints: 13 | 14 | * The number of the nodes in the list is in the range [0, 104]. 15 | * -105 <= Node.val <= 105 16 | * pos is -1 or a valid index in the linked-list. 17 | 18 | =end 19 | 20 | # Definition for singly-linked list. 21 | # class ListNode 22 | # attr_accessor :val, :next 23 | # def initialize(val) 24 | # @val = val 25 | # @next = nil 26 | # end 27 | # end 28 | 29 | # @param {ListNode} head 30 | # @return {ListNode} 31 | def detectCycle(head) 32 | hash = {} 33 | pos = 0 34 | tmp = head 35 | while tmp 36 | if hash[tmp] 37 | return tmp 38 | else 39 | hash[tmp] = pos 40 | end 41 | 42 | pos += 1 43 | tmp = tmp.next 44 | end 45 | end 46 | -------------------------------------------------------------------------------- /algorithms/ruby/0109-convert-sorted-list-to-binary-search-tree.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 109. Convert Sorted List to Binary Search Tree 4 | # https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree 5 | 6 | =begin 7 | 8 | Given the head of a singly linked list where elements are sorted in ascending order, convert it to a 9 | height-balanced binary search tree. 10 | 11 | # Constraints: 12 | 13 | * The number of nodes in head is in the range [0, 2 * 104]. 14 | * -105 <= Node.val <= 105 15 | 16 | =end 17 | 18 | # Definition for singly-linked list. 19 | # class ListNode 20 | # attr_accessor :val, :next 21 | # def initialize(val = 0, _next = nil) 22 | # @val = val 23 | # @next = _next 24 | # end 25 | # end 26 | # Definition for a binary tree node. 27 | # class TreeNode 28 | # attr_accessor :val, :left, :right 29 | # def initialize(val = 0, left = nil, right = nil) 30 | # @val = val 31 | # @left = left 32 | # @right = right 33 | # end 34 | # end 35 | # @param {ListNode} head 36 | # @return {TreeNode} 37 | def sorted_list_to_bst(head) 38 | a = [] 39 | while head 40 | a << head.val 41 | head = head.next 42 | end 43 | f = -> i, j do 44 | return nil if i >= j 45 | m = (i + j) / 2 46 | TreeNode.new a[m], f.(i, m), f.(m + 1, j) 47 | end 48 | f.(0, a.size) 49 | end 50 | -------------------------------------------------------------------------------- /algorithms/ruby/0670-maximum-swap.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 670. Maximum Swap 4 | # Medium 5 | # https://leetcode.com/problems/maximum-swap 6 | 7 | =begin 8 | You are given an integer num. You can swap two digits at most once to get the maximum valued number. 9 | Return the maximum valued number you can get. 10 | 11 | Example 1: 12 | * Input: num = 2736 13 | * Output: 7236 14 | * Explanation: Swap the number 2 and the number 7. 15 | 16 | Example 2: 17 | * Input: num = 9973 18 | * Output: 9973 19 | * Explanation: No swap. 20 | 21 | Constraints: 22 | * 0 <= num <= 108 23 | =end 24 | 25 | # @param {Integer} num 26 | # @return {Integer} 27 | def maximum_swap(num) 28 | digits = num.digits.reverse 29 | last = Array.new(10, -1) 30 | 31 | digits.each_with_index { |digit, i| last[digit] = i } 32 | 33 | digits.each_with_index do |digit, i| 34 | (9).downto(digit + 1) do |d| 35 | if last[d] > i 36 | digits[i], digits[last[d]] = digits[last[d]], digits[i] 37 | return digits.join.to_i 38 | end 39 | end 40 | end 41 | 42 | num 43 | end 44 | 45 | # **************** # 46 | # TEST # 47 | # **************** # 48 | 49 | require "test/unit" 50 | class Test_maximum_swap < Test::Unit::TestCase 51 | def test_ 52 | assert_equal 7236, maximum_swap(2736) 53 | assert_equal 9973, maximum_swap(9973) 54 | end 55 | end 56 | -------------------------------------------------------------------------------- /algorithms/ruby/0322-coin-change.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 322. Coin Change 4 | # https://leetcode.com/problems/coin-change/ 5 | # Medium 6 | 7 | =begin 8 | 9 | You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. 10 | 11 | Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. 12 | 13 | You may assume that you have an infinite number of each kind of coin. 14 | 15 | Example 1: 16 | Input: coins = [1,2,5], amount = 11 17 | Output: 3 18 | Explanation: 11 = 5 + 5 + 1 19 | 20 | Example 2: 21 | Input: coins = [2], amount = 3 22 | Output: -1 23 | 24 | Example 3: 25 | Input: coins = [1], amount = 0 26 | Output: 0 27 | 28 | Constraints: 29 | 1 <= coins.length <= 12 30 | 1 <= coins[i] <= 231 - 1 31 | 0 <= amount <= 104 32 | 33 | =end 34 | 35 | # @param {Integer[]} coins 36 | # @param {Integer} amount 37 | # @return {Integer} 38 | INF = Float::INFINITY 39 | 40 | def coin_change(coins, amount) 41 | dp = [INF] * (amount + 1) 42 | dp[0] = 0 43 | 44 | (1..amount).each do |i| 45 | coins.each do |j| 46 | if i - j >= 0 && dp[i - j] < INF 47 | dp[i] = [dp[i], 1 + dp[i - j]].min 48 | end 49 | end 50 | end 51 | 52 | dp[-1] < INF ? dp[-1] : -1 53 | end 54 | -------------------------------------------------------------------------------- /algorithms/ruby/0066-plus-one.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 66. Plus One 4 | # https://leetcode.com/problems/plus-one 5 | 6 | =begin 7 | 8 | You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's. 9 | Increment the large integer by one and return the resulting array of digits. 10 | 11 | # Constraints: 12 | 13 | * 1 <= digits.length <= 100 14 | * 0 <= digits[i] <= 9 15 | * digits does not contain any leading 0's. 16 | =end 17 | 18 | # @param {Integer[]} digits 19 | # @return {Integer[]} 20 | def plus_one(digits) 21 | carryover, pointer = 1, -1 22 | 23 | while carryover.positive? 24 | break digits.unshift(carryover) if digits[pointer].nil? 25 | 26 | sum = digits[pointer] + carryover 27 | carryover = sum / 10 28 | digits[pointer] = sum % 10 29 | pointer -= 1 30 | end 31 | 32 | digits 33 | end 34 | 35 | # ********************# 36 | # TEST # 37 | # ********************# 38 | 39 | require "test/unit" 40 | class Test_plus_one < Test::Unit::TestCase 41 | def test_ 42 | assert_equal [1, 2, 4], plus_one([1, 2, 3]) 43 | assert_equal [4, 3, 2, 2], plus_one([4, 3, 2, 1]) 44 | assert_equal [1, 0], plus_one([9]) 45 | end 46 | end 47 | -------------------------------------------------------------------------------- /algorithms/ruby/0383-ransom-note.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 383. Ransom Note 4 | # https://leetcode.com/problems/ransom-note 5 | # Easy 6 | 7 | =begin 8 | Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise. 9 | 10 | Each letter in magazine can only be used once in ransomNote. 11 | 12 | Example 1: 13 | Input: ransomNote = "a", magazine = "b" 14 | Output: false 15 | 16 | Example 2: 17 | Input: ransomNote = "aa", magazine = "ab" 18 | Output: false 19 | 20 | Example 3: 21 | Input: ransomNote = "aa", magazine = "aab" 22 | Output: true 23 | 24 | Constraints: 25 | 1 <= ransomNote.length, magazine.length <= 105 26 | ransomNote and magazine consist of lowercase English letters. 27 | =end 28 | 29 | # @param {String} ransom_note 30 | # @param {String} magazine 31 | # @return {Boolean} 32 | def can_construct(ransom_note, magazine) 33 | ransom_note.chars.uniq.all? { |character| ransom_note.count(character) <= magazine.count(character) } 34 | end 35 | 36 | # **************** # 37 | # TEST # 38 | # **************** # 39 | 40 | require "test/unit" 41 | class Test_can_construct < Test::Unit::TestCase 42 | def test_ 43 | assert_equal false, can_construct("a", "b") 44 | assert_equal false, can_construct("aa", "ab") 45 | assert_equal true, can_construct("aa", "aab") 46 | end 47 | end 48 | -------------------------------------------------------------------------------- /algorithms/ruby/1287-element-appearing-more-than-25-in-sorted-array.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 1287. Element Appearing More Than 25% In Sorted Array 4 | # Easy 5 | # https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array 6 | 7 | =begin 8 | Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer. 9 | 10 | Example 1: 11 | Input: arr = [1,2,2,6,6,6,6,7,10] 12 | Output: 6 13 | 14 | Example 2: 15 | Input: arr = [1,1] 16 | Output: 1 17 | 18 | Constraints: 19 | 1 <= arr.length <= 104 20 | 0 <= arr[i] <= 105 21 | =end 22 | 23 | # @param {Integer[]} arr 24 | # @return {Integer} 25 | def find_special_integer(arr) 26 | return arr[0] if arr.size < 3 27 | 28 | size = arr.size 29 | appearance = size.fdiv(4) 30 | 31 | counter = 1 32 | (1...size).each do |i| 33 | value = arr[i] 34 | if arr[i - 1] == value 35 | counter += 1 36 | else 37 | counter = 1 38 | end 39 | return value if appearance < counter 40 | end 41 | end 42 | 43 | # **************** # 44 | # TEST # 45 | # **************** # 46 | 47 | require "test/unit" 48 | class Test_find_special_integer < Test::Unit::TestCase 49 | def test_ 50 | assert_equal 6, find_special_integer([1, 2, 2, 6, 6, 6, 6, 7, 10]) 51 | assert_equal 1, find_special_integer([1, 1]) 52 | end 53 | end 54 | -------------------------------------------------------------------------------- /database/1683-invalid-tweets.sql: -------------------------------------------------------------------------------- 1 | -- https://leetcode.com/problems/invalid-tweets 2 | -- 1683. Invalid Tweets 3 | -- Easy 4 | 5 | /* 6 | Table: Tweets 7 | +----------------+---------+ 8 | | Column Name | Type | 9 | +----------------+---------+ 10 | | tweet_id | int | 11 | | content | varchar | 12 | +----------------+---------+ 13 | tweet_id is the primary key for this table. 14 | This table contains all the tweets in a social media app. 15 | 16 | Write an SQL query to find the IDs of the invalid tweets. The tweet is invalid if the number of characters used in the content of the tweet is strictly greater than 15. 17 | Return the result table in any order. 18 | The query result format is in the following example. 19 | 20 | Example 1: 21 | Input: 22 | Tweets table: 23 | +----------+----------------------------------+ 24 | | tweet_id | content | 25 | +----------+----------------------------------+ 26 | | 1 | Vote for Biden | 27 | | 2 | Let us make America great again! | 28 | +----------+----------------------------------+ 29 | Output: 30 | +----------+ 31 | | tweet_id | 32 | +----------+ 33 | | 2 | 34 | +----------+ 35 | Explanation: 36 | Tweet 1 has length = 14. It is a valid tweet. 37 | Tweet 2 has length = 32. It is an invalid tweet. 38 | */ 39 | 40 | SELECT 41 | tweet_id 42 | FROM 43 | Tweets 44 | WHERE 45 | length(content) > 15; 46 | -------------------------------------------------------------------------------- /algorithms/ruby/0199-binary-tree-right-side-view.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 199. Binary Tree Right Side View 4 | # https://leetcode.com/problems/binary-tree-right-side-view/ 5 | # Medium 6 | 7 | =begin 8 | Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. 9 | 10 | Example 1: 11 | Input: root = [1,2,3,null,5,null,4] 12 | Output: [1,3,4] 13 | 14 | Example 2: 15 | Input: root = [1,null,3] 16 | Output: [1,3] 17 | 18 | Example 3: 19 | Input: root = [] 20 | Output: [] 21 | 22 | Constraints: 23 | The number of nodes in the tree is in the range [0, 100]. 24 | -100 <= Node.val <= 100 25 | 26 | =end 27 | 28 | # Definition for a binary tree node. 29 | # class TreeNode 30 | # attr_accessor :val, :left, :right 31 | # def initialize(val = 0, left = nil, right = nil) 32 | # @val = val 33 | # @left = left 34 | # @right = right 35 | # end 36 | # end 37 | # @param {TreeNode} root 38 | # @return {Integer[]} 39 | def right_side_view(root) 40 | return [] unless root 41 | res = [] 42 | queue = [root] 43 | 44 | until queue.empty? 45 | current = nil 46 | queue.size.times do 47 | current = queue.shift 48 | queue.push(current.left) if current.left 49 | queue.push(current.right) if current.right 50 | end 51 | res << current.val 52 | end 53 | res 54 | end 55 | -------------------------------------------------------------------------------- /algorithms/ruby/1721-swapping-nodes-in-a-linked-list.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 1721. Swapping Nodes in a Linked List 4 | # https://leetcode.com/problems/swapping-nodes-in-a-linked-list 5 | # Medium 6 | 7 | =begin 8 | You are given the head of a linked list, and an integer k. 9 | 10 | Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed). 11 | 12 | Example 1: 13 | Input: head = [1,2,3,4,5], k = 2 14 | Output: [1,4,3,2,5] 15 | 16 | Example 2: 17 | Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5 18 | Output: [7,9,6,6,8,7,3,0,9,5] 19 | 20 | Constraints: 21 | The number of nodes in the list is n. 22 | 1 <= k <= n <= 105 23 | 0 <= Node.val <= 100 24 | =end 25 | 26 | # Definition for singly-linked list. 27 | # class ListNode 28 | # attr_accessor :val, :next 29 | # def initialize(val = 0, _next = nil) 30 | # @val = val 31 | # @next = _next 32 | # end 33 | # end 34 | # @param {ListNode} head 35 | # @param {Integer} k 36 | # @return {ListNode} 37 | def swap_nodes(head, k) 38 | n1 = nil 39 | n2 = nil 40 | curr = head 41 | 42 | while curr 43 | k -= 1 44 | if n2 != nil 45 | n2 = n2.next 46 | end 47 | 48 | if k == 0 49 | n1 = curr 50 | n2 = head 51 | end 52 | 53 | curr = curr.next 54 | end 55 | 56 | n1.val, n2.val = n2.val, n1.val 57 | head 58 | end 59 | -------------------------------------------------------------------------------- /algorithms/ruby/0169-majority-element.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 169. Majority Element 4 | # https://leetcode.com/problems/majority-element 5 | # Easy 6 | 7 | =begin 8 | Given an array nums of size n, return the majority element. 9 | 10 | The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. 11 | 12 | Example 1: 13 | Input: nums = [3,2,3] 14 | Output: 3 15 | 16 | Example 2: 17 | Input: nums = [2,2,1,1,1,2,2] 18 | Output: 2 19 | 20 | Constraints: 21 | n == nums.length 22 | 1 <= n <= 5 * 104 23 | -109 <= nums[i] <= 109 24 | =end 25 | 26 | # @param {Integer[]} nums 27 | # @return {Integer} 28 | def majority_element(nums) 29 | candidate = nil 30 | count = 0 31 | 32 | nums.each do |ele| 33 | candidate = ele if count == 0 34 | 35 | if candidate == ele 36 | count += 1 37 | else 38 | count -= 1 39 | end 40 | end 41 | 42 | count = 0 43 | nums.each do |ele| 44 | count += 1 if ele == candidate 45 | end 46 | 47 | count > nums.count / 2 ? candidate : nil 48 | end 49 | 50 | # ********************# 51 | # TEST # 52 | # ********************# 53 | 54 | require "test/unit" 55 | class Test_majority_element < Test::Unit::TestCase 56 | def test_ 57 | assert_equal 3, majority_element([3, 2, 3]) 58 | assert_equal 2, majority_element([2, 2, 1, 1, 1, 2, 2]) 59 | end 60 | end 61 | -------------------------------------------------------------------------------- /algorithms/ruby/0427-construct-quad-tree.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 427. Construct Quad Tree 4 | # https://leetcode.com/problems/construct-quad-tree 5 | 6 | # Definition for a QuadTree node. 7 | # class Node 8 | # attr_accessor :val, :isLeaf, :topLeft, :topRight, :bottomLeft, :bottomRight 9 | # def initialize(val=false, isLeaf=false, topLeft=nil, topRight=nil, bottomLeft=nil, bottomRight=nil) 10 | # @val = val 11 | # @isLeaf = isLeaf 12 | # @topLeft = topLeft 13 | # @topRight = topRight 14 | # @bottomLeft = bottomLeft 15 | # @bottomRight = bottomRight 16 | # end 17 | # end 18 | 19 | # @param {Integer[][]} grid 20 | # @return {Node} 21 | def construct(grid, r = 0, c = 0, length = grid.length) 22 | if same?(grid, r, c, length) 23 | return Node.new(grid[r][c] == 1 ? true : false, true) 24 | end 25 | 26 | node = Node.new(true, false) 27 | node.topLeft = construct(grid, r, c, length / 2) 28 | node.topRight = construct(grid, r, c + length / 2, length / 2) 29 | node.bottomLeft = construct(grid, r + length / 2, c, length / 2) 30 | node.bottomRight = construct(grid, r + length / 2, c + length / 2, length / 2) 31 | node 32 | end 33 | 34 | def same?(grid, r, c, n) 35 | for i in r..r + n - 1 36 | for j in c..c + n - 1 37 | if grid[i][j] != grid[r][c] 38 | return false 39 | end 40 | end 41 | end 42 | 43 | true 44 | end 45 | -------------------------------------------------------------------------------- /algorithms/ruby/0704-binary-search.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 704. Binary Search 4 | # https://leetcode.com/problems/binary-search 5 | 6 | =begin 7 | 8 | Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1. 9 | 10 | You must write an algorithm with O(log n) runtime complexity. 11 | 12 | ### Example 1: 13 | Input: nums = [-1,0,3,5,9,12], target = 9 14 | Output: 4 15 | Explanation: 9 exists in nums and its index is 4 16 | 17 | ### Example 2: 18 | Input: nums = [-1,0,3,5,9,12], target = 2 19 | Output: -1 20 | Explanation: 2 does not exist in nums so return -1 21 | 22 | ### Constraints: 23 | * 1 <= nums.length <= 104 24 | * -104 < nums[i], target < 104 25 | * All the integers in nums are unique. 26 | * nums is sorted in ascending order. 27 | 28 | =end 29 | 30 | # Runtime: 100 ms 31 | # Memory: 213.7 MB 32 | # @param {Integer[]} nums 33 | # @param {Integer} target 34 | # @return {Integer} 35 | def search(nums, target) 36 | nums.bsearch_index { |i| target - i } || -1 37 | end 38 | 39 | # **************** # 40 | # TEST # 41 | # **************** # 42 | 43 | require "test/unit" 44 | class Test_search < Test::Unit::TestCase 45 | def test_ 46 | assert_equal 4, search([-1, 0, 3, 5, 9, 12], 9) 47 | assert_equal(-1, search([-1, 0, 3, 5, 9, 12], 2)) 48 | end 49 | end 50 | -------------------------------------------------------------------------------- /algorithms/ruby/0049-group-anagrams.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 49. Group Anagrams 4 | # https://leetcode.com/problems/group-anagrams 5 | # Medium 6 | 7 | =begin 8 | Given an array of strings strs, group the anagrams together. You can return the answer in any order. 9 | 10 | An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 11 | 12 | Example 1: 13 | Input: strs = ["eat","tea","tan","ate","nat","bat"] 14 | Output: [["bat"],["nat","tan"],["ate","eat","tea"]] 15 | 16 | Example 2: 17 | Input: strs = [""] 18 | Output: [[""]] 19 | 20 | Example 3: 21 | Input: strs = ["a"] 22 | Output: [["a"]] 23 | 24 | Constraints: 25 | 1 <= strs.length <= 104 26 | 0 <= strs[i].length <= 100 27 | strs[i] consists of lowercase English letters. 28 | =end 29 | 30 | # @param {String[]} strs 31 | # @return {String[][]} 32 | def group_anagrams(strs) 33 | strs.sort.group_by { |s| s.chars.sort }.values 34 | end 35 | 36 | # **************** # 37 | # TEST # 38 | # **************** # 39 | 40 | require "test/unit" 41 | class Test_group_anagrams < Test::Unit::TestCase 42 | def test_ 43 | assert_equal [["bat"], ["nat", "tan"], ["ate", "eat", "tea"]].sort, group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"]) 44 | assert_equal [[""]].sort, group_anagrams([""]) 45 | assert_equal [["a"]].sort, group_anagrams(["a"]) 46 | end 47 | end 48 | -------------------------------------------------------------------------------- /algorithms/ruby/0053-maximum-subarray.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # https://leetcode.com/problems/maximum-subarray 4 | # 53. Maximum Subarray 5 | # Medium 6 | 7 | =begin 8 | Given an integer array nums, find the subarray with the largest sum, and return its sum. 9 | 10 | Example 1: 11 | Input: nums = [-2,1,-3,4,-1,2,1,-5,4] 12 | Output: 6 13 | Explanation: The subarray [4,-1,2,1] has the largest sum 6. 14 | 15 | Example 2: 16 | Input: nums = [1] 17 | Output: 1 18 | Explanation: The subarray [1] has the largest sum 1. 19 | 20 | Example 3: 21 | Input: nums = [5,4,-1,7,8] 22 | Output: 23 23 | Explanation: The subarray [5,4,-1,7,8] has the largest sum 23. 24 | 25 | Constraints: 26 | * 1 <= nums.length <= 105 27 | * -104 <= nums[i] <= 104 28 | =end 29 | 30 | # @param {Integer[]} nums 31 | # @return {Integer} 32 | def max_sub_array(nums) 33 | max_sum = nums[0] 34 | current_sum = nums[0] 35 | 36 | nums[1..-1].each do |num| 37 | current_sum = [num, current_sum + num].max 38 | max_sum = [max_sum, current_sum].max 39 | end 40 | 41 | max_sum 42 | end 43 | 44 | # **************** # 45 | # TEST # 46 | # **************** # 47 | 48 | require "test/unit" 49 | class Test_max_sub_array < Test::Unit::TestCase 50 | def test_ 51 | assert_equal 6, max_sub_array([-2, 1, -3, 4, -1, 2, 1, -5, 4]) 52 | assert_equal 1, max_sub_array([1]) 53 | assert_equal 23, max_sub_array([5, 4, -1, 7, 8]) 54 | end 55 | end 56 | -------------------------------------------------------------------------------- /algorithms/ruby/1480-running-sum-of-1d-array.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 1480. Running Sum of 1d Array 4 | # https://leetcode.com/problems/running-sum-of-1d-array 5 | 6 | =begin 7 | 8 | Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). 9 | 10 | Return the running sum of nums. 11 | 12 | ### Example 1: 13 | Input: nums = [1,2,3,4] 14 | Output: [1,3,6,10] 15 | Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4]. 16 | 17 | ### Example 2: 18 | Input: nums = [1,1,1,1,1] 19 | Output: [1,2,3,4,5] 20 | Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1]. 21 | 22 | ### Example 3: 23 | Input: nums = [3,1,2,10,1] 24 | Output: [3,4,6,16,17] 25 | 26 | ### Constraints: 27 | 28 | * 1 <= nums.length <= 1000 29 | * -10^6 <= nums[i] <= 10^6 30 | =end 31 | 32 | # Runtime 96 ms 33 | # Memory 211.1 MB 34 | # @param {Integer[]} nums 35 | # @return {Integer[]} 36 | def running_sum(nums) 37 | nums.reduce([]) { _1 << _2 + (_1.last || 0) } 38 | end 39 | 40 | # **************** # 41 | # TEST # 42 | # **************** # 43 | 44 | require "test/unit" 45 | class Test_running_sum < Test::Unit::TestCase 46 | def test_ 47 | assert_equal [1, 3, 6, 10], running_sum([1, 2, 3, 4]) 48 | assert_equal [1, 2, 3, 4, 5], running_sum([1, 1, 1, 1, 1]) 49 | assert_equal [3, 4, 6, 16, 17], running_sum([3, 1, 2, 10, 1]) 50 | end 51 | end 52 | -------------------------------------------------------------------------------- /algorithms/ruby/0589-n-ary-tree-preorder-traversal.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 589. N-ary Tree Preorder Traversal 4 | # https://leetcode.com/problems/n-ary-tree-preorder-traversal 5 | 6 | =begin 7 | 8 | Given the root of an n-ary tree, return the preorder traversal of its nodes' values. 9 | 10 | Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) 11 | 12 | ### Example 1: 13 | Input: root = [1,null,3,2,4,null,5,6] 14 | Output: [1,3,5,6,2,4] 15 | 16 | ### Example 2: 17 | Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] 18 | Output: [1,2,3,6,7,11,14,4,8,12,5,9,13,10] 19 | 20 | ### Constraints: 21 | * The number of nodes in the tree is in the range [0, 104]. 22 | * 0 <= Node.val <= 104 23 | * The height of the n-ary tree is less than or equal to 1000. 24 | 25 | =end 26 | 27 | # Definition for a Node. 28 | # class Node 29 | # attr_accessor :val, :children 30 | # def initialize(val) 31 | # @val = val 32 | # @children = [] 33 | # end 34 | # end 35 | 36 | # Runtime: 112 ms 37 | # Memory: 211.7 MB 38 | # @param {Node} root 39 | # @return {List[int]} 40 | def preorder(root) 41 | loop.reduce([[], root ? [root] : []]) do | (r, s) | 42 | s.empty? ? (break r) : [ 43 | r << (root = s.pop).val, s.push(*root.children.reverse_each) 44 | ] 45 | end 46 | end 47 | -------------------------------------------------------------------------------- /algorithms/ruby/0077-combinations.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 77. Combinations 4 | # https://leetcode.com/problems/combinations 5 | # Medium 6 | 7 | =begin 8 | Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n]. 9 | 10 | You may return the answer in any order. 11 | 12 | Example 1: 13 | Input: n = 4, k = 2 14 | Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] 15 | Explanation: There are 4 choose 2 = 6 total combinations. 16 | Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination. 17 | 18 | Example 2: 19 | Input: n = 1, k = 1 20 | Output: [[1]] 21 | Explanation: There is 1 choose 1 = 1 total combination. 22 | 23 | Constraints: 24 | * 1 <= n <= 20 25 | * 1 <= k <= n 26 | =end 27 | 28 | # @param {Integer} n 29 | # @param {Integer} k 30 | # @return {Integer[][]} 31 | def combine(n, k) 32 | return (1..n).map { |i| [i] } if k == 1 33 | 34 | i = n 35 | result = [] 36 | 37 | while i > 1 38 | result += combine(i - 1, k - 1).map { |tuple| tuple + [i] } 39 | i -= 1 40 | end 41 | 42 | result 43 | end 44 | 45 | # **************** # 46 | # TEST # 47 | # **************** # 48 | 49 | require "test/unit" 50 | class Test_combine < Test::Unit::TestCase 51 | def test_ 52 | assert_equal [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]].sort, combine(4, 2).sort 53 | assert_equal [[1]], combine(1, 1) 54 | end 55 | end 56 | -------------------------------------------------------------------------------- /algorithms/ruby/0219-contains-duplicate-ii.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 219. Contains Duplicate II 4 | # https://leetcode.com/problems/contains-duplicate-ii 5 | # Easy 6 | 7 | =begin 8 | Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k. 9 | 10 | Example 1: 11 | Input: nums = [1,2,3,1], k = 3 12 | Output: true 13 | 14 | Example 2: 15 | Input: nums = [1,0,1,1], k = 1 16 | Output: true 17 | 18 | Example 3: 19 | Input: nums = [1,2,3,1,2,3], k = 2 20 | Output: false 21 | 22 | Constraints: 23 | 1 <= nums.length <= 105 24 | -109 <= nums[i] <= 109 25 | 0 <= k <= 105 26 | =end 27 | 28 | # @param {Integer[]} nums 29 | # @param {Integer} k 30 | # @return {Boolean} 31 | def contains_nearby_duplicate(nums, k) 32 | hash = {} 33 | nums.each_with_index do |value, j| 34 | i = hash[value] 35 | if i && (j - i) <= k 36 | return true 37 | end 38 | hash[value] = j 39 | end 40 | false 41 | end 42 | 43 | # **************** # 44 | # TEST # 45 | # **************** # 46 | 47 | require "test/unit" 48 | class Test_contains_nearby_duplicate < Test::Unit::TestCase 49 | def test_ 50 | assert_equal true, contains_nearby_duplicate([1, 2, 3, 1], 3) 51 | assert_equal true, contains_nearby_duplicate([1, 0, 1, 1], 1) 52 | assert_equal false, contains_nearby_duplicate([1, 2, 3, 1, 2, 3], 2) 53 | end 54 | end 55 | -------------------------------------------------------------------------------- /algorithms/ruby/2433-find-the-original-array-of-prefix-xor.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 2433. Find The Original Array of Prefix Xor 4 | # Medium 5 | # https://leetcode.com/problems/find-the-original-array-of-prefix-xor 6 | 7 | =begin 8 | You are given an integer array pref of size n. Find and return the array arr of size n that satisfies: 9 | * pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i]. 10 | Note that ^ denotes the bitwise-xor operation. 11 | 12 | It can be proven that the answer is unique. 13 | 14 | 15 | Example 1: 16 | Input: pref = [5,2,0,3,1] 17 | Output: [5,7,2,3,2] 18 | Explanation: From the array [5,7,2,3,2] we have the following: 19 | - pref[0] = 5. 20 | - pref[1] = 5 ^ 7 = 2. 21 | - pref[2] = 5 ^ 7 ^ 2 = 0. 22 | - pref[3] = 5 ^ 7 ^ 2 ^ 3 = 3. 23 | - pref[4] = 5 ^ 7 ^ 2 ^ 3 ^ 2 = 1. 24 | 25 | Example 2: 26 | Input: pref = [13] 27 | Output: [13] 28 | Explanation: We have pref[0] = arr[0] = 13. 29 | 30 | Constraints: 31 | * 1 <= pref.length <= 105 32 | * 0 <= pref[i] <= 106 33 | =end 34 | 35 | # @param {Integer[]} pref 36 | # @return {Integer[]} 37 | def find_array(pref) 38 | [0, *pref].each_cons(2).map { _1 ^ _2 } 39 | end 40 | 41 | # **************** # 42 | # TEST # 43 | # **************** # 44 | 45 | require "test/unit" 46 | class Test_find_array < Test::Unit::TestCase 47 | def test_ 48 | assert_equal [5, 7, 2, 3, 2], find_array([5, 2, 0, 3, 1]) 49 | assert_equal [13], find_array([13]) 50 | end 51 | end 52 | -------------------------------------------------------------------------------- /algorithms/ruby/0102-binary-tree-level-order-traversal.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 102. Binary Tree Level Order Traversal 4 | # https://leetcode.com/problems/binary-tree-level-order-traversal 5 | 6 | =begin 7 | 8 | Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level). 9 | 10 | ### Example 1: 11 | Input: root = [3,9,20,null,null,15,7] 12 | Output: [[3],[9,20],[15,7]] 13 | 14 | ### Example 2: 15 | Input: root = [1] 16 | Output: [[1]] 17 | 18 | ### Example 3: 19 | Input: root = [] 20 | Output: [] 21 | 22 | ### Constraints: 23 | * The number of nodes in the tree is in the range [0, 2000]. 24 | * -1000 <= Node.val <= 1000 25 | 26 | =end 27 | 28 | # Runtime: 103 ms 29 | # Memory: 211.2 MB 30 | # Definition for a binary tree node. 31 | # class TreeNode 32 | # attr_accessor :val, :left, :right 33 | # def initialize(val = 0, left = nil, right = nil) 34 | # @val = val 35 | # @left = left 36 | # @right = right 37 | # end 38 | # end 39 | # @param {TreeNode} root 40 | # @return {Integer[][]} 41 | def level_order(root) 42 | return [] unless root 43 | 44 | result = [] 45 | deque = [[root, 1]] 46 | 47 | until deque.empty? 48 | n, d = deque.shift 49 | result << [] if d > result.count 50 | result[d - 1] << n.val 51 | deque << [n.left, d + 1] if n.left 52 | deque << [n.right, d + 1] if n.right 53 | end 54 | 55 | result 56 | end 57 | -------------------------------------------------------------------------------- /algorithms/ruby/0515-find-largest-value-in-each-tree-row.rb: -------------------------------------------------------------------------------- 1 | # 515. Find Largest Value in Each Tree Row 2 | # Medium 3 | # https://leetcode.com/problems/find-largest-value-in-each-tree-row 4 | 5 | =begin 6 | Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed). 7 | 8 | Example 1: 9 | Input: root = [1,3,2,5,3,null,9] 10 | Output: [1,3,9] 11 | 12 | Example 2: 13 | Input: root = [1,2,3] 14 | Output: [1,3] 15 | 16 | Constraints: 17 | The number of nodes in the tree will be in the range [0, 104]. 18 | -231 <= Node.val <= 231 - 1 19 | =end 20 | 21 | # frozen_string_literal: true 22 | 23 | # Definition for a binary tree node. 24 | # class TreeNode 25 | # attr_accessor :val, :left, :right 26 | # def initialize(val = 0, left = nil, right = nil) 27 | # @val = val 28 | # @left = left 29 | # @right = right 30 | # end 31 | # end 32 | # @param {TreeNode} root 33 | # @return {Integer[]} 34 | def largest_values(root) 35 | return [] if root.nil? 36 | 37 | res = [] 38 | 39 | queue = Queue.new 40 | 41 | queue << root 42 | 43 | while !queue.empty? do 44 | n_a = [] 45 | queue.size.times do 46 | node = queue.pop 47 | 48 | n_a << node.val 49 | if node.left != nil 50 | queue << node.left 51 | end 52 | 53 | if node.right != nil 54 | queue << node.right 55 | end 56 | end 57 | res << n_a.max 58 | end 59 | 60 | res 61 | end 62 | -------------------------------------------------------------------------------- /algorithms/ruby/0530-minimum-absolute-difference-in-bst.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 530. Minimum Absolute Difference in BST 4 | # https://leetcode.com/problems/minimum-absolute-difference-in-bst 5 | # Easy 6 | 7 | =begin 8 | Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree. 9 | 10 | Example 1: 11 | Input: root = [4,2,6,1,3] 12 | Output: 1 13 | 14 | Example 2: 15 | Input: root = [1,0,48,null,null,12,49] 16 | Output: 1 17 | 18 | Constraints: 19 | * The number of nodes in the tree is in the range [2, 104]. 20 | * 0 <= Node.val <= 105 21 | =end 22 | 23 | # Definition for a binary tree node. 24 | # class TreeNode 25 | # attr_accessor :val, :left, :right 26 | # def initialize(val = 0, left = nil, right = nil) 27 | # @val = val 28 | # @left = left 29 | # @right = right 30 | # end 31 | # end 32 | # @param {TreeNode} root 33 | # @return {Integer} 34 | # @param {TreeNode} root 35 | # @return {Integer} 36 | def get_minimum_difference(root) 37 | @prev = nil 38 | @min_diff = Float::INFINITY 39 | 40 | in_order_traversal(root) 41 | @min_diff 42 | end 43 | 44 | def in_order_traversal(node) 45 | return if node.nil? 46 | 47 | in_order_traversal(node.left) 48 | 49 | if @prev 50 | diff = node.val - @prev.val 51 | @min_diff = [@min_diff, diff].min 52 | end 53 | 54 | @prev = node 55 | in_order_traversal(node.right) 56 | end 57 | -------------------------------------------------------------------------------- /algorithms/ruby/0064-minimum-path-sum.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 64. Minimum Path Sum 4 | # https://leetcode.com/problems/minimum-path-sum 5 | 6 | =begin 7 | 8 | Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. 9 | 10 | Note: You can only move either down or right at any point in time. 11 | 12 | ### Example 1: 13 | Input: grid = [[1,3,1],[1,5,1],[4,2,1]] 14 | Output: 7 15 | Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum. 16 | 17 | ### Example 2: 18 | Input: grid = [[1,2,3],[4,5,6]] 19 | Output: 12 20 | 21 | ### Constraints: 22 | * m == grid.length 23 | * n == grid[i].length 24 | * 1 <= m, n <= 200 25 | * 0 <= grid[i][j] <= 100 26 | 27 | =end 28 | 29 | # Runtime 72 ms 30 | # Memory 212.3 MB 31 | # @param {Integer[][]} grid 32 | # @return {Integer} 33 | def min_path_sum(grid) 34 | acc = [0] + [Float::INFINITY] * (grid[0].size - 1) 35 | 36 | grid.each { |row| 37 | left = Float::INFINITY 38 | acc.map!.with_index { |n, i| left = row[i] + (left < n ? left : n) } 39 | } 40 | 41 | acc.last 42 | end 43 | 44 | # ********************# 45 | # TEST # 46 | # ********************# 47 | 48 | require "test/unit" 49 | class Test_min_path_sum < Test::Unit::TestCase 50 | def test_ 51 | assert_equal 7, min_path_sum([[1, 3, 1], [1, 5, 1], [4, 2, 1]]) 52 | # assert_equal 12, min_path_sum([[1,2,3],[4,5,6]]) 53 | end 54 | end 55 | -------------------------------------------------------------------------------- /algorithms/ruby/1424-diagonal-traverse-ii.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 1424. Diagonal Traverse II 4 | # Medium 5 | # https://leetcode.com/problems/diagonal-traverse-ii 6 | 7 | =begin 8 | Given a 2D integer array nums, return all elements of nums in diagonal order as shown in the below images. 9 | 10 | Example 1: 11 | Input: nums = [[1,2,3],[4,5,6],[7,8,9]] 12 | Output: [1,4,2,7,5,3,8,6,9] 13 | 14 | Example 2 15 | Input: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]] 16 | Output: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16] 17 | 18 | Constraints: 19 | 1 <= nums.length <= 105 20 | 1 <= nums[i].length <= 105 21 | 1 <= sum(nums[i].length) <= 105 22 | 1 <= nums[i][j] <= 105 23 | =end 24 | 25 | # @param {Integer[][]} nums 26 | # @return {Integer[]} 27 | def find_diagonal_order(a) 28 | r, z = [], a.size 29 | a.each_with_index do | v, i | 30 | p = z - i 31 | v.each_with_index do 32 | r << [(i + _2 << 20) | p, _1] 33 | end 34 | end 35 | r.sort_by!(&:first).map!(&:last) 36 | end 37 | 38 | # **************** # 39 | # TEST # 40 | # **************** # 41 | 42 | require "test/unit" 43 | class Test_find_diagonal_order < Test::Unit::TestCase 44 | def test_ 45 | assert_equal [1, 4, 2, 7, 5, 3, 8, 6, 9], find_diagonal_order([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) 46 | assert_equal [1, 6, 2, 8, 7, 3, 9, 4, 12, 10, 5, 13, 11, 14, 15, 16], find_diagonal_order([[1, 2, 3, 4, 5], [6, 7], [8], [9, 10, 11], [12, 13, 14, 15, 16]]) 47 | end 48 | end 49 | -------------------------------------------------------------------------------- /algorithms/ruby/0215-kth-largest-element-in-an-array.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 215. Kth Largest Element in an Array 4 | # https://leetcode.com/problems/kth-largest-element-in-an-array 5 | # Medium 6 | 7 | =begin 8 | Given an integer array nums and an integer k, return the kth largest element in the array. 9 | 10 | Note that it is the kth largest element in the sorted order, not the kth distinct element. 11 | 12 | You must solve it in O(n) time complexity. 13 | 14 | Example 1: 15 | Input: nums = [3,2,1,5,6,4], k = 2 16 | Output: 5 17 | 18 | Example 2: 19 | Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 20 | Output: 4 21 | 22 | Constraints: 23 | 1 <= k <= nums.length <= 105 24 | -104 <= nums[i] <= 104 25 | =end 26 | 27 | # @param {Integer[]} nums 28 | # @param {Integer} k 29 | # @return {Integer} 30 | def find_kth_largest(nums, k) 31 | nums.sort[-k] 32 | end 33 | 34 | # ********************# 35 | # TEST # 36 | # ********************# 37 | 38 | require "test/unit" 39 | class Test_find_kth_largest < Test::Unit::TestCase 40 | def test_ 41 | assert_equal 5, find_kth_largest([3, 2, 1, 5, 6, 4], 2) 42 | assert_equal 4, find_kth_largest([3, 2, 3, 1, 2, 4, 5, 5, 6], 4) 43 | end 44 | end 45 | 46 | # ********************# 47 | # Benchmark # 48 | # ********************# 49 | 50 | require "benchmark" 51 | 52 | nums = [3, 2, 3, 1, 2, 4, 5, 5, 6] 53 | k = 4 54 | Benchmark.bm do |x| 55 | x.report("find_kth_largest: ") { find_kth_largest(nums, k) } 56 | end 57 | -------------------------------------------------------------------------------- /algorithms/ruby/0055-jump-game.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 55. Jump Game 4 | # https://leetcode.com/problems/jump-game 5 | # Medium 6 | 7 | =begin 8 | You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. 9 | 10 | Return true if you can reach the last index, or false otherwise. 11 | 12 | Example 1: 13 | Input: nums = [2,3,1,1,4] 14 | Output: true 15 | Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. 16 | 17 | Example 2: 18 | Input: nums = [3,2,1,0,4] 19 | Output: false 20 | Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. 21 | 22 | Constraints: 23 | 1 <= nums.length <= 104 24 | 0 <= nums[i] <= 105 25 | =end 26 | 27 | # @param {Integer[]} nums 28 | # @return {Boolean} 29 | def can_jump(nums) 30 | i = nums.length - 2 31 | distance = 1 32 | 33 | while i >= 0 do 34 | if nums[i] - distance >= 0 35 | distance = 1 36 | else 37 | distance += 1 38 | end 39 | 40 | i -= 1 41 | end 42 | 43 | distance == 1 44 | end 45 | 46 | # **************** # 47 | # TEST # 48 | # **************** # 49 | 50 | require "test/unit" 51 | class Test_can_jump < Test::Unit::TestCase 52 | def test_ 53 | assert_equal true, can_jump([2, 3, 1, 1, 4]) 54 | assert_equal false, can_jump([3, 2, 1, 0, 4]) 55 | end 56 | end 57 | -------------------------------------------------------------------------------- /algorithms/ruby/0319-bulb-switcher.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 319. Bulb Switcher 4 | # https://leetcode.com/problems/bulb-switcher 5 | # Medium 6 | 7 | =begin 8 | There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. 9 | 10 | On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. 11 | 12 | Return the number of bulbs that are on after n rounds. 13 | 14 | Example 1: 15 | Input: n = 3 16 | Output: 1 17 | Explanation: At first, the three bulbs are [off, off, off]. 18 | After the first round, the three bulbs are [on, on, on]. 19 | After the second round, the three bulbs are [on, off, on]. 20 | After the third round, the three bulbs are [on, off, off]. 21 | So you should return 1 because there is only one bulb is on. 22 | 23 | Example 2: 24 | Input: n = 0 25 | Output: 0 26 | 27 | Example 3: 28 | Input: n = 1 29 | Output: 1 30 | 31 | Constraints: 32 | 0 <= n <= 109 33 | =end 34 | 35 | # @param {Integer} n 36 | # @return {Integer} 37 | def bulb_switch(n) 38 | Integer.sqrt(n) 39 | end 40 | 41 | # **************** # 42 | # TEST # 43 | # **************** # 44 | 45 | require "test/unit" 46 | class Test_two_sum < Test::Unit::TestCase 47 | def test_ 48 | assert_equal 1, bulb_switch(3) 49 | assert_equal 0, bulb_switch(0) 50 | assert_equal 1, bulb_switch(1) 51 | end 52 | end 53 | -------------------------------------------------------------------------------- /algorithms/ruby/0274-h-index.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 274. H-Index 4 | # https://leetcode.com/problems/h-index 5 | # Medium 6 | 7 | =begin 8 | Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return the researcher's h-index. 9 | 10 | According to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h such that the given researcher has published at least h papers that have each been cited at least h times. 11 | 12 | Example 1: 13 | Input: citations = [3,0,6,1,5] 14 | Output: 3 15 | Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. 16 | Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. 17 | 18 | Example 2: 19 | Input: citations = [1,3,1] 20 | Output: 1 21 | 22 | Constraints: 23 | n == citations.length 24 | 1 <= n <= 5000 25 | 0 <= citations[i] <= 1000 26 | =end 27 | 28 | # @param {Integer[]} citations 29 | # @return {Integer} 30 | def h_index(citations) 31 | citations.sort.reverse.each_with_index.count(&:>) 32 | end 33 | 34 | # **************** # 35 | # TEST # 36 | # **************** # 37 | 38 | require "test/unit" 39 | class Test_h_index < Test::Unit::TestCase 40 | def test_ 41 | assert_equal 3, h_index([3, 0, 6, 1, 5]) 42 | assert_equal 1, h_index([1, 3, 1]) 43 | end 44 | end 45 | -------------------------------------------------------------------------------- /algorithms/ruby/0278-first-bad-version.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 278. First Bad Version 4 | # https://leetcode.com/problems/first-bad-version 5 | 6 | =begin 7 | 8 | You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. 9 | 10 | Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. 11 | 12 | You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. 13 | 14 | ### Example 1: 15 | Input: n = 5, bad = 4 16 | Output: 4 17 | Explanation: 18 | call isBadVersion(3) -> false 19 | call isBadVersion(5) -> true 20 | call isBadVersion(4) -> true 21 | Then 4 is the first bad version. 22 | 23 | ### Example 2: 24 | Input: n = 1, bad = 1 25 | Output: 1 26 | 27 | ### Constraints: 28 | * 1 <= bad <= n <= 231 - 1 29 | 30 | =end 31 | 32 | # The is_bad_version API is already defined for you. 33 | # @param {Integer} version 34 | # @return {boolean} whether the version is bad 35 | # def is_bad_version(version): 36 | 37 | # Runtime: 74 ms 38 | # Memory: 211 MB 39 | # @param {Integer} n 40 | # @return {Integer} 41 | def first_bad_version(n) 42 | (1..n).bsearch { |i| is_bad_version(i) } 43 | end 44 | -------------------------------------------------------------------------------- /algorithms/ruby/0896-monotonic-array.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 896. Monotonic Array 4 | # Easy 5 | # https://leetcode.com/problems/monotonic-array 6 | 7 | =begin 8 | An array is monotonic if it is either monotone increasing or monotone decreasing. 9 | An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j]. 10 | Given an integer array nums, return true if the given array is monotonic, or false otherwise. 11 | 12 | Example 1: 13 | Input: nums = [1,2,2,3] 14 | Output: true 15 | 16 | Example 2: 17 | Input: nums = [6,5,4,4] 18 | Output: true 19 | 20 | Example 3: 21 | Input: nums = [1,3,2] 22 | Output: false 23 | 24 | Constraints: 25 | 1 <= nums.length <= 105 26 | -105 <= nums[i] <= 105 27 | =end 28 | 29 | # @param {Integer[]} nums 30 | # @return {Boolean} 31 | def is_monotonic(nums) 32 | x = nums 33 | up = false 34 | down = false 35 | (1...x.size).each do |i| 36 | return false if up && down 37 | up = true if x[i - 1] < x[i] 38 | down = true if x[i - 1] > x[i] 39 | end 40 | return false if up && down 41 | true 42 | end 43 | 44 | # **************** # 45 | # TEST # 46 | # **************** # 47 | 48 | require "test/unit" 49 | class Test_is_monotonic < Test::Unit::TestCase 50 | def test_ 51 | assert_equal true, is_monotonic([1, 2, 2, 3]) 52 | assert_equal true, is_monotonic([6, 5, 4, 4]) 53 | assert_equal false, is_monotonic([1, 3, 2]) 54 | end 55 | end 56 | -------------------------------------------------------------------------------- /algorithms/ruby/0082-remove-duplicates-from-sorted-list-ii.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 82. Remove Duplicates from Sorted List II 4 | # https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii 5 | # Medium 6 | 7 | =begin 8 | Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well. 9 | 10 | Example 1: 11 | Input: head = [1,2,3,3,4,4,5] 12 | Output: [1,2,5] 13 | 14 | Example 2: 15 | Input: head = [1,1,1,2,3] 16 | Output: [2,3] 17 | 18 | Constraints: 19 | * The number of nodes in the list is in the range [0, 300]. 20 | * -100 <= Node.val <= 100 21 | * The list is guaranteed to be sorted in ascending order. 22 | =end 23 | 24 | # Definition for singly-linked list. 25 | # class ListNode 26 | # attr_accessor :val, :next 27 | # def initialize(val = 0, _next = nil) 28 | # @val = val 29 | # @next = _next 30 | # end 31 | # end 32 | # @param {ListNode} head 33 | # @return {ListNode} 34 | def delete_duplicates(head) 35 | dummy = ListNode.new(-101, head) 36 | prev = dummy 37 | current = head 38 | 39 | while current 40 | if current.next && current.val == current.next.val 41 | while current.next && current.val == current.next.val 42 | current = current.next 43 | end 44 | prev.next = current.next 45 | else 46 | prev = current 47 | end 48 | current = current.next 49 | end 50 | 51 | dummy.next 52 | end 53 | -------------------------------------------------------------------------------- /algorithms/ruby/0202-happy-number.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 202. Happy Number 4 | # https://leetcode.com/problems/happy-number 5 | 6 | =begin 7 | 8 | Write an algorithm to determine if a number n is happy. 9 | 10 | A happy number is a number defined by the following process: 11 | 12 | Starting with any positive integer, replace the number by the sum of the squares of its digits. 13 | Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. 14 | Those numbers for which this process ends in 1 are happy. 15 | Return true if n is a happy number, and false if not. 16 | 17 | 18 | ### Example 1: 19 | Input: n = 19 20 | Output: true 21 | Explanation: 22 | 12 + 92 = 82 23 | 82 + 22 = 68 24 | 62 + 82 = 100 25 | 12 + 02 + 02 = 1 26 | 27 | ### Example 2: 28 | Input: n = 2 29 | Output: false 30 | 31 | ### Constraints: 32 | * 1 <= n <= 231 - 1 33 | 34 | =end 35 | 36 | # @param {Integer} n 37 | # @return {Boolean} 38 | def is_happy(n) 39 | touched = [] 40 | res = n 41 | 42 | loop do 43 | res = res.digits.sum { |el| el * el } 44 | 45 | return false if touched.include?(res) 46 | return true if res == 1 47 | 48 | touched << res 49 | end 50 | end 51 | 52 | # **************** # 53 | # TEST # 54 | # **************** # 55 | 56 | require "test/unit" 57 | class Test_is_happy < Test::Unit::TestCase 58 | def test_ 59 | assert_equal true, is_happy(19) 60 | assert_equal false, is_happy(2) 61 | end 62 | end 63 | -------------------------------------------------------------------------------- /algorithms/ruby/0092-reverse-linked-list-ii.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 92. Reverse Linked List II 4 | # https://leetcode.com/problems/reverse-linked-list-ii 5 | # Medium 6 | 7 | =begin 8 | Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list. 9 | 10 | Example 1: 11 | Input: head = [1,2,3,4,5], left = 2, right = 4 12 | Output: [1,4,3,2,5] 13 | 14 | Example 2: 15 | Input: head = [5], left = 1, right = 1 16 | Output: [5] 17 | 18 | Constraints: 19 | * The number of nodes in the list is n. 20 | * 1 <= n <= 500 21 | * -500 <= Node.val <= 500 22 | * 1 <= left <= right <= n 23 | =end 24 | 25 | # Definition for singly-linked list. 26 | # class ListNode 27 | # attr_accessor :val, :next 28 | # def initialize(val = 0, _next = nil) 29 | # @val = val 30 | # @next = _next 31 | # end 32 | # end 33 | # @param {ListNode} head 34 | # @param {Integer} left 35 | # @param {Integer} right 36 | # @return {ListNode} 37 | def reverse_between(head, left, right) 38 | dummy = ListNode.new(0) 39 | dummy.next = head 40 | prev = dummy 41 | 42 | (left - 1).times do 43 | prev = prev.next 44 | end 45 | 46 | start = prev.next 47 | then_node = start.next 48 | 49 | (right - left).times do 50 | start.next = then_node.next 51 | then_node.next = prev.next 52 | prev.next = then_node 53 | then_node = start.next 54 | end 55 | 56 | dummy.next 57 | end 58 | -------------------------------------------------------------------------------- /algorithms/ruby/0637-average-of-levels-in-binary-tree.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 637. Average of Levels in Binary Tree 4 | # https://leetcode.com/problems/average-of-levels-in-binary-tree 5 | # Easy 6 | 7 | =begin 8 | Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted. 9 | 10 | Example 1: 11 | Input: root = [3,9,20,null,null,15,7] 12 | Output: [3.00000,14.50000,11.00000] 13 | Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. 14 | Hence return [3, 14.5, 11]. 15 | 16 | Example 2: 17 | Input: root = [3,9,20,15,7] 18 | Output: [3.00000,14.50000,11.00000] 19 | 20 | Constraints: 21 | * The number of nodes in the tree is in the range [1, 104]. 22 | * -231 <= Node.val <= 231 - 1 23 | =end 24 | 25 | # Definition for a binary tree node. 26 | # class TreeNode 27 | # attr_accessor :val, :left, :right 28 | # def initialize(val = 0, left = nil, right = nil) 29 | # @val = val 30 | # @left = left 31 | # @right = right 32 | # end 33 | # end 34 | # @param {TreeNode} root 35 | # @return {Float[]} 36 | def average_of_levels(root, sums = [], level = 0) 37 | return if !root 38 | sums[level] ||= [0, 0] 39 | sums[level][0] += root.val 40 | sums[level][1] += 1 41 | average_of_levels(root.left, sums, level + 1) 42 | average_of_levels(root.right, sums, level + 1) 43 | sums.map { |sum, n| sum.fdiv(n) } if level == 0 44 | end 45 | -------------------------------------------------------------------------------- /algorithms/ruby/1456-maximum-number-of-vowels-in-a-substring-of-given-length.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 1456. Maximum Number of Vowels in a Substring of Given Length 4 | # https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length 5 | # Medium 6 | 7 | =begin 8 | Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k. 9 | 10 | Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'. 11 | 12 | Example 1: 13 | Input: s = "abciiidef", k = 3 14 | Output: 3 15 | Explanation: The substring "iii" contains 3 vowel letters. 16 | 17 | Example 2: 18 | Input: s = "aeiou", k = 2 19 | Output: 2 20 | Explanation: Any substring of length 2 contains 2 vowels. 21 | 22 | Example 3: 23 | Input: s = "leetcode", k = 3 24 | Output: 2 25 | Explanation: "lee", "eet" and "ode" contain 2 vowels. 26 | 27 | Constraints: 28 | 1 <= s.length <= 105 29 | s consists of lowercase English letters. 30 | 1 <= k <= s.length 31 | =end 32 | 33 | # @param {String} s 34 | # @param {Integer} k 35 | # @return {Integer} 36 | def max_vowels(s, k) 37 | (0..s.length - k).map { |i| s[i..i + k - 1].count("aeiou") }.max 38 | end 39 | 40 | # **************** # 41 | # TEST # 42 | # **************** # 43 | 44 | require "test/unit" 45 | class Test_max_vowels < Test::Unit::TestCase 46 | def test_ 47 | assert_equal 3, max_vowels("abciiidef", 3) 48 | assert_equal 2, max_vowels("aeiou", 2) 49 | assert_equal 2, max_vowels("leetcode", 3) 50 | end 51 | end 52 | -------------------------------------------------------------------------------- /algorithms/ruby/1732-find-the-highest-altitude.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 1732. Find the Highest Altitude 4 | # https://leetcode.com/problems/find-the-highest-altitude 5 | # Easy 6 | 7 | =begin 8 | There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts his trip on point 0 with altitude equal 0. 9 | 10 | You are given an integer array gain of length n where gain[i] is the net gain in altitude between points i and i + 1 for all (0 <= i < n). Return the highest altitude of a point. 11 | 12 | Example 1: 13 | Input: gain = [-5,1,5,0,-7] 14 | Output: 1 15 | Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1. 16 | 17 | Example 2: 18 | Input: gain = [-4,-3,-2,-1,4,3,2] 19 | Output: 0 20 | Explanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0. 21 | 22 | Constraints: 23 | n == gain.length 24 | 1 <= n <= 100 25 | -100 <= gain[i] <= 100 26 | =end 27 | 28 | # @param {Integer[]} gain 29 | # @return {Integer} 30 | def largest_altitude(gain) 31 | prefix = gain.inject([]) { |acc, value| acc << acc.last.to_i + value.to_i } 32 | max_gain = prefix.max 33 | max_gain < 0 ? 0 : max_gain 34 | end 35 | 36 | # **************** # 37 | # TEST # 38 | # **************** # 39 | 40 | require "test/unit" 41 | class Test_largest_altitude < Test::Unit::TestCase 42 | def test_ 43 | assert_equal 1, largest_altitude([-5, 1, 5, 0, -7]) 44 | assert_equal 0, largest_altitude([-4, -3, -2, -1, 4, 3, 2]) 45 | end 46 | end 47 | -------------------------------------------------------------------------------- /algorithms/ruby/0095-unique-binary-search-trees-ii.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 95. Unique Binary Search Trees II 4 | # Medium 5 | # https://leetcode.com/problems/unique-binary-search-trees-ii 6 | 7 | =begin 8 | Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order. 9 | 10 | Example 1: 11 | Input: n = 3 12 | Output: [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]] 13 | 14 | Example 2: 15 | Input: n = 1 16 | Output: [[1]] 17 | 18 | Constraints: 19 | * 1 <= n <= 8 20 | =end 21 | 22 | # Definition for a binary tree node. 23 | # class TreeNode 24 | # attr_accessor :val, :left, :right 25 | # def initialize(val = 0, left = nil, right = nil) 26 | # @val = val 27 | # @left = left 28 | # @right = right 29 | # end 30 | # end 31 | # @param {Integer} n 32 | # @return {TreeNode[]} 33 | def generate(start_val, end_val) 34 | return [nil] if start_val > end_val 35 | 36 | result = [] 37 | (start_val..end_val).each do |i| 38 | left_trees = generate(start_val, i - 1) 39 | right_trees = generate(i + 1, end_val) 40 | 41 | left_trees.each do |l| 42 | right_trees.each do |r| 43 | node = TreeNode.new(i) 44 | node.left = l 45 | node.right = r 46 | result << node 47 | end 48 | end 49 | end 50 | result 51 | end 52 | 53 | def generate_trees(n) 54 | return [] if n == 0 55 | generate(1, n) 56 | end 57 | -------------------------------------------------------------------------------- /algorithms/ruby/0238-product-of-array-except-self.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 238. Product of Array Except Self 4 | # https://leetcode.com/problems/product-of-array-except-self 5 | # Medium 6 | 7 | =begin 8 | Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. 9 | The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. 10 | You must write an algorithm that runs in O(n) time and without using the division operation. 11 | 12 | Example 1: 13 | Input: nums = [1,2,3,4] 14 | Output: [24,12,8,6] 15 | 16 | Example 2: 17 | Input: nums = [-1,1,0,-3,3] 18 | Output: [0,0,9,0,0] 19 | 20 | Constraints: 21 | * 2 <= nums.length <= 105 22 | * -30 <= nums[i] <= 30 23 | * The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. 24 | =end 25 | 26 | # @param {Integer[]} nums 27 | # @return {Integer[]} 28 | def product_except_self(nums) 29 | n = nums.size 30 | out = [1] * n 31 | left = right = 1 32 | 1.upto(n - 1) { |i| 33 | out[i] *= left *= nums[i - 1] 34 | out[~i] *= right *= nums[-i] 35 | } 36 | out 37 | end 38 | 39 | # **************** # 40 | # TEST # 41 | # **************** # 42 | 43 | require "test/unit" 44 | class Test_length_of_longest_substring < Test::Unit::TestCase 45 | def test_ 46 | assert_equal [24, 12, 8, 6], product_except_self([1, 2, 3, 4]) 47 | assert_equal [0, 0, 9, 0, 0], product_except_self([-1, 1, 0, -3, 3]) 48 | end 49 | end 50 | -------------------------------------------------------------------------------- /algorithms/ruby/0779-k-th-symbol-in-grammar.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 779. K-th Symbol in Grammar 4 | # Medium 5 | # https://leetcode.com/problems/k-th-symbol-in-grammar 6 | 7 | =begin 8 | We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10. 9 | * For example, for n = 3, the 1st row is 0, the 2nd row is 01, and the 3rd row is 0110. 10 | Given two integer n and k, return the kth (1-indexed) symbol in the nth row of a table of n rows. 11 | 12 | Example 1: 13 | Input: n = 1, k = 1 14 | Output: 0 15 | Explanation: row 1: 0 16 | 17 | Example 2: 18 | Input: n = 2, k = 1 19 | Output: 0 20 | Explanation: 21 | row 1: 0 22 | row 2: 01 23 | 24 | Example 3: 25 | Input: n = 2, k = 2 26 | Output: 1 27 | Explanation: 28 | row 1: 0 29 | row 2: 01 30 | 31 | Constraints: 32 | 1 <= n <= 30 33 | 1 <= k <= 2n - 1 34 | =end 35 | 36 | # @param {Integer} n 37 | # @param {Integer} k 38 | # @return {Integer} 39 | def kth_grammar(n, k) 40 | r = 0 41 | while n > 1 42 | k.odd? ? k += 1 : r ^= 1 43 | k /= 2 44 | n -= 1 45 | end 46 | r 47 | end 48 | 49 | # **************** # 50 | # TEST # 51 | # **************** # 52 | 53 | require "test/unit" 54 | class Test_kth_grammar < Test::Unit::TestCase 55 | def test_ 56 | assert_equal 0, kth_grammar(1, 1) 57 | assert_equal 0, kth_grammar(2, 1) 58 | assert_equal 1, kth_grammar(2, 2) 59 | end 60 | end 61 | -------------------------------------------------------------------------------- /algorithms/ruby/0287-find-the-duplicate-number.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 287. Find the Duplicate Number 4 | # Medium 5 | # https://leetcode.com/problems/find-the-duplicate-number 6 | 7 | =begin 8 | Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. 9 | There is only one repeated number in nums, return this repeated number. 10 | You must solve the problem without modifying the array nums and uses only constant extra space. 11 | 12 | Example 1: 13 | Input: nums = [1,3,4,2,2] 14 | Output: 2 15 | 16 | Example 2: 17 | Input: nums = [3,1,3,4,2] 18 | Output: 3 19 | 20 | 21 | Constraints: 22 | * 1 <= n <= 105 23 | * nums.length == n + 1 24 | * 1 <= nums[i] <= n 25 | * All the integers in nums appear only once except for precisely one integer which appears two or more times. 26 | =end 27 | 28 | # @param {Integer[]} nums 29 | # @return {Integer} 30 | def find_duplicate(nums) 31 | left, right = 1, nums.max 32 | 33 | while left < right 34 | mid = (left + right) / 2 35 | 36 | count = nums.count { |x| x <= mid } 37 | 38 | if count > mid 39 | right = mid 40 | else 41 | left = mid + 1 42 | end 43 | end 44 | 45 | left 46 | end 47 | 48 | # **************** # 49 | # TEST # 50 | # **************** # 51 | 52 | require "test/unit" 53 | class Test_find_duplicate < Test::Unit::TestCase 54 | def test_ 55 | assert_equal 2, find_duplicate([1, 3, 4, 2, 2]) 56 | assert_equal 3, find_duplicate([3, 1, 3, 4, 2]) 57 | end 58 | end 59 | -------------------------------------------------------------------------------- /algorithms/ruby/1232-check-if-it-is-a-straight-line.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # https://leetcode.com/problems/check-if-it-is-a-straight-line 4 | # 1232. Check If It Is a Straight Line 5 | # Easy 6 | 7 | =begin 8 | You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. 9 | 10 | Example 1: 11 | Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] 12 | Output: true 13 | 14 | Example 2: 15 | Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] 16 | Output: false 17 | 18 | Constraints: 19 | * 2 <= coordinates.length <= 1000 20 | * coordinates[i].length == 2 21 | * -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4 22 | * coordinates contains no duplicate point. 23 | =end 24 | 25 | # @param {Integer[][]} coordinates 26 | # @return {Boolean} 27 | def check_straight_line(coordinates) 28 | x1, y1 = coordinates.shift 29 | x2, y2 = coordinates.shift 30 | coordinates.each do |a, b| 31 | if (x2 - x1) * (b - y1) != (y2 - y1) * (a - x1) 32 | return false 33 | end 34 | end 35 | true 36 | end 37 | 38 | # **************** # 39 | # TEST # 40 | # **************** # 41 | 42 | require "test/unit" 43 | class Test_check_straight_line < Test::Unit::TestCase 44 | def test_ 45 | assert_equal true, check_straight_line([[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7]]) 46 | assert_equal false, check_straight_line([[1, 1], [2, 2], [3, 4], [4, 5], [5, 6], [7, 7]]) 47 | end 48 | end 49 | -------------------------------------------------------------------------------- /algorithms/ruby/0377-combination-sum-iv.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 377. Combination Sum IV 4 | # Medium 5 | # https://leetcode.com/problems/combination-sum-iv 6 | 7 | =begin 8 | Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target. 9 | The test cases are generated so that the answer can fit in a 32-bit integer. 10 | 11 | Example 1: 12 | Input: nums = [1,2,3], target = 4 13 | Output: 7 14 | Explanation: 15 | The possible combination ways are: 16 | (1, 1, 1, 1) 17 | (1, 1, 2) 18 | (1, 2, 1) 19 | (1, 3) 20 | (2, 1, 1) 21 | (2, 2) 22 | (3, 1) 23 | Note that different sequences are counted as different combinations. 24 | 25 | Example 2: 26 | Input: nums = [9], target = 3 27 | Output: 0 28 | 29 | Constraints: 30 | * 1 <= nums.length <= 200 31 | * 1 <= nums[i] <= 1000 32 | * All the elements of nums are unique. 33 | * 1 <= target <= 1000 34 | =end 35 | 36 | # @param {Integer[]} nums 37 | # @param {Integer} target 38 | # @return {Integer} 39 | def combination_sum4(nums, target) 40 | a = [1] + [0] * target 41 | 42 | (1..target).each do |i| 43 | nums.each do |num| 44 | a[i] += a[i - num] if num <= i 45 | end 46 | end 47 | 48 | a.last 49 | end 50 | 51 | # **************** # 52 | # TEST # 53 | # **************** # 54 | 55 | require "test/unit" 56 | class Test_combination_sum4 < Test::Unit::TestCase 57 | def test_ 58 | assert_equal 7, combination_sum4([1, 2, 3], 4) 59 | assert_equal 0, combination_sum4([9], 3) 60 | end 61 | end 62 | -------------------------------------------------------------------------------- /algorithms/ruby/0875-koko-eating-bananas.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 875. Koko Eating Bananas 4 | # https://leetcode.com/problems/koko-eating-bananas 5 | # Medium 6 | 7 | =begin 8 | 9 | Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours. 10 | 11 | Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour. 12 | 13 | Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return. 14 | 15 | Return the minimum integer k such that she can eat all the bananas within h hours. 16 | 17 | Constraints: 18 | 19 | * 1 <= piles.length <= 104 20 | * piles.length <= h <= 109 21 | * 1 <= piles[i] <= 109 22 | 23 | =end 24 | 25 | # @param {Integer[]} piles 26 | # @param {Integer} h 27 | # @return {Integer} 28 | def min_eating_speed(piles, h) 29 | (1..piles.max).bsearch do |x| 30 | piles.sum { (_1 + x - 1) / x } <= h 31 | end 32 | end 33 | 34 | # ********************# 35 | # TEST # 36 | # ********************# 37 | 38 | require "test/unit" 39 | class Test_min_eating_speed < Test::Unit::TestCase 40 | def test_ 41 | assert_equal 4, min_eating_speed([3, 6, 7, 11], 8) 42 | assert_equal 30, min_eating_speed([30, 11, 23, 4, 20], 5) 43 | assert_equal 23, min_eating_speed([30, 11, 23, 4, 20], 6) 44 | end 45 | end 46 | -------------------------------------------------------------------------------- /algorithms/ruby/1359-count-all-valid-pickup-and-delivery-options.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 1359. Count All Valid Pickup and Delivery Options 4 | # Hard 5 | # https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options 6 | 7 | =begin 8 | Given n orders, each order consist in pickup and delivery services. 9 | Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). 10 | Since the answer may be too large, return it modulo 10^9 + 7. 11 | 12 | Example 1: 13 | Input: n = 1 14 | Output: 1 15 | Explanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1. 16 | 17 | Example 2: 18 | Input: n = 2 19 | Output: 6 20 | Explanation: All possible orders: 21 | (P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1). 22 | This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2. 23 | 24 | Example 3: 25 | Input: n = 3 26 | Output: 90 27 | 28 | Constraints: 29 | * 1 <= n <= 500 30 | =end 31 | 32 | # @param {Integer} n 33 | # @return {Integer} 34 | def count_orders(n) 35 | ans = 1 36 | mod = (10**9) + 7 37 | (1..n).each do |i| 38 | ans *= i * (2 * i - 1) 39 | ans %= mod 40 | end 41 | ans 42 | end 43 | 44 | # **************** # 45 | # TEST # 46 | # **************** # 47 | 48 | require "test/unit" 49 | class Test_count_orders < Test::Unit::TestCase 50 | def test_ 51 | assert_equal 1, count_orders(1) 52 | assert_equal 6, count_orders(2) 53 | assert_equal 90, count_orders(3) 54 | end 55 | end 56 | -------------------------------------------------------------------------------- /algorithms/ruby/1822-sign-of-the-product-of-an-array.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 1822. Sign of the Product of an Array 4 | # https://leetcode.com/problems/sign-of-the-product-of-an-array 5 | # Easy 6 | 7 | =begin 8 | There is a function signFunc(x) that returns: 9 | 10 | * 1 if x is positive. 11 | * -1 if x is negative. 12 | * 0 if x is equal to 0. 13 | You are given an integer array nums. Let product be the product of all values in the array nums. 14 | 15 | Return signFunc(product). 16 | 17 | Example 1: 18 | Input: nums = [-1,-2,-3,-4,3,2,1] 19 | Output: 1 20 | Explanation: The product of all values in the array is 144, and signFunc(144) = 1 21 | 22 | Example 2: 23 | Input: nums = [1,5,0,2,-3] 24 | Output: 0 25 | Explanation: The product of all values in the array is 0, and signFunc(0) = 0 26 | 27 | Example 3: 28 | Input: nums = [-1,1,-1,1,-1] 29 | Output: -1 30 | Explanation: The product of all values in the array is -1, and signFunc(-1) = -1 31 | 32 | Constraints: 33 | * 1 <= nums.length <= 1000 34 | * -100 <= nums[i] <= 100 35 | =end 36 | 37 | # @param {Integer[]} nums 38 | # @return {Integer} 39 | def array_sign(nums) 40 | nums.reduce(1) { _1 * (_2 <=> 0) } 41 | end 42 | 43 | # **************** # 44 | # TEST # 45 | # **************** # 46 | 47 | require "test/unit" 48 | class Test_array_sign < Test::Unit::TestCase 49 | def test_ 50 | assert_equal 1, array_sign([-1, -2, -3, -4, 3, 2, 1]) 51 | assert_equal 0, array_sign([1, 5, 0, 2, -3]) 52 | assert_equal(-1, array_sign([-1, 1, -1, 1, -1])) 53 | end 54 | end 55 | -------------------------------------------------------------------------------- /algorithms/ruby/0300-longest-increasing-subsequence.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 300. Longest Increasing Subsequence 4 | # https://leetcode.com/problems/longest-increasing-subsequence 5 | # Medium 6 | 7 | =begin 8 | Given an integer array nums, return the length of the longest strictly increasing subsequence. 9 | 10 | Example 1: 11 | Input: nums = [10,9,2,5,3,7,101,18] 12 | Output: 4 13 | Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. 14 | 15 | Example 2: 16 | Input: nums = [0,1,0,3,2,3] 17 | Output: 4 18 | 19 | Example 3: 20 | Input: nums = [7,7,7,7,7,7,7] 21 | Output: 1 22 | 23 | Constraints: 24 | 1 <= nums.length <= 2500 25 | -104 <= nums[i] <= 104 26 | =end 27 | 28 | # @param {Integer[]} nums 29 | # @return {Integer} 30 | def length_of_lis(nums) 31 | tails = Array.new 32 | k = 0 33 | nums.each do |num| 34 | start, finish = 0, k 35 | while start != finish 36 | mid = (start + finish) / 2 37 | if tails[mid] < num 38 | start = mid + 1 39 | else 40 | finish = mid 41 | end 42 | end 43 | tails[start] = num 44 | k += 1 if start == k 45 | end 46 | k 47 | end 48 | 49 | # **************** # 50 | # TEST # 51 | # **************** # 52 | 53 | require "test/unit" 54 | class Test_length_of_lis < Test::Unit::TestCase 55 | def test_ 56 | assert_equal 4, length_of_lis([10, 9, 2, 5, 3, 7, 101, 18]) 57 | assert_equal 4, length_of_lis([0, 1, 0, 3, 2, 3]) 58 | assert_equal 1, length_of_lis([7, 7, 7, 7, 7, 7, 7]) 59 | end 60 | end 61 | -------------------------------------------------------------------------------- /algorithms/ruby/1464-maximum-product-of-two-elements-in-an-array.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 1464. Maximum Product of Two Elements in an Array 4 | # Easy 5 | # https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array 6 | 7 | =begin 8 | Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1). 9 | 10 | Example 1: 11 | Input: nums = [3,4,5,2] 12 | Output: 12 13 | Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. 14 | 15 | Example 2: 16 | Input: nums = [1,5,4,5] 17 | Output: 16 18 | Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16. 19 | 20 | Example 3: 21 | Input: nums = [3,7] 22 | Output: 12 23 | 24 | Constraints: 25 | 2 <= nums.length <= 500 26 | 1 <= nums[i] <= 10^3 27 | =end 28 | 29 | # @param {Integer[]} nums 30 | # @return {Integer} 31 | def max_product(nums) 32 | vice = max = 0 33 | nums.each do |num| 34 | next if num < vice 35 | vice, max = [num, max].minmax 36 | end 37 | (vice - 1) * (max - 1) 38 | end 39 | 40 | # **************** # 41 | # TEST # 42 | # **************** # 43 | 44 | require "test/unit" 45 | class Test_max_product < Test::Unit::TestCase 46 | def test_ 47 | assert_equal 12, max_product([3, 4, 5, 2]) 48 | assert_equal 16, max_product([1, 5, 4, 5]) 49 | assert_equal 12, max_product([3, 7]) 50 | end 51 | end 52 | -------------------------------------------------------------------------------- /algorithms/ruby/0643-maximum-average-subarray-i.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 643. Maximum Average Subarray I 4 | # https://leetcode.com/problems/maximum-average-subarray-i 5 | # Easy 6 | 7 | =begin 8 | You are given an integer array nums consisting of n elements, and an integer k. 9 | 10 | Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10-5 will be accepted. 11 | 12 | Example 1: 13 | Input: nums = [1,12,-5,-6,50,3], k = 4 14 | Output: 12.75000 15 | Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75 16 | 17 | Example 2: 18 | Input: nums = [5], k = 1 19 | Output: 5.00000 20 | 21 | Constraints: 22 | n == nums.length 23 | 1 <= k <= n <= 105 24 | -104 <= nums[i] <= 104 25 | =end 26 | 27 | # @param {Integer[]} nums 28 | # @param {Integer} k 29 | # @return {Float} 30 | def find_max_average(nums, k) 31 | max_sum = 0 32 | i = 0 33 | while i < k do 34 | max_sum += nums[i] 35 | i += 1 36 | end 37 | 38 | new_sum = max_sum 39 | 40 | while i < nums.length do 41 | new_sum += nums[i] - nums[i - k] 42 | max_sum = new_sum if new_sum > max_sum 43 | i += 1 44 | end 45 | max_sum / k.to_f 46 | end 47 | 48 | # **************** # 49 | # TEST # 50 | # **************** # 51 | 52 | require "test/unit" 53 | class Test_max_vowels < Test::Unit::TestCase 54 | def test_ 55 | assert_equal 12.75, find_max_average([1, 12, -5, -6, 50, 3], 4) 56 | assert_equal 5.0, find_max_average([5], 1) 57 | end 58 | end 59 | -------------------------------------------------------------------------------- /algorithms/python3/1444-number-of-ways-of-cutting-a-pizza.py: -------------------------------------------------------------------------------- 1 | # 1444. Number of Ways of Cutting a Pizza 2 | # https://leetcode.com/problems/number-of-ways-of-cutting-a-pizza 3 | 4 | from functools import lru_cache 5 | 6 | class Solution: 7 | def ways(self, pizza: list[str], K: int) -> int: 8 | m, n, MOD = len(pizza), len(pizza[0]), 10 ** 9 + 7 9 | preSum = [[0] * (n + 1) for _ in range(m + 1)] 10 | 11 | for r in range(m - 1, -1, -1): 12 | for c in range(n - 1, -1, -1): 13 | preSum[r][c] = preSum[r][c + 1] + preSum[r + 1][c] - preSum[r + 1][c + 1] + (pizza[r][c] == 'A') 14 | 15 | @lru_cache(None) 16 | def dp(k, r, c): 17 | if preSum[r][c] == 0: return 0 18 | if k == 0: return 1 19 | ans = 0 20 | 21 | for nr in range(r + 1, m): 22 | if preSum[r][c] - preSum[nr][c] > 0: 23 | ans = (ans + dp(k - 1, nr, c)) % MOD 24 | for nc in range(c + 1, n): 25 | if preSum[r][c] - preSum[r][nc] > 0: 26 | ans = (ans + dp(k - 1, r, nc)) % MOD 27 | 28 | return ans 29 | 30 | return dp(K - 1, 0, 0) 31 | 32 | # ********************# 33 | # TEST # 34 | # ********************# 35 | 36 | import unittest 37 | 38 | class TestStringMethods(unittest.TestCase): 39 | def test_ways(self): 40 | self.assertEqual(Solution.ways(self, ["A..", "AAA", "..."], 3), 3) 41 | self.assertEqual(Solution.ways(self, ["A..", "AA.", "..."], 3), 1) 42 | self.assertEqual(Solution.ways(self, ["A..", "A..", "..."], 1), 1) 43 | 44 | 45 | if __name__ == '__main__': 46 | unittest.main() 47 | -------------------------------------------------------------------------------- /algorithms/ruby/0790-domino-and-tromino-tiling.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 790. Domino and Tromino Tiling 4 | # https://leetcode.com/problems/domino-and-tromino-tiling 5 | # Medium 6 | 7 | =begin 8 | You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes. 9 | 10 | Given an integer n, return the number of ways to tile an 2 x n board. Since the answer may be very large, return it modulo 109 + 7. 11 | 12 | In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile. 13 | 14 | Example 1: 15 | Input: n = 3 16 | Output: 5 17 | Explanation: The five different ways are show above. 18 | 19 | Example 2: 20 | Input: n = 1 21 | Output: 1 22 | 23 | Constraints: 24 | 1 <= n <= 1000 25 | =end 26 | 27 | # @param {Integer} n 28 | # @return {Integer} 29 | MOD = 10**9 + 7 30 | def num_tilings(n) 31 | dp = Array.new(3) { Array.new(2, 0) } 32 | dp[1] = [1, 1] 33 | dp[2] = [2, 2] 34 | (3..n).each do |i| 35 | dp[i % 3][0] = dp[(i - 1) % 3][0] + dp[(i - 2) % 3][0] + 2 * dp[(i - 2) % 3][1] 36 | dp[i % 3][1] = dp[(i - 1) % 3][0] + dp[(i - 1) % 3][1] 37 | end 38 | dp[n % 3][0] % MOD 39 | end 40 | 41 | # **************** # 42 | # TEST # 43 | # **************** # 44 | 45 | require "test/unit" 46 | class Test_num_tilings < Test::Unit::TestCase 47 | def test_ 48 | assert_equal 5, num_tilings(3) 49 | assert_equal 1, num_tilings(1) 50 | end 51 | end 52 | -------------------------------------------------------------------------------- /algorithms/ruby/0017-letter-combinations-of-a-phone-number.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 17. Letter Combinations of a Phone Number 4 | # https://leetcode.com/problems/letter-combinations-of-a-phone-number 5 | # Medium 6 | 7 | =begin 8 | Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. 9 | 10 | A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. 11 | 12 | Example 1: 13 | Input: digits = "23" 14 | Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] 15 | 16 | Example 2: 17 | Input: digits = "" 18 | Output: [] 19 | 20 | Example 3: 21 | Input: digits = "2" 22 | Output: ["a","b","c"] 23 | 24 | Constraints: 25 | 0 <= digits.length <= 4 26 | digits[i] is a digit in the range ['2', '9']. 27 | =end 28 | 29 | # @param {String} digits 30 | # @return {String[]} 31 | def letter_combinations(digits) 32 | map = "- - abc def ghi jkl mno pqrs tuv wxyz".split 33 | charsets = digits.chars.map { |d| map[d.to_i].chars } 34 | digits == "" ? [] : [""].product(*charsets).map(&:join) 35 | end 36 | 37 | # **************** # 38 | # TEST # 39 | # **************** # 40 | 41 | require "test/unit" 42 | class Test_letter_combinations < Test::Unit::TestCase 43 | def test_ 44 | assert_equal ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"], letter_combinations("23") 45 | assert_equal [], letter_combinations("") 46 | assert_equal ["a", "b", "c"], letter_combinations("2") 47 | end 48 | end 49 | -------------------------------------------------------------------------------- /algorithms/ruby/0056-merge-intervals.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 56. Merge Intervals 4 | # https://leetcode.com/problems/merge-intervals 5 | # Medium 6 | 7 | =begin 8 | Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. 9 | 10 | Example 1: 11 | Input: intervals = [[1,3],[2,6],[8,10],[15,18]] 12 | Output: [[1,6],[8,10],[15,18]] 13 | Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6]. 14 | 15 | Example 2: 16 | Input: intervals = [[1,4],[4,5]] 17 | Output: [[1,5]] 18 | Explanation: Intervals [1,4] and [4,5] are considered overlapping. 19 | 20 | Constraints: 21 | * 1 <= intervals.length <= 104 22 | * intervals[i].length == 2 23 | * 0 <= starti <= endi <= 104 24 | =end 25 | 26 | # @param {Integer[][]} intervals 27 | # @return {Integer[][]} 28 | def merge(intervals) 29 | result = [] 30 | 31 | intervals.sort_by { |interval| interval[0] }.each do |interval| 32 | if !result.empty? && interval[0] <= result[-1][1] 33 | result[-1][1] = [result[-1][1], interval[1]].max 34 | else 35 | result << interval 36 | end 37 | end 38 | 39 | result 40 | end 41 | 42 | # **************** # 43 | # TEST # 44 | # **************** # 45 | 46 | require "test/unit" 47 | class Test_merge < Test::Unit::TestCase 48 | def test_ 49 | assert_equal([[1, 6], [8, 10], [15, 18]], merge([[1, 3], [2, 6], [8, 10], [15, 18]])) 50 | assert_equal([[1, 5]], merge([[1, 4], [4, 5]])) 51 | end 52 | end 53 | -------------------------------------------------------------------------------- /algorithms/ruby/0098-validate-binary-search-tree.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 98. Validate Binary Search Tree 4 | # https://leetcode.com/problems/validate-binary-search-tree 5 | 6 | =begin 7 | 8 | Given the root of a binary tree, determine if it is a valid binary search tree (BST). 9 | 10 | A valid BST is defined as follows: 11 | 12 | * The left subtree of a node contains only nodes with keys less than the node's key. 13 | * The right subtree of a node contains only nodes with keys greater than the node's key. 14 | * Both the left and right subtrees must also be binary search trees. 15 | 16 | ### Example 1: 17 | Input: root = [2,1,3] 18 | Output: true 19 | 20 | ### Example 2: 21 | Input: root = [5,1,4,null,null,3,6] 22 | Output: false 23 | Explanation: The root node's value is 5 but its right child's value is 4. 24 | 25 | ### Constraints: 26 | * The number of nodes in the tree is in the range [1, 104]. 27 | * -231 <= Node.val <= 231 - 1 28 | 29 | =end 30 | 31 | # Runtime: 83 ms 32 | # Memory: 211.7 MB 33 | # Definition for a binary tree node. 34 | # class TreeNode 35 | # attr_accessor :val, :left, :right 36 | # def initialize(val = 0, left = nil, right = nil) 37 | # @val = val 38 | # @left = left 39 | # @right = right 40 | # end 41 | # end 42 | # @param {TreeNode} root 43 | # @return {Boolean} 44 | def is_valid_bst(root, min = -Float::INFINITY, max = Float::INFINITY) 45 | !root || 46 | min < root.val && 47 | root.val < max && 48 | is_valid_bst(root.left, min, root.val) && 49 | is_valid_bst(root.right, root.val, max) 50 | end 51 | -------------------------------------------------------------------------------- /algorithms/ruby/0392-is-subsequence.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # 392. Is Subsequence 4 | # https://leetcode.com/problems/is-subsequence 5 | # Easy 6 | 7 | =begin 8 | 9 | Given two strings s and t, return true if s is a subsequence of t, or false otherwise. 10 | 11 | A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not). 12 | 13 | ### Example 1: 14 | 15 | Input: s = "abc", t = "ahbgdc" 16 | Output: true 17 | 18 | ### Example 2: 19 | 20 | Input: s = "axc", t = "ahbgdc" 21 | Output: false 22 | 23 | ### Constraints: 24 | 25 | * 0 <= s.length <= 100 26 | * 0 <= t.length <= 104 27 | * s and t consist only of lowercase English letters. 28 | 29 | =end 30 | 31 | # Runtime 86 ms 32 | # Memory 212.1 MB 33 | # @param {String} s 34 | # @param {String} t 35 | # @return {Boolean} 36 | def is_subsequence(s, t) 37 | return true if s.size == 0 38 | return false if s.size > t.size 39 | 40 | sp = 0 41 | t.chars.each do |char| 42 | if s[sp] == char 43 | sp += 1 44 | return true if sp == s.size 45 | end 46 | end 47 | 48 | false 49 | end 50 | 51 | # **************** # 52 | # TEST # 53 | # **************** # 54 | 55 | require "test/unit" 56 | class Test_is_subsequence < Test::Unit::TestCase 57 | def test_ 58 | assert_equal true, is_subsequence("abc", "ahbgdc") 59 | assert_equal false, is_subsequence("axc", "ahbgdc") 60 | end 61 | end 62 | --------------------------------------------------------------------------------