Hypercube's LeetCode Weekly Contest 44

  • Rank: 145 / 2272
  • Score: 19 / 24
  • Finish Time: 00:59:01

Two Sum IV - Input is a BST

Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.

Example 1:

Input:
    5
   / \
  3   6
 / \   \
2   4   7
Target = 9
Output: True

Example 2:

Input:
    5
   / \
  3   6
 / \   \
2   4   7
Target = 28
Output: False
Accepted in 00:09:04 with 1 wrong submissions
def add(s, r):
    if r:
        s.add(r.val)
        add(s, r.left)
        add(s, r.right)
class Solution:
    def findTarget(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: bool
        """
        s = set()
        add(s, root)
        for i in s:
            if (k-i) in s and i+i != k:
                return True
        return False

Maximum Binary Tree

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:

  1. The root is the maximum number in the array.
  2. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
  3. The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.

Construct the maximum tree by the given array and output the root node of this tree.

Example 1:

Input: [3, 2, 1, 6, 0, 5]
Output: return the tree root node representing the following tree:
   6
 /   \
3     5
 \   /
  2 0
   \
    1

Note:

  1. The size of the given array will be in the range [1, 1000].
Wrong Answer

Print a binary tree in an m*n 2D string array following these rules:

  1. The row number m should be equal to the height of the given binary tree.
  2. The column number n should always be an odd number.
  3. The root node’s value (in string format) should be put in the exactly middle of the first row it can be put. The column and the row where the root node belongs will separate the rest space into two parts (left-bottom part and right-bottom part). You should print the left subtree in the left-bottom part and print the right subtree in the right-bottom part. The left-bottom part and the right-bottom part should have the same size. Even if one subtree is none while the other is not, you don’t need to print anything for the none subtree but still need to leave the space as large as that for the other subtree. However, if two subtrees are none, then you don’t need to leave space for both of them.
  4. Each unused space should contain an empty string "".
  5. Print the subtrees following the same rules.

Example 1:

Input:
  1
 /
2
Output:
[["", "1", ""],
 ["2", "", ""]]

Example 2:

Input:
  1
 / \
2   3
 \
  4
Output:
[["", "", "", "1", "", "", ""],
 ["", "2", "", "", "", "3", ""],
 ["", "", "4", "", "", "", ""]]

Example 3:

Input:
      1
     / \
    2   5
   /
  3
 /
4
Output:

[["",  "",  "", "",  "", "", "", "1", "",  "",  "",  "",  "", "", ""]
 ["",  "",  "", "2", "", "", "", "",  "",  "",  "",  "5", "", "", ""]
 ["",  "3", "", "",  "", "", "", "",  "",  "",  "",  "",  "", "", ""]
 ["4", "",  "", "",  "", "", "", "",  "",  "",  "",  "",  "", "", ""]]

Note: The height of binary tree is in the range of [1, 10].

Accepted in 00:30:37
def height(r, n=0):
    if r:
        return max(height(r.left,n+1), height(r.right,n+1))
    return n

def draw(buf, r, top, left, right):
    if r is None:
        return
    mid = (left+right)//2
    buf[top][mid] = str(r.val)
    draw(buf, r.left, top+1, left, mid-1)
    draw(buf, r.right, top+1, mid+1, right)

class Solution:
    def printTree(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[str]]
        """
        h = height(root)
        buffer = []
        for i in range(h):
            buffer.append([''] * (2 ** h - 1))
        draw(buffer, root, 0, 0, 2**h-2)
        return buffer

Coin Path

Given an array A (index starts at 1) consisting of N integers: A1, A2, …, AN and an integer B. The integer B denotes that from any place (suppose the index is i) in the array A, you can jump to any one of the place in the array A indexed i+1, i+2, …, i+B if this place can be jumped to. Also, if you step on the index i, you have to pay Ai coins. If Ai is -1, it means you can’t jump to the place indexed i in the array.

Now, you start from the place indexed 1 in the array A, and your aim is to reach the place indexed N using the minimum coins. You need to return the path of indexes (starting from 1 to N) in the array you should take to get to the place indexed N using minimum coins.

If there are multiple paths with the same cost, return the lexicographically smallest such path.

If it’s not possible to reach the place indexed N then you need to return an empty array.

Example 1:

Input: [1, 2, 4, -1, 2], 2
Output: [1, 3, 5]

Example 2:

Input: [1, 2, 4, -1, 2], 1
Output: []

Note:

  1. Path Pa1, Pa2, …, Pan is lexicographically smaller than Pb1, Pb2, …, Pbm, if and only if at the first i where Pai and Pbi differ, Pai < Pbi; when no such i exists, then n < m.
  2. A1 >= 0. A2, …, AN (if exist) will in the range of [-1, 100].
  3. Length of A is in the range of [1, 1000].
  4. B is in the range of [1, 100].
Accepted in 00:49:01 with 1 wrong submissions
class Solution:
    def cheapestJump(self, A, B):
        """
        :type A: List[int]
        :type B: int
        :rtype: List[int]
        """
        cost = [-1] * len(A) + [0] + [-1] * (B-1)
        path = [()] * len(A) + [()] *B
        for i in range(len(A)):
            if A[i] == -1:
                cost[i] = -1
            else:
                try:
                    c, p = min(((cost[i-j], path[i-j]+(i,)) for j in range(1, B+1) if cost[i-j] != -1))
                    cost[i] = c+A[i]
                    path[i] = p
                except ValueError:
                    cost[i] = -1
                    path[i] = ()
        return [i+1 for i in path[len(A)-1]]