LeetCode 2222: Number of Ways to Select Buildings Solution

Master LeetCode problem 2222 (Number of Ways to Select Buildings), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2222. Number of Ways to Select Buildings

Problem Explanation

Explanation:

To solve this problem, we can iterate through the binary string and count the number of ways to select 3 buildings that satisfy the given conditions. We can use a sliding window approach to keep track of the current selection of buildings. If the current selection violates the condition of having consecutive buildings of the same type, we can skip that selection.

  1. Initialize a counter variable to keep track of the number of valid selections.
  2. Use a sliding window of size 3 to iterate through the binary string.
  3. Check if the current selection violates the condition of having consecutive buildings of the same type. If it does not, increment the counter.
  4. Return the final count as the result.

Time Complexity: O(n), where n is the length of the binary string.

Space Complexity: O(1)

Solution Code

class Solution {
    public int numWays(String s) {
        int count = 0;
        for (int i = 0; i <= s.length() - 3; i++) {
            if (s.charAt(i) != s.charAt(i + 1) && s.charAt(i + 1) != s.charAt(i + 2) && s.charAt(i) != s.charAt(i + 2)) {
                count++;
            }
        }
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2222 (Number of Ways to Select Buildings)?

This page provides optimized solutions for LeetCode problem 2222 (Number of Ways to Select Buildings) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2222 (Number of Ways to Select Buildings)?

The time complexity for LeetCode 2222 (Number of Ways to Select Buildings) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2222 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2222 in Java, C++, or Python.

Back to LeetCode Solutions