DDSA Solutions

2053. Kth Distinct String in an Array

Time: O(n)
Space: O(n)

Problem Overview

Kth Distinct String in an Array (Unknown) asks you to solve a structured algorithmic task. This is a common Array / Hash Table pattern in coding interviews. Count occurrences with a dictionary; iterate in order and return the kth string with count 1.

A full step-by-step explanation is being added. See the study guide for pattern-based practice.

Approach

Count occurrences with a dictionary; iterate in order and return the kth string with count 1.

Related patterns: Array, Hash Table, String

2053.cs
C#
// Approach: Count occurrences with a dictionary; iterate in order and return the kth string with count 1.
// Time: O(n) Space: O(n)

public class Solution
{
    public string KthDistinct(string[] arr, int k)
    {
        Dictionary<string, int> count = new Dictionary<string, int>();

        foreach (var a in arr)
            count[a] = count.GetValueOrDefault(a, 0) + 1;

        foreach (var a in arr)
            if (count[a] == 1 && --k == 0)
                return a;

        return string.Empty;
    }
}
Was this solution helpful?

Related Problems