Number of ways to color the balls (Ball Coloring)

Last Updated : 13 Jun, 2026

Given n balls arranged in a line, each ball must be colored either RED or BLUE. A coloring is considered valid if the number of adjacent positions where the color changes (from RED to BLUE or BLUE to RED) is at most 2. Find the total number of valid ways to color all the balls.

Examples:

Input: n = 1
Output: 2
Explanation: Possible ways to color are {{R}, {B}}. So the answer is 2.

Input: n = 2
Output: 4
Explanation: Possible ways to color are {{RB},{BR},{RR},{BB}}. So the answer is 4.

Try It Yourself
redirect icon

[Naive Approach] Generate All Colorings - O(n * 2 ^ n) Time O(1) Space

The idea is to generate all possible colorings of the n balls. Since each ball can be colored either RED or BLUE, there are 2 ^ n possible colorings. For each coloring, count the number of adjacent color changes and consider it valid if the count is at most 2.

C++
#include <iostream>
using namespace std;

// Function to calculate the number of ways.
int noOfWays(int n)
{
    int ans = 0;

    // Generate all possible colorings
    for (int mask = 0; mask < (1 << n); mask++)
    {
        int changes = 0;

        for (int i = 1; i < n; i++)
        {
            int prev = (mask >> (i - 1)) & 1;
            int curr = (mask >> i) & 1;

            if (prev != curr)
            {
                changes++;
            }
        }

        if (changes <= 2)
        {
            ans++;
        }
    }

    return ans;
}

// Driver code
int main()
{
    int n = 2;

    cout << noOfWays(n) << endl;

    return 0;
}
Java
import java.util.Scanner;

// Function to calculate the number of ways.
public class GfG {
    public static int noOfWays(int n)
    {
        int ans = 0;

        // Generate all possible colorings
        for (int mask = 0; mask < (1 << n); mask++) {
            int changes = 0;

            for (int i = 1; i < n; i++) {
                int prev = (mask >> (i - 1)) & 1;
                int curr = (mask >> i) & 1;

                if (prev != curr) {
                    changes++;
                }
            }

            if (changes <= 2) {
                ans++;
            }
        }

        return ans;
    }

    // Driver code
    public static void main(String[] args)
    {
        int n = 2;
        System.out.println(noOfWays(n));
    }
}
Python
"""
Function to calculate the number of ways.
"""


def noOfWays(n):
    ans = 0

    # Generate all possible colorings
    for mask in range(1 << n):
        changes = 0

        for i in range(1, n):
            prev = (mask >> (i - 1)) & 1
            curr = (mask >> i) & 1

            if prev != curr:
                changes += 1

        if changes <= 2:
            ans += 1

    return ans


# Driver code
if __name__ == "__main__":
    n = 2
    print(noOfWays(n))
C#
using System;

// Function to calculate the number of ways.
public class GfG {
    public static int noOfWays(int n)
    {
        int ans = 0;

        // Generate all possible colorings
        for (int mask = 0; mask < (1 << n); mask++) {
            int changes = 0;

            for (int i = 1; i < n; i++) {
                int prev = (mask >> (i - 1)) & 1;
                int curr = (mask >> i) & 1;

                if (prev != curr) {
                    changes++;
                }
            }

            if (changes <= 2) {
                ans++;
            }
        }

        return ans;
    }

    // Driver code
    public static void Main()
    {
        int n = 2;
        Console.WriteLine(noOfWays(n));
    }
}
JavaScript
"use strict";

// Function to calculate the number of ways.
function noOfWays(n) {
    let ans = 0;

    // Generate all possible colorings
    for (let mask = 0; mask < (1 << n); mask++) {
        let changes = 0;

        for (let i = 1; i < n; i++) {
            let prev = (mask >> (i - 1)) & 1;
            let curr = (mask >> i) & 1;

            if (prev!== curr) {
                changes++;
            }
        }

        if (changes <= 2) {
            ans++;
        }
    }

    return ans;
}

// Driver code
let n = 2;
console.log(noOfWays(n));

Output
4

Time Complexity: O(n * 2 ^ n)
Auxiliary Space: O(1)

[Expected Approach] Counting Color Segments - O(1) Time O(1) Space

The idea is to count valid colorings based on the number of color changes. A valid coloring can have 0, 1, or 2 color changes. Count the number of ways for each case separately and add them together, which simplifies to the formula: 2 + n * (n - 1).

Mathematical Formula: A valid coloring can have 0, 1, or 2 color changes.

  • 0 changes: 2 ways (all R or all B)
  • 1 change: 2(n - 1) ways (All R and 1 B at n-1 different positions OR All B and 1 R at n-1 different positions)
  • 2 changes: 2C(n - 1, 2) ways (Consider all R and pick any 2 gaps to fill B OR consider all B and pick any two gaps to fill R).

Therefore, Ways = 2 + 2 (n - 1) + 2 * C (n - 1, 2) = 2 + n (n − 1).

C++
#include <iostream>
using namespace std;

// Function to calculate the number of ways.
int noOfWays(int n)
{
    return 2 + n * (n - 1);
}

// Driver code
int main()
{
    int n = 2;

    cout << noOfWays(n) << endl;

    return 0;
}
Java
import java.util.Scanner;

// Function to calculate the number of ways.
class GfG {
    public static int noOfWays(int n)
    {
        return 2 + n * (n - 1);
    }

    // Driver code
    public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        int n = 2;

        System.out.println(noOfWays(n));
    }
}
Python
# Function to calculate the number of ways.
def noOfWays(n):
    return 2 + n * (n - 1)


# Driver code
if __name__ == "__main__":
    n = 2
    print(noOfWays(n))
C#
// Function to calculate the number of ways.
using System;

class GfG {
    static int noOfWays(int n) { return 2 + n * (n - 1); }

    // Driver code
    static void Main()
    {
        int n = 2;

        Console.WriteLine(noOfWays(n));
    }
}
JavaScript
// Function to calculate the number of ways.
function noOfWays(n) {
    return 2 + n * (n - 1);
}

// Driver code
let n = 2;

console.log(noOfWays(n));

Output
4

Time Complexity: O(1)
Auxiliary Space: O(1)

Comment