Hypercube's LeetCode Weekly Contest 53

  • Rank: 334 / 2932
  • Score: 15 / 24
  • Finish Time: 00:55:20

Binary Number with Alternating Bits

Given a positive integer, check whether it has alternating bits or not.

Example 1:

Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101

Example 2:

Input: 7
Output: False
Explanation:
The binary representation of 7 is: 111
Accepted in 00:07:48 with 1 wrong submissions
class Solution:
    def hasAlternatingBits(self, n):
        """
        :type n: int
        :rtype: bool
        """
        s = bin(n)[2:]
        for i in range(len(s) - 1):
            if s[i] == s[i+1]:
                return False
        return True

Max Area of Island

Given a non-empty 2D array grid of 0’s and 1’s, an island is a group of 1’s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

Example 1:

[[0,0,1,0,0,0,0,1,0,0,0,0,0],
 [0,0,0,0,0,0,0,1,1,1,0,0,0],
 [0,1,1,0,1,0,0,0,0,0,0,0,0],
 [0,1,0,0,1,1,0,0,1,0,1,0,0],
 [0,1,0,0,1,1,0,0,1,1,1,0,0],
 [0,0,0,0,0,0,0,0,0,0,1,0,0],
 [0,0,0,0,0,0,0,1,1,1,0,0,0],
 [0,0,0,0,0,0,0,1,1,0,0,0,0]]

Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.

Example 2:

[[0,0,0,0,0,0,0,0]]

Given the above grid, return 0.

Note: The length of each dimension in the given grid does not exceed 50.

Accepted in 00:45:20
class Solution:
    def maxAreaOfIsland(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        islands = {}
        mapping = {}
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if not grid[i][j]:
                    continue
                if i and grid[i-1][j]:
                    islandx, islandy = mapping[i-1, j]
                    mapping[i, j] = islandx, islandy
                    islands[islandx, islandy].add((i-islandx, j-islandy))
                    if j and grid[i][j-1] and mapping[i, j-1] != mapping[i, j]:
                        # join the left side
                        leftx, lefty = mapping[i, j-1]
                        s = islands[islandx, islandy]
                        for (dx, dy) in islands[leftx, lefty]:
                            mapping[leftx+dx, lefty+dy] = islandx, islandy
                            s.add((leftx+dx-islandx, lefty+dy-islandy))
                        del islands[leftx, lefty]
                    continue
                if j and grid[i][j-1]:
                    islandx, islandy = mapping[i, j-1]
                    mapping[i, j] = islandx, islandy
                    islands[islandx, islandy].add((i-islandx, j-islandy))
                    continue
                mapping[i, j] = i, j
                islands[i, j] = {(0, 0)}
        sizes = {len(islands[k]) for k in islands}
        sizes.add(0)
        return max(sizes)

Number of Distinct Islands

Given a non-empty 2D array grid of 0’s and 1’s, an island is a group of 1’s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

Count the number of distinct islands. An island is considered to be the same as another if and only if one island can be translated (and not rotated or reflected) to equal the other.

Example 1:

11000
11000
00011
00011

Given the above grid map, return 1.

Example 2:

11011
10000
00001
11011

Given the above grid map, return 3.

Notice that: 11 1 and 1 11 are considered different island shapes, because we do not consider reflection / rotation.

Note: The length of each dimension in the given grid does not exceed 50.

Accepted in 00:43:35 with 1 wrong submissions
class Solution:
    def numDistinctIslands(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        islands = {}
        mapping = {}
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if not grid[i][j]:
                    continue
                if i and grid[i-1][j]:
                    islandx, islandy = mapping[i-1, j]
                    mapping[i, j] = islandx, islandy
                    islands[islandx, islandy].add((i-islandx, j-islandy))
                    if j and grid[i][j-1] and mapping[i, j-1] != mapping[i, j]:
                        # join the left side
                        leftx, lefty = mapping[i, j-1]
                        s = islands[islandx, islandy]
                        for (dx, dy) in islands[leftx, lefty]:
                            mapping[leftx+dx, lefty+dy] = islandx, islandy
                            s.add((leftx+dx-islandx, lefty+dy-islandy))
                        del islands[leftx, lefty]
                    continue
                if j and grid[i][j-1]:
                    islandx, islandy = mapping[i, j-1]
                    mapping[i, j] = islandx, islandy
                    islands[islandx, islandy].add((i-islandx, j-islandy))
                    continue
                mapping[i, j] = i, j
                islands[i, j] = {(0, 0)}
        shapes = {frozenset(islands[k]) for k in islands}
        return len(shapes)

Stickers to Spell Word

We are given N different types of stickers. Each sticker has a lowercase English word on it.

You would like to spell out the given target string by cutting individual letters from your collection of stickers and rearranging them.

You can use each sticker more than once if you want, and you have infinite quantities of each sticker.

What is the minimum number of stickers that you need to spell out the target? If the task is impossible, return -1.

Example 1:

Input:

["with", "example", "science"], "thehat"

Output:

3

Explanation:

We can use 2 "with" stickers, and 1 "example" sticker.
After cutting and rearrange the letters of those stickers, we can form the target "thehat".
Also, this is the minimum number of stickers necessary to form the target string.

Example 2:

Input:

["notice", "possible"], "basicbasic"

Output:

-1

Explanation:

We can't form the target "basicbasic" from cutting letters from the given stickers.

Note:

  • stickers has length in the range [1, 50].
  • stickers consists of lowercase English words (without apostrophes).
  • target has length in the range [1, 15], and consists of lowercase English letters.
  • In all test cases, all words were chosen randomly from the 1000 most common US English words, and the target was chosen as a concatenation of two random words.
  • The time limit may be more challenging than usual. It is expected that a 50 sticker test case can be solved within 35ms on average.
Wrong Answer
def scorec(sticker, target):
    return {k: min(sticker[k], target[k]) for k in target if k in sticker}

def maked(s, cache={}):
    if s in cache:
        return dict(cache[s])
    d = {}
    for c in s:
        d.setdefault(c, 0)
        d[c] += 1
    cache[s] = d
    return dict(d)

class Solution:
    def minStickers(self, stickers, target):
        """
        :type stickers: List[str]
        :type target: str
        :rtype: int
        """
        target = maked(target)
        stickers = [maked(s) for s in stickers]
        scores = []
        for i in range(len(stickers)):
            s = stickers[i]
            score = scorec(s, target)
            scores.append((sum(score.values()), i, score, s))
        scores.sort(reverse=True)
        count = 0
        while target:
            count += 1
            sticker = scores[0][2]
            if not sticker:
                return -1
            changed = set()
            removed = set()
            for k in sticker:
                target[k] -= sticker[k]
                if target[k]:
                    changed.add(k)
                else:
                    del target[k]
                    removed.add(k)
            for i in range(len(scores)):
                s = scores[i]
                rebuild = False
                for c in changed:
                    if c in s[2]:
                        rebuild = True
                        break
                if rebuild:
                    score = scorec(s[3], target)
                    scores[i] = sum(score.values()), s[1], score, s[3]
                    continue
                recalc = False
                for r in removed:
                    if r in s[2]:
                        recalc = True
                        del s[2][r]
                if recalc:
                    scores[i] = sum(s[2].values()), s[1], s[2], s[3]
            scores.sort(reverse=True)
        return count