Skip to content

Commit a262ff0

Browse files
authored
Added tasks 131-200
1 parent 13c4284 commit a262ff0

File tree

33 files changed

+1367
-0
lines changed

33 files changed

+1367
-0
lines changed

README.md

Lines changed: 55 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# #Medium #Top_100_Liked_Questions #Top_Interview_Questions #String #Dynamic_Programming
2+
# #Backtracking #Big_O_Time_O(N*2^N)_Space_O(2^N*N)
3+
# #2024_06_09_Time_444_ms_(93.43%)_Space_32.1_MB_(84.45%)
4+
5+
class Solution:
6+
def partition(self, s: str) -> List[List[str]]:
7+
res = []
8+
self.backtracking(res, [], s, 0)
9+
return res
10+
11+
def backtracking(self, res, curr_arr, s, start):
12+
if start == len(s):
13+
res.append(list(curr_arr))
14+
return
15+
for end in range(start, len(s)):
16+
if not self.is_palindrome(s, start, end):
17+
continue
18+
curr_arr.append(s[start:end + 1])
19+
self.backtracking(res, curr_arr, s, end + 1)
20+
curr_arr.pop()
21+
22+
def is_palindrome(self, s, start, end):
23+
while start < end and s[start] == s[end]:
24+
start += 1
25+
end -= 1
26+
return start >= end
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
131\. Palindrome Partitioning
2+
3+
Medium
4+
5+
Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return all possible palindrome partitioning of `s`.
6+
7+
A **palindrome** string is a string that reads the same backward as forward.
8+
9+
**Example 1:**
10+
11+
**Input:** s = "aab"
12+
13+
**Output:** [["a","a","b"],["aa","b"]]
14+
15+
**Example 2:**
16+
17+
**Input:** s = "a"
18+
19+
**Output:** [["a"]]
20+
21+
**Constraints:**
22+
23+
* `1 <= s.length <= 16`
24+
* `s` contains only lowercase English letters.
25+
26+
To solve this task, we can use a backtracking approach. Here are the steps to solve the problem using the `Solution` class:
27+
28+
1. Define the `Solution` class with a method `partition` that takes a string `s` as input and returns a list of lists containing all possible palindrome partitions of `s`.
29+
2. Within the `partition` method, initialize an empty list to store the result.
30+
3. Define a helper function, let's name it `dfs`, which will perform depth-first search to generate all possible partitions.
31+
4. In the `dfs` function, if the current partition `start` is equal to the length of the string `s`, append the current partition to the result list.
32+
5. Otherwise, iterate through each possible end index of the substring starting from `start` to the end of the string.
33+
6. Check if the substring from `start` to the current end index is a palindrome. If it is, recursively call the `dfs` function with the updated start index and add the current palindrome substring to the current partition.
34+
7. After exploring all possible partitions, backtrack by removing the last added substring to explore other possibilities.
35+
8. Finally, return the result list containing all possible palindrome partitions.
36+
37+
Here's how the `Solution` class would look like in Python:
38+
39+
```python
40+
class Solution:
41+
def partition(self, s: str) -> List[List[str]]:
42+
result = []
43+
44+
def dfs(start, partition):
45+
if start == len(s):
46+
result.append(partition[:])
47+
return
48+
49+
for end in range(start + 1, len(s) + 1):
50+
if s[start:end] == s[start:end][::-1]:
51+
partition.append(s[start:end])
52+
dfs(end, partition)
53+
partition.pop()
54+
55+
dfs(0, [])
56+
return result
57+
58+
# Example usage:
59+
solution = Solution()
60+
print(solution.partition("aab")) # Output: [["a","a","b"],["aa","b"]]
61+
print(solution.partition("a")) # Output: [["a"]]
62+
```
63+
64+
This solution utilizes backtracking to efficiently generate all possible palindrome partitions of the given string `s`.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# #Easy #Top_100_Liked_Questions #Top_Interview_Questions #Array #Bit_Manipulation
2+
# #Data_Structure_II_Day_1_Array #Algorithm_I_Day_14_Bit_Manipulation #Udemy_Integers
3+
# #Big_O_Time_O(N)_Space_O(1) #2024_06_09_Time_98_ms_(96.80%)_Space_19_MB_(89.40%)
4+
5+
class Solution:
6+
def singleNumber(self, nums: List[int]) -> int:
7+
res = 0
8+
for num in nums:
9+
res ^= num
10+
return res
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
136\. Single Number
2+
3+
Easy
4+
5+
Given a **non-empty** array of integers `nums`, every element appears _twice_ except for one. Find that single one.
6+
7+
You must implement a solution with a linear runtime complexity and use only constant extra space.
8+
9+
**Example 1:**
10+
11+
**Input:** nums = [2,2,1]
12+
13+
**Output:** 1
14+
15+
**Example 2:**
16+
17+
**Input:** nums = [4,1,2,1,2]
18+
19+
**Output:** 4
20+
21+
**Example 3:**
22+
23+
**Input:** nums = [1]
24+
25+
**Output:** 1
26+
27+
**Constraints:**
28+
29+
* <code>1 <= nums.length <= 3 * 10<sup>4</sup></code>
30+
* <code>-3 * 10<sup>4</sup> <= nums[i] <= 3 * 10<sup>4</sup></code>
31+
* Each element in the array appears twice except for one element which appears only once.
32+
33+
To solve this problem with the `Solution` class, which requires linear runtime complexity and constant extra space, we can utilize the bitwise XOR operation. Here are the steps:
34+
35+
1. Define the `Solution` class with a method `singleNumber` that takes a list of integers `nums` as input and returns the single number that appears only once.
36+
2. Within the `singleNumber` method, initialize a variable `result` to 0.
37+
3. Iterate through each element in the `nums` list.
38+
4. Perform bitwise XOR operation between `result` and the current element.
39+
5. After iterating through all elements, `result` will contain the single number that appears only once due to the properties of XOR operation.
40+
6. Finally, return the `result`.
41+
42+
Here's how the `Solution` class would look like in Python:
43+
44+
```python
45+
class Solution:
46+
def singleNumber(self, nums: List[int]) -> int:
47+
result = 0
48+
for num in nums:
49+
result ^= num
50+
return result
51+
52+
# Example usage:
53+
solution = Solution()
54+
print(solution.singleNumber([2, 2, 1])) # Output: 1
55+
print(solution.singleNumber([4, 1, 2, 1, 2]))# Output: 4
56+
print(solution.singleNumber([1])) # Output: 1
57+
```
58+
59+
This solution leverages the bitwise XOR operation to find the single number that appears only once in the array, achieving linear runtime complexity and constant extra space usage.
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Hash_Table #Linked_List
2+
# #Programming_Skills_II_Day_14 #Udemy_Linked_List #Big_O_Time_O(N)_Space_O(N)
3+
# #2024_06_09_Time_36_ms_(72.10%)_Space_17.3_MB_(95.85%)
4+
5+
"""
6+
# Definition for a Node.
7+
class Node:
8+
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
9+
self.val = int(x)
10+
self.next = next
11+
self.random = random
12+
"""
13+
14+
class Solution:
15+
def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
16+
if head is None:
17+
return None
18+
19+
# First pass: create the cloned nodes and insert them right after the original nodes
20+
curr = head
21+
while curr:
22+
cloned_node = Node(curr.val)
23+
cloned_node.next = curr.next
24+
curr.next = cloned_node
25+
curr = cloned_node.next
26+
27+
# Second pass: update the random pointers of the cloned nodes
28+
curr = head
29+
while curr:
30+
if curr.random:
31+
curr.next.random = curr.random.next
32+
curr = curr.next.next
33+
34+
# Third pass: separate the cloned list from the original list
35+
curr = head
36+
new_head = head.next
37+
while curr:
38+
cloned_node = curr.next
39+
curr.next = cloned_node.next
40+
if cloned_node.next:
41+
cloned_node.next = cloned_node.next.next
42+
curr = curr.next
43+
44+
return new_head
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
138\. Copy List with Random Pointer
2+
3+
Medium
4+
5+
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`.
6+
7+
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**.
8+
9+
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`.
10+
11+
Return _the head of the copied linked list_.
12+
13+
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:
14+
15+
* `val`: an integer representing `Node.val`
16+
* `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.
17+
18+
Your code will **only** be given the `head` of the original linked list.
19+
20+
**Example 1:**
21+
22+
![](https://assets.leetcode.com/uploads/2019/12/18/e1.png)
23+
24+
**Input:** head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
25+
26+
**Output:** [[7,null],[13,0],[11,4],[10,2],[1,0]]
27+
28+
**Example 2:**
29+
30+
![](https://assets.leetcode.com/uploads/2019/12/18/e2.png)
31+
32+
**Input:** head = [[1,1],[2,1]]
33+
34+
**Output:** [[1,1],[2,1]]
35+
36+
**Example 3:**
37+
38+
**![](https://assets.leetcode.com/uploads/2019/12/18/e3.png)**
39+
40+
**Input:** head = [[3,null],[3,0],[3,null]]
41+
42+
**Output:** [[3,null],[3,0],[3,null]]
43+
44+
**Example 4:**
45+
46+
**Input:** head = []
47+
48+
**Output:** []
49+
50+
**Explanation:** The given linked list is empty (null pointer), so return null.
51+
52+
**Constraints:**
53+
54+
* `0 <= n <= 1000`
55+
* `-10000 <= Node.val <= 10000`
56+
* `Node.random` is `null` or is pointing to some node in the linked list.
57+
58+
To solve this problem with the `Solution` class, we can use a hashmap to keep track of the mapping between original nodes and their corresponding copied nodes. Here are the steps:
59+
60+
1. Define the `Solution` class with a method `copyRandomList` that takes the head of the original linked list as input and returns the head of the copied linked list.
61+
2. Within the `copyRandomList` method, if the input `head` is `None`, return `None` as the copied list is empty.
62+
3. Initialize an empty hashmap to store the mapping between original nodes and copied nodes.
63+
4. Iterate through the original linked list and create a copied node for each original node. Set the value of the copied node to be the same as the original node and set both `next` and `random` pointers of the copied node to `None`.
64+
5. Store the mapping between original nodes and copied nodes in the hashmap.
65+
6. Iterate through the original linked list again and update the `next` and `random` pointers of copied nodes according to the mapping stored in the hashmap.
66+
7. Finally, return the head of the copied linked list.
67+
68+
Here's how the `Solution` class would look like in Python:
69+
70+
```python
71+
class Solution:
72+
def copyRandomList(self, head: 'Node') -> 'Node':
73+
if not head:
74+
return None
75+
76+
mapping = {}
77+
78+
# Create copies of nodes without pointers
79+
current = head
80+
while current:
81+
mapping[current] = Node(current.val)
82+
current = current.next
83+
84+
# Assign pointers for each copied node
85+
current = head
86+
while current:
87+
mapping[current].next = mapping.get(current.next)
88+
mapping[current].random = mapping.get(current.random)
89+
current = current.next
90+
91+
return mapping[head]
92+
```
93+
94+
Make sure to define the `Node` class before using it in the `copyRandomList` method. This solution constructs a deep copy of the original linked list while maintaining the relationships between nodes as specified.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# #Medium #Top_100_Liked_Questions #Top_Interview_Questions #String #Hash_Table
2+
# #Dynamic_Programming #Trie #Memoization #Algorithm_II_Day_15_Dynamic_Programming
3+
# #Dynamic_Programming_I_Day_9 #Udemy_Dynamic_Programming #Big_O_Time_O(M+max*N)_Space_O(M+N+max)
4+
# #2024_06_09_Time_41_ms_(50.55%)_Space_16.6_MB_(88.23%)
5+
6+
class Solution:
7+
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
8+
n = len(s)
9+
dp = [-1] * n
10+
11+
def solve(i, s):
12+
if i < 0:
13+
return True
14+
if dp[i] != -1:
15+
return dp[i] == 1
16+
for w in wordDict:
17+
sz = len(w)
18+
if i - sz + 1 >= 0 and s[i - sz + 1 : i + 1] == w:
19+
if solve(i - sz, s):
20+
dp[i] = 1
21+
return True
22+
dp[i] = 0
23+
return False
24+
25+
return solve(n - 1, s)

0 commit comments

Comments
 (0)