
You are given a string s and an integer k (1 ≤ k ≤ |s|). Return the length of the longest substring in which every distinct character occurs at least k times. If no such substring exists, return 0. Describe your algorithm, explain why it is correct, and analyze its time and space complexity. Discuss edge cases such as k = 1, k > |s|, and strings with all unique characters.