FastPrepFastPrep
Problem Brief

Coloring Houses

INTERNOA
See Snowflake online assessment and hiring insights

The city of Hackerland can be represented with an even number n houses arranged in a row. A painter must paint the houses using at most three colors. The following conditions must hold true:

  • No two adjacent houses are the same color.
  • The houses which are at the same distance from both ends must not be colored with the same color. For example, n=6 then houses will be [1,2,3,4,5,6], so the houses at the same distance from both the ends will be [1,6], [2,5], [3,4].
  • The task is to find the number of ways to paint the houses using at most three colors such that both the above conditions hold true. Since the answer can be large, report it modulo 10^9 + 7. Two ways are considered different if at least one house is colored differently.

    Function Description

    Complete the countWaysToColorHouses function in the editor.

    countWaysToColorHouses takes in a single parameter:

    1. int n, the number of houses

    1Example 1

    Input
    n = 4
    Output
    18
    Explanation
    For n = 4, some of the possible valid arrangements are:
  • (color1, color2, color3, color2)
  • (color1, color3, color1, color3)
  • The number of ways to paint 4 houses using three colors is 18. Return 18 modulo (10^9 + 7) which is 18.

    2Example 2

    Input
    n = 2
    Output
    6
    Explanation
    The valid arrangements for 2 houses are: (color1, color2) (color1, color3) (color2, color1) (color3, color1) (color2, color3) (color3, color2)

    3Example 3

    Input
    n = 4
    Output
    18
    Explanation
    Total valid arrangements for 4 hourses are 18. Some of the valid arrangements are: {color1, color2, color1, color2} {color1, color3, color1, color3} {color2, color1, color2, color1} {color3, color1, color3, color1} {color2, color3, color2, color3} {color3, color2, color3, color2}

    Constraints

    Limits and guarantees your solution can rely on.

  • 1 <= n <= 100000
  • n is an even integer
  • public int countWaysToColorHouses(int n) {
      // write your code here
    }
    
    Input

    n

    4

    Output

    18

    Sign in to submit your solution.