Convert BST to Greater Tree

Convert BST to Greater Tree

Recursive Version - 88ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.lSum = 0
def convertBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return None
self.convertBST(root.right)
self.lSum += root.val
root.val = self.lSum
self.convertBST(root.left)
return root

leet code

Find All Numbers Disappeared in an Array

Find All Numbers Disappeared in an Array

One line Version - 152ms

1
2
3
4
5
6
7
class Solution:
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
return list(set(range(1, len(nums) + 1)) - set(nums))

Without Extra Space Version - 224ms

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
for i in range(len(nums)):
idx = abs(nums[i]) - 1
nums[idx] = - abs(nums[idx])
#print(i, idx, nums)
return [i + 1 for i in range(len(nums)) if nums[i] > 0]

test code

1
2
In [31]: s = Solution(); t = s.findDisappearedNumbers([4,3,2,7,8,2,3,1]); print(t)
[5, 6]

leet code

Palindromic Substrings

Palindromic Substrings

One line Version - 924ms

1
2
3
4
5
6
7
class Solution:
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
return sum(s[i:j] == s[i:j][::-1] for j in range(len(s) + 1) for i in range(j))

O(n) Version - 128ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def countSubstrings(self, S):
"""
:type s: str
:rtype: int
"""
N = len(S)
ans = 0
for center in range(2*N - 1):
left = center // 2
right = left + center % 2
while left >= 0 and right < N and S[left] == S[right]:
ans += 1
left -= 1
right += 1
return ans

test code

1
2
In [25]: s = Solution(); t = s.countSubstrings('abc'); print(t)
3

leet code

Queue Reconstruction by Height

Queue Reconstruction by Height

Sort Insert Version - 84ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution(object):
def reconstructQueue(self, people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
if not people:
return []
n = len(people)
people_sorted = sorted(people, key = lambda x: (-x[0],x[1]))
res = [people_sorted[0]]
for i in range(1,n):
hi, ki = people_sorted[i]
res.insert(ki, people_sorted[i])
return res

test code

1
2
3
4
In [161]: people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]
In [162]: s = Solution(); t = s.reconstructQueue(people); print(t)
[[5, 0], [7, 0], [5, 2], [6, 1], [4, 4], [7, 1]]

leet code

Counting Bits

Counting Bits

Bitwise Operator Version - 108ms

1
2
3
4
5
6
7
8
9
10
class Solution:
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
res = [0]
for i in range(1, num + 1):
res.append(res[i >> 1] + (i & 1))
return res

test code

1
2
In [147]: s = Solution(); t = s.countBits(5); print(t)
[0, 1, 1, 2, 1, 2]

leet code