-3

I want to solve a problem and I need some help because my code doesn't work.

Ok, so I have a sequence S(input data) and I need to find the number of subsequences such that a subsequence number of distinct characters must be equal with K (input data)

Example:

For S = abcaa and K = 3, the answer is 5.
s1 = abc
s2 = abca
s3 = abcaa
s4 = bca
s5 = bcaa

I was thinking a little and I look on internet for some answers but I don't find what I really want. So, I think that i must find frequency of every character in sequence, but I don't know what to do after this...

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Vader
  • 111
  • 1
  • 2
  • 7

2 Answers2

0

Not the most efficient solution, but here you go : Start by iterating through your string and, for every position , you need to do 2 things. First of all, iterate from that position until you found k different characters ( use a frequency array for that) or until you reach the end of the string. In case you found a subsequence , start iterating again from the position where you stopped + 1 and , while the characters you find are already in your frequency vector and you haven't reached the end of the string , count the number of letters you find . You add 1 to that number(because of the first subsequence) and there you go, found all subsequences from that position. Then you increment your first index and continue.

Andrei
  • 16
0

Ruby solution:

S="abcaa"
k=3
distinct_arr = []
result = 0
S_arr = S.split("")


while S_arr.length != 0
    S_arr.each do |char|
        if !distinct_arr.include? (char)
            distinct_arr << char
        end
        if distinct_arr.length == k
            result = result + 1
        end 
        if distinct_arr.length == k + 1
            break
        end
    end
    S_arr.shift
    distinct_arr = []
end

puts result
Mihaiiii
  • 1
  • 1