[JavaScript] Use Two Pointer Method O(N)
Because the problem is to find the shortest "subarray" to remove, in other words, we only need to consider the existed sorted arrays at the front and the end, a
Because the problem is to find the shortest "subarray" to remove, in other words, we only need to consider the existed sorted arrays at the front and the end, and remove the middle subarray.\n\nNow the question becomes:\n**How to remove the shortest subarray where the array is consisted of two sorted array?**\n\n**Solution:**\nUse two pointer method.\n1. Let i, j are the beginning indices are the two arrays (arr1 with length L1, arr2 with length L2) respectively.\n2. Make a while loop:\n- If arr1[i] <= arr2[j], i++ and continue\n- Otherwise, one of possible number of removed elements is `{right part of arr1} + {left part of arr2} = (L1-i) + j`\n\n```\nvar findLengthOfShortestSubarray = function(arr) {\n    let left = 0, pos = [];\n    \n    for (let i = 1; i < arr.length; i++) {\n        if (arr[i-1] > arr[i]) {\n            if (pos.length == 2) {\n                pos.pop();\n            }\n            pos.push([left, i-1]);\n            left = i;\n        }\n    }\n    if (pos.length == 2)\n        pos.pop();\n    pos.push([left, arr.length-1]);\n    \n    if (pos.length < 2)\n        return 0;\n    \n    let res = arr.length;\n    let i = 0, j = pos[1][0];\n    \n    while (i <= pos[0][1] && j <= pos[1][1]) {\n        console.log(arr[i], arr[j], res)\n        if (arr[i] > arr[j]) {\n            res = Math.min(res, j - pos[1][0] + pos[0][1] - i + 1);\n            j++;\n        } else {\n            i++;\n        }\n    }\n    \n    res = Math.min(res, j - pos[1][0]);\n    \n    return res + (pos[1][0]-1) - (pos[0][1]+1) + 1;\n};
['Two Pointers', 'JavaScript']