Skip to main content

Dart: Find the first recurring character

In this problem, we need to find the first recurring character in a string. For example, if we have the string ABCABC, the first recurring character is A.

Examples

Below are several examples with the expected result to test if our solution is correct:

Text: ABCABC
Result: A
Text: ABBA
Result: B
Text: AB😀D😀BA
Result: 😀
Text: ABCDE
Result: null

Solution

In the following solution, we will iterate through each of the characters and store them in a Set. In each iteration, we will check if the character exists in the Set or not. If it exists, then we have found the first recurring character.

Let's see how the solution works:

Iteration 1: check if A exists in the set, if not, store it

Iteration 1: check if A exists in the set, if not, store it


Iteration 2: check if B exists in the set, if not, store it

Iteration 2: check if B exists in the set, if not, store it


Iteration 3: check if C exists in the set, if not, store it

Iteration 3: check if C exists in the set, if not, store it


Iteration 4: check if A exists in the set, if it does, the recurring character is A

Iteration 4: check if A exists in the set, if it does, the recurring character is A

Now that we know how the solution works, it's time to code it:

final text = 'ABCABC';

// Set to store the characters
final recurring = <int>{};

// Helper variable to store
// the first recurring character
int? result;

// Iterate through each character
for (final character in text.runes) {

// If the set contains the character we
// have found the first recurring character
if (recurring.contains(character)) {
// Store the recurring character
// in the helper variable
result = character;

// End the execution of the for loop
break;
}

// If the set does not contain the
// character we add it to the set
recurring.add(character);
}

// Print the result to the terminal
if (result == null) {
print('No recurring character');
} else {
print(
'The first recurring character is: ${String.fromCharCode(result)}',
);
}
info

In Dart, if we want to access the characters of a String, we have to use the Runes API. A "rune" is an integer that represents a Unicode code point.

You can run the DartPad code to see the results:

Conclusion

As in any programming problem, there are many different ways to approach it, but from my point of view, one of the simplest ways is using a Set. If you know a different way, you can leave it in the comments.