← Back to challenges

Equalize an Array

JavaScriptHardalgorithmsarrayslogicloops

Instructions

Mubashir needs your help to equalize (make all array elements the same) an array.

Create a function that takes an array of integers arr and a constant c and returns minimum number of operations required to equalize the given array.

Rules

  • You can choose any integer x to equalize the given array.
  • Pick a contiguous subarray of length not greater than the given c

Examples

arr = [1, 2, 2, 1, 2, 1, 2, 2, 2, 1, 1, 1], c = 2
equalize(arr, c) ➞ 4
You have chosen x = 1 (change all values of the array to 1)

[1, 2, 2, 1, 2, 1, 2, 2, 2, 1, 1, 1]
[1, 1, 1, 1, 2, 1, 2, 2, 2, 1, 1, 1] -> Step 1
[1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1] -> Step 2
[1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1] -> Step 3
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] -> Step 4

Notes

N/A

javascript
Loading editor…
to run
Walks through the solution with reasoning and edge cases.