Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Remove all occurrences of a given value in an array in place in Go (Golang)

Posted on January 31, 2023January 31, 2023 by admin

Table of Contents

  • Overview
  • Program

Overview

An integer array is given and a target element is given. Remove all occurrences of that target element from the array. The removal must be done in place

Input: [1, 4, 2, 5, 4]
Target: 4
Output: [1, 2, 5]
Input: [1, 2, 3]
Target:3
Output: [1, 2]

Program

Here is the program for the same.

package main
import (
"fmt"
)
func removeElement(nums []int, val int) []int {
lenNums := len(nums)
k := 0
for i := 0; i < lenNums; {
if nums[i] != val {
nums[k] = nums[i]
k++
}
i++
}
return nums[0:k]
}
func main() {
output := removeElement([]int{1, 4, 2, 5, 4}, 4)
fmt.Println(output)
output = removeElement([]int{1, 2, 3}, 3)
fmt.Println(output)
}

Output

[1 2 5]
[1 2]

Note: Check out our Golang Advanced Tutorial. The tutorials in this series are elaborative and we have tried to cover all concepts with examples. This tutorial is for those who are looking to gain expertise and a solid understanding of golang - Golang Advance Tutorial

Also if you are interested in understanding how all design patterns can be implemented in Golang. If yes, then this post is for you -All Design Patterns Golang

  • go
  • Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2023 Welcome To Golang By Example | Design: Web XP