Skip to content

Commit 39d7836

Browse files
authored
Create 1930-unique-length-3-palindromic-subsequences.kt
1 parent 8d7da5b commit 39d7836

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*
2+
* Time complexity 0(N * 26) ~ O(N)
3+
*
4+
* Space complexity O(26 + 26 + 26*26) or 0(A^2) where A is the alphabet which technically is O(1)
5+
*/
6+
class Solution {
7+
fun countPalindromicSubsequence(s: String): Int {
8+
9+
val left = HashSet<Char>()
10+
val right = IntArray(26)
11+
var res = HashSet<Pair<Char, Char>>() // inner to outer pair, where they form the palindrome outer-inner-outer
12+
13+
for(c in s) right[c - 'a']++
14+
15+
for(i in s.indices) {
16+
if(right[s[i] - 'a'] > 0 ) right[s[i] - 'a']--
17+
for(j in 0 until 26) {
18+
val c = 'a'.plus(j)
19+
if(c in left && right[c - 'a'] > 0) {
20+
res.add(s[i] to c)
21+
}
22+
}
23+
left.add(s[i])
24+
}
25+
26+
return res.size
27+
}
28+
}
29+
30+
/*
31+
* Time complexity 0(26*N+N*M) where M is the length of the substring between first and last character ~O(N*M)
32+
* I see many posts claiming O(N) for the time complexity of this algorithm, but for Java/Kotlin, time complexity should be O(M*N)
33+
* since according to https://stackoverflow.com/questions/4679746/time-complexity-of-javas-substring , substring() time complexity is Linear.
34+
*
35+
* Space complexity O(2*26) ~O(1)
36+
*/
37+
class Solution {
38+
fun countPalindromicSubsequence(s: String): Int {
39+
40+
val first = IntArray(26) {Integer.MAX_VALUE}
41+
val second = IntArray(26)
42+
var res = 0
43+
44+
for(i in s.indices) {
45+
first[s[i] - 'a'] = minOf(first[s[i] - 'a'], i)
46+
second[s[i] - 'a'] = i
47+
}
48+
49+
for(i in 0 until 26) {
50+
if(first[i] < second[i])
51+
res += s.substring(first[i]+1, second[i]).toCharArray().distinct().count()
52+
}
53+
54+
return res
55+
}
56+
}

0 commit comments

Comments
 (0)