Count ways to place buildings on a row of plots with no two adjacent

Quick Overview

Count how many ways buildings can be placed on a row of n plots so that no two buildings sit on neighboring plots. It tests setting up a two-state dynamic programming recurrence, spotting the Fibonacci pattern, and cutting the memory down to constant space.

Count ways to place buildings on a row of plots with no two adjacent

Company: Sap

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

Given `n` free plots arranged in a row, find the number of ways to assign buildings to these plots such that no two buildings are adjacent. Each plot can either have a building placed on it or be left empty. Return the total number of valid arrangements. ### Function Signature ```python def count_ways(n: int) -> int: ``` ### Rules - Two arrangements are different when some plot holds a building in one of them and is empty in the other. - Leaving every plot empty is a valid arrangement and counts once. ### Constraints - `1 <= n <= 50` ### Examples ```text Input: n = 3 Output: 5 ``` The 5 valid arrangements are [E,E,E], [B,E,E], [E,B,E], [E,E,B] and [B,E,B], where B is a building and E is an empty plot. ```text Input: n = 4 Output: 8 ``` The 8 valid arrangements are [E,E,E,E], [B,E,E,E], [E,B,E,E], [E,E,B,E], [E,E,E,B], [B,E,B,E], [B,E,E,B] and [E,B,E,B]. ```text Input: n = 1 Output: 2 ``` A single plot is either empty or holds a building, and it has no neighbor to conflict with.

Overview: Count how many ways buildings can be placed on a row of n plots so that no two buildings sit on neighboring plots. It tests setting up a two-state dynamic programming recurrence, spotting the Fibonacci pattern, and cutting the memory down to constant space.

Sap logo
Sap
Nov 25, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Given n free plots arranged in a row, find the number of ways to assign buildings to these plots such that no two buildings are adjacent.

Each plot can either have a building placed on it or be left empty. Return the total number of valid arrangements.

Function Signature

def count_ways(n: int) -> int:

Rules

  • Two arrangements are different when some plot holds a building in one of them and is empty in the other.
  • Leaving every plot empty is a valid arrangement and counts once.

Constraints

  • 1 <= n <= 50

Examples

Input: n = 3
Output: 5

The 5 valid arrangements are [E,E,E], [B,E,E], [E,B,E], [E,E,B] and [B,E,B], where B is a building and E is an empty plot.

Input: n = 4
Output: 8

The 8 valid arrangements are [E,E,E,E], [B,E,E,E], [E,B,E,E], [E,E,B,E], [E,E,E,B], [B,E,B,E], [B,E,E,B] and [E,B,E,B].

Input: n = 1
Output: 2

A single plot is either empty or holds a building, and it has no neighbor to conflict with.