#9286Medium

FirstUniqueCharIndex

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1. (Inspired by [leetcode 387](https://leetcode.com/problems/first-unique-character-in-a-string/)) Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll find the first non-repeating character in a string and return its index. If no unique character exists, you return -1, inspired by LeetCode problem 387.

Challenge Instructions: FirstUniqueCharIndex

Medium

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

Change the following code to make the test cases pass (no type check errors).

Loading...

Detailed Explanation

We need a helper type to check if a character appears in a string, then iterate through each character to find the first one that does not appear in the rest of the string (and has not been seen before).

type Contains<
  S extends string,
  C extends string
> = S extends `${infer _}${C}${infer _Rest}` ? true : false
 
type FirstUniqueCharIndex<
  T extends string,
  Index extends any[] = [],
  Seen extends string = never
> = T extends `${infer First}${infer Rest}`
  ? First extends Seen
    ? FirstUniqueCharIndex<Rest, [...Index, 1], Seen>
    : Contains<Rest, First> extends true
      ? FirstUniqueCharIndex<Rest, [...Index, 1], Seen | First>
      : Index['length']
  : -1

How it works:

This challenge helps you understand string character iteration with duplicate detection and how to apply this concept in real-world scenarios.

This challenge is originally from here.

Share this challenge

Join early, learn faster.

Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.

No spam, unsubscribe at any time. We respect your privacy.

Limited Availability

Only 27 Spots left

Early Access

Get 1 month early access

>75% Off

Pre-Launch discount