fork download
  1. x = [3, 2, 3, 3, 2, 8]
  2. k = 8
  3.  
  4. def count_min_length_subarrays(x, k):
  5. # Maps prefix_sum -> list of indices where it occurred
  6. # (Since we want all valid windows, we track all occurrences)
  7. prefix_map = {0: [-1]}
  8. current_sum = 0
  9.  
  10. min_len = float('inf')
  11. count = 0
  12.  
  13. for index, value in enumerate(x):
  14. current_sum += value
  15. target = current_sum - k
  16.  
  17. # If the complement prefix sum exists, we found valid subarrays
  18. if target in prefix_map:
  19. for start_index in prefix_map[target]:
  20. length = index - start_index
  21.  
  22. if length < min_len:
  23. min_len = length
  24. count = 1 # Reset count for the new strictly smaller minimum length
  25. elif length == min_len:
  26. count += 1 # Increment count for matching the current minimum length
  27.  
  28. # Record the current prefix sum index
  29. if current_sum not in prefix_map:
  30. prefix_map[current_sum] = []
  31. prefix_map[current_sum].append(index)
  32.  
  33. return min_len, count
  34.  
  35. min_length, frequency = count_min_length_subarrays(x, k)
  36. print(f"Minimum Length: {min_length}")
  37. print(f"Count of Minimum Length Subarrays: {frequency}")
  38.  
Success #stdin #stdout 0.07s 14040KB
stdin
Standard input is empty
stdout
Minimum Length: 1
Count of Minimum Length Subarrays: 1