Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,8 @@
* Two City Scheduling
* [Test Two City Scheduling](https://github.com/BrianLusina/PythonSnips/blob/master/algorithms/greedy/two_city_scheduling/test_two_city_scheduling.py)
* Hash Table
* First Unique Character
* [Test First Unique Character](https://github.com/BrianLusina/PythonSnips/blob/master/algorithms/hash_table/first_unique_character/test_first_unique_character.py)
* Ransom Note
* [Test Ransom Note](https://github.com/BrianLusina/PythonSnips/blob/master/algorithms/hash_table/ransom_note/test_ransom_note.py)
* Heap
Expand Down
35 changes: 35 additions & 0 deletions algorithms/hash_table/first_unique_character/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# First Unique Character

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

## Examples

Example 1:

```text
Input: s = "leetcode"
Output: 0
Explanation:
The character 'l' at index 0 is the first character that does not occur at any other index.
```

Example 2:

```text
Input: s = "loveleetcode"
Output: 2
```

Example 3:

```text
Input: s = "aabb"
Output: -1
```

## Constraints

- 1 <= `s.length` <= 10^5
- `s` consists of lowercase English letters
- There are no spaces in the string.

10 changes: 10 additions & 0 deletions algorithms/hash_table/first_unique_character/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from collections import Counter


def first_unique_character(s: str) -> int:
frequency = Counter(s)

for idx, letter in enumerate(s):
if frequency[letter] == 1:
return idx
return -1
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import unittest
from parameterized import parameterized
from algorithms.hash_table.first_unique_character import first_unique_character

FIRST_UNIQUE_CHARACTER_TEST_CASES = [
("leetcode", 0),
("loveleetcode", 2),
("aabb", -1),
("baefeab", 3),
("aabbcc", -1),
("dajhfiuebdafsdhdgaj", 5),
("xyurtwxwtryua", 12),
("aeiouqwertyauieotweryqq", -1),
("awsjuhfajwfnkag", 2),
]


class FirstUniqueCharacterTestCase(unittest.TestCase):
@parameterized.expand(FIRST_UNIQUE_CHARACTER_TEST_CASES)
def test_first_unique_character(self, s: str, expected: int):
actual = first_unique_character(s)
self.assertEqual(expected, actual)


if __name__ == '__main__':
unittest.main()
Loading