Skip to content

2053. Kth Distinct String in an Array #237

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

To solve this problem, we can follow these steps:

  1. Create a frequency map (associative array) to count the occurrences of each string in the given array.
  2. Iterate through the array to collect the distinct strings (strings that appear only once) in the order they appear.
  3. Check if the number of distinct strings is at least k. If yes, return the k-th distinct string; otherwise, return an empty string.

Let's implement this solution in PHP: 2053. Kth Distinct String in an Array

<?php
function kthDistinct($arr, $k) {
    // Step 1: Create a frequency map
    $frequency = array();
    foreach ($arr as $string) {
        if (isset($frequency[$string])) {
            $frequency[$string]++;
        } 

Replies: 1 comment

Comment options

mah-shamim
Aug 5, 2024
Maintainer Author

You must be logged in to vote
0 replies
Answer selected by basharul-siddike
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested easy Difficulty
1 participant