The Flowerbed Challenge: Can You Plant Them All? (Python, Typescript, Golang)

in #algorithms2 months ago


image.png

Let flowerbed be an integer array representing a flowerbed, where 0 denotes an empty plot and 1 denotes a planted plot. Determine whether it is possible to plant n additional flowers in the flowerbed such that no two planted flowers are adjacent.

Example 1:

Input: flowerbed = [1,0,0,0,1], n = 1
Output: true

Example 2:

Input: flowerbed = [1,0,0,0,1], n = 2
Output: false

Constraints:

  • 1 <= flowerbed.length <= 2 * 104
  • flowerbed[i] is 0 or 1.
  • There are no two adjacent flowers in flowerbed.
  • 0 <= n <= flowerbed.length

Solution in Python

class Solution:
    def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
        count = 0
        for i in range(len(flowerbed)):
            if flowerbed[i] == 0:  # Check if the current plot is empty
                left_empty = (i == 0) or (flowerbed[i - 1] == 0) # Check left, handle edge
                right_empty = (i == len(flowerbed) - 1) or (flowerbed[i + 1] == 0) # Check right, handle edge

                if left_empty and right_empty:
                    flowerbed[i] = 1  # Plant a flower (conceptually - or modify if you need to)
                    count += 1

        return count >= n

Solution in Typescript

function canPlaceFlowers(flowerbed: number[], n: number): boolean {
    let count = 0;
    for (let i = 0; i < flowerbed.length; i++) {
        if (flowerbed[i] === 0) { // Check if the current plot is empty
            const leftEmpty = (i === 0) || (flowerbed[i - 1] === 0); // Check left, handle edge
            const rightEmpty = (i === flowerbed.length - 1) || (flowerbed[i + 1] === 0); // Check right, handle edge

            if (leftEmpty && rightEmpty) {
                flowerbed[i] = 1; // Plant a flower (conceptually - or modify if you need to)
                count++;
            }
        }
    }

    return count >= n;
}

Solution in Go

func canPlaceFlowers(flowerbed []int, n int) bool {
    count := 0
    for i := 0; i < len(flowerbed); i++ {
        if flowerbed[i] == 0 { // Check if the current plot is empty
            leftEmpty := i == 0 || flowerbed[i-1] == 0 // Check left, handle edge
            rightEmpty := i == len(flowerbed)-1 || flowerbed[i+1] == 0 // Check right, handle edge

            if leftEmpty && rightEmpty {
                flowerbed[i] = 1 // Plant a flower (conceptually - or modify if you need to)
                count++
            }
        }
    }

    return count >= n
}

Explanation

The code implements a solution to the “flowerbed planting” problem. Here’s a breakdown of what it does in general terms:

  1. Initialization: It starts by setting a count to 0. This count will keep track of how many flowers we can successfully plant.
  2. Iterating Through the Flowerbed: The code then goes through each plot in the flowerbed, one by one. Think of it like walking along the flowerbed and checking each spot.
  3. Checking if a Plot is Empty: For each plot, it first checks if the plot is empty (represented by a 0). If it’s not empty (meaning a flower is already planted there), it skips that plot and moves on to the next.
  4. Checking Adjacent Plots: If the current plot is empty, the code then checks the plots immediately to the left and right of the current plot. It’s crucial to make sure we don’t plant flowers next to each other.
  5. Handling Edge Cases: A very important detail is how the code handles the edges of the flowerbed. If we’re checking the first plot, there is no plot to the left. Similarly, if we’re checking the last plot, there is no plot to the right. The code must take these situations into account so we don’t try to check plots that don’t exist.
  6. Planting a Flower: If the current plot is empty and both the left and right adjacent plots are also empty (or don’t exist because we’re at an edge), then the code “plants” a flower in the current plot. (In the actual code, it often just changes the value in the array to 1. Sometimes, the code may not actually modify the input array, but the logic is the same.) It also increments the count because we've successfully planted a flower.
  7. Checking if Enough Flowers Were Planted: After checking all the plots in the flowerbed, the code compares the count (the number of flowers we were able to plant) with the number of flowers we wanted to plant (n).
  8. Returning the Result: If the count is greater than or equal to n, it means we were able to plant enough flowers, so the code returns "true." Otherwise, it returns "false."

In essence, the code simulates walking along the flowerbed, checking each empty plot to see if it’s a valid place to plant a new flower, and keeping track of how many flowers it can plant. It then compares that number to the desired number of flowers to determine if the planting is possible.


If you liked this content I’d appreciate an upvote or a comment. That helps me improve the quality of my posts as well as getting to know more about you, my dear reader.

Muchas gracias!

Follow me for more content like this.

X | PeakD | Rumble | YouTube | Linked In | GitHub | PayPal.me | Medium

Down below you can find other ways to tip my work.

BankTransfer: "710969000019398639", // CLABE
BAT: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875",
ETH: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875",
BTC: "33xxUWU5kjcPk1Kr9ucn9tQXd2DbQ1b9tE",
ADA: "addr1q9l3y73e82hhwfr49eu0fkjw34w9s406wnln7rk9m4ky5fag8akgnwf3y4r2uzqf00rw0pvsucql0pqkzag5n450facq8vwr5e",
DOT: "1rRDzfMLPi88RixTeVc2beA5h2Q3z1K1Uk3kqqyej7nWPNf",
DOGE: "DRph8GEwGccvBWCe4wEQsWsTvQvsEH4QKH",
DAI: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875"