Kth Distinct String in an Array

🏠 ⬅️ ➡️

A distinct string is a string that is present only once in an array.

Given an array of strings arr, and an integer k, return the kth distinct string present in arr. If there are fewer than k distinct strings, return an empty string " ".

Note that the strings are considered in the order in which they appear in the array.

Example 1:

Input: arr = [ "d ", "b ", "c ", "b ", "c ", "a "], k = 2 Output: "a " Explanation: The only distinct strings in arr are "d " and "a ". "d " appears 1st, so it is the 1st distinct string. "a " appears 2nd, so it is the 2nd distinct string. Since k == 2, "a " is returned.

Example 2:

Input: arr = [ "aaa ", "aa ", "a "], k = 1 Output: "aaa " Explanation: All strings in arr are distinct, so the 1st string "aaa " is returned.

Example 3:

Input: arr = [ "a ", "b ", "a "], k = 3 Output: " " Explanation: The only distinct string is "b ". Since there are fewer than 3 distinct strings, we return an empty string " ".

Constraints:

  • 1 <= k <= arr.length <= 1000
  • 1 <= arr[i].length <= 5
  • arr[i] consists of lowercase English letters.

Note: This problem is from LeetCode.
Compiled
Executed
Correct
program main
    implicit none

    character(len=:), allocatable :: arr(:)
    integer :: k
    character(len=:), allocatable :: result

    ! Examples
    allocate(arr(6))
    arr = ["d ", "b ", "c ", "b ", "c ", "a "]
    k = 2
    result = getKthDistinctString(arr, k)
    print '(A)', result

    allocate(arr(3))
    arr = ["aaa ", "aa ", "a "]
    k = 1
    result = getKthDistinctString(arr, k)
    print '(A)', result

    allocate(arr(3))
    arr = ["a ", "b ", "a "]
    k = 3
    result = getKthDistinctString(arr, k)
    print '(A)', result

contains

    function getKthDistinctString(arr, k) result(res)
        implicit none
        character(len=*), intent(in) :: arr(:)
        integer, intent(in) :: k
        character(len=:), allocatable :: res
        logical, dimension(:), allocatable :: seen
        integer :: i, j, n

        n = size(arr)
        allocate(seen(n))
        seen = .false.
        do i = 1, n
            if (.not. seen(i)) then
                do j = i + 1, n
                    if (arr(j) == arr(i)) then
                        seen(j) = .true.
                    end if
                end do
            end if
        end do

        if (count(seen) < k) then
            res = ""
        else
            res = arr(k)
        end if
    end function getKthDistinctString
end program main
Compiled
Executed
Correct
program distinct_string
      implicit none

      integer, parameter :: k = 2
      character(len=5), dimension(6) :: arr = ["d ", "b ", "c ", "b ", "c ", "a "]
      character(len=5) :: result
      integer :: i, count

      ! Initialize result to an empty string
      result = " "

      ! Count the number of distinct strings in arr
      count = 0
      do i = 1, size(arr)
          if (count(arr == arr(i)) == 1) then
              count = count + 1
          end if
      end do

      ! If there are fewer than k distinct strings, return an empty string
      if (count < k) then
          result = " "
      else
          ! Find the kth distinct string in arr
          count = 0
          do i = 1, size(arr)
              if (count(arr == arr(i)) == 1) then
                  count = count + 1
                  if (count == k) then
                      result = arr(i)
                      exit
                  end if
              end if
          end do
      end if

      ! Print the result
      write (*,*) result

      end program distinct_string
🌐 Data from online sources
def is_good_string(s: str) -> bool:
    freq_map = {}
    for c in s:
        if c in freq_map:
            freq_map[c] += 1
        else:
            freq_map[c] = 1

    count = next(iter(freq_map.values()))
    for value in freq_map.values():
        if value != count:
            return False
    return True

The algorithm for each implementation is as follows:

  1. Create a dictionary/hash map to store the frequencies of each character in the string.
  2. Iterate through the input string and update the dictionary with the character frequencies.
  3. Get the count of the first character in the dictionary.
  4. Iterate through the dictionary, compare the count of each character to the initial count obtained in step 3. If the counts are not equal, return false. In the end, if all counts are equal, return true.

This algorithm works in O(n) time complexity, where n is the length of the input string, since it traverses the input string and dictionary in linear time.

🌐 Data from online sources
#include <string>
#include <unordered_map>

bool isGoodString(const std::string& s) {
    std::unordered_map<char, int> freq_map;
    for (char c : s) {
        freq_map[c]++;
    }

    int count = freq_map.begin()->second;
    for (const auto& entry : freq_map) {
        if (entry.second != count) {
            return false;
        }
    }
    return true;
}

The algorithm for each implementation is as follows:

  1. Create a dictionary/hash map to store the frequencies of each character in the string.
  2. Iterate through the input string and update the dictionary with the character frequencies.
  3. Get the count of the first character in the dictionary.
  4. Iterate through the dictionary, compare the count of each character to the initial count obtained in step 3. If the counts are not equal, return false. In the end, if all counts are equal, return true.

This algorithm works in O(n) time complexity, where n is the length of the input string, since it traverses the input string and dictionary in linear time.