First Unique Character in a String
💻 coding

First Unique Character in a String

1 min read 179 words
1 min read
ShareWhatsAppPost on X
  • 1The task is to find the first non-repeating character in a given string and return its index.
  • 2If no non-repeating character exists, the function should return -1.
  • 3The solution has a time complexity of O(n) and a space complexity of O(n).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to find the first non-repeating character in a given string and return its index."

First Unique Character in a String

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.

Note: You may assume the string contains only lowercase English letters.

Solution:

using System;
using System.Collections.Generic;
using System.Text;

namespace LeetCode.AskGif.Easy.String
{
 public class FirstUniqCharSoln
 {
 public int FirstUniqChar(string s)
 {
 var map = new Dictionary<char, int>();
 for(int i=0; i < s.Length; i++)
 {
 if (map.ContainsKey(s[i]))
 {
 map[s[i]]++;
 }
 else
 {
 map.Add(s[i], 1);
 }
 }

 for (int i = 0; i < s.Length; i++)
 {
 if (map[s[i]] == 1)
 {
 return i;
 }
 }

 return -1;
 }
 }
}

Time Complexity: O(n)

Space Complexity: O(n)

Unit Tests:

using LeetCode.AskGif.Easy.String;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;

namespace CodingUnitTest.Easy.String
{
 [TestClass]
 public class FirstUniqCharSolnTests
 {
 [TestMethod]
 public void FirstUniqCharSoln_First()
 {
 var s = "leetcode";
 var output = 0;
 var res = new FirstUniqCharSoln().FirstUniqChar(s);

 Assert.AreEqual(res, output);
 }

 [TestMethod]
 public void FirstUniqCharSoln_Second()
 {
 var s = "loveleetcode";
 var output = 2;
 var res = new FirstUniqCharSoln().FirstUniqChar(s);

 Assert.AreEqual(res, output);
 }
 }
}

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 4 June 2020 · 1 min read · 179 words

Part of AskGif Blog · coding

You might also like