Open In App

Ways to arrange N balls of K colors with no adjacent same colors

Last Updated : 29 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given infinite balls of K distinct colors. Count the number of ways to arrange N balls in a line such that no two adjacent balls are of same color. Since the answer may be very large, output the result MOD 1000000007.

Examples:

Input: N = 2, K = 2
Output: 2
Explanation: We will denote the colors by ‘R’ and ‘G’. There are two possible ways: “RG” and “GR”.

Input: N = 1, K = 100
Output: 100
Explanation: As there is only 1 box and 100 different colored balls, we can put any of the 100 balls in the box.

Input: N = 3, K = 2
Output: 2
Explanation: There are only two possible ways: “RGR” and “GRG”.

Approach: To solve the problem, follow the below idea:

If the number of balls to be arranged is 1, then the number of ways = K as we can choose one ball from any of the K different colors. For N > 1, we have K choices for the first ball and for every subsequent ball, we can choose from any of the K colors except the one which was used in the previous ball. So, the total number of ways are: N * ((K – 1) ^ (N – 1)). This can be easily calculated using Binary Exponentiation.

Below is the implementation of the approach:

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

class BinaryExponentiation {
public:
    static const long long MOD = 1000000007;

    // Binary Exponentiation
    static long long power(long long base, long long expo)
    {
        long long ans = 1;
        while (expo > 0) {
            if ((expo & 1) == 1)
                ans = (ans * base) % MOD;
            base = (base * base) % MOD;
            expo >>= 1;
        }
        return ans;
    }

    static void main()
    {
        int N = 5, K = 3;

        // Calculate the result using the formula
        // (K)*(K-1)^(N-1)
        long long ways = (K * power(K - 1, N - 1)) % MOD;

        cout << ways << endl;
    }
};

int main()
{
    BinaryExponentiation::main();
    return 0;
}
Java
import java.util.Scanner;

public class BinaryExponentiation {

    static long MOD = 1000000007;

    // Binary Exponentiation
    static long power(long base, long expo)
    {
        long ans = 1;
        while (expo > 0) {
            if ((expo & 1) == 1)
                ans = (ans * base) % MOD;
            base = (base * base) % MOD;
            expo >>= 1;
        }
        return ans;
    }

    public static void main(String[] args)
    {
        int N = 5, K = 3;

        // Calculate the result using the formula
        // (K)*(K-1)^(N-1)
        long ways = (K * power(K - 1, N - 1)) % MOD;

        System.out.println(ways);
    }
}

// This code is contributed by rambabuguphka
Python3
# Define the modulus value
MOD = 1000000007

# Binary Exponentiation function to calculate (base^expo) % MOD


def power(base, expo):
    ans = 1
    # Iterate through each bit of the exponent
    while expo > 0:
        # If the current bit is set, multiply ans by base
        if expo & 1:
            ans = (ans * base) % MOD
        # Update base to base^2 % MOD
        base = (base * base) % MOD
        # Shift the exponent right by 1 (divide by 2)
        expo >>= 1
    return ans

# Main function


def main():
    # Given values for N and K
    N = 5
    K = 3

    # Calculate the result using the formula (K)*(K-1)^(N-1)
    # and taking modulo MOD
    ways = (K * power(K - 1, N - 1)) % MOD

    # Print the calculated result
    print(ways)


# Call the main function to execute the program
main()
C#
using System;

class Program
{
    // Define the modulus constant
    const int MOD = 1000000007;

    // Binary Exponentiation
    static long Power(long baseValue, long expo)
    {
        long ans = 1;
        while (expo > 0)
        {
            // If expo is odd, multiply ans by baseValue
            if ((expo & 1) == 1)
                ans = (ans * baseValue) % MOD;

            // Square the baseValue
            baseValue = (baseValue * baseValue) % MOD;

            // Right shift expo by 1
            expo >>= 1;
        }
        return ans;
    }

    static void Main()
    {
        int N = 5, K = 3;

        // Calculate the result using the formula (K)*(K-1)^(N-1)
        long ways = (K * Power(K - 1, N - 1)) % MOD;

        Console.WriteLine(ways);
    }
}
Javascript
const MOD = 1000000007;

// Binary Exponentiation
function power(base, expo) {
    let ans = 1;
    while (expo > 0) {
        if (expo & 1)
            ans = (ans * base) % MOD;
        base = (base * base) % MOD;
        expo >>= 1;
    }
    return ans;
}

function main() {
    let N = 5, K = 3;

    // Calculate the result using the formula
    // (K)*(K-1)^(N-1)
    let ways = (K * power(K - 1, N - 1)) % MOD;

    console.log(ways);
}

main();
PHP
<?php
class BinaryExponentiation {
    const MOD = 1000000007;

    // Binary Exponentiation
    static function power($base, $expo)
    {
        $ans = 1;
        while ($expo > 0) {
            if (($expo & 1) == 1)
                $ans = ($ans * $base) % self::MOD;
            $base = ($base * $base) % self::MOD;
            $expo >>= 1;
        }
        return $ans;
    }

    public static function main()
    {
        $N = 5;
        $K = 3;

        // Calculate the result using the formula
        // (K)*(K-1)^(N-1)
        $ways = ($K * self::power($K - 1, $N - 1)) % self::MOD;

        echo $ways . "\n";
    }
}

// Call main function
BinaryExponentiation::main();
?>

Output
48

Time Complexity: O(log2N), where N is the number of balls to arrange.
Auxiliary Space: O(1)



Similar Reads

Find ways to arrange K green balls among N balls such that exactly i moves is needed to collect all K green balls
Given two integers N and K. There are N balls placed in a row. K of them are green and N - K of them are black. The task is to find the number of ways to arrange N balls such that one will need exactly i ( 1 ? i ? K ) moves to collect all the green balls. In one move, we can collect any group of consecutive green balls. Note that the answer can be
10 min read
Ways to arrange Balls such that adjacent balls are of different types
There are 'p' balls of type P, 'q' balls of type Q and 'r' balls of type R. Using the balls we want to create a straight line such that no two balls of same type are adjacent.Examples : Input : p = 1, q = 1, r = 0 Output : 2 There are only two arrangements PQ and QP Input : p = 1, q = 1, r = 1 Output : 6 There are only six arrangements PQR, QPR, QR
34 min read
Count ways of selecting X red balls and Y blue balls
Given integers A, B, C, and D, There are two boxes First Box has A red balls and B blue balls and the second box has C red balls and D blue balls, the task is to count ways to select 3 red balls and 3 blue balls so that there are 3 balls drawn from the first box and 3 balls drawn from the second box. (Print the answer modulo 109 + 7). Examples: Inp
17 min read
Count ways to arrange integers in circle such that no two adjacent are same
Given 2 integers N and M, find the number of ways to arrange N integers in a circle such that every integer is in the range 0 to M-1, and no two adjacent integers are same. As the answer could be large, find the number, modulo 998244353. Examples: Input: N=3, M=3Output: 6Explanation: There are six ways as follows (0, 1, 2), (0, 2, 1), (1, 0, 2), (1
5 min read
Find winner in game of N balls, in which a player can remove any balls in range [A, B] in a single move
Given two integers A and B, and also given that Alice and Bob are playing a game starting with a bag containing N balls, in which, in a single move, a player can remove any number of balls between the range [A, B] and if the player cannot remove any balls, then the player loses, the task is to find the winner of the game if Alice and Bob play the g
5 min read
Ways to fill N positions using M colors such that there are exactly K pairs of adjacent different colors
Given three integers N, M and K. The task is to find the number of ways to fill N positions using M colors such that there are exactly K pairs of different adjacent colors. Examples: Input: N = 3, M = 2, K = 1 Output: 4 Let the colors be 1 and 2, so the ways are: 1, 1, 2 1, 2, 2 2, 2, 1 2, 1, 1 The above 4 ways have exactly one pair of adjacent ele
12 min read
Ways to paint N paintings such that adjacent paintings don't have same colors
Given two integers n and m, where n represent some paintings numbered from 1 to n and m represent some colours 1 to m with unlimited amount. The task is to find the number of ways to paint the paintings such that no two consecutive paintings have the same colors.Note: Answer must be calculated in modulo 10^9 +7 as answer can be very large. Examples
7 min read
Count ways to arrange N distinct objects if all clockwise arrangements are considered the same
Given N distinct objects, the task is to find the number of distinct arrangements of N objects if all clockwise arrangements are considered the same. If A, B, and C are three distinct objects, then arrangements {A, B, C}, {C, A, B}, and {B, C, A} are considered the same as all the arrangements are clockwise to each other. Examples: Input: N = 3Outp
4 min read
Probability of distributing given balls into two halves having equal count of distinct colors
Given an array arr[] of size N, representing the number of balls of each of N distinct colors, the task is to find the probability of distributing all the balls into two boxes, such that both the boxes contain an equal number of distinct colored balls. Examples: Input: arr[] = {1, 1}, N = 2Output: 1.00000Explanation: Two possible ways to distribute
14 min read
Ways to paint stairs with two colors such that two adjacent are not yellow
Given n stairs and we have 2 colour yellow and green the task is that we have to paint given stairs by given colour with condition is that we cannot paints two yellow steps directly after each other.Examples : Input : n = 1 Output : 2 A single stair can be colored either as green or yellow. Input : n = 3 Output : 5 Case 1: When we have 1 stair, we
4 min read