Home > leetcode > First Unique Character in a String (Swift)

First Unique Character in a String (Swift)


Today we solve a very popular 'kata' on Leetcode #387 First Unique Character in a String

Difficulty level: Easy

Related Topics: Hash Table, String

Disclaimer: You might have different results in Runtime and Memory Usage, it's okay 🤣 it how it works.


Description:

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.

And your playground looks like this:

class Solution {
    func firstUniqChar(_ s: String) -> Int {

    }
}

I'll walk you thru the process of how I solved it.

Solution 1

At first, we'll count how many times a letter appears in the string. And we store results into an hashtable.

var letterCounter: [Character : Int] = [:]

Now use a loop and store result in letterCounter

for char in s {
    letterCounter[char, default: 0] += 1
}

And our hashtable looks like this:

["t": 1, "l": 1, "c": 1, "d": 1, "o": 1, "e": 3]

Now we have to return the first unique character, but as you can see hashtable doesn't guarantee order. That's why we have to loop over the string and find the first letter with value 1. Or return -1if there is no unique character.

for (index, char) in s.enumerated() {
    if letterCounter[char] == 1 {
        return index
    }
}

We go thru string letter by letter and check where this letter has value 1 in letterCounter if so, we return its number.

Let's submit it and see the result.

Runtime: 304 ms, faster than 58.60% of Swift online submissions for First Unique Character in a String.
Memory Usage: 21.3 MB, less than 54.03% of Swift online submissions for First Unique Character in a String.

Solution 2

This solution base on checking an index of a character of the string.

I convert string to array

let characters = Array(s)

And then I loop over the array and compare the first and last index for a character.

for char in characters {
        if(characters.firstIndex(of: char) == characters.lastIndex(of: char)) {
           ...
        }
    }

If they are the same, that means it's a unique one and I return this character.

return characters.firstIndex(of: char) ?? -1

Full solution

func firstUniqChar(_ s: String) -> Int {

    let characters = Array(s)

    for char in characters {
        if(characters.firstIndex(of: char) == characters.lastIndex(of: char)) {
            return characters.firstIndex(of: char) ?? -1
        }
    }

    return -1
}

Let's submit it and see the result.

Runtime: 2128 ms, faster than 5.19% of Swift online submissions for First Unique Character in a String.
Memory Usage: 20.6 MB, less than 100.00% of Swift online submissions for First Unique Character in a String.

Oh, not the best runtime, right? 🥵 Let's make it better!

© 2021, Andrew Losseff