2053. Kth Distinct String in an Array #237
-
A distinct string is a string that is present only once in an array. Given an array of strings Note that the strings are considered in the order in which they appear in the array. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
To solve this problem, we can follow these steps:
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]++;
} else {
$frequency[$string] = 1;
}
}
// Step 2: Collect distinct strings in the order they appear
$distinctStrings = array();
foreach ($arr as $string) {
if ($frequency[$string] == 1) {
$distinctStrings[] = $string;
}
}
// Step 3: Return the k-th distinct string if it exists, otherwise return an empty string
if (count($distinctStrings) >= $k) {
return $distinctStrings[$k - 1];
} else {
return "";
}
}
// Test cases
$arr1 = array("d", "b", "c", "b", "c", "a");
$k1 = 2;
echo kthDistinct($arr1, $k1) . "\n"; // Output: "a"
$arr2 = array("aaa", "aa", "a");
$k2 = 1;
echo kthDistinct($arr2, $k2) . "\n"; // Output: "aaa"
$arr3 = array("a", "b", "a");
$k3 = 3;
echo kthDistinct($arr3, $k3) . "\n"; // Output: ""
?> Explanation:
The provided code handles the problem efficiently within the given constraints. |
Beta Was this translation helpful? Give feedback.
To solve this problem, we can follow these steps:
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