koenjazh-CNfresde
짬뽕얼큰하게의 맨땅에 헤딩 :: Kth Distinct String in an Array

Leetcode Problem:

Summary

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

Approach

  • The approach used is to count the frequency of each string in the array using an unordered map
  • Then, iterate through the array again to find the kth distinct string
  • If k is greater than the number of distinct strings, return an empty string.

Complexity

  • O(n + m) where n is the size of the array and m is the number of distinct strings

Explain

  • First, we create an unordered map to store the frequency of each string in the array
  • We then initialize a counter K to keep track of the number of distinct strings
  • We iterate through the array again, and for each string, we check if its frequency is 1
  • If it is, we increment the counter K
  • If K equals k, we return the current string
  • If we finish iterating through the array and K is still less than k, we return an empty string.

Solution Code:


class Solution {
public:
    string kthDistinct(vector& arr, int k) {
        unordered_map m;
        for(int i = 0 ; i < arr.size(); i++){
            m[arr[i]]++;
        }
        int K = 0;
        for(int i = 0 ; i < arr.size(); i++){
            if(m[arr[i]] == 1){
                K++;
                if(k == K) return arr[i];
            }
        }
        return "";
    }
};

'알고리즘' 카테고리의 다른 글

Integer to English Words  (0) 2025.02.05
Minimum Number of Pushes to Type Word II  (0) 2025.02.05
Maximum Ascending Subarray Sum  (0) 2025.02.04
Range Sum of Sorted Subarray Sums  (0) 2025.02.04
Number of Senior Citizens  (0) 2025.02.04
블로그 이미지

짬뽕얼큰하게

,