Skip to content
LC-1042 Medium LeetCode

1042. Flower Planting With No Adjacent

Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 52% Topics: Depth-First Search, Breadth-First Search, Graph
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(n)
# Space: O(n)

class Solution(object):
    def gardenNoAdj(self, N, paths):
        """
        :type N: int
        :type paths: List[List[int]]
        :rtype: List[int]
        """
        result = [0]*N
        G = [[] for i in xrange(N)]
        for x, y in paths:
            G[x-1].append(y-1)
            G[y-1].append(x-1)
        for i in xrange(N):
            result[i] = ({1, 2, 3, 4} - {result[j] for j in G[i]}).pop()
        return result

Solution from kamyu104/LeetCode-Solutions · MIT