Skip to content

64, 206, 409, 876, 2316, 2360 #45

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
| 35 | Search Insert Position | [Ruby](./algorithms/ruby/0035-search-insert-position.rb) | Easy |
| 45 | Jump Game II | [Ruby](./algorithms/ruby/0045-jump-game-ii.rb) | Medium |
| 58 | Length of Last Word | [Ruby](./algorithms/ruby/0058-length-of-last-word.rb) | Easy |
| 64 | Minimum Path Sum | [Ruby](./algorithms/ruby/0064-minimum-path-sum.rb) | Medium |
| 66 | Plus One | [Ruby](./algorithms/ruby/0066-plus-one.rb) | Easy |
| 67 | Add Binary | [Ruby](./algorithms/ruby/0067-add-binary.rb) [Python3](./algorithms/python3/0067-add-binary.py) | Easy |
| 69 | Sqrt(x) | [Ruby](./algorithms/ruby/0069-sqrtx.rb) | Easy |
Expand All @@ -42,13 +43,15 @@
| 129 | Sum Root to Leaf Numbers | [Ruby](./algorithms/ruby/0129-sum-root-to-leaf-numbers.rb) | Medium |
| 142 | Linked List Cycle II | [Ruby](./algorithms/ruby/0142-linked-list-cycle-ii.rb) | Medium |
| 205 | Isomorphic Strings | [Ruby](./algorithms/ruby/0205-isomorphic-strings.rb) | Easy |
| 206 | Reverse Linked List | [Ruby](./algorithms/ruby/0206-reverse-linked-list.rb) | Easy |
| 208 | Implement Trie (Prefix Tree) | [Ruby](./algorithms/ruby/0208-implement-trie-prefix-tree.rb) | Medium |
| 211 | Design Add and Search Words Data Structure | [Ruby](./algorithms/ruby/0211-design-add-and-search-words-data-structure.rb) | Medium |
| 226 | Invert Binary Tree | [Ruby](./algorithms/ruby/0226-invert-binary-tree.rb) | Easy |
| 344 | Reverse String | [Ruby](./algorithms/ruby/0344-reverse-string.rb) | Easy |
| 382 | Linked List Random Node | [Ruby](./algorithms/ruby/0382-linked-list-random-node.rb) | Medium |
| 387 | First Unique Character in a String | [Ruby](./algorithms/ruby/0387-first-unique-character-in-a-string.rb) | Easy |
| 392 | Is Subsequence | [Ruby](./algorithms/ruby/0392-is-subsequence.rb) | Easy |
| 409 | Longest Palindrome | [Ruby](./algorithms/ruby/0409-longest-palindrome.rb) | Easy |
| 427 | Construct Quad Tree | [Ruby](./algorithms/ruby/0427-construct-quad-tree.rb) | Medium |
| 438 | Find All Anagrams in a String | [Ruby](./algorithms/ruby/0438-find-all-anagrams-in-a-string.rb) | Medium |
| 443 | String Compression | [Ruby](./algorithms/ruby/0443-string-compression.rb) [Python3](./algorithms/python3/0443-string-compression.py) | Medium |
Expand All @@ -64,6 +67,7 @@
| 733 | Flood Fill | [Ruby](./algorithms/ruby/0733-flood-fill.rb) | Easy |
| 783 | Minimum Distance Between BST Nodes | [Ruby](./algorithms/ruby/0783-minimum-distance-between-bst-nodes.rb) [Python3](./algorithms/python3/0783-minimum-distance-between-bst-nodes.py) | Easy |
| 875 | Koko Eating Bananas | [Ruby](./algorithms/ruby/0875-koko-eating-bananas.rb) [Python3](./algorithms/python3/0875-koko-eating-bananas.py) | Medium |
| 876 | Middle of the Linked List | [Ruby](./algorithms/ruby/0876-middle-of-the-linked-list.rb) | Easy |
| 904 | Fruit Into Baskets | [Ruby](./algorithms/ruby/0904-fruit-into-baskets.rb) | Medium |
| 912 | Sort an Array | [Ruby](./algorithms/ruby/0912-sort-an-array.rb) | Medium |
| 953 | Verifying an Alien Dictionary | [Ruby](./algorithms/ruby/0953-verifying-an-alien-dictionary.rb) | Easy |
Expand All @@ -86,7 +90,9 @@
| 1675 | Minimize Deviation in Array | [Ruby](./algorithms/ruby/1675-minimize-deviation-in-array.rb) | Hard |
| 1680 | Concatenation of Consecutive Binary Numbers | [Ruby](./algorithms/ruby/1680-concatenation-of-consecutive-binary-numbers.rb) | Medium |
| 2187 | Minimum Time to Complete Trips | [Ruby](./algorithms/ruby/2187-minimum-time-to-complete-trips.rb) [Python3](./algorithms/python3/2187-minimum-time-to-complete-trips.py) | Medium |
| 2316 | Count Unreachable Pairs of Nodes in an Undirected Graph | [Ruby](./algorithms/ruby/2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph.rb) | Medium |
| 2348 | Number of Zero-Filled Subarrays | [Ruby](./algorithms/ruby/2348-number-of-zero-filled-subarrays.rb) | Medium |
| 2360 | Longest Cycle in a Graph | [Ruby](./algorithms/ruby/2360-longest-cycle-in-a-graph.rb) | Hard |
| 2409 | Count Days Spent Together | [Ruby](./algorithms/ruby/2409-count-days-spent-together.rb) | Easy |
| 2413 | Smallest Even Multiple | [Ruby](./algorithms/ruby/2413-smallest-even-multiple.rb) | Easy |
| 2444 | Count Subarrays With Fixed Bounds | [Ruby](./algorithms/ruby/2444-count-subarrays-with-fixed-bounds.rb) | Hard |
Expand Down
54 changes: 54 additions & 0 deletions algorithms/ruby/0064-minimum-path-sum.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# frozen_string_literal: true

# 64. Minimum Path Sum
# https://leetcode.com/problems/minimum-path-sum

=begin

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.

Note: You can only move either down or right at any point in time.

### Example 1:
Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.

### Example 2:
Input: grid = [[1,2,3],[4,5,6]]
Output: 12

### Constraints:
* m == grid.length
* n == grid[i].length
* 1 <= m, n <= 200
* 0 <= grid[i][j] <= 100

=end

# Runtime 72 ms
# Memory 212.3 MB
# @param {Integer[][]} grid
# @return {Integer}
def min_path_sum(grid)
acc = [0] + [Float::INFINITY] * (grid[0].size - 1)

grid.each { |row|
left = Float::INFINITY
acc.map!.with_index { |n, i| left = row[i] + (left < n ? left : n) }
}

acc.last
end

# ********************#
# TEST #
# ********************#

require "test/unit"
class Test_min_path_sum < Test::Unit::TestCase
def test_
assert_equal 7, min_path_sum([[1, 3, 1], [1, 5, 1], [4, 2, 1]])
# assert_equal 12, min_path_sum([[1,2,3],[4,5,6]])
end
end
43 changes: 43 additions & 0 deletions algorithms/ruby/0206-reverse-linked-list.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# frozen_string_literal: true

# 206. Reverse Linked List
# https://leetcode.com/problems/reverse-linked-list

=begin

Given the head of a singly linked list, reverse the list, and return the reversed list.

### Example 1:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

### Example 2:
Input: head = [1,2]
Output: [2,1]

### Example 3:
Input: head = []
Output: []

### Constraints:
* The number of nodes in the list is the range [0, 5000].
* -5000 <= Node.val <= 5000

=end

# Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val = 0, _next = nil)
# @val = val
# @next = _next
# end
# end
# @param {ListNode} head
# @return {ListNode}
def reverse_list(head, prev = nil)
while head
head, head.next, prev = head.next, prev, head
end
prev
end
46 changes: 46 additions & 0 deletions algorithms/ruby/0409-longest-palindrome.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# frozen_string_literal: true

# 409. Longest Palindrome
# https://leetcode.com/problems/longest-palindrome

=begin

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.

Letters are case sensitive, for example, "Aa" is not considered a palindrome here.

### Example 1:
Input: s = "abccccdd"
Output: 7
Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.

### Example 2:
Input: s = "a"
Output: 1
Explanation: The longest palindrome that can be built is "a", whose length is 1.

### Constraints:
* 1 <= s.length <= 2000
* s consists of lowercase and/or uppercase English letters only.

=end

# Runtime 92 ms
# Memory 210.9 MB
# @param {String} s
# @return {Integer}
def longest_palindrome(s)
[s.size, s.each_char.tally.sum { _2 & ~1 } + 1].min
end

# **************** #
# TEST #
# **************** #

require "test/unit"
class Test_longest_palindrome < Test::Unit::TestCase
def test_
assert_equal 7, longest_palindrome("abccccdd")
assert_equal 1, longest_palindrome("a")
end
end
45 changes: 45 additions & 0 deletions algorithms/ruby/0876-middle-of-the-linked-list.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# frozen_string_literal: true

# 876. Middle of the Linked List
# https://leetcode.com/problems/middle-of-the-linked-list

=begin

Given the head of a singly linked list, return the middle node of the linked list.

If there are two middle nodes, return the second middle node.

### Example 1:
Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.

### Example 2:
Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.

### Constraints:
* The number of nodes in the list is in the range [1, 100].
* 1 <= Node.val <= 100

=end

# Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val = 0, _next = nil)
# @val = val
# @next = _next
# end
# end
# @param {ListNode} head
# @return {ListNode}
def middle_node(head)
slow = fast = head
while fast != nil && fast.next != nil
slow = slow.next
fast = fast.next.next
end
slow
end
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# frozen_string_literal: true

# 2316. Count Unreachable Pairs of Nodes in an Undirected Graph
# https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph

=begin

You are given an integer n. There is an undirected graph with n nodes, numbered from 0 to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi.

Return the number of pairs of different nodes that are unreachable from each other.

### Example 1:
Input: n = 3, edges = [[0,1],[0,2],[1,2]]
Output: 0
Explanation: There are no pairs of nodes that are unreachable from each other. Therefore, we return 0.

### Example 2:
Input: n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]]
Output: 14
Explanation: There are 14 pairs of nodes that are unreachable from each other:
[[0,1],[0,3],[0,6],[1,2],[1,3],[1,4],[1,5],[2,3],[2,6],[3,4],[3,5],[3,6],[4,6],[5,6]].
Therefore, we return 14.

### Constraints:
* 1 <= n <= 105
* 0 <= edges.length <= 2 * 105
* edges[i].length == 2
* 0 <= ai, bi < n
* ai != bi
* There are no repeated edges.

=end

# Runtime: 403 ms
# Memory Usage: 247.1 MB
# @param {Integer} n
# @param {Integer[][]} edges
# @return {Integer}
def count_pairs(n, edges)
@adj = Array.new(n + 1).map { [] }
@v = Array.new(n + 1, false)
@total = 0
@ans = 0
edges.each do |a, b|
@adj[a].push(b)
@adj[b].push(a)
end
(0...n).each do |i|
next if @v[i]
bfs(i)
end
@ans
end

def bfs(i)
return if @v[i]
count = 0
q = [i]
@v[i] = true
while !q.empty?
x = q.shift
count += 1
@ans += @total
@adj[x].each do |j|
next if @v[j]
@v[j] = true
q.push(j)
end
end
@total += count
end

# **************** #
# TEST #
# **************** #

require "test/unit"
class Test_count_pairs < Test::Unit::TestCase
def test_
assert_equal 0, count_pairs(3, [[0, 1], [0, 2], [1, 2]])
assert_equal 14, count_pairs(7, [[0, 2], [0, 5], [2, 4], [1, 6], [5, 4]])
end
end
72 changes: 72 additions & 0 deletions algorithms/ruby/2360-longest-cycle-in-a-graph.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# frozen_string_literal: true

# 2360. Longest Cycle in a Graph
# https://leetcode.com/problems/longest-cycle-in-a-graph

=begin

You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.

The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from node i, then edges[i] == -1.

Return the length of the longest cycle in the graph. If no cycle exists, return -1.

A cycle is a path that starts and ends at the same node.

### Example 1:
Input: edges = [3,3,4,2,3]
Output: 3
Explanation: The longest cycle in the graph is the cycle: 2 -> 4 -> 3 -> 2.
The length of this cycle is 3, so 3 is returned.

### Example 2:
Input: edges = [2,-1,3,1]
Output: -1
Explanation: There are no cycles in this graph.

### Constraints:
* n == edges.length
* 2 <= n <= 105
* -1 <= edges[i] < n
* edges[i] != i

=end

# Runtime 379 ms
# Memory 228.1 MB
# @param {Integer[]} edges
# @return {Integer}
def longest_cycle(edges)
max = -1

edges.size.times do |cur|
next if edges[cur] < 0
dists = {}
dist = 0
until cur < 0
if dists[cur]
cycle = dist - dists[cur]
max = cycle if cycle > max
break
else
dists[cur] = dist
cur, edges[cur] = edges[cur], -1
dist += 1
end
end
end

max
end

# **************** #
# TEST #
# **************** #

require "test/unit"
class Test_longest_cycle < Test::Unit::TestCase
def test_
assert_equal 3, longest_cycle([3, 3, 4, 2, 3])
assert_equal(-1, longest_cycle([2, -1, 3, 1]))
end
end