ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

KQL: Find First Recurring Character in a String

Kusto Query Language (KQL)

Goal -- WPM

Ready
Exercise Algorithm Area
1let findFirstRecurringChar = (inputString: string) {
2let charCounts = bag_pack_array(dynamic(split(inputString, '')) | summarize count() by tos(tostring(current_item)));
3let recurringChars = charCounts | where count_ > 1 | project char = key;
4let firstRecurring = "";
5
6if (strlen(inputString) == 0) {
7print "";
8} else {
9foreach (char in recurringChars) {
10let index = indexof(inputString, char);
11if (indexof(substring(inputString, index + 1), char) != -1) {
12if (firstRecurring == "" or indexof(inputString, char) < indexof(inputString, firstRecurring)) {
13firstRecurring = char;
14}
15}
16}
17print firstRecurring;
18}
19};
20
21findFirstRecurringChar("programming")
Algorithm description viewbox

KQL: Find First Recurring Character in a String

Algorithm description:

This KQL function identifies the first character that repeats within an input string. It's useful for tasks like data validation, where you might need to detect duplicate entries or patterns in textual data. For example, in log analysis, you could use this to find the first character that appears twice in an error message, helping to pinpoint specific issues.

Algorithm explanation:

The function `findFirstRecurringChar` takes a string and returns the first character that occurs more than once. It first splits the string into individual characters and counts their occurrences using `bag_pack_array` and `summarize count()`. Then, it filters these counts to identify characters that appear more than once. The function iterates through these recurring characters, finding the index of their first appearance in the original string. It keeps track of the character with the smallest index, which corresponds to the first recurring character. Edge cases like an empty input string or a string with no recurring characters are handled by returning an empty string. The time complexity is roughly O(N*M) where N is the length of the string and M is the number of unique characters, due to repeated string searches. Space complexity is O(M) for storing character counts.

Pseudocode:

function findFirstRecurringChar(inputString):
  if inputString is empty:
    return ""

  create a map to store character counts
  for each character in inputString:
    increment count for character in map

  create a list of recurring characters (count > 1)
  initialize firstRecurringChar = ""
  initialize minIndex = infinity

  for each recurringChar in recurring characters:
    find index of first occurrence of recurringChar in inputString
    if index < minIndex:
      minIndex = index
      firstRecurringChar = recurringChar

  return firstRecurringChar