Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return an integer
def maxDepth(self, root):
if root == None: return 0
return max(Solution().maxDepth(root.left), Solution().maxDepth(root.right)) + 1
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
class Solution:
def minDepth(self, root):
if root == None: return 0
if root.left == None and root.right == None:
return 1
ans = -1
if root.left != None:
ans = Solution().minDepth(root.left)
if root.right != None:
tmp = Solution().minDepth(root.right)
if ans == -1:
ans = tmp
else:
ans = min(ans, tmp)
if ans == -1: ans = 0
return ans + 1
Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.
class Solution:
# @param num1, a string
# @param num2, a string
# @return a string
def multiply(self, num1, num2):
return str(int(num1)*int(num2))
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18]
,
return [1,6],[8,10],[15,18]
.
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {
public:
vector<Interval> merge(vector<Interval> &intervals) {
vector<Interval> res;
vector<pair<int, int> > vec;
const int m = intervals.size();
if (m == 0) return res;
for (int i = 0; i < m; ++i) {
int s = intervals[i].start, e = intervals[i].end;
vec.push_back(make_pair(s, 0));
vec.push_back(make_pair(e, 1));
}
sort(vec.begin(), vec.end());
int cnt = 1, s = vec[0].first, e;
const int n = vec.size();
for (int i = 1; i < n; ++i) {
if (vec[i].second == 0)
++cnt;
else
--cnt;
if (cnt == 0) {
e = vec[i].first;
res.push_back(Interval(s, e));
++i;
if (i >= n) break;
s = vec[i].first;
cnt = 1;
}
}
return res;
}
};
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m andn respectively.
class Solution:
# @param A a list of integers
# @param m an integer, length of A
# @param B a list of integers
# @param n an integer, length of B
# @return nothing
def merge(self, A, m, B, n):
k = m + n - 1
i = m - 1
j = n - 1
while k >= 0:
if i < 0 or j < 0: break
if A[i] > B[j]:
A[k] = A[i]
i = i - 1
else:
A[k] = B[j]
j = j - 1
k = k - 1
while i >= 0:
A[k] = A[i]
k = k - 1
i = i - 1
while j >= 0:
A[k] = B[j]
k = k - 1
j = j - 1
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param two ListNodes
# @return a ListNode
def mergeTwoLists(self, l1, l2):
if l1 == None: return l2
if l2 == None: return l1
if l1.val < l2.val:
head = l1
l1 = l1.next
else:
head = l2
l2 = l2.next
p = head
while l1 != None and l2 != None:
if l1.val < l2.val:
p.next = l1
l1 = l1.next
else:
p.next = l2
l2 = l2.next
p = p.next
if l1 != None: p.next = l1
if l2 != None: p.next = l2
return head
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
typedef pair<int, int> pii;
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
priority_queue<pii, vector<pii>, greater<pii>> q;
const int n = lists.size();
vector<ListNode*> pointers(n, reinterpret_cast<ListNode*>(NULL));
for (int i = 0; i < n; ++i) {
if (lists[i] != NULL) q.push(make_pair(lists[i]->val, i));
pointers[i] = lists[i];
}
ListNode *head = NULL;
ListNode *p = head;
while (!q.empty()) {
const int i = q.top().second;
q.pop();
if (p == NULL)
head = p = pointers[i];
else {
p->next = pointers[i];
p = p->next;
}
pointers[i] = pointers[i]->next;
if (pointers[i] != NULL) q.push(make_pair(pointers[i]->val, i));
}
return head;
}
};
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
class Solution:
# @param grid, a list of lists of integers
# @return an integer
def minPathSum(self, grid):
m = len(grid)
n = len(grid[0])
for i in range(n-1):
grid[0][i+1] = grid[0][i] + grid[0][i+1]
for i in range(m-1):
grid[i+1][0] = grid[i][0] + grid[i+1][0]
for i in range(m-1):
for j in range(n-1):
grid[i+1][j+1] += min(grid[i][j+1], grid[i+1][j])
return grid[m-1][n-1]
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4]
,
the contiguous subarray [4,−1,2,1]
has the largest sum = 6
.
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
class Solution:
def maxSubArray(self, A):
cur = 0
ans = A[0]
l = len(A)
for j in range(l):
cur += A[j]
ans = max(ans, cur)
if cur < 0: cur = 0
return ans
Maximal Rectangle Total Accepted: 10411 Total Submissions: 48083 My Submissions
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
class Solution {
int maximalRectangleInHistogram(vector<int> &histogram) {
stack<pair<int, int> > buffer;
const int n = histogram.size();
int ans = 0;
buffer.push(make_pair(histogram[0], 1));
for (int i = 1; i < n; ++i) {
if (histogram[i] > buffer.top().first) {
buffer.push(make_pair(histogram[i], 1));
}
else if (histogram[i] == buffer.top().first) {
int cnt = buffer.top().second;
buffer.pop();
buffer.push(make_pair(histogram[i], cnt + 1));
}
else {
int cnt = 0;
while (buffer.size() > 0) {
if (buffer.top().first < histogram[i]) break;
cnt += buffer.top().second;
ans = max(ans, buffer.top().first * cnt);
buffer.pop();
}
buffer.push(make_pair(histogram[i], cnt + 1));
}
}
while (buffer.size() > 0) {
ans = max(ans, buffer.top().first * buffer.top().second);
int cnt = buffer.top().second;
buffer.pop();
if (buffer.size() > 0) {
pair<int, int> tmp = buffer.top();
buffer.pop();
buffer.push(make_pair(tmp.first, tmp.second + cnt));
}
}
return ans;
}
public:
int maximalRectangle(vector<vector<char> > &matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0) return 0;
const int r = matrix.size(), c = matrix[0].size();
vector<int> histogram(c, 0);
int ans = 0;
for (int i = 0; i < r; ++i) {
for (int j = 0; j < c; ++j) {
if (matrix[i][j] == '1')
++histogram[j];
else
histogram[j] = 0;
}
ans = max(ans, maximalRectangleInHistogram(histogram));
}
return ans;
}
};