Skip to content
Programmingoneonone
Programmingoneonone
  • Home
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programmingoneonone

HackerEarth Jumping Tokens problem solution

YASH PAL, 31 July 2024
In this HackerEarth Jumping Tokens problem solution, You are given a row of n tokens in a row colored red and blue.
In one move, you can choose to perform a capture. A capture chooses a token, and makes a jump over exactly one other token, and removes a token of the opposite color.
More specifically, given three adjacent tokens we can convert it into the following state with two adjacent tokens:
  1. R x B -> xR
  2. B x R -> xB
  3. R x B -> Bx
  4. B x R -> Rx
where x is a token of an arbitrary color.
Given the initial row of tokens, return the minimum possible length of the resulting row after a series of captures.
HackerEarth Jumping Tokens problem solution

HackerEarth Jumping Tokens problem solution.

import java.util.Scanner;
public class JumpingTokens {
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
while(t-->0) {
String s = in.next();
if (s.equals("RBBBR") || s.equals("BRRRB")) {
System.out.println(3);
continue;
}
char[] c = s.toCharArray();
int n = c.length;
int countR = 0, countB = 0;
boolean alternating = true;
int ridx = 0, bidx = 0;
for (int i = 0; i < c.length; i++) {
if (c[i] == 'R') {countR++; ridx = i;}
else {countB++; bidx = i;}
if (i > 0 && c[i] == c[i-1]) alternating = false;
}
if (alternating || countR == 0 || countB == 0) {
System.out.println(n);
continue;
}
if (countR == 1) {
System.out.println((ridx % 3 == (c.length - ridx - 1) % 3) ? 3 : 2);
continue;
}
if (countB == 1) {
System.out.println((bidx % 3 == (c.length - bidx - 1) % 3) ? 3 : 2);
continue;
}
System.out.println(2);
}
}
}
coding problems solutions

Post navigation

Previous post
Next post

Pages

  • About US
  • Contact US
  • Privacy Policy

Programing Practice

  • C Programs
  • java Programs

HackerRank Solutions

  • C
  • C++
  • Java
  • Python
  • Algorithm

Other

  • Leetcode Solutions
  • Interview Preparation

Programming Tutorials

  • DSA
  • C

CS Subjects

  • Digital Communication
  • Human Values
  • Internet Of Things
  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2025 Programmingoneonone | WordPress Theme by SuperbThemes