Skip to content

Commit cc9adec

Browse files
authored
Added tasks 347-1143
1 parent 6d3d8ca commit cc9adec

File tree

15 files changed

+966
-0
lines changed

15 files changed

+966
-0
lines changed

README.md

Lines changed: 35 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Ruby/LeetCode-in-Ruby?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Ruby/LeetCode-in-Ruby)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Ruby/LeetCode-in-Ruby?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Ruby/LeetCode-in-Ruby/fork)
3+
4+
## 138\. Copy List with Random Pointer
5+
6+
Medium
7+
8+
A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`.
9+
10+
Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**.
11+
12+
For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`.
13+
14+
Return _the head of the copied linked list_.
15+
16+
The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where:
17+
18+
* `val`: an integer representing `Node.val`
19+
* `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node.
20+
21+
Your code will **only** be given the `head` of the original linked list.
22+
23+
**Example 1:**
24+
25+
![](https://assets.leetcode.com/uploads/2019/12/18/e1.png)
26+
27+
**Input:** head = \[\[7,null],[13,0],[11,4],[10,2],[1,0]]
28+
29+
**Output:** [[7,null],[13,0],[11,4],[10,2],[1,0]]
30+
31+
**Example 2:**
32+
33+
![](https://assets.leetcode.com/uploads/2019/12/18/e2.png)
34+
35+
**Input:** head = \[\[1,1],[2,1]]
36+
37+
**Output:** [[1,1],[2,1]]
38+
39+
**Example 3:**
40+
41+
**![](https://assets.leetcode.com/uploads/2019/12/18/e3.png)**
42+
43+
**Input:** head = \[\[3,null],[3,0],[3,null]]
44+
45+
**Output:** [[3,null],[3,0],[3,null]]
46+
47+
**Example 4:**
48+
49+
**Input:** head = []
50+
51+
**Output:** []
52+
53+
**Explanation:** The given linked list is empty (null pointer), so return null.
54+
55+
**Constraints:**
56+
57+
* `0 <= n <= 1000`
58+
* `-10000 <= Node.val <= 10000`
59+
* `Node.random` is `null` or is pointing to some node in the linked list.
60+
61+
## Solution
62+
63+
```ruby
64+
require_relative '../../com_github_leetcode/random/node'
65+
66+
# Definition for Node.
67+
# class Node
68+
# attr_accessor :val, :next, :random
69+
# def initialize(val = 0)
70+
# @val = val
71+
# @next = nil
72+
# @random = nil
73+
# end
74+
# end
75+
76+
# @param {Node} node
77+
# @return {Node}
78+
def copy_random_list(head)
79+
return nil if head.nil?
80+
81+
# First pass to create cloned nodes and insert them after the original nodes
82+
curr = head
83+
while curr
84+
cloned_node = Node.new(curr.val)
85+
cloned_node.next = curr.next
86+
curr.next = cloned_node
87+
curr = cloned_node.next
88+
end
89+
90+
# Second pass to set the random pointers of the cloned nodes
91+
curr = head
92+
while curr
93+
curr.next.random = curr.random.next if curr.random
94+
curr = curr.next.next
95+
end
96+
97+
# Third pass to separate the original and cloned nodes
98+
curr = head
99+
new_head = nil
100+
while curr
101+
cloned_node = curr.next
102+
new_head ||= cloned_node
103+
curr.next = cloned_node.next
104+
cloned_node.next = curr.next.next if curr.next
105+
curr = curr.next
106+
end
107+
108+
new_head
109+
end
110+
```
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Ruby/LeetCode-in-Ruby?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Ruby/LeetCode-in-Ruby)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Ruby/LeetCode-in-Ruby?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Ruby/LeetCode-in-Ruby/fork)
3+
4+
## 139\. Word Break
5+
6+
Medium
7+
8+
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words.
9+
10+
**Note** that the same word in the dictionary may be reused multiple times in the segmentation.
11+
12+
**Example 1:**
13+
14+
**Input:** s = "leetcode", wordDict = ["leet","code"]
15+
16+
**Output:** true
17+
18+
**Explanation:** Return true because "leetcode" can be segmented as "leet code".
19+
20+
**Example 2:**
21+
22+
**Input:** s = "applepenapple", wordDict = ["apple","pen"]
23+
24+
**Output:** true
25+
26+
**Explanation:** Return true because "applepenapple" can be segmented as "apple pen apple". Note that you are allowed to reuse a dictionary word.
27+
28+
**Example 3:**
29+
30+
**Input:** s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
31+
32+
**Output:** false
33+
34+
**Constraints:**
35+
36+
* `1 <= s.length <= 300`
37+
* `1 <= wordDict.length <= 1000`
38+
* `1 <= wordDict[i].length <= 20`
39+
* `s` and `wordDict[i]` consist of only lowercase English letters.
40+
* All the strings of `wordDict` are **unique**.
41+
42+
## Solution
43+
44+
```ruby
45+
# @param {String} s
46+
# @param {String[]} word_dict
47+
# @return {Boolean}
48+
def word_break(s, word_dict)
49+
memo = Array.new(s.size - 1, nil)
50+
dp = lambda do |i|
51+
return true if i < 0
52+
return memo[i] unless memo[i].nil?
53+
54+
memo[i] = word_dict.any? do |word|
55+
s[i - word.size + 1..i] == word && dp[i - word.size]
56+
end
57+
end
58+
dp[s.size - 1]
59+
end
60+
```
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Ruby/LeetCode-in-Ruby?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Ruby/LeetCode-in-Ruby)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Ruby/LeetCode-in-Ruby?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Ruby/LeetCode-in-Ruby/fork)
3+
4+
## 347\. Top K Frequent Elements
5+
6+
Medium
7+
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+
12+
**Input:** nums = [1,1,1,2,2,3], k = 2
13+
14+
**Output:** [1,2]
15+
16+
**Example 2:**
17+
18+
**Input:** nums = [1], k = 1
19+
20+
**Output:** [1]
21+
22+
**Constraints:**
23+
24+
* <code>1 <= nums.length <= 10<sup>5</sup></code>
25+
* `k` is in the range `[1, the number of unique elements in the array]`.
26+
* It is **guaranteed** that the answer is **unique**.
27+
28+
**Follow up:** Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size.
29+
30+
## Solution
31+
32+
```ruby
33+
# @param {Integer[]} nums
34+
# @param {Integer} k
35+
# @return {Integer[]}
36+
def top_k_frequent(nums, k)
37+
numhash = Hash.new(0)
38+
nums.each {|num| numhash[num] += 1}
39+
newhash = numhash.sort_by {|k, v| -v}
40+
ret_array = []
41+
for i in 0...k
42+
ret_array << newhash[i][0]
43+
end
44+
return ret_array
45+
end
46+
```
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Ruby/LeetCode-in-Ruby?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Ruby/LeetCode-in-Ruby)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Ruby/LeetCode-in-Ruby?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Ruby/LeetCode-in-Ruby/fork)
3+
4+
## 394\. Decode String
5+
6+
Medium
7+
8+
Given an encoded string, return its decoded string.
9+
10+
The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is being repeated exactly `k` times. Note that `k` is guaranteed to be a positive integer.
11+
12+
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
13+
14+
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, `k`. For example, there won't be input like `3a` or `2[4]`.
15+
16+
**Example 1:**
17+
18+
**Input:** s = "3[a]2[bc]"
19+
20+
**Output:** "aaabcbc"
21+
22+
**Example 2:**
23+
24+
**Input:** s = "3[a2[c]]"
25+
26+
**Output:** "accaccacc"
27+
28+
**Example 3:**
29+
30+
**Input:** s = "2[abc]3[cd]ef"
31+
32+
**Output:** "abcabccdcdcdef"
33+
34+
**Example 4:**
35+
36+
**Input:** s = "abc3[cd]xyz"
37+
38+
**Output:** "abccdcdcdxyz"
39+
40+
**Constraints:**
41+
42+
* `1 <= s.length <= 30`
43+
* `s` consists of lowercase English letters, digits, and square brackets `'[]'`.
44+
* `s` is guaranteed to be **a valid** input.
45+
* All the integers in `s` are in the range `[1, 300]`.
46+
47+
## Solution
48+
49+
```ruby
50+
# @param {String} s
51+
# @return {String}
52+
def decode_string(s)
53+
@i = 0
54+
decode_helper(s)
55+
end
56+
57+
private
58+
59+
def decode_helper(s)
60+
count = 0
61+
result = ""
62+
63+
while @i < s.length
64+
c = s[@i]
65+
@i += 1
66+
67+
if letter?(c)
68+
result += c
69+
elsif digit?(c)
70+
count = count * 10 + c.to_i
71+
elsif c == ']'
72+
break
73+
elsif c == '['
74+
# sub problem
75+
repeat = decode_helper(s)
76+
result += repeat * count
77+
count = 0
78+
end
79+
end
80+
81+
result
82+
end
83+
84+
def letter?(c)
85+
c =~ /[a-zA-Z]/
86+
end
87+
88+
def digit?(c)
89+
c =~ /\d/
90+
end
91+
```
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Ruby/LeetCode-in-Ruby?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Ruby/LeetCode-in-Ruby)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Ruby/LeetCode-in-Ruby?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Ruby/LeetCode-in-Ruby/fork)
3+
4+
## 416\. Partition Equal Subset Sum
5+
6+
Medium
7+
8+
Given a **non-empty** array `nums` containing **only positive integers**, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
9+
10+
**Example 1:**
11+
12+
**Input:** nums = [1,5,11,5]
13+
14+
**Output:** true
15+
16+
**Explanation:** The array can be partitioned as [1, 5, 5] and [11].
17+
18+
**Example 2:**
19+
20+
**Input:** nums = [1,2,3,5]
21+
22+
**Output:** false
23+
24+
**Explanation:** The array cannot be partitioned into equal sum subsets.
25+
26+
**Constraints:**
27+
28+
* `1 <= nums.length <= 200`
29+
* `1 <= nums[i] <= 100`
30+
31+
## Solution
32+
33+
```ruby
34+
# @param {Integer[]} nums
35+
# @return {Boolean}
36+
def can_partition(nums)
37+
sums = nums.sum
38+
return false if sums.odd?
39+
40+
sums /= 2
41+
dp = Array.new(sums + 1, false)
42+
dp[0] = true
43+
44+
nums.each do |num|
45+
sums.downto(num) do |sum|
46+
dp[sum] = dp[sum] || dp[sum - num]
47+
end
48+
end
49+
50+
dp[sums]
51+
end
52+
```

0 commit comments

Comments
 (0)