JavaScript O(n) time and O(n) space


  • 0
    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
    };
    

  • 0
    I

    @loctn
    Hi, thank you for posting your beautiful solution in JS.
    I have two questions please:

    1. why you used const for the objects when they are changing? the same for k in the first loop.
    2. code line:
      let res = nums.length;
      for what input case u assigned nums.length to res?

    thank you very much
    Itsik


  • 0

    @itsik const means constant binding, not necessarily constant and not necessarily immutable - you can alter const 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 with Math.min.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.