Runtime beats 87.50%, memory beats 100.00% [EXPLAINED]
Intuition\nThe goal is to find a contiguous subarray that, when removed from the array, makes the sum of the remaining elements divisible by a given number p. B
# Intuition\nThe goal is to find a contiguous subarray that, when removed from the array, makes the sum of the remaining elements divisible by a given number p. By focusing on the total sum and its remainder when divided by p, we can identify the subarray whose removal would eliminate the "excess" or remainder.\n\n# Approach\nCalculate the total sum of the array, find the excess remainder when this sum is divided by p, and use a cumulative sum with a hash map to track previous remainders, allowing us to efficiently identify the smallest subarray to remove.\n\n# Complexity\n- Time complexity:\nO(n) since we traverse the array a couple of times.\n\n- Space complexity:\nO(p) in the worst case due to the storage of remainders in a hash map.\n\n# Code\n```typescript []\n/**\n * Finds the length of the smallest subarray that can be removed so that the sum of the remaining elements is divisible by p.\n * \n * @param {number[]} nums - An array of positive integers.\n * @param {number} p - A positive integer for divisibility check.\n * @return {number} - The length of the smallest subarray to remove, or -1 if impossible.\n */\nfunction minSubarray(nums: number[], p: number): number {\n    // Calculate the total excess (the remainder when the total sum is divided by p)\n    const excess = nums.reduce((acc, val) => (acc + val) % p, 0);\n    \n    // If there is no excess, the sum is already divisible by p\n    if (excess === 0) return 0;\n    \n    let sumSoFar = 0; // Current cumulative sum modulo p\n    const lastIndex: Record<number, number> = { [sumSoFar]: -1 }; // Store last seen indices of remainders\n    const n = nums.length; // Length of the input array\n    let min = n; // Initialize min length as n (the maximum possible)\n\n    for (let i = 0; i < n; i++) {\n        sumSoFar = (sumSoFar + nums[i]) % p; // Update cumulative sum modulo p\n        lastIndex[sumSoFar] = i; // Update the last seen index for the current remainder\n        \n        // Calculate the required prefix sum remainder to achieve divisibility\n        const trailPrefixSum = (sumSoFar - excess + p) % p;\n        \n        // Check if the required prefix sum has been seen\n        let trail = trailPrefixSum in lastIndex ? lastIndex[trailPrefixSum] : -n;\n        \n        // Update the minimum length if a valid subarray is found\n        min = Math.min(min, i - trail);\n    }\n\n    // Return the minimum length if valid, otherwise return -1\n    return min < n ? min : -1;\n}\n\n\n\n```
['TypeScript']