×

Program to find the duplicate characters in a string

Problem statement

You have given with a string and your task is to find out the repeated characters from the string and print them. If no character is repeated, then you need to output “no character is repeated in the given string”.

Example

Consider the string “javaprogramming”, the repeated characters are a, r, g, m. Therefore, you need to output a, r, g, m.

import java.io.*;
import java.util.*;


public class Main
{
public static void main (String [] args) {

Scanner sc = new Scanner ( System.in ) ;
HashMap <Character,Integer> p = new HashMap<> ();
// creating hashmap to store the individual character as Key
// and storing count of each character as value of hashmap
                  System.out.println(“enter the string:”);
String s = sc.next ();
for (int i = 0; i < s.length (); i++)
{
    if (p.containsKey (s.charAt (i)))
    {
        p.put (s.charAt (i),p.get (s.charAt (i))+1);
   // increment count if character already exists in hashmap
        
    }
    else
    {
        p.put (s.charAt (i),1);
        // inerting characters into hashmap
        
    }
}
System .out. println ("repeated characters are");
for (int i = 0; i < s.length (); i++)
{
    if (p.get (s.charAt (i)) >1)
    {
        System .out. println (s.charAt(i));
        p.put (s.charAt (i),0);
        // making the count of traversed character to zero 
        // to prevent repating of same character (on output ).
    }
    else
    { 
           System.out.println("no chacter is repeated in the given string");
        
    }
}
    
}
}

Time complexity for this code is O(n*log(n)) where n is the length of the string and it take O(log(n)) for the insertion into the map.

Space complexity of this code is O(k), k is the size of map.

Program To Find The Duplicate Characters In A String

Example 2

import java .io. *;
import java .util.  *;


public class Main {  
     public static void main (String [ ] args) {
        Scanner sc = new Scanner (System.in);
        System.out.println("enter the string:");
        String str = sc.next ();  
        int count ;  
        int found=0;
          
        // Convert the given string into character array  
        char str1 [ ] = str.toCharArray ();  
          
        System.out.println ("characters repeated in the given string: ");  
        // Counts each character present in the string  
        for (int i = 0; i <str1.length; i++) {  
            count = 1;  
            for (int j = i+1 ; j < str1.length;  j++) {  
                if (str1 [ i ] == str1 [ j ]) {  
                    count++;  
                    // Set str [j] to 0 to avoid printing visited character  
                    str1 [ j ] ='0';  
                }  
            }  
            // A character is considered as duplicate if count is greater than 1  
            if (count > 1 && str1[i] != '0')  
            {
                System.out.println (str1 [ i ] ); 
                found++;
              }
            
        }  
        if(found==0)
        {
            System.out.println ("no character is repeated in the given string");
        }
    }  
}  

Output

Program To Find The Duplicate Characters In A String

If user gives an input that string does not have repeated character like browncat, the output will loke like shown in the below:

Program To Find The Duplicate Characters In A String

Related Topics

Local Minima in Java

An Array Finding a local minimum in an array a[0. m-1] of different integers is the job. A[i] is considered a local minimum if it is smaller than two of its...

4 minutes read.

Unicode System in Java

In this tutorial, we will understand the meaning and emergence of the Unicode system in java. The Unicode system is one of the important and useful features in the world...

6 minutes read.

Java import packages

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Bouncy Number in Java

We will define bouncy numbers in this section and write Java programmes to determine whether a specific number is bouncy. Java coding exams and academic assignments usually inquire about the...

3 minutes read.

Java Abstraction

Java Abstraction Abstraction is an advanced feature of Java to make it transparent. The main motive behind the abstraction is to deal with ideas, not with events. Abstraction is a process...

4 minutes read.

Why to use Enum in Java?

In this article, you will be acknowledged about the Enum in java, its uses and mainly its purpose. Enum has various functionalities. Each of them will be discussed. Enum In a computer...

3 minutes read.

Thread Scheduler in java

Scheduling: it is defined as the execution of multiple threads on a single CPU in some order is called scheduling. Preemptive-priority scheduling: This algorithm schedules threads based on their priority relative to other...

11 minutes read.

Java finally

Java finally: There are some statements in a program whose execution is extremely important. For example, closing of a database connection. Statements that do the closing of the database connection...

5 minutes read.

JDBC vs ODBC

Difference Between JDBC and ODBC ODBC: ODBC (Open Database Connectivity) is the accepted method for accessing databases among organisations and programmers. A database is linked to other programmes, such as word processors, spreadsheets,...

4 minutes read.

Internal Working of ArrayList in Java

Java's version of a resizable array is called ArrayList. The dynamic growth of an array list ensures that there is always room for new elements. ArrayList's backing data structure is...

8 minutes read.

Difference between Aggregation and Composition in Java

What is Aggregation? Before we start discussing Aggregation, we have to know some general information about our classes in java. Generally we have two members in our classes , the first...

8 minutes read.

Add numbers represented by Linked Lists in Java

For calculating the sum of the two numbers that are represented by a linked list, and then store the result in a new linked list. A linked list's head node...

7 minutes read.

Differences and Similarities between HashSet, LinkedHashSet and TreeSet in Java

HashSet Class: The HashSet is a class that executes the Setpoint of interaction. It is utilised to store the items in a hashtable; a hashtable is an information structure which holds...

10 minutes read.

Bean class in Java

The web applications that are created with the help of the JSP or Java Server Pages generally have fairly more functionality than the web pages that specifically are created with...

5 minutes read.

Bedrock vs Java

The popularity of Minecraft, a sandbox video game, has skyrocketed. The scope, level of complexity, and variety of gameplay in this game are enormous, and user-generated content has helped to...

4 minutes read.

Java vs Scala

Java : Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say...

4 minutes read.

How to Convert Decimal to Binary in Java

How to Convert Decimal to Binary in Java There are two methods to convert Decimal to Binary. Using toBinaryString() method Using user-defined logic Using Integer.toBinaryString() The toBinaryString() is a static method of Integer...

2 minutes read.

Group by in Java 8

By using this groupingBy() method, developers can directly able to perform the "GROUP BY" operation. The thing is, now, the Java 8 programming language allows the programmers to do this...

3 minutes read.

Java Math incrementExact() Method

The incrementExact() method of Math class returns the argument incremented by one, throwing an exception if the result overflows an int or a long. Syntax: public static int incrementExact (int a)public static...

1 minute read.

Web Service Response Time Calculation in Java

Administration response time or reaction time is the typical measure of time it takes for a solicitation to be handled by a PC framework, like your organization switch. In the...

4 minutes read.