Skip to content

2808. Minimum Seconds to Equalize a Circular Array 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
 public:
  int minimumSeconds(vector<int>& nums) {
    const int n = nums.size();
    int ans = n;
    unordered_map<int, vector<int>> numToIndices;

    for (int i = 0; i < n; ++i)
      numToIndices[nums[i]].push_back(i);

    for (const auto& [_, indices] : numToIndices) {
      int seconds = getSeconds(indices.front() + n, indices.back());
      for (int i = 1; i < indices.size(); ++i)
        seconds = max(seconds, getSeconds(indices[i], indices[i - 1]));
      ans = min(ans, seconds);
    }

    return ans;
  }

 private:
  // Returns the number of seconds required to make nums[i..j] the same.
  int getSeconds(int i, int j) {
    return (i - j) / 2;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
  public int minimumSeconds(List<Integer> nums) {
    int n = nums.size();
    int ans = n;
    Map<Integer, List<Integer>> numToIndices = new HashMap<>();

    for (int i = 0; i < n; ++i) {
      numToIndices.putIfAbsent(nums.get(i), new ArrayList<>());
      numToIndices.get(nums.get(i)).add(i);
    }

    for (List<Integer> indices : numToIndices.values()) {
      int seconds = getSeconds(indices.get(0) + n, indices.get(indices.size() - 1));
      for (int i = 1; i < indices.size(); ++i)
        seconds = Math.max(seconds, getSeconds(indices.get(i), indices.get(i - 1)));
      ans = Math.min(ans, seconds);
    }

    return ans;
  }

  // Returns the number of seconds required to make nums[i..j] the same.
  private int getSeconds(int i, int j) {
    return (i - j) / 2;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
  def minimumSeconds(self, nums: list[int]) -> int:
    n = len(nums)
    ans = n
    numToIndices = collections.defaultdict(list)

    for i, num in enumerate(nums):
      numToIndices[num].append(i)

    def getSeconds(i: int, j: int) -> int:
      """Returns the number of seconds required to make nums[i..j] the same."""
      return (i - j) // 2

    for indices in numToIndices.values():
      seconds = getSeconds(indices[0] + n, indices[-1])
      for i in range(1, len(indices)):
        seconds = max(seconds, getSeconds(indices[i], indices[i - 1]))
      ans = min(ans, seconds)

    return ans