Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# 387. First Unique Character in a String

[LeetCode problem 387](https://leetcode.com/problems/first-unique-character-in-a-string/)

- **Difficulty**: Easy
- **Tags**: hash-table, string, queue, counting

## Description

Given a string `s`, return the index of the first non-repeating character,
or `-1` if none exists.
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#include "solution.hpp"

#include <array>

namespace leetcode::p0387 {

int solve(const std::string& s) {
std::array<int, 26> counts{};

for (char c : s) {
++counts.at(static_cast<std::size_t>(c - 'a'));
}

for (std::size_t i = 0; i < s.size(); ++i) {
if (counts.at(static_cast<std::size_t>(s[i] - 'a')) == 1) {
return static_cast<int>(i);
}
}

return -1;
}

} // namespace leetcode::p0387
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#pragma once

#include <string>

namespace leetcode::p0387 {

// optimized: O(n) time, O(1) space — fixed 26-slot count array (assumes
// lowercase English letters, per the problem's constraints), two passes.
int solve(const std::string& s);

} // namespace leetcode::p0387
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#include <catch2/catch_test_macros.hpp>

#include "solution.hpp"

TEST_CASE("Problem 387", "[p0387]") {
CHECK(leetcode::p0387::solve("leetcode") == 0);
CHECK(leetcode::p0387::solve("loveleetcode") == 2);
CHECK(leetcode::p0387::solve("aabb") == -1);
}
17 changes: 0 additions & 17 deletions swift/387.swift

This file was deleted.

Loading