Leetcode 2222: Number of Ways to Select Buildings

grid47
grid47
Exploring patterns and algorithms
Mar 29, 2024 7 min read

You are given a binary string s that represents the types of buildings along a street. Each building is either an office (‘0’) or a restaurant (‘1’). You are tasked with selecting 3 buildings for inspection, with the constraint that no two consecutive buildings in the selection can be of the same type. Return the number of valid ways to select 3 buildings where no two consecutive buildings are of the same type.
Problem
Approach
Steps
Complexity
Input: The input consists of a binary string `s`, where each character is either '0' (for an office) or '1' (for a restaurant).
Example: s = '101010'
Constraints:
• 3 <= s.length <= 10^5
• s[i] is either '0' or '1'
Output: Return the number of valid ways to select 3 buildings such that no two consecutive buildings are of the same type.
Example: Output: 4
Constraints:
• The input string will always have at least three characters.
Goal: The goal is to count all possible valid selections of 3 buildings such that no two consecutive buildings in the selected set are of the same type.
Steps:
• Count the total number of '0's and '1's in the string.
• Iterate through the string and, for each character, calculate how many valid combinations of 3 buildings can be made, taking care to avoid consecutive buildings of the same type.
• Use efficient counting to avoid checking each triplet explicitly.
Goal: The string `s` will have at least 3 characters, and each character is either '0' or '1'.
Steps:
• 3 <= s.length <= 10^5
• s[i] is either '0' or '1'
Assumptions:
• The string will always have at least three characters.
Input: Input: s = '101010'
Explanation: The valid selections of 3 buildings are: [0, 2, 4], [0, 2, 5], [1, 2, 4], and [1, 2, 5]. Each of these selections alternates between '0' and '1', making them valid.

Input: Input: s = '11100'
Explanation: There are no valid selections, as all possible combinations of 3 buildings either have consecutive '1's or '0's, violating the problem's constraints.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus