educative.io

Can I use If instead of While as the results seems to be the same?

def longest_substring_with_k_distinct(str, k):
  #pdb.set_trace()
  max_len = 0
  win_start = 0
  count_chars = {}
  for win_end in range(len(str)):
    right_char = str[win_end]
    if right_char not in count_chars.keys():
      count_chars[right_char] = 0
  
    count_chars[right_char] += 1

    if(len(count_chars) > k):
      left_char = str[win_start]
      count_chars[left_char] -= 1

      if count_chars[left_char] == 0:
        del count_chars[left_char]
      win_start += 1
          
    max_len = max(max_len, win_end-win_start +1)

  if (max_len > 0 ):
    return max_len
  return -1
2 Likes

I was wondering the same initially.

So what if you had aaadj and k=2. When you encounter j you want to remove all the as and not just the first one. I think the default test cases they provide don’t really cover for this.