Move old algos files to archive
This commit is contained in:
parent
cc2e468d3d
commit
22abae2fd6
55 changed files with 0 additions and 2276 deletions
|
|
@ -1,3 +0,0 @@
|
||||||
module BST_108
|
|
||||||
|
|
||||||
go 1.21.3
|
|
||||||
|
|
@ -1,50 +0,0 @@
|
||||||
package main
|
|
||||||
|
|
||||||
import "fmt"
|
|
||||||
|
|
||||||
/**
|
|
||||||
Given an integer array nums where the elements are sorted in ascending order, convert it to a
|
|
||||||
height-balanced binary search tree.
|
|
||||||
|
|
||||||
Constraints:
|
|
||||||
|
|
||||||
1 <= nums.length <= 104
|
|
||||||
-104 <= nums[i] <= 104
|
|
||||||
nums is sorted in a strictly increasing order.
|
|
||||||
|
|
||||||
**/
|
|
||||||
|
|
||||||
type TreeNode struct {
|
|
||||||
Val int
|
|
||||||
Left *TreeNode
|
|
||||||
Right *TreeNode
|
|
||||||
}
|
|
||||||
|
|
||||||
func sortedArrayToBST(nums []int) *TreeNode {
|
|
||||||
if len(nums) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return buildBST(nums, 0, len(nums)-1)
|
|
||||||
}
|
|
||||||
|
|
||||||
func buildBST(nums []int, left, right int) *TreeNode {
|
|
||||||
if left > right {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Find the middle element and make it the root
|
|
||||||
mid := (left + right) / 2
|
|
||||||
root := &TreeNode{Val: nums[mid]}
|
|
||||||
|
|
||||||
// Recursively build the left and right subtrees
|
|
||||||
root.Left = buildBST(nums, left, mid-1)
|
|
||||||
root.Right = buildBST(nums, mid+1, right)
|
|
||||||
|
|
||||||
return root
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
nums := []int{2, 3, 4, 5, 6}
|
|
||||||
result := sortedArrayToBST(nums)
|
|
||||||
fmt.Printf("%v, left val: %v, right val: %v", result.Val, result.Left.Val, result.Right.Val)
|
|
||||||
}
|
|
||||||
|
|
@ -1,22 +0,0 @@
|
||||||
package main
|
|
||||||
|
|
||||||
type TreeNode struct {
|
|
||||||
Val int
|
|
||||||
Left *TreeNode
|
|
||||||
Right *TreeNode
|
|
||||||
}
|
|
||||||
|
|
||||||
func traverse(root *TreeNode, res *[]int) {
|
|
||||||
if root == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
traverse(root.Left, res)
|
|
||||||
*res = append(*res, root.Val)
|
|
||||||
traverse(root.Right, res)
|
|
||||||
}
|
|
||||||
|
|
||||||
func kthSmallest(root *TreeNode, k int) int {
|
|
||||||
var result []int
|
|
||||||
traverse(root, &result)
|
|
||||||
return result[k-1]
|
|
||||||
}
|
|
||||||
|
|
@ -1,59 +0,0 @@
|
||||||
package main
|
|
||||||
|
|
||||||
// Given a root node reference of a BST and a key, delete the node with the given key in the BST.
|
|
||||||
// Return the root node reference (possibly updated) of the BST.
|
|
||||||
//
|
|
||||||
// Basically, the deletion can be divided into two stages:
|
|
||||||
//
|
|
||||||
// Search for a node to remove.
|
|
||||||
// If the node is found, delete the node.
|
|
||||||
|
|
||||||
// Constraints:
|
|
||||||
//
|
|
||||||
// The number of nodes in the tree is in the range [0, 104].
|
|
||||||
// -105 <= Node.val <= 105
|
|
||||||
// Each node has a unique value.
|
|
||||||
// root is a valid binary search tree.
|
|
||||||
// -105 <= key <= 105
|
|
||||||
|
|
||||||
type TreeNode struct {
|
|
||||||
Val int
|
|
||||||
Left *TreeNode
|
|
||||||
Right *TreeNode
|
|
||||||
}
|
|
||||||
|
|
||||||
func findMin(subTreeRoot *TreeNode) *TreeNode {
|
|
||||||
for (subTreeRoot != nil) && (subTreeRoot.Left != nil) {
|
|
||||||
subTreeRoot = subTreeRoot.Left
|
|
||||||
}
|
|
||||||
return subTreeRoot
|
|
||||||
}
|
|
||||||
|
|
||||||
func deleteNode(root *TreeNode, key int) *TreeNode {
|
|
||||||
if root == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if key < root.Val {
|
|
||||||
root.Left = deleteNode(root.Left, key)
|
|
||||||
} else if key > root.Val {
|
|
||||||
root.Right = deleteNode(root.Right, key)
|
|
||||||
} else {
|
|
||||||
if (root.Right == nil) && (root.Left == nil) {
|
|
||||||
root = nil
|
|
||||||
return root
|
|
||||||
} else if (root.Right != nil) && (root.Left == nil) {
|
|
||||||
root = root.Right
|
|
||||||
return root
|
|
||||||
} else if (root.Left != nil) && (root.Right == nil) {
|
|
||||||
root = root.Left
|
|
||||||
return root
|
|
||||||
} else if (root.Left != nil) && (root.Right != nil) {
|
|
||||||
minSubTreeNode := findMin(root.Right)
|
|
||||||
deleteNode(root.Right, minSubTreeNode.Val)
|
|
||||||
root.Val = minSubTreeNode.Val
|
|
||||||
return root
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return root
|
|
||||||
}
|
|
||||||
|
|
@ -1,35 +0,0 @@
|
||||||
package main
|
|
||||||
|
|
||||||
import "fmt"
|
|
||||||
|
|
||||||
type TreeNode struct {
|
|
||||||
Val int
|
|
||||||
Left *TreeNode
|
|
||||||
Right *TreeNode
|
|
||||||
}
|
|
||||||
|
|
||||||
func traverse(root *TreeNode, res *[]int) {
|
|
||||||
if root == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
traverse(root.Left, res)
|
|
||||||
*res = append(*res, root.Val)
|
|
||||||
traverse(root.Right, res)
|
|
||||||
}
|
|
||||||
func inorderTraversal(root *TreeNode) []int {
|
|
||||||
var result []int
|
|
||||||
traverse(root, &result)
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
n10 := TreeNode{Val: 2}
|
|
||||||
n9 := TreeNode{Val: 5}
|
|
||||||
n8 := TreeNode{Val: 7}
|
|
||||||
n7 := TreeNode{Val: 6, Left: &n9, Right: &n8}
|
|
||||||
n6 := TreeNode{Val: 3, Left: &n10}
|
|
||||||
n5 := TreeNode{Val: 4, Left: &n6, Right: &n7}
|
|
||||||
|
|
||||||
res := inorderTraversal(&n5)
|
|
||||||
fmt.Print(res)
|
|
||||||
}
|
|
||||||
|
|
@ -1,17 +0,0 @@
|
||||||
# Link: https://leetcode.com/problems/concatenation-of-array/
|
|
||||||
from typing import List
|
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
|
||||||
def getConcatenation(self, nums: List[int]) -> List[int]:
|
|
||||||
# ans = [] * (len(nums) * 2)
|
|
||||||
ans = nums + nums
|
|
||||||
return ans
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
nums = [2, 5, 1, 3, 4, 7]
|
|
||||||
sol = Solution
|
|
||||||
print(nums)
|
|
||||||
print(sol().getConcatenation(nums))
|
|
||||||
print("-" * 60)
|
|
||||||
|
|
@ -1,74 +0,0 @@
|
||||||
from typing import Optional
|
|
||||||
import pytest
|
|
||||||
# Definition for singly-linked list.
|
|
||||||
|
|
||||||
|
|
||||||
class ListNode:
|
|
||||||
def __init__(self, val=0, next=None):
|
|
||||||
self.val = val
|
|
||||||
self.next = next
|
|
||||||
|
|
||||||
def __repr__(self) -> str:
|
|
||||||
return f"Val: {self.val}"
|
|
||||||
|
|
||||||
|
|
||||||
# Not solved by me
|
|
||||||
class Solution:
|
|
||||||
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
|
|
||||||
rl = []
|
|
||||||
if not head:
|
|
||||||
return
|
|
||||||
|
|
||||||
def rr(cn: ListNode):
|
|
||||||
if cn.next:
|
|
||||||
rr(cn.next)
|
|
||||||
cn.next.next = cn
|
|
||||||
rl.append(cn)
|
|
||||||
else:
|
|
||||||
rl.append(cn)
|
|
||||||
|
|
||||||
rr(head)
|
|
||||||
head.next = None
|
|
||||||
|
|
||||||
class SolutionFromLeetCode:
|
|
||||||
def reverseList(self, head: ListNode) -> ListNode:
|
|
||||||
# Initialize pointers
|
|
||||||
prev = None # Previous node starts as None
|
|
||||||
curr = head # Current node starts at the head
|
|
||||||
|
|
||||||
# Traverse the list
|
|
||||||
while curr is not None:
|
|
||||||
next_node = curr.next # Save the next node
|
|
||||||
|
|
||||||
curr.next = prev # Reverse the link
|
|
||||||
|
|
||||||
# Move pointers forward
|
|
||||||
prev = curr # Move prev to the current node
|
|
||||||
curr = next_node # Move curr to the next node
|
|
||||||
|
|
||||||
# prev is now the new head of the reversed list
|
|
||||||
return prev
|
|
||||||
|
|
||||||
|
|
||||||
def test_solution():
|
|
||||||
l5 = ListNode(val=5, next=None)
|
|
||||||
l4 = ListNode(val=4, next=l5)
|
|
||||||
l3 = ListNode(val=3, next=l4)
|
|
||||||
l2 = ListNode(val=2, next=l3)
|
|
||||||
l1 = ListNode(val=1, next=l2)
|
|
||||||
sol = SolutionFromLeetCode()
|
|
||||||
sol.reverseList(head=l1)
|
|
||||||
assert l1.next is None
|
|
||||||
assert l2.next == l1
|
|
||||||
assert l3.next == l2
|
|
||||||
assert l4.next == l3
|
|
||||||
assert l5.next == l4
|
|
||||||
|
|
||||||
|
|
||||||
def test_solution_1():
|
|
||||||
l2 = ListNode(val=2, next=None)
|
|
||||||
l1 = ListNode(val=1, next=l2)
|
|
||||||
sol = SolutionFromLeetCode()
|
|
||||||
sol.reverseList(head=l1)
|
|
||||||
assert l1.next is None
|
|
||||||
assert l2.next == l1
|
|
||||||
|
|
@ -1,58 +0,0 @@
|
||||||
# Link: https://leetcode.com/problems/valid-parentheses/description/
|
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
|
||||||
def isValid(self, s: str) -> bool:
|
|
||||||
c = [] # Checker stack
|
|
||||||
m = {
|
|
||||||
")": "(",
|
|
||||||
"}": "{",
|
|
||||||
"]": "[",
|
|
||||||
}
|
|
||||||
cb = m.keys()
|
|
||||||
op = m.values()
|
|
||||||
for char in s:
|
|
||||||
if len(c) == 0:
|
|
||||||
c.append(char)
|
|
||||||
continue
|
|
||||||
if char in op:
|
|
||||||
c.append(char)
|
|
||||||
continue
|
|
||||||
if char in cb:
|
|
||||||
if len(c) > 0 and c[-1] == m[char]:
|
|
||||||
c.pop()
|
|
||||||
continue
|
|
||||||
if len(c) > 0 and c[-1] != m[char]:
|
|
||||||
return False
|
|
||||||
if len(c) == 0:
|
|
||||||
return False
|
|
||||||
print(f"c = {c} (len={len(c)})")
|
|
||||||
return False if len(c) > 0 else True
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
tt = "()[]{}"
|
|
||||||
sol = Solution
|
|
||||||
print(f"Initial: {tt}")
|
|
||||||
print(sol().isValid(tt))
|
|
||||||
print("-" * 60)
|
|
||||||
tt = "()"
|
|
||||||
print(f"Initial: {tt}")
|
|
||||||
print(sol().isValid(tt))
|
|
||||||
print("-" * 60)
|
|
||||||
tt = "())"
|
|
||||||
print(f"Initial: {tt}")
|
|
||||||
print(sol().isValid(tt))
|
|
||||||
print("-" * 60)
|
|
||||||
tt = "([])"
|
|
||||||
print(f"Initial: {tt}")
|
|
||||||
print(sol().isValid(tt))
|
|
||||||
print("-" * 60)
|
|
||||||
tt = "("
|
|
||||||
print(f"Initial: {tt}")
|
|
||||||
print(sol().isValid(tt))
|
|
||||||
print("-" * 60)
|
|
||||||
tt = "(])"
|
|
||||||
print(f"Initial: {tt}")
|
|
||||||
print(sol().isValid(tt))
|
|
||||||
print("-" * 60)
|
|
||||||
|
|
@ -1,51 +0,0 @@
|
||||||
# Link: https://leetcode.com/problems/min-stack/
|
|
||||||
from typing import List
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
|
|
||||||
class MinStack:
|
|
||||||
def __init__(self):
|
|
||||||
self._s: List[int] = []
|
|
||||||
self._min: List[int] = []
|
|
||||||
|
|
||||||
def push(self, val: int) -> None:
|
|
||||||
if len(self._s) == 0:
|
|
||||||
self._min.append(0)
|
|
||||||
elif val < self._s[self._min[-1]]:
|
|
||||||
self._min.append(len(self._s))
|
|
||||||
self._s.append(val)
|
|
||||||
|
|
||||||
def pop(self) -> None:
|
|
||||||
if len(self._s) - 1 == self._min[-1]:
|
|
||||||
self._min.pop()
|
|
||||||
self._s.pop()
|
|
||||||
|
|
||||||
def top(self) -> int:
|
|
||||||
return self._s[-1]
|
|
||||||
|
|
||||||
def getMin(self) -> int:
|
|
||||||
return self._s[self._min[-1]]
|
|
||||||
|
|
||||||
|
|
||||||
class TestSuite:
|
|
||||||
@pytest.fixture(autouse=True)
|
|
||||||
def init_tests(self):
|
|
||||||
self.sol = MinStack()
|
|
||||||
|
|
||||||
def test_solution_1(self):
|
|
||||||
self.sol.push(1)
|
|
||||||
self.sol.push(-1)
|
|
||||||
self.sol.push(2)
|
|
||||||
self.sol.push(-2)
|
|
||||||
self.sol.pop()
|
|
||||||
assert self.sol.getMin() == -1
|
|
||||||
|
|
||||||
def test_solution_2(self):
|
|
||||||
breakpoint()
|
|
||||||
self.sol.push(-2)
|
|
||||||
self.sol.push(0)
|
|
||||||
self.sol.push(-1)
|
|
||||||
assert self.sol.getMin() == -2
|
|
||||||
assert self.sol.top() == -1
|
|
||||||
self.sol.pop()
|
|
||||||
assert self.sol.getMin() == -2
|
|
||||||
|
|
@ -1,46 +0,0 @@
|
||||||
# Link: https://leetcode.com/problems/baseball-game/description/
|
|
||||||
from typing import List
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
|
||||||
def calPoints(self, operations: List[str]) -> int:
|
|
||||||
r: List[int] = [] # result
|
|
||||||
r_l: int = 0
|
|
||||||
for o_i in range(0, len(operations)):
|
|
||||||
try:
|
|
||||||
i = int(operations[o_i])
|
|
||||||
r.append(i)
|
|
||||||
r_l += 1
|
|
||||||
continue
|
|
||||||
except ValueError:
|
|
||||||
pass
|
|
||||||
if operations[o_i] == "+":
|
|
||||||
r.append(r[r_l - 1] + r[r_l - 2])
|
|
||||||
r_l += 1
|
|
||||||
continue
|
|
||||||
elif operations[o_i] == "D":
|
|
||||||
r.append(r[r_l - 1] * 2)
|
|
||||||
r_l += 1
|
|
||||||
continue
|
|
||||||
elif operations[o_i] == "C":
|
|
||||||
r.pop()
|
|
||||||
r_l -= 1
|
|
||||||
continue
|
|
||||||
else:
|
|
||||||
pass
|
|
||||||
return sum(r)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
|
||||||
"input, exp_output",
|
|
||||||
[
|
|
||||||
(["5", "2", "C", "D", "+"], 30),
|
|
||||||
(["5", "-2", "4", "C", "D", "9", "+", "+"], 27),
|
|
||||||
(["1", "C"], 0),
|
|
||||||
([], 0),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
def test_solution(input, exp_output):
|
|
||||||
sol = Solution()
|
|
||||||
assert sol.calPoints(input) == exp_output
|
|
||||||
|
|
@ -1,26 +0,0 @@
|
||||||
package main
|
|
||||||
|
|
||||||
import "fmt"
|
|
||||||
|
|
||||||
func removeDuplicates(nums []int) int {
|
|
||||||
if len(nums) == 1 {
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
var unique, rp int = 0, 0
|
|
||||||
for i := 0; i < len(nums); i++ {
|
|
||||||
if nums[rp] != nums[i] {
|
|
||||||
unique++
|
|
||||||
rp++
|
|
||||||
nums[rp] = nums[i]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return unique + 1
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
nums := []int{1, 1, 2}
|
|
||||||
// nums := []int{0, 0, 1, 1, 1, 2, 2, 3, 3, 4}
|
|
||||||
res := removeDuplicates(nums)
|
|
||||||
fmt.Println(res)
|
|
||||||
fmt.Println(nums)
|
|
||||||
}
|
|
||||||
|
|
@ -1,22 +0,0 @@
|
||||||
# Link to task: https://leetcode.com/problems/remove-duplicates-from-sorted-array/
|
|
||||||
from typing import List
|
|
||||||
|
|
||||||
class Solution:
|
|
||||||
def removeDuplicates(self, nums: List[int]) -> int:
|
|
||||||
if len(nums) <= 1:
|
|
||||||
return 0
|
|
||||||
unique, iteratror, real_pose = 1, 1, 0
|
|
||||||
while iteratror < len(nums):
|
|
||||||
if nums[real_pose] != nums[iteratror]:
|
|
||||||
unique += 1
|
|
||||||
real_pose += 1
|
|
||||||
nums[real_pose] = nums[iteratror]
|
|
||||||
iteratror += 1
|
|
||||||
return unique
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
# nums = [1, 1, 2]
|
|
||||||
nums = [0,0,1,1,1,2,2,3,3,4]
|
|
||||||
print(Solution().removeDuplicates(nums))
|
|
||||||
print(nums)
|
|
||||||
|
|
@ -1,23 +0,0 @@
|
||||||
# Link: https://leetcode.com/problems/remove-element/description/
|
|
||||||
from typing import List
|
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
|
||||||
def removeElement(self, nums: List[int], val: int) -> int:
|
|
||||||
c = 0
|
|
||||||
n = len(nums) - 1
|
|
||||||
while n >= 0:
|
|
||||||
if nums[n] == val:
|
|
||||||
del nums[n]
|
|
||||||
else:
|
|
||||||
c += 1
|
|
||||||
n -= 1
|
|
||||||
return c
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
# nums = [0, 1, 2, 2, 3, 0, 4, 2]
|
|
||||||
nums = [3, 2, 2, 3]
|
|
||||||
print(nums)
|
|
||||||
print(Solution().removeElement(nums, 3))
|
|
||||||
print(nums)
|
|
||||||
|
|
@ -1,48 +0,0 @@
|
||||||
from typing import List
|
|
||||||
|
|
||||||
|
|
||||||
class SolutionOne:
|
|
||||||
def shuffle(self, nums: List[int], n: int) -> List[int]:
|
|
||||||
n_a = []
|
|
||||||
l = 0
|
|
||||||
for i in range(0, len(nums)):
|
|
||||||
if i % 2 == 0:
|
|
||||||
n_a.append(nums[l])
|
|
||||||
l += 1
|
|
||||||
else:
|
|
||||||
n_a.append(nums[n])
|
|
||||||
n += 1
|
|
||||||
return n_a
|
|
||||||
|
|
||||||
|
|
||||||
class SolutionTwo:
|
|
||||||
def shuffle(self, nums: List[int], n: int) -> List[int]:
|
|
||||||
lst = []
|
|
||||||
for i in range(n):
|
|
||||||
lst += [nums[i]]
|
|
||||||
lst += [nums[i + n]]
|
|
||||||
return lst
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
nums = [2, 5, 1, 3, 4, 7]
|
|
||||||
n = 3
|
|
||||||
sol = SolutionTwo
|
|
||||||
print(nums)
|
|
||||||
print(sol().shuffle(nums, n))
|
|
||||||
print("-" * 60)
|
|
||||||
nums = [1, 2, 3, 4, 4, 3, 2, 1]
|
|
||||||
n = 4
|
|
||||||
print(nums)
|
|
||||||
print(sol().shuffle(nums, n))
|
|
||||||
print("-" * 60)
|
|
||||||
nums = [1, 1, 2, 2]
|
|
||||||
n = 2
|
|
||||||
print(nums)
|
|
||||||
print(sol().shuffle(nums, n))
|
|
||||||
print("-" * 60)
|
|
||||||
nums = [1, 2]
|
|
||||||
n = 1
|
|
||||||
print(nums)
|
|
||||||
print(SolutionOne().shuffle(nums, n))
|
|
||||||
print("-" * 60)
|
|
||||||
|
|
@ -1,8 +0,0 @@
|
||||||
import pytest
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("input, exp_output", [
|
|
||||||
|
|
||||||
])
|
|
||||||
def test_solution(input, exp_output):
|
|
||||||
sol = Solution()
|
|
||||||
assert sol == exp_output
|
|
||||||
|
|
@ -1,21 +0,0 @@
|
||||||
Binary Search
|
|
||||||
You are given an array of distinct integers nums, sorted in ascending order, and an integer target.
|
|
||||||
|
|
||||||
Implement a function to search for target within nums. If it exists, then return its index, otherwise, return -1.
|
|
||||||
|
|
||||||
Your solution must run in O(logn) time.
|
|
||||||
|
|
||||||
Example 1:
|
|
||||||
|
|
||||||
Input: nums = [-1,0,2,4,6,8], target = 4
|
|
||||||
|
|
||||||
Output: 3
|
|
||||||
Example 2:
|
|
||||||
|
|
||||||
Input: nums = [-1,0,2,4,6,8], target = 3
|
|
||||||
|
|
||||||
Output: -1
|
|
||||||
Constraints:
|
|
||||||
|
|
||||||
1 <= nums.length <= 10000.
|
|
||||||
-10000 < nums[i], target < 10000
|
|
||||||
|
|
@ -1,24 +0,0 @@
|
||||||
from typing import List
|
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
|
||||||
def search(self, nums: List[int], target: int) -> int:
|
|
||||||
left = 0
|
|
||||||
right = len(nums) - 1
|
|
||||||
while left <= right:
|
|
||||||
mid = (right + left) // 2
|
|
||||||
if target < nums[mid]:
|
|
||||||
right = mid - 1
|
|
||||||
elif target > nums[mid]:
|
|
||||||
left = mid + 1
|
|
||||||
else:
|
|
||||||
return mid
|
|
||||||
return -1
|
|
||||||
|
|
||||||
|
|
||||||
s = Solution()
|
|
||||||
# nums = [-1, 0, 2, 4, 6, 8]
|
|
||||||
# print(s.search(nums, 4))
|
|
||||||
# print(s.search(nums, 3))
|
|
||||||
nums = [-1, 0, 3, 5, 9, 12]
|
|
||||||
print(s.search(nums, 9))
|
|
||||||
|
|
@ -1,49 +0,0 @@
|
||||||
##################### Section ##############################
|
|
||||||
# Section topic: Arrays
|
|
||||||
#
|
|
||||||
# Design an algorithm to encode a list of strings to a single string. The encoded string is then decoded back to the original list of strings.
|
|
||||||
#
|
|
||||||
# Please implement encode and decode
|
|
||||||
#
|
|
||||||
# Example 1:
|
|
||||||
#
|
|
||||||
# Input: ["neet","code","love","you"]
|
|
||||||
#
|
|
||||||
# Output:["neet","code","love","you"]
|
|
||||||
# Example 2:
|
|
||||||
#
|
|
||||||
# Input: ["we","say",":","yes"]
|
|
||||||
#
|
|
||||||
# Output: ["we","say",":","yes"]
|
|
||||||
# Constraints:
|
|
||||||
#
|
|
||||||
# 0 <= strs.length < 100
|
|
||||||
# 0 <= strs[i].length < 200
|
|
||||||
# strs[i] contains only UTF-8 characters.
|
|
||||||
#
|
|
||||||
############################################################
|
|
||||||
from typing import List
|
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
|
||||||
def encode(self, strs: List[str]) -> str:
|
|
||||||
delim: str = "-+-"
|
|
||||||
res: str = ""
|
|
||||||
counts: str = ""
|
|
||||||
encoded: str = ""
|
|
||||||
for elem in strs:
|
|
||||||
counts += f"{len(elem)}{delim}"
|
|
||||||
encoded += elem
|
|
||||||
counts += delim
|
|
||||||
res = counts + encoded
|
|
||||||
return encoded
|
|
||||||
|
|
||||||
|
|
||||||
def decode(self, s: str) -> List[str]:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
s = Solution()
|
|
||||||
|
|
||||||
print(s.encode(strs=["we", "say", ":", "yes"]))
|
|
||||||
# s.decode("we say: yes")
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
|
|
||||||
|
|
@ -1,64 +0,0 @@
|
||||||
##################### Section ##############################
|
|
||||||
# Section topic: Arrays
|
|
||||||
#
|
|
||||||
# Design an algorithm to encode a list of strings to a single string. The encoded string is then decoded back to the original list of strings.
|
|
||||||
#
|
|
||||||
# Please implement encode and decode
|
|
||||||
#
|
|
||||||
# Example 1:
|
|
||||||
#
|
|
||||||
# Input: ["neet","code","love","you"]
|
|
||||||
#
|
|
||||||
# Output:["neet","code","love","you"]
|
|
||||||
# Example 2:
|
|
||||||
#
|
|
||||||
# Input: ["we","say",":","yes"]
|
|
||||||
#
|
|
||||||
# Output: ["we","say",":","yes"]
|
|
||||||
# Constraints:
|
|
||||||
#
|
|
||||||
# 0 <= strs.length < 100
|
|
||||||
# 0 <= strs[i].length < 200
|
|
||||||
# strs[i] contains only UTF-8 characters.
|
|
||||||
#
|
|
||||||
############################################################
|
|
||||||
from typing import List
|
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
|
||||||
delim: str = "-+-"
|
|
||||||
|
|
||||||
def encode(self, strs: List[str]) -> str:
|
|
||||||
if not strs:
|
|
||||||
return ""
|
|
||||||
delim: str = self.delim
|
|
||||||
res: str = ""
|
|
||||||
counts: str = ""
|
|
||||||
encoded: str = ""
|
|
||||||
for elem in strs:
|
|
||||||
counts += f"{len(elem)}{delim}"
|
|
||||||
encoded += elem
|
|
||||||
counts += delim
|
|
||||||
res = counts + encoded
|
|
||||||
return res
|
|
||||||
|
|
||||||
def decode(self, s: str) -> List[str]:
|
|
||||||
breakpoint()
|
|
||||||
if not s:
|
|
||||||
return []
|
|
||||||
res = []
|
|
||||||
splitted = s.split(f"{self.delim}{self.delim}")
|
|
||||||
breaks = [int(s) for s in splitted[0].split(self.delim)]
|
|
||||||
i = 0
|
|
||||||
for l in breaks:
|
|
||||||
res.append(splitted[1][i:i+l])
|
|
||||||
i += l
|
|
||||||
return res
|
|
||||||
|
|
||||||
|
|
||||||
s = Solution()
|
|
||||||
|
|
||||||
en = s.encode(strs=["we", "say", ":", "yes"])
|
|
||||||
en = s.encode(strs=["we", "", "say", ":", "yes"])
|
|
||||||
en = s.encode(strs=[])
|
|
||||||
print(s.decode(en))
|
|
||||||
|
|
@ -1,55 +0,0 @@
|
||||||
Longest Consecutive Sequence
|
|
||||||
Given an array of integers nums, return the length of the longest consecutive sequence of elements that can be formed.
|
|
||||||
|
|
||||||
A consecutive sequence is a sequence of elements in which each element is exactly 1 greater than the previous element. The elements do not have to be consecutive in the original array.
|
|
||||||
|
|
||||||
You must write an algorithm that runs in O(n) time.
|
|
||||||
|
|
||||||
Example 1:
|
|
||||||
|
|
||||||
Input: nums = [2,20,4,10,3,4,5]
|
|
||||||
|
|
||||||
Output: 4
|
|
||||||
Explanation: The longest consecutive sequence is [2, 3, 4, 5].
|
|
||||||
|
|
||||||
Example 2:
|
|
||||||
|
|
||||||
Input: nums = [0,3,2,5,4,6,1,1]
|
|
||||||
|
|
||||||
Output: 7
|
|
||||||
Constraints:
|
|
||||||
|
|
||||||
0 <= nums.length <= 1000
|
|
||||||
-10^9 <= nums[i] <= 10^9
|
|
||||||
|
|
||||||
# Solution
|
|
||||||
|
|
||||||
[2,20,4,10,3,4,5]
|
|
||||||
|
|
||||||
# 1
|
|
||||||
e = 2
|
|
||||||
[[2]]
|
|
||||||
|
|
||||||
# 2
|
|
||||||
e = 20
|
|
||||||
[[2], [20]]
|
|
||||||
|
|
||||||
# 3
|
|
||||||
e = 4
|
|
||||||
[[2], [20], [4]]
|
|
||||||
|
|
||||||
# 4
|
|
||||||
e = 10
|
|
||||||
[[2], [20], [4], [10]]
|
|
||||||
|
|
||||||
# 5
|
|
||||||
e = 3
|
|
||||||
[[2,3], [20], [4], [10]]
|
|
||||||
|
|
||||||
# 6
|
|
||||||
e = 4
|
|
||||||
[[2,3,4], [20], [4], [10]]
|
|
||||||
|
|
||||||
# 7
|
|
||||||
e = 5
|
|
||||||
[[2,3,4,5], [20], [4], [10]]
|
|
||||||
|
|
@ -1,33 +0,0 @@
|
||||||
from typing import List
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
|
||||||
def longestConsecutive(self, nums: List[int]) -> int:
|
|
||||||
if len(nums) == 0:
|
|
||||||
return 0
|
|
||||||
res: List[List[int]] = []
|
|
||||||
for i in range(0, len(nums)):
|
|
||||||
if i == 0:
|
|
||||||
res.append([nums[i]])
|
|
||||||
continue
|
|
||||||
e = nums[i]
|
|
||||||
for ri in range(0, len(res)):
|
|
||||||
if res[ri][-1] + 1 == e:
|
|
||||||
res[ri].append(e)
|
|
||||||
break
|
|
||||||
res.append([e])
|
|
||||||
return res
|
|
||||||
return max([len(r) for r in res])
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
|
||||||
"input_value, expected_value",
|
|
||||||
[
|
|
||||||
([2, 20, 4, 10, 3, 4, 5], 4),
|
|
||||||
([0, 3, 2, 5, 4, 6, 1, 1], 7),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
def test_solution(input_value, expected_value):
|
|
||||||
s = Solution()
|
|
||||||
assert s.longestConsecutive(nums=input_value) == expected_value
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 184 KiB |
|
|
@ -1,35 +0,0 @@
|
||||||
class MinStack:
|
|
||||||
def __init__(self):
|
|
||||||
self.stack = []
|
|
||||||
self.min_stack = []
|
|
||||||
|
|
||||||
def push(self, val: int) -> None:
|
|
||||||
self.stack.append(val)
|
|
||||||
if not self.min_stack:
|
|
||||||
self.min_stack.append(val)
|
|
||||||
else:
|
|
||||||
self.min_stack.append(min(val, self.min_stack[-1]))
|
|
||||||
|
|
||||||
def pop(self) -> None:
|
|
||||||
if self.min_stack:
|
|
||||||
self.min_stack.pop()
|
|
||||||
if self.stack:
|
|
||||||
self.stack.pop()
|
|
||||||
else:
|
|
||||||
return None
|
|
||||||
|
|
||||||
def top(self) -> int:
|
|
||||||
return self.stack[-1]
|
|
||||||
|
|
||||||
def getMin(self) -> int:
|
|
||||||
if self.min_stack:
|
|
||||||
return self.min_stack[-1]
|
|
||||||
else:
|
|
||||||
return None
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
s = MinStack()
|
|
||||||
s.push(12)
|
|
||||||
s.pop()
|
|
||||||
s.pop()
|
|
||||||
print(s.getMin())
|
|
||||||
|
|
@ -1,21 +0,0 @@
|
||||||
Given an integer array nums, return an array output where output[i] is the product of all the elements of nums except nums[i].
|
|
||||||
|
|
||||||
Each product is guaranteed to fit in a 32-bit integer.
|
|
||||||
|
|
||||||
Follow-up: Could you solve it in O (n)
|
|
||||||
O(n) time without using the division operation?
|
|
||||||
|
|
||||||
Example 1:
|
|
||||||
|
|
||||||
Input: nums = [1,2,4,6]
|
|
||||||
|
|
||||||
Output: [48,24,12,8]
|
|
||||||
Example 2:
|
|
||||||
|
|
||||||
Input: nums = [-1,0,1,2,3]
|
|
||||||
|
|
||||||
Output: [0,-6,0,0,0]
|
|
||||||
Constraints:
|
|
||||||
|
|
||||||
2 <= nums.length <= 1000
|
|
||||||
-20 <= nums[i] <= 20
|
|
||||||
|
|
@ -1,83 +0,0 @@
|
||||||
from typing import List
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
|
||||||
"""Bruteforce solution (4 hints)"""
|
|
||||||
|
|
||||||
def productExceptSelf(self, nums: List[int]) -> List[int]:
|
|
||||||
if not nums:
|
|
||||||
return []
|
|
||||||
res = []
|
|
||||||
while len(res) != len(nums):
|
|
||||||
for i in range(0, len(nums)):
|
|
||||||
j = 0
|
|
||||||
tmp = 0
|
|
||||||
for j in range(0, len(nums)):
|
|
||||||
if i == j:
|
|
||||||
continue
|
|
||||||
if j == 0:
|
|
||||||
tmp = nums[j]
|
|
||||||
continue
|
|
||||||
if j == 1 and i == 0:
|
|
||||||
tmp = nums[j]
|
|
||||||
continue
|
|
||||||
tmp *= nums[j]
|
|
||||||
res.append(tmp)
|
|
||||||
return res
|
|
||||||
|
|
||||||
|
|
||||||
class SolutionUnoptimal:
|
|
||||||
"""Unoptimal prefix-postfix solution"""
|
|
||||||
|
|
||||||
def productExceptSelf(self, nums: List[int]) -> List[int]:
|
|
||||||
prefixes: List[int] = [1] * len(nums)
|
|
||||||
postfixes: List[int] = [1] * len(nums)
|
|
||||||
res: List[int] = [1] * len(nums)
|
|
||||||
prefix, postfix = 1, 1
|
|
||||||
for num_index in range(0, len(nums)):
|
|
||||||
prefixes[num_index] = prefix * nums[num_index]
|
|
||||||
prefix = prefixes[num_index]
|
|
||||||
for num_index in range(len(nums) - 1, -1, -1):
|
|
||||||
postfixes[num_index] = postfix * nums[num_index]
|
|
||||||
postfix = postfixes[num_index]
|
|
||||||
for i in range(0, len(res)):
|
|
||||||
if i == 0:
|
|
||||||
res[i] = 1 * postfixes[i + 1]
|
|
||||||
continue
|
|
||||||
if i == len(res) - 1:
|
|
||||||
res[i] = prefixes[i - 1] * 1
|
|
||||||
continue
|
|
||||||
res[i] = prefixes[i - 1] * postfixes[i + 1]
|
|
||||||
return res
|
|
||||||
|
|
||||||
|
|
||||||
class SolutionOptimal:
|
|
||||||
"""Optimal prefix-postfix solution"""
|
|
||||||
|
|
||||||
def productExceptSelf(self, nums: List[int]) -> List[int]:
|
|
||||||
prefix: int = 1
|
|
||||||
res: List[int] = [1] * len(nums)
|
|
||||||
# Left -> Right
|
|
||||||
for i in range(0, len(nums)):
|
|
||||||
res[i] = prefix
|
|
||||||
prefix = nums[i] * prefix
|
|
||||||
# Right -> Left
|
|
||||||
postfix: int = 1
|
|
||||||
for i in range(len(nums) - 1, -1, -1):
|
|
||||||
res[i] = postfix * res[i]
|
|
||||||
postfix = nums[i] * postfix
|
|
||||||
return res
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
|
||||||
"input_value, expected_value",
|
|
||||||
[
|
|
||||||
([1, 2, 4, 6], [48, 24, 12, 8]),
|
|
||||||
([-1, 0, 1, 2, 3], [0, -6, 0, 0, 0]),
|
|
||||||
([-1, 1, 0, -3, 3], [0, 0, 9, 0, 0]),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
def test_solution(input_value, expected_value):
|
|
||||||
s = SolutionOptimal()
|
|
||||||
assert s.productExceptSelf(nums=input_value) == expected_value
|
|
||||||
|
|
@ -1,27 +0,0 @@
|
||||||
Search a 2D Matrix
|
|
||||||
You are given an m x n 2-D integer array matrix and an integer target.
|
|
||||||
|
|
||||||
Each row in matrix is sorted in non-decreasing order.
|
|
||||||
The first integer of every row is greater than the last integer of the previous row.
|
|
||||||
Return true if target exists within matrix or false otherwise.
|
|
||||||
|
|
||||||
Can you write a solution that runs in O(log(m * n)) time?
|
|
||||||
|
|
||||||
Example 1:
|
|
||||||
|
|
||||||
|
|
||||||
Input: matrix = [[1,2,4,8],[10,11,12,13],[14,20,30,40]], target = 10
|
|
||||||
|
|
||||||
Output: true
|
|
||||||
Example 2:
|
|
||||||
|
|
||||||
|
|
||||||
Input: matrix = [[1,2,4,8],[10,11,12,13],[14,20,30,40]], target = 15
|
|
||||||
|
|
||||||
Output: false
|
|
||||||
Constraints:
|
|
||||||
|
|
||||||
m == matrix.length
|
|
||||||
n == matrix[i].length
|
|
||||||
1 <= m, n <= 100
|
|
||||||
-10000 <= matrix[i][j], target <= 10000
|
|
||||||
|
|
@ -1,55 +0,0 @@
|
||||||
from typing import List
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
|
||||||
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
|
|
||||||
matrix_length = len(matrix)
|
|
||||||
right = len(matrix) - 1
|
|
||||||
left = 0
|
|
||||||
middle = matrix_length // 2
|
|
||||||
while left <= right:
|
|
||||||
middle_row_left = matrix[middle][0]
|
|
||||||
middle_row_right = matrix[middle][-1]
|
|
||||||
# Check if target is in current middle row
|
|
||||||
if target >= middle_row_left and target <= middle_row_right:
|
|
||||||
bingo_matrix = matrix[middle]
|
|
||||||
bingo_matrix_left = 0
|
|
||||||
bingo_matrix_right = len(bingo_matrix) - 1
|
|
||||||
bingo_matrix_middle = (bingo_matrix_left + bingo_matrix_right) // 2
|
|
||||||
print(bingo_matrix)
|
|
||||||
while bingo_matrix_left <= bingo_matrix_right:
|
|
||||||
print(f"Middle: {bingo_matrix[bingo_matrix_middle]}")
|
|
||||||
if target < bingo_matrix[bingo_matrix_middle]:
|
|
||||||
bingo_matrix_right = bingo_matrix_middle - 1
|
|
||||||
bingo_matrix_middle = (
|
|
||||||
bingo_matrix_left + bingo_matrix_right
|
|
||||||
) // 2
|
|
||||||
elif target > bingo_matrix[bingo_matrix_middle]:
|
|
||||||
bingo_matrix_left = bingo_matrix_middle + 1
|
|
||||||
bingo_matrix_middle = (
|
|
||||||
bingo_matrix_left + bingo_matrix_right
|
|
||||||
) // 2
|
|
||||||
else:
|
|
||||||
print("Target: {target}")
|
|
||||||
return True
|
|
||||||
return False
|
|
||||||
if target < middle_row_left:
|
|
||||||
right = middle - 1
|
|
||||||
middle = (left + right) // 2
|
|
||||||
else:
|
|
||||||
left = middle + 1
|
|
||||||
middle = (left + right) // 2
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
|
||||||
"input_value,target, expected_value",
|
|
||||||
[
|
|
||||||
([[1, 2, 4, 8], [10, 11, 12, 13], [14, 20, 30, 40]], 10, True),
|
|
||||||
([[1, 2, 4, 8], [10, 11, 12, 13], [14, 20, 30, 40]], 15, False),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
def test_solution(input_value, target, expected_value):
|
|
||||||
s = Solution()
|
|
||||||
assert s.searchMatrix(matrix=input_value, target=target) == expected_value
|
|
||||||
|
|
@ -1,110 +0,0 @@
|
||||||
##################### Section ##############################
|
|
||||||
# Section topic: Arrays and hashing
|
|
||||||
# Task name: Top K Frequent Elements
|
|
||||||
# Task:
|
|
||||||
# Given an integer array nums and an integer k, return the k most frequent
|
|
||||||
# elements within the array.
|
|
||||||
#
|
|
||||||
# The test cases are generated such that the answer is always unique.
|
|
||||||
#
|
|
||||||
# You may return the output in any order.
|
|
||||||
#
|
|
||||||
# Example 1:
|
|
||||||
#
|
|
||||||
# Input: nums = [1,2,2,3,3,3], k = 2
|
|
||||||
#
|
|
||||||
# Output: [2,3]
|
|
||||||
# Example 2:
|
|
||||||
#
|
|
||||||
# Input: nums = [7,7], k = 1
|
|
||||||
#
|
|
||||||
# Output: [7]
|
|
||||||
# Constraints:
|
|
||||||
#
|
|
||||||
# 1 <= nums.length <= 10^4.
|
|
||||||
# -1000 <= nums[i] <= 1000
|
|
||||||
# 1 <= k <= number of distinct elements in nums.
|
|
||||||
############################################################
|
|
||||||
|
|
||||||
##################### Section ##############################
|
|
||||||
# Section topic: Мой ход мыслей
|
|
||||||
# Заход 1
|
|
||||||
# Допустим возьмем простой массив, где в качестве индекса будет кол-во раз, которое
|
|
||||||
# встречается число в массиве nums
|
|
||||||
#
|
|
||||||
# Пример для первого кейса:
|
|
||||||
# cout = [0,1,2,3,4,5,6,7,8,9,...]
|
|
||||||
# 0,1,2,3,0,0,0,0,0,0,...
|
|
||||||
#
|
|
||||||
# Пример для второго кейса:
|
|
||||||
# cout = [0,1,2,3,4,5,6,7,8,9,...]
|
|
||||||
# 0,0,0,0,0,0,0,2,0,0,...
|
|
||||||
#
|
|
||||||
# Пример для неотсортированного массива
|
|
||||||
# nums = [4,1,2,5,5,2,3,1,6,3,2,0]
|
|
||||||
#
|
|
||||||
# cout = [0,1,2,3,4,5,6,7,8,9,...]
|
|
||||||
# 1,2,3,2,1,2,1,0,0,0,...
|
|
||||||
#
|
|
||||||
# => Заход не рабочий
|
|
||||||
#
|
|
||||||
# Заход 2
|
|
||||||
# Допустим будем хранить кол-во повторений в словаре, тогда на после первого
|
|
||||||
# просчета будем иметь:
|
|
||||||
#
|
|
||||||
# Первый случай:
|
|
||||||
# {1: 1, 2: 2, 3: 3}
|
|
||||||
#
|
|
||||||
# Второй случай:
|
|
||||||
# {7: 2}
|
|
||||||
#
|
|
||||||
# Получив такие словари берем, создаем массив с длиной len(nums) и заполненный нулями
|
|
||||||
# len(nums) = 6 => res = [[0],[0],[0],[0],[0],[0],[0]]
|
|
||||||
#
|
|
||||||
# {1: 1} => res[1].append(1)
|
|
||||||
# {2: 2} => res[2].append(2)
|
|
||||||
# {3: 3} => res[3].append(3)
|
|
||||||
#
|
|
||||||
#
|
|
||||||
# res = [[0],[1],[2],[3],[0],[0],[0]]
|
|
||||||
#
|
|
||||||
# Для семерок не интересно, попробуем для третьего примера первого кейса:
|
|
||||||
# nums = [4,1,2,5,5,2,3,1,6,3,2,0]
|
|
||||||
#
|
|
||||||
#
|
|
||||||
# Начинаем итерацию по полученному словарю
|
|
||||||
# {4: 1, 1: 2, 2: 3, 5: 2, 3: 2, 6: 1, 0: 1}
|
|
||||||
# res = [[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0]]
|
|
||||||
#
|
|
||||||
# {4:1} => res[1].append(4)
|
|
||||||
# {1:2} => res[2].append(1)
|
|
||||||
# {2:3} => res[3].append(2)
|
|
||||||
# {5:2} => res[2].append(5)
|
|
||||||
# {3:2} => res[2].append(3)
|
|
||||||
# {6:1} => res[1].append(6)
|
|
||||||
# {0:1} => res[1].append(0)
|
|
||||||
############################################################
|
|
||||||
|
|
||||||
|
|
||||||
from typing import List
|
|
||||||
from collections import defaultdict
|
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
|
||||||
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
|
|
||||||
ic = defaultdict(int)
|
|
||||||
for n in nums:
|
|
||||||
ic[n] += 1
|
|
||||||
res = [[] for _ in range(0, len(nums)+1)]
|
|
||||||
for num,count in ic.items():
|
|
||||||
res[count].append(num)
|
|
||||||
return [item for sublist in res for item in sublist][-k:]
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
s = Solution()
|
|
||||||
nums = [7,7]
|
|
||||||
# nums = [1,2,2,3,3,3]
|
|
||||||
# nums = [4,1,2,5,5,2,3,1,6,3,2,0]
|
|
||||||
k = 1
|
|
||||||
print(s.topKFrequent(nums, k))
|
|
||||||
|
|
@ -1,89 +0,0 @@
|
||||||
You are given a a 9 x 9 Sudoku board board. A Sudoku board is valid if the following rules are followed:
|
|
||||||
|
|
||||||
Each row must contain the digits 1-9 without duplicates.
|
|
||||||
Each column must contain the digits 1-9 without duplicates.
|
|
||||||
Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without duplicates.
|
|
||||||
Return true if the Sudoku board is valid, otherwise return false
|
|
||||||
|
|
||||||
Note: A board does not need to be full or be solvable to be valid.
|
|
||||||
|
|
||||||
Example 1:
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Input: board =
|
|
||||||
[["1","2",".",".","3",".",".",".","."],
|
|
||||||
["4",".",".","5",".",".",".",".","."],
|
|
||||||
[".","9","8",".",".",".",".",".","3"],
|
|
||||||
["5",".",".",".","6",".",".",".","4"],
|
|
||||||
[".",".",".","8",".","3",".",".","5"],
|
|
||||||
["7",".",".",".","2",".",".",".","6"],
|
|
||||||
[".",".",".",".",".",".","2",".","."],
|
|
||||||
[".",".",".","4","1","9",".",".","8"],
|
|
||||||
[".",".",".",".","8",".",".","7","9"]]
|
|
||||||
|
|
||||||
Output: true
|
|
||||||
Example 2:
|
|
||||||
|
|
||||||
Input: board =
|
|
||||||
[["1","2",".",".","3",".",".",".","."],
|
|
||||||
["4",".",".","5",".",".",".",".","."],
|
|
||||||
[".","9","1",".",".",".",".",".","3"],
|
|
||||||
["5",".",".",".","6",".",".",".","4"],
|
|
||||||
[".",".",".","8",".","3",".",".","5"],
|
|
||||||
["7",".",".",".","2",".",".",".","6"],
|
|
||||||
[".",".",".",".",".",".","2",".","."],
|
|
||||||
[".",".",".","4","1","9",".",".","8"],
|
|
||||||
[".",".",".",".","8",".",".","7","9"]]
|
|
||||||
|
|
||||||
Output: false
|
|
||||||
Explanation: There are two 1's in the top-left 3x3 sub-box.
|
|
||||||
|
|
||||||
Constraints:
|
|
||||||
|
|
||||||
board.length == 9
|
|
||||||
board[i].length == 9
|
|
||||||
board[i][j] is a digit 1-9 or '.'.
|
|
||||||
|
|
||||||
# Решение
|
|
||||||
Пусть будет матрица 3х3 где будут храниться числа в каждом квадрате валидации, т.е.
|
|
||||||
```
|
|
||||||
sq = [
|
|
||||||
(), (), (),
|
|
||||||
(), (), (),
|
|
||||||
(), (), (),
|
|
||||||
]
|
|
||||||
```
|
|
||||||
Когда начнем проходить по двумерной матрице - будем смотреть на номер строк и остаток деления на три от длины проверяемого столбца, чтобы определять в какой квадрат писать
|
|
||||||
|
|
||||||
|
|
||||||
i // 3
|
|
||||||
[
|
|
||||||
0 0 0 0 0 0 0 0 0
|
|
||||||
0 0 0 0 0 0 0 0 0
|
|
||||||
0 0 0 0 0 0 0 0 0
|
|
||||||
|
|
||||||
1 1 1 1 1 1 1 1 1
|
|
||||||
1 1 1 1 1 1 1 1 1
|
|
||||||
1 1 1 1 1 1 1 1 1
|
|
||||||
|
|
||||||
2 2 2 2 2 2 2 2 2
|
|
||||||
2 2 2 2 2 2 2 2 2
|
|
||||||
2 2 2 2 2 2 2 2 2
|
|
||||||
]
|
|
||||||
|
|
||||||
j // 3
|
|
||||||
[
|
|
||||||
0 0 0 1 1 1 2 2 2
|
|
||||||
0 0 0 1 1 1 2 2 2
|
|
||||||
0 0 0 1 1 1 2 2 2
|
|
||||||
|
|
||||||
0 0 0 1 1 1 2 2 2
|
|
||||||
0 0 0 1 1 1 2 2 2
|
|
||||||
0 0 0 1 1 1 2 2 2
|
|
||||||
|
|
||||||
0 0 0 1 1 1 2 2 2
|
|
||||||
0 0 0 1 1 1 2 2 2
|
|
||||||
0 0 0 1 1 1 2 2 2
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
@ -1,74 +0,0 @@
|
||||||
from typing import Dict, List, Set
|
|
||||||
import pytest
|
|
||||||
from collections import defaultdict
|
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
|
||||||
"""Bruteforce solution (4 hints)"""
|
|
||||||
|
|
||||||
def isValidSudoku(self, board: List[List[str]]) -> bool:
|
|
||||||
squares: Dict = {
|
|
||||||
"00": set(),
|
|
||||||
"01": set(),
|
|
||||||
"02": set(),
|
|
||||||
"10": set(),
|
|
||||||
"11": set(),
|
|
||||||
"12": set(),
|
|
||||||
"20": set(),
|
|
||||||
"21": set(),
|
|
||||||
"22": set(),
|
|
||||||
}
|
|
||||||
lines = defaultdict(set)
|
|
||||||
for i in range(0, len(board)):
|
|
||||||
for j in range(0, len(board[i])):
|
|
||||||
board_elem = board[i][j]
|
|
||||||
squares_index = f"{i // 3}{j // 3}"
|
|
||||||
squares_index_len = len(squares[squares_index])
|
|
||||||
lines_index_len = len(lines[squares_index])
|
|
||||||
if board_elem != ".":
|
|
||||||
squares[squares_index].add(board_elem)
|
|
||||||
if len(squares[squares_index]) == squares_index_len:
|
|
||||||
return False
|
|
||||||
lines[f"{i}{j}"].add(board_elem)
|
|
||||||
if len(lines[f"{i}{j}"]) == lines_index_len:
|
|
||||||
breakpoint()
|
|
||||||
return False
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
|
||||||
"input_value, expected_value",
|
|
||||||
[
|
|
||||||
(
|
|
||||||
[
|
|
||||||
["1", "2", ".", ".", "3", ".", ".", ".", "."],
|
|
||||||
["4", ".", ".", "5", ".", ".", ".", ".", "."],
|
|
||||||
[".", "9", "8", ".", ".", ".", ".", ".", "3"],
|
|
||||||
["5", ".", ".", ".", "6", ".", ".", ".", "4"],
|
|
||||||
[".", ".", ".", "8", ".", "3", ".", ".", "5"],
|
|
||||||
["7", ".", ".", ".", "2", ".", ".", ".", "6"],
|
|
||||||
[".", ".", ".", ".", ".", ".", "2", ".", "."],
|
|
||||||
[".", ".", ".", "4", "1", "9", ".", ".", "8"],
|
|
||||||
[".", ".", ".", ".", "8", ".", ".", "7", "9"],
|
|
||||||
],
|
|
||||||
True,
|
|
||||||
),
|
|
||||||
(
|
|
||||||
[
|
|
||||||
["1", "2", ".", ".", "3", ".", ".", ".", "."],
|
|
||||||
["4", ".", ".", "5", ".", ".", ".", ".", "."],
|
|
||||||
[".", "9", "1", ".", ".", ".", ".", ".", "3"],
|
|
||||||
["5", ".", ".", ".", "6", ".", ".", ".", "4"],
|
|
||||||
[".", ".", ".", "8", ".", "3", ".", ".", "5"],
|
|
||||||
["7", ".", ".", ".", "2", ".", ".", ".", "6"],
|
|
||||||
[".", ".", ".", ".", ".", ".", "2", ".", "."],
|
|
||||||
[".", ".", ".", "4", "1", "9", ".", ".", "8"],
|
|
||||||
[".", ".", ".", ".", "8", ".", ".", "7", "9"],
|
|
||||||
],
|
|
||||||
False,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
def test_solution(input_value, expected_value):
|
|
||||||
s = Solution()
|
|
||||||
assert s.isValidSudoku(board=input_value) == expected_value
|
|
||||||
|
|
@ -1,78 +0,0 @@
|
||||||
package main
|
|
||||||
|
|
||||||
import "fmt"
|
|
||||||
|
|
||||||
type TreeNode struct {
|
|
||||||
Val int
|
|
||||||
Left *TreeNode
|
|
||||||
Right *TreeNode
|
|
||||||
}
|
|
||||||
|
|
||||||
func inorder(root *TreeNode) {
|
|
||||||
if root == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
inorder(root.Left)
|
|
||||||
fmt.Print(root.Val)
|
|
||||||
inorder(root.Right)
|
|
||||||
}
|
|
||||||
|
|
||||||
func preorder(root *TreeNode) {
|
|
||||||
if root == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
fmt.Print(root.Val)
|
|
||||||
preorder(root.Left)
|
|
||||||
preorder(root.Right)
|
|
||||||
}
|
|
||||||
|
|
||||||
func postorder(root *TreeNode) {
|
|
||||||
if root == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
postorder(root.Left)
|
|
||||||
postorder(root.Right)
|
|
||||||
fmt.Print(root.Val)
|
|
||||||
}
|
|
||||||
|
|
||||||
func reverserOrder(root *TreeNode) {
|
|
||||||
if root == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
reverserOrder(root.Right)
|
|
||||||
fmt.Print(root.Val)
|
|
||||||
reverserOrder(root.Left)
|
|
||||||
}
|
|
||||||
|
|
||||||
func traverse(root *TreeNode, res *[]int){
|
|
||||||
if root == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
traverse(root.Left, res)
|
|
||||||
*res = append(*res, root.Val)
|
|
||||||
traverse(root.Right, res)
|
|
||||||
}
|
|
||||||
func inorderTraversal(root *TreeNode) []int {
|
|
||||||
var result []int
|
|
||||||
traverse(root, &result)
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
n10 := TreeNode{Val: 2}
|
|
||||||
n9 := TreeNode{Val: 5}
|
|
||||||
n8 := TreeNode{Val: 7}
|
|
||||||
n7 := TreeNode{Val: 6, Left: &n9, Right: &n8}
|
|
||||||
n6 := TreeNode{Val: 3, Left: &n10}
|
|
||||||
n5 := TreeNode{Val: 4, Left: &n6, Right: &n7}
|
|
||||||
|
|
||||||
// inorder(&n5)
|
|
||||||
// fmt.Println()
|
|
||||||
// preorder(&n5)
|
|
||||||
// fmt.Println()
|
|
||||||
// postorder(&n5)
|
|
||||||
// fmt.Println()
|
|
||||||
// reverserOrder(&n5)
|
|
||||||
res := inorderTraversal(&n5)
|
|
||||||
fmt.Print(res)
|
|
||||||
}
|
|
||||||
|
|
@ -1,34 +0,0 @@
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
|
|
||||||
class TreeNode:
|
|
||||||
def __init__(self, val=0, left=None, right=None):
|
|
||||||
self.val = val
|
|
||||||
self.left = left
|
|
||||||
self.right = right
|
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
|
||||||
def find_min(self, root) -> TreeNode:
|
|
||||||
cur = root
|
|
||||||
while cur and cur.left:
|
|
||||||
cur = cur.left
|
|
||||||
return cur
|
|
||||||
|
|
||||||
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
|
|
||||||
if not root:
|
|
||||||
return None
|
|
||||||
if key < root.val:
|
|
||||||
root.left = self.deleteNode(root.left, key)
|
|
||||||
elif key > root.val:
|
|
||||||
root.right = self.deleteNode(root.right, key)
|
|
||||||
else:
|
|
||||||
if not root.right:
|
|
||||||
return root.left
|
|
||||||
elif not root.left:
|
|
||||||
return root.right
|
|
||||||
else:
|
|
||||||
min_node = self.find_min(root.right)
|
|
||||||
root.val = min_node.val
|
|
||||||
root.right = self.deleteNode(root.right, min_node.val)
|
|
||||||
return root
|
|
||||||
|
|
@ -1,30 +0,0 @@
|
||||||
You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.
|
|
||||||
|
|
||||||
Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Example 1:
|
|
||||||
|
|
||||||
|
|
||||||
Input: root = [4,2,7,1,3], val = 5
|
|
||||||
Output: [4,2,7,1,3,5]
|
|
||||||
Explanation: Another accepted tree is:
|
|
||||||
|
|
||||||
Example 2:
|
|
||||||
|
|
||||||
Input: root = [40,20,60,10,30,50,70], val = 25
|
|
||||||
Output: [40,20,60,10,30,50,70,null,null,25]
|
|
||||||
Example 3:
|
|
||||||
|
|
||||||
Input: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5
|
|
||||||
Output: [4,2,7,1,3,5]
|
|
||||||
|
|
||||||
|
|
||||||
Constraints:
|
|
||||||
|
|
||||||
The number of nodes in the tree will be in the range [0, 104].
|
|
||||||
-108 <= Node.val <= 108
|
|
||||||
All the values Node.val are unique.
|
|
||||||
-108 <= val <= 108
|
|
||||||
It's guaranteed that val does not exist in the original BST.
|
|
||||||
|
|
@ -1,30 +0,0 @@
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
|
|
||||||
class TreeNode:
|
|
||||||
def __init__(self, val=0, left=None, right=None):
|
|
||||||
self.val = val
|
|
||||||
self.left = left
|
|
||||||
self.right = right
|
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
|
||||||
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
|
|
||||||
if not root:
|
|
||||||
return TreeNode(val, None, None)
|
|
||||||
if val < root.val:
|
|
||||||
root.left = self.insertIntoBST(root.left, val)
|
|
||||||
elif val > root.val:
|
|
||||||
root.right = self.insertIntoBST(root.right, val)
|
|
||||||
return root
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
s = Solution()
|
|
||||||
n10 = TreeNode(1, None, None)
|
|
||||||
n9 = TreeNode(3, None, None)
|
|
||||||
n8 = TreeNode(2, n10, n9)
|
|
||||||
n7 = TreeNode(7, None, None)
|
|
||||||
root = TreeNode(4, n8, n7)
|
|
||||||
|
|
||||||
# print(s.searchBST(root, 2).val)
|
|
||||||
|
|
@ -1,18 +0,0 @@
|
||||||
700. Search in a Binary Search Tree
|
|
||||||
You are given the root of a binary search tree (BST) and an integer val.
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
Example 1:
|
|
||||||
Input: root = [4,2,7,1,3], val = 2
|
|
||||||
Output: [2,1,3]
|
|
||||||
|
|
||||||
Example 2:
|
|
||||||
Input: root = [4,2,7,1,3], val = 5
|
|
||||||
Output: []
|
|
||||||
|
|
||||||
Constraints:
|
|
||||||
The number of nodes in the tree is in the range [1, 5000].
|
|
||||||
1 <= Node.val <= 107
|
|
||||||
root is a binary search tree.
|
|
||||||
1 <= val <= 107
|
|
||||||
|
|
@ -1,32 +0,0 @@
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
|
|
||||||
class TreeNode:
|
|
||||||
def __init__(self, val=0, left=None, right=None):
|
|
||||||
self.val = val
|
|
||||||
self.left = left
|
|
||||||
self.right = right
|
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
|
||||||
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
|
|
||||||
if not root:
|
|
||||||
return None
|
|
||||||
|
|
||||||
if val < root.val:
|
|
||||||
return self.searchBST(root.left, val)
|
|
||||||
elif val > root.val:
|
|
||||||
return self.searchBST(root.right, val)
|
|
||||||
else:
|
|
||||||
return root
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
s = Solution()
|
|
||||||
n10 = TreeNode(1, None, None)
|
|
||||||
n9 = TreeNode(3, None, None)
|
|
||||||
n8 = TreeNode(2, n10, n9)
|
|
||||||
n7 = TreeNode(7, None, None)
|
|
||||||
root = TreeNode(4, n8, n7)
|
|
||||||
|
|
||||||
print(s.searchBST(root, 2).val)
|
|
||||||
|
|
@ -1,35 +0,0 @@
|
||||||
Linked List Cycle Detection
|
|
||||||
Given the beginning of a linked list head, return true if there is a cycle in the linked list. Otherwise, return false.
|
|
||||||
|
|
||||||
There is a cycle in a linked list if at least one node in the list that can be visited again by following the next pointer.
|
|
||||||
|
|
||||||
Internally, index determines the index of the beginning of the cycle, if it exists. The tail node of the list will set it's next pointer to the index-th node. If index = -1, then the tail node points to null and no cycle exists.
|
|
||||||
|
|
||||||
Note: index is not given to you as a parameter.
|
|
||||||
|
|
||||||
Example 1:
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Input: head = [1,2,3,4], index = 1
|
|
||||||
|
|
||||||
Output: true
|
|
||||||
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
|
|
||||||
|
|
||||||
Example 2:
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Input: head = [1,2], index = -1
|
|
||||||
|
|
||||||
Output: false
|
|
||||||
Constraints:
|
|
||||||
|
|
||||||
1 <= Length of the list <= 1000.
|
|
||||||
-1000 <= Node.val <= 1000
|
|
||||||
index is -1 or a valid index in the linked list.
|
|
||||||
|
|
||||||
# Solution
|
|
||||||
## Использовать хэшмап
|
|
||||||
|
|
||||||
nodes = defaultdict()
|
|
||||||
|
|
@ -1,33 +0,0 @@
|
||||||
from collections import defaultdict
|
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
|
|
||||||
class ListNode:
|
|
||||||
def __init__(self, val=0, next=None):
|
|
||||||
self.val = val
|
|
||||||
self.next = next
|
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
|
||||||
def hasCycle(self, head: Optional[ListNode]) -> bool:
|
|
||||||
nodes: set[ListNode] = set()
|
|
||||||
cur_node = head
|
|
||||||
while cur_node:
|
|
||||||
lb = len(nodes)
|
|
||||||
nodes.add(cur_node)
|
|
||||||
cur_node = cur_node.next
|
|
||||||
la = len(nodes)
|
|
||||||
if lb == la:
|
|
||||||
return True
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
s = Solution()
|
|
||||||
e3 = ListNode(3, None)
|
|
||||||
e2 = ListNode(2, e3)
|
|
||||||
e1 = ListNode(1, e2)
|
|
||||||
e0 = ListNode(0, e1)
|
|
||||||
# k = [e0, e1, e2, e3]
|
|
||||||
nb = s.hasCycle(e0)
|
|
||||||
print(nb)
|
|
||||||
|
|
@ -1,25 +0,0 @@
|
||||||
Merge K Sorted Linked Lists
|
|
||||||
You are given an array of k linked lists lists, where each list is sorted in ascending order.
|
|
||||||
|
|
||||||
Return the sorted linked list that is the result of merging all of the individual linked lists.
|
|
||||||
|
|
||||||
Example 1:
|
|
||||||
|
|
||||||
Input: lists = [[1,2,4],[1,3,5],[3,6]]
|
|
||||||
|
|
||||||
Output: [1,1,2,3,3,4,5,6]
|
|
||||||
Example 2:
|
|
||||||
|
|
||||||
Input: lists = []
|
|
||||||
|
|
||||||
Output: []
|
|
||||||
Example 3:
|
|
||||||
|
|
||||||
Input: lists = [[]]
|
|
||||||
|
|
||||||
Output: []
|
|
||||||
Constraints:
|
|
||||||
|
|
||||||
0 <= lists.length <= 1000
|
|
||||||
0 <= lists[i].length <= 100
|
|
||||||
-1000 <= lists[i][j] <= 1000
|
|
||||||
|
|
@ -1,55 +0,0 @@
|
||||||
from typing import List, Optional
|
|
||||||
|
|
||||||
|
|
||||||
# Definition for singly-linked list.
|
|
||||||
class ListNode:
|
|
||||||
def __init__(self, val=0, next=None):
|
|
||||||
self.val = val
|
|
||||||
self.next = next
|
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
|
||||||
def merge2lists(self, l1: ListNode, l2: ListNode) -> ListNode:
|
|
||||||
dummy = node = ListNode()
|
|
||||||
while l1 and l2:
|
|
||||||
if l1.val < l2.val:
|
|
||||||
node.next = l1
|
|
||||||
l1 = l1.next
|
|
||||||
else:
|
|
||||||
node.next = l2
|
|
||||||
l2 = l2.next
|
|
||||||
node = node.next
|
|
||||||
|
|
||||||
node.next = l1 or l2
|
|
||||||
|
|
||||||
return dummy.next
|
|
||||||
|
|
||||||
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
|
|
||||||
if len(lists) == 0 or not lists:
|
|
||||||
return None
|
|
||||||
if len(lists) == 1:
|
|
||||||
return lists[0]
|
|
||||||
middle = int(len(lists) / 2)
|
|
||||||
breakpoint()
|
|
||||||
left_side = self.mergeKLists(lists[0:middle])
|
|
||||||
right_side = self.mergeKLists(lists[middle:])
|
|
||||||
|
|
||||||
return self.merge2lists(left_side, right_side)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
s = Solution()
|
|
||||||
e3 = ListNode(3, None)
|
|
||||||
e2 = ListNode(2, e3)
|
|
||||||
e1 = ListNode(1, e2)
|
|
||||||
|
|
||||||
k3 = ListNode(5, None)
|
|
||||||
k2 = ListNode(3, k3)
|
|
||||||
k1 = ListNode(2, k2)
|
|
||||||
k0 = ListNode(0, k1)
|
|
||||||
|
|
||||||
s= Solution()
|
|
||||||
k = s.mergeKLists([e1, k0])
|
|
||||||
while k:
|
|
||||||
print(f"{k.val}")
|
|
||||||
k = k.next
|
|
||||||
|
|
@ -1,143 +0,0 @@
|
||||||
Merge Two Sorted Linked Lists
|
|
||||||
You are given the heads of two sorted linked lists list1 and list2.
|
|
||||||
|
|
||||||
Merge the two lists into one sorted linked list and return the head of the new sorted linked list.
|
|
||||||
|
|
||||||
The new list should be made up of nodes from list1 and list2.
|
|
||||||
|
|
||||||
Example 1:
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Input: list1 = [1,2,4], list2 = [1,3,5]
|
|
||||||
|
|
||||||
Output: [1,1,2,3,4,5]
|
|
||||||
Example 2:
|
|
||||||
|
|
||||||
Input: list1 = [], list2 = [1,2]
|
|
||||||
|
|
||||||
Output: [1,2]
|
|
||||||
Example 3:
|
|
||||||
|
|
||||||
Input: list1 = [], list2 = []
|
|
||||||
|
|
||||||
Output: []
|
|
||||||
Constraints:
|
|
||||||
|
|
||||||
0 <= The length of the each list <= 100.
|
|
||||||
-100 <= Node.val <= 100
|
|
||||||
|
|
||||||
# Solution
|
|
||||||
|
|
||||||
## Edge cases
|
|
||||||
### Two empty
|
|
||||||
l1 = []
|
|
||||||
l2 = []
|
|
||||||
|
|
||||||
r = None
|
|
||||||
### l1 empty
|
|
||||||
l1 = []
|
|
||||||
l2 = [1,2,...,n]
|
|
||||||
|
|
||||||
r = l2
|
|
||||||
### l2 empty
|
|
||||||
l1 = [1,2,...,n]
|
|
||||||
l2 = []
|
|
||||||
|
|
||||||
r = l1
|
|
||||||
|
|
||||||
## Algorithm
|
|
||||||
### 0
|
|
||||||
i
|
|
||||||
l1 = [1,2,4]
|
|
||||||
|
|
||||||
j
|
|
||||||
l2 = [1,3,5]
|
|
||||||
|
|
||||||
r = []
|
|
||||||
|
|
||||||
### 1
|
|
||||||
Before:
|
|
||||||
|
|
||||||
i
|
|
||||||
l1 = [1,2,4]
|
|
||||||
|
|
||||||
j
|
|
||||||
l2 = [1,3,5]
|
|
||||||
|
|
||||||
r = []
|
|
||||||
|
|
||||||
Step:
|
|
||||||
```
|
|
||||||
if i.val <= j.val:
|
|
||||||
r = i
|
|
||||||
i = i.next
|
|
||||||
```
|
|
||||||
|
|
||||||
After:
|
|
||||||
|
|
||||||
i
|
|
||||||
l1 = [1,2,4]
|
|
||||||
|
|
||||||
j
|
|
||||||
l2 = [1,3,5]
|
|
||||||
|
|
||||||
r = [l10]
|
|
||||||
|
|
||||||
### 2
|
|
||||||
Before:
|
|
||||||
i
|
|
||||||
l1 = [1,2,4]
|
|
||||||
|
|
||||||
j
|
|
||||||
l2 = [1,3,5]
|
|
||||||
|
|
||||||
r = [l10]
|
|
||||||
|
|
||||||
Step:
|
|
||||||
```
|
|
||||||
if i.val <= j.val:
|
|
||||||
---
|
|
||||||
else:
|
|
||||||
r.next = j
|
|
||||||
j = j.next
|
|
||||||
r = r.next
|
|
||||||
```
|
|
||||||
After:
|
|
||||||
i
|
|
||||||
l1 = [1,2,4]
|
|
||||||
|
|
||||||
j
|
|
||||||
l2 = [1,3,5]
|
|
||||||
|
|
||||||
r = [l10, l20]
|
|
||||||
|
|
||||||
### 3
|
|
||||||
Before:
|
|
||||||
i
|
|
||||||
l1 = [1,2,4]
|
|
||||||
|
|
||||||
j
|
|
||||||
l2 = [1,3,5]
|
|
||||||
|
|
||||||
r = [l10, l20]
|
|
||||||
|
|
||||||
Step:
|
|
||||||
```
|
|
||||||
if i.val <= j.val:
|
|
||||||
r.next = i
|
|
||||||
i = i.next
|
|
||||||
r = r.next
|
|
||||||
else:
|
|
||||||
r.next = j
|
|
||||||
j = j.next
|
|
||||||
r = r.next
|
|
||||||
```
|
|
||||||
After:
|
|
||||||
j
|
|
||||||
l1 = [1,2,4]
|
|
||||||
|
|
||||||
j
|
|
||||||
l2 = [1,3,5]
|
|
||||||
|
|
||||||
r = [l10, l20, l11]
|
|
||||||
|
|
@ -1,76 +0,0 @@
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
|
|
||||||
# Definition for singly-linked list.
|
|
||||||
class ListNode:
|
|
||||||
def __init__(self, val=0, next=None):
|
|
||||||
self.val = val
|
|
||||||
self.next = next
|
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
|
||||||
def mergeTwoLists(
|
|
||||||
self, list1: Optional[ListNode], list2: Optional[ListNode]
|
|
||||||
) -> Optional[ListNode]:
|
|
||||||
if not list1 and not list2:
|
|
||||||
return None
|
|
||||||
if not list1 and isinstance(list2, ListNode):
|
|
||||||
return list2
|
|
||||||
if not list2 and isinstance(list1, ListNode):
|
|
||||||
return list1
|
|
||||||
i = list1
|
|
||||||
j = list2
|
|
||||||
r = None
|
|
||||||
rf = None
|
|
||||||
while i or j:
|
|
||||||
print(f"i : {i.val if i else 'No value'}\nj : {j.val if j else 'No value'}\n")
|
|
||||||
if not j:
|
|
||||||
r.next = i
|
|
||||||
i = i.next
|
|
||||||
r = r.next
|
|
||||||
continue
|
|
||||||
if not i:
|
|
||||||
r.next = j
|
|
||||||
j = j.next
|
|
||||||
r = r.next
|
|
||||||
continue
|
|
||||||
if i.val <= j.val:
|
|
||||||
if not r:
|
|
||||||
r = i
|
|
||||||
rf = i
|
|
||||||
else:
|
|
||||||
r.next = i
|
|
||||||
r = r.next
|
|
||||||
i = i.next
|
|
||||||
else:
|
|
||||||
if not r:
|
|
||||||
r = j
|
|
||||||
rf = j
|
|
||||||
else:
|
|
||||||
r.next = j
|
|
||||||
r = r.next
|
|
||||||
j = j.next
|
|
||||||
return rf
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
s = Solution()
|
|
||||||
# l12 = ListNode(val=4, next=None)
|
|
||||||
# l11 = ListNode(val=2, next=l12)
|
|
||||||
# l10 = ListNode(val=1, next=l11)
|
|
||||||
#
|
|
||||||
# l22 = ListNode(val=5, next=None)
|
|
||||||
# l21 = ListNode(val=3, next=l22)
|
|
||||||
# l20 = ListNode(val=1, next=l21)
|
|
||||||
|
|
||||||
l11 = ListNode(val=3, next=None)
|
|
||||||
l10 = ListNode(val=-9, next=l11)
|
|
||||||
|
|
||||||
l21 = ListNode(val=7, next=None)
|
|
||||||
l20 = ListNode(val=5, next=l21)
|
|
||||||
|
|
||||||
k = s.mergeTwoLists(list1=l10, list2=l20)
|
|
||||||
|
|
||||||
while k:
|
|
||||||
print(f"{k.val}")
|
|
||||||
k = k.next
|
|
||||||
|
|
@ -1,49 +0,0 @@
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
|
|
||||||
# Definition for singly-linked list.
|
|
||||||
class ListNode:
|
|
||||||
def __init__(self, val=0, next=None):
|
|
||||||
self.val = val
|
|
||||||
self.next = next
|
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
|
||||||
def mergeTwoLists(self, list1: ListNode, list2: ListNode) -> ListNode:
|
|
||||||
dummy = node = ListNode()
|
|
||||||
|
|
||||||
while list1 and list2:
|
|
||||||
if list1.val < list2.val:
|
|
||||||
node.next = list1
|
|
||||||
list1 = list1.next
|
|
||||||
else:
|
|
||||||
node.next = list2
|
|
||||||
list2 = list2.next
|
|
||||||
node = node.next
|
|
||||||
|
|
||||||
node.next = list1 or list2
|
|
||||||
|
|
||||||
return dummy.next
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
s = Solution()
|
|
||||||
# l12 = ListNode(val=4, next=None)
|
|
||||||
# l11 = ListNode(val=2, next=l12)
|
|
||||||
# l10 = ListNode(val=1, next=l11)
|
|
||||||
#
|
|
||||||
# l22 = ListNode(val=5, next=None)
|
|
||||||
# l21 = ListNode(val=3, next=l22)
|
|
||||||
# l20 = ListNode(val=1, next=l21)
|
|
||||||
|
|
||||||
l11 = ListNode(val=3, next=None)
|
|
||||||
l10 = ListNode(val=-9, next=l11)
|
|
||||||
|
|
||||||
l21 = ListNode(val=7, next=None)
|
|
||||||
l20 = ListNode(val=5, next=l21)
|
|
||||||
|
|
||||||
k = s.mergeTwoLists(list1=l10, list2=l20)
|
|
||||||
|
|
||||||
while k:
|
|
||||||
print(f"{k.val}")
|
|
||||||
k = k.next
|
|
||||||
|
|
@ -1,37 +0,0 @@
|
||||||
# Remove Node From End of Linked List
|
|
||||||
|
|
||||||
You are given the beginning of a linked list head, and an integer n.
|
|
||||||
|
|
||||||
Remove the nth node from the end of the list and return the beginning of the list.
|
|
||||||
|
|
||||||
Example 1:
|
|
||||||
|
|
||||||
Input: head = [1,2,3,4], n = 2
|
|
||||||
|
|
||||||
Output: [1,2,4]
|
|
||||||
Example 2:
|
|
||||||
|
|
||||||
Input: head = [5], n = 1
|
|
||||||
|
|
||||||
Output: []
|
|
||||||
Example 3:
|
|
||||||
|
|
||||||
Input: head = [1,2], n = 2
|
|
||||||
|
|
||||||
Output: [2]
|
|
||||||
Constraints:
|
|
||||||
|
|
||||||
The number of nodes in the list is sz.
|
|
||||||
1 <= sz <= 30
|
|
||||||
0 <= Node.val <= 100
|
|
||||||
1 <= n <= sz
|
|
||||||
|
|
||||||
# Edge cases
|
|
||||||
## size of LL == 1
|
|
||||||
return None
|
|
||||||
|
|
||||||
## n = 1
|
|
||||||
return head.next
|
|
||||||
|
|
||||||
# Solution
|
|
||||||
- Save head and return it after algo
|
|
||||||
|
|
@ -1,43 +0,0 @@
|
||||||
from typing import List, Optional
|
|
||||||
|
|
||||||
|
|
||||||
class ListNode:
|
|
||||||
def __init__(self, val=0, next=None):
|
|
||||||
self.val = val
|
|
||||||
self.next = next
|
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
|
||||||
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
|
|
||||||
if not head:
|
|
||||||
return None
|
|
||||||
if head.next is None:
|
|
||||||
return None
|
|
||||||
perm_head = head
|
|
||||||
nodes = []
|
|
||||||
while head:
|
|
||||||
nodes.append(head)
|
|
||||||
head = head.next
|
|
||||||
if n == 1:
|
|
||||||
nodes[-2].next = None
|
|
||||||
return perm_head
|
|
||||||
if n == len(nodes):
|
|
||||||
return perm_head.next
|
|
||||||
counter = 1
|
|
||||||
for i in range(len(nodes) - 1, 0, -1):
|
|
||||||
if counter == n:
|
|
||||||
nodes[i - 1].next = nodes[i + 1]
|
|
||||||
counter += 1
|
|
||||||
return perm_head
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
s = Solution()
|
|
||||||
e3 = ListNode(3, None)
|
|
||||||
e2 = ListNode(2, e3)
|
|
||||||
e1 = ListNode(1, e2)
|
|
||||||
e0 = ListNode(0, e1)
|
|
||||||
fe = s.removeNthFromEnd(e0, 1)
|
|
||||||
while fe:
|
|
||||||
print(f"{fe.val}")
|
|
||||||
fe = fe.next
|
|
||||||
|
|
@ -1,40 +0,0 @@
|
||||||
from typing import List, Optional
|
|
||||||
|
|
||||||
|
|
||||||
class ListNode:
|
|
||||||
def __init__(self, val=0, next=None):
|
|
||||||
self.val = val
|
|
||||||
self.next = next
|
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
|
||||||
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
|
|
||||||
N = 0
|
|
||||||
cur = head
|
|
||||||
while cur:
|
|
||||||
N += 1
|
|
||||||
cur = cur.next
|
|
||||||
|
|
||||||
removeIndex = N - n
|
|
||||||
if removeIndex == 0:
|
|
||||||
return head.next
|
|
||||||
|
|
||||||
cur = head
|
|
||||||
for i in range(N - 1):
|
|
||||||
if (i + 1) == removeIndex:
|
|
||||||
cur.next = cur.next.next
|
|
||||||
break
|
|
||||||
cur = cur.next
|
|
||||||
return head
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
s = Solution()
|
|
||||||
e3 = ListNode(3, None)
|
|
||||||
e2 = ListNode(2, e3)
|
|
||||||
e1 = ListNode(1, e2)
|
|
||||||
e0 = ListNode(0, e1)
|
|
||||||
fe = s.removeNthFromEnd(e0, 1)
|
|
||||||
while fe:
|
|
||||||
print(f"{fe.val}")
|
|
||||||
fe = fe.next
|
|
||||||
|
|
@ -1,38 +0,0 @@
|
||||||
Reorder Linked List
|
|
||||||
You are given the head of a singly linked-list.
|
|
||||||
|
|
||||||
The positions of a linked list of length = 7 for example, can intially be represented as:
|
|
||||||
|
|
||||||
[0, 1, 2, 3, 4, 5, 6]
|
|
||||||
|
|
||||||
Reorder the nodes of the linked list to be in the following order:
|
|
||||||
|
|
||||||
[0, 6, 1, 5, 2, 4, 3]
|
|
||||||
|
|
||||||
Notice that in the general case for a list of length = n the nodes are reordered to be in the following order:
|
|
||||||
|
|
||||||
[0, n-1, 1, n-2, 2, n-3, ...]
|
|
||||||
|
|
||||||
You may not modify the values in the list's nodes, but instead you must reorder the nodes themselves.
|
|
||||||
|
|
||||||
Example 1:
|
|
||||||
|
|
||||||
Input: head = [2,4,6,8]
|
|
||||||
|
|
||||||
Output: [2,8,4,6]
|
|
||||||
Example 2:
|
|
||||||
|
|
||||||
Input: head = [2,4,6,8,10]
|
|
||||||
|
|
||||||
Output: [2,10,4,8,6]
|
|
||||||
Constraints:
|
|
||||||
|
|
||||||
1 <= Length of the list <= 1000.
|
|
||||||
1 <= Node.val <= 1000
|
|
||||||
|
|
||||||
# Solution
|
|
||||||
|
|
||||||
input = [0, 1, 2, 3, 4, 5, 6]
|
|
||||||
index = 0
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -1,43 +0,0 @@
|
||||||
from typing import List, Optional
|
|
||||||
|
|
||||||
|
|
||||||
class ListNode:
|
|
||||||
def __init__(self, val=0, next=None):
|
|
||||||
self.val = val
|
|
||||||
self.next = next
|
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
|
||||||
def reorderList(self, head: Optional[ListNode]) -> None:
|
|
||||||
nodes: List[ListNode] = []
|
|
||||||
sorted_nodes: List[ListNode] = []
|
|
||||||
while head:
|
|
||||||
nodes.append(head)
|
|
||||||
head = head.next
|
|
||||||
right = len(nodes) - 1
|
|
||||||
left = 0
|
|
||||||
counter = 0
|
|
||||||
while left <= right:
|
|
||||||
if counter % 2 == 0:
|
|
||||||
sorted_nodes.append(nodes[left])
|
|
||||||
left += 1
|
|
||||||
else:
|
|
||||||
sorted_nodes.append(nodes[right])
|
|
||||||
right -= 1
|
|
||||||
counter += 1
|
|
||||||
for sni in range(0, len(sorted_nodes) - 1):
|
|
||||||
sorted_nodes[sni].next = sorted_nodes[sni + 1]
|
|
||||||
sorted_nodes[-1].next = None
|
|
||||||
return sorted_nodes[0]
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
s = Solution()
|
|
||||||
e3 = ListNode(8, None)
|
|
||||||
e2 = ListNode(6, e3)
|
|
||||||
e1 = ListNode(4, e2)
|
|
||||||
e0 = ListNode(2, e1)
|
|
||||||
fe = s.reorderList(e0)
|
|
||||||
while fe:
|
|
||||||
print(f"{fe.val}")
|
|
||||||
fe = fe.next
|
|
||||||
|
|
@ -1,68 +0,0 @@
|
||||||
# Task
|
|
||||||
Reverse Linked List
|
|
||||||
Given the beginning of a singly linked list head, reverse the list, and return the new beginning of the list.
|
|
||||||
|
|
||||||
Example 1:
|
|
||||||
|
|
||||||
Input: head = [0,1,2,3]
|
|
||||||
|
|
||||||
Output: [3,2,1,0]
|
|
||||||
Example 2:
|
|
||||||
|
|
||||||
Input: head = []
|
|
||||||
|
|
||||||
Output: []
|
|
||||||
Constraints:
|
|
||||||
|
|
||||||
0 <= The length of the list <= 1000.
|
|
||||||
-1000 <= Node.val <= 1000
|
|
||||||
|
|
||||||
# Solution
|
|
||||||
## 0
|
|
||||||
ll = [0, 1, 2, 3]
|
|
||||||
p = None
|
|
||||||
c = 0
|
|
||||||
n = 1
|
|
||||||
|
|
||||||
## 1
|
|
||||||
p
|
|
||||||
c
|
|
||||||
n
|
|
||||||
[0, 1, 2, 3]
|
|
||||||
|
|
||||||
```
|
|
||||||
if p == c
|
|
||||||
p.next = None
|
|
||||||
c = n
|
|
||||||
n = c.next
|
|
||||||
```
|
|
||||||
|
|
||||||
## 2
|
|
||||||
p
|
|
||||||
c
|
|
||||||
n
|
|
||||||
[0, 1, 2, 3]
|
|
||||||
```
|
|
||||||
c.next = p
|
|
||||||
p = c
|
|
||||||
c = n
|
|
||||||
n = c.next
|
|
||||||
```
|
|
||||||
|
|
||||||
## 3
|
|
||||||
p
|
|
||||||
c
|
|
||||||
n
|
|
||||||
[0, 1, 2, 3]
|
|
||||||
```
|
|
||||||
c.next = p
|
|
||||||
p = c
|
|
||||||
c = n
|
|
||||||
n = c.next
|
|
||||||
```
|
|
||||||
## 4
|
|
||||||
p
|
|
||||||
c
|
|
||||||
n = None
|
|
||||||
[0, 1, 2, 3]
|
|
||||||
|
|
||||||
|
|
@ -1,46 +0,0 @@
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
|
|
||||||
# Definition for singly-linked list.
|
|
||||||
class ListNode:
|
|
||||||
def __init__(self, val=0, next=None):
|
|
||||||
self.val = val
|
|
||||||
self.next = next
|
|
||||||
|
|
||||||
|
|
||||||
class Solution:
|
|
||||||
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
|
|
||||||
if not head:
|
|
||||||
return None
|
|
||||||
if head.next is None:
|
|
||||||
return head
|
|
||||||
p = head
|
|
||||||
c = head
|
|
||||||
n = head.next
|
|
||||||
while True:
|
|
||||||
if p == c:
|
|
||||||
p.next = None
|
|
||||||
c = n
|
|
||||||
n = c.next
|
|
||||||
if c.next is None:
|
|
||||||
c.next = p
|
|
||||||
break
|
|
||||||
else:
|
|
||||||
c.next = p
|
|
||||||
p = c
|
|
||||||
c = n
|
|
||||||
n = c.next
|
|
||||||
return c
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
s = Solution()
|
|
||||||
e3 = ListNode(3, None)
|
|
||||||
e2 = ListNode(2, e3)
|
|
||||||
e1 = ListNode(1, e2)
|
|
||||||
e0 = ListNode(0, e1)
|
|
||||||
k = [e0, e1, e2, e3]
|
|
||||||
nb = s.reverseList(e0)
|
|
||||||
for index, elem in enumerate(k):
|
|
||||||
next_val = elem.next.val if elem.next else "No value"
|
|
||||||
print(f"{index} - v: {elem.val} - vn: {next_val}")
|
|
||||||
|
|
@ -1,26 +0,0 @@
|
||||||
You are given an integer n representing the number of steps to reach the top of a staircase. You can climb with either 1 or 2 steps at a time.
|
|
||||||
|
|
||||||
Return the number of distinct ways to climb to the top of the staircase.
|
|
||||||
|
|
||||||
Example 1:
|
|
||||||
|
|
||||||
Input: n = 2
|
|
||||||
|
|
||||||
Output: 2
|
|
||||||
Explanation:
|
|
||||||
|
|
||||||
1 + 1 = 2
|
|
||||||
2 = 2
|
|
||||||
Example 2:
|
|
||||||
|
|
||||||
Input: n = 3
|
|
||||||
|
|
||||||
Output: 3
|
|
||||||
Explanation:
|
|
||||||
|
|
||||||
1 + 1 + 1 = 3
|
|
||||||
1 + 2 = 3
|
|
||||||
2 + 1 = 3
|
|
||||||
Constraints:
|
|
||||||
|
|
||||||
1 <= n <= 30
|
|
||||||
|
|
@ -1,14 +0,0 @@
|
||||||
class Solution:
|
|
||||||
def climbStairs(self, n: int) -> int:
|
|
||||||
if n == 0:
|
|
||||||
return 1
|
|
||||||
if n < 0:
|
|
||||||
return 0
|
|
||||||
return self.climbStairs(n - 1) + self.climbStairs(n - 2)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
s = Solution()
|
|
||||||
print(s.climbStairs(5))
|
|
||||||
print(s.climbStairs(30))
|
|
||||||
print(s.climbStairs(1))
|
|
||||||
Loading…
Reference in a new issue