Program to check : Non-Repeating Character in a String
Definition & Explanation
The task is to find non-repeating characters in a given string, i.e., characters that occur only once in the string.
More Description
Program Logic
- Create a dictionary (or hash map) to store the frequency/count of each character in the string.
- Iterate through each character in the string and update its count in the dictionary.
- Iterate through the string again and check if the count of each character is 1. If so, it means the character is non-repeating, so add it to a result string.
- Finally, return the result string containing all non-repeating characters.
C
Method 1 :
#include <stdio.h>
#include <string.h>
#define MAX_CHAR 256
void findNonRepeatingChars(char* str) {
int count[MAX_CHAR] = {0};
// Count frequency of each character
for (int i = 0; str[i]; i++)
count[str[i]]++;
// Print non-repeating characters
printf("Non-repeating characters: ");
for (int i = 0; i < MAX_CHAR; i++) {
if (count[i] == 1)
printf("%c ", i);
}
printf("\n");
}
int main() {
char str[] = "hello";
findNonRepeatingChars(str);
return 0;
}
Output :
C++
Method 1 :
#include <iostream>
#include <unordered_map>
using namespace std;
void findNonRepeatingChars(string str) {
unordered_map<char, int> freq;
// Count frequency of each character
for (char ch : str)
freq[ch]++;
// Print non-repeating characters
cout << "Non-repeating characters: ";
for (char ch : str) {
if (freq[ch] == 1)
cout << ch << " ";
}
cout << endl;
}
int main() {
string str = "hello";
findNonRepeatingChars(str);
return 0;
}
Output :
JAVA
Method 1 :
import java.util.HashMap;
import java.util.Map;
public class NonRepeatingChars {
public static void findNonRepeatingChars(String str) {
Map<Character, Integer> freq = new HashMap<>();
// Count frequency of each character
for (char ch : str.toCharArray())
freq.put(ch, freq.getOrDefault(ch, 0) + 1);
// Print non-repeating characters
System.out.print("Non-repeating characters: ");
for (char ch : str.toCharArray()) {
if (freq.get(ch) == 1)
System.out.print(ch + " ");
}
System.out.println();
}
public static void main(String[] args) {
String str = "hello";
findNonRepeatingChars(str);
}
}
Output :
Python
Method 1 :
def find_non_repeating_chars(s):
freq = {}
# Count frequency of each character
for char in s:
freq[char] = freq.get(char, 0) + 1
# Print non-repeating characters
print("Non-repeating characters:", end=" ")
for char in s:
if freq[char] == 1:
print(char, end=" ")
print()
# Test the function
s = "hello"
find_non_repeating_chars(s)
Output :
Non-repeating characters: h e o