0% found this document useful (0 votes)
5 views

first non repeating character in string

The document outlines an approach to find the first non-repeating character in a string using a queue and a frequency count array for lowercase characters. It describes a Java program that processes the string character by character, updating the queue and frequency counts, and outputs the first non-repeating character or -1 if none exist. The time complexity of the solution is O(n).

Uploaded by

Kaushal Bhatt
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

first non repeating character in string

The document outlines an approach to find the first non-repeating character in a string using a queue and a frequency count array for lowercase characters. It describes a Java program that processes the string character by character, updating the queue and frequency counts, and outputs the first non-repeating character or -1 if none exist. The time complexity of the solution is O(n).

Uploaded by

Kaushal Bhatt
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

first non repeating character in string

Approach:

Create a count array of size 26(i am assuming only lower case characters are
present) and initialize it with zero.
Create a queue of char datatype.
Store each character in queue and increase its frequency in the hash array.
For every character of stream, we check front of the queue.
If the frequency of character at the front of queue is one, then that will be the
first non-repeating character.
Else if frequency is more than 1, then we pop that element.
If queue became empty that means there are no non-repeating characters so we will
print -1.

// Java Program for a Queue based approach


// to find first non-repeating character

import java.util.LinkedList;
import java.util.Queue;

public class NonReapatingCQueue {


final static int MAX_CHAR = 26;

// function to find first non repeating


// character of stream
static void firstNonRepeating(String str)
{
// count array of size 26(assuming
// only lower case characters are present)
int[] charCount = new int[MAX_CHAR];

// Queue to store Characters


Queue<Character> q = new LinkedList<Character>();

// traverse whole stream


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

// push each character in queue


q.add(ch);

// increment the frequency count


charCount[ch - 'a']++;

// check for the non repeating character


while (!q.isEmpty()) {
if (charCount[q.peek() - 'a'] > 1)
q.remove();
else {
System.out.print(q.peek() + " ");
break;
}
}
if (q.isEmpty())
System.out.print(-1 + " ");
}
System.out.println();
}
// Driver function
public static void main(String[] args)
{
String str = "aabc";
firstNonRepeating(str);
}
}

time complexity is O(n)

You might also like