forked from PiotrPrus/kotlin-coding-challenges
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.kt
68 lines (57 loc) · 1.46 KB
/
solution.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.igorwojda.string.maxchar
// Kotlin idiomatic solution
private object Solution1 {
private fun maxOccurrentChar(str: String): Char? {
return str.toCharArray()
.groupBy { it }
.maxBy { it.value.size }
?.key
}
}
// Kotlin idiomatic solution
private object Solution2 {
private fun maxOccurrentChar(str: String): Char? {
return str.toList()
.groupingBy { it }
.eachCount()
.maxBy { it.value }
?.key
}
}
private object Solution3 {
private fun maxOccurrentChar(str: String): Char? {
val map = mutableMapOf<Char, Int>()
str.forEach {
map[it] = (map[it] ?: 0) + 1
}
return map.maxBy { it.value }?.key
}
}
// Recursive optimal approach:
// Time complexity: O(n)
private object Solution4 {
private fun recurringChar(str: String): Char? {
val set = mutableSetOf<Char>()
str.forEach { char ->
if (set.any { it == char }) {
return char
}
set.add(char)
}
return null
}
}
// Recursive naive approach
// Time complexity: O(n^2)
private object Solution5 {
private fun recurringChar(str: String): Char? {
str.forEachIndexed { index, c ->
str.substring(index + 1).forEach {
if (c == it) {
return it
}
}
}
return null
}
}