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.

Contents

**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.