Finding the First Repeating Character in a String
Have you ever wanted to find the first repeating character in a string? Maybe you need to remove duplicates or simply want to know if there are any repeated letters in a word or phrase.
In this article, we’ll explore two methods for finding the first repeating character in a string: the hashing technique and the brute-force method.
Hashing Technique
The hashing technique involves creating a hash table and scanning the characters, inserting them into the table. The hash table is essentially an array of buckets, each containing a linked list of characters that hash to the same bucket index.
To insert a character into the table, we first hash it to get an index, then insert it into the linked list at that index. If we encounter a character that is already in the table, we know it’s the first duplicate.
Creating a Hash Table
To create a hash table, we first need to decide on the size of the table. A good rule of thumb is to make the size of the table about twice the size of the input, to minimize collisions.
We’ll also need a hash function that maps each character to a unique index in the table. One popular hash function is the modulo function, which takes the ASCII value of the character, divides it by the size of the table, and takes the remainder:
int hash(char c) { return c % TABLE_SIZE; }
Scanning and Inserting Characters
Once we have a hash table and a hash function, we can start scanning the characters in the string. For each character, we hash it to get an index in the table, then insert it into the linked list at that index.
If we encounter a character that is already in the table, we know it’s the first duplicate. Here’s some sample code:
char firstDuplicate(string s) {
unordered_set
for (char c : s) {
if (seen.count(c)) {
return c;
}
seen.insert(c);
}
return ‘