const findShortestSubArray = (nums) => {
const counts = {}
const firstIndexes = {}
const lastIndexes = {}
let max = 0
for (let i = 0; i < nums.length; i++) {
const k = nums[i]
counts[k] = (counts[k]  0) + 1
max = Math.max(max, counts[k])
if (firstIndexes[k] === undefined) {
firstIndexes[k] = i
}
lastIndexes[k] = i
}
let res = nums.length
for (const k in counts) {
if (counts[k] === max) {
res = Math.min(res, lastIndexes[k]  firstIndexes[k] + 1)
}
}
return res
};
JavaScript O(n) time and O(n) space


@loctn
Hi, thank you for posting your beautiful solution in JS.
I have two questions please: why you used const for the objects when they are changing? the same for k in the first loop.
 code line:
let res = nums.length;
for what input case u assigned nums.length to res?
thank you very much
Itsik

@itsik
const
means constant binding, not necessarily constant and not necessarily immutable  you can alterconst
variables but not reassign them.res
can start at anything>= nums.length
since any subarray is going to be smaller than that and operate correctly withMath.min
.