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.
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).
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']
: -1How it works:
Contains<S, C> checks whether character C appears anywhere in string S using template literal inferenceT one character at a time, maintaining an Index counter and a Seen union of characters already known to be duplicatedFirst is already in Seen, it has been encountered before and is a duplicate, so we skip itFirst is not in Seen but appears in Rest, it is a duplicate -- we add it to Seen and continueFirst is not in Seen and does not appear in Rest, it is the first unique character, so we return Index['length']-1This 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.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount