Menu Close

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:

  • We will solve this problem with two variables
  • Place first variable at start of array and second variable at end of array
  • Check ball colour at first variable and ball colour at second variable
    • If colour at first variable is Red then increment the first variable
    • If colour at second variable is blue then decrement the second variable
    • If colour at first variable is blue and colour at second variable is Red then swap the colour ball.
  • return the updated ball array

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:

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

Posted in golang, golang program, Medium

Leave a Reply

Your email address will not be published. Required fields are marked *