Kth Distinct Element in an Array

Given an integer array *arr* and an integer *k*, return *the kth distinct element in the array*. If there are fewer than *k* distinct elements, return -1. An element is distinct if it appears exactly once in the array.

Input Format

arr = [array of integers], k = integer

Output Format

integer (kth distinct element or -1)

Constraints

  • 1 <= arr.length <= 1000; -1000 <= arr[i] <= 1000; 1 <= k <= arr.length

Examples

Example 1:

Input:

arr = [3,1,2,3]
k = 2

Output:

2

Explanation:

Distinct elements in order are [1,2,3], the 2nd is 2.

Example 2:

Input:

arr = [1,2,1,2]
k = 3

Output:

-1

Explanation:

Only two distinct elements (1 and 2), so return -1.

Loading...
Kth Distinct Element in an Array - Hashing