Advertisement
saurav_kalsoor

K Unique String - KOTLIN

Jul 19th, 2022
1,218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Author : Saurav Kalsoor
  2. // K Unique String - KOTLIN
  3.  
  4. import java.util.*;
  5.  
  6. var sc = Scanner(System.`in`)
  7.  
  8. fun main() {
  9.     val s = sc.next()
  10.     val k = sc.nextInt()
  11.     println(kUniqueString(s, k))
  12. }
  13.  
  14. fun kUniqueString(s: String, k: Int): Int {
  15.     val freq = HashMap<Char, Int>()
  16.     for (i in 0 until s.length) {
  17.         freq[s[i]] = freq.getOrDefault(s[i], 0) + 1
  18.     }
  19.     val st: MutableSet<MyPair> =
  20.         TreeSet { a, b ->
  21.             if (a.frequency == b.frequency)
  22.                 a.ch - b.ch
  23.             else
  24.                 a.frequency - b.frequency
  25.         }
  26.  
  27.     for ((key, value) in freq) {
  28.         st.add(MyPair(key, value))
  29.     }
  30.     var distinct = freq.size
  31.     var changes = 0
  32.     for (x in st) {
  33.         if (distinct <= k) break
  34.         changes += x.frequency
  35.         distinct--
  36.     }
  37.     return changes
  38. }
  39.  
  40. internal class MyPair(var ch: Char, var frequency: Int)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement