Skip to content

Commit 228c4f8

Browse files
committed
Adding solution of top interview question of id between 200-300
1 parent 6321dbb commit 228c4f8

File tree

17 files changed

+704
-0
lines changed

17 files changed

+704
-0
lines changed

1-100q/4.py

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
'''
2+
There are two sorted arrays nums1 and nums2 of size m and n respectively.
3+
4+
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
5+
6+
Example 1:
7+
nums1 = [1, 3]
8+
nums2 = [2]
9+
10+
The median is 2.0
11+
Example 2:
12+
nums1 = [1, 2]
13+
nums2 = [3, 4]
14+
15+
The median is (2 + 3)/2 = 2.5
16+
'''
17+
18+
class Solution(object):
19+
def findMedianSortedArrays(self, nums1, nums2):
20+
"""
21+
:type nums1: List[int]
22+
:type nums2: List[int]
23+
:rtype: float
24+
"""
25+
26+
if len(nums1) > len(nums2):
27+
nums1, nums2 = nums2, nums1
28+
29+
x, y = len(nums1), len(nums2)
30+
low , high = 0, x
31+
32+
while low <= high:
33+
partitionx = (low+high)/2
34+
partitiony = (x+y+1)/2 - partitionx
35+
if partitionx == 0:
36+
maxLeftX = float('-inf')
37+
else:
38+
maxLeftX = nums1[partitionx-1]
39+
40+
if partitionx == x:
41+
minRightX = float('inf')
42+
else:
43+
minRightX = nums1[partitionx]
44+
45+
if partitiony == 0:
46+
maxLeftY = float('-inf')
47+
else:
48+
maxLeftY = nums2[partitiony-1]
49+
50+
if partitiony == y:
51+
minRightY = float('inf')
52+
else:
53+
minRightY = nums2[partitiony]
54+
55+
if maxLeftX <= minRightY and maxLeftY <= minRightX:
56+
if((x+y)%2 == 0):
57+
return (max(maxLeftX, maxLeftY) + min(minRightX, minRightY))/2.0
58+
else:
59+
return max(maxLeftY, maxLeftX)
60+
elif maxLeftX > minRightY:
61+
high = partitionx - 1
62+
else:
63+
low = partitionx + 1
64+
65+
66+
print Solution().findMedianSortedArrays([1,2], [3, 4])

200-300q/279.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
'''
2+
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
3+
4+
Example 1:
5+
6+
Input: n = 12
7+
Output: 3
8+
Explanation: 12 = 4 + 4 + 4.
9+
Example 2:
10+
11+
Input: n = 13
12+
Output: 2
13+
Explanation: 13 = 4 + 9.
14+
'''
15+
16+
class Solution(object):
17+
def numSquares(self, n):
18+
"""
19+
:type n: int
20+
:rtype: int
21+
"""
22+
mapping = {}
23+
squares = [num*num for num in range(1, int(pow(n, 0.5)) + 1)]
24+
for square in squares:
25+
mapping[square] = 1
26+
27+
for val in range(1, n+1):
28+
if val not in mapping:
29+
mapping[val] = float('inf')
30+
for square in squares:
31+
if square < val:
32+
mapping[val] = min(mapping[val], mapping[square] + mapping[val-square])
33+
return mapping[n]

200-300q/287.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
'''
2+
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
3+
4+
Example 1:
5+
6+
Input: [1,3,4,2,2]
7+
Output: 2
8+
Example 2:
9+
10+
Input: [3,1,3,4,2]
11+
Output: 3
12+
'''
13+
14+
class Solution(object):
15+
def findDuplicate(self, nums):
16+
"""
17+
:type nums: List[int]
18+
:rtype: int
19+
"""
20+
slow, fast = nums[0], nums[0]
21+
while True:
22+
slow = nums[slow]
23+
fast = nums[nums[fast]]
24+
if slow == fast:
25+
break
26+
27+
num1= nums[0]
28+
num2 = slow
29+
while num1 != num2:
30+
num1 = nums[num1]
31+
num2 = nums[num2]
32+
return num2

200-300q/289.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution(object):
2+
def gameOfLife(self, board):
3+
"""
4+
:type board: List[List[int]]
5+
:rtype: void Do not return anything, modify board in-place instead.
6+
"""
7+
index = []
8+
9+
def around(i, j, board):
10+
count = 0
11+
for k in range(i-1, i+2):
12+
for l in range(j-1, j+2):
13+
if 0<=k < len(board) and 0 <= l < len(board[0]):
14+
if board[k][l] == 1:
15+
count += 1
16+
17+
return count-1 if board[i][j] == 1 else count
18+
19+
for i in range(len(board)):
20+
for j in range(len(board[0])):
21+
count = around(i, j, board)
22+
if board[i][j] == 1:
23+
if count > 3 or count < 2:
24+
index.append([i, j, 0])
25+
else:
26+
if count == 3:
27+
index.append([i, j, 1])
28+
29+
while index:
30+
i, j, value = index.pop()
31+
board[i][j] =value
32+
33+

200-300q/295.py

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
'''
2+
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
3+
4+
Examples:
5+
[2,3,4] , the median is 3
6+
7+
[2,3], the median is (2 + 3) / 2 = 2.5
8+
9+
Design a data structure that supports the following two operations:
10+
11+
void addNum(int num) - Add a integer number from the data stream to the data structure.
12+
double findMedian() - Return the median of all elements so far.
13+
For example:
14+
15+
addNum(1)
16+
addNum(2)
17+
findMedian() -> 1.5
18+
addNum(3)
19+
findMedian() -> 2
20+
'''
21+
import heapq
22+
class MedianFinder(object):
23+
24+
def __init__(self):
25+
"""
26+
initialize your data structure here.
27+
"""
28+
self.max_heap = []
29+
self.min_heap = []
30+
31+
32+
def addNum(self, num):
33+
"""
34+
:type num: int
35+
:rtype: void
36+
"""
37+
if not self.max_heap or num > -self.max_heap[0]:
38+
heapq.heappush(self.min_heap, num)
39+
40+
if len(self.min_heap) > len(self.max_heap) + 1:
41+
heapq.heappush(self.max_heap, -heapq.heapop(self.min_heap))
42+
else:
43+
heapq.heappush(self.max_heap, -num)
44+
if len(self.max_heap) > len(self.min_heap):
45+
heapq.heappush(self.min_heap, -heapq.heapop(self.max_heap))
46+
47+
def findMedian(self):
48+
"""
49+
:rtype: float
50+
"""
51+
print self.max_heap, self.min_heap
52+
if len(self.max_heap) == len(self.min_heap):
53+
return (-self.max_heap[0]+self.min_heap[0] )/2.0
54+
else:
55+
return self.min_heap[0]
56+
57+
58+
59+
# Your MedianFinder object will be instantiated and called as such:
60+
# obj = MedianFinder()
61+
# obj.addNum(num)
62+
# param_2 = obj.findMedian()

200-300q/300.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
'''
2+
Given an unsorted array of integers, find the length of longest increasing subsequence.
3+
4+
For example,
5+
Given [10, 9, 2, 5, 3, 7, 101, 18],
6+
The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.
7+
8+
Your algorithm should run in O(n2) complexity.
9+
10+
Follow up: Could you improve it to O(n log n) time complexity?
11+
'''
12+
13+
class Solution(object):
14+
def lengthOfLIS(self, nums):
15+
"""
16+
:type nums: List[int]
17+
:rtype: int
18+
"""
19+
20+
if len(nums) <= 1:
21+
return len(nums)
22+
23+
count = [0 for _ in range(len(nums))]
24+
result = 1
25+
count[0] = nums[0]
26+
27+
for index in range(1, len(nums)):
28+
if nums[index] < count[0]:
29+
count[0] = nums[index]
30+
elif nums[index] > count[result-1]:
31+
count[result] = nums[index]
32+
result += 1
33+
else:
34+
left, right = -1, result-1
35+
while (right-left > 1):
36+
mid = (left+right)/2
37+
if count[mid] >= nums[index]:
38+
right = mid
39+
else:
40+
left = mid
41+
count[right] = nums[index]
42+
43+
return result

300-400q/315.py

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
'''
2+
You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].
3+
4+
Example:
5+
6+
Given nums = [5, 2, 6, 1]
7+
8+
To the right of 5 there are 2 smaller elements (2 and 1).
9+
To the right of 2 there is only 1 smaller element (1).
10+
To the right of 6 there is 1 smaller element (1).
11+
To the right of 1 there is 0 smaller element.
12+
Return the array [2, 1, 1, 0].
13+
'''
14+
15+
class TreeNode(object):
16+
def __init__(self, val):
17+
self.right = None
18+
self.left = None
19+
self.val = val
20+
self.count = 1
21+
22+
class Solution(object):
23+
def countSmaller(self, nums):
24+
"""
25+
:type nums: List[int]
26+
:rtype: List[int]
27+
"""
28+
if len(nums) == 0:
29+
return []
30+
31+
node = TreeNode(nums[len(nums)-1])
32+
result = [0]
33+
for index in range(len(nums)-2, -1, -1):
34+
result.append(self.insertNode(node, nums[index]))
35+
36+
return result[::-1]
37+
38+
def insertNode(self, node, val):
39+
totalCount = 0
40+
while True:
41+
if val <= node.val:
42+
node.count += 1
43+
if node.left is None:
44+
node.left = TreeNode(val)
45+
break
46+
else:
47+
node = node.left
48+
else:
49+
totalCount += node.count
50+
if node.right is None:
51+
node.right = TreeNode(val)
52+
break
53+
else:
54+
node = node.right
55+
56+
return totalCount
57+

300-400q/322.py

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
'''
2+
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
3+
4+
Example 1:
5+
coins = [1, 2, 5], amount = 11
6+
return 3 (11 = 5 + 5 + 1)
7+
8+
Example 2:
9+
coins = [2], amount = 3
10+
return -1.
11+
'''
12+
13+
class Solution(object):
14+
def coinChange(self, coins, amount):
15+
"""
16+
:type coins: List[int]
17+
:type amount: int
18+
:rtype: int
19+
"""
20+
if not coins:
21+
return 0
22+
23+
dp = [float('inf') for _ in range(amount+1)]
24+
dp[0] = 0
25+
26+
for val in range(1, amount+1):
27+
for coin in coins:
28+
if coin <= val:
29+
dp[val] = min(dp[val-coin]+1, dp[val])
30+
return dp[amount] if dp[amount] != float('inf') else -1

300-400q/326.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
'''
2+
Given an integer, write a function to determine if it is a power of three.
3+
4+
Follow up:
5+
Could you do it without using any loop / recursion?
6+
'''
7+
8+
class Solution(object):
9+
def isPowerOfThree(self, n):
10+
"""
11+
:type n: int
12+
:rtype: bool
13+
"""
14+
if n <= 0:
15+
return False
16+
17+
import math
18+
return (math.log10(n)/math.log10(3))%1 == 0

0 commit comments

Comments
 (0)