Imports System
Module Program
''' <summary>
''' Finds the last repeated character in a string.
'''
''' Examples:
''' "abca" -> "a"c
''' "abcbd" -> "b"c
''' "abcde" -> Nothing
''' "abcdxypcbop" -> "p"c
''' "abcdxypcbadom" -> "d"c
'''
''' Time Complexity: O(n)
''' Space Complexity: O(1)
''' </summary>
''' <param name="input">The input string.</param>
''' <returns>
''' The last repeated character, or Nothing if none exists.
''' </returns>
Function FindLastRepeatedCharacter(input As String) As Char?
If String.IsNullOrEmpty(input) Then
Return Nothing
End If
' Frequency table for ASCII characters.
Dim frequency(255) As Integer
' Count occurrences of each character.
For Each ch As Char In input
frequency(Convert.ToInt32(ch)) += 1
Next
' Traverse from right to left.
For i As Integer = input.Length - 1 To 0 Step -1
Dim ch As Char = input(i)
If frequency(Convert.ToInt32(ch)) > 1 Then
Return ch
End If
Next
' No repeated character found.
Return Nothing
End Function
Sub Main()
Console.WriteLine(FindLastRepeatedCharacter("abca"))
Console.WriteLine(FindLastRepeatedCharacter("abcbd"))
Dim result As Char? = FindLastRepeatedCharacter("abcde")
Console.WriteLine(If(result.HasValue, result.Value, " "c))
Console.WriteLine(FindLastRepeatedCharacter("abcdxypcbop"))
Console.WriteLine(FindLastRepeatedCharacter("abcdxypcbadom"))
End Sub
End Module
' run:
'
' a
' b
'
' p
' d
'
'