WAP To Find Out First Repeated Character In A String

Find Out First Repeated Character In A String: Welcome to the captivating world of string manipulation and coding challenges! In this exciting topic, we’ll explore the intriguing problem of finding the first repeated character in a given string. Imagine a scenario where you’re presented with a text, and your task is to swiftly identify the first character that appears more than once in the string. This seemingly simple yet powerful problem has applications in various real-world scenarios, such as detecting duplicate entries in databases, validating user inputs, and optimizing search algorithms.

Throughout this journey, we’ll walk you step-by-step through different approaches to efficiently solve this problem using Java. We’ll dive into fundamental programming concepts, such as loops, conditional statements, and data structures, while gaining valuable insights into algorithm design. Whether you’re a Java beginner or a seasoned developer, this exploration promises to enhance your problem-solving skills and deepen your understanding of string manipulation.

Our goal is to empower you with the knowledge and techniques to tackle this challenge with elegance and confidence. We’ll demonstrate how simple yet effective coding can lead to powerful solutions. Are you ready to embark on this thrilling adventure to find the first repeated character in a string? Let’s unravel the mysteries of string analysis and become proficient in text processing.

Find Out First Repeated Character In A String

package com.softwaretestingo.interviewprograms;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class InterviewPrograms95 
{
	//Write a program to find out First repeated character in a string
	private static char findFirstRepeatedChar(String str) 
	{
		int n = str.length();
		char ans = ' ';
		int index = Integer.MAX_VALUE;
		for (int i = 0; i < n; i++) 
		{
			char temp = str.charAt(i);

			// Checking that character in temp repeats or not by running a for loop
			for (int j = i + 1; j < n; j++)
			{
				if (str.charAt(j) == temp)
				{

					// if the index where it repeated is less than the index of the previously
					// repeated character then store this character in ans variable
					// and its index where it repeated in index variable
					if (j < index)
					{
						index = j;
						ans = str.charAt(j);
					}
				}
			}
		}
		return ans;
	}

	public static void main(String[] args) throws IOException 
	{
		String str;

		// create an object of Scanner
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		System.out.println("Enter the string");
		str=br.readLine();

		System.out.println("The First Repeated Character: "+findFirstRepeatedChar(str));
		br.close();
	}
}

Output

Enter the string
softwaretestingo
The First Repeated Character: t

In this Java program, we aim to find the first repeated character in a given string. The program efficiently searches the string for duplicate characters, returning the first character that appears more than once. Let’s break down the code step by step to help Java beginners understand it:

  1. Import Statements: The program starts with import statements to include the required BufferedReader and IOException classes from the Java standard library.
  2. Class and Method Declaration: The program defines a class named InterviewPrograms95. Inside the class, there is a private static method findFirstRepeatedChar, responsible for finding the first repeated character in the input string. The main method serves as the entry point of the program.
  3. findFirstRepeatedChar Method: This method takes a single parameter str, which represents the input string to be analyzed. The method returns a character, which is the first repeated character found in the string.
  4. Searching for Repeated Characters: Inside the findFirstRepeatedChar method, the program initializes variables ans to store the first repeated character and index to store the index of its occurrence.The method then uses two nested loops to search for repeated characters in the string. The outer loop iterates through each character of the string, while the inner loop checks the characters that appear after the current character.When a repeated character is found, the program compares its index with the index of the previously repeated character. If the current character’s index is lower, it means it appeared earlier in the string, so the program updates the ans and index variables accordingly.
  5. User Input and Output: In the main method, the program prompts the user to enter a string using System.out.println(). The user’s input is obtained using a BufferedReader, which reads input from the console. The input string is then stored in the str variable.The program then calls the findFirstRepeatedChar method with the input string str and displays the first repeated character using System.out.println().

In summary, this program efficiently identifies and returns the first repeated character in a given string. It showcases how to use nested loops and conditional statements to search for duplicates in the text. Java beginners can learn from this code about handling string manipulation tasks and creating an optimized solution to find a repeated character within a string.

Alternative Way 1:

package com.softwaretestingo.interviewprograms;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
public class InterviewPrograms95_1 
{
	//Write a program to find out First repeated character in a string
	private static char findFirstRepeatedChar(String str) 
	{
		char[] arr = str.toCharArray();

		HashSet<Character> h = new HashSet<>();

		for (int i=0; i<=str.length()-1; i++)
		{
			char c = arr[i];

			if (h.contains(c))
				return c;

			else
				h.add(c);
		}
		return 0;
	}

	public static void main(String[] args) throws IOException 
	{
		String str;

		// create an object of Scanner
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		System.out.println("Enter the string");
		str=br.readLine();

		System.out.println("The First Repeated Character: "+findFirstRepeatedChar(str));
		br.close();
	}
}

Output

Enter the string
softwaretestingo
The First Repeated Character: t

In this alternative Java program, we continue our quest to find the first repeated character in a given string. This time, we adopt a more concise and efficient approach using a HashSet, a data structure that guarantees unique elements. Let’s explore the code step by step:

  1. Import Statements: The program starts with import statements to include the required BufferedReader, IOException, and HashSet classes from the Java standard library.
  2. Class and Method Declaration: The program defines a class named InterviewPrograms95_1. Inside the class, there is a private static method findFirstRepeatedChar, responsible for finding the first repeated character in the input string. The main method serves as the entry point of the program.
  3. findFirstRepeatedChar Method: This method takes a single parameter str, which represents the input string to be analyzed. The method returns a character, which is the first repeated character found in the string.
  4. Using HashSet: Inside the findFirstRepeatedChar method, the program converts the input string into a character array arr using toCharArray(). It then creates an empty HashSet named h, which will be used to store unique characters encountered so far.
  5. Searching for Repeated Characters: The method then iterates through the character array arr. For each character c, it checks if it already exists in the HashSet h. If h contains the character, it means the character is repeated, and the method returns that character as the first repeated character.If the character is not present in h, it is added to the HashSet, indicating that it is a new unique character.
  6. User Input and Output: In the main method, the program prompts the user to enter a string using System.out.println(). The user’s input is obtained using a BufferedReader, which reads input from the console. The input string is then stored in the str variable.The program then calls the findFirstRepeatedChar method with the input string str and displays the first repeated character using System.out.println().

In summary, this Java program efficiently identifies and returns the first repeated character in a given string using a HashSet. It showcases how using appropriate data structures can lead to more concise and optimized solutions to the same problem. Java beginners can learn from this code about the advantages of using a HashSet to keep track of unique elements and efficiently find duplicates within a string. Happy coding!

Alternative Way 2:

package com.softwaretestingo.interviewprograms;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class InterviewPrograms95_2 
{
	//Write a program to find out First repeated character in a string
	private static String findFirstRepeatedChar(String str) 
	{
		// code here
		int a[] = new int[26];

		for (int i = 0; i<str.length(); i++) {
			char ch = str.charAt(i);

			if (a[ch - 'a'] != 0)
				return Character.toString(ch);
			else
				a[ch - 'a']++;
		}
		return "-1";
	}

	public static void main(String[] args) throws IOException 
	{
		String str;

		// create an object of Scanner
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		System.out.println("Enter the string");
		str=br.readLine();

		System.out.println("The First Repeated Character: "+findFirstRepeatedChar(str));
		br.close();
	}
}

Output

Enter the string
softwaretestingo
The First Repeated Character: t

In this Java program, we continue our quest to find the first repeated character in a given string using a different approach. This time, we utilize an array of integers to keep track of character occurrences, efficiently reducing the space complexity. Let’s break down the code step by step:

  1. Import Statements: The program starts without any import statements, as it doesn’t require any external classes from the Java standard library.
  2. Class and Method Declaration: The program defines a class named InterviewPrograms95_2. Inside the class, there is a private static method findFirstRepeatedChar, responsible for finding the first repeated character in the input string. The main method serves as the entry point of the program.
  3. findFirstRepeatedChar Method: This method takes a single parameter str, which represents the input string to be analyzed. The method returns a string, which is the first repeated character found in the string. If no repeated character is found, it returns “-1”.
  4. Using an Array to Track Occurrences: Inside the findFirstRepeatedChar method, the program initializes an integer array a of size 26. This array will be used to keep track of the occurrences of lowercase English alphabet characters.
  5. Searching for Repeated Characters: The method then iterates through the input string str. For each character ch, it checks if its corresponding position in the array a[ch – ‘a’] is not equal to 0. If it is not 0, it means the character has already occurred before, and the method returns that character as the first repeated character.If the character has not occurred before, it increments the value in a[ch – ‘a’], indicating that the character has been encountered.
  6. User Input and Output: In the main method, the program prompts the user to enter a string using System.out.println(). The user’s input is obtained using a BufferedReader, which reads input from the console. The input string is then stored in the str variable.The program then calls the findFirstRepeatedChar method with the input string str and displays the first repeated character using System.out.println().

In summary, this Java program efficiently identifies and returns the first repeated character in a given string using an array to keep track of character occurrences. This approach effectively reduces the space complexity compared to using a HashSet. Java beginners can learn from this code how to optimize space usage while solving similar problems and how to efficiently handle character occurrences in a string. Happy coding!

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment