Skip to content

387 First Unique Character ✅

Leetcode

::: tip Key points 💡

  • Character check map Dictionary(), where value = -1 if key already exists else index :::

Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.

Examples:

s = "leetcode"
return 0.

s = "loveleetcode"
return 2.

C# Solution

using System;
using System.Collections.Generic;

namespace Algorithms.Simple
{
  public class FirstUniqueCharacter
  {
    public static int GetIndex(string stringInput)
    {
      var charCheckMap = new Dictionary<char, int>();
      var foundIndex = -1;

      for (var i = 0; i < stringInput.Length; i++)
      {
        charCheckMap[stringInput[i]] = charCheckMap.ContainsKey(stringInput[i]) ? -1 : i;
      }

      foreach (var kvp in charCheckMap)
      {
        if (kvp.Value > -1)
        {
          foundIndex = kvp.Value;
          break;
        }
      }

      return foundIndex;
    }
  }
}

C# Tests

using Algorithms.Simple;
using Xunit;

namespace AlgorithmTests.Simple
{
  public class FirstUniqueCharacterTests
  {
    [Fact]
    public void Test()
    {
      Assert.Equal(0, FirstUniqueCharacter.GetIndex("leetcode"));
      Assert.Equal(2, FirstUniqueCharacter.GetIndex("loveleetcode"));
    }
  }
}