[Typescript] 126. Hard - Two Sum
Given an array of integers nums
and an integer target
, return true if two numbers such that they add up to target
.
/* _____________ Your Code Here _____________ */
type NumberToArray<N, ACC extends any[] = []> = ACC['length'] extends N ? ACC: NumberToArray<N, [...ACC, 1]>;
type RecursiveAdd<Current extends number, T extends number[], Target extends number> = T extends [infer F, ...infer RT extends number[]]
? [...NumberToArray<F>, ...NumberToArray<Current>]['length'] extends Target
? true
: RecursiveAdd<Current, RT, Target>
: false;
type TwoSum<T extends number[], U extends number> = T extends [infer F extends number, ...infer RT extends number[]]
? RecursiveAdd<F, RT, U> extends false
? TwoSum<RT, U>
: true
: false;
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'
type cases = [
Expect<Equal<TwoSum<[3, 3], 6>, true>>,
Expect<Equal<TwoSum<[3, 2, 4], 6>, true>>,
Expect<Equal<TwoSum<[2, 7, 11, 15], 15>, false>>,
Expect<Equal<TwoSum<[2, 7, 11, 15], 9>, true>>,
Expect<Equal<TwoSum<[1, 2, 3], 0>, false>>,
Expect<Equal<TwoSum<[1, 2, 3], 1>, false>>,
Expect<Equal<TwoSum<[1, 2, 3], 2>, false>>,
Expect<Equal<TwoSum<[1, 2, 3], 3>, true>>,
Expect<Equal<TwoSum<[1, 2, 3], 4>, true>>,
Expect<Equal<TwoSum<[1, 2, 3], 5>, true>>,
Expect<Equal<TwoSum<[1, 2, 3], 6>, false>>,
]