Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Problems
  • Python
  • C
  • C++
  • Java
  • Courses
  • Machine Learning
  • DevOps
  • Web Development
  • System Design
  • Aptitude
  • Projects
Open In App
Next Article:
How to Remove Duplicate Elements from Array in Ruby?
Next article icon

How to remove duplicate characters from a String in Scala?

Last Updated : 18 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn how to remove duplicate characters from a string in Scala using different approaches. First, we will look through the Brute-Force Approach and then use different standard libraries.

Examples:

Input: String = "hello"
Output: helo

Input: String = "Geeks"
Output: Geks

Naive Approach to remove duplicate characters from a String in Scala

In the brute force approach, we compare each character in the string with every other character to determine if it's a duplicate.

Below is the code in Scala.

Scala
// Program to remove duplicate from string using scala // Creating Object object Gfg {   //Method to removeDuplicates   def removeDuplicates(str: String): String = {     var result = ""     for (char <- str) {       if (!result.contains(char)) {         result += char       }     }     result   }    // Main Method   def main(args: Array[String]): Unit = {     val inputString = "hello"     val outputString = removeDuplicates(inputString)     println(stringWithoutDuplicates)    } } 

Output


Screenshot-(297)
Output

Explanation:

  • First we will create a function removeDuplicates
    • Inside this function we will took a empty var string.
    • We iterate over each character in the input string str.
    • For each character, we check if it exists in the result string. If it doesn't, we append it to the result.
    • Finally, we return the result string, which contains unique characters.
  • In main method we will call the removeDuplicate Method and Print the Output.

Time Complexity : O(n2)

Remove duplicate characters from a String in Scala Using Set

This is the another approach using a mutable Set to keep track of duplicate characters.

Below is the code in Scala using set.

Scala
// Program to remove duplicate from string using set  //creating object object Gfg {      //remove duplicate function   def removeDuplicates(str: String): String = {     val set = scala.collection.mutable.Set[Char]()     val result = new StringBuilder     for (char <- str) {       if (!set(char)) {         result += char         contain += char       }     }     result.toString   }    //Main Method   def main(args: Array[String]): Unit = {     val inputString = "hello"     val outputString = removeDuplicates(inputString)     println(outputString)    } } 

Output:

Screenshot-(297)
Output

Explanation:

  • First we will define a removeDuplicate Method
    • Inside that method we will define a mutable set named set.
    • We iterate over each character in the input string str.
    • For each character, if it's not already present in the set, we append it to the result string and add it to the set.
    • At the end, we convert the result string builder to a regular string and return it.
  • In main method we will call removeDuplicate Function and Print the Output.

Time Complexity: O(n)
Auxiliary Space: O(n)

Remove duplicate characters from a String in Scala Using foldLeft Method

This is the another method for removing duplicate characters from a String in Scala.

Below is the code in Scala.

Scala
//Creating Object object Gfg {      // defining removeDuplicates Method   def removeDuplicates(str: String): String = {        // Use foldLeft to iterate through each character of the string     str.foldLeft("") { (acc, char) =>      // If the accumulator already contains the character, return the accumulator       if (acc.contains(char)) acc       // Otherwise, append the character to the accumulator       else acc + char     }   }     // Defining Main Method   def main(args: Array[String]): Unit = {     val inputString = "Geeksforgeeks"     val outputString = removeDuplicates(inputString)     println(outputString)   } } 

Output:

Screenshot-(298)
Output

Explanation:

  • We define a function removeDuplicates that takes a string str as input and returns a string with duplicate characters removed.
    • We use foldLeft to iterate over each character in the input string.
    • For each character, we check if it already exists in the accumulator string (acc). If it does, we don't add it to the accumulator. If it doesn't, we append it to the accumulator.
    • Finally, we return the accumulator string, which contains unique characters.
  • We will create Main Method , call the function removeDuplicates and Print that return output.

Remove duplicate characters from a String in Scala Using Distinct Method

The distinct method provides a convenient way to remove duplicate characters from a string in Scala.

Below is the code of remove duplicate characters from a string using string.distinct Method.

Scala
// Creating Object object Gfg {   // defining a removeDuplicate Method   def removeDuplicates(str: String): String = {     // Using string.distinct method     str.distinct   }    //defining main Method   def main(args: Array[String]): Unit = {     val inputString = "Geeksforgeeks"     val outputString = removeDuplicates(inputString)     println(outputString)    } } 

Output:

Screenshot-(298)
Output

Explanation

  • The removeDuplicates function simply calls the distinct method on the input string str, which returns a new string with duplicate characters removed.
  • The main method is the entry point for the program.

Time Complexity: O(n)
Auxiliary Space: O(n)


Next Article
How to Remove Duplicate Elements from Array in Ruby?
author
cyrust8t7y
Improve
Article Tags :
  • Scala

Similar Reads

  • How to remove First and Last character from String in Scala?
    In this article, we will explore different approaches to removing the first and last character from a string in Scala. Table of Content Using substring methodUsing drop and dropRight methodsUsing substring methodIn this approach, we are using the substring method which takes two arguments the starti
    1 min read
  • How to Remove Special Characters from a String in Ruby?
    In this article, we will discuss how to remove special characters from a string in Ruby. In Ruby, special characters can be removed from a string using various methods. Special characters typically include punctuation marks, symbols, and non-alphanumeric characters. Let us explore different methods
    2 min read
  • How to Remove Double Quotes from String in Scala?
    This article focuses on discussing how to remove double quotes from a string in Scala. Removing double quotes consists of eliminating all occurrences of double quotes (") from a given string, resulting in a modified string without the double quotes. Remove Double Quotes from String in ScalaBelow are
    2 min read
  • How to Remove Last Character from String in Ruby?
    Removing the last character from a string in Ruby is a common task in various programming scenarios. Whether you need to manipulate user input, process file paths, or clean up data, there are several approaches to achieve this. This article focuses on discussing how to remove the last character from
    2 min read
  • How to Remove Duplicate Elements from Array in Ruby?
    This article focuses on discussing how to remove duplicate elements from an array in Ruby. In Ruby, an array is a fundamental data structure that stores a collection of elements in a specific order. Various methods and approaches can be used to remove duplicate elements from an array. Removing Dupli
    2 min read
  • How to Reduce Code Duplication in Scala?
    For this definition, duplicate code refers to a sequence of source code that appears more than once in a program, whether inside the same program or across various programs owned or maintained by the same company. For a variety of reasons, duplicate code is typically seen as bad. A minimal requireme
    8 min read
  • How to Merge Two Lists and Remove Duplicates in Scala?
    In Scala, lists are flexible data structures that are crucial for many programming tasks. They help in organizing and handling collections of items effectively. Knowing how to work with lists efficiently is vital for anyone coding in Scala. In this article, we'll explore how to combine two lists and
    3 min read
  • How to reverse a String in Scala?
    In this article, we will learn to reverse a string in Scala. Reverse of a string means changing its order so that the last character becomes the first, the second-to-last becomes the second, and so on, effectively flipping the string's sequence of characters. Examples: Input: S = "GeeksforGeeks"Outp
    3 min read
  • Program to convert Java Set of characters to a String in Scala
    A java Set of characters can be converted to a String in Scala by utilizing toString method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work. Now, lets see some examples and then discuss how it works in details. Example:1# // Scala progr
    2 min read
  • Remove All Adjacent Duplicates in String II
    Given a string s and an integer k, the task is to repeatedly delete k adjacent duplicates till no deletions are possible and then return the final string. On deletion of k adjacent duplicates, the left and right sides of the deleted substring is concatenated together. Examples: Input: s = "abcd", k
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences