In this post, we will solve **Sequence full of colors HackerRank Solution**. This problem **(Sequence full of colors)** is a part of **HackerRank Functional Programming** series.

**Task**

You are given a sequence of * N* balls in 4 colors:

*red, green, yellow and blue*. The sequence is

*full of colors*if and only if all of the following conditions are true:

- There are as many red balls as green balls.
- There are as many yellow balls as blue balls.
- Difference between the number of red balls and green balls in every
*prefix*of the sequence is at most 1. - Difference between the number of yellow balls and blue balls in every
*prefix*of the sequence is at most 1.

Your task is to write a program, which for a given sequence prints `True`

if it is *full of colors*, otherwise it prints `False`

.

**Input**

In the first line there is one number * T* denoting the number of tests cases.

*lines follow. In each of them there is a sequence of letters*

**T****{**denoting the input sequence (

*R*,*G*,*Y*,*B*}*– red,*

**R***– green,*

**G***– yellow,*

**Y***– blue).*

**B****Output**

For each test case, print `True`

if this is a sequence *full of colors*, otherwise print `False`

.

**Constraints**

**1 <=***T*<= 10- Sequence will only consists of letters
**{**.*R*,*G*,*Y*,*B*} - Sum of length of all sequences will not exceed
**10**.^{6}

**Sample Input**

```
4
RGGR
RYBG
RYRB
YGYGRBRB
```

**Sample Output**

```
True
True
False
False
```

**Explanation**

In the first two test cases, all four conditions are satisfied.

In the third test case, condition #1 fails as there are more red balls than green balls and condition #3 also fails for prefix “RYR” as the difference between the number of red and green balls is more than 1. In the fourth test, for a prefix “YGYG” condition 4^{th} fails.

**Solution – Sequence full of colors – HackerRank Solution**

**Scala**

import java.util.Scanner object Solution { def main(args: Array[String]): Unit = { val sc = new Scanner(System.in) val t = sc.nextInt sc.nextLine val colors = "RGYB" (0 until t).foreach(_ => { val s = sc.nextLine val counts = colors.map(c => c -> s.count(_ == c)).toMap println(if (counts('R') == counts('G') && counts('Y') == counts('B') && prefix(s.toList, 'R', 'G') && prefix(s.toList, 'R', 'G')) "True" else "False") }) sc.close() } def prefix(s: List[Char], c0: Char, c1: Char): Boolean = { @scala.annotation.tailrec def inner(s: List[Char], delta: Int): Boolean = s match { case Nil => true case x :: xs => val nextDelta = delta + (x match { case `c0` => -1 case `c1` => 1 case _ => 0 }) math.abs(nextDelta) <= 1 && inner(xs, nextDelta) } inner(s, 0) } }

**Note:** This problem **(Sequence full of colors)** is generated by **HackerRank** but the solution is provided by **CodingBroz**. This tutorial is only for **Educational** and **Learning** purpose.