Techieindoor

Go – Program to rearrange the Red and Blue ball such that Red ball comes first

Here, we will see Program to rearrange the Red and Blue ball such that Red ball comes first with code and algorithm.

You are given an array of Red and Blue balls in random order.

You have to arrange the balls such that Red balls should come first and Blue balls should come later.

Example 1:

Input: array = [R, B, B, R, R]
Output: [R, R, R, B, B]
Explanation: Here, R belongs to Red ball and B belongs to Blue ball. 

Example 2:

Input: array = [B, B, B, B, R]
Output: [R, B, B, B, B]

Algorithm:

Program to rearrange the Red and Blue ball such that Red ball comes first code in Go

Code 1:

package main

import (
    "fmt"
    "strings"
)

func rearrange_balls(balls []string) []string {
   
   if len(balls) == 0 {
     return balls
   }
   
   first := 0
   second := len(balls) - 1
   
   for ; first < second; {
     // Check if first variable colour ball is RED
     if strings.Compare(balls[first], "R") == 0 {
       first++
     } else if strings.Compare(balls[second], "B") == 0 {
       // Check if second variable colour ball is BLUE
       second --
     } else {
       // swap the balla colour If balls colour is mismatched
       tmp := balls[first]
       balls[first] = balls[second]
       balls[second] = tmp
       first++ 
       second --
     }
   }
   return balls
}

func main(){
    balls := []string{"R", "B", "B", "R", "R"}
    
    balls = rearrange_balls(balls)
    
    for _, ball := range balls {
        fmt.Print(ball, " ")
    }
}

Output:

$ go run sample.go

R R R B B 

To check more leetcode problem’s solution. Pls click given below link:

Golang tutorial

https://www.techieindoor.com/category/leetcode/

Exit mobile version