×

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

Java Switch string

A multi-way branch statement is the switch statement. It offers a simple method for allocating execution to various code sections according to the expression's value. Primitive data types, including bytes,...

3 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

How to Create Immutable Classes in Java

Introduction Java is a programming language that is entirely object-oriented, and everything in it is seen as an object. And the blueprint or template of these objects are classes. Several classes...

3 minutes read.

Java Throw and Throws Keyword

Exceptions in Java enable us to construct high-quality programs where faults are checked at compile time rather than run time and where we may define unique exceptions that make code...

6 minutes read.

Convert IP to Binary in Java

Fundamental conversion, such as going from binary to decimal or vice versa, is a crucial activity in computers. Understanding IP addressing and subnetting is crucial for networking. The primary networking...

4 minutes read.

Java Math subtractExact() Method

The subtractExact() method of Java Math class returns mathematical difference of the specified two arguments, throwing an exception if the result overflows int or long. Syntax: public static int subtractExact (int x,...

1 minute read.

Deadlock Prevention and avoidance in Java

This tutorial will discuss deadlock prevention and Avoidance in Java programming language. Introduction Multithreading in Java includes deadlock. We can multitask by running several threads concurrently in the multithreading environment. Deadlock occurs...

4 minutes read.

Bubble Sort in Java

Bubble Sort in Java Bubble sort isalso known as sinking sort. It is one of the simplest sorting algorithms. In the bubble sort algorithm, the given array is traversed from left...

5 minutes read.

Empty Statement in Java

The three sorts of statements in Java are control, expression, and declaration statements. Additionally, another statement is referred to as an empty statement. In this section, we will discuss about...

4 minutes read.

Uses of Java

Java is used in many real-world Java applications, including technologies and tools. This Java programming language has become the backbone for developing many applications. In areas like embedded systems and...

3 minutes read.

Maximizing Profit in Stock Buy Sell in Java

In this tutorial, we will deal with a popular problem, a favourite of interviewers. The problem is named as Maximising profit in stock Buy Sell. we will see certain approaches...

6 minutes read.

Anagram Program in Java using String

Anagram Program in Java Anagrams are those words that are generated by rearrangement of the letters of another phrase or word. Usually, while doing the rearrangement, the original letters are used...

8 minutes read.

Java AWT

Java AWT Java programming is used to develop different types of applications like window-based applications, web applications, Enterprise applications, or mobile applications. For creating standalone applications, Java AWT API is used....

11 minutes read.

Sudoku in Java

Sudoku is a combinatorial-number-placement puzzle with a logic-based approach. The goal of a traditional Sudoku puzzle is to fill in the numbers on a 9 by 9 grid so that...

6 minutes read.

How to calculate time complexity of any program in Java

Java : Java's syntax and principles are derived from the C and C++ languages. We know that java is one of the programming language. The main feature of java which is...

3 minutes read.

Java Maven Silicon

Maven is a build automation tool that is mostly used for Java applications. It allows you to manage the build, reporting, and documentation of a project from the central location. Maven provides...

4 minutes read.

Difference between final, finally, and finalize()

Difference between final, finally, and finalize() In Java, final, finally and finalize sound similar they are totally different in functionality. Final and finally are the two keywords but the finalize is...

4 minutes read.

Java String copyValueOf() method

copyValueOf() method returns a String that holds the character sequence of the character array. Syntax: copyValueOf(char[] data) Parameters: data : the character array i.e. String Returns: It returns a String that contains the characters of the...

2 minutes read.

Java Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates. HashSet: This class stores its elements in hash tables. It uses the hashCode()...

3 minutes read.

This Operator Using in Java

this keyword in Java has a wide range of applications. this reference variable in Programming language refers to the object of interest. This keyword is used in Java. this keyword is...

5 minutes read.